import { BLEND_MODES, DisplayAssetType, GameObject, GameObjectBase, GameObjectBaseType, GameObjectData, rgbStrToHex, } from '@gedit/render-engine/lib/common'; import { followKeyType } from '../mixins'; import { fixPIXIParticlesBug } from './pixi-particles-bug-fix'; import { fixCanvasTextSystem, fixPIXIAssetsLoader } from './pixi-bug-fix'; // export * from './GraphicsResource'; export * from './ease-func-utils'; export * from './pixi-bug-fix'; export * from './mars-player'; const { navigator } = window || {}; const u = navigator.userAgent; export const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; export function getBackgroundConfig( rgbStr: string ): { backgroundColor: number; backgroundAlpha: number; } { // 完全toumin if (!rgbStr) return { backgroundColor: 0, backgroundAlpha: 0, }; const rgba: number[] = rgbStr .match(/^rgba?\(([^)]+)\)$/)![1] .split(/,\s*/) .map((item: string) => parseFloat(item)); return { backgroundColor: (rgba[0] << 16) + (rgba[1] << 8) + (rgba[2] | 0), backgroundAlpha: rgba[3] ?? 1, }; } export function setGameObjectEffect( target: PIXI.Sprite | any, data: GameObjectData ): void { const effect = data.effect; if (effect) { if (target.tint) { const tint = rgbStrToHex(effect.tint) ?? 0xffffff; if (target.tint !== tint) { target.tint = tint; } } } if (data.blendMode) { target.blendMode = data.blendMode; } } const graphicsType: string[] = [ GameObjectBaseType.RECTANGLE, GameObjectBaseType.PATH, GameObjectBaseType.STAR, GameObjectBaseType.POLYGON, GameObjectBaseType.TRIANGLE, GameObjectBaseType.CIRCLE, ]; export function setGameObjectBaseData( obj: GameObject, data: GameObjectData, ignoreSize?: boolean, ignoreEffect?: boolean, isContainer?: boolean ): void { const target = obj.rendererObject as any; if (!target || target.destroyed) return; const { position, origin, scale, rotation, size, opacity, flip, skew, follow, } = data; if (position) { // follow 状态下 if (follow && obj.followPos && follow.open) { follow.type?.forEach(c => { const key = followKeyType[c] as 'x' | 'y'; position[key] = obj.followPos?.[key] || position[key]; }); } target.x = position.x; target.y = position.y; } if (rotation !== undefined) { target.rotation = rotation; } if (opacity !== undefined) { target.alpha = opacity; } if (!ignoreSize && size) { target.width = size.width; target.height = size.height; } let scaleX = 1; let scaleY = 1; if (scale) { scaleX = scale.x; scaleY = scale.y; } if (skew) { target.skew.set(skew.x, skew.y); } if (flip) { scaleX = flip.x ? -scaleX : scaleX; scaleY = flip.y ? -scaleY : scaleY; } if (target.scale !== undefined) { target.scale.set(scaleX, scaleY); } if (origin && target.anchor) { const originX = flip?.x ? 1 - origin.x : origin.x; const originY = flip?.y ? 1 - origin.y : origin.y; if (graphicsType.includes(data.displayType)) { const targetWidth = target.width / scaleX; const targetHeight = target.height / scaleY; // 形状是 size 变动,有描边,,边框会变大,所以要减去差值 const diffX = (targetWidth - (obj.width || size?.width || targetWidth)) / 2 / targetWidth; const diffY = (targetHeight - (obj.height || size?.height || targetHeight)) / 2 / targetHeight; const sizeScaleX = targetWidth / (obj.width || size?.width || targetWidth); const sizeScaleY = targetHeight / (obj.height || size?.height || targetHeight); target.anchor.set( originX / sizeScaleX + diffX, originY / sizeScaleY + diffY ); } else { target.anchor.set(originX, originY); } } if (origin && isContainer && data.id !== 'root') { // 组件里子级移动,场景里的实例宽高没有更新,使用 pixi 的 _localBoundsRect; // 组件与组不支持镜像 const { localBounds = { with: target.width, height: target.height }, } = target._localBoundsCacheData; // console.log(data.size?.width, localBounds.width, origin); // 需要保证宽高不为0 // 否则会导致计算错误为 NaN const width = localBounds.width || data.size?.width || 0; const height = localBounds.height || data.size?.height || 0; (target as PIXI.Container).pivot.set( localBounds.x + origin.x * width, localBounds.y + origin.y * height ); data.size = { ...data.size, width, height, }; } if (origin && data.displayType === 'spine') { const spineObject = target.children[0]; const { x, y, width, height } = spineObject.skeleton.data; const pivotX = x + width * origin.x; const pivotY = -y - height * origin.y; spineObject.pivot.set(pivotX, pivotY); } if (!ignoreEffect) { setGameObjectEffect(target, data); } target.id = data.id; target.label = obj.name; } export function isPixiRenderer(obj?: any): boolean { return !!obj && 'localTransform' in obj && 'worldTransform' in obj; } export function getVisible(data: GameObjectData, obj: GameObjectBase): boolean { const canvasHide = data.canvasHide === undefined ? true : !data.canvasHide; const visible = obj.visible === undefined ? true : !!obj.visible; return canvasHide && visible; } // https://github.com/pixijs/particle-emitter/blob/master/src/behaviors/PathMovement.ts // 输入框先拦,免得报错 const MATH_FUNCS = [ 'E', 'LN2', 'LN10', 'LOG2E', 'LOG10E', 'PI', 'SQRT1_2', 'SQRT2', 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'atan2', 'cbrt', 'ceil', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'hypot', 'log', 'log1p', 'log10', 'log2', 'max', 'min', 'pow', 'random', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', ]; const rep = new RegExp(`(${MATH_FUNCS.join('|')})`, 'ig'); const domPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); const parsePathNode = (path: any) => { if (typeof path === 'string') { if (path.charAt(0).match(/m/i)) { domPath.setAttributeNS(null, 'd', path); return domPath; } return document.querySelector(path); } else if (path.style) { return path; } throw new Error('Error while parsing the path'); }; export const parsePath = (pathString: string): ((x: number) => number) => { const isSvgPath = pathString.match(/[(\s+|,)\w]{10,}/); if (isSvgPath) { const pathNode = parsePathNode(pathString); const pathLength = pathNode.getTotalLength(); const rect = 100; // path 的大小,100 * 100, const lengthPixel = 100; // 线上取点像素,默认分为 200 段。。 const points: any[] = []; for (let i = 0; i < lengthPixel - 1; i++) { points.push( pathNode.getPointAtLength((pathLength / (lengthPixel - 1)) * i) ); } points.push(pathNode.getPointAtLength(lengthPixel)); // eslint-disable-next-line return function (r: number) { // @ts-ignore const { agePercent } = this; const timePointX = rect * agePercent; const point = points.filter(item => item.x >= timePointX)[0] || pathNode.getPointAtLength(agePercent * pathLength); return point.y * (r / timePointX); }; } /** * 先替换 Math. 再添加回去,保证 Math.cos 和 cos 都能成为 Math.cos; */ const path = pathString.replace(/Math\./gi, '').replace(rep, 'Math.$1'); // eslint-disable-next-line no-new-func return new Function('x', `return ${path};`) as (x: number) => number; }; export function addTexture( app: PIXI.Application, resourceKey: string, uri: string, type: DisplayAssetType, data?: any ): void { if (type === DisplayAssetType.AUDIO || type === DisplayAssetType.VIDEO) { const v = type === DisplayAssetType.AUDIO ? 3 : 4; // 音乐只支持 mp3 const url = uri.match(/http(s?)\:\/\//) && uri.indexOf(`.mp${v}`) === -1 ? `${uri}/a.mp${v}` : uri; PIXI.Assets.add({ alias: resourceKey, src: url, data }); /* if (!app.loader.resources.dddd) { app.loader.add({ loadType: PIXI.LoaderResource.LOAD_TYPE.AUDIO, key: 'dddd', url: 'https://mass-office.alipay.com/yuyan_jehgkw/afts/file/dCMtSqryTu0AAAAAAAAAABAAFpV3AQBr' }); console.log(app.loader); } */ } else if (type === DisplayAssetType.IMAGE) { PIXI.Assets.add({ alias: resourceKey, src: uri, data, }); } else { // TODO 后续要考虑json模式 PIXI.Assets.add({ // xhrType: PIXI.LoaderResource.XHR_RESPONSE_TYPE.BLOB, alias: resourceKey, src: uri, data, }); } } const addButtonToContainer = () => { Object.defineProperty(PIXI.Container.prototype, 'buttonMode', { get: function (): boolean { return this.cursor === 'pointer'; }, set: function (value?: boolean): void { this.cursor = value ? 'pointer' : 'default'; }, }); }; let bugFix = false; export const fixPIXIBug = () => { if (bugFix) return; bugFix = true; // @ts-ignore PIXI.BLEND_MODES = BLEND_MODES; fixPIXIParticlesBug(); fixPIXIAssetsLoader(); fixCanvasTextSystem(); addButtonToContainer(); }; export const createVideoView = () => { const videoView = document.createElement('div'); videoView.style.position = 'absolute'; videoView.style.left = '0'; videoView.style.top = '0'; videoView.style.width = '0'; videoView.style.height = '0'; videoView.style.pointerEvents = 'none'; videoView.style.zIndex = '-99999'; videoView.style.opacity = '0'; return videoView; };