添加pixijs等相关依赖

同步图形框架代码(后面可以使用npm run sync来同步graphic-pixi图形框架库代码到项目jl-graphic目录中)
This commit is contained in:
walker 2023-05-30 17:04:50 +08:00
parent 2c6d563d2e
commit 0fe6b2c393
39 changed files with 9184 additions and 9 deletions

View File

@ -11,26 +11,34 @@
"test": "echo \"No test specified\" && exit 0",
"dev": "quasar dev",
"build": "quasar build",
"protoc": "node scripts/proto.cjs"
"protoc": "node scripts/proto.cjs",
"sync": "node scripts/sync.cjs"
},
"dependencies": {
"axios": "^1.2.1",
"pinia": "^2.0.11",
"@pixi/filter-outline": "^5.2.0",
"@quasar/extras": "^1.0.0",
"@stomp/stompjs": "^7.0.0",
"axios": "^1.2.1",
"google-protobuf": "^3.21.2",
"js-base64": "^3.7.5",
"pinia": "^2.0.11",
"pixi-viewport": "^5.0.1",
"pixi.js": "^7.2.4",
"quasar": "^2.6.0",
"vue": "^3.0.0",
"vue-router": "^4.0.0"
},
"devDependencies": {
"@quasar/app-vite": "^1.0.0",
"@types/google-protobuf": "^3.15.6",
"@types/node": "^12.20.21",
"@typescript-eslint/eslint-plugin": "^5.10.0",
"@typescript-eslint/parser": "^5.10.0",
"eslint": "^8.10.0",
"eslint-plugin-vue": "^9.0.0",
"eslint-config-prettier": "^8.1.0",
"prettier": "^2.5.1",
"@types/node": "^12.20.21",
"@quasar/app-vite": "^1.0.0",
"autoprefixer": "^10.4.2",
"eslint": "^8.10.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-vue": "^9.0.0",
"prettier": "^2.5.1",
"typescript": "^4.5.4"
},
"engines": {

70
scripts/sync.cjs Normal file
View File

@ -0,0 +1,70 @@
/**
* 同步图形框架文件到 src/jl-graphic/
*/
const {
readdirSync,
existsSync,
copyFileSync,
mkdirSync,
rmSync,
} = require('fs');
const { resolve } = require('path');
const jlGraphicSrcPath = resolve(__dirname, '../graphic-pixi/src/jlgraphic');
const jlGraphicLibPath = resolve(__dirname, '../src/jl-graphic');
/**
* 检查并初始化当前项目引入的jl-graphic库
*/
function checkAndInitJlGraphicLib() {
const exist = existsSync(jlGraphicLibPath);
if (exist) {
console.log('jl-graphic文件夹已存在,清空');
readdirSync(jlGraphicLibPath, {
withFileTypes: true,
}).forEach((file) => {
if (file.isDirectory()) {
rmSync(resolve(jlGraphicLibPath, file.name), { recursive: true });
} else {
rmSync(resolve(jlGraphicLibPath, file.name));
}
});
} else {
console.log('jl-graphic文件夹不存在,创建');
// 文件夹不存在,创建
mkdirSync(jlGraphicLibPath);
}
}
function copyJlGraphicFiles() {
readdirSync(jlGraphicSrcPath, {
withFileTypes: true,
}).forEach((file) => {
recursiveCopyFiles(file);
});
}
function recursiveCopyFiles(file, path = []) {
if (file.isFile()) {
const fileSrcPath = resolve(jlGraphicSrcPath, ...path, file.name);
const fileDestPath = resolve(jlGraphicLibPath, ...path, file.name);
console.log(`copy file ${fileSrcPath} -> ${fileDestPath}`);
copyFileSync(fileSrcPath, fileDestPath);
} else if (file.isDirectory()) {
const srcDir = resolve(jlGraphicSrcPath, ...path, file.name);
const dirPath = resolve(jlGraphicLibPath, ...path, file.name);
mkdirSync(dirPath);
readdirSync(srcDir, {
withFileTypes: true,
}).forEach((subFile) => {
recursiveCopyFiles(subFile, [...path, file.name]);
});
}
}
function main() {
checkAndInitJlGraphicLib();
copyJlGraphicFiles();
}
main();

View File

@ -0,0 +1,680 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-function */
import {
BitmapFont,
BitmapText,
Container,
DisplayObject,
FederatedMouseEvent,
IPointData,
Point,
} from 'pixi.js';
import { GraphicIdGenerator } from '../core/IdGenerator';
import { GraphicData, GraphicTemplate, JlGraphic } from '../core/JlGraphic';
import { JlOperation } from '../operation/JlOperation';
import {
AppDragEvent,
AppInteractionPlugin,
CombinationKey,
GraphicTransformEvent,
InteractionPlugin,
KeyListener,
ShiftData,
} from '../plugins';
import { CommonMouseTool } from '../plugins/CommonMousePlugin';
import { MenuItemOptions } from '../ui/Menu';
import { DOWN, LEFT, RIGHT, UP, recursiveChildren } from '../utils';
import {
GraphicApp,
GraphicAppOptions,
ICanvasProperties,
JlCanvas,
} from './JlGraphicApp';
/**
*
*/
export abstract class GraphicDrawAssistant<
GT extends GraphicTemplate,
GD extends GraphicData
> extends AppInteractionPlugin {
readonly __GraphicDrawAssistant = true;
app: JlDrawApp;
type: string; // 图形对象类型
description: string; // 描述
icon: string; // 界面显示的图标
container: Container = new Container();
graphicTemplate: GT;
createGraphicData: () => GD;
escListener: KeyListener = new KeyListener({
value: 'Escape',
onRelease: () => {
this.onEsc();
},
});
onEsc() {
this.createAndStore(true);
}
constructor(
graphicApp: JlDrawApp,
graphicTemplate: GT,
createGraphicData: () => GD,
icon: string,
description: string
) {
super(graphicTemplate.type, graphicApp);
this.app = graphicApp;
this.type = graphicTemplate.type;
this.graphicTemplate = graphicTemplate;
this.createGraphicData = createGraphicData;
this.icon = icon;
this.description = description;
this.app.registerGraphicTemplates(this.graphicTemplate);
}
public get canvas(): JlCanvas {
return this.app.canvas;
}
bind(): void {
this.app._drawing = true;
const canvas = this.canvas;
canvas.addChild(this.container);
canvas.on('mousedown', this.onLeftDown, this);
canvas.on('mousemove', this.onMouseMove, this);
canvas.on('mouseup', this.onLeftUp, this);
canvas.on('rightdown', this.onRightDown, this);
canvas.on('rightup', this.onRightUp, this);
canvas.on('_rightclick', this.onRightClick, this);
this.app.viewport.wheel({
percent: 0.01,
});
this.app.addKeyboardListener(this.escListener);
this.app.viewport.drag({
mouseButtons: 'right',
});
}
unbind(): void {
this.clearCache();
const canvas = this.canvas;
canvas.removeChild(this.container);
canvas.off('mousedown', this.onLeftDown, this);
canvas.off('mousemove', this.onMouseMove, this);
canvas.off('mouseup', this.onLeftUp, this);
canvas.off('rightdown', this.onRightDown, this);
canvas.off('rightup', this.onRightUp, this);
this.app.viewport.plugins.remove('wheel');
this.app.removeKeyboardListener(this.escListener);
this.app.viewport.plugins.remove('drag');
this.app._drawing = false;
}
onLeftDown(e: FederatedMouseEvent) {}
onMouseMove(e: FederatedMouseEvent) {
this.redraw(this.toCanvasCoordinates(e.global));
}
onLeftUp(e: FederatedMouseEvent) {}
onRightDown(e: FederatedMouseEvent) {}
onRightUp(e: FederatedMouseEvent) {}
onRightClick(e: FederatedMouseEvent) {
this.finish();
}
/**
* id
*/
nextId(): string {
return GraphicIdGenerator.next();
}
clearCache(): void {}
/**
*
* @param cp
*/
abstract redraw(cp: Point): void;
abstract prepareData(data: GD): boolean;
toCanvasCoordinates(p: Point): Point {
return this.app.toCanvasCoordinates(p);
}
/**
*
*/
storeGraphic(...graphics: JlGraphic[]): void {
this.app.addGraphics(...graphics);
// 创建图形对象操作记录
this.app.opRecord.record(new GraphicCreateOperation(this.app, graphics));
}
/**
* App
*/
createAndStore(finish: boolean): JlGraphic | null {
const data = this.createGraphicData();
data.id = this.nextId();
data.graphicType = this.graphicTemplate.type;
if (!this.prepareData(data)) {
if (finish) {
this.finish();
}
return null;
}
const template = this.graphicTemplate;
const g = template.new();
g.loadData(data);
this.storeGraphic(g);
if (finish) {
this.finish(g);
}
return g;
}
/**
*
*/
finish(...graphics: JlGraphic[]): void {
this.clearCache();
this.app.interactionPlugin(CommonMouseTool.Name).resume();
this.app.updateSelected(...graphics);
}
}
export type DrawAssistant = GraphicDrawAssistant<GraphicTemplate, GraphicData>;
export interface IDrawAppOptions {
/**
*
*/
drawAssistants: DrawAssistant[];
}
export type DrawAppOptions = GraphicAppOptions & IDrawAppOptions;
/**
*
*/
export class JlDrawApp extends GraphicApp {
font: BitmapFont = BitmapFont.from(
'coordinates',
{
fontFamily: 'Roboto',
fontSize: 16,
fill: '#ff2700',
},
{ chars: ['画布坐标:() 屏幕坐标:() 缩放:.,', ['0', '9']] }
);
coordinates: BitmapText = new BitmapText('画布坐标: (0, 0) 屏幕坐标:(0, 0)', {
fontName: 'coordinates',
});
scaleText: BitmapText = new BitmapText('缩放: 1', {
fontName: 'coordinates',
});
drawAssistants: DrawAssistant[] = [];
_drawing = false;
constructor(dom: HTMLElement) {
super(dom);
this.appendDrawStatesDisplay();
// 拖拽操作记录
this.appOperationRecord();
// 绑定通用键盘操作
this.bindKeyboardOperation();
}
setOptions(options: DrawAppOptions): void {
super.setOptions(options);
// this.registerInteractionPlugin(...options.drawAssistants);
}
registerInteractionPlugin(...plugins: InteractionPlugin[]): void {
plugins.forEach((plugin) => {
if (plugin instanceof GraphicDrawAssistant) {
this.drawAssistants.push(plugin);
}
super.registerInteractionPlugin(plugin);
});
}
getDrawAssistant<DA extends DrawAssistant>(graphicType: string): DA {
const sda = this.drawAssistants
.filter((da) => da.type === graphicType)
.pop();
if (!sda) {
throw new Error(`未找到图形绘制助手: ${graphicType}`);
}
return sda as DA;
}
private appOperationRecord() {
let dragStartDatas: GraphicData[] = [];
this.on('drag_op_start', (e: AppDragEvent) => {
// 图形拖拽,记录初始数据
if (!e.target.isCanvas()) {
dragStartDatas = this.selectedGraphics.map((g) => g.saveData());
}
});
// 图形拖拽操作监听
this.on('drag_op_end', () => {
// 图形拖拽,记录操作
if (dragStartDatas.length > 0) {
const newData = this.selectedGraphics.map((g) => g.saveData());
this.opRecord.record(
new GraphicDataUpdateOperation(
this,
this.selectedGraphics,
dragStartDatas,
newData
)
);
dragStartDatas = [];
}
});
// 菜单操作
let preMenuHandleDatas: GraphicData[] = [];
this.on('pre-menu-handle', (menu: MenuItemOptions) => {
if (menu.name === '撤销' || menu.name === '重做') {
return;
}
preMenuHandleDatas = this.selectedGraphics.map((g) => g.saveData());
});
this.on('post-menu-handle', () => {
if (preMenuHandleDatas.length > 0) {
const newData = this.selectedGraphics.map((g) => g.saveData());
this.opRecord.record(
new GraphicDataUpdateOperation(
this,
this.selectedGraphics,
preMenuHandleDatas,
newData
)
);
preMenuHandleDatas = [];
}
});
}
/**
*
*/
private appendDrawStatesDisplay(): void {
this.app.stage.addChild(this.coordinates);
this.app.stage.addChild(this.scaleText);
const bound = this.coordinates.getLocalBounds();
this.scaleText.position.set(bound.width + 10, 0);
this.canvas.on('mousemove', (e) => {
if (e.target) {
const { x, y } = this.toCanvasCoordinates(e.global);
const cpTxt = `(${x}, ${y})`;
const tp = e.global;
const tpTxt = `(${tp.x}, ${tp.y})`;
this.coordinates.text = `画布坐标:${cpTxt} 屏幕坐标:${tpTxt}`;
const bound = this.coordinates.getLocalBounds();
this.scaleText.position.set(bound.width + 10, 0);
}
});
this.viewport.on('zoomed-end', () => {
this.scaleText.text = `缩放: ${this.viewport.scaled}`;
});
}
bindKeyboardOperation(): void {
this.addKeyboardListener(
// Ctrl + A
new KeyListener({
value: 'KeyA',
combinations: [CombinationKey.Ctrl],
onPress: (e: KeyboardEvent, app: GraphicApp) => {
if (e.ctrlKey) {
(app as JlDrawApp).selectAllGraphics();
}
},
})
);
// 复制功能
this.addKeyboardListener(
new KeyListener({
value: 'KeyD',
combinations: [CombinationKey.Shift],
onPress: (e: KeyboardEvent, app: GraphicApp) => {
app.graphicCopyPlugin.init();
},
})
);
this.addKeyboardListener(
new KeyListener({
// Ctrl + Z
value: 'KeyZ',
global: true,
combinations: [CombinationKey.Ctrl],
onPress: (e: KeyboardEvent, app: GraphicApp) => {
app.opRecord.undo();
},
})
);
this.addKeyboardListener(
new KeyListener({
// Ctrl + Shift + Z
value: 'KeyZ',
global: true,
combinations: [CombinationKey.Ctrl, CombinationKey.Shift],
onPress: (e: KeyboardEvent, app: GraphicApp) => {
app.opRecord.redo();
},
})
);
this.addKeyboardListener(
new KeyListener({
value: 'Delete',
onPress: (e: KeyboardEvent, app: GraphicApp) => {
(app as JlDrawApp).deleteSelectedGraphics();
},
})
);
this.addKeyboardListener(
new KeyListener({
value: 'ArrowUp',
pressTriggerAsOriginalEvent: true,
onPress: (e: KeyboardEvent, app: GraphicApp) => {
updateGraphicPositionOnKeyboardEvent(app, UP);
},
onRelease: (e: KeyboardEvent, app: GraphicApp) => {
recordGraphicMoveOperation(app);
},
})
);
this.addKeyboardListener(
new KeyListener({
value: 'ArrowDown',
pressTriggerAsOriginalEvent: true,
onPress: (e: KeyboardEvent, app: GraphicApp) => {
updateGraphicPositionOnKeyboardEvent(app, DOWN);
},
onRelease: (e: KeyboardEvent, app: GraphicApp) => {
recordGraphicMoveOperation(app);
},
})
);
this.addKeyboardListener(
new KeyListener({
value: 'ArrowLeft',
pressTriggerAsOriginalEvent: true,
onPress: (e: KeyboardEvent, app: GraphicApp) => {
updateGraphicPositionOnKeyboardEvent(app, LEFT);
},
onRelease: (e: KeyboardEvent, app: GraphicApp) => {
recordGraphicMoveOperation(app);
},
})
);
this.addKeyboardListener(
new KeyListener({
value: 'ArrowRight',
pressTriggerAsOriginalEvent: true,
onPress: (e: KeyboardEvent, app: GraphicApp) => {
updateGraphicPositionOnKeyboardEvent(app, RIGHT);
},
onRelease: (e: KeyboardEvent, app: GraphicApp) => {
recordGraphicMoveOperation(app);
},
})
);
}
/**
*
*/
selectAllGraphics() {
this.updateSelected(...this.queryStore.getAllGraphics());
}
/**
* ,
* @param graphic
*/
beforeGraphicStore(graphic: JlGraphic): void {
graphic.eventMode = 'static';
graphic.selectable = true;
graphic.draggable = true;
}
/**
*
*/
deleteSelectedGraphics() {
const deletes = this.selectedGraphics.slice(
0,
this.selectedGraphics.length
);
this.deleteGraphics(...this.selectedGraphics);
// 删除图形对象操作记录
this.opRecord.record(new GraphicDeleteOperation(this, deletes));
}
updateCanvasAndRecord(data: ICanvasProperties) {
const old = this.canvas.properties.clone();
this.canvas.update(data);
const newVal = this.canvas.properties.clone();
this.opRecord.record(
new UpdateCanvasOperation(this, this.canvas, old, newVal)
);
}
updateGraphicAndRecord(g: JlGraphic, data: GraphicData) {
const old = g.saveData();
g.updateData(data);
const newVal = g.saveData();
this.opRecord.record(
new GraphicDataUpdateOperation(this, [g], [old], [newVal])
);
}
}
let dragStartDatas: GraphicData[] = [];
function handleArrowKeyMoveGraphics(
app: GraphicApp,
handler: (obj: DisplayObject) => void
) {
if (
app.selectedGraphics.length === 1 &&
app.selectedGraphics[0].hasSelectedChilds()
) {
recursiveChildren(app.selectedGraphics[0], (child) => {
if (child.selected && child.draggable) {
handler(child);
}
});
} else {
app.selectedGraphics.forEach((g) => {
handler(g);
});
}
}
function updateGraphicPositionOnKeyboardEvent(app: GraphicApp, dp: IPointData) {
let dragStart = false;
if (dragStartDatas.length === 0) {
dragStartDatas = app.selectedGraphics.map((g) => g.saveData());
dragStart = true;
}
handleArrowKeyMoveGraphics(app, (g) => {
if (dragStart) {
g.shiftStartPoint = g.position.clone();
g.emit(
'transformstart',
GraphicTransformEvent.shift(g, ShiftData.new(g.shiftStartPoint))
);
} else {
g.shiftLastPoint = g.position.clone();
}
g.position.x += dp.x;
g.position.y += dp.y;
if (!dragStart) {
if (g.shiftStartPoint && g.shiftLastPoint) {
g.emit(
'transforming',
GraphicTransformEvent.shift(
g,
ShiftData.new(
g.shiftStartPoint,
g.position.clone(),
g.shiftLastPoint
)
)
);
}
}
});
}
function recordGraphicMoveOperation(app: GraphicApp) {
if (
dragStartDatas.length > 0 &&
dragStartDatas.length === app.selectedGraphics.length
) {
const newData = app.selectedGraphics.map((g) => g.saveData());
app.opRecord.record(
new GraphicDataUpdateOperation(
app,
app.selectedGraphics,
dragStartDatas,
newData
)
);
handleArrowKeyMoveGraphics(app, (g) => {
if (g.shiftStartPoint) {
g.emit(
'transformend',
GraphicTransformEvent.shift(
g,
ShiftData.new(g.shiftStartPoint, g.position.clone())
)
);
}
});
}
dragStartDatas = [];
}
/**
*
*/
export class UpdateCanvasOperation extends JlOperation {
obj: JlCanvas;
old: ICanvasProperties;
data: ICanvasProperties;
description = '';
constructor(
app: GraphicApp,
obj: JlCanvas,
old: ICanvasProperties,
data: ICanvasProperties
) {
super(app, 'update-canvas');
this.app = app;
this.obj = obj;
this.old = old;
this.data = data;
}
undo(): JlGraphic[] {
this.obj.update(this.old);
return [];
}
redo(): JlGraphic[] {
this.obj.update(this.data);
return [];
}
}
/**
*
*/
export class GraphicCreateOperation extends JlOperation {
obj: JlGraphic[];
description = '';
constructor(app: GraphicApp, obj: JlGraphic[]) {
super(app, 'graphic-create');
this.app = app;
this.obj = obj;
}
undo(): JlGraphic[] | void {
this.app.deleteGraphics(...this.obj);
}
redo(): JlGraphic[] {
this.app.addGraphics(...this.obj);
return this.obj;
}
}
/**
*
*/
export class GraphicDeleteOperation extends JlOperation {
obj: JlGraphic[];
constructor(app: GraphicApp, obj: JlGraphic[]) {
super(app, 'graphic-delete');
this.app = app;
this.obj = obj;
}
undo(): JlGraphic[] {
this.app.addGraphics(...this.obj);
return this.obj;
}
redo(): void {
this.app.deleteGraphics(...this.obj);
}
}
export class GraphicDataUpdateOperation extends JlOperation {
obj: JlGraphic[];
oldData: GraphicData[];
newData: GraphicData[];
constructor(
app: GraphicApp,
obj: JlGraphic[],
oldData: GraphicData[],
newData: GraphicData[]
) {
super(app, 'graphic-drag');
this.obj = [...obj];
this.oldData = oldData;
this.newData = newData;
}
undo(): void | JlGraphic[] {
for (let i = 0; i < this.obj.length; i++) {
const g = this.obj[i];
// g.exitChildEdit();
g.updateData(this.oldData[i]);
}
return this.obj;
}
redo(): void | JlGraphic[] {
for (let i = 0; i < this.obj.length; i++) {
const g = this.obj[i];
// g.exitChildEdit();
g.updateData(this.newData[i]);
}
return this.obj;
}
}

View File

@ -0,0 +1,904 @@
import EventEmitter from 'eventemitter3';
import { Viewport } from 'pixi-viewport';
import {
Application,
Color,
Container,
DisplayObject,
Graphics,
Point,
Rectangle,
} from 'pixi.js';
import { GraphicQueryStore, GraphicStore } from '../core/GraphicStore';
import { GraphicIdGenerator } from '../core/IdGenerator';
import {
GraphicData,
GraphicState,
GraphicTemplate,
GraphicTransform,
JlGraphic,
} from '../core/JlGraphic';
import { AbsorbablePosition } from '../graphic';
import {
AppWsMsgBroker,
StompCli,
type AppStateSubscription,
type StompCliOption,
} from '../message/WsMsgBroker';
import { OperationRecord } from '../operation/JlOperation';
import {
AnimationManager,
CommonMouseTool,
GraphicTransformPlugin,
IMouseToolOptions,
} from '../plugins';
import { GraphicCopyPlugin } from '../plugins/CopyPlugin';
import {
AppDragEvent,
DragPlugin,
InteractionPlugin,
InteractionPluginType,
ViewportMovePlugin,
} from '../plugins/InteractionPlugin';
import {
JlGraphicAppKeyboardPlugin,
KeyListener,
} from '../plugins/KeyboardPlugin';
import { ContextMenu, ContextMenuPlugin } from '../ui/ContextMenu';
import { MenuItemOptions } from '../ui/Menu';
import { getRectangleCenter, recursiveChildren } from '../utils/GraphicUtils';
export const AppConsts = {
viewportname: '__viewport',
canvasname: '__jlcanvas',
AssistantAppendsName: '__assistantAppends',
};
/**
*
*/
export interface ICanvasProperties {
width: number;
height: number;
backgroundColor: string;
viewportTransform: GraphicTransform;
}
export class CanvasData implements ICanvasProperties {
width: number;
height: number;
backgroundColor: string;
viewportTransform: GraphicTransform;
constructor(
properties: ICanvasProperties = {
width: 1920,
height: 1080,
backgroundColor: '#ffffff',
viewportTransform: GraphicTransform.default(),
}
) {
this.width = properties.width;
this.height = properties.height;
this.backgroundColor = properties.backgroundColor;
this.viewportTransform = properties.viewportTransform;
}
copyFrom(properties: ICanvasProperties): boolean {
let sizeChange = false;
if (properties.width <= 0 || properties.height <= 0) {
console.error('画布宽度/高度不能小于等于0');
} else {
const width = Math.floor(properties.width);
const height = Math.floor(properties.height);
if (this.width != width) {
this.width = width;
sizeChange = true;
}
if (this.height != height) {
this.height = height;
sizeChange = true;
}
}
this.backgroundColor = properties.backgroundColor;
this.viewportTransform = properties.viewportTransform;
return sizeChange;
}
clone(): CanvasData {
const cp = new CanvasData(this);
return cp;
}
}
export class JlCanvas extends Container {
__JlCanvas = true;
type = 'Canvas';
app: GraphicApp;
_properties: CanvasData;
bg: Graphics = new Graphics(); // 背景
nonInteractiveContainer: Container; // 无交互对象容器
assistantAppendContainer: Container; // 辅助附加容器
constructor(app: GraphicApp, properties: CanvasData = new CanvasData()) {
super();
this.app = app;
this._properties = properties;
this.eventMode = 'static';
this.nonInteractiveContainer = new Container();
this.nonInteractiveContainer.name = 'non-interactives';
this.nonInteractiveContainer.eventMode = 'none';
this.addChild(this.bg);
this.addChild(this.nonInteractiveContainer);
this.sortableChildren = true;
this.assistantAppendContainer = new Container();
this.assistantAppendContainer.eventMode = 'static';
this.assistantAppendContainer.name = AppConsts.AssistantAppendsName;
this.assistantAppendContainer.zIndex = 999;
this.assistantAppendContainer.sortableChildren = true;
this.addChild(this.assistantAppendContainer);
this.repaint();
}
/**
* /
*/
repaint(): void {
this.doRepaint();
}
public get width(): number {
return this._properties.width;
}
public get height(): number {
return this._properties.height;
}
public get backgroundColor(): string {
return this._properties.backgroundColor;
}
doRepaint() {
this.bg.clear();
this.bg
.beginFill(new Color(this.backgroundColor))
.drawRect(0, 0, this._properties.width, this._properties.height)
.endFill();
}
public get properties(): CanvasData {
return this._properties;
}
saveData(): CanvasData {
const vp = this.getViewport();
this.properties.viewportTransform = vp.saveTransform();
return this.properties.clone();
}
update(properties: ICanvasProperties) {
// 更新画布
const old = this.properties.clone();
const sizeChange = this._properties.copyFrom(properties);
this.repaint();
if (sizeChange) {
this.app.updateViewport();
}
const vp = this.getViewport();
vp.loadTransform(properties.viewportTransform);
this.emit('dataupdate', this.properties, old);
}
addChild<U extends DisplayObject[]>(...children: U): U[0] {
const rt = super.addChild(...children);
children.forEach((g) => {
recursiveChildren(g as Container, (child) => child.onAddToCanvas());
});
return rt;
}
removeChild<U extends DisplayObject[]>(...children: U): U[0] {
children.forEach((g) => {
recursiveChildren(g as Container, (child) => child.onRemoveFromCanvas());
});
return super.removeChild(...children);
}
/**
* Child
*/
addNonInteractiveChild(...obj: DisplayObject[]): void {
this.nonInteractiveContainer.addChild(...obj);
obj.forEach((g) => {
recursiveChildren(g as Container, (child) => child.onAddToCanvas());
});
}
removeGraphic(...obj: DisplayObject[]): void {
obj.forEach((g) => {
recursiveChildren(g as Container, (child) => child.onRemoveFromCanvas());
});
this.removeChild(...obj);
this.nonInteractiveContainer.removeChild(...obj);
}
/**
* Child
*/
removeNonInteractiveChild(...obj: DisplayObject[]): void {
obj.forEach((g) => {
recursiveChildren(g as Container, (child) => child.onRemoveFromCanvas());
});
this.nonInteractiveContainer.removeChild(...obj);
}
addAssistantAppends(...appends: DisplayObject[]): void {
this.assistantAppendContainer.addChild(...appends);
appends.forEach((g) => {
recursiveChildren(g as Container, (child) => child.onAddToCanvas());
});
}
removeAssistantAppends(...appends: DisplayObject[]): void {
appends.forEach((g) => {
recursiveChildren(g as Container, (child) => child.onAddToCanvas());
});
this.assistantAppendContainer.removeChild(...appends);
}
/**
*
*/
pauseInteractiveChildren() {
this.interactiveChildren = false;
}
/**
*
*/
resumeInteractiveChildren() {
this.interactiveChildren = true;
}
}
/**
*
*/
export class SelectedChangeEvent {
graphic: JlGraphic;
select: boolean;
constructor(graphic: JlGraphic, select: boolean) {
this.graphic = graphic;
this.select = select;
}
}
export interface GraphicAppEvents extends GlobalMixins.GraphicAppEvents {
graphicstored: [graphic: JlGraphic];
graphicdeleted: [graphic: JlGraphic];
loadfinish: [];
'interaction-plugin-resume': [plugin: InteractionPlugin]; // 交互插件启用
'interaction-plugin-pause': [plugin: InteractionPlugin]; // 交互插件停止
'options-update': [options: GraphicAppOptions]; // 配置更新
graphicselectedchange: [graphic: JlGraphic, selected: boolean];
graphicchildselectedchange: [child: DisplayObject, selected: boolean];
'viewport-scaled': [vp: Viewport];
drag_op_start: [event: AppDragEvent];
drag_op_move: [event: AppDragEvent];
drag_op_end: [event: AppDragEvent];
'pre-menu-handle': [menu: MenuItemOptions];
'post-menu-handle': [menu: MenuItemOptions];
destroy: [app: GraphicApp];
}
/**
* App构造参数
*/
export interface IGraphicAppConfig {
/**
*
*/
interactiveTypeOptions?: IInteractiveGraphicOptions;
/**
* 100
*/
maxOperationRecords?: number;
/**
*
*/
threshold?: number;
/**
*
*/
mouseToolOptions?: IMouseToolOptions;
/**
*
*/
absorbablePositions?: AbsorbablePosition[];
/**
* true
*/
cullable?: boolean;
}
/**
*
*/
export interface IInteractiveGraphicOptions {
/**
* Excludes同时只能存在一个
*/
interactiveGraphicTypeIncludes?: string[];
/**
* Includes同时只能存在一个
*/
interactiveGraphicTypeExcludes?: string[];
}
export type GraphicAppOptions = IGraphicAppConfig;
/**
* app基类
*/
export class GraphicApp extends EventEmitter<GraphicAppEvents> {
private graphicStore: GraphicStore;
_options?: GraphicAppOptions;
dom: HTMLElement;
app: Application; // Pixi 渲染器
viewport: Viewport; // 视口
canvas: JlCanvas; // 画布
interactiveTypeOptions: IInteractiveGraphicOptions; // 图形交互配置
graphicTemplateMap: Map<string, GraphicTemplate> = new Map<
string,
GraphicTemplate
>(); // 图形对象模板
opRecord: OperationRecord; // 操作记录
keyboardPlugin: JlGraphicAppKeyboardPlugin; // 键盘操作处理插件
graphicCopyPlugin: GraphicCopyPlugin; // 图形复制操作插件
menuPlugin: ContextMenuPlugin; // 菜单插件
animationManager: AnimationManager; // 动画管理组件
interactionPluginMap: Map<string, InteractionPlugin> = new Map<
string,
InteractionPlugin
>(); // 交互插件
wsMsgBroker?: AppWsMsgBroker; // websocket消息代理
constructor(dom: HTMLElement) {
super();
document.body.style.overflow = 'hidden';
// console.log('创建图形App')
this.dom = dom;
this.graphicStore = new GraphicStore(this);
/**
*
*/
this.interactiveTypeOptions = { interactiveGraphicTypeIncludes: [] };
// 创建pixi渲染app
this.app = new Application({
width: dom.clientWidth,
height: dom.clientHeight,
antialias: true,
resizeTo: dom,
});
dom.appendChild(this.app.view as unknown as Node);
// 创建画布
this.canvas = new JlCanvas(this);
this.canvas.name = AppConsts.canvasname;
// 创建相机
this.viewport = new Viewport({
screenWidth: window.innerWidth,
screenHeight: window.innerHeight,
worldWidth: this.canvas._properties.width,
worldHeight: this.canvas._properties.height,
// divWheel: dom,
passiveWheel: true,
events: this.app.renderer.events,
disableOnContextMenu: true,
});
// 设置视口操作方式
this.viewport
.wheel({
percent: 1,
})
.pinch()
.clampZoom({
minScale: 0.1,
maxScale: 8,
})
.clamp({
direction: 'all',
});
this.viewport.name = AppConsts.viewportname;
this.viewport.interactiveChildren = true;
// 添加视口到渲染器舞台
this.app.stage.addChild(this.viewport);
// 将画布置于视口
this.viewport.addChild(this.canvas);
// 监听并通知缩放变化事件
this.viewport.on('zoomed-end', () => {
this.emit('viewport-scaled', this.viewport);
});
this.opRecord = new OperationRecord();
// 绑定键盘监听
this.keyboardPlugin = new JlGraphicAppKeyboardPlugin(this);
this.graphicCopyPlugin = new GraphicCopyPlugin(this);
this.menuPlugin = new ContextMenuPlugin(this);
// 添加通用交互插件
CommonMouseTool.new(this).resume();
// drag插件
DragPlugin.new(this).resume();
// 视口移动插件
ViewportMovePlugin.new(this);
// 图形变换插件
GraphicTransformPlugin.new(this).resume();
// 动画管理
this.animationManager = new AnimationManager(this);
}
setOptions(options: GraphicAppOptions) {
// console.log('更新选项', options);
if (this._options) {
this._options = Object.assign(this._options, options);
} else {
this._options = options;
}
if (options.interactiveTypeOptions) {
// 更新交互类型配置
this.interactiveTypeOptions = options.interactiveTypeOptions;
}
if (options.maxOperationRecords && options.maxOperationRecords > 0) {
this.opRecord.setMaxLen(options.maxOperationRecords);
}
this.emit('options-update', options);
}
/**
*
* @param graphicTemplates
*/
registerGraphicTemplates(...graphicTemplates: GraphicTemplate[]) {
graphicTemplates.forEach((graphicTemplate) => {
this.graphicTemplateMap.set(graphicTemplate.type, graphicTemplate);
});
}
getGraphicTemplatesByType<GT extends GraphicTemplate>(type: string): GT {
const template = this.graphicTemplateMap.get(type);
if (!template) {
throw new Error(`不存在type=${type}的图形对象模板`);
}
return template as GT;
}
/**
*
* @param menu
*/
registerMenu(menu: ContextMenu) {
this.menuPlugin.registerMenu(menu);
}
/**
* 使websocket Stomp通信
*/
enableWsStomp(options: StompCliOption) {
StompCli.new(options);
this.wsMsgBroker = new AppWsMsgBroker(this);
}
/**
* websocket消息
*/
subscribe(sub: AppStateSubscription) {
if (this.wsMsgBroker) {
// console.log('APP订阅', sub)
this.wsMsgBroker.subscribe(sub);
} else {
throw new Error('请先打开StompClient, 执行app.enableWebsocket()');
}
}
/**
* websocket订阅
*/
unsubscribe(destination: string) {
if (this.wsMsgBroker) {
this.wsMsgBroker.unsbuscribe(destination);
} else {
throw new Error('请先执行enableWebsocket');
}
}
/**
* websocket状态
* @param graphicStates
*/
handleGraphicStates(graphicStates: GraphicState[]) {
graphicStates.forEach((state) => {
const list = this.queryStore.queryByIdOrCode(state.code);
if (list.length == 0) {
const template = this.getGraphicTemplatesByType(state.graphicType);
const g = template.new();
g.loadState(state);
this.addGraphics(g);
} else {
list.forEach((g) => {
g.updateStates(state);
});
}
});
}
/**
* ,
* @param keyListeners
*/
addKeyboardListener(...keyListeners: KeyListener[]) {
keyListeners.forEach((keyListener) =>
this.keyboardPlugin.addKeyListener(keyListener)
);
}
/**
*
* @param keyListeners
*/
removeKeyboardListener(...keyListeners: KeyListener[]) {
keyListeners.forEach((keyListener) =>
this.keyboardPlugin.removeKeyListener(keyListener)
);
}
/**
* dom尺寸变更处理
* @param domWidth canvas容器的宽
* @param domHeight canvas容器的高
*/
onDomResize(domWidth: number, domHeight: number) {
this.updateViewport(domWidth, domHeight);
}
public get queryStore(): GraphicQueryStore {
return this.graphicStore;
}
public get selectedGraphics(): JlGraphic[] {
return this.queryStore.getAllGraphics().filter((g) => g.selected);
}
fireSelectedChange(graphic: JlGraphic) {
// console.log('通知选中变化', this.selecteds)
const select = graphic.selected;
this.emit('graphicselectedchange', graphic, select);
}
/**
*
*/
updateSelected(...graphics: JlGraphic[]) {
this.selectedGraphics.forEach((graphic) => {
if (graphics.findIndex((g) => g.id === graphic.id) >= 0) {
return;
}
if (graphic.selected) {
graphic.updateSelected(false);
this.fireSelectedChange(graphic);
}
});
graphics.forEach((graphic) => {
if (graphic.updateSelected(true)) {
this.fireSelectedChange(graphic);
}
});
}
/**
*
* @param param
*/
updateCanvas(param: ICanvasProperties) {
this.canvas.update(param);
}
/**
* ,GraphicApp默认添加到无交互容器,DrawApp默认添加到交互容器,
* @param protos
* @param options /
*/
async loadGraphic(protos: GraphicData[]) {
for (const item of this.graphicTemplateMap) {
await item[1].loadAssets();
}
// console.log('开始加载proto数据', protos);
// 加载数据到图形存储
protos.forEach((proto) => {
const template = this.getGraphicTemplatesByType(proto.graphicType);
const g = template.new();
g.loadData(proto);
this.addGraphics(g);
});
// 加载数据关系
this.graphicStore.getAllGraphics().forEach((g) => g.loadRealtions());
// 更新id生成器
const max =
this.graphicStore
.getAllGraphics()
.filter((g) => !isNaN(parseInt(g.id)))
.map((g) => parseInt(g.id))
.sort((a, b) => a - b)
.pop() ?? 0;
// console.log('最大值', max)
GraphicIdGenerator.initSerial(max);
// 加载完成通知
this.emit('loadfinish');
}
/**
*
* @param graphic
*/
beforeGraphicStore(graphic: JlGraphic): void {
const options = this.interactiveTypeOptions;
// 默认无交互
graphic.eventMode = 'auto';
if (options) {
if (
options.interactiveGraphicTypeIncludes &&
options.interactiveGraphicTypeIncludes.findIndex(
(type) => type === graphic.type
) >= 0
) {
graphic.eventMode = 'static';
} else if (
options.interactiveGraphicTypeExcludes &&
options.interactiveGraphicTypeExcludes.findIndex(
(type) => type === graphic.type
) < 0
) {
graphic.eventMode = 'static';
}
}
}
private doAddGraphics(graphic: JlGraphic): void {
this.beforeGraphicStore(graphic);
if (this.graphicStore.storeGraphics(graphic)) {
// cullable,默认设置剪裁,如果图形包围框不在屏幕内,则不渲染,增加效率用
if (!this._options || this._options.cullable !== false) {
graphic.cullable = true;
}
if (graphic.eventMode == 'static' || graphic.eventMode == 'dynamic') {
// 添加为可交互
// console.log(`type=${graphic.type}的图形添加到交互容器`);
this.canvas.addChild(graphic);
} else {
// 添加到不可交互容器
// console.log(`type=${graphic.type}的图形添加到无交互容器`);
this.canvas.addNonInteractiveChild(graphic);
}
graphic.repaint();
this.emit('graphicstored', graphic);
graphic.on('childselected', (child) => {
this.emit('graphicchildselectedchange', child, true);
});
graphic.on('childunselected', (child) => {
this.emit('graphicchildselectedchange', child, false);
});
}
}
private doDeleteGraphics(graphic: JlGraphic): void {
// graphic可能是vue的Proxy对象会导致canvas删除时因不是同一个对象而无法从画布移除
const g = this.graphicStore.deleteGraphics(graphic);
if (g) {
// 从画布移除
this.canvas.removeGraphic(g);
// 清除选中
if (g.updateSelected(false)) {
this.fireSelectedChange(g);
}
// 对象删除处理
g.onDelete();
this.emit('graphicdeleted', g);
}
}
/**
*
* @param graphics
*/
addGraphics(...graphics: JlGraphic[]) {
graphics.forEach((g) => this.doAddGraphics(g));
}
/**
*
* @param graphics
*/
deleteGraphics(...graphics: JlGraphic[]) {
graphics.forEach((g) => this.doDeleteGraphics(g));
}
/**
*
*/
detectRelations(): void {
this.graphicStore.getAllGraphics().forEach((g) => g.buildRelation());
}
/**
*
* @param e
* @returns
*/
toCanvasCoordinates(p: Point): Point {
return this.viewport.toWorld(p);
}
/**
*
*/
getViewportScaled(): number {
return this.viewport.scaled;
}
/**
*
* @returns
*/
getViewportCenter(): Point {
return this.viewport.center;
}
/**
*
* @returns
*/
getViewportCorner(): Point {
return this.viewport.corner;
}
/**
* ,
*/
registerInteractionPlugin(...plugins: InteractionPlugin[]): void {
plugins.forEach((plugin) => {
const old = this.interactionPluginMap.get(plugin.name);
if (old) {
console.warn(`已经存在name=${plugin.name}的交互插件,忽略此插件注册!`);
return;
}
this.interactionPluginMap.set(plugin.name, plugin);
});
}
/**
*
* @param name
* @returns
*/
interactionPlugin<P = InteractionPlugin>(name: string): P {
const plugin = this.interactionPluginMap.get(name);
if (!plugin) {
throw new Error(`未找到name=${name}的交互插件`);
}
return plugin as P;
}
/**
*
*/
pauseAppInteractionPlugins(): void {
this.interactionPluginMap.forEach((plugin) => {
if (plugin.isActive() && plugin._type === InteractionPluginType.App) {
this.doPauseInteractionPlugin(plugin);
}
});
}
private doPauseInteractionPlugin(plugin?: InteractionPlugin): void {
if (plugin && plugin.isActive()) {
plugin.pause();
this.emit('interaction-plugin-pause', plugin);
}
}
/**
*
*/
removeInteractionPlugin(plugin: InteractionPlugin) {
this.interactionPluginMap.delete(plugin.name);
}
updateViewport(domWidth?: number, domHeight?: number): void {
let screenWidth = this.viewport.screenWidth;
let screenHeight = this.viewport.screenHeight;
if (domWidth) {
screenWidth = domWidth;
}
if (domHeight) {
screenHeight = domHeight;
}
const worldWidth = this.canvas._properties.width;
const worldHeight = this.canvas._properties.height;
this.app.resize();
this.viewport.resize(screenWidth, screenHeight, worldWidth, worldHeight);
if (this.viewport.OOB().right) {
this.viewport.right = this.viewport.right + 1;
} else if (this.viewport.OOB().left) {
this.viewport.left = this.viewport.left - 1;
} else if (this.viewport.OOB().top) {
this.viewport.top = this.viewport.top - 1;
} else if (this.viewport.OOB().bottom) {
this.viewport.bottom = this.viewport.bottom + 1;
}
}
/**
* 使()
*/
makeGraphicCenterShow(...group: JlGraphic[]): void {
if (group.length > 0) {
const bounds0 = group[0].getBounds();
let lx = bounds0.x;
let ly = bounds0.y;
let rx = bounds0.x + bounds0.width;
let ry = bounds0.y + bounds0.height;
if (group.length > 1) {
for (let i = 1; i < group.length; i++) {
const g = group[i];
const bound = g.getBounds();
if (bound.x < lx) {
lx = bound.x;
}
if (bound.y < ly) {
ly = bound.y;
}
const brx = bound.x + bound.width;
if (brx > rx) {
rx = brx;
}
const bry = bound.y + bound.height;
if (bry > ry) {
ry = bry;
}
}
}
const { x, y } = getRectangleCenter(
new Rectangle(lx, ly, rx - lx, ry - ly)
);
const p = this.viewport.toWorld(x, y);
this.viewport.moveCenter(p.x, p.y);
}
}
/**
*
*/
destroy(): void {
console.log('销毁图形 APP');
this.emit('destroy', this);
if (this.wsMsgBroker) {
this.wsMsgBroker.close();
if (!StompCli.hasAppMsgBroker()) {
// 如果没有其他消息代理关闭websocket Stomp客户端
StompCli.close();
}
}
this.interactionPluginMap.forEach((plugin) => {
plugin.pause();
});
this.canvas.destroy(true);
this.viewport.destroy();
this.app.destroy(true, true);
document.body.style.overflow = 'auto';
}
}

View File

@ -0,0 +1,2 @@
export * from './JlGraphicApp';
export * from './JlDrawApp';

View File

@ -0,0 +1,185 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { GraphicApp } from '../app/JlGraphicApp';
import { JlGraphic } from './JlGraphic';
/**
*
*/
export class GraphicRelationParam {
g: JlGraphic;
param: any;
constructor(g: JlGraphic, param: any = null) {
this.g = g;
this.param = param;
}
isTheGraphic(g: JlGraphic): boolean {
return this.g.id === g.id;
}
getGraphic<G extends JlGraphic>(): G {
return this.g as G;
}
getParam<P>(): P {
return this.param as P;
}
equals(other: GraphicRelationParam): boolean {
return this.isTheGraphic(other.g) && this.param === other.param;
}
}
/**
*
*/
export class GraphicRelation {
rp1: GraphicRelationParam;
rp2: GraphicRelationParam;
constructor(rp1: GraphicRelationParam, rp2: GraphicRelationParam) {
this.rp1 = rp1;
this.rp2 = rp2;
}
contains(g: JlGraphic): boolean {
return this.rp1.isTheGraphic(g) || this.rp2.isTheGraphic(g);
}
/**
*
* @param g
* @returns
*/
getRelationParam(g: JlGraphic): GraphicRelationParam {
if (!this.contains(g)) {
throw new Error(
`图形关系${this.rp1.g.id}-${this.rp2.g.id}中不包含给定图形${g.id}`
);
}
if (this.rp1.isTheGraphic(g)) {
return this.rp1;
} else {
return this.rp2;
}
}
/**
*
* @param g
* @returns
*/
getOtherRelationParam(g: JlGraphic): GraphicRelationParam {
if (!this.contains(g)) {
throw new Error(
`图形关系${this.rp1.g.id}-${this.rp2.g.id}中不包含给定图形${g.id}`
);
}
if (this.rp1.isTheGraphic(g)) {
return this.rp2;
} else {
return this.rp1;
}
}
/**
*
* @param g
* @returns graphic
*/
getOtherGraphic<G extends JlGraphic>(g: JlGraphic): G {
return this.getOtherRelationParam(g).g as G;
}
equals(orp1: GraphicRelationParam, orp2: GraphicRelationParam): boolean {
if (this.rp1.isTheGraphic(orp1.g)) {
return this.rp1.equals(orp1) && this.rp2.equals(orp2);
} else if (this.rp1.isTheGraphic(orp2.g)) {
return this.rp1.equals(orp2) && this.rp2.equals(orp1);
}
return false;
}
isEqualOther(other: GraphicRelation): boolean {
return this.equals(other.rp1, other.rp2);
}
}
/**
*
*/
export class RelationManage {
app: GraphicApp;
relations: GraphicRelation[] = [];
constructor(app: GraphicApp) {
this.app = app;
}
isContainsRelation(
rp1: GraphicRelationParam,
rp2: GraphicRelationParam
): boolean {
const relation = this.relations.find((relation) =>
relation.equals(rp1, rp2)
);
return !!relation;
}
addRelation(
rp1: GraphicRelationParam | JlGraphic,
rp2: GraphicRelationParam | JlGraphic
): void {
if (!(rp1 instanceof GraphicRelationParam)) {
rp1 = new GraphicRelationParam(rp1);
}
if (!(rp2 instanceof GraphicRelationParam)) {
rp2 = new GraphicRelationParam(rp2);
}
if (!this.isContainsRelation(rp1, rp2)) {
const relation = new GraphicRelation(rp1, rp2);
this.relations.push(relation);
}
}
/**
*
* @param g
* @returns
*/
getRelationsOfGraphic(g: JlGraphic): GraphicRelation[] {
return this.relations.filter((rl) => rl.contains(g));
}
/**
*
* @param g
* @param type
* @returns
*/
getRelationsOfGraphicAndOtherType(
g: JlGraphic,
type: string
): GraphicRelation[] {
return this.relations.filter(
(rl) => rl.contains(g) && rl.getOtherGraphic(g).type === type
);
}
/**
*
* @param relation
*/
private deleteRelation(relation: GraphicRelation): void {
const index = this.relations.findIndex((rl) => rl.isEqualOther(relation));
if (index >= 0) {
this.relations.splice(index, 1);
}
}
/**
*
* @param g
*/
deleteRelationOfGraphic(g: JlGraphic): void {
const relations = this.getRelationsOfGraphic(g);
relations.forEach((rl) => this.deleteRelation(rl));
}
/**
*
* @param g
*/
deleteRelationOfGraphicAndOtherType(g: JlGraphic, type: string): void {
const relations = this.getRelationsOfGraphicAndOtherType(g, type);
relations.forEach((rl) => this.deleteRelation(rl));
}
}

View File

@ -0,0 +1,185 @@
import { GraphicApp } from '../app/JlGraphicApp';
import { RelationManage } from './GraphicRelation';
import { JlGraphic } from './JlGraphic';
export interface GraphicQueryStore {
/**
*
*/
getAllGraphics(): JlGraphic[];
/**
* id获取图形
*/
queryById<T extends JlGraphic>(id: string): T;
/**
* id模糊查询图形
* @param id
*/
queryByIdAmbiguous(id: string): JlGraphic[];
/**
*
*/
queryByType<T extends JlGraphic>(type: string): T[];
/**
* code查询
* @param code
*/
queryByCode(code: string): JlGraphic[] | undefined;
/**
* code模糊查询图形
* @param code
* @param type
*/
queryByCodeAmbiguous(code: string): JlGraphic[];
/**
* id或code查询图形
* @param v
*/
queryByIdOrCode(v: string): JlGraphic[];
/**
* code和类型获取图形
* @param code
* @param type
*/
queryByCodeAndType<T extends JlGraphic>(
code: string,
type: string
): T | undefined;
/**
* code和类型模糊查询图形
* @param code
* @param type
*/
queryByCodeAndTypeAmbiguous<T extends JlGraphic>(
code: string,
type: string
): T[];
}
/**
*
*/
export class GraphicStore implements GraphicQueryStore {
app: GraphicApp;
store: Map<string, JlGraphic>;
relationManage: RelationManage;
constructor(app: GraphicApp) {
this.app = app;
this.store = new Map<string, JlGraphic>();
this.relationManage = new RelationManage(app);
}
/**
*
*/
getAllGraphics(): JlGraphic[] {
return [...this.store.values()];
}
queryById<T extends JlGraphic>(id: string): T {
const graphic = this.store.get(id) as T;
if (!graphic) throw Error(`未找到id为 [${id}] 的图形.`);
return this.store.get(id) as T;
}
queryByIdAmbiguous(id: string): JlGraphic[] {
const list: JlGraphic[] = [];
this.store.forEach((g) => {
if (g.id.search(id) >= 0) {
list.push(g);
}
});
return list;
}
queryByType<T extends JlGraphic>(type: string): T[] {
const list: T[] = [];
this.store.forEach((g) => {
if (g.type === type) {
list.push(g as T);
}
});
return list;
}
queryByCode(code: string): JlGraphic[] | undefined {
const list: JlGraphic[] = [];
this.store.forEach((g) => {
if (g.code === code) {
list.push(g);
}
});
return list;
}
queryByCodeAmbiguous(code: string): JlGraphic[] {
const list: JlGraphic[] = [];
this.store.forEach((g) => {
if (g.code.search(code) >= 0) {
list.push(g);
}
});
return list;
}
queryByIdOrCode(s: string): JlGraphic[] {
const list: JlGraphic[] = [];
this.store.forEach((g) => {
if (g.isIdOrCode(s)) {
list.push(g);
}
});
return list;
}
queryByCodeAndType<T extends JlGraphic>(
code: string,
type: string
): T | undefined {
for (const item of this.store.values()) {
if (item.code === code && item.type === type) {
return item as T;
}
}
}
queryByCodeAndTypeAmbiguous<T extends JlGraphic>(
code: string,
type: string
): T[] {
const list: T[] = [];
this.store.forEach((g) => {
if (g.type === type && g.code.search(code) >= 0) {
list.push(g as T);
}
});
return list;
}
/**
*
* @param graphics
*/
storeGraphics(graphic: JlGraphic): boolean {
if (!graphic.id || graphic.id.trim() === '') {
throw new Error(`存储图形对象异常: id为空, ${graphic}`);
}
if (this.store.has(graphic.id)) {
// 已经存在
const exist = this.store.get(graphic.id);
console.error(`已经存在id=${graphic.id}的设备${exist}`);
return false;
} else {
this.store.set(graphic.id, graphic);
graphic.queryStore = this;
graphic.relationManage = this.relationManage;
return true;
}
}
/**
*
* @param graph
*/
deleteGraphics(graphic: JlGraphic): JlGraphic | undefined {
const id = graphic.id;
const remove = this.store.get(id);
if (remove) {
this.store.delete(id);
// 删除图形关系
this.relationManage.deleteRelationOfGraphic(remove);
}
return remove;
}
}

View File

@ -0,0 +1,28 @@
/**
* ID生成器
*/
export class IdGenerator {
serial = 0;
type: string;
constructor(type: string) {
this.type = type;
}
next(): string {
++this.serial;
// console.log(this.getType() + this.serial)
return this.getType() + this.serial;
}
getType(): string {
return this.type;
}
initSerial(serial: number): void {
// console.log(serial)
this.serial = serial;
}
}
export const GraphicIdGenerator: IdGenerator = new IdGenerator('');

View File

@ -0,0 +1,966 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-function */
import { Viewport } from 'pixi-viewport';
import {
Container,
DisplayObject,
Graphics,
IPointData,
Point,
Rectangle,
} from 'pixi.js';
import { AppConsts, JlCanvas } from '../app';
import {
convertRectangleToPolygonPoints,
recursiveChildren,
recursiveFindChild,
recursiveFindParent,
recursiveParents,
} from '../utils';
import { GraphicRelation, RelationManage } from './GraphicRelation';
import { GraphicQueryStore } from './GraphicStore';
import { GraphicIdGenerator } from './IdGenerator';
//基础图形对象扩展
DisplayObject.prototype._selectable = false; //是否可选中
DisplayObject.prototype._selected = false;
DisplayObject.prototype._childEdit = false;
DisplayObject.prototype._transformSave = false;
DisplayObject.prototype._assistantAppendMap = null;
DisplayObject.prototype._draggable = false;
DisplayObject.prototype._shiftStartPoint = null;
DisplayObject.prototype._shiftLastPoint = null;
DisplayObject.prototype._scalable = false;
DisplayObject.prototype._keepAspectRatio = true;
DisplayObject.prototype._rotatable = false;
Object.defineProperties(DisplayObject.prototype, {
assistantAppendMap: {
get() {
if (this._assistantAppendMap == null) {
this._assistantAppendMap = new Map<string, DisplayObject>();
}
return this._assistantAppendMap;
},
},
selectable: {
get(): boolean {
return this._selectable;
},
set(value: boolean): void {
this._selectable = value;
},
},
selected: {
get(): boolean {
return this._selected;
},
set(v) {
this._selected = v;
},
},
childEdit: {
get() {
return this._childEdit;
},
set(v) {
this._childEdit = v;
},
},
transformSave: {
get() {
return this._transformSave;
},
set(v) {
this._transformSave = v;
},
},
draggable: {
get(): boolean {
return this._draggable;
},
set(v) {
this._draggable = v;
},
},
shiftStartPoint: {
get() {
return this._shiftStartPoint;
},
set(v) {
this._shiftStartPoint = v;
},
},
shiftLastPoint: {
get() {
return this._shiftLastPoint;
},
set(v) {
this._shiftLastPoint = v;
},
},
scalable: {
get() {
return this._scalable;
},
set(v) {
this._scalable = v;
},
},
keepAspectRatio: {
get(): boolean {
return this._keepAspectRatio;
},
set(v) {
this._keepAspectRatio = v;
},
},
rotatable: {
get() {
return this._rotatable;
},
set(v) {
this._rotatable = v;
},
},
worldAngle: {
get() {
let angle = this.angle;
let parent = this.parent;
while (parent != undefined && parent != null) {
angle += parent.angle;
parent = parent.parent;
}
angle = angle % 360;
if (angle > 180) {
angle = angle - 360;
}
return angle;
},
},
});
DisplayObject.prototype.getAllParentScaled =
function getAllParentScaled(): Point {
const scaled = new Point(1, 1);
recursiveParents(this, (parent) => {
scaled.x *= parent.scale.x;
scaled.y *= parent.scale.y;
});
return scaled;
};
DisplayObject.prototype.saveTransform = function saveTransform() {
return GraphicTransform.fromObject(this);
};
DisplayObject.prototype.loadTransform = function loadTransform(
transfrom: GraphicTransform
) {
this.position.copyFrom(transfrom.position);
this.scale.copyFrom(transfrom.scale);
this.rotation = transfrom.rotation;
this.skew.copyFrom(transfrom.skew);
};
DisplayObject.prototype.isChild = function isChild(
obj: DisplayObject
): boolean {
return recursiveFindChild(this as Container, (child) => child == obj) != null;
};
DisplayObject.prototype.isParent = function isParent(
obj: DisplayObject
): boolean {
return recursiveFindParent(this, (parent) => parent == obj) != null;
};
DisplayObject.prototype.isAssistantAppend =
function isAssistantAppend(): boolean {
return (
recursiveFindParent(this, (parent) => {
return parent.name === AppConsts.AssistantAppendsName;
}) != null
);
};
DisplayObject.prototype.addAssistantAppend = function addAssistantAppend<
D extends DisplayObject
>(...appends: D[]): void {
appends.forEach((append) => {
if (append.name == null || append.name.trim() == '') {
throw new Error('辅助附加name不能为空');
}
this.assistantAppendMap.set(append.name, append);
this.getCanvas().addAssistantAppends(append);
});
};
DisplayObject.prototype.getAssistantAppend = function getAssistantAppend<
D extends DisplayObject
>(name: string): D | undefined {
return this.assistantAppendMap.get(name) as D;
};
DisplayObject.prototype.removeAssistantAppend = function removeAssistantAppend(
...appends: DisplayObject[]
): void {
appends.forEach((append) => {
if (append.name) {
this.removeAssistantAppendByName(append.name);
}
});
};
DisplayObject.prototype.removeAssistantAppendByName =
function removeAssistantAppendByName(...names: string[]): void {
names.forEach((name) => {
const append = this.getAssistantAppend(name);
if (append) {
this.getCanvas().removeAssistantAppends(append);
this.assistantAppendMap.delete(name);
append.destroy();
}
});
};
DisplayObject.prototype.removeAllAssistantAppend =
function removeAllAssistantAppend(): void {
if (this._assistantAppendMap != null) {
this.assistantAppendMap.forEach((append) => {
append.getCanvas().removeAssistantAppends(append);
});
this.assistantAppendMap.clear();
}
};
DisplayObject.prototype.isGraphic = function isGraphic() {
return Object.hasOwn(this, '__JlGraphic');
};
DisplayObject.prototype.getGraphic = function getGraphic<
G extends JlGraphic
>(): G | null {
let graphic = this as DisplayObject;
while (graphic && !Object.hasOwn(graphic, '__JlGraphic')) {
graphic = graphic.parent;
}
if (graphic) {
return graphic as G;
}
return null;
};
DisplayObject.prototype.isGraphicChild = function isGraphicChild() {
const g = this.getGraphic();
return g != null && !this.isAssistantAppend() && g.isChild(this);
};
DisplayObject.prototype.onAddToCanvas = function onAddToCanvas() {};
DisplayObject.prototype.onRemoveFromCanvas = function onRemoveFromCanvas() {};
DisplayObject.prototype.isInCanvas = function isInCanvas(): boolean {
let graphic = this as DisplayObject;
while (graphic && !Object.hasOwn(graphic, '__JlCanvas')) {
graphic = graphic.parent;
}
if (graphic) {
return true;
}
return false;
};
DisplayObject.prototype.getCanvas = function getCanvas() {
let graphic = this as DisplayObject;
while (graphic && !Object.hasOwn(graphic, '__JlCanvas')) {
graphic = graphic.parent;
}
if (graphic) {
return graphic as JlCanvas;
}
throw new Error(`图形${this.name}不在画布中`);
};
DisplayObject.prototype.isCanvas = function isCanvas(): boolean {
return Object.hasOwn(this, '__JlCanvas');
};
DisplayObject.prototype.getViewport = function getViewport() {
const canvas = this.getCanvas();
return canvas.parent as Viewport;
};
DisplayObject.prototype.getGraphicApp = function getGraphicApp() {
const canvas = this.getCanvas();
return canvas.app;
};
DisplayObject.prototype.localToCanvasPoint = function localToCanvasPoint(
p: IPointData
): Point {
return this.getViewport().toWorld(this.toGlobal(p));
};
DisplayObject.prototype.localToCanvasPoints = function localToCanvasPoints(
...points: IPointData[]
): Point[] {
return points.map((p) => this.localToCanvasPoint(p));
};
DisplayObject.prototype.canvasToLocalPoint = function canvasToLocalPoint(
p: IPointData
): Point {
return this.toLocal(this.getViewport().toScreen(p));
};
DisplayObject.prototype.canvasToLocalPoints = function canvasToLocalPoints(
...points: IPointData[]
): Point[] {
return points.map((p) => this.canvasToLocalPoint(p));
};
DisplayObject.prototype.localToScreenPoint = function localToScreenPoint(
p: IPointData
): Point {
return this.toGlobal(p);
};
DisplayObject.prototype.localToScreenPoints = function localToScreenPoints(
...points: IPointData[]
): Point[] {
return points.map((p) => this.toGlobal(p));
};
DisplayObject.prototype.screenToLocalPoint = function screenToLocalPoint(
p: IPointData
): Point {
return this.toLocal(p);
};
DisplayObject.prototype.screenToLocalPoints = function screenToLocalPoints(
...points: IPointData[]
): Point[] {
return points.map((p) => this.toLocal(p));
};
DisplayObject.prototype.localBoundsToCanvasPoints =
function localBoundsToCanvasPoints() {
const rect = this.getLocalBounds();
const pps = convertRectangleToPolygonPoints(rect);
return this.localToCanvasPoints(...pps);
};
// 扩展pixijs图形对象添加自定义绘制贝塞尔曲线可自定义分段数
Graphics.prototype.drawBezierCurve = function drawBezierCurve(
p1: IPointData,
p2: IPointData,
cp1: IPointData,
cp2: IPointData,
segmentsCount: number
): Graphics {
const fromX = p1.x;
const fromY = p1.y;
const n = segmentsCount;
let dt = 0;
let dt2 = 0;
let dt3 = 0;
let t2 = 0;
let t3 = 0;
const cpX = cp1.x;
const cpY = cp1.y;
const cpX2 = cp2.x;
const cpY2 = cp2.y;
const toX = p2.x;
const toY = p2.y;
this.moveTo(p1.x, p1.y);
for (let i = 1, j = 0; i <= n; ++i) {
j = i / n;
dt = 1 - j;
dt2 = dt * dt;
dt3 = dt2 * dt;
t2 = j * j;
t3 = t2 * j;
const px = dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX;
const py = dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY;
this.lineTo(px, py);
}
return this;
};
export interface IGraphicTransform {
position: IPointData;
scale: IPointData;
rotation: number;
skew: IPointData;
}
/**
*
*/
export class GraphicTransform {
position: IPointData;
scale: IPointData;
rotation: number;
skew: IPointData;
constructor(
position: IPointData,
scale: IPointData,
rotation: number,
skew: IPointData
) {
this.position = position;
this.scale = scale;
this.rotation = rotation;
this.skew = skew;
}
static default(): GraphicTransform {
return new GraphicTransform(
new Point(0, 0),
new Point(1, 1),
0,
new Point(0, 0)
);
}
static fromObject(obj: DisplayObject): GraphicTransform {
return new GraphicTransform(
obj.position.clone(),
obj.scale.clone(),
obj.rotation,
obj.skew.clone()
);
}
static from(transform: IGraphicTransform | undefined): GraphicTransform {
if (transform) {
return new GraphicTransform(
new Point(transform.position.x, transform.position.y),
new Point(transform.scale.x, transform.scale.y),
transform.rotation,
new Point(transform.skew.x, transform.skew.y)
);
}
return GraphicTransform.default();
}
}
export interface IChildTransform {
name: string;
transform: IGraphicTransform;
}
/**
*
*/
export class ChildTransform {
name: string;
transform: GraphicTransform;
constructor(name: string, transform: GraphicTransform) {
this.name = name;
this.transform = transform;
}
static fromChild(child: DisplayObject): ChildTransform {
if (
child.name == null ||
child.name == undefined ||
child.name.trim() == ''
) {
throw new Error(
`图形type=${
child.getGraphic()?.type
}${child}name为空`
);
}
return new ChildTransform(child.name, GraphicTransform.fromObject(child));
}
static from(ct: IChildTransform): ChildTransform {
return new ChildTransform(ct.name, GraphicTransform.from(ct.transform));
}
}
/**
*
*/
export interface GraphicData {
get id(): string; // 图形id
set id(v: string);
get graphicType(): string; // 图形类型
set graphicType(v: string);
get transform(): GraphicTransform; //
set transform(v: GraphicTransform);
get childTransforms(): ChildTransform[] | undefined; //
set childTransforms(v: ChildTransform[] | undefined);
/**
*
*/
clone(): GraphicData;
/**
*
* @param data
*/
copyFrom(data: GraphicData): void;
/**
*
* @param other
*/
eq(other: GraphicData): boolean;
}
/**
*
*/
export interface GraphicState {
get code(): string; // 业务标识
get graphicType(): string; // 图形类型
/**
*
*/
clone(): GraphicState;
/**
*
* @param data
*/
copyFrom(data: GraphicState): void;
/**
*
* @param data
*/
eq(data: GraphicState): boolean;
}
export interface GraphicAnimationOptions {
name: string;
run?: (dt: number) => void;
}
export class GraphicAnimation {
options: GraphicAnimationOptions;
_running: boolean;
/**
*
*/
_xSpeed: number;
constructor(options: GraphicAnimationOptions) {
this.options = options;
this._running = false;
this._xSpeed = 1;
}
static init(options: GraphicAnimationOptions) {
return new GraphicAnimation(options);
}
pause(): GraphicAnimation {
this._running = false;
return this;
}
resume(): GraphicAnimation {
this._running = true;
return this;
}
public get name(): string {
return this.options.name;
}
public get running(): boolean {
return this._running;
}
public get xSpeed(): number {
return this._xSpeed;
}
public set xSpeed(v: number) {
this._xSpeed = v;
}
run(dt: number): GraphicAnimation {
if (this.options.run) {
this.options.run(dt * this.xSpeed);
}
return this;
}
}
/**
*
*/
export abstract class JlGraphic extends Container {
readonly __JlGraphic = true as const;
readonly type: string; // 图形类型
private _id = ''; // 图形的唯一标识,不具有业务意义,唯一,不可重复,可用做图形数据关联。
private _code = ''; // 业务编号/名称,用于标识图形对象,具有业务意义
_datas?: GraphicData; // 图形数据
_states?: GraphicState; // 图形状态数据
private _relationManage?: RelationManage; // 图形关系管理
private _queryStore?: GraphicQueryStore; // 图形对象查询仓库
constructor(type: string) {
super();
this.type = type;
this.draggable = false;
this.filters;
}
/**
*
* @param animation
*/
addAnimation(animation: GraphicAnimation): void {
const app = this.getGraphicApp();
app.animationManager.registerAnimation(this, animation);
}
removeAnimation(name: string): void {
const app = this.getGraphicApp();
app.animationManager.unregisterAnimation(this, name);
}
animation(name: string): GraphicAnimation | undefined {
const app = this.getGraphicApp();
return app.animationManager.animation(this, name);
}
removeAllAnimation(): void {
const app = this.getGraphicApp();
app.animationManager.unregisterGraphicAnimations(this);
}
/**
*
* @param selected
* @returns
*/
updateSelected(selected: boolean): boolean {
if (this.selected !== selected) {
this.selected = selected;
this.fireSelected();
return true;
}
return false;
}
invertSelected() {
this.selected = !this.selected;
this.fireSelected();
}
fireSelected() {
if (this.selected) {
this.emit('selected', this);
} else {
this.exitChildEdit();
this.removeAllChildSelected();
this.emit('unselected', this);
}
}
hasSelectedChilds(): boolean {
return (
recursiveFindChild(this, (child) => {
if (child.selected) {
return true;
}
return false;
}) != null
);
}
setChildSelected(child: DisplayObject): boolean {
if (child.isGraphicChild() && child.selectable) {
this.removeAllChildSelected();
child.selected = true;
this.fireChildSelected(child);
}
return false;
}
invertChildSelected(child: DisplayObject): boolean {
if (child.isGraphicChild() && child.selectable) {
child.selected = !child.selected;
this.fireChildSelected(child);
}
return false;
}
removeAllChildSelected() {
recursiveChildren(this, (child) => {
if (child.selected) {
child.selected = false;
this.fireChildSelected(child);
}
});
}
fireChildSelected(child: DisplayObject) {
if (child.selected) {
this.emit('childselected', child);
} else {
this.emit('childunselected', child);
}
}
exitChildEdit() {
this.childEdit = false;
this.removeAllChildSelected();
}
/**
* id/code
*/
isIdOrCode(s: string): boolean {
return this.id === s || this.code === s;
}
/**
* idid
*/
public get id(): string {
if (this._datas) {
return this._datas.id;
}
return this._id;
}
/**
* idid
*/
public set id(v: string) {
this._id = v;
if (this._datas) {
this._datas.id = v;
}
}
/**
* codecode在图形数据或图形状态中
*/
public get code(): string {
return this._code;
}
/**
* codecode在图形数据或图形状态中
*/
public set code(v: string) {
this._code = v;
}
getDatas<D extends GraphicData>(): D {
if (this._datas) {
return this._datas as D;
}
throw new Error(`id=${this.id},type=${this.type}的图形没有数据`);
}
getStates<S extends GraphicState>(): S {
if (this._states) {
return this._states as S;
}
throw new Error(`id=${this.id},type=${this.type}的的图形没有状态`);
}
public get queryStore(): GraphicQueryStore {
if (this._queryStore) {
return this._queryStore;
}
throw new Error(`type=${this.type}的图形没有QueryStore`);
}
public set queryStore(v: GraphicQueryStore) {
this._queryStore = v;
}
public get relationManage(): RelationManage {
if (this._relationManage) {
return this._relationManage;
}
throw new Error(`type=${this.type}的图形没有关系管理`);
}
public set relationManage(v: RelationManage) {
this._relationManage = v;
}
/**
*
* @param g
*/
buildRelation() {}
/**
*
*/
loadRealtions() {}
/**
*
* @returns
*/
getAllRelations(): GraphicRelation[] {
return this.relationManage.getRelationsOfGraphic(this);
}
/**
*
* @param type
* @returns
*/
queryRelationByType(type: string): GraphicRelation[] {
return this.relationManage.getRelationsOfGraphicAndOtherType(this, type);
}
/**
*
* @param type
*/
deleteRelationByType(type: string): void {
this.relationManage.deleteRelationOfGraphicAndOtherType(this, type);
}
/**
* datas中
*/
saveRelations(): void {}
/**
*
* @returns
*/
saveData<D extends GraphicData>(): D {
this.getDatas().graphicType = this.type;
this.getDatas().transform = GraphicTransform.fromObject(this);
this.getDatas().childTransforms = this.buildChildTransforms();
this.saveRelations();
return this.getDatas().clone() as D;
}
/**
*
* @returns
*/
private buildChildTransforms(): ChildTransform[] {
const childTransforms: ChildTransform[] = [];
recursiveChildren(this, (child) => {
if (child.transformSave) {
childTransforms.push(ChildTransform.fromChild(child));
}
});
return childTransforms;
}
/**
*
* @param data
*/
loadData(data: GraphicData) {
if (data.graphicType !== this.type) {
throw new Error(
`不同的图形类型,请检查数据是否正常: data.graphicType="${data.graphicType}, type="${this.type}`
);
}
this._datas = data;
this.loadTransformFrom(data);
}
private loadTransformFrom(data: GraphicData) {
if (data.transform) {
this.loadTransform(data.transform);
}
if (data.childTransforms) {
data.childTransforms.forEach((ct) => {
const child = this.getChildByName(ct.name, true);
if (child) {
child.loadTransform(ct.transform);
}
});
}
}
/**
*
* @param data
* @returns
*/
updateData(data: GraphicData): boolean {
let update = false;
if (!this.getDatas().eq(data)) {
update = true;
const old = this.getDatas().clone();
this.getDatas().copyFrom(data);
this.onDataChange(data, old);
this.loadTransformFrom(data);
this.emit('dataupdate', this.getDatas(), old);
this.repaint();
}
return update;
}
/**
*
*/
onDataChange(newVal: GraphicData, old?: GraphicData): void {}
/**
*
* @param state
*/
loadState(state: GraphicState) {
if (state.graphicType !== this.type) {
throw new Error(
`不同的图形类型,请检查数据是否正常: state.graphicType="${state.graphicType}, type="${this.type}`
);
}
this._states = state;
}
/**
*
* @param state
* @returns
*/
updateStates(state: GraphicState): boolean {
let stateChange = false;
if (!this.getStates().eq(state)) {
// 判断并更新状态,默认状态
const old = this.getStates().clone();
this.getStates().copyFrom(state);
this.onStateChange(state, old);
stateChange = true;
this.emit('stateupdate', this.getStates(), old);
this.repaint();
}
return stateChange;
}
/**
*
*/
onStateChange(newVal: GraphicState, old?: GraphicState): void {}
repaint(): void {
this.doRepaint();
this.emit('repaint', this);
}
/**
*
*/
abstract doRepaint(): void;
/**
*
*/
onDelete(): void {
this.removeAllAssistantAppend();
this.removeAllListeners();
recursiveChildren(this, (child) => child.removeAllAssistantAppend());
}
/**
* ,,-
* @param box
* @returns
*/
boxIntersectCheck(box: Rectangle): boolean {
return box.intersects(this.getLocalBounds(), this.localTransform);
}
}
/**
*
*/
export abstract class JlGraphicTemplate<G extends JlGraphic> {
readonly type: string;
constructor(type: string) {
this.type = type;
}
/**
*
*/
abstract new(): G;
/**
*
*/
async loadAssets(): Promise<any> {}
/**
*
* @param graphic
* @returns
*/
clone(graphic: G): G {
const g = this.new();
if (graphic._datas) {
// 数据克隆
const datas = graphic.saveData();
g.loadData(datas);
}
if (graphic._states) {
// 状态克隆
const state = graphic.getStates().clone();
g.loadState(state);
}
g.id = GraphicIdGenerator.next();
return g;
}
}
export type GraphicTemplate = JlGraphicTemplate<JlGraphic>;

View File

@ -0,0 +1,4 @@
export * from './JlGraphic';
export * from './IdGenerator';
export * from './GraphicRelation';
export * from './GraphicStore';

108
src/jl-graphic/global.d.ts vendored Normal file
View File

@ -0,0 +1,108 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
declare namespace GlobalMixins {
type JlCanvasType = import('./app').JlCanvas;
type CanvasProperties = import('./app').ICanvasProperties;
type GraphicApp = import('./app').GraphicApp;
type JlGraphicType = import('./core').JlGraphic;
type GraphicData = import('./core').GraphicData;
type GraphicState = import('./core').GraphicState;
type GraphicTransform = import('./core').GraphicTransform;
type GraphicTransformEvent = import('./plugins').GraphicTransformEvent;
type BoundsGraphic = import('./plugins').BoundsGraphic;
type IPointDataType = import('pixi.js').IPointData;
type PointType = import('pixi.js').Point;
type FederatedMouseEvent = import('pixi.js').FederatedMouseEvent;
type DisplayObjectType = import('pixi.js').DisplayObject;
type ContainerType = import('pixi.js').Container;
interface DisplayObjectEvents {
'enter-absorbable-area': [number | undefined, number | undefined];
'out-absorbable-area': [number | undefined, number | undefined];
dataupdate: [newVal: any, oldVal: any];
stateupdate: [newVal: any, oldVal: any];
repaint: [DisplayObjectType];
transformstart: [e: GraphicTransformEvent];
transforming: [e: GraphicTransformEvent];
transformend: [e: GraphicTransformEvent];
_rightclick: [e: FederatedMouseEvent];
_leftclick: [e: FederatedMouseEvent];
selected: [DisplayObjectType];
unselected: [DisplayObjectType];
childselected: [DisplayObjectType];
childunselected: [DisplayObjectType];
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface GraphicAppEvents {
// propertiesupdate: [selectedData: GraphicData | CanvasProperties | null];
}
interface DisplayObject {
_selectable: boolean;
_selected: boolean;
selectable: boolean; //是否可选中
selected: boolean; // 是否选中
_childEdit: boolean; // 子元素编辑模式
childEdit: boolean;
_transformSave: boolean; // 变换是否保存
transformSave: boolean; //
_assistantAppendMap: Map<string, DisplayObjectType> | null; // 辅助附加图形map
assistantAppendMap: Map<string, DisplayObjectType>;
_draggable: boolean; // 是否可拖拽
draggable: boolean;
_shiftStartPoint: PointType | null; // 位移起始坐标
shiftStartPoint: PointType | null;
_shiftLastPoint: PointType | null; // 位移上一个事件时坐标
shiftLastPoint: PointType | null;
_scalable: boolean; // 是否可缩放
scalable: boolean;
_keepAspectRatio: boolean; // 缩放是否保持纵横比,默认保持
keepAspectRatio: boolean;
_rotatable: boolean; // 是否可旋转
rotatable: boolean;
worldAngle: number; // 世界角度,(-180, 180]
getAllParentScaled(): PointType;
saveTransform(): GraphicTransform; // 保存变换
loadTransform(transform: GraphicTransform): void; // 加载变换
isChild(obj: DisplayObject): boolean; // 是否子元素
isParent(obj: DisplayObject): boolean; // 是否父元素
isAssistantAppend(): boolean; // 是否辅助附加图形
addAssistantAppend<D extends DisplayObjectType>(...appends: D[]): void;
removeAssistantAppend(...appends: DisplayObjectType[]): void;
removeAssistantAppendByName(...names: string[]): void;
removeAllAssistantAppend(): void;
getAssistantAppend<D extends DisplayObjectType>(
name: string
): D | undefined; // 获取辅助附加图形对象
isGraphic(): boolean; // 是否业务图形对象
getGraphic<G extends JlGraphicType>(): G | null; // 获取所属的图形对象
isGraphicChild(): boolean; // 是否图形子元素
onAddToCanvas(): void; // 添加到画布处理
onRemoveFromCanvas(): void; //从画布移除处理
isInCanvas(): boolean; // 是否添加到画布中
getCanvas(): JlCanvasType; // 获取所在画布
isCanvas(): boolean; // 是否画布对象
getViewport(): Viewport; // 获取视口
getGraphicApp(): GraphicApp; // 获取图形app
localToCanvasPoint(p: IPointData): PointType; // 图形本地坐标转为画布坐标
localToCanvasPoints(...points: IPointData[]): PointType[]; // 批量转换
canvasToLocalPoint(p: IPointData): PointType; // 画布坐标转为图形本地坐标
canvasToLocalPoints(...points: IPointData[]): PointType[]; // 批量转换
localToScreenPoint(p: IPointData): PointType; // 本地坐标转为屏幕坐标
localToScreenPoints(...points: IPointData[]): PointType[]; // 批量
screenToLocalPoint(p: IPointData): PointType; // 屏幕坐标转为本地坐标
screenToLocalPoints(...points: IPointData[]): PointType[]; // 批量
localBoundsToCanvasPoints(): PointType[]; // 本地包围框转为多边形点坐标
}
interface Graphics {
drawBezierCurve(
p1: IPointData,
p2: IPointData,
cp1: IPointData,
cp2: IPointData,
segmentsCount: number
): Graphics;
}
}

View File

@ -0,0 +1,173 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
Color,
Container,
DisplayObject,
Graphics,
IPointData,
Point,
} from 'pixi.js';
import {
calculateFootPointFromPointToLine,
calculateIntersectionPointOfCircleAndPoint,
distance,
linePoint,
} from '../utils';
import { VectorGraphic, VectorGraphicUtil } from './VectorGraphic';
/**
*
*/
export interface AbsorbablePosition extends Container {
/**
*
* @param objs
* @returns truefalse
*/
tryAbsorb(...objs: DisplayObject[]): boolean;
}
/**
*
*/
export const AbsorbablePointParam = {
lineWidth: 1,
lineColor: '#000000',
fillColor: '#E77E0E',
radius: 5, // 半径
};
const AbsorbablePointGraphic = new Graphics();
// AbsorbablePointGraphic.lineStyle(
// AbsorbablePointParam.lineWidth,
// AbsorbablePointParam.lineColor
// );
AbsorbablePointGraphic.beginFill(AbsorbablePointParam.fillColor);
AbsorbablePointGraphic.drawCircle(0, 0, AbsorbablePointParam.radius);
AbsorbablePointGraphic.endFill();
/**
*
*/
export default class AbsorbablePoint
extends Graphics
implements AbsorbablePosition, VectorGraphic
{
_point: Point;
absorbRange: number;
scaledListenerOn = false;
constructor(point: IPointData, absorbRange = 10) {
super(AbsorbablePointGraphic.geometry);
this._point = new Point(point.x, point.y);
this.absorbRange = absorbRange;
this.position.copyFrom(this._point);
this.interactive;
VectorGraphicUtil.handle(this);
}
tryAbsorb(...objs: DisplayObject[]): boolean {
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
if (
distance(this._point.x, this._point.y, obj.position.x, obj.position.y) <
this.absorbRange
) {
obj.position.copyFrom(this._point);
return true;
}
}
return false;
}
updateOnScaled() {
const scaled = this.getAllParentScaled();
const scale = Math.max(scaled.x, scaled.y);
this.scale.set(1 / scale, 1 / scale);
}
}
/**
* 线
*/
export class AbsorbableLine extends Graphics implements AbsorbablePosition {
p1: Point;
p2: Point;
absorbRange: number;
_color = '#E77E0E';
constructor(p1: IPointData, p2: IPointData, absorbRange = 20) {
super();
this.p1 = new Point(p1.x, p1.y);
this.p2 = new Point(p2.x, p2.y);
this.absorbRange = absorbRange;
this.redraw();
}
redraw() {
this.clear();
this.lineStyle(1, new Color(this._color));
this.moveTo(this.p1.x, this.p1.y);
this.lineTo(this.p2.x, this.p2.y);
}
tryAbsorb(...objs: DisplayObject[]): boolean {
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
const p = obj.position.clone();
if (linePoint(this.p1, this.p2, p, this.absorbRange, true)) {
const fp = calculateFootPointFromPointToLine(this.p1, this.p2, p);
obj.position.copyFrom(fp);
return true;
}
}
return false;
}
}
/**
*
*/
export class AbsorbableCircle extends Graphics implements AbsorbablePosition {
absorbRange: number;
p0: Point;
radius: number;
_color = '#E77E0E';
constructor(p: IPointData, radius: number, absorbRange = 10) {
super();
this.p0 = new Point(p.x, p.y);
this.radius = radius;
this.absorbRange = absorbRange;
this.redraw();
}
redraw() {
this.clear();
this.lineStyle(1, new Color(this._color));
this.drawCircle(this.p0.x, this.p0.y, this.radius);
}
tryAbsorb(...objs: DisplayObject[]): boolean {
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
const len = distance(
this.p0.x,
this.p0.y,
obj.position.x,
obj.position.y
);
if (
len > this.radius - this.absorbRange &&
len < this.radius + this.absorbRange
) {
// 吸附,计算直线与圆交点,更新对象坐标
const p = calculateIntersectionPointOfCircleAndPoint(
this.p0,
this.radius,
obj.position
);
obj.position.copyFrom(p);
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,102 @@
import { Container, Graphics, IPointData, Point } from 'pixi.js';
import { angleToAxisx } from '../utils';
export interface IDashedLineOptions {
/**
* ,4
*/
length?: number;
/**
* ,0
*/
startSpace?: number;
/**
* ,4
*/
space?: number;
/**
* 线,1
*/
lineWidth?: number;
/**
* 线,
*/
color?: string;
}
interface ICompleteDashedLineOptions extends IDashedLineOptions {
length: number;
startSpace: number;
space: number;
lineWidth: number;
color: string;
}
const DefaultDashedLineOptions: ICompleteDashedLineOptions = {
length: 4,
startSpace: 0,
space: 4,
lineWidth: 1,
color: '#0000ff',
};
export class DashedLine extends Container {
p1: Point;
p2: Point;
_options: ICompleteDashedLineOptions;
constructor(p1: IPointData, p2: IPointData, options?: IDashedLineOptions) {
super();
const config = Object.assign({}, DefaultDashedLineOptions, options);
this._options = config;
this.p1 = new Point(p1.x, p1.y);
this.p2 = new Point(p2.x, p2.y);
this.redraw();
}
setOptions(options: IDashedLineOptions) {
if (options.startSpace != undefined) {
this._options.startSpace = options.startSpace;
}
if (options.length != undefined) {
this._options.length = options.length;
}
if (options.space != undefined) {
this._options.space = options.space;
}
if (options.lineWidth != undefined) {
this._options.lineWidth = options.lineWidth;
}
if (options.color != undefined) {
this._options.color = options.color;
}
this.redraw();
}
redraw() {
this.removeChildren();
const p1 = this.p1;
const p2 = this.p2;
const option = this._options;
const total = Math.pow(
Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2),
0.5
);
let len = option.startSpace;
while (len < total) {
let dashedLen = option.length;
if (len + option.length > total) {
dashedLen = total - len;
}
const line = new Graphics();
line.lineStyle(option.lineWidth, option.color);
line.moveTo(len, 0);
line.lineTo(len + dashedLen, 0);
this.addChild(line);
len = len + dashedLen + option.space;
}
this.pivot.set(0, option.lineWidth / 2);
this.position.set(p1.x, p1.y);
this.angle = angleToAxisx(p1, p2);
}
}

View File

@ -0,0 +1,45 @@
import { Graphics, IPointData } from 'pixi.js';
import { VectorGraphic, VectorGraphicUtil } from './VectorGraphic';
/**
*
*/
export const DraggablePointParam = {
lineWidth: 1,
lineColor: 0x000000,
fillColor: 0xffffff,
radius: 5, // 半径
};
const DraggablePointGraphic = new Graphics();
DraggablePointGraphic.lineStyle(
DraggablePointParam.lineWidth,
DraggablePointParam.lineColor
);
DraggablePointGraphic.beginFill(DraggablePointParam.fillColor);
DraggablePointGraphic.drawCircle(0, 0, DraggablePointParam.radius);
DraggablePointGraphic.endFill();
/**
*
*/
export class DraggablePoint extends Graphics implements VectorGraphic {
scaledListenerOn = false;
/**
*
* @param point
*/
constructor(point: IPointData) {
super(DraggablePointGraphic.geometry);
this.position.copyFrom(point);
this.eventMode = 'static';
this.draggable = true;
this.cursor = 'crosshair';
VectorGraphicUtil.handle(this);
}
updateOnScaled() {
const scaled = this.getAllParentScaled();
const scale = Math.max(scaled.x, scaled.y);
this.scale.set(1 / scale, 1 / scale);
}
}

View File

@ -0,0 +1,44 @@
import { DisplayObject } from 'pixi.js';
export interface VectorGraphic extends DisplayObject {
scaledListenerOn: boolean;
updateOnScaled(): void;
}
export class VectorGraphicUtil {
static handle(obj: VectorGraphic): void {
const vg = obj;
const onScaleChange = function (obj: DisplayObject) {
if (vg.isParent(obj)) {
vg.updateOnScaled();
}
};
const registerScaleChange = function registerScaleChange(
obj: VectorGraphic
): void {
if (!obj.scaledListenerOn) {
obj.scaledListenerOn = true;
obj.getGraphicApp().on('viewport-scaled', onScaleChange);
}
};
const unregisterScaleChange = function unregisterScaleChange(
obj: VectorGraphic
): void {
obj.scaledListenerOn = false;
obj.getGraphicApp().off('viewport-scaled', onScaleChange);
};
obj.onAddToCanvas = function onAddToCanvas() {
obj.updateOnScaled();
registerScaleChange(obj);
};
obj.onRemoveFromCanvas = function onRemoveFromCanvas() {
unregisterScaleChange(obj);
};
obj.on('added', (container) => {
if (container.isInCanvas()) {
obj.onAddToCanvas();
}
});
}
}

View File

@ -0,0 +1,35 @@
import { ICanvas, ITextStyle, Text, TextStyle } from 'pixi.js';
import { VectorGraphic, VectorGraphicUtil } from '.';
/**
* .fontSize
*/
export class VectorText extends Text implements VectorGraphic {
vectorFontSize = 8;
scaled = 1;
scaledListenerOn = false;
constructor(
text?: string | number,
style?: Partial<ITextStyle> | TextStyle,
canvas?: ICanvas
) {
super(text, style, canvas);
VectorGraphicUtil.handle(this);
}
updateOnScaled() {
const scaled = this.getAllParentScaled();
const scale = Math.max(scaled.x, scaled.y);
this.style.fontSize = this.vectorFontSize * scale;
this.scale.set(1 / scale, 1 / scale);
}
/**
*
*/
setVectorFontSize(fontSize: number) {
this.vectorFontSize = fontSize;
this.style.fontSize = fontSize;
}
}

View File

@ -0,0 +1,4 @@
export * from './VectorGraphic';
export * from './VectorText';
export * from './DraggablePoint';
export * from './AbsorbablePosition';

7
src/jl-graphic/index.ts Normal file
View File

@ -0,0 +1,7 @@
export * from './core';
export * from './graphic';
export * from './app';
export * from './operation';
export * from './utils';
export * from './plugins';
export * from './message';

View File

@ -0,0 +1,26 @@
/**
*
*/
export const epsilon = 0.00001;
/**
* 0
* @param v
* @returns
*/
export function isZero(v: number) {
if (Math.abs(v) < epsilon) {
return true;
}
return false;
}
/**
*
* @param f1
* @param f2
* @returns
*/
export function floatEquals(f1: number, f2: number): boolean {
return isZero(f1 - f2);
}

View File

@ -0,0 +1,360 @@
/* eslint-disable @typescript-eslint/no-this-alias */
import { epsilon } from './Constants';
export default class Vector2 {
constructor(values?: [number, number]) {
if (values !== undefined) {
this.xy = values;
}
}
static from(p: { x: number; y: number }): Vector2 {
return new Vector2([p.x, p.y]);
}
private values = new Float32Array(2);
static readonly zero = new Vector2([0, 0]);
static readonly one = new Vector2([1, 1]);
get x(): number {
return this.values[0];
}
set x(value: number) {
this.values[0] = value;
}
get y(): number {
return this.values[1];
}
set y(value: number) {
this.values[1] = value;
}
get xy(): [number, number] {
return [this.values[0], this.values[1]];
}
set xy(values: [number, number]) {
this.values[0] = values[0];
this.values[1] = values[1];
}
at(index: number): number {
return this.values[index];
}
reset(): void {
this.x = 0;
this.y = 0;
}
copy(dest?: Vector2): Vector2 {
if (!dest) {
dest = new Vector2();
}
dest.x = this.x;
dest.y = this.y;
return dest;
}
negate(dest?: Vector2): Vector2 {
if (!dest) {
dest = this;
}
dest.x = -this.x;
dest.y = -this.y;
return dest;
}
equals(vector: Vector2, threshold = epsilon): boolean {
if (Math.abs(this.x - vector.x) > threshold) {
return false;
}
if (Math.abs(this.y - vector.y) > threshold) {
return false;
}
return true;
}
length(): number {
return Math.sqrt(this.squaredLength());
}
squaredLength(): number {
const x = this.x;
const y = this.y;
return x * x + y * y;
}
add(vector: Vector2): Vector2 {
this.x += vector.x;
this.y += vector.y;
return this;
}
subtract(vector: Vector2): Vector2 {
this.x -= vector.x;
this.y -= vector.y;
return this;
}
multiply(vector: Vector2): Vector2 {
this.x *= vector.x;
this.y *= vector.y;
return this;
}
divide(vector: Vector2): Vector2 {
this.x /= vector.x;
this.y /= vector.y;
return this;
}
scale(value: number, dest?: Vector2): Vector2 {
if (!dest) {
dest = this;
}
dest.x *= value;
dest.y *= value;
return dest;
}
normalize(dest?: Vector2): Vector2 {
if (!dest) {
dest = this;
}
let length = this.length();
if (length === 1) {
return this;
}
if (length === 0) {
dest.x = 0;
dest.y = 0;
return dest;
}
length = 1.0 / length;
dest.x *= length;
dest.y *= length;
return dest;
}
// multiplyMat2(matrix: mat2, dest?: Vector2): Vector2 {
// if (!dest) {
// dest = this;
// }
// return matrix.multiplyVec2(this, dest);
// }
// multiplyMat3(matrix: mat3, dest?: Vector2): Vector2 {
// if (!dest) {
// dest = this;
// }
// return matrix.multiplyVec2(this, dest);
// }
// static cross(vector: Vector2, vector2: Vector2, dest?: vec3): vec3 {
// if (!dest) {
// dest = new vec3();
// }
// const x = vector.x;
// const y = vector.y;
// const x2 = vector2.x;
// const y2 = vector2.y;
// const z = x * y2 - y * x2;
// dest.x = 0;
// dest.y = 0;
// dest.z = z;
// return dest;
// }
/**
*
* @param vector
* @param vector2
* @returns
*/
static dot(vector: Vector2, vector2: Vector2): number {
return vector.x * vector2.x + vector.y * vector2.y;
}
/**
*
* @param vector
* @param vector2
* @returns
*/
static distance(vector: Vector2, vector2: Vector2): number {
return Math.sqrt(this.squaredDistance(vector, vector2));
}
/**
*
* @param vector
* @param vector2
* @returns
*/
static squaredDistance(vector: Vector2, vector2: Vector2): number {
const x = vector2.x - vector.x;
const y = vector2.y - vector.y;
return x * x + y * y;
}
/**
* v2->v1的方向的单位向量
* @param v1
* @param v2
* @param dest
* @returns
*/
static direction(v1: Vector2, v2: Vector2, dest?: Vector2): Vector2 {
if (!dest) {
dest = new Vector2();
}
const x = v1.x - v2.x;
const y = v1.y - v2.y;
let length = Math.sqrt(x * x + y * y);
if (length === 0) {
dest.x = 0;
dest.y = 0;
return dest;
}
length = 1 / length;
dest.x = x * length;
dest.y = y * length;
return dest;
}
static mix(
vector: Vector2,
vector2: Vector2,
time: number,
dest?: Vector2
): Vector2 {
if (!dest) {
dest = new Vector2();
}
const x = vector.x;
const y = vector.y;
const x2 = vector2.x;
const y2 = vector2.y;
dest.x = x + time * (x2 - x);
dest.y = y + time * (y2 - y);
return dest;
}
/**
*
* @param vector
* @param vector2
* @param dest
* @returns
*/
static sum(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
if (!dest) {
dest = new Vector2();
}
dest.x = vector.x + vector2.x;
dest.y = vector.y + vector2.y;
return dest;
}
/**
*
* @param vector
* @param vector2
* @param dest
* @returns
*/
static difference(
vector: Vector2,
vector2: Vector2,
dest?: Vector2
): Vector2 {
if (!dest) {
dest = new Vector2();
}
dest.x = vector.x - vector2.x;
dest.y = vector.y - vector2.y;
return dest;
}
/**
*
* @param vector
* @param vector2
* @param dest
* @returns
*/
static product(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
if (!dest) {
dest = new Vector2();
}
dest.x = vector.x * vector2.x;
dest.y = vector.y * vector2.y;
return dest;
}
/**
*
* @param vector
* @param vector2
* @param dest
* @returns
*/
static quotient(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
if (!dest) {
dest = new Vector2();
}
dest.x = vector.x / vector2.x;
dest.y = vector.y / vector2.y;
return dest;
}
}

View File

@ -0,0 +1,4 @@
/// 向量和矩阵代码源自开源代码https://github.com/matthiasferch/tsm
export * from './Constants';
export * from './Vector2';

View File

@ -0,0 +1,215 @@
import {
Client as StompClient,
StompSubscription,
type Frame,
type Message,
type messageCallbackType,
} from '@stomp/stompjs';
import type { GraphicApp } from '../app/JlGraphicApp';
import { GraphicState } from '../core/JlGraphic';
export interface StompCliOption {
wsUrl: string; // websocket url
token: string; // 认证token
reconnectDelay?: number; // 重连延时默认3秒
heartbeatIncoming?: number; // 服务端过来的心跳间隔默认30秒
heartbeatOutgoing?: number; // 到服务端的心跳间隔默认30秒
}
const DefaultStompOption: StompCliOption = {
wsUrl: '',
token: '',
reconnectDelay: 3000,
heartbeatIncoming: 30000,
heartbeatOutgoing: 30000,
};
export class StompCli {
private static enabled = false;
private static options: StompCliOption;
private static client: StompClient;
private static appMsgBroker: AppWsMsgBroker[] = [];
private static connected = false;
static new(options: StompCliOption) {
if (StompCli.enabled) {
// 以及启用
return;
// throw new Error('websocket 已连接若确实需要重新连接请先断开StompCli.close再重新StompCli.new')
}
StompCli.enabled = true;
StompCli.options = Object.assign({}, DefaultStompOption, options);
StompCli.client = new StompClient({
brokerURL: StompCli.options.wsUrl,
connectHeaders: {
Authorization: StompCli.options.token,
// Authorization: ''
},
// debug: (str) => {
// console.log(str)
// }
reconnectDelay: StompCli.options.reconnectDelay,
heartbeatIncoming: StompCli.options.heartbeatIncoming,
heartbeatOutgoing: StompCli.options.heartbeatOutgoing,
});
StompCli.client.onConnect = () => {
// console.log('websocket连接(重连),重新订阅', StompCli.appMsgBroker.length)
StompCli.connected = true;
StompCli.appMsgBroker.forEach((broker) => {
broker.resubscribe();
});
};
StompCli.client.onStompError = (frame: Frame) => {
console.error(
'Stomp收到error消息,可能是认证失败(暂时没有判断具体错误类型,后需添加判断),关闭Stomp客户端',
frame
);
StompCli.close();
};
StompCli.client.onDisconnect = (frame: Frame) => {
console.log('Stomp 断开连接', frame);
StompCli.connected = false;
// StompCli.appMsgBroker.forEach(broker => {
// broker.close();
// });
};
StompCli.client.onWebSocketClose = (evt: CloseEvent) => {
console.log('websocket 关闭', evt);
StompCli.connected = false;
};
// websocket错误处理
StompCli.client.onWebSocketError = (err: Event) => {
console.log('websocket错误', err);
// StompCli.appMsgBroker.forEach(broker => {
// broker.unsbuscribeAll();
// });
};
StompCli.client.activate();
}
static isEnabled(): boolean {
return StompCli.enabled;
}
static isConnected(): boolean {
return StompCli.client && StompCli.client.connected;
}
static trySubscribe(
destination: string,
handler: messageCallbackType
): StompSubscription | undefined {
if (StompCli.isConnected()) {
return StompCli.client.subscribe(destination, handler, {
id: destination,
});
}
return undefined;
}
static registerAppMsgBroker(broker: AppWsMsgBroker) {
StompCli.appMsgBroker.push(broker);
}
static removeAppMsgBroker(broker: AppWsMsgBroker) {
const index = StompCli.appMsgBroker.findIndex((mb) => mb == broker);
if (index >= 0) {
StompCli.appMsgBroker.splice(index, 1);
}
}
static hasAppMsgBroker(): boolean {
return StompCli.appMsgBroker.length > 0;
}
/**
* websocket连接
*/
static close() {
StompCli.enabled = false;
StompCli.connected = false;
if (StompCli.client) {
StompCli.client.deactivate();
}
}
}
// 状态订阅消息转换器
export type MessageConverter = (message: Uint8Array) => GraphicState[];
// 图形app状态订阅
export class AppStateSubscription {
destination: string;
messageConverter: MessageConverter;
subscription?: StompSubscription; // 订阅成功对象,用于取消订阅
constructor(
destination: string,
messageConverter: MessageConverter,
subscription?: StompSubscription
) {
this.destination = destination;
this.messageConverter = messageConverter;
this.subscription = subscription;
}
}
/**
* APP的websocket消息代理
*/
export class AppWsMsgBroker {
app: GraphicApp;
subscriptions: Map<string, AppStateSubscription> = new Map<
string,
AppStateSubscription
>();
constructor(app: GraphicApp) {
this.app = app;
StompCli.registerAppMsgBroker(this);
}
subscribe(sub: AppStateSubscription) {
this.unsbuscribe(sub.destination); // 先尝试取消之前订阅
sub.subscription = StompCli.trySubscribe(
sub.destination,
(message: Message) => {
const graphicStates = sub.messageConverter(message.binaryBody);
this.app.handleGraphicStates(graphicStates);
}
);
// console.log('代理订阅结果', sub.subscription)
this.subscriptions.set(sub.destination, sub);
}
resubscribe() {
this.subscriptions.forEach((record) => {
this.subscribe(record);
});
}
unsbuscribe(destination: string) {
const oldSub = this.subscriptions.get(destination);
if (oldSub) {
if (oldSub.subscription && StompCli.isConnected()) {
oldSub.subscription.unsubscribe();
}
oldSub.subscription = undefined;
}
}
unsbuscribeAll() {
this.subscriptions.forEach((record) => {
this.unsbuscribe(record.destination);
});
}
/**
* Stomp客户端移除此消息代理
*/
close() {
StompCli.removeAppMsgBroker(this);
this.unsbuscribeAll();
}
}

View File

@ -0,0 +1 @@
export * from './WsMsgBroker';

View File

@ -0,0 +1,99 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { GraphicApp } from '../app/JlGraphicApp';
import { JlGraphic } from '../core/JlGraphic';
/**
*
*/
export abstract class JlOperation {
type: string; // 操作类型/名称
app: GraphicApp;
obj?: any; // 操作对象
data?: any; // 操作数据
description?: string = ''; // 操作描述
constructor(app: GraphicApp, type: string) {
this.app = app;
this.type = type;
}
undo1(): void {
const updates = this.undo();
if (updates) {
this.app.updateSelected(...updates);
}
}
redo1(): void {
const updates = this.redo();
if (updates) {
this.app.updateSelected(...updates);
}
}
abstract undo(): JlGraphic[] | void;
abstract redo(): JlGraphic[] | void;
}
/**
*
*/
export class OperationRecord {
undoStack: JlOperation[] = [];
redoStack: JlOperation[] = [];
private maxLen: number;
constructor(maxLen = 100) {
this.maxLen = maxLen;
}
public get hasUndo(): boolean {
return this.undoStack.length > 0;
}
public get hasRedo(): boolean {
return this.redoStack.length > 0;
}
setMaxLen(v: number) {
this.maxLen = v;
const len = this.undoStack.length;
if (len > v) {
const removeCount = len - v;
this.undoStack.splice(0, removeCount);
}
}
/**
*
* @param op
*/
record(op: JlOperation) {
if (this.undoStack.length >= this.maxLen) {
this.undoStack.shift();
}
// console.log('operation record', op)
this.undoStack.push(op);
this.redoStack.splice(0, this.redoStack.length);
}
/**
*
*/
undo() {
const op = this.undoStack.pop();
// console.log('撤销', op);
if (op) {
op.undo1();
this.redoStack.push(op);
}
}
/**
*
*/
redo() {
const op = this.redoStack.pop();
// console.log('重做', op);
if (op) {
op.redo1();
this.undoStack.push(op);
}
}
}

View File

@ -0,0 +1 @@
export * from './JlOperation';

View File

@ -0,0 +1,75 @@
import { GraphicApp } from '../app';
import { GraphicAnimation, JlGraphic } from '../core';
/**
*
*/
export class AnimationManager {
app: GraphicApp;
graphicAnimationMap: Map<string, Map<string, GraphicAnimation>>;
constructor(app: GraphicApp) {
this.app = app;
this.graphicAnimationMap = new Map<string, Map<string, GraphicAnimation>>();
// 动画控制
app.app.ticker.add((dt: number) => {
this.graphicAnimationMap.forEach((map) => {
map.forEach((animation) => {
if (animation.running) {
animation.run(dt);
}
});
});
});
}
static new(app: GraphicApp): AnimationManager {
return new AnimationManager(app);
}
/**
* map
* @param graphic
* @returns
*/
animationMap(graphic: JlGraphic): Map<string, GraphicAnimation> {
let map = this.graphicAnimationMap.get(graphic.id);
if (!map) {
map = new Map<string, GraphicAnimation>();
this.graphicAnimationMap.set(graphic.id, map);
}
return map;
}
/**
*
* @param graphic
* @param animation
*/
registerAnimation(graphic: JlGraphic, animation: GraphicAnimation) {
this.animationMap(graphic).set(animation.name, animation);
}
/**
*
* @param graphic
* @param name
*/
unregisterAnimation(graphic: JlGraphic, name: string) {
this.animationMap(graphic).delete(name);
}
/**
*
* @param graphic
*/
unregisterGraphicAnimations(graphic: JlGraphic) {
this.animationMap(graphic).clear();
}
/**
*
* @param graphic
* @param name
* @returns
*/
animation(graphic: JlGraphic, name: string): GraphicAnimation | undefined {
return this.animationMap(graphic).get(name);
}
}

View File

@ -0,0 +1,329 @@
import { DisplayObject, FederatedMouseEvent, Graphics, Point } from 'pixi.js';
import { GraphicApp, JlCanvas } from '../app';
import { JlGraphic } from '../core';
import {
AppDragEvent,
AppInteractionPlugin,
ViewportMovePlugin,
} from './InteractionPlugin';
type GraphicSelectFilter = (graphic: JlGraphic) => boolean;
export interface IMouseToolOptions {
/**
* ,
*/
boxSelect?: boolean;
/**
* (),
*/
viewportDrag?: boolean;
/**
* ,
*/
wheelZoom?: boolean;
/**
*
*/
selectFilter?: GraphicSelectFilter;
}
class CompleteMouseToolOptions implements IMouseToolOptions {
boxSelect: boolean;
viewportDrag: boolean;
wheelZoom: boolean;
selectFilter?: GraphicSelectFilter | undefined;
constructor() {
this.boxSelect = true;
this.viewportDrag = true;
this.wheelZoom = true;
}
update(options: IMouseToolOptions) {
if (options.boxSelect != undefined) {
this.boxSelect = options.boxSelect;
}
if (options.viewportDrag != undefined) {
this.viewportDrag = options.viewportDrag;
}
if (options.wheelZoom != undefined) {
this.wheelZoom = options.wheelZoom;
}
this.selectFilter = options.selectFilter;
}
}
const DefaultSelectToolOptions: CompleteMouseToolOptions =
new CompleteMouseToolOptions();
/**
*
*/
export class CommonMouseTool extends AppInteractionPlugin {
static Name = 'mouse-tool';
static SelectBox = '__select_box';
options: CompleteMouseToolOptions;
box: Graphics;
leftDownTarget: DisplayObject | null = null;
drag = false;
graphicSelect = false;
rightTarget: DisplayObject | null = null;
constructor(graphicApp: GraphicApp) {
super(CommonMouseTool.Name, graphicApp);
this.options = DefaultSelectToolOptions;
this.box = new Graphics();
this.box.name = CommonMouseTool.SelectBox;
this.box.visible = false;
this.app.canvas.addAssistantAppends(this.box);
graphicApp.on('options-update', (options) => {
if (options.mouseToolOptions) {
this.options.update(options.mouseToolOptions);
if (this.isActive()) {
this.pause();
this.resume();
}
}
});
}
static new(app: GraphicApp) {
return new CommonMouseTool(app);
}
bind(): void {
const canvas = this.app.canvas;
canvas.on('mousedown', this.onMouseDown, this);
canvas.on('mouseup', this.onMouseUp, this);
this.app.on('drag_op_start', this.onDragStart, this);
this.app.on('drag_op_move', this.onDragMove, this);
this.app.on('drag_op_end', this.onDragEnd, this);
if (this.options.viewportDrag) {
this.app.viewport.drag({
mouseButtons: 'right',
});
canvas.on('rightdown', this.setCursor, this);
canvas.on('rightup', this.resumeCursor, this);
canvas.on('rightupoutside', this.resumeCursor, this);
}
if (this.options.wheelZoom) {
this.app.viewport.wheel({
percent: 0.01,
});
}
}
unbind(): void {
const canvas = this.app.canvas;
// 确保所有事件取消监听
canvas.off('mousedown', this.onMouseDown, this);
canvas.off('mouseup', this.onMouseUp, this);
this.app.off('drag_op_start', this.onDragStart, this);
this.app.off('drag_op_move', this.onDragMove, this);
this.app.off('drag_op_end', this.onDragEnd, this);
this.app.viewport.plugins.remove('drag');
canvas.off('rightdown', this.setCursor, this);
canvas.off('rightup', this.resumeCursor, this);
canvas.off('rightupoutside', this.resumeCursor, this);
this.app.viewport.plugins.remove('wheel');
this.clearCache();
}
onDragStart(event: AppDragEvent) {
// console.log(
// 'start',
// `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}`
// );
if (this.boxSelect && event.target.isCanvas() && event.isLeftButton) {
this.box.visible = true;
this.app.interactionPlugin(ViewportMovePlugin.Name).resume();
}
this.drag = true;
}
onDragMove(event: AppDragEvent) {
// console.log(
// 'moving',
// `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}`
// );
if (this.boxSelect && event.target.isCanvas()) {
this.boxSelectDraw(event.start, event.end);
}
}
onDragEnd(event: AppDragEvent) {
// console.log(
// 'end',
// `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}`
// );
if (this.boxSelect && event.target.isCanvas() && event.isLeftButton) {
this.boxSelectDraw(event.start, event.end);
this.boxSelectGraphicCheck();
this.app.interactionPlugin(ViewportMovePlugin.Name).pause();
this.box.clear();
this.box.visible = false;
}
}
setCursor(e: FederatedMouseEvent) {
this.rightTarget = e.target as DisplayObject;
if (e.target instanceof JlCanvas && this.app.app.view.style) {
this.app.app.view.style.cursor = 'grab';
}
}
resumeCursor() {
if (
this.rightTarget &&
this.rightTarget instanceof JlCanvas &&
this.app.app.view.style
) {
this.app.app.view.style.cursor = 'inherit';
}
this.rightTarget = null;
}
onMouseDown(e: FederatedMouseEvent) {
this.leftDownTarget = e.target as DisplayObject;
this.graphicSelect = false;
// 图形
const graphic = this.leftDownTarget.getGraphic();
if (graphic) {
const app = this.app;
// 图形选中
if (!e.ctrlKey && !graphic.selected && graphic.selectable) {
app.updateSelected(graphic);
graphic.childEdit = false;
this.graphicSelect = true;
} else if (
!e.ctrlKey &&
graphic.selected &&
graphic.childEdit &&
this.leftDownTarget.isGraphicChild()
) {
if (this.leftDownTarget.selectable) {
graphic.setChildSelected(this.leftDownTarget);
} else {
graphic.exitChildEdit();
}
}
}
}
/**
*
* @param e
*/
onMouseUp(e: FederatedMouseEvent) {
const app = this.app;
if (!this.drag) {
const target = e.target as DisplayObject;
const graphic = (e.target as DisplayObject).getGraphic();
if (
graphic &&
graphic.selected &&
!this.graphicSelect &&
app.selectedGraphics.length == 1 &&
target === this.leftDownTarget &&
target.isGraphicChild() &&
target.selectable
) {
graphic.childEdit = true;
}
if (e.ctrlKey) {
// 多选
if (graphic) {
if (graphic.childEdit && target === this.leftDownTarget) {
graphic.invertChildSelected(target);
} else {
graphic.invertSelected();
app.fireSelectedChange(graphic);
}
}
} else {
// 非多选
if (e.target instanceof JlCanvas) {
this.app.updateSelected();
} else {
if (
graphic &&
graphic.childEdit &&
app.selectedGraphics.length === 1 &&
target === this.leftDownTarget
) {
graphic.setChildSelected(target);
}
}
}
// 多个图形选中,退出子元素编辑模式
const selecteds = this.app.selectedGraphics;
if (selecteds.length > 1) {
selecteds.forEach((g) => g.exitChildEdit());
}
}
this.clearCache();
}
/**
*
*/
clearCache() {
this.drag = false;
this.leftDownTarget = null;
}
public get boxSelect(): boolean | undefined {
return this.options.boxSelect;
}
public get selectFilter(): GraphicSelectFilter | undefined {
return this.options.selectFilter;
}
/**
*
*/
boxSelectDraw(start: Point, end: Point): void {
if (!this.drag) return;
// 绘制框选矩形框
this.box.clear();
this.box.lineStyle({ width: 1, color: 0x000000 });
const dsx = end.x - start.x;
const dsy = end.y - start.y;
let { x, y } = start;
if (dsx < 0) {
x += dsx;
}
if (dsy < 0) {
y += dsy;
}
const width = Math.abs(dsx);
const height = Math.abs(dsy);
this.box.drawRect(x, y, width, height);
}
/**
*
* @returns
*/
boxSelectGraphicCheck(): void {
if (!this.drag) return;
// 遍历筛选
const boxRect = this.box.getLocalBounds();
const app = this.app;
const selects: JlGraphic[] = [];
app.queryStore.getAllGraphics().forEach((g) => {
if (!this.selectFilter || this.selectFilter(g)) {
// 选择过滤器
if (g.boxIntersectCheck(boxRect)) {
selects.push(g);
}
}
});
app.updateSelected(...selects);
}
}

View File

@ -0,0 +1,141 @@
import { Container, FederatedPointerEvent, Point } from 'pixi.js';
import { GraphicApp, GraphicCreateOperation } from '../app';
import { JlGraphic } from '../core';
import { KeyListener } from './KeyboardPlugin';
export class GraphicCopyPlugin {
container: Container;
app: GraphicApp;
keyListeners: KeyListener[];
copys: JlGraphic[];
start?: Point;
running = false;
moveLimit?: 'x' | 'y';
constructor(app: GraphicApp) {
this.app = app;
this.container = new Container();
this.copys = [];
this.keyListeners = [];
this.keyListeners.push(
new KeyListener({
// ESC 用于取消复制操作
value: 'Escape',
global: true,
// combinations: [CombinationKey.Ctrl],
onPress: () => {
this.cancle();
},
}),
new KeyListener({
// X 限制只能在x轴移动
value: 'KeyX',
global: true,
// combinations: [CombinationKey.Ctrl],
onPress: () => {
this.updateMoveLimit('x');
},
}),
new KeyListener({
// Y 限制只能在y轴移动
value: 'KeyY',
global: true,
// combinations: [CombinationKey.Ctrl],
onPress: () => {
this.updateMoveLimit('y');
},
})
);
}
updateMoveLimit(limit?: 'x' | 'y'): void {
if (this.moveLimit === limit) {
this.moveLimit = undefined;
} else {
this.moveLimit = limit;
}
}
init(): void {
if (this.running) return;
if (this.app.selectedGraphics.length === 0) {
throw new Error('没有选中图形,复制取消');
}
this.running = true;
this.copys = [];
this.container.alpha = 0.5;
this.app.canvas.addChild(this.container);
const app = this.app;
this.app.selectedGraphics.forEach((g) => {
const template = app.getGraphicTemplatesByType(g.type);
const clone = template.clone(g);
this.copys.push(clone);
this.container.position.set(0, 0);
this.container.addChild(clone);
clone.repaint();
});
this.app.canvas.on('mousemove', this.onPointerMove, this);
this.app.canvas.on('mouseup', this.onFinish, this);
this.app.canvas.on('rightup', this.cancle, this);
this.keyListeners.forEach((kl) => {
this.app.addKeyboardListener(kl);
});
}
clear(): void {
this.running = false;
this.start = undefined;
this.moveLimit = undefined;
this.copys = [];
this.container.removeChildren();
this.app.canvas.removeChild(this.container);
this.app.canvas.off('mousemove', this.onPointerMove, this);
this.app.canvas.off('mouseup', this.onFinish, this);
this.app.canvas.off('rightup', this.cancle, this);
this.keyListeners.forEach((kl) => {
this.app.removeKeyboardListener(kl);
});
}
onPointerMove(e: FederatedPointerEvent): void {
const cp = this.app.toCanvasCoordinates(e.global);
if (!this.start) {
this.start = cp;
} else {
if (this.moveLimit === 'x') {
const dx = cp.x - this.start.x;
this.container.position.x = dx;
this.container.position.y = 0;
} else if (this.moveLimit === 'y') {
const dy = cp.y - this.start.y;
this.container.position.x = 0;
this.container.position.y = dy;
} else {
const dx = cp.x - this.start.x;
const dy = cp.y - this.start.y;
this.container.position.x = dx;
this.container.position.y = dy;
}
}
}
onFinish(): void {
console.log('复制确认');
// 将图形添加到app
this.copys.forEach((g) => {
g.position.x += this.container.position.x;
g.position.y += this.container.position.y;
});
this.app.addGraphics(...this.copys);
// 创建图形对象操作记录
this.app.opRecord.record(new GraphicCreateOperation(this.app, this.copys));
this.app.detectRelations();
this.app.updateSelected(...this.copys);
this.clear();
}
cancle(): void {
console.log('复制操作取消');
this.app.canvas.removeChild(this.container);
this.clear();
}
}

View File

@ -0,0 +1,498 @@
import {
Color,
Container,
DisplayObject,
FederatedMouseEvent,
Graphics,
IDestroyOptions,
IPointData,
Point,
} from 'pixi.js';
import { JlGraphic } from '../core';
import { DraggablePoint } from '../graphic';
import { ContextMenu } from '../ui/ContextMenu';
import { MenuItemOptions, MenuOptions } from '../ui/Menu';
import {
calculateFootPointFromPointToLine,
calculateMirrorPoint,
assertBezierPoints,
distance2,
linePoint,
pointPolygon,
} from '../utils';
import { GraphicTransformEvent, ShiftData } from './GraphicTransformPlugin';
export abstract class GraphicEditPlugin<
DO extends DisplayObject = DisplayObject
> extends Container {
graphic: DO;
constructor(g: DO) {
super();
this.graphic = g;
this.zIndex = 2;
this.sortableChildren = true;
this.graphic.on('transformstart', this.hideAll, this);
this.graphic.on('transformend', this.showAll, this);
this.graphic.on('repaint', this.showAll, this);
}
destroy(options?: boolean | IDestroyOptions | undefined): void {
this.graphic.off('transformstart', this.hideAll, this);
this.graphic.off('transformend', this.showAll, this);
this.graphic.off('repaint', this.showAll, this);
super.destroy(options);
}
abstract updateEditedPointsPosition(): void;
hideAll() {
this.visible = false;
}
showAll() {
this.updateEditedPointsPosition();
this.visible = true;
}
}
export const addWaypointConfig: MenuItemOptions = {
name: '添加路径点',
};
export const removeWaypointConfig: MenuItemOptions = {
name: '移除路径点',
};
export const clearWaypointsConfig: MenuItemOptions = {
name: '清除所有路径点',
};
const menuOptions: MenuOptions = {
name: '图形编辑点菜单',
groups: [
{
items: [removeWaypointConfig, clearWaypointsConfig],
},
],
};
const EditPointContextMenu = ContextMenu.init(menuOptions);
export interface ILineGraphic extends JlGraphic {
get linePoints(): IPointData[];
set linePoints(points: IPointData[]);
}
export abstract class LineEditPlugin extends GraphicEditPlugin<ILineGraphic> {
linePoints: IPointData[];
editedPoints: DraggablePoint[] = [];
constructor(g: ILineGraphic) {
super(g);
this.linePoints = g.linePoints;
this.graphic.on('dataupdate', this.reset, this);
}
destroy(options?: boolean | IDestroyOptions | undefined): void {
this.graphic.off('dataupdate', this.reset, this);
super.destroy(options);
}
reset(): void {
this.linePoints = this.graphic.linePoints;
this.removeChildren();
this.editedPoints.splice(0, this.editedPoints.length);
this.initEditPoints();
}
abstract initEditPoints(): void;
}
export function getWaypointRangeIndex(
points: IPointData[],
curve: boolean,
p: IPointData
): { start: number; end: number } {
let start = 0;
let end = 0;
if (!curve) {
// 直线
for (let i = 1; i < points.length; i++) {
const sp = points[i - 1];
const ep = points[i];
const fp = calculateFootPointFromPointToLine(sp, ep, p);
if (linePoint(sp, ep, fp, 1, true)) {
start = i - 1;
end = i;
break;
}
}
} else {
// 贝塞尔曲线
assertBezierPoints(points);
for (let i = 0; i < points.length - 3; i += 3) {
const p1 = points[i];
const cp1 = points[i + 1];
const cp2 = points[i + 2];
const p2 = points[i + 3];
if (pointPolygon(p, [p1, cp1, cp2, p2], 1)) {
start = i;
end = i + 3;
}
}
}
return { start, end };
}
export type onEditPointCreate = (
g: ILineGraphic,
dp: DraggablePoint,
index: number
) => void;
export interface IEditPointOptions {
/**
*
*/
onEditPointCreate?: onEditPointCreate;
}
/**
* 线(线)
*/
export class PolylineEditPlugin extends LineEditPlugin {
static Name = 'line_points_edit';
options: IEditPointOptions;
constructor(g: ILineGraphic, options?: IEditPointOptions) {
super(g);
this.options = Object.assign({}, options);
this.name = PolylineEditPlugin.Name;
this.initEditPoints();
}
initEditPoints() {
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
for (let i = 0; i < cps.length; i++) {
const p = cps[i];
const dp = new DraggablePoint(p);
dp.on('rightclick', (e: FederatedMouseEvent) => {
// dp.getGraphicApp().openContextMenu(EditPointContextMenu.DefaultMenu);
// 路径中的点
const app = dp.getGraphicApp();
app.registerMenu(EditPointContextMenu);
removeWaypointConfig.handler = () => {
removeLineWayPoint(this.graphic, i);
};
clearWaypointsConfig.handler = () => {
clearWayPoint(this.graphic, false);
};
EditPointContextMenu.open(e.global);
});
dp.on('transforming', () => {
const tlp = this.graphic.canvasToLocalPoint(dp.position);
const cp = this.linePoints[i];
cp.x = tlp.x;
cp.y = tlp.y;
this.graphic.repaint();
});
if (this.options.onEditPointCreate) {
this.options.onEditPointCreate(this.graphic, dp, i);
}
this.editedPoints.push(dp);
}
this.addChild(...this.editedPoints);
}
updateEditedPointsPosition() {
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
if (cps.length === this.editedPoints.length) {
for (let i = 0; i < cps.length; i++) {
const cp = cps[i];
this.editedPoints[i].position.copyFrom(cp);
}
}
}
}
export interface BezierCurveEditPointOptions extends IEditPointOptions {
// 曲线控制点辅助连线颜色
auxiliaryLineColor?: string;
// // 拖拽点颜色
// pointColor?: string;
// 连接点处是否平滑(点左右控制点是否在一条直线),默认true
smooth?: boolean;
// 控制点是否完全对称(对称必平滑)
symmetry?: boolean;
}
export interface ICompleteBezierCurveEditPointOptions
extends BezierCurveEditPointOptions {
smooth: boolean;
}
export function addWayPoint(
graphic: ILineGraphic,
curve: boolean,
start: number,
end: number,
p: IPointData
) {
if (!curve) {
addLineWayPoint(graphic, start, end, p);
} else {
addBezierWayPoint(graphic, start, end, p);
}
}
export function addLineWayPoint(
graphic: ILineGraphic,
start: number,
end: number,
p: IPointData
) {
const linePoints = graphic.linePoints;
const points = linePoints.slice(0, start + 1);
points.push(new Point(p.x, p.y));
points.push(...linePoints.slice(end));
graphic.linePoints = points;
}
function assertBezierWayPoint(i: number) {
const c = i % 3;
if (c !== 0) {
throw new Error(`i=${i}的点不是路径点`);
}
}
export function addBezierWayPoint(
graphic: ILineGraphic,
start: number,
end: number,
p: IPointData
) {
if (start === end) {
throw new Error('开始结束点不能一致');
}
assertBezierWayPoint(start);
assertBezierWayPoint(end);
const linePoints = graphic.linePoints;
const points = linePoints.slice(0, start + 2);
const ap = new Point(p.x, p.y);
points.push(ap.clone(), ap.clone(), ap.clone());
points.push(...linePoints.slice(end - 1));
graphic.linePoints = points;
}
export function removeWayPoint(
graphic: ILineGraphic,
curve: boolean,
i: number
) {
if (!curve) {
removeLineWayPoint(graphic, i);
} else {
removeBezierWayPoint(graphic, i);
}
}
export function removeLineWayPoint(graphic: ILineGraphic, i: number) {
const linePoints = graphic.linePoints;
if (linePoints.length > 2) {
const points = linePoints.slice(0, i);
points.push(...linePoints.slice(i + 1));
graphic.linePoints = points;
}
}
export function removeBezierWayPoint(graphic: ILineGraphic, i: number) {
let points;
const linePoints = graphic.linePoints;
const c = i % 3;
if (c !== 0) {
throw new Error(`i=${i}的点${linePoints[i]}不是路径点`);
}
if (i === 0) {
// 第一个点
if (linePoints.length > 4) {
points = linePoints.slice(3);
} else {
console.error('不能移除:剩余点数不足');
}
} else if (i === linePoints.length - 1) {
// 最后一个点
if (linePoints.length > 4) {
points = linePoints.slice(0, linePoints.length - 3);
} else {
console.error('无法移除:剩余点数不足');
}
} else {
// 中间点
points = linePoints.slice(0, i - 1);
points.push(...linePoints.slice(i + 2));
}
if (points) {
graphic.linePoints = points;
}
}
/**
* (),线线
* @param graphic
* @param curve
*/
export function clearWayPoint(graphic: ILineGraphic, curve: boolean) {
const linePoints = graphic.linePoints;
if (!curve) {
if (linePoints.length > 2) {
const points = linePoints.slice(0, 1);
points.push(...linePoints.slice(-1));
graphic.linePoints = points;
}
} else {
if (linePoints.length > 4) {
const points = linePoints.slice(0, 2);
points.push(...linePoints.slice(-2));
graphic.linePoints = points;
}
}
}
/**
* 线
*/
export class BezierCurveEditPlugin extends LineEditPlugin {
static Name = 'bezier_curve_points_edit';
options: ICompleteBezierCurveEditPointOptions;
// 曲线控制点辅助线
auxiliaryLines: Graphics[] = [];
constructor(g: ILineGraphic, options?: BezierCurveEditPointOptions) {
super(g);
this.options = Object.assign({}, { smooth: true }, options);
this.name = BezierCurveEditPlugin.Name;
this.initEditPoints();
}
reset(): void {
this.auxiliaryLines.splice(0, this.auxiliaryLines.length);
super.reset();
}
initEditPoints() {
// console.log('initEditPoints');
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
for (let i = 0; i < cps.length; i++) {
const p = cps[i];
const dp = new DraggablePoint(p);
const startOrEnd = i == 0 || i == cps.length - 1;
const c = i % 3;
if (c === 1) {
// 前一路径点的控制点
dp.zIndex = 2;
const fp = cps[i - 1];
const line = new Graphics();
this.drawAuxiliaryLine(line, fp, p);
this.auxiliaryLines.push(line);
} else if (c === 2) {
// 后一路径点的控制点
dp.zIndex = 3;
const np = cps[i + 1];
const line = new Graphics();
this.drawAuxiliaryLine(line, p, np);
this.auxiliaryLines.push(line);
}
dp.on('rightclick', (e: FederatedMouseEvent) => {
// dp.getGraphicApp().openContextMenu(EditPointContextMenu.DefaultMenu);
if (c === 0) {
// 路径中的点
const app = dp.getGraphicApp();
app.registerMenu(EditPointContextMenu);
removeWaypointConfig.handler = () => {
removeBezierWayPoint(this.graphic, i);
};
clearWaypointsConfig.handler = () => {
clearWayPoint(this.graphic, true);
};
EditPointContextMenu.open(e.global);
}
});
dp.on('transforming', (e: GraphicTransformEvent) => {
const tlp = this.graphic.canvasToLocalPoint(dp.position);
const cp = this.linePoints[i];
cp.x = tlp.x;
cp.y = tlp.y;
if (this.options.smooth || this.options.symmetry) {
if (c === 0 && !startOrEnd) {
const shiftData = e.getData<ShiftData>();
const fp = this.linePoints[i - 1];
const np = this.linePoints[i + 1];
fp.x = fp.x + shiftData.dx;
fp.y = fp.y + shiftData.dy;
np.x = np.x + shiftData.dx;
np.y = np.y + shiftData.dy;
} else if (c === 1 && i !== 1) {
const bp = this.linePoints[i - 1];
const fp2 = this.linePoints[i - 2];
let mp;
if (this.options.symmetry) {
mp = calculateMirrorPoint(bp, cp);
} else {
const distance = distance2(bp, fp2);
mp = calculateMirrorPoint(bp, cp, distance);
}
fp2.x = mp.x;
fp2.y = mp.y;
} else if (c === 2 && i !== cps.length - 2) {
const bp = this.linePoints[i + 1];
const np2 = this.linePoints[i + 2];
let mp;
if (this.options.symmetry) {
mp = calculateMirrorPoint(bp, cp);
} else {
const distance = distance2(bp, np2);
mp = calculateMirrorPoint(bp, cp, distance);
}
np2.x = mp.x;
np2.y = mp.y;
}
}
this.graphic.repaint();
});
if (this.options.onEditPointCreate) {
this.options.onEditPointCreate(this.graphic, dp, i);
}
this.editedPoints.push(dp);
if (this.auxiliaryLines.length > 0) {
this.addChild(...this.auxiliaryLines);
}
}
this.addChild(...this.editedPoints);
}
drawAuxiliaryLine(line: Graphics, p1: IPointData, p2: IPointData) {
line.clear();
if (this.options.auxiliaryLineColor) {
line.lineStyle(1, new Color(this.options.auxiliaryLineColor));
} else {
line.lineStyle(1, new Color('blue'));
}
line.moveTo(p1.x, p1.y);
line.lineTo(p2.x, p2.y);
}
updateEditedPointsPosition() {
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
if (cps.length === this.editedPoints.length) {
for (let i = 0; i < cps.length; i++) {
const cp = cps[i];
this.editedPoints[i].position.copyFrom(cp);
const c = i % 3;
const d = Math.floor(i / 3);
if (c === 1 || c === 2) {
const li = d * 2 + c - 1;
const line = this.auxiliaryLines[li];
if (c === 1) {
const fp = cps[i - 1];
this.drawAuxiliaryLine(line, fp, cp);
} else {
const np = cps[i + 1];
this.drawAuxiliaryLine(line, cp, np);
}
}
}
}
}
}

View File

@ -0,0 +1,823 @@
import {
Container,
DisplayObject,
Graphics,
IDestroyOptions,
Point,
Polygon,
} from 'pixi.js';
import {
AppDragEvent,
InteractionPluginBase,
InteractionPluginType,
KeyListener,
} from '.';
import { GraphicApp } from '../app';
import { JlGraphic } from '../core';
import { AbsorbablePosition } from '../graphic';
import { DraggablePoint } from '../graphic/DraggablePoint';
import {
angleToAxisx,
calculateLineMidpoint,
convertRectangleToPolygonPoints,
distance,
recursiveChildren,
} from '../utils';
export class ShiftData {
/**
*
*/
startPosition: Point;
/**
*
*/
lastPosition?: Point;
/**
*
*/
currentPosition?: Point;
constructor(
startPosition: Point,
currentPosition?: Point,
lastPosition?: Point
) {
this.startPosition = startPosition;
this.lastPosition = lastPosition;
this.currentPosition = currentPosition;
}
static new(
startPosition: Point,
currentPosition?: Point,
lastPosition?: Point
) {
return new ShiftData(startPosition, currentPosition, lastPosition);
}
public get dx(): number {
if (!this.lastPosition || !this.currentPosition) {
throw new Error('错误的位移数据或阶段');
}
return this.currentPosition.x - this.lastPosition.x;
}
public get dy(): number {
if (!this.lastPosition || !this.currentPosition) {
throw new Error('错误的位移数据或阶段');
}
return this.currentPosition.y - this.lastPosition.y;
}
public get dsx(): number {
if (!this.currentPosition) {
throw new Error('错误的位移数据或阶段');
}
return this.currentPosition.x - this.startPosition.x;
}
public get dsy(): number {
if (!this.currentPosition) {
throw new Error('错误的位移数据或阶段');
}
return this.currentPosition.y - this.startPosition.y;
}
}
export class ScaleData {
start: Point;
current?: Point;
last?: Point;
constructor(start: Point, current?: Point, last?: Point) {
this.start = start;
this.current = current;
this.last = last;
}
static new(start: Point, current?: Point, last?: Point) {
return new ScaleData(start, current, last);
}
}
export type TransformData = ShiftData | null;
/**
*
*/
export class GraphicTransformEvent {
/**
*
*/
target: DisplayObject;
type: 'shift' | 'rotate' | 'scale' | 'skew';
data: TransformData;
constructor(
target: DisplayObject,
type: 'shift' | 'rotate' | 'scale' | 'skew',
data: TransformData
) {
this.target = target;
this.type = type;
this.data = data;
}
getData<D extends TransformData>(): D {
return this.data as D;
}
static shift(target: DisplayObject, data: ShiftData) {
return new GraphicTransformEvent(target, 'shift', data);
}
static scale(target: DisplayObject) {
return new GraphicTransformEvent(target, 'scale', null);
}
static rotate(target: DisplayObject) {
return new GraphicTransformEvent(target, 'rotate', null);
}
static skew(target: DisplayObject) {
return new GraphicTransformEvent(target, 'skew', null);
}
isShift(): boolean {
return this.type === 'shift';
}
isRotate(): boolean {
return this.type === 'rotate';
}
isScale(): boolean {
return this.type === 'scale';
}
isSkew(): boolean {
return this.type === 'skew';
}
}
export class GraphicTransformPlugin extends InteractionPluginBase {
static Name = '__graphic_transform_plugin';
/**
*
*/
absorbablePositions?: AbsorbablePosition[];
apContainer: Container;
static AbsorbablePosisiontsName = '__AbsorbablePosisionts';
constructor(app: GraphicApp) {
super(app, GraphicTransformPlugin.Name, InteractionPluginType.Other);
this.apContainer = new Container();
this.apContainer.name = GraphicTransformPlugin.AbsorbablePosisiontsName;
this.app.canvas.addAssistantAppend(this.apContainer);
app.on('options-update', (options) => {
if (options.absorbablePositions) {
this.absorbablePositions = options.absorbablePositions;
}
});
}
static new(app: GraphicApp) {
return new GraphicTransformPlugin(app);
}
bind(): void {
this.app.on('drag_op_start', this.onDragStart, this);
this.app.on('drag_op_move', this.onDragMove, this);
this.app.on('drag_op_end', this.onDragEnd, this);
this.app.on('graphicselectedchange', this.onGraphicSelectedChange, this);
this.app.on(
'graphicchildselectedchange',
this.onGraphicChildSelectedChange,
this
);
}
unbind(): void {
this.app.off('drag_op_start', this.onDragStart, this);
this.app.off('drag_op_move', this.onDragMove, this);
this.app.off('drag_op_end', this.onDragEnd, this);
this.app.off('graphicselectedchange', this.onGraphicSelectedChange, this);
this.app.off(
'graphicchildselectedchange',
this.onGraphicChildSelectedChange,
this
);
}
getDraggedTargets(e: AppDragEvent): DisplayObject[] {
const targets: DisplayObject[] = [];
if (e.target.isGraphicChild() && e.target.selected && e.target.draggable) {
const graphic = e.target.getGraphic() as JlGraphic;
// 图形子元素
recursiveChildren(graphic, (child) => {
if (child.selected && child.draggable) {
targets.push(child);
}
});
} else if (
(e.target.isGraphic() || e.target.isGraphicChild()) &&
e.target.getGraphic()?.draggable
) {
// 图形对象
targets.push(...this.app.selectedGraphics);
} else if (e.target.draggable) {
targets.push(e.target);
}
return targets;
}
onDragStart(e: AppDragEvent) {
if (!e.target.isCanvas() && e.isLeftButton) {
const targets: DisplayObject[] = this.getDraggedTargets(e);
if (targets.length > 0) {
targets.forEach((target) => {
target.shiftStartPoint = target.position.clone();
target.emit(
'transformstart',
GraphicTransformEvent.shift(
target,
ShiftData.new(target.shiftStartPoint)
)
);
});
// 显示吸附图形
if (this.absorbablePositions && this.absorbablePositions.length > 0) {
this.apContainer.removeChildren();
this.apContainer.addChild(...this.absorbablePositions);
}
}
}
}
onDragMove(e: AppDragEvent) {
if (!e.target.isCanvas() && e.isLeftButton) {
const targets: DisplayObject[] = this.getDraggedTargets(e);
if (targets.length > 0) {
// 处理位移
targets.forEach((target) => {
if (target.shiftStartPoint) {
target.shiftLastPoint = target.position.clone();
target.position.set(
target.shiftStartPoint.x + e.dsx,
target.shiftStartPoint.y + e.dsy
);
}
});
// 处理吸附
if (this.absorbablePositions) {
for (let i = 0; i < this.absorbablePositions.length; i++) {
const ap = this.absorbablePositions[i];
if (ap.tryAbsorb(...targets)) {
break;
}
}
}
// 事件发布
targets.forEach((target) => {
if (target.shiftStartPoint && target.shiftLastPoint) {
target.emit(
'transforming',
GraphicTransformEvent.shift(
target,
ShiftData.new(
target.shiftStartPoint,
target.position.clone(),
target.shiftLastPoint
)
)
);
}
});
}
}
}
onDragEnd(e: AppDragEvent) {
if (!e.target.isCanvas() && e.isLeftButton) {
const targets: DisplayObject[] = this.getDraggedTargets(e);
targets.forEach((target) => {
if (target.shiftStartPoint) {
target.emit(
'transformend',
GraphicTransformEvent.shift(
target,
ShiftData.new(target.shiftStartPoint, target.position.clone())
)
);
}
target.shiftStartPoint = null;
});
}
this.clearCache();
}
/**
*
*/
clearCache() {
// 移除吸附图形
this.absorbablePositions = [];
this.apContainer.removeChildren();
}
onGraphicSelectedChange(g: DisplayObject, selected: boolean) {
let br = g.getAssistantAppend<BoundsGraphic>(BoundsGraphic.Name);
if (!br) {
// 绘制辅助包围框
br = new BoundsGraphic(g);
}
if (selected) {
if (br) {
br.redraw();
br.visible = true;
}
} else {
if (br) {
br.visible = false;
}
}
if (g.scalable) {
// 缩放点
let sp = g.getAssistantAppend<TransformPoints>(TransformPoints.Name);
if (!sp) {
sp = new TransformPoints(g);
}
if (selected) {
sp.update();
sp.visible = true;
} else {
sp.visible = false;
}
}
}
onGraphicChildSelectedChange(child: DisplayObject, selected: boolean) {
let br = child.getAssistantAppend<BoundsGraphic>(BoundsGraphic.Name);
if (!br) {
// 绘制辅助包围框
br = new BoundsGraphic(child);
}
if (selected) {
br.redraw();
br.visible = true;
} else {
br.visible = false;
}
}
}
/**
*
*/
export class TransformPoints extends Container {
static Name = 'transformPoints';
static MinLength = 40;
static LeftTopName = 'lt-scale-point';
static TopName = 't-scale-point';
static RightTopName = 'rt-scale-point';
static RightName = 'r-scale-point';
static RightBottomName = 'rb-scale-point';
static BottomName = 'b-scale-point';
static LeftBottomName = 'lb-scale-point';
static LeftName = 'l-scale-point';
static RotateName = 'rotate-point';
obj: DisplayObject;
ltScalePoint: DraggablePoint;
ltLocal: Point = new Point();
tScalePoint: DraggablePoint;
tLocal: Point = new Point();
tCanvas: Point = new Point();
rtScalePoint: DraggablePoint;
rtLocal: Point = new Point();
rScalePoint: DraggablePoint;
rLocal: Point = new Point();
rbScalePoint: DraggablePoint;
rbLocal: Point = new Point();
bScalePoint: DraggablePoint;
bLocal: Point = new Point();
lbScalePoint: DraggablePoint;
lbLocal: Point = new Point();
lScalePoint: DraggablePoint;
lLocal: Point = new Point();
originScale: Point = new Point();
scalePivot: Point = new Point();
/**
*
*/
rotatePoint: DraggablePoint;
/**
*
*/
rotatePivot: Point;
/**
*
*/
rotateLastPoint: Point;
/**
*
*/
startAngle = 0;
/**
*
*/
angleStep = 1;
/**
*
*/
rotateAngleStepKeyListeners: KeyListener[] = [];
constructor(obj: DisplayObject) {
super();
this.obj = obj;
this.name = TransformPoints.Name;
// 创建缩放拖拽点
this.ltScalePoint = new DraggablePoint(new Point());
this.ltScalePoint.name = TransformPoints.LeftTopName;
this.addChild(this.ltScalePoint);
this.tScalePoint = new DraggablePoint(new Point());
this.tScalePoint.name = TransformPoints.TopName;
this.addChild(this.tScalePoint);
this.rtScalePoint = new DraggablePoint(new Point());
this.rtScalePoint.name = TransformPoints.RightTopName;
this.addChild(this.rtScalePoint);
this.rScalePoint = new DraggablePoint(new Point());
this.rScalePoint.name = TransformPoints.RightName;
this.addChild(this.rScalePoint);
this.rbScalePoint = new DraggablePoint(new Point());
this.rbScalePoint.name = TransformPoints.RightBottomName;
this.addChild(this.rbScalePoint);
this.bScalePoint = new DraggablePoint(new Point());
this.bScalePoint.name = TransformPoints.BottomName;
this.addChild(this.bScalePoint);
this.lbScalePoint = new DraggablePoint(new Point());
this.lbScalePoint.name = TransformPoints.LeftBottomName;
this.addChild(this.lbScalePoint);
this.lScalePoint = new DraggablePoint(new Point());
this.lScalePoint.name = TransformPoints.LeftName;
this.addChild(this.lScalePoint);
this.obj.on('transformstart', this.onObjTransformStart, this);
this.obj.on('transformend', this.onObjTransformEnd, this);
this.obj.on('repaint', this.onGraphicRepaint, this);
this.children.forEach((dp) => {
dp.on('transformstart', this.onScaleDragStart, this);
dp.on('transforming', this.onScaleDragMove, this);
dp.on('transformend', this.onScaleDragEnd, this);
});
// 创建旋转拖拽点
this.rotatePoint = new DraggablePoint(new Point());
this.addChild(this.rotatePoint);
this.rotatePoint.on('transformstart', this.onRotateStart, this);
this.rotatePoint.on('transforming', this.onRotateMove, this);
this.rotatePoint.on('transformend', this.onRotateEnd, this);
this.rotatePivot = new Point();
this.rotateLastPoint = new Point();
// 初始化旋转角度修改键盘监听器
for (let i = 1; i < 10; i++) {
this.rotateAngleStepKeyListeners.push(
KeyListener.create({
value: '' + i,
onPress: () => {
// console.log('修改角度step');
this.angleStep = i;
},
})
);
}
this.obj.addAssistantAppend(this);
}
onObjTransformStart() {
this.visible = false;
}
onObjTransformEnd() {
this.update();
this.visible = true;
}
onGraphicRepaint() {
if (this.visible) {
this.update();
}
}
/**
*
* @param de
*/
onRotateStart(de: GraphicTransformEvent) {
this.hideAll();
const assistantPoint = this.obj.localToCanvasPoint(this.obj.pivot);
this.rotatePivot.copyFrom(assistantPoint);
this.rotateLastPoint.copyFrom(de.target.position);
this.startAngle = this.obj.angle;
const app = this.obj.getGraphicApp();
this.rotateAngleStepKeyListeners.forEach((listener) =>
app.addKeyboardListener(listener)
);
this.obj.emit('transformstart', GraphicTransformEvent.rotate(this.obj));
// app.emit('transformstart', app.selectedGraphics);
}
/**
*
* @param de
*/
onRotateMove(de: GraphicTransformEvent) {
// 旋转角度计算逻辑取锚点y负方向一点作为旋转点求旋转点和锚点所形成的直线与x轴角度此角度+90°即为最终旋转角度再将旋转角度限制到(-180,180]之间
let angle = angleToAxisx(this.rotatePivot, de.target.position);
angle = Math.floor(angle / this.angleStep) * this.angleStep;
angle = (angle + 90) % 360;
if (angle > 180) {
angle = angle - 360;
}
this.obj.angle = angle;
// this.obj.emit('rotatemove', this.obj);
}
/**
*
* @param de
*/
onRotateEnd() {
this.showAll();
this.rotateAngleStepKeyListeners.forEach((listener) =>
this.obj.getGraphicApp().removeKeyboardListener(listener)
);
this.obj.emit('transformend', GraphicTransformEvent.rotate(this.obj));
}
/**
*
*/
onScaleDragStart() {
this.hideAll();
const points = convertRectangleToPolygonPoints(this.obj.getLocalBounds());
const p0 = points[0];
const p1 = points[1];
const p2 = points[2];
const p3 = points[3];
this.scalePivot = this.obj.pivot.clone();
this.ltLocal.copyFrom(p0);
this.tCanvas.copyFrom(
this.obj.localToCanvasPoint(calculateLineMidpoint(p0, p1))
);
this.tLocal.copyFrom(calculateLineMidpoint(p0, p1));
this.rtLocal.copyFrom(p1);
this.rLocal.copyFrom(calculateLineMidpoint(p1, p2));
this.rbLocal.copyFrom(p2);
this.bLocal.copyFrom(calculateLineMidpoint(p2, p3));
this.lbLocal.copyFrom(p3);
this.lLocal.copyFrom(calculateLineMidpoint(p0, p3));
this.originScale = this.obj.scale.clone();
this.obj.emit('transformstart', GraphicTransformEvent.scale(this.obj));
}
onScaleDragMove(e: GraphicTransformEvent) {
// 缩放计算逻辑共8个方向缩放点根据所拖拽的方向:
// 1,计算缩放为1时的此点在拖拽开始时的位置到锚点x、y距离
// 2,计算拖拽点的当前位置到锚点的x、y方向距离
// PS:以上两个计算都是在local也就是图形对象本地坐标系
// 用当前距离除以原始距离即为缩放比例
const defaultScale = new Point(1, 1);
let originWidth = 0;
let originHeight = 0;
let width = 0;
let height = 0;
this.obj.scale.copyFrom(defaultScale);
const point = this.obj.toLocal(
e.target.parent.localToScreenPoint(e.target.position)
);
if (e.target === this.ltScalePoint) {
// 左上角
originWidth = Math.abs(this.ltLocal.x - this.scalePivot.x);
originHeight = Math.abs(this.ltLocal.y - this.scalePivot.y);
width = Math.abs(point.x - this.scalePivot.x);
height = Math.abs(point.y - this.scalePivot.y);
} else if (e.target == this.tScalePoint) {
// 上
originHeight = Math.abs(this.tLocal.y - this.scalePivot.y);
height = Math.abs(point.y - this.scalePivot.y);
} else if (e.target == this.rtScalePoint) {
// 右上
originWidth = Math.abs(this.rtLocal.x - this.scalePivot.x);
originHeight = Math.abs(this.rtLocal.y - this.scalePivot.y);
width = Math.abs(point.x - this.scalePivot.x);
height = Math.abs(point.y - this.scalePivot.y);
} else if (e.target == this.rScalePoint) {
// 右
originWidth = Math.abs(this.rLocal.x - this.scalePivot.x);
width = Math.abs(point.x - this.scalePivot.x);
} else if (e.target == this.rbScalePoint) {
// 右下
originWidth = Math.abs(this.rbLocal.x - this.scalePivot.x);
originHeight = Math.abs(this.rbLocal.y - this.scalePivot.y);
width = Math.abs(point.x - this.scalePivot.x);
height = Math.abs(point.y - this.scalePivot.y);
} else if (e.target == this.bScalePoint) {
// 下
originHeight = Math.abs(this.bLocal.y - this.scalePivot.y);
height = Math.abs(point.y - this.scalePivot.y);
} else if (e.target == this.lbScalePoint) {
// 左下
originWidth = Math.abs(this.lbLocal.x - this.scalePivot.x);
originHeight = Math.abs(this.lbLocal.y - this.scalePivot.y);
width = Math.abs(point.x - this.scalePivot.x);
height = Math.abs(point.y - this.scalePivot.y);
} else {
// 左
originWidth = Math.abs(this.lLocal.x - this.scalePivot.x);
width = Math.abs(point.x - this.scalePivot.x);
}
// 计算缩放比例,并根据是否保持纵横比两种情况进行缩放处理
const sx = originWidth == 0 ? this.originScale.x : width / originWidth;
const sy = originHeight == 0 ? this.originScale.y : height / originHeight;
// console.log(originWidth, originHeight, width, height, sx, sy);
if (this.obj.keepAspectRatio) {
let max = Math.max(sx, sy);
if (originWidth == 0) {
max = sy;
} else if (originHeight == 0) {
max = sx;
}
this.obj.scale.set(max, max);
} else {
this.obj.scale.x = sx;
this.obj.scale.y = sy;
}
}
onScaleDragEnd() {
this.showAll();
this.obj.emit('transformend', GraphicTransformEvent.scale(this.obj));
}
hideOthers(dg: DisplayObject) {
this.children.forEach((child) => {
if (child.name !== dg.name) {
child.visible = false;
}
});
}
hideAll() {
this.children.forEach((child) => (child.visible = false));
}
showAll() {
this.update();
this.children.forEach((child) => (child.visible = true));
}
getObjBounds(): { width: number; height: number } {
const points = this.obj.localBoundsToCanvasPoints();
const p0 = points[0];
const p1 = points[1];
const p3 = points[3];
const width = distance(p0.x, p0.y, p1.x, p1.y);
const height = distance(p0.x, p0.y, p3.x, p3.y);
return { width, height };
}
/**
* cursor
* @returns
*/
update() {
if (this.obj.scalable) {
this.updateScalePoints();
}
if (this.obj.rotatable) {
this.updateRotatePoint();
}
}
updateRotatePoint() {
const rect = this.obj.getLocalBounds();
const lp = this.obj.pivot.clone();
const dy = 10 / this.obj.scale.y;
lp.y = rect.y - dy;
const p = this.obj.localToCanvasPoint(lp);
this.rotatePoint.position.copyFrom(p);
}
updateScalePoints() {
const points = this.obj.localBoundsToCanvasPoints();
this.ltScalePoint.position.copyFrom(points[0]);
this.tScalePoint.position.copyFrom(
calculateLineMidpoint(points[0], points[1])
);
this.rtScalePoint.position.copyFrom(points[1]);
this.rScalePoint.position.copyFrom(
calculateLineMidpoint(points[1], points[2])
);
this.rbScalePoint.position.copyFrom(points[2]);
this.bScalePoint.position.copyFrom(
calculateLineMidpoint(points[2], points[3])
);
this.lbScalePoint.position.copyFrom(points[3]);
this.lScalePoint.position.copyFrom(
calculateLineMidpoint(points[3], points[0])
);
const angle = this.obj.worldAngle;
const angle360 = (360 + angle) % 360;
if (
(angle >= -22.5 && angle <= 22.5) ||
(angle360 >= 180 - 22.5 && angle360 <= 180 + 22.5)
) {
this.ltScalePoint.cursor = 'nw-resize';
this.tScalePoint.cursor = 'n-resize';
this.rtScalePoint.cursor = 'ne-resize';
this.rScalePoint.cursor = 'e-resize';
this.rbScalePoint.cursor = 'se-resize';
this.bScalePoint.cursor = 's-resize';
this.lbScalePoint.cursor = 'sw-resize';
this.lScalePoint.cursor = 'w-resize';
} else if (
(angle >= 22.5 && angle <= 67.5) ||
(angle360 >= 180 + 22.5 && angle360 <= 180 + 67.5)
) {
this.ltScalePoint.cursor = 'n-resize';
this.tScalePoint.cursor = 'ne-resize';
this.rtScalePoint.cursor = 'e-resize';
this.rScalePoint.cursor = 'se-resize';
this.rbScalePoint.cursor = 's-resize';
this.bScalePoint.cursor = 'sw-resize';
this.lbScalePoint.cursor = 'w-resize';
this.lScalePoint.cursor = 'nw-resize';
} else if (
(angle >= 67.5 && angle < 112.5) ||
(angle360 >= 180 + 67.5 && angle360 <= 180 + 112.5)
) {
this.ltScalePoint.cursor = 'ne-resize';
this.tScalePoint.cursor = 'e-resize';
this.rtScalePoint.cursor = 'se-resize';
this.rScalePoint.cursor = 's-resize';
this.rbScalePoint.cursor = 'sw-resize';
this.bScalePoint.cursor = 'w-resize';
this.lbScalePoint.cursor = 'nw-resize';
this.lScalePoint.cursor = 'n-resize';
} else {
this.ltScalePoint.cursor = 'e-resize';
this.tScalePoint.cursor = 'se-resize';
this.rtScalePoint.cursor = 's-resize';
this.rScalePoint.cursor = 'sw-resize';
this.rbScalePoint.cursor = 'w-resize';
this.bScalePoint.cursor = 'nw-resize';
this.lbScalePoint.cursor = 'n-resize';
this.lScalePoint.cursor = 'ne-resize';
}
}
}
/**
* 使
*/
export class BoundsGraphic extends Graphics {
static Name = '_BoundsRect';
static BoundsLineStyle = {
width: 1,
color: 0x29b6f2,
alpha: 1,
};
obj: DisplayObject;
constructor(graphic: DisplayObject) {
super();
this.obj = graphic;
this.name = BoundsGraphic.Name;
this.visible = false;
this.obj.on('transformstart', this.onObjTransformStart, this);
this.obj.on('transformend', this.onObjTransformEnd, this);
this.obj.on('repaint', this.onGraphicRepaint, this);
graphic.addAssistantAppend(this);
}
onObjTransformStart(): void {
this.visible = false;
}
onObjTransformEnd(): void {
this.redraw();
this.visible = true;
}
onGraphicRepaint(): void {
if (this.visible) {
this.redraw();
this.visible = true;
}
}
destroy(options?: boolean | IDestroyOptions | undefined): void {
if (this.obj.isGraphic()) {
this.obj.off('repaint', this.onGraphicRepaint, this);
}
super.destroy(options);
}
redraw() {
this.visible = false; // 屏蔽包围框本身
const bounds = new Polygon(this.obj.localBoundsToCanvasPoints());
this.clear().lineStyle(BoundsGraphic.BoundsLineStyle).drawShape(bounds);
}
}

View File

@ -0,0 +1,477 @@
import {
DisplayObject,
FederatedMouseEvent,
FederatedPointerEvent,
Point,
} from 'pixi.js';
import { GraphicApp, IGraphicAppConfig } from '../app/JlGraphicApp';
import { JlGraphic } from '../core/JlGraphic';
export enum InteractionPluginType {
App = 'app',
Graphic = 'graphic',
Other = 'other',
}
/**
*
*/
export interface InteractionPlugin {
readonly _type: string;
name: string; // 唯一标识
app: GraphicApp;
/**
*
*/
resume(): void;
/**
*
*/
pause(): void;
/**
*
*/
isActive(): boolean;
isAppPlugin(): boolean;
isOtherPlugin(): boolean;
isGraphicPlugin(): boolean;
}
export abstract class InteractionPluginBase implements InteractionPlugin {
readonly _type: string;
name: string; // 唯一标识
app: GraphicApp;
_pause: boolean;
constructor(app: GraphicApp, name: string, type: string) {
this._type = type;
this.app = app;
this.name = name;
this._pause = true;
app.registerInteractionPlugin(this);
}
/**
*
*/
resume(): void {
this.bind();
this._pause = false;
this.app.emit('interaction-plugin-resume', this);
}
/**
*
*/
pause(): void {
this.unbind();
this._pause = true;
this.app.emit('interaction-plugin-pause', this);
}
abstract bind(): void;
abstract unbind(): void;
/**
*
*/
isActive(): boolean {
return !this._pause;
}
isGraphicPlugin(): boolean {
return this._type === InteractionPluginType.Graphic;
}
isAppPlugin(): boolean {
return this._type === InteractionPluginType.App;
}
isOtherPlugin(): boolean {
return this._type === InteractionPluginType.Other;
}
}
export abstract class OtherInteractionPlugin extends InteractionPluginBase {
constructor(app: GraphicApp, name: string) {
super(app, name, InteractionPluginType.Other);
}
}
export class AppDragEvent {
app: GraphicApp;
type: 'start' | 'move' | 'end';
target: DisplayObject;
original: FederatedPointerEvent;
start: Point;
constructor(
app: GraphicApp,
type: 'start' | 'move' | 'end',
target: DisplayObject,
original: FederatedPointerEvent,
start: Point
) {
this.app = app;
this.type = type;
this.target = target;
this.original = original;
this.start = start;
}
public get isMouse(): boolean {
return this.original.pointerType === 'mouse';
}
public get isLeftButton(): boolean {
return (
this.isMouse &&
((this.original.button === -1 && this.original.buttons === 1) ||
(this.original.button === 0 && this.original.buttons === 0))
);
}
public get isRightButton(): boolean {
return (
this.isMouse &&
((this.original.button === -1 && this.original.buttons === 2) ||
(this.original.button === 2 && this.original.buttons === 0))
);
}
public get isMiddleButton(): boolean {
return (
this.isMouse &&
((this.original.button === -1 && this.original.buttons === 4) ||
(this.original.button === 1 && this.original.buttons === 0))
);
}
public get isTouch(): boolean {
return this.original.pointerType === 'touch';
}
public get end(): Point {
return this.app.toCanvasCoordinates(this.original.global);
}
public get dx(): number {
const move = this.original.movement;
return move.x / this.app.viewport.scaled;
}
public get dy(): number {
const move = this.original.movement;
return move.y / this.app.viewport.scaled;
}
public get dsx(): number {
return this.end.x - this.start.x;
}
public get dsy(): number {
return this.end.y - this.start.y;
}
}
/**
*
*/
export class DragPlugin extends OtherInteractionPlugin {
static Name = '__drag_operation_plugin';
private threshold = 3;
target: DisplayObject | null = null;
start: Point | null = null;
startClientPoint: Point | null = null;
drag = false;
constructor(app: GraphicApp) {
super(app, DragPlugin.Name);
app.on('options-update', (options: IGraphicAppConfig) => {
if (options.threshold !== undefined) {
this.threshold = options.threshold;
}
});
}
static new(app: GraphicApp) {
return new DragPlugin(app);
}
bind(): void {
const canvas = this.app.canvas;
canvas.on('pointerdown', this.onPointerDown, this);
}
unbind(): void {
const canvas = this.app.canvas;
canvas.off('pointerdown', this.onPointerDown, this);
canvas.off('pointerup', this.onPointerUp, this);
canvas.off('pointerupoutside', this.onPointerUp, this);
}
onPointerDown(e: FederatedPointerEvent) {
this.target = e.target as DisplayObject;
this.start = this.app.toCanvasCoordinates(e.global);
this.startClientPoint = e.global.clone();
const canvas = this.app.canvas;
canvas.on('pointermove', this.onPointerMove, this);
canvas.on('pointerup', this.onPointerUp, this);
canvas.on('pointerupoutside', this.onPointerUp, this);
}
onPointerMove(e: FederatedPointerEvent) {
if (this.start && this.startClientPoint) {
const current = e.global;
const sgp = this.startClientPoint;
const dragStart =
Math.abs(current.x - sgp.x) > this.threshold ||
Math.abs(current.y - sgp.y) > this.threshold;
if (this.target && this.start && !this.drag && dragStart) {
this.app.emit(
'drag_op_start',
new AppDragEvent(this.app, 'start', this.target, e, this.start)
);
this.drag = true;
}
// drag移动处理
if (this.target && this.drag && this.start) {
// console.log('drag move', e.movement);
this.app.emit(
'drag_op_move',
new AppDragEvent(this.app, 'move', this.target, e, this.start)
);
}
}
}
onPointerUp(e: FederatedPointerEvent) {
if (this.target && this.drag && this.start) {
// console.log('drag end');
this.app.emit(
'drag_op_end',
new AppDragEvent(this.app, 'end', this.target, e, this.start)
);
} else if (this.target && this.start && !this.drag) {
// this.target.emit('click', this.target);
const ade = new AppDragEvent(this.app, 'end', this.target, e, this.start);
const graphic = this.target.getGraphic();
if (ade.isRightButton) {
this.target.emit('_rightclick', e);
if (graphic != null) {
graphic.emit('_rightclick', e);
}
} else if (ade.isLeftButton) {
this.target.emit('_leftclick', e);
if (graphic != null) {
graphic.emit('_leftclick', e);
}
}
}
const canvas = this.app.canvas;
canvas.off('mousemove', this.onPointerMove, this);
canvas.off('mouseup', this.onPointerUp, this);
canvas.off('mouseupoutside', this.onPointerUp, this);
this.clearCache();
}
/**
*
*/
clearCache() {
this.drag = false;
this.start = null;
this.startClientPoint = null;
this.target = null;
}
}
/**
*
*/
export class ViewportMovePlugin extends OtherInteractionPlugin {
static Name = '__viewport_move_plugin';
static MoveInterval = 20; // 移动间隔单位ms
static TriggerRange = 100; // 边界触发范围,单位px
static DefaultMoveSpeed = 200 / ViewportMovePlugin.MoveInterval; // 默认移动速度
moveHandler: NodeJS.Timeout | null = null;
moveSpeedx = 0;
moveSpeedy = 0;
constructor(app: GraphicApp) {
super(app, ViewportMovePlugin.Name);
}
static new(app: GraphicApp): ViewportMovePlugin {
return new ViewportMovePlugin(app);
}
pause(): void {
super.pause();
this.stopMove();
}
bind(): void {
this.app.canvas.on('pointermove', this.viewportMove, this);
}
unbind(): void {
this.app.canvas.off('pointermove', this.viewportMove, this);
}
startMove(moveSpeedx: number, moveSpeedy: number) {
this.moveSpeedx = moveSpeedx;
this.moveSpeedy = moveSpeedy;
if (this.moveHandler == null) {
const viewport = this.app.viewport;
this.moveHandler = setInterval(() => {
viewport.moveCorner(
viewport.corner.x + this.moveSpeedx,
viewport.corner.y + this.moveSpeedy
);
}, ViewportMovePlugin.MoveInterval);
}
}
stopMove() {
if (this.moveHandler != null) {
clearInterval(this.moveHandler);
this.moveHandler = null;
this.app.canvas.cursor = 'auto';
}
}
private calculateBoundaryMoveSpeed(sp: Point): {
moveSpeedx: number;
moveSpeedy: number;
} {
let moveSpeedx = 0;
let moveSpeedy = 0;
const range = ViewportMovePlugin.TriggerRange;
const viewport = this.app.viewport;
if (sp.x < range) {
moveSpeedx = this.calculateMoveSpeed(sp.x - range);
} else if (sp.x > viewport.screenWidth - range) {
moveSpeedx = this.calculateMoveSpeed(sp.x + range - viewport.screenWidth);
} else {
moveSpeedx = 0;
}
if (sp.y < range) {
moveSpeedy = this.calculateMoveSpeed(sp.y - range);
} else if (sp.y > viewport.screenHeight - range) {
moveSpeedy = this.calculateMoveSpeed(
sp.y + range - viewport.screenHeight
);
} else {
moveSpeedy = 0;
}
return { moveSpeedx, moveSpeedy };
}
calculateMoveSpeed(dd: number): number {
return (
(dd / ViewportMovePlugin.TriggerRange) *
ViewportMovePlugin.DefaultMoveSpeed
);
}
viewportMove(e: FederatedMouseEvent) {
const sp = e.global;
const { moveSpeedx, moveSpeedy } = this.calculateBoundaryMoveSpeed(sp);
if (moveSpeedx == 0 && moveSpeedy == 0) {
this.app.canvas.cursor = 'auto';
this.stopMove();
} else {
this.app.canvas.cursor = 'grab';
this.startMove(moveSpeedx, moveSpeedy);
}
}
}
/**
*
*/
export abstract class AppInteractionPlugin extends InteractionPluginBase {
constructor(name: string, app: GraphicApp) {
super(app, name, InteractionPluginType.App);
}
/**
* app交互插件同时只能生效一个
*/
resume(): void {
this.app.pauseAppInteractionPlugins();
super.resume();
}
}
/**
* ,
*/
export abstract class GraphicInteractionPlugin<G extends JlGraphic>
implements InteractionPlugin
{
readonly _type = InteractionPluginType.Graphic;
app: GraphicApp;
name: string; // 唯一标识
_pause: boolean;
constructor(name: string, app: GraphicApp) {
this.app = app;
this.name = name;
this._pause = true;
app.registerInteractionPlugin(this);
this.resume();
// 新增的图形对象绑定
this.app.on('graphicstored', (g) => {
if (this.isActive()) {
this.binds(this.filter(g));
}
});
this.app.on('graphicdeleted', (g) => {
if (this.isActive()) {
this.unbinds(this.filter(g));
}
});
}
isActive(): boolean {
return !this._pause;
}
isAppPlugin(): boolean {
return false;
}
isOtherPlugin(): boolean {
return false;
}
isGraphicPlugin(): boolean {
return true;
}
resume(): void {
const list = this.filter(...this.app.queryStore.getAllGraphics());
this.binds(list);
this._pause = false;
this.app.emit('interaction-plugin-resume', this);
}
pause(): void {
const list = this.filter(...this.app.queryStore.getAllGraphics());
this.unbinds(list);
this._pause = true;
this.app.emit('interaction-plugin-pause', this);
}
/**
*
*/
abstract filter(...grahpics: JlGraphic[]): G[] | undefined;
binds(list?: G[]): void {
if (list) {
list.forEach((g) => this.bind(g));
}
}
unbinds(list?: G[]): void {
if (list) {
list.forEach((g) => this.unbind(g));
}
}
/**
*
* @param g
*/
abstract bind(g: G): void;
/**
*
* @param g
*/
abstract unbind(g: G): void;
}

View File

@ -0,0 +1,351 @@
import { GraphicApp } from '../app/JlGraphicApp';
let target: Node | undefined;
export class GlobalKeyboardHelper {
appKeyboardPluginMap: JlGraphicAppKeyboardPlugin[] = [];
constructor() {
window.onkeydown = (e: KeyboardEvent) => {
this.appKeyboardPluginMap.forEach((plugin) => {
const listenerMap = plugin.getKeyListener(e);
listenerMap?.forEach((listener) => {
if (listener.global) {
listener.press(e, plugin.app);
}
});
});
if (e.ctrlKey) {
if (e.code == 'KeyS') {
// 屏蔽全局Ctrl+S保存操作
// console.log('屏蔽全局Ctrl+S')
return false;
}
}
if (target && target.nodeName == 'CANVAS') {
// 事件的目标是画布时,屏蔽总的键盘操作操作
if (e.ctrlKey) {
if (e.code == 'KeyA' || e.code == 'KeyS') {
// 屏蔽Canvas上的Ctrl+A、Ctrl+S操作
return false;
}
}
}
return true;
};
window.onkeyup = (e: KeyboardEvent) => {
this.appKeyboardPluginMap.forEach((plugin) => {
const listenerMap = plugin.getKeyListener(e);
listenerMap?.forEach((listener) => {
if (listener.global) {
listener.release(e, plugin.app);
}
});
});
};
}
registerGAKPlugin(plugin: JlGraphicAppKeyboardPlugin) {
if (!this.appKeyboardPluginMap.find((pg) => pg == plugin)) {
this.appKeyboardPluginMap.push(plugin);
}
}
removeGAKPlugin(plugin: JlGraphicAppKeyboardPlugin) {
const index = this.appKeyboardPluginMap.findIndex((pg) => pg == plugin);
if (index >= 0) {
this.appKeyboardPluginMap.splice(index, 1);
}
}
}
const GlobalKeyboardPlugin = new GlobalKeyboardHelper();
export class JlGraphicAppKeyboardPlugin {
app: GraphicApp;
/**
* Map<key.code|key.key|key.keyCode, Map<KeyListener.identifier, KeyListener>>
*/
keyListenerMap: Map<number | string, Map<string, KeyListener>> = new Map<
number | string,
Map<string, KeyListener>
>(); // 键值监听map
keyListenerStackMap: Map<string, KeyListener[]> = new Map<
string,
KeyListener[]
>(); // 键值监听栈(多次注册相同的监听会把之前注册的监听器入栈,移除最新的监听会从栈中弹出一个作为指定事件监听处理器)
constructor(app: GraphicApp) {
this.app = app;
GlobalKeyboardPlugin.registerGAKPlugin(this);
const onMouseUpdateTarget = (e: MouseEvent) => {
const node = e.target as Node;
target = node;
// console.log('Mousedown Event', node.nodeName, node.nodeType, node.nodeValue)
};
const keydownHandle = (e: KeyboardEvent) => {
console.debug(e.key, e.code, e.keyCode);
if (target && target == this.app.dom.getElementsByTagName('canvas')[0]) {
const listenerMap = this.getKeyListener(e);
listenerMap?.forEach((listener) => {
if (!listener.global) {
listener.press(e, this.app);
}
});
}
};
const keyupHandle = (e: KeyboardEvent) => {
if (target && target == this.app.dom.getElementsByTagName('canvas')[0]) {
const listenerMap = this.getKeyListener(e);
listenerMap?.forEach((listener) => {
if (!listener.global) {
listener.release(e, this.app);
}
});
}
};
document.addEventListener('mousedown', onMouseUpdateTarget, false);
document.addEventListener('keydown', keydownHandle, false);
document.addEventListener('keyup', keyupHandle, false);
this.app.on('destroy', () => {
document.removeEventListener('mousedown', onMouseUpdateTarget, false);
document.removeEventListener('keydown', keydownHandle, false);
document.removeEventListener('keyup', keyupHandle, false);
});
}
private getOrInit(key: string | number): Map<string, KeyListener> {
let map = this.keyListenerMap.get(key);
if (map === undefined) {
map = new Map<string, KeyListener>();
this.keyListenerMap.set(key, map);
}
return map;
}
private getOrInitStack(key: string): KeyListener[] {
let stack = this.keyListenerStackMap.get(key);
if (stack === undefined) {
stack = [];
this.keyListenerStackMap.set(key, stack);
}
return stack;
}
/**
*
* @param keyListener
*/
addKeyListener(keyListener: KeyListener) {
const map = this.getOrInit(keyListener.value);
// 查询是否有旧的监听,若有入栈
const old = map.get(keyListener.identifier);
if (old) {
const stack = this.getOrInitStack(keyListener.identifier);
stack.push(old);
}
map.set(keyListener.identifier, keyListener);
// console.log(this.getAllListenedKeys());
}
/**
*
* @param keyListener
*/
removeKeyListener(keyListener: KeyListener) {
keyListener.onRemove();
const map = this.getOrInit(keyListener.value);
const old = map.get(keyListener.identifier);
map.delete(keyListener.identifier);
const stack = this.getOrInitStack(keyListener.identifier);
if (old && old === keyListener) {
// 是旧的监听
const listener = stack.pop();
if (listener) {
map.set(keyListener.identifier, listener);
}
} else {
// 移除栈中的
const index = stack.findIndex((ls) => ls === keyListener);
if (index >= 0) {
stack.splice(index, 1);
}
}
// console.log(this);
}
getKeyListenerBy(key: string | number): Map<string, KeyListener> | undefined {
return this.keyListenerMap.get(key);
}
getKeyListener(e: KeyboardEvent): Map<string, KeyListener> | undefined {
return (
this.getKeyListenerBy(e.key) ||
this.getKeyListenerBy(e.code) ||
this.getKeyListenerBy(e.keyCode)
);
}
isKeyListened(key: string | number): boolean {
return this.getOrInit(key).size > 0;
}
/**
*
*/
getAllListenedKeys(): string[] {
const keys: string[] = [];
this.keyListenerMap.forEach((v) =>
v.forEach((_listener, ck) => keys.push(ck))
);
return keys;
}
}
type KeyboardKeyHandler = (e: KeyboardEvent, app: GraphicApp) => void;
export enum CombinationKey {
Ctrl = 'Ctrl',
Alt = 'Alt',
Shift = 'Shift',
}
export interface KeyListenerOptions {
// 具体的键值可以是key/code/keycode(keycode已经弃用建议优先使用key或code),例如KeyA/(a/A)分别表示键盘A建其中KeyA为键盘事件的code字段a/A为键盘事件的key字段
value: string | number;
// 组合键
combinations?: CombinationKey[];
// 是否监听全局为false则只在画布为焦点时才处理
global?: boolean;
// 按下操作处理
onPress?: KeyboardKeyHandler;
// 按下操作是否每次触发,默认一次
pressTriggerAsOriginalEvent?: boolean;
// 释放/抬起操作处理
onRelease?: KeyboardKeyHandler;
}
export interface ICompleteKeyListenerOptions {
// 具体的键值可以是key/code/keycode(keycode已经弃用建议优先使用key或code),例如KeyA/(a/A)分别表示键盘A建其中KeyA为键盘事件的code字段a/A为键盘事件的key字段
value: string | number;
// 组合键
combinations: CombinationKey[];
// 是否监听全局为false则只在画布为焦点时才处理
global: boolean;
// 按下操作处理
onPress?: KeyboardKeyHandler;
pressTriggerAsOriginalEvent: boolean;
// 释放/抬起操作处理
onRelease?: KeyboardKeyHandler;
}
const DefaultKeyListenerOptions: ICompleteKeyListenerOptions = {
value: '',
combinations: [],
global: false,
onPress: undefined,
pressTriggerAsOriginalEvent: false,
onRelease: undefined,
};
export class KeyListener {
// value 支持keyCodekeycode三种值
readonly options: ICompleteKeyListenerOptions;
private isPress = false;
constructor(options: KeyListenerOptions) {
this.options = Object.assign({}, DefaultKeyListenerOptions, options);
}
static create(options: KeyListenerOptions): KeyListener {
return new KeyListener(options);
}
public get value(): string | number {
return this.options.value;
}
public get combinations(): string[] {
return this.options.combinations;
}
public get identifier(): string {
return this.options.combinations.join('+') + '+' + this.options.value;
}
public get global(): boolean | undefined {
return this.options.global;
}
public get onPress(): KeyboardKeyHandler | undefined {
return this.options.onPress;
}
public set onPress(v: KeyboardKeyHandler | undefined) {
this.options.onPress = v;
}
public get onRelease(): KeyboardKeyHandler | undefined {
return this.options.onRelease;
}
public set onRelease(v: KeyboardKeyHandler | undefined) {
this.options.onRelease = v;
}
public get pressTriggerEveryTime(): boolean {
return this.options.pressTriggerAsOriginalEvent;
}
public set pressTriggerEveryTime(v: boolean) {
this.options.pressTriggerAsOriginalEvent = v;
}
press(e: KeyboardEvent, app: GraphicApp): void {
if (!this.checkCombinations(e)) {
console.debug('组合键不匹配, 不执行press', e, this);
return;
}
if (this.pressTriggerEveryTime || !this.isPress) {
// console.log('Keydown: ', e, this.onPress);
this.isPress = true;
if (this.onPress) {
this.onPress(e, app);
}
}
}
/**
*
*/
checkCombinations(e: KeyboardEvent): boolean {
const cbs = this.combinations;
if (cbs.length > 0) {
if (
((e.altKey && cbs.includes(CombinationKey.Alt)) ||
(!e.altKey && !cbs.includes(CombinationKey.Alt))) &&
((e.ctrlKey && cbs.includes(CombinationKey.Ctrl)) ||
(!e.ctrlKey && !cbs.includes(CombinationKey.Ctrl))) &&
((e.shiftKey && cbs.includes(CombinationKey.Shift)) ||
(!e.shiftKey && !cbs.includes(CombinationKey.Shift)))
) {
return true;
}
} else {
return !e.altKey && !e.ctrlKey && !e.shiftKey;
}
return false;
}
release(e: KeyboardEvent, app: GraphicApp): void {
if (this.isPress) {
// console.log('Keyup : ', e.key, e);
this.isPress = false;
if (this.onRelease) {
this.onRelease(e, app);
}
}
}
onRemove(): void {
// 重置按下状态
this.isPress = false;
}
}

View File

@ -0,0 +1,6 @@
export * from './InteractionPlugin';
export * from './CommonMousePlugin';
export * from './KeyboardPlugin';
export * from './CopyPlugin';
export * from './GraphicTransformPlugin';
export * from './AnimationManager';

View File

@ -0,0 +1,774 @@
import { Color, Container, Graphics, Point, Rectangle, Text } from 'pixi.js';
import { GraphicApp } from '../app';
import { OutOfBound } from '../utils';
import {
DefaultWhiteMenuOptions,
MenuCompletionItemStyle,
MenuCompletionOptions,
MenuCompletionStyleOptions,
MenuGroupOptions,
MenuItemOptions,
MenuOptions,
} from './Menu';
export class ContextMenuPlugin {
app: GraphicApp;
contextMenuMap: Map<string, ContextMenu> = new Map<string, ContextMenu>();
constructor(app: GraphicApp) {
this.app = app;
const canvas = this.app.canvas;
canvas.on('pointerdown', () => {
this.contextMenuMap.forEach((menu) => {
menu.close();
});
});
}
registerMenu(menu: ContextMenu) {
this.contextMenuMap.set(menu.menuName, menu);
menu.plugin = this;
}
/**
*
*/
public get screenWidth(): number {
return this.app.viewport.screenWidth;
}
/**
*
*/
public get screenHeight(): number {
return this.app.viewport.screenHeight;
}
/**
*
* @param menu
* @param global
*/
open(menu: ContextMenu, global: Point) {
if (!menu.opened) {
menu.opened = true;
this.app.app.stage.addChild(menu);
}
// 处理超出显示范围
const screenHeight = this.screenHeight;
const bottomY = global.y + menu.height;
let oob = this.oob(menu, global);
const pos = global.clone();
if (oob.right) {
pos.x = global.x - menu.width;
}
if (oob.bottom) {
const py = global.y - menu.height;
if (py > 0) {
pos.y = py;
} else {
pos.y = global.y - (bottomY - screenHeight);
}
}
// 移动后是否左上超出
oob = this.oob(menu, pos);
if (oob.left) {
pos.x = 0;
}
if (oob.top) {
pos.y = 0;
}
menu.position.copyFrom(pos);
}
/**
*
* @param menu
*/
close(menu: ContextMenu) {
if (menu.opened) {
menu.opened = false;
this.app.app.stage.removeChild(menu);
}
}
/**
*
* @param menu
* @param global
* @returns
*/
oob(menu: ContextMenu, global: Point): OutOfBound {
const screenWidth = this.screenWidth;
const screenHeight = this.screenHeight;
const bound = new Rectangle(0, 0, screenWidth, screenHeight);
const menuRect = new Rectangle(global.x, global.y, menu.width, menu.height);
return OutOfBound.check(menuRect, bound);
}
}
/**
* ,
*/
export class ContextMenu extends Container {
_plugin?: ContextMenuPlugin;
parentMenuItem?: ContextMenuItem;
openedSubMenu?: ContextMenu;
menuOptions: MenuCompletionOptions;
opened = false;
bg: Graphics;
title?: Text;
groups: MenuGroup[];
private padding = 5;
_active = false; // 激活状态
timeoutCloseHandle?: NodeJS.Timeout;
constructor(menuOptions: MenuOptions, parentMenuItem?: ContextMenuItem) {
super();
this.menuOptions = Object.assign({}, DefaultWhiteMenuOptions, menuOptions);
this.name = this.menuOptions.name;
this.bg = new Graphics();
this.addChild(this.bg);
this.groups = [];
this.init();
this.parentMenuItem = parentMenuItem;
}
static init(options: MenuOptions): ContextMenu {
return new ContextMenu(options);
}
public get style(): MenuCompletionStyleOptions {
return this.menuOptions.style;
}
/**
*
*/
public get parentMenu(): ContextMenu | undefined {
return this.parentMenuItem?.menu;
}
/**
*
*/
public get rootMenu(): ContextMenu {
if (this.parentMenu) {
return this.parentMenu.rootMenu;
}
return this;
}
/**
*
* @returns
*/
hasActiveItem(): boolean {
for (let i = 0; i < this.groups.length; i++) {
const group = this.groups[i];
if (group.hasActiveItem()) {
return true;
}
}
return false;
}
public get active(): boolean {
return (
this._active ||
this.hasActiveItem() ||
(this.parentMenuItem != undefined && this.parentMenuItem._active)
);
}
public set active(v: boolean) {
this._active = v;
this.onActiveChanged();
}
onActiveChanged() {
if (this.parentMenuItem) {
this.parentMenuItem.onActiveChanged();
if (!this.active) {
this.timeoutCloseHandle = setTimeout(() => {
this.close();
}, 500);
} else {
if (this.timeoutCloseHandle) {
clearTimeout(this.timeoutCloseHandle);
}
}
}
}
setOptions(menuOptions: MenuOptions) {
this.menuOptions = Object.assign({}, DefaultWhiteMenuOptions, menuOptions);
this.init();
}
/**
*
*/
init() {
// this.initTitle();
this.groups = [];
const options = this.menuOptions;
let maxItemWidth = 0;
let borderHeight = 0;
options.groups.forEach((group) => {
const menuGroup = new MenuGroup(this, group);
this.groups.push(menuGroup);
borderHeight += menuGroup.totalHeight;
if (menuGroup.maxWidth > maxItemWidth) {
maxItemWidth = menuGroup.maxWidth;
}
});
const splitLineWidth = 1;
const bgWidth = maxItemWidth + this.padding * 2;
const bgHeight =
borderHeight +
this.groups.length * this.padding * 2 +
(this.groups.length - 1) * splitLineWidth;
if (options.style.border) {
this.bg.lineStyle(
options.style.borderWidth,
new Color(options.style.borderColor)
);
}
this.bg.beginFill(new Color(options.style.backgroundColor));
if (options.style.borderRoundRadius > 0) {
this.bg.drawRoundedRect(
0,
0,
bgWidth,
bgHeight,
options.style.borderRoundRadius
);
} else {
this.bg.drawRect(0, 0, bgWidth, bgHeight);
}
this.bg.endFill();
let groupHeight = 0;
this.bg.lineStyle(splitLineWidth, new Color(options.style.borderColor));
for (let i = 0; i < this.groups.length; i++) {
const group = this.groups[i];
group.updateItemBox(maxItemWidth);
group.position.set(this.padding, groupHeight + this.padding);
if (i === this.groups.length - 1) {
// 最后一个
break;
}
const splitLineY = groupHeight + group.height + this.padding * 2;
this.bg.moveTo(0, splitLineY);
this.bg.lineTo(bgWidth, splitLineY);
groupHeight = splitLineY + splitLineWidth;
}
this.addChild(...this.groups);
this.eventMode = 'static';
this.on('pointerover', () => {
this.active = true;
});
this.on('pointerout', () => {
this.active = false;
});
}
initGroups() {
this.groups = [];
const options = this.menuOptions;
options.groups.forEach((group) => {
const menuGroup = new MenuGroup(this, group);
this.groups.push(menuGroup);
});
this.addChild(...this.groups);
}
initTitle() {
if (this.menuOptions.title) {
this.title = new Text(this.menuOptions.title, { align: 'left' });
}
}
updateBg() {
this.bg.clear();
const options = this.menuOptions;
let maxItemWidth = 0;
let borderHeight = 0;
const splitLineWidth = 1;
this.groups.forEach((menuGroup) => {
borderHeight += menuGroup.totalHeight;
if (menuGroup.maxWidth > maxItemWidth) {
maxItemWidth = menuGroup.maxWidth;
}
});
const bgWidth = maxItemWidth + this.padding * 2;
const bgHeight =
borderHeight +
this.groups.length * this.padding * 2 +
(this.groups.length - 1) * splitLineWidth;
if (options.style.border) {
this.bg.lineStyle(
options.style.borderWidth,
new Color(options.style.borderColor)
);
}
this.bg.beginFill(new Color(options.style.backgroundColor));
if (options.style.borderRoundRadius > 0) {
this.bg.drawRoundedRect(
0,
0,
bgWidth,
bgHeight,
options.style.borderRoundRadius
);
} else {
this.bg.drawRect(0, 0, bgWidth, bgHeight);
}
this.bg.endFill();
let groupHeight = 0;
this.bg.lineStyle(splitLineWidth, new Color(options.style.borderColor));
for (let i = 0; i < this.groups.length; i++) {
const group = this.groups[i];
group.updateItemBox(maxItemWidth);
group.position.set(this.padding, groupHeight + this.padding);
if (i === this.groups.length - 1) {
// 最后一个
break;
}
const splitLineY = groupHeight + group.height + this.padding * 2;
this.bg.moveTo(0, splitLineY);
this.bg.lineTo(bgWidth, splitLineY);
groupHeight = splitLineY + splitLineWidth;
}
}
update() {
this.groups.forEach((group) => group.update());
this.updateBg();
}
public get menuName(): string {
return this.menuOptions.name;
}
public get plugin(): ContextMenuPlugin {
if (this.parentMenu) {
return this.parentMenu.plugin;
}
if (this._plugin) {
return this._plugin;
}
throw new Error(`上下文菜单name=${this.menuOptions.name}没有添加到插件中`);
}
public set plugin(v: ContextMenuPlugin) {
this._plugin = v;
}
/**
*
*/
open(global: Point): void {
if (this.parentMenu) {
this.parentMenu.openSub(this, global);
} else {
this.update();
this.plugin.open(this, global);
}
}
/**
*
*/
close(): void {
if (this.openedSubMenu) {
this.openedSubMenu.close();
this.openedSubMenu = undefined;
}
this.plugin.close(this);
}
/**
*
* @param subMenu
* @param global
*/
private openSub(subMenu: ContextMenu, global: Point) {
if (this.openedSubMenu) {
this.openedSubMenu.close();
}
const pos = global.clone();
const oob = this.plugin.oob(subMenu, global);
if (oob.right) {
pos.x = this.position.x - subMenu.width + this.padding;
}
if (oob.bottom) {
pos.y = this.plugin.screenHeight - subMenu.height - this.padding;
}
this.plugin.open(subMenu, pos);
this.openedSubMenu = subMenu;
}
}
class MenuGroup extends Container {
private gutter = 3; // 名称、快捷键、箭头文本间隙
config: MenuGroupOptions;
menu: ContextMenu;
items: ContextMenuItem[] = [];
constructor(menu: ContextMenu, config: MenuGroupOptions) {
super();
this.config = config;
this.menu = menu;
config.items.forEach((item) => {
this.items.push(new ContextMenuItem(menu, item));
});
this.addChild(...this.items);
}
hasActiveItem(): boolean {
for (let i = 0; i < this.items.length; i++) {
const item = this.items[i];
if (item.active) {
return true;
}
}
return false;
}
public get maxWidth(): number {
const maxNameWidth = this.items
.map((item) => item.nameBounds.width)
.sort((a, b) => a - b)
.reverse()[0];
const maxShortcutWidth = this.items
.map((item) => item.shortcutKeyBounds.width)
.sort((a, b) => a - b)
.reverse()[0];
const maxWidth =
maxNameWidth +
this.gutter +
maxShortcutWidth +
this.items[0].paddingLeft +
this.items[0].paddingRight;
return maxWidth;
}
public get totalHeight(): number {
let total = 0;
this.items.forEach((item) => (total += item.totalHeight));
return total;
}
update() {
let i = 0;
this.items.forEach((item) => {
item.update();
if (item.visible) {
item.position.y = i * item.totalHeight;
i++;
}
});
// this.items.forEach()
// for (let i = 0; i < this.items.length; i++) {
// const item = this.items[i];
// if (item.visible) {
// item.position.y = i * item.totalHeight;
// }
// }
}
updateItemBox(maxItemWidth: number) {
this.items.forEach((item) =>
item.updateBox(maxItemWidth, item.totalHeight)
);
}
}
/**
*
*/
class ContextMenuItem extends Container {
menu: ContextMenu;
config: MenuItemOptions;
/**
*
*/
nameText: Text;
/**
*
*/
shortcutKeyText?: Text;
private gutter = 3; // 名称、快捷键、箭头文本间隙
arrowText?: Text;
box: Graphics;
subMenu?: ContextMenu;
_active = false; // 激活状态
constructor(menu: ContextMenu, config: MenuItemOptions) {
super();
this.menu = menu;
this.config = config;
this.box = new Graphics();
this.addChild(this.box);
this.nameText = new Text(this.config.name, {
fontSize: this.fontSize,
fill: this.fontColor,
});
this.addChild(this.nameText);
this.initShortcutKeyText();
this.initSubMenu();
}
registerEventHandler() {
this.eventMode = 'static';
this.cursor = 'pointer';
this.on('pointerover', () => {
this.active = true;
if (this.config.disabled) {
this.cursor = 'not-allowed';
} else {
this.cursor = 'pointer';
}
if (this.subMenu) {
const p = this.toGlobal(new Point(this.width));
this.subMenu.open(p);
}
});
this.on('pointerout', () => {
this.active = false;
});
this.on('pointertap', () => {
if (this.config.disabled) {
// 禁用,不处理
return;
}
if (this.config.handler) {
this.menu.plugin.app.emit('pre-menu-handle', this.config);
this.config.handler();
this.menu.plugin.app.emit('post-menu-handle', this.config);
}
if (!this.config.subMenu || this.config.subMenu.length === 0) {
this.active = false;
this.menu.active = false;
this.menu.rootMenu.close();
}
});
}
public get active(): boolean {
return this._active || (this.subMenu != undefined && this.subMenu.active);
}
public set active(v: boolean) {
this._active = v;
if (this.subMenu) {
this.subMenu.onActiveChanged();
}
this.onActiveChanged();
}
onActiveChanged() {
if (this.active) {
this.box.alpha = 1;
} else {
this.box.alpha = 0;
}
}
public get textWidth(): number {
return this.nameBounds.width + this.shortcutKeyBounds.width + this.gutter;
}
public get nameGraphic(): Text {
if (this.nameText) {
return this.nameText;
}
throw new Error(`菜单项name=${this.config.name}没有初始化名称图形对象`);
}
public get totalHeight(): number {
if (this.config.visible === false) {
return 0;
} else {
return this.paddingTop + this.paddingBottom + this.nameGraphic.height;
}
}
public get nameBounds(): Rectangle {
return this.nameGraphic.getLocalBounds();
}
public get shortcutKeyBounds(): Rectangle {
if (this.shortcutKeyText) {
return this.shortcutKeyText.getLocalBounds();
} else {
return new Rectangle(0, 0, 0, 0);
}
}
public get style(): MenuCompletionItemStyle {
return this.menu.style.itemStyle;
}
private checkPadding(padding: number | number[]) {
if (Array.isArray(padding)) {
if (padding.length !== 2 && padding.length !== 4) {
throw new Error('错误的padding数据');
}
}
}
private toWholePadding(padding: number | number[]): number[] {
this.checkPadding(padding);
if (Array.isArray(padding)) {
if (padding.length == 2) {
return [padding[0], padding[1], padding[0], padding[1]];
} else {
return padding;
}
} else {
return [padding, padding, padding, padding];
}
}
public get paddingTop(): number {
return this.toWholePadding(this.menu.style.itemStyle.padding)[0];
}
public get paddingBottom(): number {
return this.toWholePadding(this.menu.style.itemStyle.padding)[2];
}
public get paddingLeft(): number {
return this.toWholePadding(this.menu.style.itemStyle.padding)[3];
}
public get paddingRight(): number {
return this.toWholePadding(this.menu.style.itemStyle.padding)[1];
}
public get hoverColor(): string {
return this.style.hoverColor;
}
public get fontSize(): number {
return this.style.fontSize;
}
public get fontColor(): string {
if (this.config.disabled) {
return this.style.disabledFontColor;
} else if (this.config.fontColor) {
return this.config.fontColor;
}
return this.style.fontColor;
}
initShortcutKeyText(): Text | undefined {
if (this.config.shortcutKeys && this.config.shortcutKeys.length > 0) {
this.shortcutKeyText = new Text(this.config.shortcutKeys.join('+'), {
fontSize: this.fontSize,
fill: this.fontColor,
});
this.addChild(this.shortcutKeyText);
return this.shortcutKeyText;
}
return undefined;
}
initSubMenu() {
if (this.config.subMenu && this.config.subMenu.length > 0) {
this.arrowText = new Text('>', {
fontSize: this.fontSize,
fill: this.fontColor,
});
this.addChild(this.arrowText);
this.subMenu = new ContextMenu(
{
name: `${this.config.name}子菜单`,
groups: this.config.subMenu,
style: this.menu.style,
},
this
);
}
}
updateBackground(width: number, height: number) {
this.box.clear();
const box = this.box;
const style = this.menu.style;
if (!style.itemStyle.hoverColor) {
throw new Error('未设置菜单项的hoverColor');
}
let hoverColor = style.itemStyle.hoverColor;
if (this.style && this.style.hoverColor) {
hoverColor = this.style.hoverColor;
}
box.beginFill(new Color(hoverColor));
if (style.borderRoundRadius > 0) {
box.drawRoundedRect(0, 0, width, height, style.borderRoundRadius);
} else {
box.drawRect(0, 0, width, height);
}
box.endFill();
box.alpha = 0;
}
updateBox(width: number, height: number) {
this.removeAllListeners();
this.updateBackground(width, height);
this.nameText?.position.set(this.paddingLeft, this.paddingTop);
if (this.shortcutKeyText) {
const skTextWidth = this.shortcutKeyBounds.width;
this.shortcutKeyText.position.set(
width - skTextWidth - this.paddingRight,
this.paddingTop
);
}
if (this.arrowText) {
this.arrowText.position.set(
width - this.paddingRight - this.gutter,
this.paddingTop
);
}
// 事件监听
this.hitArea = new Rectangle(0, 0, width, height);
this.registerEventHandler();
}
update() {
if (this.config.visible === false) {
this.visible = false;
return;
}
this.visible = true;
this.nameText.text = this.config.name;
this.nameText.style.fontSize = this.fontSize;
this.nameText.style.fill = this.fontColor;
if (this.shortcutKeyText) {
if (this.config.shortcutKeys && this.config.shortcutKeys.length > 0) {
this.shortcutKeyText.text = this.config.shortcutKeys.join('+');
this.shortcutKeyText.style.fontSize = this.fontSize;
this.shortcutKeyText.style.fill = this.fontColor;
} else {
this.shortcutKeyText.visible = false;
}
} else {
this.initShortcutKeyText();
}
if (this.subMenu) {
this.subMenu.update();
}
}
}

177
src/jl-graphic/ui/Menu.ts Normal file
View File

@ -0,0 +1,177 @@
/**
*
*/
export interface MenuOptions {
/**
*
*/
name: string;
/**
*
*/
title?: string;
/**
*
*/
groups: MenuGroupOptions[];
/**
*
*/
style?: MenuStyleOptions;
}
/**
*
*/
export interface MenuGroupOptions {
/**
*
*/
name?: string;
/**
*
*/
items: MenuItemOptions[];
}
export interface MenuCompletionOptions extends MenuOptions {
style: MenuCompletionStyleOptions;
}
/**
*
*/
export interface MenuStyleOptions {
/**
*
*/
titleStyle?: MenuItemStyle;
/**
*
*/
backgroundColor?: string;
/**
* 线,1,0线
*/
borderWidth?: number;
/**
*
*/
borderColor?: string;
/**
* ,0
*/
borderRoundRadius?: number;
/**
*
*/
itemStyle?: MenuItemStyle;
}
export interface MenuCompletionStyleOptions extends MenuStyleOptions {
titleStyle: MenuItemStyle;
backgroundColor: string;
border: boolean;
borderWidth: number;
borderColor: string;
borderRoundRadius: number;
itemStyle: MenuCompletionItemStyle;
}
export interface MenuItemOptions {
/**
*
*/
name: string;
/**
* ,
*/
disabled?: boolean;
/**
* ,
*/
visible?: boolean;
/**
*
*/
shortcutKeys?: string[];
/**
*
*/
handler?: () => void;
fontColor?: string;
/**
*
*/
subMenu?: MenuGroupOptions[];
}
export interface MenuItemStyle {
/**
*
*/
fontSize: number;
/**
*
*/
fontColor?: string;
/**
* hover颜色
*/
hoverColor?: string;
/**
*
*/
disabledFontColor?: string;
/**
*
*/
padding: number[] | number; // 内边距
}
export interface MenuCompletionItemStyle extends MenuItemStyle {
/**
*
*/
fontColor: string;
/**
*
*/
hoverColor: string;
/**
*
*/
disabledFontColor: string;
}
/**
*
*/
export const DefaultWhiteStyleOptions: MenuCompletionStyleOptions = {
titleStyle: {
fontSize: 16,
fontColor: '#000000',
padding: [5, 15],
},
backgroundColor: '#ffffff',
border: true,
borderWidth: 1,
borderColor: '#4C4C4C',
/**
*
*/
borderRoundRadius: 5,
itemStyle: {
fontSize: 16,
fontColor: '#000000',
padding: [5, 25],
hoverColor: '#1E78DB',
disabledFontColor: '#9D9D9D',
},
};
/**
*
*/
export const DefaultWhiteMenuOptions: MenuCompletionOptions = {
name: '',
style: DefaultWhiteStyleOptions,
groups: [],
};

View File

@ -0,0 +1,519 @@
import {
Container,
DisplayObject,
IPointData,
Point,
Rectangle,
} from 'pixi.js';
import { floatEquals, isZero } from '../math';
import Vector2 from '../math/Vector2';
/**
*
* @param obj
* @param handler
*/
export function recursiveParents(
obj: DisplayObject,
handler: (parent: Container) => void
): void {
if (obj.parent) {
handler(obj.parent);
recursiveParents(obj.parent, handler);
}
}
/**
*
* @param obj
* @param finder
* @returns
*/
export function recursiveFindParent(
obj: DisplayObject,
finder: (parent: Container) => boolean
): Container | null {
if (obj.parent) {
if (finder(obj.parent)) {
return obj.parent;
} else {
return recursiveFindParent(obj.parent, finder);
}
}
return null;
}
/**
*
* @param container
* @param handler
*/
export function recursiveChildren(
container: Container,
handler: (child: DisplayObject) => void
): void {
container.children.forEach((child) => {
handler(child);
if (child.children) {
recursiveChildren(child as Container, handler);
}
});
}
/**
*
*/
export function recursiveFindChild(
container: Container,
finder: (child: DisplayObject) => boolean
): DisplayObject | null {
for (let i = 0; i < container.children.length; i++) {
const child = container.children[i];
if (finder(child)) {
return child;
} else if (child.children) {
return recursiveFindChild(child as Container, finder);
}
}
return null;
}
export interface BezierParam {
p1: IPointData;
p2: IPointData;
cp1: IPointData;
cp2: IPointData;
}
/**
* 线
* @param points
*/
export function assertBezierPoints(points: IPointData[]) {
if (points.length < 4 || points.length % 3 !== 1) {
throw new Error(`bezierCurve 数据错误: ${points}`);
}
}
/**
* 线
* @param points
* @returns
*/
export function convertToBezierParams(points: IPointData[]): BezierParam[] {
assertBezierPoints(points);
const bps: BezierParam[] = [];
for (let i = 0; i < points.length - 3; i += 3) {
const p1 = new Point(points[i].x, points[i].y);
const p2 = new Point(points[i + 3].x, points[i + 3].y);
const cp1 = new Point(points[i + 1].x, points[i + 1].y);
const cp2 = new Point(points[i + 2].x, points[i + 2].y);
bps.push({
p1,
p2,
cp1,
cp2,
});
}
return bps;
}
/**
* 线
* @param basePoints
* @param segmentsCount
* @returns
*/
export function calculateBezierPoints(
basePoints: IPointData[],
segmentsCount: number
): Point[] {
const bps = convertToBezierParams(basePoints);
const points: Point[] = [];
bps.forEach((bp) => {
points.push(
...calculateOneBezierPoints(bp.p1, bp.p2, bp.cp1, bp.cp2, segmentsCount)
);
});
return points;
}
/**
* 线
* @param basePoints
* @param segmentsCount
* @returns
*/
export function calculateOneBezierPoints(
p1: IPointData,
p2: IPointData,
cp1: IPointData,
cp2: IPointData,
segmentsCount: number
): Point[] {
const points: Point[] = [];
const fromX = p1.x;
const fromY = p1.y;
const n = segmentsCount;
let dt = 0;
let dt2 = 0;
let dt3 = 0;
let t2 = 0;
let t3 = 0;
const cpX = cp1.x;
const cpY = cp1.y;
const cpX2 = cp2.x;
const cpY2 = cp2.y;
const toX = p2.x;
const toY = p2.y;
points.push(new Point(p1.x, p1.y));
for (let i = 1, j = 0; i <= n; ++i) {
j = i / n;
dt = 1 - j;
dt2 = dt * dt;
dt3 = dt2 * dt;
t2 = j * j;
t3 = t2 * j;
const px = dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX;
const py = dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY;
points.push(new Point(px, py));
}
return points;
}
/**
*
*/
export function getRectangleCenter(rectangle: Rectangle): Point {
return new Point(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2
);
}
/**
* , PS: 计算的是较大包围框的中心
* @param rect1
* @param rect2
* @returns
*/
export function getCenterOfTwoRectangle(
rect1: Rectangle,
rect2: Rectangle
): Point {
const x = Math.abs(rect1.width - rect2.width) / 2;
const y = Math.abs(rect1.height - rect2.height) / 2;
return new Point(x, y);
}
/**
*
* @param obj
* @returns
*/
export function serializeTransform(obj: DisplayObject): number[] {
const position = obj.position;
const scale = obj.scale;
const angle = obj.angle;
const skew = obj.skew;
return [position.x, position.y, scale.x, scale.y, angle, skew.x, skew.y];
}
/**
*
* @param obj
* @param transform
*/
export function deserializeTransformInto(
obj: DisplayObject,
transform: number[]
): void {
if (transform.length === 7) {
obj.position.set(transform[0], transform[1]);
obj.scale.set(transform[2], transform[3]);
obj.angle = transform[4];
obj.skew.set(transform[5], transform[6]);
} else if (transform.length > 0) {
console.warn('错误的变换数据', transform);
}
}
/**
* 线
* @param p1
* @param p2
* @param thick
* @returns
*/
export function convertLineToPolygonPoints(
p1: IPointData,
p2: IPointData,
thick: number
): IPointData[] {
const angle = Math.atan2(p2.y - p1.y, p2.x - p1.x) - Math.PI / 2;
const half = thick / 2;
const cos = Math.cos(angle) * half;
const sin = Math.sin(angle) * half;
return [
new Point(p1.x - cos, p1.y - sin),
new Point(p2.x - cos, p2.y - sin),
new Point(p2.x + cos, p2.y + sin),
new Point(p1.x + cos, p1.y + sin),
];
}
/**
*
* @param rect
* @returns
*/
export function convertRectangleToPolygonPoints(rect: Rectangle): IPointData[] {
return [
new Point(rect.x, rect.y),
new Point(rect.x + rect.width, rect.y),
new Point(rect.x + rect.width, rect.y + rect.height),
new Point(rect.x, rect.y + rect.height),
];
}
/**
* 线
* @param p1
* @param p2
* @returns
*/
export function calculateLineMidpoint(p1: IPointData, p2: IPointData): Point {
const x = (p1.x + p2.x) / 2;
const y = (p1.y + p2.y) / 2;
return new Point(x, y);
}
/**
* 线
* @param p1
* @param p2
* @param p
*/
export function calculateDistanceFromPointToLine(
p1: IPointData,
p2: IPointData,
p: IPointData
): number {
// 求直线的一般方程参数ABC直线的一般式方程AX+BY+C=0
const A = p1.y - p2.y;
const B = p2.x - p1.x;
const C = p1.x * p2.y - p1.y * p2.x;
// 计算点到直线垂直距离: d = |Ax+By+C|/sqrt(A*A+B*B),其中x,y为点坐标
const dl = Math.abs(A * p.x + B * p.y + C) / Math.sqrt(A * A + B * B);
return dl;
}
/**
* 线
* @param p
* @param p1
* @param p2
*/
export function calculateFootPointFromPointToLine(
p1: IPointData,
p2: IPointData,
p: IPointData
): Point {
if (p1.x == p2.x && p1.y == p2.y) {
throw new Error(`直线两坐标点相等:${p1}`);
}
const k = -(
((p1.x - p.x) * (p2.x - p1.x) + (p1.y - p.y) * (p2.y - p1.y)) /
(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2))
);
if (isZero(k)) {
return new Point(p.x, p.y);
}
const xf = k * (p2.x - p1.x) + p1.x;
const yf = k * (p2.y - p1.y) + p1.y;
return new Point(xf, yf);
}
/**
* 线
* 1线
* 2线
* 3线e
* 4(Intersection)projectPoint的长度(sideLength)
* 5sideLength和这侧端点到projectPoint距离的比例(ratio)
* 6projectPoint +/- ratio * e =
* @param p0
* @param radius
* @param p1 线1
* @param p2 线2
* @returns 2/1/0
*/
export function calculateIntersectionPointOfCircleAndLine(
p0: IPointData,
radius: number,
p1: IPointData,
p2: IPointData
): Point[] {
const distance = calculateDistanceFromPointToLine(p1, p2, p0);
if (distance <= radius) {
// 有交点
// 计算垂点
const pr = calculateFootPointFromPointToLine(p1, p2, p0);
if (floatEquals(distance, radius)) {
// 切线
return [pr];
}
const vpr = new Vector2([pr.x, pr.y]);
const vc = new Vector2([p0.x, p0.y]);
// 计算直线单位向量
const v1 = new Vector2([p1.x, p1.y]);
const v2 = new Vector2([p2.x, p2.y]);
const ve = Vector2.direction(v2, v1);
const base = Math.sqrt(
Math.abs(radius * radius - Vector2.difference(vpr, vc).squaredLength())
);
const vl = ve.scale(base);
const ip1 = Vector2.sum(vpr, vl);
const ip2 = Vector2.difference(vpr, vl);
return [new Point(ip1.x, ip1.y), new Point(ip2.x, ip2.y)];
} else {
// 无交点
return [];
}
}
/**
*
* @param p0
* @param radius
* @param p
* @returns
*/
export function calculateIntersectionPointOfCircleAndPoint(
p0: IPointData,
radius: number,
p: IPointData
): Point {
const points = calculateIntersectionPointOfCircleAndLine(p0, radius, p0, p);
const vc = new Vector2([p0.x, p0.y]);
const vp = new Vector2([p.x, p.y]);
const vecp = Vector2.direction(vp, vc);
for (let i = 0; i < points.length; i++) {
const ip = points[i];
const ve = Vector2.direction(new Vector2([ip.x, ip.y]), vc);
if (ve.equals(vecp)) {
return ip;
}
}
throw new Error('计算圆心与圆心外一点与圆的交点逻辑错误');
}
/**
*
* @param bp
* @param p
* @param distance p到基准点的距离,
* @returns
*/
export function calculateMirrorPoint(
bp: IPointData,
p: IPointData,
distance?: number
): Point {
const vbp = Vector2.from(bp);
const vp = Vector2.from(p);
const direction = Vector2.direction(vbp, vp);
if (distance == undefined) {
distance = Vector2.distance(vbp, vp);
}
const vmp = Vector2.sum(vbp, direction.scale(distance));
return new Point(vmp.x, vmp.y);
}
/**
*
* @param pa 线
* @param pb 线
* @param p
* @param distance
* @returns
*/
export function calculateMirrorPointBasedOnAxis(
pa: IPointData,
pb: IPointData,
p: IPointData,
distance?: number
): Point {
const fp = calculateFootPointFromPointToLine(pa, pb, p);
if (fp.equals(p)) {
return fp;
} else {
return calculateMirrorPoint(fp, p, distance);
}
}
/**
* 线,0
* @param p1
* @param p2
* @returns [0, 360)
*/
export function angleToAxisx(p1: IPointData, p2: IPointData): number {
if (p1.x == p2.x && p1.y == p2.y) {
throw new Error('一个点无法计算角度');
}
const dx = Math.abs(p1.x - p2.x);
const dy = Math.abs(p1.y - p2.y);
if (p2.x == p1.x) {
if (p2.y > p1.y) {
return 90;
} else {
return 270;
}
}
if (p2.y == p1.y) {
if (p2.x > p1.x) {
return 0;
} else {
return 180;
}
}
const angle = (Math.atan2(dy, dx) * 180) / Math.PI;
if (p2.x > p1.x) {
if (p2.y > p1.y) {
return angle;
} else if (p2.y < p1.y) {
return 360 - angle;
}
} else if (p2.x < p1.x) {
if (p2.y > p1.y) {
return 180 - angle;
} else {
return 180 + angle;
}
}
return angle;
}
/**
* 线,pc与pa,pb的夹角
* @param pa
* @param pb
* @param pc
* @returns , [-180, 180]
*/
export function angleOfIncludedAngle(
pa: IPointData,
pb: IPointData,
pc: IPointData
): number {
const abAngle = angleToAxisx(pa, pb);
const acAngle = angleToAxisx(pa, pc);
let angle = acAngle - abAngle;
if (angle < -180) {
angle = 360 + angle;
} else if (angle > 180) {
angle = -(360 - angle);
}
return angle;
}

View File

@ -0,0 +1,362 @@
import { IPointData, Point, Rectangle } from 'pixi.js';
// /**
// * 点线碰撞检测
// * @param pa 线段a端坐标
// * @param pb 线段b端坐标
// * @param p 点坐标
// * @param tolerance 容忍度,越大检测范围越大
// * @returns
// */
// export function linePoint(pa: Point, pb: Point, p: Point, tolerance: number): boolean {
// return (Math.abs(distanceSquared(pa.x, pa.y, pb.x, pb.y) - (distanceSquared(pa.x, pa.y, p.x, p.y) + distanceSquared(pb.x, pb.y, p.x, p.y))) <= tolerance)
// }
/**
* 线
* @param pa 线a端坐标
* @param pb 线b端坐标
* @param p
* @param lineWidth 线
* @param exact 使线线8
* @returns
*/
export function linePoint(
pa: IPointData,
pb: IPointData,
p: IPointData,
lineWidth: number,
exact = false
): boolean {
if (!exact && lineWidth < 6) {
lineWidth = 6;
}
// 求直线的一般方程参数ABC直线的一般式方程AX+BY+C=0
const A = pa.y - pb.y;
const B = pb.x - pa.x;
const C = pa.x * pb.y - pa.y * pb.x;
// 计算点到直线垂直距离: d = |Ax+By+C|/sqrt(A*A+B*B),其中x,y为点坐标
const dl = Math.abs(A * p.x + B * p.y + C) / Math.sqrt(A * A + B * B);
const intersect = dl <= lineWidth / 2;
if (intersect) {
// 距离在线宽范围内,再判断点是否超过线段两端点范围外(两端点外会有一点误差,两端点线宽一半半径的圆范围内)
const da = distance(pa.x, pa.y, p.x, p.y);
const db = distance(pb.x, pb.y, p.x, p.y);
const dab = distance(pa.x, pa.y, pb.x, pb.y);
return da <= dl + dab && db <= dl + dab;
}
return false;
}
/**
* 线
* @param points 线
* @param p
* @param lineWidth 线
*/
export function polylinePoint(
points: IPointData[],
p: IPointData,
lineWidth: number
) {
const len = points.length;
for (let i = 0; i < len - 1; i++) {
if (linePoint(points[i], points[i + 1], p, lineWidth)) {
return true;
}
}
return false;
}
/**
* 线线
* @param pa 线1a端坐标
* @param pb 线1b端坐标
* @param p1 线2a端坐标
* @param p2 线2b端坐标
* @returns
*/
export function lineLine(
pa: IPointData,
pb: IPointData,
p1: IPointData,
p2: IPointData
): boolean {
const x1 = pa.x;
const y1 = pa.y;
const x2 = pb.x;
const y2 = pb.y;
const x3 = p1.x;
const y3 = p1.y;
const x4 = p2.x;
const y4 = p2.y;
const s1_x = x2 - x1;
const s1_y = y2 - y1;
const s2_x = x4 - x3;
const s2_y = y4 - y3;
const s =
(-s1_y * (x1 - x3) + s1_x * (y1 - y3)) / (-s2_x * s1_y + s1_x * s2_y);
const t =
(s2_x * (y1 - y3) - s2_y * (x1 - x3)) / (-s2_x * s1_y + s1_x * s2_y);
return s >= 0 && s <= 1 && t >= 0 && t <= 1;
}
/**
*
* @param p
* @param rect
* @returns
*/
export function pointBox(p: IPointData, rect: Rectangle): boolean {
const { x, y, width, height } = rect;
const x2 = p.x;
const y2 = p.y;
return x2 >= x && x2 <= x + width && y2 >= y && y2 <= y + height;
}
/**
* 线
* @param pa 线a端坐标
* @param pb 线b端坐标
* @param rect
* @returns
*/
export function lineBox(
pa: IPointData,
pb: IPointData,
rect: Rectangle
): boolean {
if (pointBox(pa, rect) || pointBox(pb, rect)) {
return true;
}
const { x, y, width, height } = rect;
const rp1 = new Point(x, y);
const rp2 = new Point(x + width, y);
const rp3 = new Point(x + width, y + height);
const rp4 = new Point(x, y + height);
return (
lineLine(pa, pb, rp1, rp2) ||
lineLine(pa, pb, rp2, rp3) ||
lineLine(pa, pb, rp3, rp4) ||
lineLine(pa, pb, rp1, rp4)
);
}
/**
* 线
* @param points
* @param rect
* @returns false / 线
*/
export function polylineBox(points: IPointData[], rect: Rectangle): boolean {
if (points.length < 2) {
return false;
}
for (let i = 0; i < points.length - 1; i++) {
const p1 = points[i];
const p2 = points[i + 1];
if (lineBox(p1, p2, rect)) {
return true;
}
}
return false;
}
/**
*
* @param p1
* @param p2
* @param tolerance
* @returns
*/
export function pointPoint2(
p1: IPointData,
p2: IPointData,
tolerance: number
): boolean {
return pointPoint(p1.x, p1.y, p2.x, p2.y, tolerance);
}
/**
*
* @param x1
* @param y1
* @param x2
* @param y2
* @param tolerance /
* @returns
*/
export function pointPoint(
x1: number,
y1: number,
x2: number,
y2: number,
tolerance: number
): boolean {
return distance(x1, y1, x2, y2) <= tolerance;
}
/**
*
* @param x1
* @param y1
* @param x2
* @param y2
* @returns
*/
export function distance(x1: number, y1: number, x2: number, y2: number) {
return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}
/**
*
* @param p1
* @param p2
* @returns
*/
export function distance2(p1: IPointData, p2: IPointData): number {
return distance(p1.x, p1.y, p2.x, p2.y);
}
/**
*
* @param x1 x
* @param y1 y
* @param r1
* @param x2 x
* @param y2 y
* @returns
*/
export function circlePoint(
x1: number,
y1: number,
r1: number,
x2: number,
y2: number
) {
const x = x2 - x1;
const y = y2 - y1;
return x * x + y * y <= r1 * r1;
}
/**
* --
*/
export function circlePoint2(
x1: number,
y1: number,
r1: number,
x2: number,
y2: number,
tolerance: number
) {
const x = x2 - x1;
const y = y2 - y1;
return (
x * x + y * y <= (r1 + tolerance) * (r1 + tolerance) &&
x * x + y * y >= (r1 - tolerance) * (r1 - tolerance)
);
}
/**
*
*/
export function pointPolygon(
p: IPointData,
points: IPointData[],
lineWidth: number
): boolean {
const { x, y } = p;
const length = points.length;
let c = false;
let i, j;
for (i = 0, j = length - 1; i < length; i++) {
if (
points[i].y > y !== points[j].y > y &&
x <
((points[j].x - points[i].x) * (y - points[i].y)) /
(points[j].y - points[i].y) +
points[i].x
) {
c = !c;
}
j = i;
}
if (c) {
return true;
}
for (i = 0; i < length - 1; i++) {
let p1, p2;
if (i === length - 1) {
p1 = points[i];
p2 = points[0];
} else {
p1 = points[i];
p2 = points[i + 1];
}
if (linePoint(p1, p2, p, lineWidth)) {
return true;
}
}
return false;
}
/**
* 线
* @param p1
* @param p2
* @param points
* @param tolerance 线
* @returns
*/
export function linePolygon(
p1: IPointData,
p2: IPointData,
points: IPointData[],
lineWidth: number,
polygonWidth: number
): boolean {
if (pointPolygon(p1, points, polygonWidth)) {
return true;
}
const length = points.length;
for (let i = 0; i < length; i++) {
let pa, pb;
if (i === length - 1) {
pa = points[i];
pb = points[0];
} else {
pa = points[i];
pb = points[i + 1];
}
// TODO:此处后续需考虑有线宽的情况
if (lineLine(pa, pb, p1, p2)) {
return true;
}
}
return false;
}
/**
* 线
* @param polylinePoints 线
* @param polygonPoints
* @param polylineWidth 线线
* @param polygonWidth 线
* @returns
*/
export function polylinePolygon(
polylinePoints: IPointData[],
polygonPoints: IPointData[],
polylineWidth: number,
polygonWidth: number
): boolean {
const length = polylinePoints.length;
for (let i = 0; i < length - 1; i++) {
const p1 = polylinePoints[i];
const p2 = polylinePoints[i + 1];
if (linePolygon(p1, p2, polygonPoints, polylineWidth, polygonWidth)) {
return true;
}
}
return false;
}

View File

@ -0,0 +1,53 @@
import { Point, Rectangle } from 'pixi.js';
export * from './GraphicUtils';
export * from './IntersectUtils';
export const UP: Point = new Point(0, -1);
export const DOWN: Point = new Point(0, 1);
export const LEFT: Point = new Point(-1, 0);
export const RIGHT: Point = new Point(1, 0);
/**
*
*/
export class OutOfBound {
left: boolean;
top: boolean;
right: boolean;
bottom: boolean;
constructor(left: boolean, top: boolean, right: boolean, bottom: boolean) {
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
static check(rect: Rectangle, bound: Rectangle): OutOfBound {
const left = rect.left < bound.left;
const top = rect.top < bound.top;
const right = rect.right > bound.right;
const bottom = rect.bottom > bound.bottom;
return new OutOfBound(left, top, right, bottom);
}
static none(): OutOfBound {
return new OutOfBound(false, false, false, false);
}
static leftOut(): OutOfBound {
return new OutOfBound(true, false, false, false);
}
static topOut(): OutOfBound {
return new OutOfBound(false, true, false, false);
}
static rightOut(): OutOfBound {
return new OutOfBound(false, false, true, false);
}
static bottomOut(): OutOfBound {
return new OutOfBound(false, false, false, true);
}
static leftTopOut(): OutOfBound {
return new OutOfBound(true, true, false, false);
}
static rightBottomOut(): OutOfBound {
return new OutOfBound(false, false, true, true);
}
}

334
yarn.lock
View File

@ -89,6 +89,226 @@
"@nodelib/fs.scandir" "2.1.5"
fastq "^1.6.0"
"@pixi/accessibility@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/accessibility/-/accessibility-7.2.4.tgz#3198d0059c230c668b1179457346a3b5dcba6e64"
integrity sha512-EVjuqUqv9FeYFXCv0S0qj1hgCtbAMNBPCbOGEtiMogpM++/IySxBZvcOYg3rRgo9inwt2s4Bi7kUiqMPD8hItw==
"@pixi/app@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/app/-/app-7.2.4.tgz#ae16fdc9fce04224fb36311168d902a2e7d0e65a"
integrity sha512-eJ2jpu5P28ip07nLItw6sETXn45P4KR/leMJ6zPHRlhT1m8t5zTsWr3jK4Uj8LF2E+6KlPNzLQh5Alf/unn/aQ==
"@pixi/assets@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/assets/-/assets-7.2.4.tgz#944f4a15acc888071c0811d3d68524afb0ed069c"
integrity sha512-7199re3wvMAlVqXLaCyAr8IkJSXqkeVAxcYyB2rBu4Id5m2hhlGX1dQsdMBiCXLwu6/LLVqDvJggSNVQBzL6ZQ==
dependencies:
"@types/css-font-loading-module" "^0.0.7"
"@pixi/color@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/color/-/color-7.2.4.tgz#6d6d5dbc01ae2a4f1c8eb48e98fff89ac0c3e40d"
integrity sha512-B/+9JRcXe2uE8wQfsueFRPZVayF2VEMRB7XGeRAsWCryOX19nmWhv0Nt3nOU2rvzI0niz9XgugJXsB6vVmDFSg==
dependencies:
colord "^2.9.3"
"@pixi/compressed-textures@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/compressed-textures/-/compressed-textures-7.2.4.tgz#bbf84689a9f4f41d5a8e9476ea6520a4c19412ac"
integrity sha512-atnWyw/ot/Wg69qhgskKiuTYCZx15IxV35sa0KyXMthyjyvDLCIvOn0nczM6wCBy9H96SjJbfgynVWhVrip6qw==
"@pixi/constants@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/constants/-/constants-7.2.4.tgz#45c23b247309e78d4105f04063ad8b453dae8b2f"
integrity sha512-hKuHBWR6N4Q0Sf5MGF3/9l+POg/G5rqhueHfzofiuelnKg7aBs3BVjjZ+6hZbd6M++vOUmxYelEX/NEFBxrheA==
"@pixi/core@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/core/-/core-7.2.4.tgz#9f93a0744c795b17045127c2630f976580f03008"
integrity sha512-0XtvrfxHlS2T+beBBSpo7GI8+QLyyTqMVQpNmPqB4woYxzrOEJ9JaUFBaBfCvycLeUkfVih1u6HAbtF+2d1EjQ==
dependencies:
"@pixi/color" "7.2.4"
"@pixi/constants" "7.2.4"
"@pixi/extensions" "7.2.4"
"@pixi/math" "7.2.4"
"@pixi/runner" "7.2.4"
"@pixi/settings" "7.2.4"
"@pixi/ticker" "7.2.4"
"@pixi/utils" "7.2.4"
"@types/offscreencanvas" "^2019.6.4"
"@pixi/display@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/display/-/display-7.2.4.tgz#cbf46ba0c0c0d30064b9ce67190a0a6a3624c62f"
integrity sha512-w5tqb8cWEO5qIDaO9GEqRvxYhL0iMk0Wsngw23bbLm1gLEQmrFkB2tpJlRAqd7H82C3DrDDeWvkrrxW6+m4apg==
"@pixi/events@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/events/-/events-7.2.4.tgz#06434c9e84838b87d7626151ec556a66796ac206"
integrity sha512-/JtmoB98fzIU8giN9xvlRvmvOi6u4MaD2DnKNOMHkQ1MBraj3pmrXM9fZ0JbNzi+324GraAAY76QidgHjIYoYQ==
"@pixi/extensions@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/extensions/-/extensions-7.2.4.tgz#ab2940abce3935706e956d1bcf2dbf44aca440db"
integrity sha512-Mnqv9scbL1ARD3QFKfOWs2aSVJJfP1dL8g5UiqGImYO3rZbz/9QCzXOeMVIZ5n3iaRyKMNhFFr84/zUja2H7Dw==
"@pixi/extract@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/extract/-/extract-7.2.4.tgz#2db62611a3135ee8232affdb7b26cab37cb2a0a3"
integrity sha512-wlXZg+J2L/1jQhRi5nZQP/cXshovhjksjss91eAKMvY5aGxNAQovCP4xotJ/XJjfTvPMpeRzHPFYzm3PrOPQ7g==
"@pixi/filter-alpha@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/filter-alpha/-/filter-alpha-7.2.4.tgz#f33621fa4bdc95de09457780aa33eb253fe6447f"
integrity sha512-UTUMSGyktUr+I9vmigqJo9iUhb0nwGyqTTME2xBWZvVGCnl5z+/wHxvIBBCe5pNZ66IM15pGXQ4cDcfqCuP2kA==
"@pixi/filter-blur@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/filter-blur/-/filter-blur-7.2.4.tgz#834447f9d6edec7d27414c9961b9e6009acd678a"
integrity sha512-aLyXIoxy14bTansCPtbY8x7Sdn2OrrqkF/pcKiRXHJGGhi7wPacvB/NcmYJdnI/n2ExQ6V5Njuj/nfrsejVwcA==
"@pixi/filter-color-matrix@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/filter-color-matrix/-/filter-color-matrix-7.2.4.tgz#4c9e6e174b27635ce5e92f34d372366b901e250f"
integrity sha512-DFtayybYXoUh73eHUFRK5REbi1t3FZuVUnaQTj+euHKF9L7EaYc3Q9wctpx1WPRcwkqEX50M4SNFhxpA7Pxtaw==
"@pixi/filter-displacement@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/filter-displacement/-/filter-displacement-7.2.4.tgz#39da0592966079d7e194be46494b8055b5eebda2"
integrity sha512-Simq3IBJKt7+Gvk4kK7OFkfoeYUMhNhIyATCdeT+Jkdkq5WV7pYnH5hqO0YW7eAHrgjV13yn6t4H/GC4+6LhEA==
"@pixi/filter-fxaa@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/filter-fxaa/-/filter-fxaa-7.2.4.tgz#78fac5466ca1a249f343be1af90c79bae399bf92"
integrity sha512-qzKjdL+Ih18uGTJLg8tT/H+YCsTeGkw2uF7lyKnw/lxGLJQhLWIhM95M9qSNgxbXyW1vp7SbG81a9aAEz2HAhA==
"@pixi/filter-noise@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/filter-noise/-/filter-noise-7.2.4.tgz#0586a00381ec0e63f6c00d49cd58b781eaf07f37"
integrity sha512-QAU9Ybj2ZQrWM9ZEjTTC0iLnQcuyNoZNRinxSbg1G0yacpmsSb9wvV5ltIZ66+hfY+90+u2Nudt/v9g6pvOdGg==
"@pixi/filter-outline@^5.2.0":
version "5.2.0"
resolved "https://registry.npmmirror.com/@pixi/filter-outline/-/filter-outline-5.2.0.tgz#8572ed2c847c31c5a142db04e86f081baed0365a"
integrity sha512-xKfAouhZNKl6A0RvxT5i+2/ean7r16dE/QswwIkbWvr2hhHlp4p9U6XsqdgUERCDxK+IZibMAumbWs4DGxOUeQ==
"@pixi/graphics@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/graphics/-/graphics-7.2.4.tgz#8500b604c36184736926393cb0ca9b9de9afef86"
integrity sha512-3A2EumTjWJgXlDLOyuBrl9b6v1Za/E+/IjOGUIX843HH4NYaf1a2sfDfljx6r3oiDvy+VhuBFmgynRcV5IyA0Q==
"@pixi/math@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/math/-/math-7.2.4.tgz#219b64ca44348a1ee900ee074c51ee7e41615059"
integrity sha512-LJB+mozyEPllxa0EssFZrKNfVwysfaBun4b2dJKQQInp0DafgbA0j7A+WVg0oe51KhFULTJMpDqbLn/ITFc41A==
"@pixi/mesh-extras@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/mesh-extras/-/mesh-extras-7.2.4.tgz#e3c6721c1a8ff5852e76402276b2f495b7db702d"
integrity sha512-Lxqq/1E2EmDgjZX8KzjhBy3VvITIQ00arr2ikyHYF1d0XtQTKEYpr8VKzhchqZ5/9DuyTDbDMYGhcxoNXQmZrQ==
"@pixi/mesh@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/mesh/-/mesh-7.2.4.tgz#c78cc24f831a9e08d4ac0a1706e82f3498ba6907"
integrity sha512-wiALIqcRKib2BqeH9kOA5fOKWN352nqAspgbDa8gA7OyWzmNwqIedIlElixd0oLFOrIN5jOZAdzeKnoYQlt9Aw==
"@pixi/mixin-cache-as-bitmap@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/mixin-cache-as-bitmap/-/mixin-cache-as-bitmap-7.2.4.tgz#4fb69efc40b30b0a8c2c1ad1eee6ca3227eccaed"
integrity sha512-95L/9nzfLHw6GoeqqRl/RjSloKvRt0xrc2inCmjMZvMsFUEtHN2F8IWd1k5vcv0S+83NCreFkJg6nJm1m5AZqg==
"@pixi/mixin-get-child-by-name@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/mixin-get-child-by-name/-/mixin-get-child-by-name-7.2.4.tgz#863b14c774d3af7e2a38a68904c06bc51a2b51dd"
integrity sha512-9g17KgSBEEhkinnKk4dqmxagzHOCPSTvGB6lOopBq4yyXmr/2WVv+QGjuzE0O+p80szQeBJjPBQxzrfBILaSRw==
"@pixi/mixin-get-global-position@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/mixin-get-global-position/-/mixin-get-global-position-7.2.4.tgz#8c0b96a0bcd381db9486954aeeb6d06c5ea2e2c0"
integrity sha512-UrAUF2BXCeWtFgR2m+er41Ky7zShT7r228cZkB6ZfYwMeThhwqG5mH68UeCyP6p68JMpT1gjI2DPfeSRY3ecnA==
"@pixi/particle-container@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/particle-container/-/particle-container-7.2.4.tgz#8f277f65e73b061d0859c7e526f5161f9b090242"
integrity sha512-tpSzilZGFtAoi8XhzL0TecLPNRQAbY8nWV9XNGXJDw+nxXp18GCe8L6eEmnHLlAug67BRHl65DtrdvTknPX+4g==
"@pixi/prepare@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/prepare/-/prepare-7.2.4.tgz#fd470bbc7dd90c4a8111989c405ffb5521850ff9"
integrity sha512-Yff5Sh4kTLdKc5VkkM44LW9gpj7Izw8ns3P1TzWxqeGjzPZ3folr/tQujGL+Qw+8A9VESp+hX9MSIHyw+jpyrg==
"@pixi/runner@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/runner/-/runner-7.2.4.tgz#7356e768a43809ed6f8b3254e9bdd8c1a47af0e7"
integrity sha512-YtyqPk1LA+0guEFKSFx6t/YSvbEQwajFwi4Ft8iDhioa6VK2MmTir1GjWwy7JQYLcDmYSAcQjnmFtVTZohyYSw==
"@pixi/settings@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/settings/-/settings-7.2.4.tgz#bfd3107ad425f99316018ee441accdf7d55627e6"
integrity sha512-ZPKRar9EwibijGmH8EViu4Greq1I/O7V/xQx2rNqN23XA7g09Qo6yfaeQpufu5xl8+/lZrjuHtQSnuY7OgG1CA==
dependencies:
"@pixi/constants" "7.2.4"
"@types/css-font-loading-module" "^0.0.7"
ismobilejs "^1.1.0"
"@pixi/sprite-animated@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/sprite-animated/-/sprite-animated-7.2.4.tgz#46b95e52781dd7cf84ee315521c209e48c40656d"
integrity sha512-9eRriPSC0QVS7U9zQlrG3uEI5+h3fi+mqofXy+yjk1sGCmXSIJME5p2wg2mzxoJk3qkSMagQA9QHtL26Fti8Iw==
"@pixi/sprite-tiling@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/sprite-tiling/-/sprite-tiling-7.2.4.tgz#7bcbd6e0096512fe18934a7b3250c57be19b63e4"
integrity sha512-nGfxQoACRx49dUN0oW1vFm3141M+7gkAbzoNJym2Pljd2dpLME9fb5E6Lyahu0yWMaPRhhGorn6z9VIGmTF3Jw==
"@pixi/sprite@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/sprite/-/sprite-7.2.4.tgz#be7cd2d58d263131019545a83bb4df7340452ba1"
integrity sha512-DhR1B+/d0eXpxHIesJMXcVPrKFwQ+zRA1LvEIFfzewqfaRN3X6PMIuoKX8SIb6tl+Hq8Ba9Pe28zI7d2rmRzrA==
"@pixi/spritesheet@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/spritesheet/-/spritesheet-7.2.4.tgz#9214d0c75aa95639c1f528091ac4a4850f5b5b8e"
integrity sha512-LNmlavyiMQeCF0U4S+yhzxUYmPmat6EpLjLnkGukQTZV5CZkxDCVgXM9uKoRF2DvNydj4yuwZ6+JjK8QssHI8Q==
"@pixi/text-bitmap@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/text-bitmap/-/text-bitmap-7.2.4.tgz#444010da3898c35e2cdb01493bdc21706c9356a1"
integrity sha512-3u2CP4VN+muCaq/jtj7gn0hb3DET/X2S04zTBcgc2WVGufJc62yz+UDzS9jC+ellotVdt9c8U74++vpz3zJGfw==
"@pixi/text-html@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/text-html/-/text-html-7.2.4.tgz#4702cdb97c6a10ca883d004808d45b1517c7129b"
integrity sha512-0NfLAE/w51ZtatxVqLvDS62iO0VLKsSdctqTAVv4Zlgdk9TKJmX1WUucHJboTvbm2SbDjNDGfZ6qXM5nAslIDQ==
"@pixi/text@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/text/-/text-7.2.4.tgz#b31e7619ba80acee69cd9fb33948d34f1839bc61"
integrity sha512-DGu7ktpe+zHhqR2sG9NsJt4mgvSObv5EqXTtUxD4Z0li1gmqF7uktpLyn5I6vSg1TTEL4TECClRDClVDGiykWw==
"@pixi/ticker@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/ticker/-/ticker-7.2.4.tgz#5acb761d3b53a1bbb2e34db59eb2a1b0442a8ed8"
integrity sha512-hQQHIHvGeFsP4GNezZqjzuhUgNQEVgCH9+qU05UX1Mc5UHC9l6OJnY4VTVhhcHxZjA6RnyaY+1zBxCnoXuazpg==
dependencies:
"@pixi/extensions" "7.2.4"
"@pixi/settings" "7.2.4"
"@pixi/utils" "7.2.4"
"@pixi/utils@7.2.4":
version "7.2.4"
resolved "https://registry.npmmirror.com/@pixi/utils/-/utils-7.2.4.tgz#9f74e859481e3efbb6e54e524427b39a6d99829c"
integrity sha512-VUGQHBOINIS4ePzoqafwxaGPVRTa3oM/mEutIIHbNGI3b+QvSO+1Dnk40M0zcH6Bo+MxQZbOZK5X/wO9oU5+LQ==
dependencies:
"@pixi/color" "7.2.4"
"@pixi/constants" "7.2.4"
"@pixi/settings" "7.2.4"
"@types/earcut" "^2.1.0"
earcut "^2.2.4"
eventemitter3 "^4.0.0"
url "^0.11.0"
"@quasar/app-vite@^1.0.0":
version "1.4.3"
resolved "https://registry.npmmirror.com/@quasar/app-vite/-/app-vite-1.4.3.tgz#442944cace5008c473411212b04af3a46090ae0a"
@ -154,6 +374,11 @@
estree-walker "^2.0.1"
picomatch "^2.2.2"
"@stomp/stompjs@^7.0.0":
version "7.0.0"
resolved "https://registry.npmmirror.com/@stomp/stompjs/-/stompjs-7.0.0.tgz#46b5c454a9dc8262e0b20f3b3dbacaa113993077"
integrity sha512-fGdq4wPDnSV/KyOsjq4P+zLc8MFWC3lMmP5FBgLWKPJTYcuCbAIrnRGjB7q2jHZdYCOD5vxLuFoKIYLy5/u8Pw==
"@types/body-parser@*":
version "1.19.2"
resolved "https://registry.npmmirror.com/@types/body-parser/-/body-parser-1.19.2.tgz#aea2059e28b7658639081347ac4fab3de166e6f0"
@ -189,6 +414,16 @@
resolved "https://registry.npmmirror.com/@types/cordova/-/cordova-0.0.34.tgz#ea7addf74ecec3d7629827a0c39e2c9addc73d04"
integrity sha512-rkiiTuf/z2wTd4RxFOb+clE7PF4AEJU0hsczbUdkHHBtkUmpWQpEddynNfJYKYtZFJKbq4F+brfekt1kx85IZA==
"@types/css-font-loading-module@^0.0.7":
version "0.0.7"
resolved "https://registry.npmmirror.com/@types/css-font-loading-module/-/css-font-loading-module-0.0.7.tgz#2f98ede46acc0975de85c0b7b0ebe06041d24601"
integrity sha512-nl09VhutdjINdWyXxHWN/w9zlNCfr60JUqJbd24YXUuCwgeL0TpFSdElCwb6cxfB6ybE19Gjj4g0jsgkXxKv1Q==
"@types/earcut@^2.1.0":
version "2.1.1"
resolved "https://registry.npmmirror.com/@types/earcut/-/earcut-2.1.1.tgz#573a0af609f17005c751f6f4ffec49cfe358ea51"
integrity sha512-w8oigUCDjElRHRRrMvn/spybSMyX8MTkKA5Dv+tS1IE/TgmNZPqUYtvYBXGY8cieSE66gm+szeK+bnbxC2xHTQ==
"@types/express-serve-static-core@^4.17.33":
version "4.17.35"
resolved "https://registry.npmmirror.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.35.tgz#c95dd4424f0d32e525d23812aa8ab8e4d3906c4f"
@ -221,6 +456,11 @@
resolved "https://registry.npmmirror.com/@types/filewriter/-/filewriter-0.0.29.tgz#a48795ecadf957f6c0d10e0c34af86c098fa5bee"
integrity sha512-BsPXH/irW0ht0Ji6iw/jJaK8Lj3FJemon2gvEqHKpCdDCeemHa+rI3WBGq5z7cDMZgoLjY40oninGxqk+8NzNQ==
"@types/google-protobuf@^3.15.6":
version "3.15.6"
resolved "https://registry.npmmirror.com/@types/google-protobuf/-/google-protobuf-3.15.6.tgz#674a69493ef2c849b95eafe69167ea59079eb504"
integrity sha512-pYVNNJ+winC4aek+lZp93sIKxnXt5qMkuKmaqS3WGuTq0Bw1ZDYNBgzG5kkdtwcv+GmYJGo3yEg6z2cKKAiEdw==
"@types/har-format@*":
version "1.2.10"
resolved "https://registry.npmmirror.com/@types/har-format/-/har-format-1.2.10.tgz#7b4e1e0ada4d17684ac3b05d601a4871cfab11fc"
@ -251,6 +491,11 @@
resolved "https://registry.npmmirror.com/@types/node/-/node-12.20.55.tgz#c329cbd434c42164f846b909bd6f85b5537f6240"
integrity sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==
"@types/offscreencanvas@^2019.6.4":
version "2019.7.0"
resolved "https://registry.npmmirror.com/@types/offscreencanvas/-/offscreencanvas-2019.7.0.tgz#e4a932069db47bb3eabeb0b305502d01586fa90d"
integrity sha512-PGcyveRIpL1XIqK8eBsmRBt76eFgtzuPiSTyKHZxnGemp2yzGzWpjYKAfK3wIMiU7eH+851yEpiuP8JZerTmWg==
"@types/qs@*":
version "6.9.7"
resolved "https://registry.npmmirror.com/@types/qs/-/qs-6.9.7.tgz#63bb7d067db107cc1e457c303bc25d511febf6cb"
@ -831,6 +1076,11 @@ color-name@~1.1.4:
resolved "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
colord@^2.9.3:
version "2.9.3"
resolved "https://registry.npmmirror.com/colord/-/colord-2.9.3.tgz#4f8ce919de456f1d5c1c368c307fe20f3e59fb43"
integrity sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw==
combined-stream@^1.0.8:
version "1.0.8"
resolved "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
@ -1004,6 +1254,11 @@ dot-prop@6.0.1:
dependencies:
is-obj "^2.0.0"
earcut@^2.2.4:
version "2.2.4"
resolved "https://registry.npmmirror.com/earcut/-/earcut-2.2.4.tgz#6d02fd4d68160c114825d06890a92ecaae60343a"
integrity sha512-/pjZsA1b4RPHbeWZQn66SWS8nZZWLQQ23oE3Eam7aroEFGEvwKAsJfZ9ytiEMycfzXWpca4FA9QIOehf7PocBQ==
ee-first@1.1.1:
version "1.1.1"
resolved "https://registry.npmmirror.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d"
@ -1443,6 +1698,11 @@ etag@~1.8.1:
resolved "https://registry.npmmirror.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887"
integrity sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==
eventemitter3@^4.0.0:
version "4.0.7"
resolved "https://registry.npmmirror.com/eventemitter3/-/eventemitter3-4.0.7.tgz#2de9b68f6528d5644ef5c59526a1b4a07306169f"
integrity sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==
express@^4.17.3:
version "4.18.2"
resolved "https://registry.npmmirror.com/express/-/express-4.18.2.tgz#3fabe08296e930c796c19e3c516979386ba9fd59"
@ -1695,6 +1955,11 @@ globby@^11.1.0:
merge2 "^1.4.1"
slash "^3.0.0"
google-protobuf@^3.21.2:
version "3.21.2"
resolved "https://registry.npmmirror.com/google-protobuf/-/google-protobuf-3.21.2.tgz#4580a2bea8bbb291ee579d1fefb14d6fa3070ea4"
integrity sha512-3MSOYFO5U9mPGikIYCzK0SaThypfGgS6bHqrUGXG3DPHCrb+txNqeEcns1W0lkGfk0rCyNXm7xB9rMxnCiZOoA==
graceful-fs@^4.1.6, graceful-fs@^4.2.0:
version "4.2.11"
resolved "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3"
@ -1920,11 +2185,21 @@ isexe@^2.0.0:
resolved "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10"
integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==
ismobilejs@^1.1.0:
version "1.1.1"
resolved "https://registry.npmmirror.com/ismobilejs/-/ismobilejs-1.1.1.tgz#c56ca0ae8e52b24ca0f22ba5ef3215a2ddbbaa0e"
integrity sha512-VaFW53yt8QO61k2WJui0dHf4SlL8lxBofUuUmwBo0ljPk0Drz2TiuDW4jo3wDcv41qy/SxrJ+VAzJ/qYqsmzRw==
isobject@^3.0.1:
version "3.0.1"
resolved "https://registry.npmmirror.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df"
integrity sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==
js-base64@^3.7.5:
version "3.7.5"
resolved "https://registry.npmmirror.com/js-base64/-/js-base64-3.7.5.tgz#21e24cf6b886f76d6f5f165bfcd69cc55b9e3fca"
integrity sha512-3MEt5DTINKqfScXKfJFrRbxkrnk2AxPWGBL/ycjz4dK8iqiSJ06UxD8jh8xuh6p10TX4t2+7FsBYVxxQbMg+qA==
js-yaml@^4.1.0:
version "4.1.0"
resolved "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602"
@ -2346,6 +2621,47 @@ pinia@^2.0.11:
"@vue/devtools-api" "^6.5.0"
vue-demi ">=0.14.5"
pixi-viewport@^5.0.1:
version "5.0.1"
resolved "https://registry.npmmirror.com/pixi-viewport/-/pixi-viewport-5.0.1.tgz#42e3934bd1535c4e60a5b95d09d0cf00bd673917"
integrity sha512-fIILU9xztqGnhGF5SYfjn1Rir/7asWkJ8zSUay2hwzPrdGTWFtB4yiIlZDeFaLf7KHA04RRb2kI01Sy1kNksAw==
pixi.js@^7.2.4:
version "7.2.4"
resolved "https://registry.npmmirror.com/pixi.js/-/pixi.js-7.2.4.tgz#4cd6776bf7f74a6c5e121dd1b59329e66be2ce49"
integrity sha512-nBH60meoLnHxoMFz17HoMxXS4uJpG5jwIdL+Gx2S11TzWgP3iKF+/WLOTrkSdyuQoQSdIBxVqpnYii0Wiox15A==
dependencies:
"@pixi/accessibility" "7.2.4"
"@pixi/app" "7.2.4"
"@pixi/assets" "7.2.4"
"@pixi/compressed-textures" "7.2.4"
"@pixi/core" "7.2.4"
"@pixi/display" "7.2.4"
"@pixi/events" "7.2.4"
"@pixi/extensions" "7.2.4"
"@pixi/extract" "7.2.4"
"@pixi/filter-alpha" "7.2.4"
"@pixi/filter-blur" "7.2.4"
"@pixi/filter-color-matrix" "7.2.4"
"@pixi/filter-displacement" "7.2.4"
"@pixi/filter-fxaa" "7.2.4"
"@pixi/filter-noise" "7.2.4"
"@pixi/graphics" "7.2.4"
"@pixi/mesh" "7.2.4"
"@pixi/mesh-extras" "7.2.4"
"@pixi/mixin-cache-as-bitmap" "7.2.4"
"@pixi/mixin-get-child-by-name" "7.2.4"
"@pixi/mixin-get-global-position" "7.2.4"
"@pixi/particle-container" "7.2.4"
"@pixi/prepare" "7.2.4"
"@pixi/sprite" "7.2.4"
"@pixi/sprite-animated" "7.2.4"
"@pixi/sprite-tiling" "7.2.4"
"@pixi/spritesheet" "7.2.4"
"@pixi/text" "7.2.4"
"@pixi/text-bitmap" "7.2.4"
"@pixi/text-html" "7.2.4"
postcss-selector-parser@^6.0.9:
version "6.0.13"
resolved "https://registry.npmmirror.com/postcss-selector-parser/-/postcss-selector-parser-6.0.13.tgz#d05d8d76b1e8e173257ef9d60b706a8e5e99bf1b"
@ -2396,6 +2712,11 @@ proxy-from-env@^1.1.0:
resolved "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
punycode@1.3.2:
version "1.3.2"
resolved "https://registry.npmmirror.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d"
integrity sha512-RofWgt/7fL5wP1Y7fxE7/EmTLzQVnB0ycyibJ0OOHIlJqTNzglYFxVwETOcIoJqJmpDXJ9xImDv+Fq34F/d4Dw==
punycode@^2.1.0:
version "2.3.0"
resolved "https://registry.npmmirror.com/punycode/-/punycode-2.3.0.tgz#f67fa67c94da8f4d0cfff981aee4118064199b8f"
@ -2413,6 +2734,11 @@ quasar@^2.6.0:
resolved "https://registry.npmmirror.com/quasar/-/quasar-2.12.0.tgz#f145ad2b677a0925ea9ca6a3b44b5502be1cbd87"
integrity sha512-B8xoeOWNs/Iv7M+FGRvXGYI1qDnJH8AtIb7RiP+zMfMkBcEp+6HJHU/9ODPemC4yteDjO+HPX2f7OhNZKgsPIw==
querystring@0.2.0:
version "0.2.0"
resolved "https://registry.npmmirror.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620"
integrity sha512-X/xY82scca2tau62i9mDyU9K+I+djTMUsvwf7xnUX5GLvVzgJybOJf4Y6o9Zx3oJK/LSXg5tTZBjwzqVPaPO2g==
queue-microtask@^1.2.2:
version "1.2.3"
resolved "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243"
@ -2893,6 +3219,14 @@ uri-js@^4.2.2:
dependencies:
punycode "^2.1.0"
url@^0.11.0:
version "0.11.0"
resolved "https://registry.npmmirror.com/url/-/url-0.11.0.tgz#3838e97cfc60521eb73c525a8e55bfdd9e2e28f1"
integrity sha512-kbailJa29QrtXnxgq+DdCEGlbTeYM2eJUxsz6vjZavrCYPMIFHMKQmSKYAIuUK2i7hgPm28a8piX5NTUtM/LKQ==
dependencies:
punycode "1.3.2"
querystring "0.2.0"
util-deprecate@^1.0.1, util-deprecate@^1.0.2, util-deprecate@~1.0.1:
version "1.0.2"
resolved "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"