diff --git a/.gitignore b/.gitignore index b5711fbed..b2fe613fb 100644 --- a/.gitignore +++ b/.gitignore @@ -148,7 +148,14 @@ cython_debug/ tmp .history .DS_Store +main/feedback-backend/data +main/feedback-backend/.env +main/feedback-backend/.env.* +!main/feedback-backend/.env.example +main/xiaozhi-server/docker-compose.test.override.yml main/xiaozhi-server/data +main/xiaozhi-server/data-test +main/xiaozhi-server/mysql-test main/xiaozhi-server/.claude main/manager-web/node_modules @@ -177,6 +184,8 @@ main/manager-web/.webpack_cache/ main/xiaozhi-server/mysql uploadfile *.json +!main/feedback-h5/resources/**/*.json +!main/feedback-backend/admin-ui/resources/**/*.json .vscode .cursor diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..be893ed4a --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,47 @@ +# CLAUDE.md + +## 反馈后台公网部署前置信息 + +`feedback-admin.new123.vip` 不是在公网服务器本机托管静态文件;公网服务器只做 Nginx 反向代理。 + +当前目标链路: + +```text +浏览器 + -> https://feedback-admin.new123.vip/admin/ + -> 公网服务器 Nginx(ubuntu@100.66.236.1,配置 /etc/nginx/sites-enabled/new123.vip) + -> Tailscale 到本地 Windows:100.116.124.21:8007 + -> 本地 Docker 容器 feedback-h5 + -> 挂载的本仓库 main/feedback-backend/admin-ui +``` + +API 与后台 AI 数字人长连接也走同一条 Tailscale 链路: + +```text +https://feedback-admin.new123.vip/api/v1/* -> http://100.116.124.21:8007/api/v1/* +wss://feedback-admin.new123.vip/api/v1/agent/chat/ws -> http://100.116.124.21:8007/api/v1/agent/chat/ws +``` + +本地关键服务: + +- Windows Tailscale IP:`100.116.124.21`(机器名 `kobe-wins-book`) +- 公网服务器 Tailscale IP:`100.66.236.1`(SSH:`ubuntu@100.66.236.1`) +- 本地入口容器:`feedback-h5`,宿主机端口 `8007` +- Compose 文件:`main/xiaozhi-server/docker-compose_all.yml` +- `feedback-h5` 必须挂载:`../feedback-backend/admin-ui:/feedback-backend/admin-ui` + +注意:不要再把 admin 静态文件发布到公网服务器 `/var/www/feedback-admin/admin-ui/`。该目录已清空,避免占用服务器磁盘和干扰线上调试。修改后台页面时,改本地仓库并确保 `feedback-h5` 容器重建/已挂载即可。 + +常用检查: + +```powershell +docker ps --format "{{.Names}}\t{{.Ports}}" +docker inspect feedback-h5 --format '{{json .Mounts}}' +docker compose -f "main/xiaozhi-server/docker-compose_all.yml" up -d --force-recreate feedback-h5 +``` + +远端检查: + +```bash +ssh ubuntu@100.66.236.1 "sudo nginx -t && sudo nginx -T | grep -nE 'feedback-admin|100.116.124.21|/admin/|/api/v1/'" +``` diff --git a/docs/ai-voice-component-extraction-plan.md b/docs/ai-voice-component-extraction-plan.md new file mode 100644 index 000000000..bb08ff5b3 --- /dev/null +++ b/docs/ai-voice-component-extraction-plan.md @@ -0,0 +1,204 @@ +# AI 语音数字人 H5 组件抽取方案 + +## 目标 + +将当前 `feedback-h5` 中的 AI 语音对话能力抽成独立组件,后续可被多个业务复用: + +- 客户反馈 H5 +- 后台 AI 数字人助手 +- CRM 建档助手 +- 产品/套餐咨询助手 +- 其他门店经营助手 + +组件只负责“对话体验”,不关心 CRM、反馈、员工 KPI 等业务细节。 + +## 当前耦合点 + +当前 `feedback-h5` 同时承担: + +1. 门店服务码查询。 +2. 员工选择。 +3. 设备初始化/OTA。 +4. WebSocket 语音连接。 +5. 音频采集/Opus 编码。 +6. 音频播放/Opus 解码。 +7. Live2D 数字人展示。 +8. 反馈业务流程。 +9. 点评生成和发布跳转。 + +其中真正应该抽成通用组件的是: + +```text +音频采集 +音频播放 +WebSocket 对话协议 +Live2D 展示 +消息状态管理 +数字人说话/停顿/表情 +``` + +业务方只注入: + +```text +会话配置 +用户上下文 +系统提示词/业务指令 +onMessage 回调 +onResult 回调 +``` + +## 建议目录结构 + +```text +main/ai-voice-widget/ +├── README.md +├── index.html # 独立演示页 +├── src/ +│ ├── voice-widget.js # 对外主入口 +│ ├── voice-session.js # WebSocket 会话管理 +│ ├── audio-recorder.js # 录音/Opus 编码 +│ ├── audio-player.js # 播放/Opus 解码 +│ ├── live2d-avatar.js # Live2D 适配层 +│ ├── protocol.js # 消息协议封装 +│ └── styles.css # 组件样式 +├── adapters/ +│ ├── feedback-adapter.js # 客户反馈业务适配 +│ ├── admin-agent-adapter.js # 后台 AI 助手适配 +│ └── crm-profile-adapter.js # CRM 建档助手适配 +└── resources/ # 可选:Live2D 模型资源,或由业务方传入 +``` + +## 对外 API 设计 + +```js +import { createVoiceWidget } from './src/voice-widget.js'; + +const widget = createVoiceWidget({ + container: '#voiceWidget', + wsUrl: 'wss://example.com/ws', + model: { + type: 'live2d', + name: 'hiyori_pro_zh', + basePath: '/resources/hiyori_pro_zh/' + }, + session: { + storeId: 'store001', + employeeId: 'emp001', + memberId: 'member001', + mode: 'crm-profile' + }, + prompts: { + system: '你是门店CRM建档助手', + opening: '您好,我来帮您完善客户档案。' + }, + onMessage(message) { + console.log('message', message); + }, + onFinal(result) { + console.log('structured result', result); + }, + onError(error) { + console.error(error); + } +}); + +await widget.start(); +``` + +## 与业务解耦后的事件 + +组件只抛事件: + +```text +ready +connected +disconnected +user_speech_start +user_speech_end +assistant_speech_start +assistant_speech_end +message +structured_result +error +``` + +业务方自己决定如何处理: + +```text +保存反馈 +创建客户 +更新客户档案 +创建建议 +创建问题 +消费套餐 +``` + +## 后台 AI 数字人的落地方式 + +后台当前已经有文本对话版 AI 助手。后续可以把输入层替换为: + +```text +VoiceWidget + ↓ structured_result / message +/agent/chat + ↓ Agent Graph +Skill / CLI / CRM API +``` + +即: + +```text +数字人只是交互壳 +Agent Graph 负责思考和编排 +CLI/API 负责执行系统操作 +``` + +## CRM 建档助手示例 + +用户说: + +```text +她叫张女士,38岁,手机号尾号1234,主要是肩颈酸痛,睡眠不好,买了养生减肥10次套餐。 +``` + +语音组件产出文本,Agent Graph 解析为计划: + +```json +[ + {"skill": "crm.member-list", "args": {"keyword": "1234"}}, + {"skill": "crm.member-create-or-update", "args": {"name": "张女士", "age": 38, "healthIssues": ["肩颈酸痛", "睡眠不好"]}}, + {"skill": "crm.product-list", "args": {"keyword": "养生减肥"}}, + {"skill": "crm.product-purchase", "args": {"totalCount": 10}} +] +``` + +高风险或资产变动步骤进入确认: + +```text +我将为张女士关联“养生减肥10次套餐”,是否确认? +``` + +## 当前建议的产品方向 + +门店核心不应以“到店记录/账户流水”为中心,而应以: + +```text +客户档案 +身体状态变化 +已购产品/套餐 +套餐剩余次数/金额 +累计消费金额 +建议/问题闭环 +``` + +到店记录和账户流水仍保留,但降级为支撑数据,不作为店长主视角。 + +## 下一步拆分计划 + +1. 从 `feedback-h5/js/audio-recorder.js` 抽出 `ai-voice-widget/src/audio-recorder.js`。 +2. 从 `feedback-h5/js/audio-player.js` 抽出 `ai-voice-widget/src/audio-player.js`。 +3. 从 `feedback-h5/js/live2d-manager.js` 抽出 `ai-voice-widget/src/live2d-avatar.js`。 +4. 新增 `voice-session.js` 管理 WebSocket 协议。 +5. 新增 `voice-widget.js` 作为统一入口。 +6. 用 adapter 方式接入反馈、CRM、后台 Agent。 +7. 后台 AI 助手可选择文本输入或语音数字人输入。 diff --git a/docs/crm-user-story-test-plan.md b/docs/crm-user-story-test-plan.md new file mode 100644 index 000000000..6547cf493 --- /dev/null +++ b/docs/crm-user-story-test-plan.md @@ -0,0 +1,73 @@ +# CRM 用户故事与 30 个自动化测试用例 + +## 用户故事 + +作为门店店长,我希望客户完成语音反馈后,系统能通过手机号后四位识别客户,并自动把客户反馈关联到客户档案、到店记录、建议管理、问题修复和账户流水;同时我能在统计概览中按员工查看好评、中评、差评,用作员工 KPI 管理。 + +## 验收标准 + +1. 客户档案支持麦凯66字段,且字段数为66。 +2. 可按手机号/姓名搜索客户。 +3. 客户反馈可通过手机号后四位自动匹配客户。 +4. 客户反馈可自动创建/关联到店记录,并同步满意度、员工、项目、到店时间。 +5. 反馈建议自动进入建议管理,并支持去重、采纳、处理说明。 +6. 差评/退款/销卡/投诉类反馈自动进入问题修复。 +7. 账户消费如果没填到店记录,自动关联客户最近一次到店,并同步消费金额。 +8. 店长可在统计概览看到员工好评、中评、差评 KPI,并查看评价明细。 +9. 系统提供 CLI,方便 AI Agent 管理系统。 + +## 30 个自动化测试用例 + +1. 麦凯66字段数量等于66。 +2. 麦凯66字段 key 不重复。 +3. 创建客户并写入麦凯66字段。 +4. 按手机号搜索客户。 +5. 更新客户健康档案。 +6. 创建到店记录并自动计算耗时。 +7. 到店记录返回客户姓名。 +8. 创建到店后更新客户累计到店统计。 +9. 开卡/建账户自动生成充值流水。 +10. 账户消费后剩余次数减少。 +11. 账户消费自动生成消费流水。 +12. 消费未传到店记录时自动关联最近到店。 +13. 消费金额同步回到店记录。 +14. 创建客户建议。 +15. 重复建议自动去重并增加 frequency。 +16. 采纳建议并保存处理说明。 +17. 创建问题修复记录。 +18. 标记问题已修复并自动记录修复时间。 +19. 销卡后账户状态变为已销卡。 +20. 销卡原因不满意/退款时自动生成问题。 +21. 反馈记录可绑定客户和到店记录。 +22. 员工 KPI 正确统计好/中/差评。 +23. 员工评价明细可筛选差评。 +24. 从文本中提取手机号后四位。 +25. 反馈自动通过手机号后四位匹配客户。 +26. 反馈自动创建到店记录。 +27. 反馈自动创建建议。 +28. 差评反馈自动创建问题修复。 +29. 客户详情聚合到店、账户、流水、建议、问题。 +30. CRM 看板统计客户、到店、销卡、建议、问题数量。 + +## 执行命令 + +```bash +cd main/feedback-backend +PYTHONPATH=. python -m unittest discover -s tests -v +``` + +Windows PowerShell: + +```powershell +$env:PYTHONPATH="main/feedback-backend" +python -m unittest discover -s "main/feedback-backend/tests" -v +``` + +## CLI 示例 + +```bash +python main/feedback-backend/cli.py login --username admin --password admin123 +python main/feedback-backend/cli.py --token crm overview +python main/feedback-backend/cli.py --token crm member-list --keyword 1234 +python main/feedback-backend/cli.py --token stats employee-kpi +``` diff --git a/docs/feedback-public-deployment-notes.md b/docs/feedback-public-deployment-notes.md new file mode 100644 index 000000000..08abd7052 --- /dev/null +++ b/docs/feedback-public-deployment-notes.md @@ -0,0 +1,304 @@ +# 反馈系统公网部署记录与后续建议 + +本文记录本次 `feedback.new123.vip`、`feedback-admin.new123.vip` 公网部署/排障结论,便于后续维护。 + +## 服务器与入口 + +公网服务器: + +```bash +ssh ubuntu@100.66.236.1 +``` + +公网 Nginx 配置文件: + +```text +/etc/nginx/sites-enabled/new123.vip +``` + +配置修改前建议备份到: + +```text +/etc/nginx/sites-disabled/ +``` + +常用验证命令: + +```bash +sudo nginx -t +sudo systemctl reload nginx +sudo nginx -T +``` + +## 当前域名规划 + +### H5 反馈入口 + +```text +https://feedback.new123.vip/index.html#/home +``` + +页面和静态资源仍走 `443`。 + +### H5 语音 WebSocket 与反馈 API + +由于 `443` 上公网 WebSocket/部分 API 请求出现过 `ERR_CONNECTION_CLOSED`,已新增稳定专用入口: + +```text +wss://feedback.new123.vip:8443/ws/ +https://feedback.new123.vip:8443/api/v1/... +``` + +`feedback-h5/js/api.js` 通过公网 Nginx 动态替换为: + +```js +const FEEDBACK_API_BASE = 'https://feedback.new123.vip:8443/api/v1'; +const WS_BASE = 'wss://feedback.new123.vip:8443/ws'; +``` + +8443 已在云安全组放行,Nginx 本机和公网测试均返回 WebSocket `101 Switching Protocols`。 + +### 反馈后台管理 + +```text +https://feedback-admin.new123.vip/admin/ +``` + +根路径会跳转: + +```text +https://feedback-admin.new123.vip/ -> /admin/ +``` + +后台管理现在采用“公网 Nginx + Tailscale 回源到本地 Windows”的方式,不再在公网服务器托管 admin 静态文件: + +```text +浏览器 + -> feedback-admin.new123.vip 公网 Nginx + -> Tailscale: 100.116.124.21:8007 + -> Windows 本地 Docker feedback-h5 + -> 本仓库 main/feedback-backend/admin-ui +``` + +公网服务器上旧的后台静态目录已删除/清空,避免占用磁盘和干扰调试: + +```text +/var/www/feedback-admin/admin-ui/ # 不再使用 +/var/www/feedback-admin/admin-ui.bak-* # 已清理 +``` + +后台 API 和 AI 数字人长连接也通过同一 Tailscale 入口: + +```text +https://feedback-admin.new123.vip/api/v1/... +wss://feedback-admin.new123.vip/api/v1/agent/chat/ws +``` + +公网 Nginx 的核心配置应保持为: + +```nginx +location /admin/ { + proxy_pass http://100.116.124.21:8007; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_cache off; +} + +location /api/v1/ { + proxy_pass http://100.116.124.21:8007; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_read_timeout 600s; + proxy_send_timeout 180s; + proxy_connect_timeout 30s; + proxy_buffering off; +} +``` + +本地必须保证 `feedback-h5` 容器挂载后台静态文件目录: + +```yaml +- ../feedback-backend/admin-ui:/feedback-backend/admin-ui +``` + +如果公网 admin 页面没有更新,优先检查本地容器挂载并重建: + +```powershell +docker inspect feedback-h5 --format '{{json .Mounts}}' +docker compose -f "main/xiaozhi-server/docker-compose_all.yml" up -d --force-recreate feedback-h5 +``` + + +## 后台账号与权限 + +### 超级管理员 + +```text +用户名:admin +密码:admin123 +``` + +> 建议上线后尽快修改默认密码。 + +管理员可以访问: + +- 统计概览 +- 反馈记录 +- 门店管理 +- 员工管理 +- 智能体配置 + +### 门店店长 + +店长账号默认使用门店编码首次登录,例如: + +```text +用户名:558744 +密码:558744 +``` + +首次登录会自动创建店长账号,角色为: + +```text +store_manager +``` + +并绑定门店: + +```text +store001 / 558744 / 腰妍美容养生馆 +``` + +店长登录后: + +- 可访问:统计概览、反馈记录、员工管理 +- 不可访问:门店管理、智能体配置 +- 后端接口强制按店长门店过滤,不能通过改 URL 查看其他门店数据 +- 支持在侧边栏底部修改密码 + +## 手机端适配 + +反馈后台已做移动端适配,面向店长手机登录使用: + +- 顶部汉堡菜单打开侧边栏 +- 登录页自适应手机屏幕 +- 统计卡片自动换行 +- 表格横向滚动 +- 弹窗在手机端呈底部抽屉样式 +- 统计图表使用 CSS 响应式条形/柱状图,不再使用被拉伸的 canvas + +## 已修复问题 + +### 1. WebSocket `code 1006` + +现象: + +```text +WebSocket connection failed +code=1006 +``` + +处理:新增 `8443` 专用 WebSocket 入口,并将公网 H5 的 `WS_BASE` 指向: + +```text +wss://feedback.new123.vip:8443/ws +``` + +### 2. API `ERR_CONNECTION_CLOSED` + +现象: + +```text +POST /api/v1/public/record net::ERR_CONNECTION_CLOSED +POST /api/v1/public/process net::ERR_CONNECTION_CLOSED +``` + +处理:公网 H5 的反馈 API 也切到: + +```text +https://feedback.new123.vip:8443/api/v1 +``` + +### 3. CORS 重复响应头 + +现象: + +```text +Access-Control-Allow-Origin contains multiple values +``` + +处理:调整 8443 API CORS,避免同时返回 `*` 和具体域名。 + +### 4. 后台静态资源改为 Tailscale 回源 + +历史原因:`feedback-admin` 曾错误返回 H5 首页 HTML,导致 JS 请求拿到 HTML;当时临时将反馈后台静态文件部署到公网服务器本机,并让 Nginx 的 `/admin/` 使用 `alias /var/www/feedback-admin/admin-ui/`。 + +现状:为节省公网服务器磁盘并避免本地代码与服务器静态文件不一致,`/admin/` 已改为反向代理到 Windows 本地 Tailscale 服务: + +```nginx +location /admin/ { + proxy_pass http://100.116.124.21:8007; +} +``` + +`/var/www/feedback-admin/admin-ui/` 和历史 `admin-ui.bak-*` 备份目录已清理,不再用于发布。 + +### 5. 管理后台登录 500 + +原因:`passlib==1.7.4` 与容器内 `bcrypt==5.0.0` 不兼容。 + +处理:将 `bcrypt` 固定为兼容版本: + +```text +bcrypt==4.0.1 +``` + +并在容器内降级后重启 `feedback-backend`。 + +## 后续建议 + +1. **保持本地 Tailscale 回源链路稳定** + `feedback-admin.new123.vip` 的 `/admin/`、`/api/v1/` 和后台 AI WebSocket 都通过公网 Nginx 回源到 Windows 本地 `100.116.124.21:8007`。不要再往公网服务器 `/var/www/feedback-admin/admin-ui/` 发布静态文件;该目录已清理。 + +2. **固化 Docker 镜像** + 本次有部分代码通过 `docker cp` 快速复制进容器验证。建议后续重新构建 `feedback-backend` 镜像,确保容器重建后权限逻辑和 `bcrypt==4.0.1` 不丢失。 + +3. **将公网 Nginx 配置纳入版本管理** + 当前公网 Nginx 配置在服务器 `/etc/nginx/sites-enabled/new123.vip`,建议把稳定版同步回仓库,例如维护一份 `deploy/nginx/new123.vip.conf`。 + +4. **减少 Nginx 动态 JS 替换** + 目前公网通过 Nginx 对 H5 `api.js` 做 `sub_filter` 动态替换。长期建议在前端代码中支持生产环境配置文件,例如 `/runtime-config.js` 或环境变量注入。 + +5. **后台 API 域名统一** + 当前后台页面在 `feedback-admin.new123.vip`,API 走 `feedback-admin.new123.vip:8443`。长期可考虑单独 API 子域名,例如 `feedback-api.new123.vip`,减少端口暴露。 + +6. **密码安全** + 管理员默认密码 `admin123` 和店长初始密码等于门店编码,仅适合初始化。建议上线后要求首次登录强制修改密码。 + +7. **权限继续细化** + 店长当前可以管理本门店员工。若后续需要更细权限,可继续区分只读店长、可编辑店长、区域经理等角色。 + +8. **日志与监控** + 重点关注: + +```text +/var/log/nginx/feedback-admin.access.log +/var/log/nginx/feedback-admin.error.log +/var/log/nginx/feedback-ws8443.access.log +/var/log/nginx/feedback-ws8443.error.log +``` + +以及本地容器: + +```bash +docker logs feedback-backend +``` diff --git a/feedback-appointment-558744-qr.png b/feedback-appointment-558744-qr.png new file mode 100644 index 000000000..e34064096 Binary files /dev/null and b/feedback-appointment-558744-qr.png differ diff --git a/main/README.md b/main/README.md index ed7f9bc30..4ce678d7b 100644 --- a/main/README.md +++ b/main/README.md @@ -13,6 +13,7 @@ 4. [数据流与交互机制](#4-数据流与交互机制) 5. [核心功能概要](#5-核心功能概要) 6. [部署与配置概述](#6-部署与配置概述) +7. [反馈系统公网 Admin 回源链路](#7-反馈系统公网-admin-回源链路) --- ## 1. 引言 @@ -590,3 +591,44 @@ xiaozhi-esp32-server 在全模块部署的情况下,推荐使用`manager-web`控制面板作为大多数配置任务的主要操作界面,因为它提供了一种用户友好的方式来管理由`manager-api`持久化并最终由`xiaozhi-server`使用的各项设置。 --- + +--- + +## 7. 反馈系统公网 Admin 回源链路 + +`feedback-admin.new123.vip` 采用公网 Nginx + Tailscale 回源到本地 Windows 的部署方式,公网服务器不再保存后台静态文件。 + +链路: + +```text +浏览器 + -> https://feedback-admin.new123.vip/admin/ + -> 公网服务器 Nginx(ubuntu@100.66.236.1) + -> Tailscale:100.116.124.21:8007 + -> 本地 Windows Docker 容器 feedback-h5 + -> 本仓库 main/feedback-backend/admin-ui +``` + +关键约定: + +- 公网 Nginx 配置:`/etc/nginx/sites-enabled/new123.vip` +- Windows Tailscale IP:`100.116.124.21` +- 公网服务器 Tailscale IP:`100.66.236.1` +- 本地入口容器:`feedback-h5`,宿主机端口 `8007` +- Compose 文件:`main/xiaozhi-server/docker-compose_all.yml` +- `feedback-h5` 必须挂载:`../feedback-backend/admin-ui:/feedback-backend/admin-ui` +- 公网服务器 `/var/www/feedback-admin/admin-ui/` 不再使用,历史备份目录已清理,避免占用磁盘和干扰调试。 + +后台 API 和后台 AI 数字人长连接同样走这个入口: + +```text +https://feedback-admin.new123.vip/api/v1/... +wss://feedback-admin.new123.vip/api/v1/agent/chat/ws +``` + +修改后台页面后,优先检查本地容器是否挂载了 admin-ui;必要时重建入口容器: + +```powershell +docker inspect feedback-h5 --format '{{json .Mounts}}' +docker compose -f "main/xiaozhi-server/docker-compose_all.yml" up -d --force-recreate feedback-h5 +``` diff --git a/main/ai-voice-widget/src/voice-session.js b/main/ai-voice-widget/src/voice-session.js new file mode 100644 index 000000000..8fef1e55f --- /dev/null +++ b/main/ai-voice-widget/src/voice-session.js @@ -0,0 +1,49 @@ +// AI Voice Widget - WebSocket session scaffold +// 预留给 xiaozhi/后端长连接语音通道使用。 + +export class VoiceSession { + constructor({ url, onOpen, onClose, onText, onAudio, onError } = {}) { + this.url = url; + this.ws = null; + this.onOpen = onOpen; + this.onClose = onClose; + this.onText = onText; + this.onAudio = onAudio; + this.onError = onError; + } + + connect() { + if (!this.url) throw new Error('VoiceSession url is required'); + this.ws = new WebSocket(this.url); + this.ws.binaryType = 'arraybuffer'; + this.ws.onopen = () => this.onOpen?.(); + this.ws.onclose = (e) => this.onClose?.(e); + this.ws.onerror = (e) => this.onError?.(e); + this.ws.onmessage = (event) => { + if (typeof event.data === 'string') { + let data = event.data; + try { data = JSON.parse(event.data); } catch (e) {} + this.onText?.(data); + } else { + this.onAudio?.(event.data); + } + }; + } + + sendJson(data) { + if (this.ws?.readyState === WebSocket.OPEN) { + this.ws.send(JSON.stringify(data)); + } + } + + sendBinary(data) { + if (this.ws?.readyState === WebSocket.OPEN) { + this.ws.send(data); + } + } + + close() { + try { this.ws?.close(); } catch (e) {} + this.ws = null; + } +} diff --git a/main/ai-voice-widget/src/voice-widget.js b/main/ai-voice-widget/src/voice-widget.js new file mode 100644 index 000000000..162e55335 --- /dev/null +++ b/main/ai-voice-widget/src/voice-widget.js @@ -0,0 +1,109 @@ +// AI Voice Widget - lightweight voice interaction component +// 当前版本:浏览器 ASR + speechSynthesis TTS + 状态回调;预留 VoiceSession 长连接。 + +import { VoiceSession } from './voice-session.js'; + +export function createVoiceWidget(options = {}) { + return new VoiceWidget(options); +} + +export class VoiceWidget { + constructor({ onUserText, onStatus, onReplyStart, onReplyEnd, onError, voiceEnabled = true, sessionUrl = '' } = {}) { + this.onUserText = onUserText; + this.onStatus = onStatus; + this.onReplyStart = onReplyStart; + this.onReplyEnd = onReplyEnd; + this.onError = onError; + this.voiceEnabled = voiceEnabled; + this.sessionUrl = sessionUrl; + this.recognition = null; + this.listening = false; + this.session = null; + } + + setVoiceEnabled(enabled) { + this.voiceEnabled = !!enabled; + if (!this.voiceEnabled) this.stopSpeaking(); + } + + async startListening() { + const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; + if (!SpeechRecognition) { + const err = new Error('当前浏览器不支持语音输入,请使用 Chrome/Edge,或先用文字输入。'); + this.onError?.(err); + throw err; + } + if (this.listening && this.recognition) { + this.recognition.stop(); + return; + } + this.recognition = new SpeechRecognition(); + this.recognition.lang = 'zh-CN'; + this.recognition.interimResults = true; + this.recognition.continuous = false; + this.recognition.maxAlternatives = 1; + this.listening = true; + this.onStatus?.('listening', '正在听你说话...'); + let finalText = ''; + this.recognition.onresult = (event) => { + let interim = ''; + for (let i = event.resultIndex; i < event.results.length; i++) { + const transcript = event.results[i][0].transcript; + if (event.results[i].isFinal) finalText += transcript; + else interim += transcript; + } + this.onStatus?.('listening', finalText || interim || '正在听你说话...'); + }; + this.recognition.onerror = (event) => { + this.onError?.(new Error(event.error || '语音识别失败')); + }; + this.recognition.onend = () => { + this.listening = false; + this.onStatus?.('', '待命中 · 可语音或打字'); + const text = finalText.trim(); + if (text) this.onUserText?.(text); + }; + this.recognition.start(); + } + + speak(text) { + if (!this.voiceEnabled || !window.speechSynthesis || !text) return; + this.stopSpeaking(); + const utter = new SpeechSynthesisUtterance(String(text).replace(/<[^>]+>/g, '').slice(0, 220)); + utter.lang = 'zh-CN'; + utter.rate = 1.05; + utter.pitch = 1.0; + utter.onstart = () => { + this.onStatus?.('speaking', '正在回复...'); + this.onReplyStart?.(); + }; + utter.onend = () => { + this.onStatus?.('', '待命中 · 可语音或打字'); + this.onReplyEnd?.(); + }; + window.speechSynthesis.speak(utter); + } + + stopSpeaking() { + try { window.speechSynthesis?.cancel(); } catch (e) {} + } + + connectSession() { + if (!this.sessionUrl) return null; + this.session = new VoiceSession({ + url: this.sessionUrl, + onOpen: () => this.onStatus?.('connected', '语音长连接已建立'), + onClose: () => this.onStatus?.('', '语音长连接已关闭'), + onText: (data) => this.onUserText?.(typeof data === 'string' ? data : (data.text || '')), + onError: (e) => this.onError?.(e), + }); + this.session.connect(); + return this.session; + } + + destroy() { + try { this.recognition?.stop(); } catch (e) {} + this.stopSpeaking(); + this.session?.close(); + } +} diff --git a/main/feedback-backend/.dockerignore b/main/feedback-backend/.dockerignore new file mode 100644 index 000000000..ba823b2c2 --- /dev/null +++ b/main/feedback-backend/.dockerignore @@ -0,0 +1,17 @@ +__pycache__/ +*.pyc +*.pyo +*.pyd +.Python +*.egg-info/ +.eggs/ +.pytest_cache/ +.coverage +htmlcov/ +.git/ +.gitignore +.env +data/.config.yaml +*.log +logs/ +admin-ui/__pycache__/ diff --git a/main/feedback-backend/.env.example b/main/feedback-backend/.env.example new file mode 100644 index 000000000..418108d8c --- /dev/null +++ b/main/feedback-backend/.env.example @@ -0,0 +1,13 @@ +# Feedback Backend 本机环境变量示例 +# 复制为 .env 或在 PowerShell 中设置后再启动 docker compose。 + +# 生产/测试均不要把真实密钥提交到仓库。 +FEEDBACK_LLM_PROVIDER=deepseek +FEEDBACK_LLM_API_KEY= +FEEDBACK_LLM_BASE_URL=https://api.deepseek.com/v1 +FEEDBACK_LLM_MODEL=deepseek-chat + +# 可选:覆盖默认管理员与 JWT 密钥。 +FEEDBACK_AUTH_SECRET=change-me +FEEDBACK_ADMIN_USER=admin +FEEDBACK_ADMIN_PASSWORD=admin123 diff --git a/main/feedback-backend/Dockerfile b/main/feedback-backend/Dockerfile new file mode 100644 index 000000000..360c81beb --- /dev/null +++ b/main/feedback-backend/Dockerfile @@ -0,0 +1,26 @@ +FROM python:3.10-slim + +WORKDIR /app + +# 安装系统依赖 +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc \ + default-libmysqlclient-dev \ + && rm -rf /var/lib/apt/lists/* + +# 配置 pip 镜像(国内加速) +RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ + +# 安装 Python 依赖(利用 docker 层缓存) +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# 复制项目代码 +COPY . . + +# 暴露端口 +EXPOSE 8009 + +# 生产模式启动(不带 reload,多 worker 提升稳定性与并发) +# 单 worker 时 SQLite/连接池更稳;多 worker 用于高并发。这里用 2 worker 兼顾稳定与性能 +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8009", "--workers", "1", "--log-level", "info"] diff --git a/main/feedback-backend/README.md b/main/feedback-backend/README.md new file mode 100644 index 000000000..29a0836d0 --- /dev/null +++ b/main/feedback-backend/README.md @@ -0,0 +1,198 @@ +# 反馈系统后端 (Feedback Backend) + +客户反馈系统独立后端服务,基于 **FastAPI + DDD 架构**,与 xiaozhi-server 完全解耦。 + +## 架构 + +``` +feedback-backend/ +├── app/ +│ ├── domain/ ← DDD 领域层 +│ │ ├── store/ (门店: Entity/VO/Repository接口) +│ │ ├── employee/ (员工: Entity/VO/Repository接口) +│ │ ├── feedback/ (反馈记录: Entity/VO/Repository接口) +│ │ └── agent/ (智能体配置: Entity/VO/Repository接口) +│ ├── application/ ← 应用层 (用例服务) +│ │ ├── feedback_service.py (AI 反馈处理: 3步 LLM Pipeline) +│ │ ├── stats_service.py (统计分析) +│ │ ├── store_service.py (门店 CRUD) +│ │ ├── employee_service.py (员工 CRUD) +│ │ └── agent_config_service.py(智能体配置) +│ ├── infrastructure/ ← 基础设施层 +│ │ ├── persistence/ (MySQL ORM + Repository 实现) +│ │ ├── llm/ (LLM 调用服务) +│ │ └── xiaozhi/ (xiaozhi-server 客户端) +│ ├── interfaces/ ← 接口层 (MVC Controller) +│ │ └── api/ (REST API: /api/v1/*) +│ └── shared/ ← 共享: config/exceptions/utils +├── prompts/ ← 提示词模板 +├── admin-ui/ ← 后台管理前端 (Phase C) +├── migrations/ ← Alembic 数据库迁移 +├── config.yaml ← 配置文件 +├── alembic.ini ← Alembic 配置 +├── requirements.txt +├── start.py ← 启动脚本 +└── README.md +``` + +## 快速开始 + +### 1. 安装依赖 + +```bash +cd main/feedback-backend +pip install -r requirements.txt +``` + +### 2. 创建数据库 + +```sql +CREATE DATABASE feedback_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; +``` + +### 3. 修改配置 + +编辑 `config.yaml`,修改数据库连接信息和 LLM API Key: + +```yaml +database: + host: "127.0.0.1" + port: 3306 + username: "root" + password: "你的密码" + database: "feedback_db" + +llm: + provider: "openai" + openai: + api_key: "你的API Key" +``` + +### 4. 数据库迁移 + +```bash +# 生成迁移脚本 +alembic revision --autogenerate -m "init tables" + +# 执行迁移 +alembic upgrade head +``` + +> 开发模式下,首次启动会自动创建表,可以跳过 Alembic。 + +### 5. 启动服务 + +```bash +python start.py +``` + +访问: +- API 文档: http://localhost:8009/docs +- 后台管理: http://localhost:8009/admin +- 健康检查: http://localhost:8009/health + +### 默认管理员 + +- 用户名: `admin` +- 密码: `admin123` + +> ⚠️ 首次登录后请立即修改密码! + +## API 接口 + +### 公开接口(无需认证) + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/v1/public/store/{storeCode}` | 根据编码获取门店 | +| GET | `/api/v1/public/employees/{storeId}` | 获取门店员工列表 | +| POST | `/api/v1/public/process` | AI 处理反馈 | +| POST | `/api/v1/public/record` | 保存反馈记录 | +| POST | `/api/v1/public/device-init` | 设备初始化 | + +### 认证接口 + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/api/v1/auth/login` | 管理员登录 | +| GET | `/api/v1/auth/me` | 获取当前用户 | + +### 管理接口(需要认证) + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/v1/store/list` | 门店列表 | +| POST | `/api/v1/store` | 创建门店 | +| PUT | `/api/v1/store/{id}` | 更新门店 | +| POST | `/api/v1/store/delete` | 删除门店 | +| GET | `/api/v1/employee/list` | 员工列表 | +| POST | `/api/v1/employee` | 创建员工 | +| PUT | `/api/v1/employee/{id}` | 更新员工 | +| POST | `/api/v1/employee/delete` | 删除员工 | +| GET | `/api/v1/record/list` | 反馈记录列表 | +| GET | `/api/v1/stats/overview` | 统计概览 | +| GET | `/api/v1/stats/daily` | 按天统计 | +| GET | `/api/v1/stats/by-store` | 按门店统计 | +| GET | `/api/v1/agent-config/list` | 智能体配置列表 | +| POST | `/api/v1/agent-config` | 创建智能体配置 | +| PUT | `/api/v1/agent-config/{id}` | 更新智能体配置 | + +## Docker 部署 + +在 `docker-compose_all.yml` 中添加: + +```yaml +feedback-backend: + build: + context: . + dockerfile: Dockerfile-feedback + ports: + - "8009:8009" + environment: + FEEDBACK_DB_HOST: xiaozhi-esp32-server-db + FEEDBACK_DB_PASSWORD: "123456" + FEEDBACK_LLM_API_KEY: "your-api-key" + depends_on: + - xiaozhi-esp32-server-db +``` + +## 环境变量 + +| 变量名 | 说明 | 默认值 | +|--------|------|--------| +| FEEDBACK_DB_HOST | 数据库主机 | 127.0.0.1 | +| FEEDBACK_DB_PORT | 数据库端口 | 3306 | +| FEEDBACK_DB_USER | 数据库用户 | root | +| FEEDBACK_DB_PASSWORD | 数据库密码 | 123456 | +| FEEDBACK_DB_NAME | 数据库名 | feedback_db | +| FEEDBACK_SERVER_HOST | 服务监听地址 | 0.0.0.0 | +| FEEDBACK_SERVER_PORT | 服务端口 | 8009 | +| FEEDBACK_LLM_PROVIDER | LLM 提供商 | openai | +| FEEDBACK_LLM_API_KEY | LLM API Key | - | +| FEEDBACK_LLM_BASE_URL | LLM API Base URL | - | +| FEEDBACK_LLM_MODEL | LLM 模型 | gpt-4o-mini | +| FEEDBACK_AUTH_SECRET | JWT 密钥 | (内置) | +| FEEDBACK_ADMIN_USER | 管理员用户名 | admin | +| FEEDBACK_ADMIN_PASSWORD | 管理员密码 | admin123 | +| FEEDBACK_XIAOZHI_WS_URL | xiaozhi WebSocket URL | ws://127.0.0.1:18000 | +| FEEDBACK_XIAOZHI_HTTP_URL | xiaozhi HTTP URL | http://127.0.0.1:18003 | + +## 数据库表 + +| 表名 | 说明 | +|------|------| +| feedback_store | 门店信息 | +| feedback_employee | 员工信息 | +| feedback_record | 反馈记录(含满意度) | +| agent_config | 智能体配置(对话轮次/提示词/LLM) | +| admin_user | 管理员用户 | + +## 技术栈 + +- **Web 框架**: FastAPI 0.115 +- **ORM**: SQLAlchemy 2.0 +- **数据库**: MySQL (独立数据库 feedback_db) +- **迁移**: Alembic +- **LLM**: OpenAI SDK (兼容 OpenAI 协议) +- **认证**: JWT (python-jose + passlib) +- **日志**: loguru diff --git a/main/feedback-backend/admin-ui/css/admin.css b/main/feedback-backend/admin-ui/css/admin.css new file mode 100644 index 000000000..d35d00577 --- /dev/null +++ b/main/feedback-backend/admin-ui/css/admin.css @@ -0,0 +1,427 @@ +/* ===== CSS Variables ===== */ +:root { + --primary: #4F46E5; + --primary-light: #818CF8; + --primary-dark: #3730A3; + --success: #10B981; + --warning: #F59E0B; + --danger: #EF4444; + --gray-50: #F9FAFB; + --gray-100: #F3F4F6; + --gray-200: #E5E7EB; + --gray-300: #D1D5DB; + --gray-400: #9CA3AF; + --gray-500: #6B7280; + --gray-600: #4B5563; + --gray-700: #374151; + --gray-800: #1F2937; + --gray-900: #111827; + --radius: 8px; + --shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06); + --shadow-md: 0 4px 6px rgba(0,0,0,0.07), 0 2px 4px rgba(0,0,0,0.06); +} + +/* ===== Reset ===== */ +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } +body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--gray-50); color: var(--gray-800); line-height: 1.5; } +a { color: var(--primary); text-decoration: none; } +button { cursor: pointer; font-family: inherit; } +input, select, textarea { font-family: inherit; font-size: 14px; } +table { border-collapse: collapse; width: 100%; } + +/* ===== Layout ===== */ +.layout { display: flex; min-height: 100vh; } + +/* Sidebar */ +.sidebar { + width: 220px; background: var(--gray-900); color: #fff; + display: flex; flex-direction: column; flex-shrink: 0; + position: fixed; top: 0; left: 0; bottom: 0; z-index: 100; +} +.sidebar-brand { padding: 20px; border-bottom: 1px solid var(--gray-700); } +.sidebar-brand h1 { font-size: 16px; font-weight: 600; } +.sidebar-brand p { font-size: 12px; color: var(--gray-400); margin-top: 4px; } +.sidebar-nav { flex: 1; padding: 12px 0; overflow-y: auto; } +.nav-item { + display: flex; align-items: center; gap: 10px; + padding: 10px 20px; color: var(--gray-300); font-size: 14px; + transition: all 0.15s; border-left: 3px solid transparent; +} +.nav-item:hover { background: var(--gray-800); color: #fff; } +.nav-item.active { background: var(--gray-800); color: var(--primary-light); border-left-color: var(--primary-light); } +.nav-item .icon { width: 20px; text-align: center; } +.sidebar-footer { padding: 16px 20px; border-top: 1px solid var(--gray-700); font-size: 12px; color: var(--gray-500); } +.sidebar-footer a { color: var(--gray-400); } +.sidebar-footer a:hover { color: var(--danger); } + +/* Main */ +.main { flex: 1; margin-left: 220px; } +.topbar { + background: #fff; border-bottom: 1px solid var(--gray-200); + padding: 0 24px; height: 56px; display: flex; align-items: center; justify-content: space-between; + position: sticky; top: 0; z-index: 50; +} +.topbar-title { font-size: 18px; font-weight: 600; color: var(--gray-800); } +.topbar-user { font-size: 13px; color: var(--gray-500); } +.topbar-actions { display: flex; align-items: center; gap: 12px; } +.notify-btn { position: relative; width: 36px; height: 36px; border: none; border-radius: 10px; background: var(--gray-100); font-size: 17px; } +.notify-badge { position: absolute; right: -4px; top: -4px; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 999px; background: var(--danger); color: #fff; font-size: 11px; line-height: 18px; font-weight: 800; } +.content { padding: 24px; } + +/* ===== Cards ===== */ +.card { + background: #fff; border-radius: var(--radius); box-shadow: var(--shadow); + padding: 20px; margin-bottom: 20px; +} +.card-title { font-size: 15px; font-weight: 600; color: var(--gray-800); margin-bottom: 16px; } + +/* ===== Stat Cards ===== */ +.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; } +.stat-card { + background: #fff; border-radius: var(--radius); box-shadow: var(--shadow); + padding: 20px; display: flex; align-items: center; gap: 16px; +} +.stat-icon { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 24px; } +.stat-icon.blue { background: #EEF2FF; } +.stat-icon.green { background: #ECFDF5; } +.stat-icon.yellow { background: #FFFBEB; } +.stat-icon.red { background: #FEF2F2; } +.stat-info { flex: 1; } +.stat-label { font-size: 12px; color: var(--gray-500); text-transform: uppercase; letter-spacing: 0.5px; } +.stat-value { font-size: 28px; font-weight: 700; color: var(--gray-900); margin-top: 2px; } +.stat-sub { font-size: 12px; color: var(--gray-400); margin-top: 2px; } + +/* ===== Table ===== */ +.table-wrap { overflow-x: auto; } +table th { + background: var(--gray-50); padding: 10px 12px; text-align: left; + font-size: 12px; font-weight: 600; color: var(--gray-500); text-transform: uppercase; + letter-spacing: 0.5px; border-bottom: 1px solid var(--gray-200); +} +table td { + padding: 10px 12px; font-size: 13px; color: var(--gray-700); + border-bottom: 1px solid var(--gray-100); +} +table tr:hover td { background: var(--gray-50); } + +/* ===== Buttons ===== */ +.btn { + display: inline-flex; align-items: center; gap: 6px; + padding: 8px 16px; border-radius: 6px; font-size: 13px; font-weight: 500; + border: 1px solid transparent; transition: all 0.15s; +} +.btn-primary { background: var(--primary); color: #fff; } +.btn-primary:hover { background: var(--primary-dark); } +.btn-secondary { background: #fff; color: var(--gray-700); border-color: var(--gray-300); } +.btn-secondary:hover { background: var(--gray-50); } +.btn-danger { background: var(--danger); color: #fff; } +.btn-danger:hover { background: #DC2626; } +.btn-sm { padding: 4px 10px; font-size: 12px; } +.btn-icon { padding: 6px; width: 32px; height: 32px; justify-content: center; } + +/* ===== Forms ===== */ +.form-group { margin-bottom: 16px; } +.form-label { display: block; font-size: 13px; font-weight: 500; color: var(--gray-700); margin-bottom: 6px; } +.form-input { + width: 100%; padding: 8px 12px; border: 1px solid var(--gray-300); border-radius: 6px; + font-size: 14px; color: var(--gray-800); transition: border-color 0.15s; +} +.form-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(79,70,229,0.1); } +.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; } + +/* ===== Badges ===== */ +.badge { + display: inline-block; padding: 2px 8px; border-radius: 12px; + font-size: 11px; font-weight: 600; +} +.badge-green { background: #ECFDF5; color: #059669; } +.badge-yellow { background: #FFFBEB; color: #D97706; } +.badge-red { background: #FEF2F2; color: #DC2626; } +.badge-blue { background: #EEF2FF; color: #4F46E5; } +.badge-gray { background: var(--gray-100); color: var(--gray-600); } + +/* ===== Pagination ===== */ +.pagination { display: flex; align-items: center; justify-content: space-between; margin-top: 16px; } +.pagination-info { font-size: 13px; color: var(--gray-500); } +.pagination-btns { display: flex; gap: 4px; } +.pagination-btns button { + padding: 6px 12px; border: 1px solid var(--gray-300); border-radius: 4px; + background: #fff; font-size: 13px; color: var(--gray-700); +} +.pagination-btns button:hover { background: var(--gray-50); } +.pagination-btns button.active { background: var(--primary); color: #fff; border-color: var(--primary); } +.pagination-btns button:disabled { opacity: 0.5; cursor: not-allowed; } + +/* ===== Filter Bar ===== */ +.filter-bar { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; } +.filter-bar .form-input { width: auto; min-width: 140px; } +.filter-bar select { min-width: 120px; } + +/* ===== Chart Container ===== */ +.dashboard-chart-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; } +.chart-container { width: 100%; min-height: 260px; position: relative; } +.sat-summary { display: flex; align-items: center; gap: 14px; padding: 14px; border-radius: 14px; background: linear-gradient(135deg, #EEF2FF, #F8FAFC); margin-bottom: 18px; } +.sat-total { width: 58px; height: 58px; border-radius: 18px; background: #4F46E5; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: 800; box-shadow: 0 10px 24px rgba(79,70,229,.22); } +.sat-total-label { font-size: 13px; color: var(--gray-500); } +.sat-rate { font-size: 18px; color: var(--gray-900); font-weight: 700; margin-top: 2px; } +.sat-bars { display: grid; gap: 14px; } +.sat-row-head { display: flex; align-items: center; gap: 8px; margin-bottom: 7px; font-size: 13px; } +.sat-dot { width: 10px; height: 10px; border-radius: 999px; flex-shrink: 0; } +.sat-name { color: var(--gray-700); font-weight: 600; } +.sat-num { margin-left: auto; color: var(--gray-500); font-variant-numeric: tabular-nums; } +.sat-track { height: 10px; border-radius: 999px; overflow: hidden; } +.sat-fill { height: 100%; border-radius: 999px; transition: width .35s ease; } +.trend-bars { height: 260px; display: flex; align-items: flex-end; gap: 10px; padding: 8px 2px 0; overflow-x: auto; -webkit-overflow-scrolling: touch; } +.trend-item { min-width: 38px; flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; height: 100%; } +.trend-value { height: 20px; font-size: 12px; font-weight: 700; color: var(--primary); margin-bottom: 6px; } +.trend-bar-wrap { height: 158px; width: 100%; display: flex; align-items: flex-end; justify-content: center; border-bottom: 1px solid var(--gray-200); } +.trend-bar { width: min(28px, 70%); border-radius: 10px 10px 2px 2px; background: linear-gradient(180deg, #4F46E5 0%, #818CF8 100%); box-shadow: 0 8px 16px rgba(79,70,229,.16); transition: height .35s ease; } +.trend-date { margin-top: 8px; font-size: 11px; color: var(--gray-500); white-space: nowrap; } + +/* ===== Modal ===== */ +.modal-overlay { + position: fixed; inset: 0; background: rgba(0,0,0,0.4); + display: flex; align-items: center; justify-content: center; z-index: 200; +} +.modal-card { + background: #fff; border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,0.15); + width: 90%; max-width: 500px; max-height: 90vh; overflow-y: auto; +} +.modal-header { padding: 20px 24px; border-bottom: 1px solid var(--gray-200); display: flex; justify-content: space-between; align-items: center; } +.modal-header h3 { font-size: 16px; font-weight: 600; } +.modal-body { padding: 24px; } +.modal-footer { padding: 16px 24px; border-top: 1px solid var(--gray-200); display: flex; justify-content: flex-end; gap: 8px; } +.modal-close { background: none; border: none; font-size: 20px; color: var(--gray-400); padding: 4px; } +.modal-close:hover { color: var(--gray-700); } +.notify-modal { max-width: 620px; } +.notify-item { width: 100%; display: block; text-align: left; border: 1px solid var(--gray-200); background: #fff; border-radius: 12px; padding: 12px; margin-bottom: 10px; } +.notify-item.unread { border-color: #C7D2FE; background: #EEF2FF; } +.notify-item strong { display: block; color: var(--gray-900); margin-bottom: 4px; } +.notify-item span { display: block; color: var(--gray-600); font-size: 13px; line-height: 1.5; } +.notify-item small { display: block; margin-top: 6px; color: var(--gray-400); } + +/* ===== Appointment Calendar ===== */ +.fullcalendar-box { background: #fff; border: 1px solid var(--gray-200); border-radius: 16px; padding: 12px; box-shadow: var(--shadow); } +.fc { --fc-border-color: #E5E7EB; --fc-today-bg-color: #EEF2FF; --fc-page-bg-color: #fff; font-size: 13px; } +.fc .fc-col-header-cell { background: #F8FAFC; padding: 8px 0; color: var(--gray-600); } +.fc .fc-timegrid-slot { height: 42px; } +.fc .fc-event { border: none; border-radius: 8px; padding: 2px 4px; box-shadow: 0 6px 16px rgba(79,70,229,.12); cursor: pointer; } +.fc .fc-status-pending { background: #4F46E5; color: #fff; } +.fc .fc-status-confirmed { background: #10B981; color: #fff; } +.fc .fc-status-cancelled { background: #EF4444; color: #fff; opacity: .75; } +.fc .fc-status-completed { background: #6B7280; color: #fff; } +.appointment-board { min-height: 260px; } +.appointment-range { color: var(--gray-500); font-size: 13px; margin-bottom: 12px; } +.appointment-day-summary { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; padding: 10px; background: #F8FAFC; border: 1px solid var(--gray-200); border-radius: 12px; } +.appointment-day-summary.empty { color: var(--gray-400); font-size: 13px; } +.appointment-summary-chip { border: 1px solid #C7D2FE; background: #EEF2FF; color: #3730A3; border-radius: 999px; padding: 6px 10px; font-size: 12px; cursor: pointer; } +.appointment-summary-chip:hover { background: #E0E7FF; } +.resource-calendar { display: flex; border: 1px solid var(--gray-200); border-radius: 16px; overflow: auto; max-height: 720px; background: #fff; box-shadow: var(--shadow); } +.resource-time-axis { width: 70px; flex: 0 0 70px; background: #F8FAFC; border-right: 1px solid var(--gray-200); } +.resource-corner, .resource-head { height: 44px; display: flex; align-items: center; justify-content: center; font-weight: 800; color: var(--gray-700); background: #EEF2FF; border-bottom: 1px solid var(--gray-200); position: sticky; top: 0; z-index: 3; } +.resource-time { height: var(--slot-h); padding: 6px; font-size: 12px; color: var(--gray-500); border-bottom: 1px solid var(--gray-100); } +.resource-columns { display: flex; min-width: 720px; flex: 1; } +.resource-column { min-width: 220px; flex: 1; border-right: 1px solid var(--gray-200); } +.resource-slots { position: relative; min-height: calc(var(--slot-h) * 24); } +.resource-slot { height: var(--slot-h); border-bottom: 1px solid var(--gray-100); cursor: pointer; background: linear-gradient(180deg, #fff, #fff); } +.resource-slot:hover { background: #F8FAFC; } +.resource-event { position: absolute; left: 8px; right: 8px; border-radius: 10px; padding: 8px; background: #4F46E5; color: #fff; font-size: 12px; overflow: hidden; box-shadow: 0 10px 24px rgba(79,70,229,.22); cursor: pointer; z-index: 2; } +.resource-event.status-confirmed { background: #10B981; } +.resource-event.status-cancelled { background: #EF4444; opacity: .78; } +.resource-event.status-completed { background: #6B7280; } +.resource-event span { opacity: .9; } +.calendar-day-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 14px; } +.calendar-employee-col { border: 1px solid #E0E7FF; border-radius: 14px; background: linear-gradient(180deg, #fff, #F8FAFC); overflow: hidden; box-shadow: var(--shadow); } +.calendar-employee-head { background: #EEF2FF; padding: 12px 14px; font-weight: 800; color: #3730A3; border-bottom: 1px solid #E0E7FF; } +.appointment-empty { padding: 24px; color: var(--gray-400); font-size: 13px; text-align: center; } +.appointment-event { margin: 10px; padding: 11px; border-radius: 12px; background: #EEF2FF; border-left: 4px solid var(--primary); font-size: 13px; box-shadow: 0 8px 20px rgba(79,70,229,.08); } +.appointment-event.status-confirmed { background: #ECFDF5; border-left-color: var(--success); } +.appointment-event.status-cancelled { background: #FEF2F2; border-left-color: var(--danger); opacity: .75; } +.appointment-event.status-completed { background: var(--gray-100); border-left-color: var(--gray-500); } +.appointment-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; } +.calendar-week-grid { display: grid; grid-template-columns: repeat(7, minmax(140px, 1fr)); gap: 10px; overflow-x: auto; } +.calendar-day-cell { min-height: 220px; border: 1px solid var(--gray-200); border-radius: 14px; background: #fff; padding: 10px; } +.calendar-day-head { font-weight: 800; color: var(--gray-700); margin-bottom: 8px; } +.calendar-no-event { color: var(--gray-300); font-size: 12px; padding-top: 20px; text-align: center; } +.calendar-month { border: 1px solid var(--gray-200); border-radius: 16px; overflow: hidden; background: #fff; } +.calendar-weekdays, .calendar-month-grid { display: grid; grid-template-columns: repeat(7, 1fr); } +.calendar-weekdays > div { background: #F8FAFC; padding: 10px; font-size: 12px; font-weight: 700; color: var(--gray-500); text-align: center; border-bottom: 1px solid var(--gray-200); } +.calendar-month-cell { min-height: 116px; padding: 8px; border-right: 1px solid var(--gray-100); border-bottom: 1px solid var(--gray-100); } +.calendar-month-cell.muted-month { background: #FAFAFA; opacity: .55; } +.calendar-month-date { font-weight: 800; color: var(--gray-700); margin-bottom: 6px; } +.calendar-compact-event { border-radius: 7px; background: #EEF2FF; color: #3730A3; padding: 4px 6px; font-size: 11px; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.calendar-compact-event.status-confirmed { background: #ECFDF5; color: #047857; } +.calendar-compact-event.status-cancelled { background: #FEF2F2; color: #B91C1C; } +.calendar-compact-event.status-completed { background: var(--gray-100); color: var(--gray-600); } +.calendar-compact-event span { font-weight: 700; } +.calendar-more { font-size: 11px; color: var(--gray-500); } +.slot-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 8px; } +.slot-item { border-radius: 8px; padding: 8px; font-size: 12px; border: 1px solid var(--gray-200); } +.slot-item.available { background: #ECFDF5; color: #047857; } +.slot-item.busy { background: #FEF2F2; color: #B91C1C; } + +/* ===== AI Assistant ===== */ +.ai-fab { position: fixed; right: 22px; bottom: 22px; width: 62px; height: 62px; border-radius: 999px; border: none; background: radial-gradient(circle at 30% 25%, #A5B4FC, #4F46E5 48%, #7C3AED); color: #fff; font-size: 18px; font-weight: 900; box-shadow: 0 14px 36px rgba(79,70,229,.35); z-index: 180; } +.ai-fab span { display: inline-flex; align-items: center; justify-content: center; width: 38px; height: 38px; border-radius: 999px; border: 1px solid rgba(255,255,255,.42); background: rgba(255,255,255,.12); letter-spacing: .5px; } +.ai-panel { position: fixed; right: 22px; bottom: 96px; width: 460px; max-width: calc(100vw - 24px); height: 720px; max-height: calc(100vh - 120px); background: #fff; border-radius: 22px; box-shadow: 0 24px 80px rgba(15,23,42,.28); z-index: 180; display: none; flex-direction: column; overflow: hidden; } +.ai-panel.open { display: flex; } +.ai-panel.expanded { right: 50%; bottom: 28px; transform: translateX(50%); width: min(980px, calc(100vw - 44px)); height: min(820px, calc(100vh - 56px)); } +.ai-head { padding: 14px 16px; border-bottom: 1px solid rgba(255,255,255,.18); display: flex; justify-content: space-between; align-items: center; color: #fff; background: linear-gradient(135deg, #312E81, #4F46E5 55%, #7C3AED); } +.ai-head .muted { color: rgba(255,255,255,.74); } +.ai-head-actions { display: flex; align-items: center; gap: 8px; } +.ai-icon-btn { width: 32px; height: 32px; border: 1px solid rgba(255,255,255,.28); border-radius: 10px; color: #fff; background: rgba(255,255,255,.12); font-size: 15px; } +.ai-head .modal-close { color: #fff; opacity: .9; } +.ai-stage { position: relative; height: 330px; min-height: 330px; overflow: hidden; background: radial-gradient(circle at 50% 26%, #FFE5E5 0%, transparent 56%), linear-gradient(180deg, #FFB6C1 0%, #FFC8DD 30%, #BDE0FE 72%, #A2D2FF 100%); } +.ai-panel.expanded .ai-stage { height: 58%; min-height: 420px; } +.ai-stage-bg { position: absolute; inset: 0; z-index: 0; background: linear-gradient(180deg, rgba(255,255,255,.08), rgba(15,23,42,.16)); pointer-events: none; } +.ai-live2d-canvas { position: absolute !important; inset: 0; width: 100% !important; height: 100% !important; display: block; z-index: 1; } +.ai-face { position: absolute; left: 50%; top: 45%; transform: translate(-50%, -50%); font-size: 86px; z-index: 2; transition: transform .2s ease; text-shadow: 0 12px 28px rgba(79,70,229,.22); } +.ai-face.hidden { display: none; } +.ai-avatar { position: absolute; left: 18px; bottom: 18px; width: 86px; height: 54px; border-radius: 18px; background: rgba(255,255,255,.18); display: flex; align-items: center; justify-content: center; box-shadow: 0 10px 26px rgba(79,70,229,.16); overflow: hidden; z-index: 4; backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,.28); } +.ai-avatar-ring { width: 14px; height: 14px; border-radius: 999px; background: #94A3B8; box-shadow: 0 0 0 6px rgba(148,163,184,.16); } +.ai-avatar.live2d-ready .ai-avatar-ring { background: #10B981; box-shadow: 0 0 0 6px rgba(16,185,129,.16); } +.ai-avatar.listening .ai-avatar-ring { background: #10B981; box-shadow: 0 0 0 6px rgba(16,185,129,.22); } +.ai-avatar.thinking .ai-avatar-ring { background: #F59E0B; box-shadow: 0 0 0 6px rgba(245,158,11,.22); } +.ai-avatar.speaking .ai-avatar-ring { background: #4F46E5; box-shadow: 0 0 0 6px rgba(79,70,229,.22); } +.ai-avatar.speaking .ai-face { animation: avatarTalk .45s ease-in-out infinite alternate; } +.ai-avatar.listening .ai-wave span, .ai-avatar.speaking .ai-wave span { animation: voiceWave .8s ease-in-out infinite; } +.ai-wave { position: absolute; right: 14px; bottom: 14px; display: flex; gap: 3px; align-items: flex-end; } +.ai-wave span { width: 4px; height: 8px; border-radius: 999px; background: #4F46E5; opacity: .35; } +.ai-wave span:nth-child(2) { animation-delay: .12s; } +.ai-wave span:nth-child(3) { animation-delay: .24s; } +.ai-stage-status { position: absolute; left: 116px; right: 16px; bottom: 18px; z-index: 4; display: flex; align-items: center; gap: 8px; min-height: 54px; padding: 10px 13px; color: #fff; font-size: 13px; line-height: 1.45; border-radius: 18px; background: rgba(15,23,42,.32); backdrop-filter: blur(12px); text-shadow: 0 1px 2px rgba(0,0,0,.28); } +.ai-status-dot { width: 8px; height: 8px; border-radius: 999px; background: #10B981; box-shadow: 0 0 0 5px rgba(16,185,129,.18); flex-shrink: 0; } +.ai-body { flex: 1; min-height: 0; display: flex; flex-direction: column; background: var(--gray-50); } +@keyframes avatarTalk { from { transform: scale(1); } to { transform: scale(1.08) translateY(-1px); } } +@keyframes voiceWave { 0%,100% { height: 6px; opacity: .35; } 50% { height: 18px; opacity: 1; } } +.ai-messages { flex: 1; overflow-y: auto; padding: 14px; background: linear-gradient(180deg, rgba(248,250,252,.98), #F8FAFC); } +.ai-msg { padding: 10px 12px; border-radius: 14px; margin-bottom: 10px; font-size: 13px; line-height: 1.55; word-break: break-word; box-shadow: 0 4px 14px rgba(15,23,42,.05); } +.ai-msg-bot { background: rgba(255,255,255,.92); color: var(--gray-800); border: 1px solid var(--gray-200); border-bottom-left-radius: 5px; } +.ai-msg-user { background: linear-gradient(135deg, #4F46E5, #6366F1); color: #fff; margin-left: 54px; border-bottom-right-radius: 5px; } +.ai-quick { display: flex; flex-wrap: wrap; gap: 6px; padding: 10px 12px; border-top: 1px solid var(--gray-100); background: #fff; } +.ai-quick button { border: 1px solid var(--gray-300); background: #fff; border-radius: 999px; padding: 4px 9px; font-size: 12px; color: var(--gray-700); } +.ai-input-row .btn.active, #aiLongChat.active { background: #10B981; border-color: #10B981; color: #fff; box-shadow: 0 0 0 3px rgba(16,185,129,.14); } +.ai-feedback { margin-top: 8px; display: flex; gap: 6px; font-size: 12px; color: var(--gray-500); } +.ai-feedback button { border: 1px solid var(--gray-300); background: #fff; border-radius: 999px; padding: 2px 8px; cursor: pointer; } +.ai-feedback button:hover { background: var(--gray-50); } +.ai-input-row { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--gray-200); background: #fff; } +.ai-input-row .form-input { flex: 1; } +@media (max-width: 768px) { .ai-fab { right: 14px; bottom: 14px; } .ai-panel, .ai-panel.expanded { right: 12px; bottom: 78px; transform: none; width: calc(100vw - 24px); height: 78vh; max-height: calc(100vh - 96px); } .ai-stage { height: 44%; min-height: 260px; } .ai-panel.expanded .ai-stage { height: 46%; min-height: 280px; } .ai-input-row { flex-wrap: wrap; } .ai-input-row .form-input { flex-basis: 100%; } } + +/* ===== Login Page ===== */ +.login-page { + min-height: 100vh; display: flex; align-items: center; justify-content: center; + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); +} +.login-card { + background: #fff; border-radius: 16px; box-shadow: 0 20px 60px rgba(0,0,0,0.2); + padding: 40px; width: 380px; +} +.login-card h1 { font-size: 24px; text-align: center; margin-bottom: 8px; color: var(--gray-900); } +.login-card p { text-align: center; color: var(--gray-500); margin-bottom: 32px; font-size: 14px; } +.login-card .form-input { padding: 12px; } +.login-card .btn-primary { width: 100%; padding: 12px; font-size: 15px; justify-content: center; } +.login-error { color: var(--danger); font-size: 13px; text-align: center; margin-top: 12px; min-height: 20px; } + +/* ===== Empty State ===== */ +.empty-state { text-align: center; padding: 48px 20px; color: var(--gray-400); } +.empty-state .icon { font-size: 48px; margin-bottom: 12px; } +.empty-state p { font-size: 14px; } + +/* ===== Satisfaction Stars ===== */ +.sat-4 { color: #059669; } +.sat-3 { color: #10B981; } +.sat-2 { color: #F59E0B; } +.sat-1 { color: #EF4444; } + +/* ===== Responsive ===== */ +@media (max-width: 768px) { + body { font-size: 14px; } + .layout { display: block; min-height: 100vh; } + .sidebar { + display: flex; transform: translateX(-100%); transition: transform 0.2s ease; + width: 78vw; max-width: 300px; box-shadow: 0 20px 60px rgba(0,0,0,0.35); + } + .sidebar.open { transform: translateX(0); } + .main { margin-left: 0; } + .topbar { height: 52px; padding: 0 12px; gap: 10px; } + .topbar-title { font-size: 16px; flex: 1; } + .topbar-user { max-width: 38vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .mobile-menu-btn { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border: none; background: var(--gray-100); border-radius: 8px; font-size: 20px; } + .content { padding: 12px; } + .stat-grid { grid-template-columns: 1fr 1fr; gap: 10px; } + .dashboard-chart-grid { grid-template-columns: 1fr; gap: 12px; } + .chart-container { min-height: auto; } + .trend-bars { height: 230px; gap: 8px; } + .stat-card { padding: 12px; gap: 10px; } + .stat-icon { width: 38px; height: 38px; font-size: 20px; } + .stat-value { font-size: 22px; } + .card { padding: 12px; margin-bottom: 12px; } + .form-row { grid-template-columns: 1fr; } + .filter-bar { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } + .filter-bar .form-input, .filter-bar select, .filter-bar button { width: 100% !important; min-width: 0; } + .table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; } + table { min-width: 760px; } + table th, table td { padding: 8px; font-size: 12px; } + .modal-overlay { align-items: flex-end; } + .modal-card { width: 100%; max-width: none; max-height: 92vh; border-radius: 16px 16px 0 0; } + .modal-body { padding: 16px; } + .modal-header { padding: 16px; } + .modal-footer { padding: 12px 16px; } + .login-card { width: calc(100vw - 32px); padding: 28px 20px; } +} + +@media (min-width: 769px) { + .mobile-menu-btn { display: none; } +} + +@media (max-width: 420px) { + .stat-grid { grid-template-columns: 1fr; } + .filter-bar { grid-template-columns: 1fr; } +} + +/* ===== CRM ===== */ +.crm-tabs { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; } +.crm-tab { padding: 9px 12px; border: 1px solid var(--gray-300); background: #fff; color: var(--gray-700); border-radius: 999px; font-size: 13px; } +.crm-tab:hover { background: var(--gray-50); } +.crm-tab.active { background: var(--primary); border-color: var(--primary); color: #fff; } +.muted { color: var(--gray-500); font-size: 12px; } +textarea.form-input { min-height: 86px; resize: vertical; } +.crm-detail-modal { max-width: 700px; } +.crm-detail-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; } +.member-combobox { position: relative; } +.member-manual { margin-top: 6px; font-size: 12px; } +.member-dropdown { display: none; position: absolute; left: 0; right: 0; top: 64px; z-index: 260; background: #fff; border: 1px solid var(--gray-200); border-radius: 10px; box-shadow: 0 14px 36px rgba(0,0,0,.14); max-height: 240px; overflow-y: auto; } +.member-dropdown.open { display: block; } +.member-option { padding: 9px 12px; cursor: pointer; display: flex; justify-content: space-between; gap: 10px; font-size: 13px; border-bottom: 1px solid var(--gray-100); } +.member-option:hover { background: #EEF2FF; color: var(--primary); } +.member-option.disabled { color: var(--gray-400); cursor: default; } +.member-option.disabled:hover { background: #fff; color: var(--gray-400); } +.member-option span { color: var(--gray-500); font-size: 12px; } +.crm-profile-head { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 12px; background: var(--gray-50); padding: 16px; border-radius: 8px; margin-bottom: 16px; } +.crm-detail-section { margin-bottom: 16px; } +.crm-detail-title { font-size: 13px; font-weight: 600; color: var(--gray-600); margin-bottom: 6px; padding-bottom: 4px; border-bottom: 1px solid var(--gray-100); } +.crm-detail-body { font-size: 13px; color: var(--gray-800); line-height: 1.6; } +.crm-timeline { list-style: none; padding: 0; } +.crm-timeline li { font-size: 13px; color: var(--gray-700); padding: 6px 0; border-bottom: 1px solid var(--gray-50); } +.crm-timeline li:last-child { border: none; } +.crm-pre { background: var(--gray-50); padding: 8px; border-radius: 4px; font-size: 11px; max-height: 150px; overflow-y: auto; white-space: pre-wrap; } +.crm-trend-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; } +.crm-trend-grid > div { background: var(--gray-50); border-radius: 8px; padding: 10px; font-size: 12px; color: var(--gray-500); } +.crm-trend-grid strong { color: var(--gray-900); font-size: 18px; } +.mekai66-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; max-height: 420px; overflow-y: auto; padding: 10px; background: var(--gray-50); border-radius: 8px; } +.mekai66-group { background: #fff; border: 1px solid var(--gray-200); border-radius: 8px; padding: 10px; } +.mekai66-title { font-size: 13px; font-weight: 700; color: var(--primary); margin-bottom: 8px; } +.mekai66-field { display: grid; grid-template-columns: 88px 1fr; gap: 6px; align-items: center; margin-bottom: 6px; } +.mekai66-field span { font-size: 12px; color: var(--gray-600); } +.mekai66-field .form-input { padding: 5px 8px; font-size: 12px; } + +/* ===== Detail panel ===== */ +.detail-row { display: flex; padding: 8px 0; border-bottom: 1px solid var(--gray-100); } +.detail-label { width: 100px; font-size: 13px; color: var(--gray-500); flex-shrink: 0; } +.detail-value { font-size: 13px; color: var(--gray-800); flex: 1; word-break: break-all; } + +/* ===== Loading ===== */ +.loading { text-align: center; padding: 40px; color: var(--gray-400); } +.spinner { display: inline-block; width: 24px; height: 24px; border: 3px solid var(--gray-200); border-top-color: var(--primary); border-radius: 50%; animation: spin 0.8s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } diff --git a/main/feedback-backend/admin-ui/index.html b/main/feedback-backend/admin-ui/index.html new file mode 100644 index 000000000..9754d583d --- /dev/null +++ b/main/feedback-backend/admin-ui/index.html @@ -0,0 +1,18 @@ + + + + + + 反馈系统管理后台 + + + + + + + + +
+ + + diff --git a/main/feedback-backend/admin-ui/js/admin.js b/main/feedback-backend/admin-ui/js/admin.js new file mode 100644 index 000000000..e7b69a7c7 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/admin.js @@ -0,0 +1,308 @@ +// Main Admin SPA Application +import { api } from './api.js'; +import { renderDashboard } from './pages/dashboard.js'; +import { renderRecords } from './pages/records.js?v=20260625-records-fix'; +import { renderStores } from './pages/stores.js'; +import { renderEmployees } from './pages/employees.js'; +import { renderAgentConfigs } from './pages/agent-configs.js'; +import { renderCrm } from './pages/crm.js'; +import { initAiAssistant } from './ai-assistant.js?v=20260625-longchat-default'; +import './form-copilot.js'; + +// ---- Router ---- +function getRoute() { + const hash = window.location.hash || '#/dashboard'; + const [path] = hash.substring(2).split('?'); + return path; +} + +function navigate(route) { + window.location.hash = `#/${route}`; +} + +// ---- Auth Check ---- +function isLoggedIn() { + return !!api.token; +} + +function getNavItems() { + const items = [ + { route: 'dashboard', icon: '📊', label: '统计概览' }, + { route: 'crm', icon: '💎', label: 'CRM管理' }, + { route: 'records', icon: '📋', label: '反馈记录' }, + { route: 'employees', icon: '👥', label: '员工管理' }, + ]; + if (!api.isStoreManager) { + items.splice(2, 0, { route: 'stores', icon: '🏪', label: '门店管理' }); + items.push({ route: 'agent-configs', icon: '🤖', label: '智能体配置' }); + } + return items; +} + +// ---- Render App Shell ---- +function renderApp() { + let route = getRoute(); + const app = document.getElementById('app'); + + if (!isLoggedIn()) { + renderLogin(app); + return; + } + + const username = localStorage.getItem('feedback_admin_user') || 'admin'; + const displayName = localStorage.getItem('feedback_admin_display_name') || username; + const storeName = localStorage.getItem('feedback_admin_store_name') || ''; + const navItems = getNavItems(); + if (!navItems.some(i => i.route === route)) { + route = 'dashboard'; + window.location.hash = '#/dashboard'; + } + + app.innerHTML = ` +
+ +
+
+ +
${navItems.find(i => i.route === route)?.label || ''}
+
+ +
${escapeHtml(displayName)}
+
+
+
+
+
`; + + document.getElementById('logoutLink').addEventListener('click', (e) => { + e.preventDefault(); + api.logout(); + renderApp(); + }); + document.getElementById('changePasswordLink').addEventListener('click', (e) => { + e.preventDefault(); + showChangePasswordDialog(); + }); + document.getElementById('mobileMenuBtn')?.addEventListener('click', () => { + document.getElementById('sidebar')?.classList.toggle('open'); + }); + document.querySelectorAll('.nav-item').forEach(a => { + a.addEventListener('click', () => document.getElementById('sidebar')?.classList.remove('open')); + }); + + initAiAssistant(); + document.getElementById('notifyBtn')?.addEventListener('click', showNotificationsDialog); + loadNotificationBadge(); + + const content = document.getElementById('pageContent'); + switch (route) { + case 'dashboard': renderDashboard(content); break; + case 'crm': renderCrm(content); break; + case 'records': renderRecords(content); break; + case 'stores': renderStores(content); break; + case 'employees': renderEmployees(content); break; + case 'agent-configs': renderAgentConfigs(content); break; + default: renderDashboard(content); + } +} + +async function loadNotificationBadge() { + try { + const res = await api.getNotifications('page=1&page_size=5&status=unread'); + const unread = res.data?.unread || 0; + const badge = document.getElementById('notifyBadge'); + if (badge) { + badge.textContent = unread > 99 ? '99+' : String(unread); + badge.style.display = unread > 0 ? '' : 'none'; + } + } catch (e) {} +} + +async function showNotificationsDialog() { + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + document.getElementById('notifyClose').addEventListener('click', close); + document.getElementById('notifyReadAll').addEventListener('click', async () => { + await api.markAllNotificationsRead(); + await loadNotificationBadge(); + close(); + }); + try { + const res = await api.getNotifications('page=1&page_size=30'); + const list = res.data?.list || []; + document.getElementById('notifyBody').innerHTML = list.length ? list.map(n => ` + `).join('') : '
暂无通知
'; + document.querySelectorAll('.notify-item').forEach(btn => { + btn.addEventListener('click', async () => { + await api.markNotificationRead(btn.dataset.id); + await loadNotificationBadge(); + close(); + if (btn.dataset.route === 'crm:appointments') { + window.location.hash = '#/crm?tab=appointments'; + } + }); + }); + } catch (e) { + document.getElementById('notifyBody').innerHTML = `
加载通知失败:${escapeHtml(e.message || '')}
`; + } +} + +// ---- Login Page ---- +function renderLogin(container) { + container.innerHTML = ` + `; + + const doLogin = async () => { + const u = document.getElementById('loginUser').value.trim(); + const p = document.getElementById('loginPass').value; + const errEl = document.getElementById('loginError'); + errEl.textContent = ''; + try { + await api.login(u, p); + renderApp(); + } catch (e) { + errEl.textContent = '用户名或密码错误'; + } + }; + + document.getElementById('loginBtn').addEventListener('click', doLogin); + document.getElementById('loginPass').addEventListener('keyup', (e) => { + if (e.key === 'Enter') doLogin(); + }); +} + +function showChangePasswordDialog() { + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + document.getElementById('closePwd').addEventListener('click', close); + document.getElementById('cancelPwd').addEventListener('click', close); + document.getElementById('savePwd').addEventListener('click', async () => { + const oldPwd = document.getElementById('oldPwd').value; + const newPwd = document.getElementById('newPwd').value; + const newPwd2 = document.getElementById('newPwd2').value; + const err = document.getElementById('pwdError'); + err.textContent = ''; + if (newPwd.length < 6) { err.textContent = '新密码至少 6 位'; return; } + if (newPwd !== newPwd2) { err.textContent = '两次新密码不一致'; return; } + try { + await api.changePassword(oldPwd, newPwd); + alert('密码已修改,请重新登录'); + api.logout(); + close(); + renderApp(); + } catch (e) { + err.textContent = e.message || '修改失败'; + } + }); +} + +// ---- Helpers (global) ---- +window.escapeHtml = function(s) { + if (!s) return ''; + return String(s).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); +}; + +window.formatDate = function(d) { + if (!d) return '-'; + return d.replace('T', ' ').substring(0, 19); +}; + +window.satisfactionBadge = function(s) { + const map = { + very_satisfied: { label: '非常满意', cls: 'badge-green' }, + satisfied: { label: '满意', cls: 'badge-green' }, + unsatisfied: { label: '不满意', cls: 'badge-yellow' }, + very_bad: { label: '很差', cls: 'badge-red' }, + }; + const info = map[s] || { label: s || '-', cls: 'badge-gray' }; + return `${info.label}`; +}; + +window.statusBadge = function(s) { + return s === 1 + ? '启用' + : '禁用'; +}; + +window.employeeTypeBadge = function(t) { + const map = { + manager: { label: '店长', cls: 'badge-blue' }, + excellent: { label: '优秀员工', cls: 'badge-green' }, + intern: { label: '实习生', cls: 'badge-yellow' }, + normal: { label: '普通员工', cls: 'badge-gray' }, + }; + const info = map[t] || { label: t, cls: 'badge-gray' }; + return `${info.label}`; +}; + +window.truncate = function(s, len = 50) { + if (!s) return '-'; + return s.length > len ? s.substring(0, len) + '...' : s; +}; + +// ---- Init ---- +window.addEventListener('hashchange', renderApp); +window.addEventListener('load', renderApp); diff --git a/main/feedback-backend/admin-ui/js/ai-assistant.js b/main/feedback-backend/admin-ui/js/ai-assistant.js new file mode 100644 index 000000000..3357c6922 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/ai-assistant.js @@ -0,0 +1,441 @@ +// AI 数字人助手 - 长连接持续对话数字人 +import { api } from './api.js'; +import { createVoiceWidget } from './voice-widget/voice-widget.js?v=20260625-longchat-default'; + +let lastUserMessage = ''; +let lastAgentResult = null; +let voiceEnabled = true; +let voiceWidget = null; +let longChatEnabled = true; +let sending = false; +let live2dReady = false; +let live2dInitializing = false; +let sessionConnected = false; +let reconnectTimer = null; +let reconnectAttempts = 0; +const pendingMessages = []; +const conversationHistory = []; + +export function initAiAssistant() { + if (document.getElementById('aiAssistantFab')) return; + const box = document.createElement('div'); + box.innerHTML = ` + +
+
+
+ AI门店数字人 +
待命中 · 可语音或打字
+
+
+ + +
+
+
+ +
+
🤖
+
+
+
+
+
+ + 像客户反馈数字人一样,持续听你说话并帮你操作 CRM +
+
+
+
+
你好,我是门店AI数字人。你可以直接说:
创建客户常玉亮手机号13020109833
创建产品冰蚕乌酒价格50
明天下午2点约李爱媛做乌蛇
查客户尾号9833套餐还剩几次
+
+
+ + + + +
+
+ + + + + +
+
+
`; + document.body.appendChild(box); + + const panel = document.getElementById('aiAssistantPanel'); + const fab = document.getElementById('aiAssistantFab'); + fab.onclick = () => { + panel.classList.toggle('open'); + if (panel.classList.contains('open')) initLive2DAvatar(); + }; + document.getElementById('aiAssistantClose').onclick = () => panel.classList.remove('open'); + document.getElementById('aiAssistantExpand').onclick = () => { + panel.classList.toggle('expanded'); + setTimeout(() => window.aiLive2dManager?.resize?.(), 80); + }; + document.getElementById('aiSend').onclick = sendAiMessage; + document.getElementById('aiMic').onclick = startSpeechInput; + document.getElementById('aiLongChat').onclick = toggleLongChat; + document.getElementById('aiVoiceToggle').onclick = () => { + voiceEnabled = !voiceEnabled; + voiceWidget?.setVoiceEnabled(voiceEnabled); + document.getElementById('aiVoiceToggle').textContent = voiceEnabled ? '🔊' : '🔇'; + }; + document.getElementById('aiInput').addEventListener('keyup', (e) => { + if (e.key === 'Enter') sendAiMessage(); + }); + document.querySelectorAll('.ai-quick button').forEach(btn => { + btn.onclick = () => { + document.getElementById('aiInput').value = btn.dataset.q; + sendAiMessage(); + }; + }); + voiceWidget = createVoiceWidget({ + voiceEnabled, + sessionUrl: buildAgentWsUrl(), + onUserText(text) { + if (!text) return; + document.getElementById('aiInput').value = text; + sendAiMessage(text, { fromVoice: true }); + }, + onSessionOpen() { + sessionConnected = true; + reconnectAttempts = 0; + }, + onSessionClose() { + sessionConnected = false; + scheduleSessionReconnect(); + }, + onSessionMessage(data) { handleSessionMessage(data); }, + onStatus(state, text) { setAiState(state, text); }, + onReplyStart() { + try { window.aiLive2dManager?.startTalking?.(); window.aiLive2dManager?.motion?.('Tap'); } catch(e) {} + }, + onReplyEnd() { try { window.aiLive2dManager?.stopTalking?.(); } catch(e) {} }, + onError(err) { showVoiceError(err); }, + }); + connectLongSession(); + initLive2DAvatar(); + startDefaultLongChat(); +} + +function startDefaultLongChat() { + const btn = document.getElementById('aiLongChat'); + longChatEnabled = true; + if (btn) { + btn.textContent = '长聊中'; + btn.classList.add('active'); + btn.title = '长聊默认开启,点击暂停'; + } + setAiState('listening', '长聊中 · 我会持续听你说话'); + if (typeof voiceWidget?.startContinuous === 'function') { + voiceWidget.startContinuous().catch((e) => { + longChatEnabled = false; + if (btn) { + btn.textContent = '长聊'; + btn.classList.remove('active'); + btn.title = '开启长聊'; + } + showVoiceError(e); + }); + } else { + longChatEnabled = false; + const msg = '语音组件版本过旧,请强制刷新页面后重试'; + if (btn) { + btn.textContent = '长聊'; + btn.classList.remove('active'); + btn.title = msg; + } + showVoiceError(new Error(msg)); + } +} + +function buildAgentWsUrl() { + const token = localStorage.getItem('feedback_admin_token') || ''; + const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const host = window.location.hostname === 'feedback-admin.new123.vip' + ? 'feedback-admin.new123.vip:8443' + : window.location.host; + const url = new URL(`${scheme}//${host}/api/v1/agent/chat/ws`); + if (token) url.searchParams.set('token', token); + return url.toString(); +} + +function connectLongSession() { + if (!voiceWidget) return; + window.clearTimeout(reconnectTimer); + reconnectTimer = null; + try { + voiceWidget.connectSession(buildAgentWsUrl()); + } catch (e) { + showVoiceError(e); + scheduleSessionReconnect(); + } +} + +function scheduleSessionReconnect() { + if (reconnectTimer || !voiceWidget) return; + const delay = Math.min(10000, 1000 * Math.max(1, ++reconnectAttempts)); + reconnectTimer = window.setTimeout(() => { + reconnectTimer = null; + connectLongSession(); + }, delay); +} + +function handleSessionMessage(data) { + if (!data) return; + if (typeof data === 'string') { + appendMessage(data, 'bot', false, true); + voiceWidget?.speak(data); + return; + } + if (data.type === 'hello') { + setAiState('', '长连接已就绪 · 可语音或打字'); + return; + } + if (data.type === 'thinking') { + removeThinking(); + appendMessage(data.text || '正在思考和查询...', 'bot', true); + setAiState('thinking', data.text || '正在思考...'); + voiceWidget?.pauseContinuous(data.text || '正在思考...'); + return; + } + if (data.type === 'reply') { + removeThinking(); + const result = data.data || {}; + lastAgentResult = result; + const reply = data.text || result.reply || '已处理'; + conversationHistory.push({ role: 'assistant', text: reply }); + appendMessage(reply, 'bot', false, true); + voiceWidget?.speak(reply); + if (result.action && window.FormCopilot?.execute(result.action)) { + const msg = '我已打开对应表单,并填入已识别的信息。请确认后保存。'; + conversationHistory.push({ role: 'assistant', text: msg }); + appendMessage(msg, 'bot'); + voiceWidget?.speak(msg); + } else if (result.route) { + appendRoute(result.route); + } + sending = false; + if (!voiceWidget?.speaking) { + setAiState(longChatEnabled ? 'listening' : '', longChatEnabled ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字'); + voiceWidget?.resumeContinuous(); + } + flushPendingMessages(); + return; + } + if (data.type === 'error') { + removeThinking(); + const msg = data.text || '长连接处理失败'; + appendMessage(msg, 'bot', false, true); + voiceWidget?.speak(msg); + sending = false; + flushPendingMessages(); + } +} + +async function initLive2DAvatar() { + if (live2dReady || live2dInitializing) return; + if (!window.Live2DManager || !window.PIXI?.live2d) return; + live2dInitializing = true; + try { + window.chatApp = window.chatApp || {}; + window.chatApp.audioPlayer = null; + const manager = new window.Live2DManager(); + window.aiLive2dManager = manager; + await manager.initializeLive2D(); + live2dReady = true; + document.getElementById('aiFallbackFace')?.classList.add('hidden'); + document.getElementById('aiAvatar')?.classList.add('live2d-ready'); + setAiState('', '数字人已就绪 · 可语音或打字'); + } catch (e) { + console.warn('[AI Live2D] 初始化失败,使用轻量头像', e); + } finally { + live2dInitializing = false; + } +} + +function setAiState(state, text) { + const avatar = document.getElementById('aiAvatar'); + const status = document.getElementById('aiStatusText'); + const stageStatus = document.getElementById('aiStageStatusText'); + if (!avatar) return; + avatar.classList.remove('listening', 'thinking', 'speaking'); + if (state) avatar.classList.add(state); + const statusText = text || (longChatEnabled ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字'); + if (status) status.textContent = statusText; + if (stageStatus) stageStatus.textContent = statusText; +} + +function showVoiceError(err) { + const msg = err?.message || String(err || '语音输入异常'); + if (['aborted', 'no-speech'].includes(msg)) return; + appendMessage(msg, 'bot', false, true); +} + +async function toggleLongChat() { + const btn = document.getElementById('aiLongChat'); + try { + if (longChatEnabled) { + longChatEnabled = false; + voiceWidget?.stopListening?.(true); + if (btn) { + btn.textContent = '长聊'; + btn.classList.remove('active'); + btn.title = '开启长聊'; + } + setAiState('', '长聊已暂停 · 可打字或点长聊继续'); + return; + } + longChatEnabled = true; + if (btn) { + btn.textContent = '长聊中'; + btn.classList.add('active'); + btn.title = '长聊默认开启,点击暂停'; + } + setAiState('listening', '长聊中 · 我会持续听你说话'); + if (typeof voiceWidget?.startContinuous !== 'function') { + throw new Error('语音组件版本过旧,请强制刷新页面后重试'); + } + await voiceWidget.startContinuous(); + } catch (e) { + longChatEnabled = false; + if (btn) { + btn.textContent = '长聊'; + btn.classList.remove('active'); + btn.title = '开启长聊'; + } + showVoiceError(e); + voiceWidget?.speak(e.message || '语音输入不可用'); + } +} + +async function startSpeechInput() { + if (longChatEnabled) { + toggleLongChat(); + return; + } + const mic = document.getElementById('aiMic'); + try { + mic.textContent = '⏺'; + await voiceWidget?.startListening(); + } catch (e) { + showVoiceError(e); + voiceWidget?.speak(e.message || '语音输入不可用'); + } finally { + setTimeout(() => { mic.textContent = '🎙️'; }, 500); + } +} + +async function sendAiMessage(forcedText = '', options = {}) { + const input = document.getElementById('aiInput'); + const text = (forcedText || input.value || '').trim(); + if (!text) return; + if (input.value.trim() === text) input.value = ''; + if (sending) { + pendingMessages.push({ text, options }); + setAiState('thinking', '已收到,上一条处理完马上继续...'); + return; + } + sending = true; + lastUserMessage = text; + conversationHistory.push({ role: 'user', text }); + appendMessage(text, 'user'); + const localReply = window.FormCopilot?.handleUserMessage(text); + if (localReply) { + conversationHistory.push({ role: 'assistant', text: localReply }); + appendMessage(localReply, 'bot', false, true); + voiceWidget?.speak(localReply); + sending = false; + flushPendingMessages(); + return; + } + voiceWidget?.pauseContinuous('正在思考...'); + setAiState('thinking', sessionConnected ? '正在通过长连接思考...' : '长连接重连中,先用普通接口处理...'); + + if (sessionConnected && voiceWidget?.sendText(text)) { + appendMessage('正在思考和查询...', 'bot', true); + return; + } + + appendMessage('正在思考和查询...', 'bot', true); + try { + const res = await api.agentChat(text, conversationHistory.slice(-12)); + removeThinking(); + const data = res.data || {}; + lastAgentResult = data; + const reply = data.reply || '已处理'; + conversationHistory.push({ role: 'assistant', text: reply }); + appendMessage(reply, 'bot', false, true); + voiceWidget?.speak(reply); + if (data.action && window.FormCopilot?.execute(data.action)) { + const msg = '我已打开对应表单,并填入已识别的信息。请确认后保存。'; + conversationHistory.push({ role: 'assistant', text: msg }); + appendMessage(msg, 'bot'); + voiceWidget?.speak(msg); + } else if (data.route) { + appendRoute(data.route); + } + } catch (e) { + removeThinking(); + const msg = `操作失败:${e.message || e}`; + appendMessage(msg, 'bot', false, true); + voiceWidget?.speak(msg); + } finally { + sending = false; + if (!voiceWidget?.speaking) { + setAiState(longChatEnabled ? 'listening' : '', longChatEnabled ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字'); + voiceWidget?.resumeContinuous(); + } + flushPendingMessages(); + } +} + +function flushPendingMessages() { + if (sending || pendingMessages.length === 0) return; + const next = pendingMessages.shift(); + setTimeout(() => sendAiMessage(next.text, next.options), 80); +} + +function appendMessage(text, who, thinking = false, feedback = false) { + const el = document.getElementById('aiMessages'); + const div = document.createElement('div'); + div.className = `ai-msg ai-msg-${who}` + (thinking ? ' ai-thinking' : ''); + div.innerHTML = escapeHtml(text).replace(/\n/g, '
') + (feedback ? '
' : ''); + el.appendChild(div); + div.querySelectorAll('[data-rate]').forEach(btn => btn.onclick = () => submitAiFeedback(btn.dataset.rate, btn)); + el.scrollTop = el.scrollHeight; +} + +async function submitAiFeedback(rating, btn) { + try { + await api.agentFeedback({ + message: lastUserMessage, + reply: lastAgentResult?.reply || '', + intent: lastAgentResult?.intent || '', + trace: lastAgentResult?.trace || [], + rating, + }); + btn.parentElement.innerHTML = rating === 'like' ? '已点赞,感谢反馈' : '已记录失败案例,我会用于复盘修复'; + } catch (e) { + btn.parentElement.innerHTML = '反馈提交失败'; + } +} + +function removeThinking() { + document.querySelectorAll('.ai-thinking').forEach(el => el.remove()); +} + +function appendRoute(route) { + const el = document.getElementById('aiMessages'); + const div = document.createElement('div'); + div.className = 'ai-msg ai-msg-bot'; + div.innerHTML = ``; + div.querySelector('button').onclick = () => { window.location.hash = `#/${route}`; }; + el.appendChild(div); + el.scrollTop = el.scrollHeight; +} diff --git a/main/feedback-backend/admin-ui/js/api.js b/main/feedback-backend/admin-ui/js/api.js new file mode 100644 index 000000000..319f1b75c --- /dev/null +++ b/main/feedback-backend/admin-ui/js/api.js @@ -0,0 +1,263 @@ +// Admin API Client +const API_BASE = window.location.hostname === 'feedback-admin.new123.vip' + ? 'https://feedback-admin.new123.vip:8443/api/v1' + : window.location.origin + '/api/v1'; + +class AdminAPI { + constructor() { + this.token = localStorage.getItem('feedback_admin_token'); + } + + // ---- Auth ---- + async login(username, password) { + const res = await fetch(`${API_BASE}/auth/login`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }) + }); + if (!res.ok) throw new Error('Login failed'); + const data = await res.json(); + this.token = data.access_token; + localStorage.setItem('feedback_admin_token', data.access_token); + localStorage.setItem('feedback_admin_user', data.username); + localStorage.setItem('feedback_admin_role', data.role || 'super_admin'); + localStorage.setItem('feedback_admin_display_name', data.display_name || data.username); + if (data.store_id) localStorage.setItem('feedback_admin_store_id', data.store_id); + else localStorage.removeItem('feedback_admin_store_id'); + if (data.store_code) localStorage.setItem('feedback_admin_store_code', data.store_code); + else localStorage.removeItem('feedback_admin_store_code'); + if (data.store_name) localStorage.setItem('feedback_admin_store_name', data.store_name); + else localStorage.removeItem('feedback_admin_store_name'); + return data; + } + + logout() { + this.token = null; + localStorage.removeItem('feedback_admin_token'); + localStorage.removeItem('feedback_admin_user'); + localStorage.removeItem('feedback_admin_role'); + localStorage.removeItem('feedback_admin_display_name'); + localStorage.removeItem('feedback_admin_store_id'); + localStorage.removeItem('feedback_admin_store_code'); + localStorage.removeItem('feedback_admin_store_name'); + } + + get role() { + return localStorage.getItem('feedback_admin_role') || 'super_admin'; + } + + get isStoreManager() { + return this.role === 'store_manager'; + } + + get storeId() { + return localStorage.getItem('feedback_admin_store_id') || ''; + } + + get headers() { + return { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${this.token}` + }; + } + + async request(url, options = {}) { + const res = await fetch(`${API_BASE}${url}`, { + ...options, + headers: { ...this.headers, ...options.headers } + }); + if (res.status === 401) { + this.logout(); + window.location.reload(); + throw new Error('Unauthorized'); + } + if (!res.ok) { + let msg = `HTTP ${res.status}`; + try { + const data = await res.json(); + msg = data.detail || data.msg || msg; + } catch (e) {} + throw new Error(msg); + } + return res.json(); + } + + async changePassword(oldPassword, newPassword) { + return this.request('/auth/change-password', { + method: 'POST', + body: JSON.stringify({ old_password: oldPassword, new_password: newPassword }) + }); + } + + // ---- Stats ---- + async getOverview(params = '') { + return this.request(`/stats/overview${params ? '?' + params : ''}`); + } + + async getDailyStats(params = '') { + return this.request(`/stats/daily${params ? '?' + params : ''}`); + } + + async getStoreStats(params = '') { + return this.request(`/stats/by-store${params ? '?' + params : ''}`); + } + + async getEmployeeKpi(params = '') { + return this.request(`/stats/employee-kpi${params ? '?' + params : ''}`); + } + + async getEmployeeRecords(params = '') { + return this.request(`/stats/employee-records${params ? '?' + params : ''}`); + } + + // ---- Records ---- + async getRecords(params = '') { + return this.request(`/record/list${params ? '?' + params : ''}`); + } + + // ---- CRM ---- + async getCrmOverview() { return this.request('/crm/overview'); } + async getMekai66Fields() { return this.request('/crm/mekai66-fields'); } + async getCrmMembers(params = '') { return this.request(`/crm/member/list${params ? '?' + params : ''}`); } + async getCrmMember(id) { return this.request(`/crm/member/${id}`); } + async createCrmMember(data) { return this.request('/crm/member', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + async updateCrmMember(id, data) { return this.request(`/crm/member/${id}`, { method: 'PUT', body: JSON.stringify({ data }) }); } + async getCrmVisits(params = '') { return this.request(`/crm/visit/list${params ? '?' + params : ''}`); } + async createCrmVisit(data) { return this.request('/crm/visit', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + async updateCrmVisit(id, data) { return this.request(`/crm/visit/${id}`, { method: 'PUT', body: JSON.stringify({ data }) }); } + async getCrmAccounts(params = '') { return this.request(`/crm/account/list${params ? '?' + params : ''}`); } + async getCrmAccountTransactions(params = '') { return this.request(`/crm/account/transactions${params ? '?' + params : ''}`); } + async createCrmAccount(data) { return this.request('/crm/account', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + async consumeCrmAccount(id, data) { return this.request(`/crm/account/${id}/consume`, { method: 'POST', body: JSON.stringify({ data }) }); } + async closeCrmCard(data) { return this.request('/crm/card-close', { method: 'POST', body: JSON.stringify({ data }) }); } + async getCrmCardCloses(params = '') { return this.request(`/crm/card-close/list${params ? '?' + params : ''}`); } + // ---- Appointment ---- + async getAppointmentCalendar(params = '') { return this.request(`/appointment/calendar${params ? '?' + params : ''}`); } + async getAppointmentAvailability(params = '') { return this.request(`/appointment/availability${params ? '?' + params : ''}`); } + async createAppointment(data) { return this.request('/appointment', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + async confirmAppointment(id, data = {}) { return this.request(`/appointment/${id}/confirm`, { method: 'POST', body: JSON.stringify({ data }) }); } + async cancelAppointment(id, data = {}) { return this.request(`/appointment/${id}/cancel`, { method: 'POST', body: JSON.stringify({ data }) }); } + async completeAppointment(id, data = {}) { return this.request(`/appointment/${id}/complete`, { method: 'POST', body: JSON.stringify({ data }) }); } + + async getCrmBodyStatuses(params = '') { return this.request(`/crm/body-status/list${params ? '?' + params : ''}`); } + async createCrmBodyStatus(data) { return this.request('/crm/body-status', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + + async getCrmProducts(params = '') { return this.request(`/crm/product/list${params ? '?' + params : ''}`); } + async createCrmProduct(data) { return this.request('/crm/product', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + async getCrmMemberProducts(params = '') { return this.request(`/crm/member-product/list${params ? '?' + params : ''}`); } + async purchaseCrmProduct(data) { return this.request('/crm/member-product/purchase', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + async consumeCrmProduct(id, data) { return this.request(`/crm/member-product/${id}/consume`, { method: 'POST', body: JSON.stringify({ data }) }); } + async getCrmProductConsumes(params = '') { return this.request(`/crm/product-consume/list${params ? '?' + params : ''}`); } + + async getCrmSuggestions(params = '') { return this.request(`/crm/suggestion/list${params ? '?' + params : ''}`); } + async createCrmSuggestion(data) { return this.request('/crm/suggestion', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + async updateCrmSuggestionStatus(id, data) { return this.request(`/crm/suggestion/${id}/status`, { method: 'POST', body: JSON.stringify({ data }) }); } + async getCrmIssues(params = '') { return this.request(`/crm/issue/list${params ? '?' + params : ''}`); } + async createCrmIssue(data) { return this.request('/crm/issue', { method: 'POST', body: JSON.stringify({ data: this.withStore(data) }) }); } + async updateCrmIssue(id, data) { return this.request(`/crm/issue/${id}`, { method: 'PUT', body: JSON.stringify({ data }) }); } + async bindCrmFeedback(id, data) { return this.request(`/crm/feedback/${id}/bind`, { method: 'POST', body: JSON.stringify({ data }) }); } + + // ---- AI Agent ---- + async agentChat(message, history = []) { + return this.request('/agent/chat', { + method: 'POST', + body: JSON.stringify({ message, history }) + }); + } + + async agentFeedback(data) { + return this.request('/agent/feedback', { + method: 'POST', + body: JSON.stringify(data) + }); + } + + // ---- Notifications ---- + async getNotifications(params = '') { + return this.request(`/notification/list${params ? '?' + params : ''}`); + } + + async markNotificationRead(id) { + return this.request(`/notification/${id}/read`, { method: 'POST' }); + } + + async markAllNotificationsRead() { + return this.request('/notification/read-all', { method: 'POST' }); + } + + withStore(data) { + if (this.isStoreManager && this.storeId && !data.storeId && !data.store_id) return { ...data, storeId: this.storeId }; + return data; + } + + // ---- Stores ---- + async getStores(params = '') { + return this.request(`/store/list${params ? '?' + params : ''}`); + } + + async createStore(data) { + return this.request('/store', { + method: 'POST', + body: JSON.stringify(data) + }); + } + + async updateStore(id, data) { + return this.request(`/store/${id}`, { + method: 'PUT', + body: JSON.stringify(data) + }); + } + + async deleteStore(id) { + return this.request(`/store/delete?store_id=${id}`, { method: 'POST' }); + } + + // ---- Employees ---- + async getEmployees(params = '') { + return this.request(`/employee/list${params ? '?' + params : ''}`); + } + + async createEmployee(data) { + return this.request('/employee', { + method: 'POST', + body: JSON.stringify(data) + }); + } + + async updateEmployee(id, data) { + return this.request(`/employee/${id}`, { + method: 'PUT', + body: JSON.stringify(data) + }); + } + + async deleteEmployee(id) { + return this.request(`/employee/delete?employee_id=${id}`, { method: 'POST' }); + } + + // ---- Agent Config ---- + async getAgentConfigs(params = '') { + return this.request(`/agent-config/list${params ? '?' + params : ''}`); + } + + async createAgentConfig(data) { + return this.request('/agent-config', { + method: 'POST', + body: JSON.stringify(data) + }); + } + + async updateAgentConfig(id, data) { + return this.request(`/agent-config/${id}`, { + method: 'PUT', + body: JSON.stringify(data) + }); + } + + async deleteAgentConfig(id) { + return this.request(`/agent-config/delete?config_id=${id}`, { method: 'POST' }); + } +} + +export const api = new AdminAPI(); diff --git a/main/feedback-backend/admin-ui/js/form-copilot.js b/main/feedback-backend/admin-ui/js/form-copilot.js new file mode 100644 index 000000000..4892513f3 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/form-copilot.js @@ -0,0 +1,189 @@ +// AI 表单助手:根据 Agent action 自动跳转、打开表单、填字段,并支持多轮修改/保存 + +const FORM_FIELD_MAP = { + 'crm.member.create': { + name: 'mName', 姓名: 'mName', + phone: 'mPhone', 手机号: 'mPhone', 电话: 'mPhone', + wechat: 'mWechat', 微信: 'mWechat', 微信号: 'mWechat', + level: 'mLevel', 客户等级: 'mLevel', 等级: 'mLevel', + health: 'mHealth', 身体: 'mHealth', 身体问题: 'mHealth', 症状: 'mHealth', + allergies: 'mAllergies', 过敏: 'mAllergies', 过敏史: 'mAllergies', + notes: 'mNotes', 备注: 'mNotes', + }, + 'crm.product.create': { + productName: 'pName', 产品名称: 'pName', 名称: 'pName', 产品: 'pName', + category: 'pCategory', 分类: 'pCategory', 类别: 'pCategory', + productType: 'pType', 类型: 'pType', + defaultCount: 'pCount', 默认次数: 'pCount', 次数: 'pCount', 数量: 'pCount', + price: 'pPrice', 价格: 'pPrice', 单价: 'pPrice', 金额: 'pPrice', + description: 'pDesc', 说明: 'pDesc', 备注: 'pDesc', + }, + 'crm.appointment.create': { + employee: 'aptEmp', 员工: 'aptEmp', 技师: 'aptEmp', + startAt: 'aptStart', 开始时间: 'aptStart', 时间: 'aptStart', 预约时间: 'aptStart', + durationMinutes: 'aptDuration', 时长: 'aptDuration', 服务时长: 'aptDuration', + notes: 'aptNotes', 备注: 'aptNotes', + }, + 'crm.body_status.create': { + weight: 'bsWeight', 体重: 'bsWeight', + waistline: 'bsWaist', 腰围: 'bsWaist', + metricName: 'bsMetricName', 标签: 'bsMetricName', 身体标签: 'bsMetricName', 指标: 'bsMetricName', + metricStatus: 'bsMetricStatus', 状态: 'bsMetricStatus', 效果: 'bsMetricStatus', + metricValue: 'bsMetricValue', 数值: 'bsMetricValue', 好转数值: 'bsMetricValue', + notes: 'bsNotes', 描述: 'bsNotes', 备注: 'bsNotes', + }, +}; + +const REQUIRED_FIELDS = { + 'crm.member.create': [ ['mName', '客户姓名'], ['mPhone', '手机号'] ], + 'crm.product.create': [ ['pName', '产品名称'], ['pPrice', '价格/单价'] ], + 'crm.appointment.create': [ ['aptMember', '客户'], ['aptEmp', '员工'], ['aptStart', '预约时间'] ], + 'crm.body_status.create': [ ['bsMember', '客户'] ], +}; + +export const FormCopilot = { + current: null, + + execute(action) { + if (!action || action.type !== 'open_form') return false; + const route = action.route || 'crm'; + if (window.location.hash !== `#/${route}`) window.location.hash = `#/${route}`; + setTimeout(() => this.openForm(action.form, action.payload || {}), 250); + return true; + }, + + openForm(form, payload) { + const forms = window.CrmForms || {}; + const fn = forms[form]; + if (!fn) { alert(`表单未注册:${form}`); return; } + this.current = { form, payload: payload || {}, openedAt: Date.now() }; + fn(payload || {}); + setTimeout(() => this.showStatus(), 200); + }, + + handleUserMessage(text) { + if (!this.current) return null; + const msg = (text || '').trim(); + if (!msg) return null; + if (/^(保存|提交|确认保存|可以保存|确定保存)$/i.test(msg)) { + const missing = this.getMissingFields(); + if (missing.length) return '还缺:' + missing.join('、') + '。请补充后再保存。'; + if (!confirm('确认保存当前表单吗?')) return '已取消保存,你可以继续修改。'; + const ok = this.submitCurrent(); + return ok ? '已帮你点击保存。' : '当前没有可提交的表单。'; + } + if (/^(还缺什么|缺什么|表单状态|填了什么)$/i.test(msg)) return this.showStatus(); + const updates = this.extractFieldUpdates(msg, this.current.form); + if (!Object.keys(updates).length) return null; + this.fill(updates); + return '已更新:' + Object.keys(updates).map(id => this.fieldLabel(id)).join('、') + '。' + this.missingHint(); + }, + + showStatus() { + const missing = this.getMissingFields(); + const filled = this.getFilledFields(); + return `当前表单:${this.current?.form || '-'}。已填:${filled.length ? filled.join('、') : '暂无'}。${missing.length ? '还缺:' + missing.join('、') : '必填项已齐,可以说“保存”。'}`; + }, + + getMissingFields() { + const list = REQUIRED_FIELDS[this.current?.form] || []; + return list.filter(([id]) => !this.getValue(id)).map(([, label]) => label); + }, + + getFilledFields() { + const map = FORM_FIELD_MAP[this.current?.form] || {}; + const seen = new Set(); + const labels = []; + Object.entries(map).forEach(([label, id]) => { + if (seen.has(id)) return; + seen.add(id); + if (this.getValue(id)) labels.push(this.fieldLabel(id)); + }); + return labels; + }, + + missingHint() { + const missing = this.getMissingFields(); + return missing.length ? `还缺:${missing.join('、')}。` : '必填项已齐,可以说“保存”。'; + }, + + fieldLabel(id) { + const labels = { + mName: '姓名', mPhone: '手机号', mWechat: '微信', mLevel: '客户等级', mHealth: '身体问题', mAllergies: '过敏', mNotes: '备注', + pName: '产品名称', pCategory: '分类', pType: '类型', pCount: '次数', pPrice: '价格', pDesc: '说明', + aptMember: '客户', aptEmp: '员工', aptStart: '预约时间', aptDuration: '时长', aptNotes: '备注', + bsMember: '客户', bsWeight: '体重', bsWaist: '腰围', bsMetricName: '身体标签', bsMetricStatus: '状态', bsMetricValue: '数值', bsNotes: '描述', + }; + return labels[id] || id; + }, + + extractFieldUpdates(text, form) { + const map = FORM_FIELD_MAP[form] || {}; + const updates = {}; + const normalized = text.replace(/改成|换成|改为|设置为|写成/g, '为'); + Object.entries(map).forEach(([key, id]) => { + const patterns = [ new RegExp(`${key}[::为是 ]+([^,,。;;]+)`), new RegExp(`把${key}[改设写]?为([^,,。;;]+)`) ]; + for (const p of patterns) { const m = normalized.match(p); if (m) { updates[id] = m[1].trim(); break; } } + }); + const phone = normalized.match(/1\d{10}/); if (phone && map.phone) updates[map.phone] = phone[0]; + const vip = normalized.match(/(VIP|vip|老客|新客)/); if (vip && map.level) updates[map.level] = vip[1].toUpperCase ? vip[1].toUpperCase() : vip[1]; + const price = normalized.match(/(?:价格|单价|金额)\D*(\d+(?:\.\d+)?)/); if (price && map.price) updates[map.price] = price[1]; + const count = normalized.match(/(?:次数|默认次数|数量)\D*(\d+)/); if (count && map.defaultCount) updates[map.defaultCount] = count[1]; + const duration = normalized.match(/(?:时长|服务时长)\D*(\d+)/); if (duration && map.durationMinutes) updates[map.durationMinutes] = duration[1]; + if (form === 'crm.product.create') { + if (/套餐/.test(normalized)) updates.pType = 'package'; + if (/实物|产品/.test(normalized)) updates.pType = 'product'; + if (/服务|项目/.test(normalized)) updates.pType = 'service'; + } + if (form === 'crm.appointment.create') { + const dt = this.parseDateTimeHint(normalized); + if (dt) updates.aptStart = dt; + } + if (form === 'crm.body_status.create') { + const status = normalized.match(/(没啥效果|有改善|有好转|明显好转)/); + if (status) updates.bsMetricStatus = status[1]; + } + return updates; + }, + + parseDateTimeHint(text) { + if (!/(今天|明天|后天|上午|下午|晚上|点)/.test(text)) return ''; + const d = new Date(); + if (text.includes('明天')) d.setDate(d.getDate() + 1); + if (text.includes('后天')) d.setDate(d.getDate() + 2); + const cn = { '一':1, '二':2, '两':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '十':10 }; + const m = text.match(/(\d{1,2}|[一二两三四五六七八九十])点/); + let hour = m ? (/^\d+$/.test(m[1]) ? Number(m[1]) : cn[m[1]] || 10) : 10; + if (text.includes('下午') && hour < 12) hour += 12; + const y = d.getFullYear(), mo = String(d.getMonth()+1).padStart(2,'0'), da = String(d.getDate()).padStart(2,'0'); + return `${y}-${mo}-${da}T${String(hour).padStart(2,'0')}:00`; + }, + + submitCurrent() { + const btn = document.getElementById('crmSave') || document.getElementById('recordCrmSave'); + if (!btn) return false; + btn.click(); + this.current = null; + return true; + }, + + fill(fields) { Object.entries(fields || {}).forEach(([id, value]) => this.setValue(id, value)); }, + getValue(id) { return document.getElementById(id)?.value?.trim() || ''; }, + setValue(id, value) { + const el = document.getElementById(id); + if (!el || value === undefined || value === null) return; + if (Array.isArray(value)) value = value.join('\n'); + if (typeof value === 'object') value = JSON.stringify(value, null, 2); + el.value = value; + el.dispatchEvent(new Event('input', { bubbles: true })); + el.dispatchEvent(new Event('change', { bubbles: true })); + }, + setMember(prefix, member) { + if (!member) return; + this.setValue(`${prefix}Member`, member.id || member.memberId || ''); + this.setValue(`${prefix}MemberManual`, member.id || member.memberId || ''); + this.setValue(`${prefix}MemberKeyword`, member.label || member.name || member.phone || ''); + }, +}; + +window.FormCopilot = FormCopilot; diff --git a/main/feedback-backend/admin-ui/js/live2d-manager.js b/main/feedback-backend/admin-ui/js/live2d-manager.js new file mode 100644 index 000000000..e5013d20f --- /dev/null +++ b/main/feedback-backend/admin-ui/js/live2d-manager.js @@ -0,0 +1,869 @@ +/** + * Live2D 管理器 + * 负责 Live2D 模型的初始化、嘴部动画控制等功能 + */ +class Live2DManager { + constructor() { + this.live2dApp = null; + this.live2dModel = null; + this.isTalking = false; + this.mouthAnimationId = null; + this.mouthParam = 'ParamMouthOpenY'; + this.audioContext = null; + this.analyser = null; + this.dataArray = null; + this.lastEmotionActionTime = null; + this.currentModelName = null; + + // 模型特定配置 + this.modelConfig = { + 'hiyori_pro_zh': { + mouthParam: 'ParamMouthOpenY', + mouthAmplitude: 1.0, + mouthThresholds: { low: 0.3, high: 0.7 }, + motionMap: { + 'FlickUp': 'FlickUp', + 'FlickDown': 'FlickDown', + 'Tap': 'Tap', + 'Tap@Body': 'Tap@Body', + 'Flick': 'Flick', + 'Flick@Body': 'Flick@Body' + } + }, + 'natori_pro_zh': { + mouthParam: 'ParamMouthOpenY', + mouthAmplitude: 1.0, + mouthThresholds: { low: 0.1, high: 0.4 }, + mouthFormParam: 'ParamMouthForm', + mouthFormAmplitude: 1.0, + mouthForm2Param: 'ParamMouthForm2', + mouthForm2Amplitude: 0.8, + motionMap: { + 'FlickUp': 'FlickUp', + 'FlickDown': 'Flick@Body', + 'Tap': 'Tap', + 'Tap@Body': 'Tap@Head', + 'Flick': 'Tap', + 'Flick@Body': 'Flick@Body' + } + } + }; + + // 情绪到动作的映射 + this.emotionToActionMap = { + 'happy': 'FlickUp', // 开心-向上轻扫动作 + 'laughing': 'FlickUp', // 大笑-向上轻扫动作 + 'funny': 'FlickUp', // 搞笑-向上轻扫动作 + 'sad': 'FlickDown', // 伤心-向下轻扫动作 + 'crying': 'FlickDown', // 哭泣-向下轻扫动作 + 'angry': 'Tap@Body', // 生气-身体点击动作 + 'surprised': 'Tap', // 惊讶-点击动作 + 'neutral': 'Flick', // 平常-轻扫动作 + 'default': 'Flick@Body' // 默认-身体轻扫动作 + }; + + // 单/双击判定配置与状态 + this._lastClickTime = 0; + this._lastClickPos = { x: 0, y: 0 }; + this._singleClickTimer = null; + this._doubleClickMs = 280; // 双击时间阈值(ms) + this._doubleClickDist = 16; // 双击允许的最大位移(px) + // 滑动判定 + this._pointerDown = false; + this._downPos = { x: 0, y: 0 }; + this._downTime = 0; + this._downArea = 'Body'; + this._movedBeyondClick = false; + this._swipeMinDist = 24; // 触发滑动的最小距离 + } + + /** + * 初始化 Live2D + */ + async initializeLive2D() { + try { + const canvas = document.getElementById('live2d-stage'); + + // 清理之前的 PIXI 应用(防止 WebGL 上下文累积) + if (this.live2dApp) { + try { + this.live2dApp.destroy(true, { children: true, texture: true }); + } catch (e) { /* 忽略清理异常 */ } + this.live2dApp = null; + this.live2dModel = null; + } + + // 供内部使用 + window.PIXI = PIXI; + + // 使用 canvas 容器尺寸(适配 max-width:480 的 H5 容器) + const canvasContainer = canvas.parentElement; + const containerW = canvasContainer ? canvasContainer.clientWidth : window.innerWidth; + const containerH = canvasContainer ? canvasContainer.clientHeight : window.innerHeight; + + // 限制 resolution 最大为 2,避免高分屏 WebGL 纹理溢出 + const resolution = Math.min(window.devicePixelRatio || 1, 2); + + this.live2dApp = new PIXI.Application({ + view: canvas, + height: containerH, + width: containerW, + resolution: resolution, + autoDensity: true, + antialias: false, + backgroundAlpha: 0, + }); + + // 加载 Live2D 模型 - 动态检测当前目录,适配不同环境 + // 获取当前HTML文件所在的目录路径 + const currentPath = window.location.pathname; + const lastSlashIndex = currentPath.lastIndexOf('/'); + const basePath = currentPath.substring(0, lastSlashIndex + 1); + + // 从 localStorage 读取上次选择的模型,如果没有则使用默认 + const savedModelName = localStorage.getItem('live2dModel') || 'hiyori_pro_zh'; + const modelFileMap = { + 'hiyori_pro_zh': 'hiyori_pro_t11.model3.json', + 'natori_pro_zh': 'natori_pro_t06.model3.json' + }; + const modelFileName = modelFileMap[savedModelName] || 'hiyori_pro_t11.model3.json'; + const modelPath = basePath + 'resources/' + savedModelName + '/runtime/' + modelFileName; + + this.live2dModel = await PIXI.live2d.Live2DModel.from(modelPath); + this.live2dApp.stage.addChild(this.live2dModel); + + // 保存当前模型名称 + this.currentModelName = savedModelName; + + // 更新下拉框显示 + const modelSelect = document.getElementById('live2dModelSelect'); + if (modelSelect) { + modelSelect.value = savedModelName; + } + + // 设置模型特定的嘴部参数名 + if (this.modelConfig[savedModelName]) { + this.mouthParam = this.modelConfig[savedModelName].mouthParam || 'ParamMouthOpenY'; + } + + const fitModelToCanvas = () => { + if (!this.live2dModel || !this.live2dApp) return; + const w = canvasContainer ? canvasContainer.clientWidth : window.innerWidth; + const h = canvasContainer ? canvasContainer.clientHeight : window.innerHeight; + this.live2dApp.renderer.resize(w, h); + const baseScale = Math.min(w / Math.max(this.live2dModel.width, 1), h / Math.max(this.live2dModel.height, 1)); + const scale = Math.max(0.38, Math.min(baseScale * 2.35, 1.25)); + this.live2dModel.scale.set(scale); + this.live2dModel.x = (w - this.live2dModel.width) * 0.5; + this.live2dModel.y = Math.max(-42, (h - this.live2dModel.height) * 0.16); + }; + fitModelToCanvas(); + + // 启用交互并监听点击命中(头部/身体等) + + this.live2dModel.interactive = true; + + + this.live2dModel.on('doublehit', (args) => { + const area = Array.isArray(args) ? args[0] : args; + + // 触发双击动作 + if (area === 'Body') { + this.motion('Flick@Body'); + } else if (area === 'Head' || area === 'Face') { + this.motion('Flick'); + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'doublehit', area }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + + }); + + this.live2dModel.on('singlehit', (args) => { + const area = Array.isArray(args) ? args[0] : args; + + // 触发单击动作 + if (area === 'Body') { + this.motion('Tap@Body'); + } else if (area === 'Head' || area === 'Face') { + this.motion('Tap'); + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'singlehit', area }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + + }); + + this.live2dModel.on('swipe', (args) => { + const area = Array.isArray(args) ? args[0] : args; + const dir = Array.isArray(args) ? args[1] : undefined; + + // 触发滑动动作 + if (area === 'Body') { + if (dir === 'up') { + this.motion('FlickUp'); + } else if (dir === 'down') { + this.motion('FlickDown'); + } + } else if (area === 'Head' || area === 'Face') { + if (dir === 'up') { + this.motion('FlickUp'); + } else if (dir === 'down') { + this.motion('FlickDown'); + } + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'swipe', area, dir }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + + }); + + // 兜底:自定义"头部/身体"命中区域 + 单/双击/滑动区分 + this.live2dModel.on('pointerdown', (event) => { + try { + const global = event.data.global; + const bounds = this.live2dModel.getBounds(); + // 仅在点击落在模型可见范围内时判定 + if (!bounds || !bounds.contains(global.x, global.y)) return; + + const relX = (global.x - bounds.x) / (bounds.width || 1); + const relY = (global.y - bounds.y) / (bounds.height || 1); + let area = ''; + // 经验阈值:模型可见矩形的上部 20% 视为"头部"区域 + if (relX >= 0.4 && relX <= 0.6) { + if (relY <= 0.15) { + area = 'Head'; + } else if (relY <= 0.23) { + area = 'Face'; + } else { + area = 'Body'; + } + } + if (area === '') { + return; + } + + // 记录按下状态用于滑动判定 + this._pointerDown = true; + this._downPos = { x: global.x, y: global.y }; + this._downTime = performance.now(); + this._downArea = area; + this._movedBeyondClick = false; + + const now = performance.now(); + const dt = now - (this._lastClickTime || 0); + const dx = global.x - (this._lastClickPos?.x || 0); + const dy = global.y - (this._lastClickPos?.y || 0); + const dist = Math.hypot(dx, dy); + + // 命中确认:仅当点击在模型上时做单/双击判断 + if (this._lastClickTime && dt <= this._doubleClickMs && dist <= this._doubleClickDist) { + // 判定为双击:取消待触发的单击事件 + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + if (typeof this.live2dModel.emit === 'function') { + this.live2dModel.emit('doublehit', [area]); + } + this._lastClickTime = 0; + this._pointerDown = false; // 双击完成,重置状态 + return; + } + + // 可能是单击:记录并延迟确认 + this._lastClickTime = now; + this._lastClickPos = { x: global.x, y: global.y }; + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + this._singleClickTimer = setTimeout(() => { + // 若在等待期间发生了移动超过阈值,则不再当作单击 + if (!this._movedBeyondClick && typeof this.live2dModel.emit === 'function') { + this.live2dModel.emit('singlehit', [area]); + } + this._singleClickTimer = null; + this._lastClickTime = 0; + }, this._doubleClickMs); + } catch (e) { + // 忽略自定义命中判断中的异常,避免影响主流程 + } + }); + + // 指针移动:用于判定是否从"点击"升级为"滑动" + this.live2dModel.on('pointermove', (event) => { + try { + if (!this._pointerDown) return; + const global = event.data.global; + const dx = global.x - this._downPos.x; + const dy = global.y - this._downPos.y; + const dist = Math.hypot(dx, dy); + + // 使用 _doubleClickDist 作为点击/滑动的判定阈值 + if (dist > this._doubleClickDist) { + this._movedBeyondClick = true; + // 若已超出点击阈值,取消可能的单击触发 + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + this._lastClickTime = 0; + } + } catch (e) { + // 忽略移动判定中的异常 + } + }); + + // 指针抬起:确认是否为滑动 + const handlePointerUp = (event) => { + try { + if (!this._pointerDown) return; + const global = (event && event.data && event.data.global) ? event.data.global : { x: this._downPos.x, y: this._downPos.y }; + const dx = global.x - this._downPos.x; + const dy = global.y - this._downPos.y; + const dist = Math.hypot(dx, dy); + + // 滑动:超过滑动最小距离则触发 swipe 事件(携带方向与区域) + if (this._movedBeyondClick && dist >= this._swipeMinDist) { + if (typeof this.live2dModel.emit === 'function') { + const dir = Math.abs(dx) >= Math.abs(dy) + ? (dx > 0 ? 'right' : 'left') + : (dy > 0 ? 'down' : 'up'); + this.live2dModel.emit('swipe', [this._downArea, dir]); + } + // 终止:不再让单击/双击触发 + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + this._lastClickTime = 0; + } + } catch (e) { + // 忽略抬起判定中的异常 + } + finally { + this._pointerDown = false; + this._movedBeyondClick = false; + } + }; + + this.live2dModel.on('pointerup', handlePointerUp); + this.live2dModel.on('pointerupoutside', handlePointerUp); + + // 添加窗口大小变化监听器,保持模型在当前 Canvas 中间显示 + this.resize = fitModelToCanvas; + window.addEventListener('resize', fitModelToCanvas); + + } catch (err) { + console.error('加载 Live2D 模型失败:', err); + } + } + + /** + * 初始化音频分析器 - 使用音频播放器的分析器节点 + */ + initializeAudioAnalyzer() { + try { + // 获取音频播放器实例 + const audioPlayer = window.chatApp?.audioPlayer; + if (!audioPlayer) { + console.debug('音频播放器未初始化,使用模拟口型动画'); + return false; + } + + // 获取音频播放器的音频上下文 + this.audioContext = audioPlayer.getAudioContext(); + if (!this.audioContext) { + console.warn('无法获取音频播放器的音频上下文'); + return false; + } + + // 创建分析器节点 + this.analyser = this.audioContext.createAnalyser(); + this.analyser.fftSize = 256; + this.dataArray = new Uint8Array(this.analyser.frequencyBinCount); + + return true; + } catch (error) { + console.error('初始化音频分析器失败:', error); + return false; + } + } + + /** + * 连接到音频播放器的输出节点 + */ + connectToAudioPlayer() { + try { + // 获取音频播放器的流上下文 + const audioPlayer = window.chatApp?.audioPlayer; + if (!audioPlayer || !audioPlayer.streamingContext) { + console.warn('音频播放器或流上下文未初始化'); + return false; + } + + // 获取音频播放器的流上下文 + const streamingContext = audioPlayer.streamingContext; + + // 获取分析器节点 + const analyser = streamingContext.getAnalyser(); + if (!analyser) { + console.warn('音频播放器尚未创建分析器节点,无法连接'); + return false; + } + + // 使用音频播放器的分析器节点 + this.analyser = analyser; + this.dataArray = new Uint8Array(this.analyser.frequencyBinCount); + return true; + } catch (error) { + console.error('连接到音频播放器失败:', error); + return false; + } + } + + /** + * 嘴部动画循环 + */ + animateMouth() { + if (!this.isTalking) return; + if (!this.live2dModel) return; + const internal = this.live2dModel && this.live2dModel.internalModel; + if (internal && internal.coreModel) { + const coreModel = internal.coreModel; + + let mouthOpenY = 0; + let mouthForm = 0; + let mouthForm2 = 0; + let average = 0; + + if (this.analyser && this.dataArray) { + this.analyser.getByteFrequencyData(this.dataArray); + average = this.dataArray.reduce((a, b) => a + b) / this.dataArray.length; + + const normalizedVolume = average / 255; + + // 获取模型特定的阈值 + let lowThreshold = 0.3; + let highThreshold = 0.7; + if (this.currentModelName && this.modelConfig[this.currentModelName]) { + lowThreshold = this.modelConfig[this.currentModelName].mouthThresholds?.low || 0.3; + highThreshold = this.modelConfig[this.currentModelName].mouthThresholds?.high || 0.7; + } + + // 使用模型特定的阈值进行映射 + let minOpenY = 0.1; + if (this.currentModelName && this.modelConfig[this.currentModelName]) { + minOpenY = this.modelConfig[this.currentModelName].mouthMinOpenY || 0.1; + } + + if (normalizedVolume < lowThreshold) { + mouthOpenY = minOpenY + Math.pow(normalizedVolume / lowThreshold, 1.5) * (0.4 - minOpenY); + } else if (normalizedVolume < highThreshold) { + mouthOpenY = 0.4 + (normalizedVolume - lowThreshold) / (highThreshold - lowThreshold) * 0.4; + } else { + mouthOpenY = 0.8 + Math.pow((normalizedVolume - highThreshold) / (1 - highThreshold), 1.2) * 0.2; + } + + // 应用模型特定的嘴部开合幅度 + let amplitudeMultiplier = 1.0; + let maxOpenY = 2.5; + if (this.currentModelName && this.modelConfig[this.currentModelName]) { + amplitudeMultiplier = this.modelConfig[this.currentModelName].mouthAmplitude; + maxOpenY = this.modelConfig[this.currentModelName].maxOpenY || 2.5; + } + mouthOpenY = mouthOpenY * amplitudeMultiplier; + mouthOpenY = Math.min(Math.max(mouthOpenY, 0), maxOpenY); + + // 计算嘴型参数(仅对支持嘴型变化的模型) + if (this.currentModelName && this.modelConfig[this.currentModelName]?.mouthFormParam) { + const config = this.modelConfig[this.currentModelName]; + const formAmplitude = config.mouthFormAmplitude || 0.5; + const form2Amplitude = config.mouthForm2Amplitude || 0; + + // 嘴型随音量变化: + // 低音量:嘴型偏"一"字(负值) + // 高音量:嘴型偏"o"字(正值) + // 音量=0时:嘴型=0(自然状态) + mouthForm = (normalizedVolume - 0.5) * 2 * formAmplitude; + mouthForm = Math.max(-formAmplitude, Math.min(formAmplitude, mouthForm)); + + // 第二嘴型参数(natori特有) + if (config.mouthForm2Param) { + mouthForm2 = (normalizedVolume - 0.3) * 2 * form2Amplitude; + mouthForm2 = Math.max(-form2Amplitude, Math.min(form2Amplitude, mouthForm2)); + } + } + + // 调试日志:每60帧输出一次(避免控制台刷屏) + if (!this._debugFrameCount) this._debugFrameCount = 0; + this._debugFrameCount++; + if (this._debugFrameCount % 60 === 1) { + console.log(`[Live2D] 模型: ${this.currentModelName || 'unknown'}, 音量: ${average?.toFixed(0)}, OpenY: ${mouthOpenY.toFixed(3)}`); + } + } + + if (!this.analyser || !this.dataArray) { + average = 80 + Math.sin(performance.now() / 90) * 48 + Math.sin(performance.now() / 37) * 18; + mouthOpenY = 0.18 + (Math.max(0, Math.min(1, average / 145)) * 0.72); + } + + // 设置嘴部开合参数 + coreModel.setParameterValueById(this.mouthParam, mouthOpenY); + + // 设置嘴型参数(仅对支持嘴型变化的模型) + if (this.currentModelName && this.modelConfig[this.currentModelName]?.mouthFormParam) { + const config = this.modelConfig[this.currentModelName]; + const formParam = config.mouthFormParam; + coreModel.setParameterValueById(formParam, mouthForm); + + // 设置第二嘴型参数(natori特有) + if (config.mouthForm2Param) { + coreModel.setParameterValueById(config.mouthForm2Param, mouthForm2); + } + } + + coreModel.update(); + } + this.mouthAnimationId = requestAnimationFrame(() => this.animateMouth()); + } + + /** + * 开始说话动画 + */ + startTalking() { + if (this.isTalking || !this.live2dModel) return; + + // 确保音频分析器已初始化 + if (!this.analyser) { + if (!this.initializeAudioAnalyzer()) { + console.debug('音频分析器初始化失败,使用模拟口型动画'); + // 即使分析器初始化失败,也启动动画(使用模拟数据) + this.isTalking = true; + this.animateMouth(); + return; + } + } + + // 连接到音频播放器输出 + if (!this.connectToAudioPlayer()) { + console.warn('无法连接到音频播放器输出,将使用模拟动画'); + } + + this.isTalking = true; + this.animateMouth(); + } + + /** + * 停止说话动画 + */ + stopTalking() { + this.isTalking = false; + if (this.mouthAnimationId) { + cancelAnimationFrame(this.mouthAnimationId); + this.mouthAnimationId = null; + } + + // 重置嘴部参数 + if (this.live2dModel) { + const internal = this.live2dModel.internalModel; + if (internal && internal.coreModel) { + const coreModel = internal.coreModel; + coreModel.setParameterValueById(this.mouthParam, 0); + coreModel.update(); + } + } + } + + /** + * 基于情绪触发动作 + * @param {string} emotion - 情绪名称 + */ + triggerEmotionAction(emotion) { + if (!this.live2dModel) return; + + // 添加冷却时间控制,避免过于频繁触发 + const now = Date.now(); + if (this.lastEmotionActionTime && now - this.lastEmotionActionTime < 5000) { // 5秒冷却时间 + return; + } + + // 根据情绪获取对应的动作 + const action = this.emotionToActionMap[emotion] || this.emotionToActionMap['default']; + + // 触发动作并记录时间 + this.motion(action); + this.lastEmotionActionTime = now; + } + + + + /** + * 触发模型动作(Motion) + * @param {string} name - 动作分组名称,如 'TapBody'、'FlickUp'、'Idle' 等 + */ + motion(name) { + try { + if (!this.live2dModel) return; + + // 根据当前模型获取对应的动作名称 + let actualMotionName = name; + if (this.currentModelName && this.modelConfig[this.currentModelName]) { + const motionMap = this.modelConfig[this.currentModelName].motionMap; + actualMotionName = motionMap[name] || name; + } + + this.live2dModel.motion(actualMotionName); + } catch (error) { + console.error('触发动作失败:', error); + } + } + + /** + * 设置模型交互事件 + */ + setupModelInteractions() { + if (!this.live2dModel) return; + + this.live2dModel.interactive = true; + + this.live2dModel.on('doublehit', (args) => { + const area = Array.isArray(args) ? args[0] : args; + + if (area === 'Body') { + this.motion('Flick@Body'); + } else if (area === 'Head' || area === 'Face') { + this.motion('Flick'); + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'doublehit', area }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + }); + + this.live2dModel.on('singlehit', (args) => { + const area = Array.isArray(args) ? args[0] : args; + + if (area === 'Body') { + this.motion('Tap@Body'); + } else if (area === 'Head' || area === 'Face') { + this.motion('Tap'); + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'singlehit', area }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + }); + + this.live2dModel.on('swipe', (args) => { + const area = Array.isArray(args) ? args[0] : args; + const dir = Array.isArray(args) ? args[1] : undefined; + + if (area === 'Body') { + if (dir === 'up') { + this.motion('FlickUp'); + } else if (dir === 'down') { + this.motion('FlickDown'); + } + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'swipe', area, dir }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + }); + + this.live2dModel.on('pointerdown', (event) => { + try { + const global = event.data.global; + const bounds = this.live2dModel.getBounds(); + if (!bounds || !bounds.contains(global.x, global.y)) return; + + const relX = (global.x - bounds.x) / (bounds.width || 1); + const relY = (global.y - bounds.y) / (bounds.height || 1); + let area = ''; + + if (relX >= 0.4 && relX <= 0.6) { + if (relY <= 0.15) { + area = 'Head'; + } else if (relY >= 0.7) { + area = 'Body'; + } + } + + if (!area) return; + + const now = Date.now(); + const dt = now - (this._lastClickTime || 0); + const dx = global.x - (this._lastClickPos?.x || 0); + const dy = global.y - (this._lastClickPos?.y || 0); + const dist = Math.hypot(dx, dy); + + if (this._lastClickTime && dt <= this._doubleClickMs && dist <= this._doubleClickDist) { + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + + this.live2dModel.emit('doublehit', area); + this._lastClickTime = null; + this._lastClickPos = null; + } else { + this._lastClickTime = now; + this._lastClickPos = { x: global.x, y: global.y }; + + this._singleClickTimer = setTimeout(() => { + this._singleClickTimer = null; + this.live2dModel.emit('singlehit', area); + }, this._doubleClickMs); + } + } catch (e) { + console.warn('pointerdown 处理出错:', e); + } + }); + } + + /** + * 清理资源 + */ + destroy() { + this.stopTalking(); + + // 清理音频分析器 + if (this.audioContext) { + try { this.audioContext.close(); } catch (e) {} + this.audioContext = null; + } + this.analyser = null; + this.dataArray = null; + + // 清理 Live2D 模型 + if (this.live2dModel) { + try { + this.live2dModel.interactive = false; + this.live2dModel.removeAllListeners(); + if (this.live2dApp && this.live2dApp.stage) { + this.live2dApp.stage.removeChild(this.live2dModel); + } + if (typeof this.live2dModel.destroy === 'function') { + this.live2dModel.destroy(); + } + } catch (e) { /* 忽略清理异常 */ } + this.live2dModel = null; + } + + // 清理 PIXI 应用(释放 WebGL 上下文) + if (this.live2dApp) { + try { + this.live2dApp.destroy(true, { children: true, texture: true, baseTexture: true }); + } catch (e) { /* 忽略清理异常 */ } + this.live2dApp = null; + } + } + + /** + * 切换 Live2D 模型 + * @param {string} modelName - 模型目录名称,如 'hiyori_pro_zh'、'natori_pro_zh' + * @returns {Promise} - 切换是否成功 + */ + async switchModel(modelName) { + try { + // 获取模型文件名映射 + const modelFileMap = { + 'hiyori_pro_zh': 'hiyori_pro_t11.model3.json', + 'natori_pro_zh': 'natori_pro_t06.model3.json', + 'chitose': 'chitose.model3.json', + 'haru_greeter_pro_jp': 'haru_greeter_t05.model3.json' + }; + + const modelFileName = modelFileMap[modelName]; + if (!modelFileName) { + console.error('未知的模型名称:', modelName); + return false; + } + + // 获取基础路径 + const currentPath = window.location.pathname; + const lastSlashIndex = currentPath.lastIndexOf('/'); + const basePath = currentPath.substring(0, lastSlashIndex + 1); + const modelPath = basePath + 'resources/' + modelName + '/runtime/' + modelFileName; + + // 如果已存在模型,先移除 + if (this.live2dModel) { + this.live2dApp.stage.removeChild(this.live2dModel); + this.live2dModel.destroy(); + this.live2dModel = null; + } + + // 显示加载状态 + const app = window.chatApp; + if (app) { + app.setModelLoadingStatus(true); + } + + // 加载新模型 + this.live2dModel = await PIXI.live2d.Live2DModel.from(modelPath); + this.live2dApp.stage.addChild(this.live2dModel); + + // 设置模型属性 + this.live2dModel.scale.set(0.33); + this.live2dModel.x = (window.innerWidth - this.live2dModel.width) * 0.5; + this.live2dModel.y = -50; + + // 重新绑定交互事件 + this.setupModelInteractions(); + + // 隐藏加载状态 + if (app) { + app.setModelLoadingStatus(false); + } + + // 保存当前模型名称 + this.currentModelName = modelName; + + // 设置模型特定的嘴部参数名 + if (this.modelConfig[modelName]) { + this.mouthParam = this.modelConfig[modelName].mouthParam || 'ParamMouthOpenY'; + } + + // 保存到 localStorage + localStorage.setItem('live2dModel', modelName); + + // 更新下拉框显示 + const modelSelect = document.getElementById('live2dModelSelect'); + if (modelSelect) { + modelSelect.value = modelName; + } + + console.log('模型切换成功:', modelName); + return true; + } catch (error) { + console.error('切换模型失败:', error); + const app = window.chatApp; + if (app) { + app.setModelLoadingStatus(false); + } + return false; + } + } + + +} + +// 导出全局实例 +window.Live2DManager = Live2DManager; diff --git a/main/feedback-backend/admin-ui/js/pages/agent-configs.js b/main/feedback-backend/admin-ui/js/pages/agent-configs.js new file mode 100644 index 000000000..f35be704b --- /dev/null +++ b/main/feedback-backend/admin-ui/js/pages/agent-configs.js @@ -0,0 +1,196 @@ +// Agent Configs - 智能体配置管理 +import { api } from '../api.js'; + +let currentPage = 1; +const pageSize = 20; + +export async function renderAgentConfigs(container) { + container.innerHTML = ` +
+
+
+ +
+
+ + + + + + + + + + + + + + + + +
ID配置名称智能体ID对话轮次问题数状态创建时间操作
+
+ +
`; + + document.getElementById('addConfigBtn').addEventListener('click', () => showConfigForm()); + loadConfigs(); +} + +async function loadConfigs() { + const tbody = document.getElementById('configsBody'); + if (!tbody) return; + + try { + const res = await api.getAgentConfigs(`page=${currentPage}&page_size=${pageSize}`); + const data = res.data || {}; + + if (!data.list || data.list.length === 0) { + tbody.innerHTML = '

暂无智能体配置

'; + return; + } + + tbody.innerHTML = data.list.map(c => ` + + ${escapeHtml(c.id).substring(0,8)}... + ${escapeHtml(c.agentName)} + ${escapeHtml(c.agentId || '-')} + ${c.dialogueRounds} + ${c.questions ? c.questions.length : 0} + ${statusBadge(c.status)} + ${formatDate(c.createDate)} + + + + + `).join(''); + + tbody.querySelectorAll('.edit-cfg-btn').forEach(btn => { + btn.addEventListener('click', () => { + const cfg = data.list.find(c => c.id === btn.dataset.id); + if (cfg) showConfigForm(cfg); + }); + }); + + tbody.querySelectorAll('.del-cfg-btn').forEach(btn => { + btn.addEventListener('click', async () => { + if (!confirm('确定删除该配置?')) return; + await api.deleteAgentConfig(btn.dataset.id); + loadConfigs(); + }); + }); + + const total = data.total || 0; + const totalPages = Math.ceil(total / pageSize); + document.getElementById('pagination').innerHTML = ` +
共 ${total} 条
+
+ + + +
`; + document.getElementById('prevPage')?.addEventListener('click', () => { if (currentPage > 1) { currentPage--; loadConfigs(); } }); + document.getElementById('nextPage')?.addEventListener('click', () => { if (currentPage < totalPages) { currentPage++; loadConfigs(); } }); + + } catch (e) { + tbody.innerHTML = `

加载失败: ${e.message}

`; + } +} + +function showConfigForm(config = null) { + const isEdit = !!config; + const questions = config?.questions || []; + const llmConfig = config?.llmConfig || {}; + + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + document.getElementById('closeForm').addEventListener('click', close); + document.getElementById('cancelBtn').addEventListener('click', close); + overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); }); + + document.getElementById('saveBtn').addEventListener('click', async () => { + const errEl = document.getElementById('formError'); + errEl.textContent = ''; + + const agentName = document.getElementById('formName').value.trim(); + const agentId = document.getElementById('formAgentId').value.trim() || null; + const dialogueRounds = parseInt(document.getElementById('formRounds').value) || 7; + const questionsText = document.getElementById('formQuestions').value.trim(); + const llmText = document.getElementById('formLLM').value.trim(); + + if (!agentName) { + errEl.textContent = '配置名称不能为空'; + return; + } + + const questions = questionsText ? questionsText.split('\n').map(q => q.trim()).filter(Boolean) : null; + + let llmConfig = null; + if (llmText) { + try { + llmConfig = JSON.parse(llmText); + } catch { + errEl.textContent = 'LLM 配置 JSON 格式错误'; + return; + } + } + + try { + if (isEdit) { + await api.updateAgentConfig(config.id, { + agent_name: agentName, agent_id: agentId, + dialogue_rounds: dialogueRounds, questions, llm_config: llmConfig + }); + } else { + await api.createAgentConfig({ + agent_name: agentName, agent_id: agentId, + dialogue_rounds: dialogueRounds, questions, llm_config: llmConfig + }); + } + close(); + loadConfigs(); + } catch (e) { + errEl.textContent = '保存失败: ' + e.message; + } + }); +} diff --git a/main/feedback-backend/admin-ui/js/pages/crm.js b/main/feedback-backend/admin-ui/js/pages/crm.js new file mode 100644 index 000000000..a75dd4251 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/pages/crm.js @@ -0,0 +1,883 @@ +// CRM 管理 +import { api } from '../api.js'; + +let currentTab = 'overview'; +let currentPage = 1; +let memberKeyword = ''; +let appointmentDate = dateInput(new Date()); +let appointmentView = 'day'; +const pageSize = 20; +const MEKAI66_FIELDS = [ + ['name','姓名','基础信息'],['nickname','昵称/常用称呼','基础信息'],['gender','性别','基础信息'],['birthday','生日','基础信息'],['age','年龄','基础信息'],['hometown','籍贯/老家','基础信息'],['address','居住地址/小区','基础信息'],['phone','手机号','基础信息'],['wechat','微信号','基础信息'],['education','学历','基础信息'], + ['marital_status','婚姻状态','家庭关系'],['spouse_name','配偶姓名','家庭关系'],['spouse_job','配偶职业','家庭关系'],['children','子女情况','家庭关系'],['children_school','子女学校/年级','家庭关系'],['parents','父母情况','家庭关系'],['family_anniversary','家庭纪念日','家庭关系'],['family_focus','家庭关注点','家庭关系'],['pet','宠物','家庭关系'],['emergency_contact','紧急联系人','家庭关系'], + ['company','公司/单位','工作事业'],['industry','行业','工作事业'],['position','职位','工作事业'],['job_responsibility','工作职责','工作事业'],['income_level','收入水平','工作事业'],['work_pressure','工作压力','工作事业'],['work_schedule','作息/上下班时间','工作事业'],['business_needs','事业需求/目标','工作事业'],['decision_style','决策风格','工作事业'],['social_circle','社交圈','工作事业'], + ['hobbies','兴趣爱好','生活方式'],['sports','运动习惯','生活方式'],['travel','旅游偏好','生活方式'],['diet','饮食偏好','生活方式'],['tea_drink','茶饮偏好','生活方式'],['music','音乐偏好','生活方式'],['reading','阅读/学习偏好','生活方式'],['shopping','购物偏好','生活方式'],['brands','喜欢品牌','生活方式'],['taboo_topics','忌讳话题','生活方式'], + ['consumption_power','消费能力','消费习惯'],['consumption_frequency','消费频次','消费习惯'],['budget','预算区间','消费习惯'],['preferred_projects','偏好项目','消费习惯'],['disliked_projects','不喜欢项目','消费习惯'],['price_sensitivity','价格敏感度','消费习惯'],['promotion_preference','优惠偏好','消费习惯'],['referral_willingness','转介绍意愿','消费习惯'],['decision_factor','购买决策因素','消费习惯'],['loss_risk','流失风险点','消费习惯'], + ['skin_type','皮肤类型','健康美容'],['beauty_concerns','美容关注点','健康美容'],['body_discomfort','身体不适','健康美容'],['chronic_disease','慢性病/疾病史','健康美容'],['allergy','过敏史','健康美容'],['contraindication','护理禁忌','健康美容'],['sleep','睡眠情况','健康美容'],['menstruation','经期/备孕/孕产情况','健康美容'], + ['preferred_employee','偏好技师','服务偏好'],['service_strength','服务力度偏好','服务偏好'],['chat_preference','聊天偏好','服务偏好'],['room_preference','房间/环境偏好','服务偏好'],['temperature_preference','温度偏好','服务偏好'],['appointment_preference','预约时间偏好','服务偏好'],['last_important_event','最近重要事件','关系维护'],['next_followup','下次跟进重点','关系维护'], +].map(([key, label, category]) => ({ key, label, category })); + +export async function renderCrm(container) { + const query = (window.location.hash.split('?')[1] || ''); + const params = new URLSearchParams(query); + if (params.get('tab')) currentTab = params.get('tab'); + container.innerHTML = ` +
+ ${tabBtn('overview', '📊', 'CRM看板')} + ${tabBtn('members', '👤', '客户档案')} + ${tabBtn('appointments', '📅', '预约日历')} + ${tabBtn('visits', '🕒', '到店记录')} + ${tabBtn('products', '🧴', '产品管理')} + ${tabBtn('memberProducts', '🎁', '客户套餐')} + ${tabBtn('productConsumes', '📉', '套餐消费')} + ${tabBtn('cardCloses', '🚪', '销卡管理')} + ${tabBtn('suggestions', '💡', '建议管理')} +
+
`; + container.querySelectorAll('.crm-tab').forEach(btn => { + btn.addEventListener('click', () => { + currentTab = btn.dataset.tab; + currentPage = 1; + renderCrm(container); + }); + }); + await loadTab(); +} + +function tabBtn(tab, icon, label) { + return ``; +} + +async function loadTab() { + const el = document.getElementById('crmContent'); + if (!el) return; + if (currentTab === 'overview') return loadOverview(el); + if (currentTab === 'members') return loadMembers(el); + if (currentTab === 'appointments') return loadAppointments(el); + if (currentTab === 'bodyStatus') return loadBodyStatus(el); + if (currentTab === 'visits') return loadVisits(el); + if (currentTab === 'products') return loadProducts(el); + if (currentTab === 'memberProducts') return loadMemberProducts(el); + if (currentTab === 'productConsumes') return loadProductConsumes(el); + if (currentTab === 'accounts') return loadAccounts(el); + if (currentTab === 'transactions') return loadTransactions(el); + if (currentTab === 'cardCloses') return loadCardCloses(el); + if (currentTab === 'suggestions') return loadSuggestions(el); + if (currentTab === 'issues') return loadIssues(el); +} + +async function loadOverview(el) { + el.innerHTML = '
'; + try { + const res = await api.getCrmOverview(); + const d = res.data || {}; + el.innerHTML = ` +
+ ${stat('👤', '客户数', d.members || 0, 'blue')} + ${stat('🕒', '到店记录', d.visits || 0, 'green')} + ${stat('💳', '有效账户', d.activeAccounts || 0, 'blue')} + ${stat('💰', '账户余额', `¥${d.accountBalance || 0}`, 'green')} + ${stat('🚪', '销卡记录', d.cardCloses || 0, 'yellow')} + ${stat('💡', '待处理建议', d.pendingSuggestions || 0, 'yellow')} + ${stat('✅', '已采纳建议', d.adoptedSuggestions || 0, 'green')} +
+
使用说明
+

当前主视角:客户档案、身体变化、已购产品/套餐、套餐消耗、建议闭环。到店记录和流水作为支撑数据保留。

+
`; + } catch (e) { el.innerHTML = error(e); } +} + +function stat(icon, label, value, color) { + return `
${icon}
${label}
${value}
`; +} + +async function loadMembers(el) { + el.innerHTML = listShell('客户档案', '新增客户', 'memberAddBtn', ` + + + `, ['姓名','手机号','美容/健康','到店','消费','时间','操作']); + document.getElementById('memberAddBtn').onclick = () => showMemberDialog(); + document.getElementById('crmSearchBtn').onclick = () => { + memberKeyword = document.getElementById('crmKeyword')?.value.trim() || ''; + currentPage = 1; + loadMembers(el); + }; + document.getElementById('crmKeyword').addEventListener('keyup', (e) => { + if (e.key === 'Enter') document.getElementById('crmSearchBtn').click(); + }); + const params = new URLSearchParams({ page: currentPage, page_size: pageSize }); + if (memberKeyword) params.set('keyword', memberKeyword); + try { + const res = await api.getCrmMembers(params.toString()); + const data = res.data || {}; + renderRows(data, m => ` + ${escapeHtml(m.name || '-')}
${escapeHtml(m.level || '')}
+ ${escapeHtml(m.phone || '-')}${tags(m.beautyConcerns)}${tags(m.healthIssues)} + ${m.totalVisits || 0}¥${m.totalSpent || 0}${formatDate(m.updateDate)} + `); + bindDetailButtons(data.list || []); + } catch (e) { tableError(e, 7); } +} + +async function loadBodyStatus(el) { + el.innerHTML = listShell('身体变化状态', '新增状态', 'bodyAddBtn', '', ['客户','日期','体重','腰围','标签','状态','数值','描述']); + document.getElementById('bodyAddBtn').onclick = () => showBodyStatusDialog(); + try { + const res = await api.getCrmBodyStatuses(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, b => `${escapeHtml(b.memberName || '-')}
${escapeHtml(b.memberId)}
${formatDate(b.recordDate)}${b.weight ?? '-'}${b.waistline ?? '-'}${escapeHtml(b.metrics?.name || '-')}${escapeHtml(b.metrics?.status || '-')}${escapeHtml(b.metrics?.value || '-')}${escapeHtml(b.notes || '-')}`); + } catch (e) { tableError(e, 8); } +} + +async function loadAppointments(el) { + const range = appointmentRange(appointmentDate, appointmentView); + el.innerHTML = ` +
+
+
预约日历
+ + + + + + +
+
+
`; + document.getElementById('aptView').value = appointmentView; + await loadAppointmentEmployees(); + document.getElementById('aptSearch').onclick = () => { appointmentDate = val('aptDate'); appointmentView = val('aptView'); loadAppointments(el); }; + document.getElementById('aptAvailability').onclick = () => showAvailabilityDialog(); + document.getElementById('aptCreate').onclick = () => showAppointmentDialog(); + await renderAppointmentBoard(range); +} + +function appointmentRange(baseDate, view) { + const d = new Date(baseDate + 'T00:00:00'); + if (view === 'day') return { start: dateInput(d), end: dateInput(d) }; + if (view === 'week') { + const start = new Date(d); start.setDate(d.getDate() - ((d.getDay() + 6) % 7)); + const end = new Date(start); end.setDate(start.getDate() + 6); + return { start: dateInput(start), end: dateInput(end) }; + } + const start = new Date(d.getFullYear(), d.getMonth(), 1); + const end = new Date(d.getFullYear(), d.getMonth() + 1, 0); + return { start: dateInput(start), end: dateInput(end) }; +} + +async function loadAppointmentEmployees() { + const sel = document.getElementById('aptEmployee'); if (!sel) return; + try { + const res = await api.getEmployees('page=1&page_size=100'); + const list = res.data?.list || []; + sel.innerHTML = '' + list.map(e => ``).join(''); + } catch (e) {} +} + +async function renderAppointmentBoard(range) { + const board = document.getElementById('aptBoard'); if (!board) return; + const params = new URLSearchParams({ start_date: range.start, end_date: range.end }); + const emp = document.getElementById('aptEmployee')?.value || ''; + if (emp) params.set('employee_id', emp); + try { + const res = await api.getAppointmentCalendar(params.toString()); + const data = res.data || { resources: [], events: [] }; + if (appointmentView === 'day') { + board.innerHTML = `
${range.start} · ${data.events.length || 0} 个预约
${renderDayEventSummary(data.events)}${renderResourceDayCalendar(data.resources, data.events)}`; + bindAppointmentActions(board, range); + setTimeout(() => { + const first = board.querySelector('.resource-event'); + const cal = board.querySelector('.resource-calendar'); + if (first && cal) cal.scrollTop = Math.max(0, first.offsetTop - 80); + }, 50); + } else if (window.FullCalendar) { + renderFullCalendar(board, range, data); + } else { + board.innerHTML = ` +
${range.start} 至 ${range.end} · ${data.events.length || 0} 个预约
+ ${appointmentView === 'month' ? renderMonthCalendar(range, data.events) : appointmentView === 'week' ? renderWeekCalendar(range, data.events) : renderDayCalendar(data.resources, data.events)}`; + bindAppointmentActions(board, range); + } + } catch (e) { + board.innerHTML = `
加载预约失败:${escapeHtml(e.message)}
`; + } +} + +function renderFullCalendar(board, range, data) { + board.innerHTML = `
${range.start} 至 ${range.end} · ${data.events.length || 0} 个预约
`; + const initialView = appointmentView === 'month' ? 'dayGridMonth' : appointmentView === 'week' ? 'timeGridWeek' : 'timeGridDay'; + const calendar = new FullCalendar.Calendar(document.getElementById('fullCalendarBox'), { + initialView, + initialDate: appointmentDate, + locale: 'zh-cn', + height: 'auto', + nowIndicator: true, + slotMinTime: '09:00:00', + slotMaxTime: '21:00:00', + headerToolbar: false, + eventTimeFormat: { hour: '2-digit', minute: '2-digit', hour12: false }, + events: data.events.map(ev => ({ + id: ev.id, + title: ev.title || '-', + start: (ev.start || '').replace(' ', 'T'), + end: (ev.end || '').replace(' ', 'T'), + className: [`fc-status-${ev.status || 'pending'}`], + extendedProps: ev, + })), + eventClick(info) { + const ev = info.event.extendedProps; + showAppointmentActionDialog(ev, range); + }, + dateClick(info) { + appointmentDate = info.dateStr.slice(0, 10); + showAppointmentDialog(); + }, + }); + calendar.render(); +} + +function showAppointmentActionDialog(ev, range) { + modal('预约操作', `
预约
${escapeHtml(ev.title || '-')}
时间
${formatDate(ev.start)} - ${String(ev.end || '').substring(11,16)}
状态
${escapeHtml(ev.status || '-')}
`, async () => {}); + document.getElementById('aptDlgConfirm').onclick = async () => { await api.confirmAppointment(ev.id); document.querySelector('.modal-overlay')?.remove(); await renderAppointmentBoard(range); }; + document.getElementById('aptDlgCancel').onclick = async () => { const reason = prompt('取消原因') || ''; await api.cancelAppointment(ev.id, { reason }); document.querySelector('.modal-overlay')?.remove(); await renderAppointmentBoard(range); }; + document.getElementById('aptDlgComplete').onclick = async () => { const consume = confirm('是否完成并扣减关联套餐1次?'); await api.completeAppointment(ev.id, consume ? { consume: true, consumeCount: 1 } : {}); document.querySelector('.modal-overlay')?.remove(); await renderAppointmentBoard(range); }; +} + +function bindAppointmentActions(board, range) { + board.querySelectorAll('[data-jump-apt]').forEach(btn => btn.onclick = () => { + const target = board.querySelector(`[data-apt-open="${btn.dataset.jumpApt}"]`); + const cal = board.querySelector('.resource-calendar'); + if (target && cal) cal.scrollTop = Math.max(0, target.offsetTop - 80); + }); + board.querySelectorAll('[data-apt-open]').forEach(el => el.onclick = (event) => { + event.stopPropagation(); + const id = el.dataset.aptOpen; + showAppointmentActionDialog({ id, title: el.textContent, start: '', end: '', status: '' }, range); + }); + board.querySelectorAll('.resource-slot').forEach(slot => slot.onclick = () => { + appointmentDate = val('aptDate') || appointmentDate; + showAppointmentDialog('', slot.dataset.emp, `${appointmentDate}T${slot.dataset.time}`); + }); + board.querySelectorAll('[data-apt-confirm]').forEach(btn => btn.onclick = async () => { await api.confirmAppointment(btn.dataset.aptConfirm); await renderAppointmentBoard(range); }); + board.querySelectorAll('[data-apt-cancel]').forEach(btn => btn.onclick = async () => { const reason = prompt('取消原因') || ''; await api.cancelAppointment(btn.dataset.aptCancel, { reason }); await renderAppointmentBoard(range); }); + board.querySelectorAll('[data-apt-complete]').forEach(btn => btn.onclick = async () => { const consume = confirm('是否完成并扣减关联套餐1次?'); await api.completeAppointment(btn.dataset.aptComplete, consume ? { consume: true, consumeCount: 1 } : {}); await renderAppointmentBoard(range); }); +} + +function renderDayEventSummary(events) { + if (!events.length) return '
当天暂无预约
'; + return `
${events.map(ev => ``).join('')}
`; +} + +function renderResourceDayCalendar(resources, events) { + const startHour = 9, endHour = 21, slotHeight = 44; + const totalSlots = (endHour - startHour) * 2; + const times = Array.from({ length: totalSlots + 1 }, (_, i) => { + const minutes = startHour * 60 + i * 30; + return `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`; + }); + const eventsByEmp = {}; + events.forEach(ev => { (eventsByEmp[ev.resourceId] ||= []).push(ev); }); + return `
时间
${times.slice(0, -1).map(t => `
${t}
`).join('')}
${resources.map(r => `
${escapeHtml(r.title)}${r.number ? `(${r.number}号)` : ''}
${times.slice(0, -1).map((t, idx) => `
`).join('')}${(eventsByEmp[r.id] || []).map(ev => resourceEventBlock(ev, startHour, slotHeight)).join('')}
`).join('')}
`; +} + +function resourceEventBlock(ev, startHour, slotHeight) { + const sm = timeToMinutes(ev.start), em = timeToMinutes(ev.end); + const top = Math.max(0, (sm - startHour * 60) / 30 * slotHeight); + const height = Math.max(slotHeight, (em - sm) / 30 * slotHeight - 4); + return `
${escapeHtml(ev.title || '-')}
${String(ev.start || '').slice(11,16)}-${String(ev.end || '').slice(11,16)}
`; +} + +function timeToMinutes(dt) { + const t = String(dt || '').slice(11, 16).split(':'); + return (Number(t[0]) || 0) * 60 + (Number(t[1]) || 0); +} + +function renderDayCalendar(resources, events) { + const eventsByEmp = {}; + events.forEach(ev => { (eventsByEmp[ev.resourceId] ||= []).push(ev); }); + return `
${resources.map(r => `
${escapeHtml(r.title)}${r.number ? `(${r.number}号)` : ''}
${(eventsByEmp[r.id] || []).length ? (eventsByEmp[r.id] || []).map(eventCard).join('') : '
暂无预约
'}
`).join('')}
`; +} + +function renderWeekCalendar(range, events) { + const days = dateRangeList(range.start, range.end); + const byDay = groupEventsByDay(events); + return `
${days.map(d => `
${formatDayLabel(d)}
${(byDay[d] || []).length ? byDay[d].map(compactEventCard).join('') : '
空
'}
`).join('')}
`; +} + +function renderMonthCalendar(range, events) { + const start = new Date(range.start + 'T00:00:00'); + const first = new Date(start.getFullYear(), start.getMonth(), 1); + const gridStart = new Date(first); gridStart.setDate(first.getDate() - first.getDay()); + const byDay = groupEventsByDay(events); + const cells = []; + for (let i = 0; i < 42; i++) { const d = new Date(gridStart); d.setDate(gridStart.getDate() + i); cells.push(dateInput(d)); } + return `
${['日','一','二','三','四','五','六'].map(w => `
周${w}
`).join('')}
${cells.map(d => `
${Number(d.slice(8,10))}
${(byDay[d] || []).slice(0,3).map(compactEventCard).join('')}${(byDay[d] || []).length > 3 ? `
+${(byDay[d] || []).length - 3}更多
` : ''}
`).join('')}
`; +} + +function groupEventsByDay(events) { + const m = {}; + events.forEach(e => { const d = String(e.start || '').slice(0, 10); (m[d] ||= []).push(e); }); + return m; +} +function dateRangeList(start, end) { + const arr = []; const s = new Date(start + 'T00:00:00'); const e = new Date(end + 'T00:00:00'); + for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) arr.push(dateInput(d)); + return arr; +} +function formatDayLabel(d) { const x = new Date(d + 'T00:00:00'); return `${x.getMonth()+1}/${x.getDate()} 周${'日一二三四五六'[x.getDay()]}`; } +function compactEventCard(ev) { return `
${String(ev.start || '').slice(11,16)} ${escapeHtml(ev.title || '-')}
`; } + +function eventCard(ev) { + return `
${escapeHtml(ev.title || '-')}
${formatDate(ev.start)} - ${String(ev.end || '').substring(11,16)}
${escapeHtml(ev.status || '')}
`; +} + +async function showAvailabilityDialog() { + const date = val('aptDate') || appointmentDate; + const emp = val('aptEmployee'); + const params = new URLSearchParams({ date, duration_minutes: 60 }); + if (emp) params.set('employee_id', emp); + try { + const res = await api.getAppointmentAvailability(params.toString()); + const slots = res.data?.slots || []; + modal('可预约空档', `
${slots.map(s => `
${escapeHtml(s.employeeName)}
${s.start}-${s.end}
${s.available ? '可约' : '已占用'}
`).join('') || '暂无空档'}
`, async () => {}); + } catch (e) { alert('加载空档失败:' + e.message); } +} + +async function showAppointmentDialog(defaultMemberId = '', defaultEmployeeId = '', defaultStartAt = '') { + let employees = []; + try { employees = (await api.getEmployees('page=1&page_size=100')).data?.list || []; } catch (e) {} + modal('新增预约', ` + ${memberPicker('apt')} +
+
+
选择客户后展示客户剩余套餐。
+
`, + () => { + const opt = document.getElementById('aptMp')?.selectedOptions?.[0]; + appointmentDate = (val('aptStart') || appointmentDate).slice(0, 10); + appointmentView = 'day'; + return api.createAppointment({ memberId: pickedMember('apt'), employeeId: val('aptEmp'), memberProductId: val('aptMp'), productName: opt?.dataset?.name || '', startAt: val('aptStart'), durationMinutes: val('aptDuration'), storeNotes: val('aptNotes'), source: 'admin' }); + } + ); + fillMemberPicker('apt'); + wireAppointmentMemberPicker(); + if (defaultMemberId) { + document.getElementById('aptMemberManual').value = defaultMemberId; + loadAppointmentMemberProducts(defaultMemberId); + } +} + +function wireAppointmentMemberPicker() { + const input = document.getElementById('aptMemberKeyword'); + const manual = document.getElementById('aptMemberManual'); + input?.addEventListener('member-selected', (e) => loadAppointmentMemberProducts(e.detail.id)); + manual?.addEventListener('change', () => loadAppointmentMemberProducts(manual.value)); +} + +async function loadAppointmentMemberProducts(memberId) { + const sel = document.getElementById('aptMp'); + const info = document.getElementById('aptProductInfo'); + if (!sel || !memberId) return; + try { + const res = await api.getCrmMemberProducts(new URLSearchParams({ page: 1, page_size: 100, member_id: memberId, status: 1 }).toString()); + const list = res.data?.list || []; + sel.innerHTML = list.length ? list.map(p => ``).join('') : ''; + if (list.length) { + document.getElementById('aptDuration').value = sel.selectedOptions[0].dataset.duration || 60; + info.textContent = `当前选择:${sel.selectedOptions[0].textContent}`; + } else { + info.textContent = '该客户暂无可用套餐,也可以先去客户详情购买产品/套餐。'; + } + sel.onchange = () => { + document.getElementById('aptDuration').value = sel.selectedOptions[0]?.dataset.duration || 60; + info.textContent = `当前选择:${sel.selectedOptions[0]?.textContent || '-'}`; + }; + } catch (e) { + info.textContent = '加载客户套餐失败:' + e.message; + } +} + +async function loadVisits(el) { + el.innerHTML = listShell('到店记录', '新增到店', 'visitAddBtn', '', ['客户ID','员工ID','到店','离店','耗时','项目','消费','满意度']); + document.getElementById('visitAddBtn').onclick = () => showVisitDialog(); + try { + const res = await api.getCrmVisits(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, v => `${escapeHtml(v.memberName || '-')}
${escapeHtml(v.memberId || '-')}
${escapeHtml(v.employeeId || '-')}${formatDate(v.arriveAt)}${formatDate(v.leaveAt)}${v.durationMinutes || '-'} 分钟${tags(v.serviceItems)}¥${v.consumptionAmount || 0}${satisfactionBadge(v.satisfaction)}`); + } catch (e) { tableError(e, 8); } +} + +async function loadProducts(el) { + el.innerHTML = listShell('产品管理', '新增产品', 'productAddBtn', '', ['名称','分类','类型','价格','默认次数','状态','操作']); + document.getElementById('productAddBtn').onclick = () => showProductDialog(); + try { + const res = await api.getCrmProducts(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, p => `${escapeHtml(p.productName)}
${escapeHtml(p.description || '')}
${escapeHtml(p.category || '-')}${escapeHtml(p.productType || '-')}¥${p.price || 0}${p.defaultCount || 0}${statusBadge(p.status)}`); + document.querySelectorAll('[data-buy-product]').forEach(btn => btn.onclick = () => showPurchaseDialog(btn.dataset.buyProduct, btn.dataset.name, btn.dataset.count, btn.dataset.price)); + } catch (e) { tableError(e, 7); } +} + +async function loadMemberProducts(el) { + el.innerHTML = listShell('客户已购产品/套餐', '', '', '', ['客户','产品/套餐','剩余次数','剩余金额','有效期','状态','操作']); + try { + const res = await api.getCrmMemberProducts(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, p => `${escapeHtml(p.memberName || '-')}
${escapeHtml(p.memberId)}
${escapeHtml(p.productName)}${p.balanceCount || 0}/${p.totalCount || 0}¥${p.balanceAmount || 0}/¥${p.totalAmount || 0}${p.validEnd || '-'}${packageStatus(p.status)}`); + document.querySelectorAll('[data-consume-product]').forEach(btn => btn.onclick = () => showProductConsumeDialog(btn.dataset.consumeProduct, btn.dataset.name)); + } catch (e) { tableError(e, 7); } +} + +async function loadProductConsumes(el) { + el.innerHTML = listShell('产品/套餐消费记录', '', '', '', ['客户','已购产品ID','到店ID','消费次数','消费金额','剩余次数','剩余金额','备注','时间']); + try { + const res = await api.getCrmProductConsumes(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, c => `${escapeHtml(c.memberName || '-')}
${escapeHtml(c.memberId)}
${escapeHtml(c.memberProductId)}${escapeHtml(c.visitId || '-')}${c.consumeCount || 0}¥${c.consumeAmount || 0}${c.balanceCountAfter || 0}¥${c.balanceAmountAfter || 0}${escapeHtml(c.notes || '-')}${formatDate(c.createDate)}`); + } catch (e) { tableError(e, 9); } +} + +async function loadAccounts(el) { + el.innerHTML = listShell('账户管理', '开卡/建账户', 'accountAddBtn', '', ['客户ID','卡名称','类型','余额','次数','有效期','状态','操作']); + document.getElementById('accountAddBtn').onclick = () => showAccountDialog(); + try { + const res = await api.getCrmAccounts(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, a => `${escapeHtml(a.memberName || '-')}
${escapeHtml(a.memberId)}
${escapeHtml(a.cardName || '-')}${escapeHtml(a.accountType)}¥${a.balanceAmount || 0}${a.balanceCount || 0}/${a.totalCount || 0}${a.validEnd || '-'}${accountStatus(a.status)} `); + document.querySelectorAll('[data-consume-account]').forEach(btn => btn.onclick = () => showConsumeDialog(btn.dataset.consumeAccount, btn.dataset.card)); + document.querySelectorAll('[data-close-account]').forEach(btn => btn.onclick = () => showCloseDialog(btn.dataset.closeAccount)); + } catch (e) { tableError(e, 8); } +} + +async function loadTransactions(el) { + el.innerHTML = listShell('账户流水', '', '', '', ['客户','账户ID','类型','金额','次数','变动前','变动后','备注','时间']); + try { + const res = await api.getCrmAccountTransactions(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, t => `${escapeHtml(t.memberName || '-')}
${escapeHtml(t.memberId)}
${escapeHtml(t.accountId)}${txType(t.transactionType)}${t.amount || 0}${t.countChange || 0}¥${t.balanceBefore || 0}¥${t.balanceAfter || 0}${escapeHtml(t.notes || '-')}${formatDate(t.createDate)}`); + } catch (e) { tableError(e, 9); } +} + +async function loadCardCloses(el) { + el.innerHTML = listShell('销卡管理', '', '', '', ['客户ID','账户ID','原因','退款','剩余次数','状态','反馈ID','时间']); + try { + const res = await api.getCrmCardCloses(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, c => `${escapeHtml(c.memberName || '-')}
${escapeHtml(c.memberId)}
${escapeHtml(c.accountId)}${escapeHtml(c.reason || '-')}¥${c.refundAmount || 0}${c.remainingCount || 0}${escapeHtml(c.status)}${escapeHtml(c.feedbackRecordId || '-')}${formatDate(c.createDate)}`); + } catch (e) { tableError(e, 8); } +} + +async function loadSuggestions(el) { + el.innerHTML = listShell('建议管理', '新增建议', 'suggestionAddBtn', '', ['内容','标签','优先级','提出人','来源','次数','状态','处理说明','时间','操作']); + document.getElementById('suggestionAddBtn').onclick = () => showSuggestionDialog(); + try { + const res = await api.getCrmSuggestions(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, s => `${escapeHtml(s.content)}
${escapeHtml(s.category || '-')}
${tags(s.tags)}${priorityBadge(s.priority)}${escapeHtml(s.submitterName || s.memberName || '-')}
${escapeHtml(s.memberName && s.submitterName && s.memberName !== s.submitterName ? s.memberName : s.memberId || '-')}
${escapeHtml(s.source || '-')}${s.frequency || 1}${suggestionStatusBadge(s.status)}${escapeHtml(s.handleNotes || '-')}${formatDate(s.createDate)} `); + document.querySelectorAll('[data-sug-adopting]').forEach(btn => btn.onclick = () => showSuggestionStatusDialog(btn.dataset.sugAdopting, 'adopting')); + document.querySelectorAll('[data-sug-adopt]').forEach(btn => btn.onclick = () => showSuggestionStatusDialog(btn.dataset.sugAdopt, 'adopted')); + document.querySelectorAll('[data-sug-ignore]').forEach(btn => btn.onclick = () => showSuggestionStatusDialog(btn.dataset.sugIgnore, 'ignored')); + } catch (e) { tableError(e, 10); } +} + +async function loadIssues(el) { + el.innerHTML = listShell('问题修复', '新增问题', 'issueAddBtn', '', ['标题','分类','严重度','状态','负责人','修复方案','时间','操作']); + document.getElementById('issueAddBtn').onclick = () => showIssueDialog(); + try { + const res = await api.getCrmIssues(new URLSearchParams({ page: currentPage, page_size: pageSize }).toString()); + renderRows(res.data || {}, i => `${escapeHtml(i.title)}${escapeHtml(i.category || '-')}${escapeHtml(i.severity)}${escapeHtml(i.status)}${escapeHtml(i.assignedTo || '-')}${escapeHtml(i.fixPlan || '-')}${formatDate(i.createDate)}`); + document.querySelectorAll('[data-issue-fixed]').forEach(btn => btn.onclick = () => updateIssue(btn.dataset.issueFixed, { status: 'fixed' })); + } catch (e) { tableError(e, 8); } +} + +function listShell(title, addText, addId, filters, headers) { + return `
${title}
${filters || ''}${addText ? `` : ''}
${headers.map(h => ``).join('')}
${h}
`; +} + +function renderRows(data, rowFn) { + const tbody = document.getElementById('crmTableBody'); + const list = data.list || []; + if (!list.length) { tbody.innerHTML = `暂无数据`; return; } + tbody.innerHTML = list.map(rowFn).join(''); + renderPagination(data); +} +function renderPagination(data) { + const el = document.getElementById('crmPagination'); if (!el) return; + const total = data.total || 0; const totalPages = Math.ceil(total / pageSize) || 1; + el.innerHTML = `
共 ${total} 条,第 ${currentPage}/${totalPages} 页
`; + document.getElementById('crmPrev')?.addEventListener('click', () => { currentPage--; loadTab(); }); + document.getElementById('crmNext')?.addEventListener('click', () => { currentPage++; loadTab(); }); +} +function tableError(e, colspan) { document.getElementById('crmTableBody').innerHTML = `加载失败:${escapeHtml(e.message)}`; } +function error(e) { return `
加载失败:${escapeHtml(e.message)}
`; } +function tags(arr) { if (!arr) return ''; if (typeof arr === 'string') return `${escapeHtml(arr)}`; return (arr || []).map(x => `${escapeHtml(x)}`).join(''); } +function accountStatus(s) { return s === 1 ? '使用中' : s === 0 ? '已销卡' : '已过期'; } +function packageStatus(s) { return s === 1 ? '使用中' : s === 0 ? '已用完' : '已过期'; } +function priorityBadge(p) { const map = { urgent: ['紧急','badge-red'], high: ['高','badge-yellow'], medium: ['中','badge-blue'], low: ['低','badge-gray'] }; const it = map[p] || map.medium; return `${it[0]}`; } +function suggestionStatusBadge(s) { const map = { pending: ['待处理','badge-yellow'], adopting: ['采纳中','badge-blue'], adopted: ['已采纳','badge-green'], ignored: ['已忽略','badge-gray'], duplicate: ['重复','badge-gray'] }; const it = map[s] || [s || '-', 'badge-gray']; return `${it[0]}`; } +function txType(t) { + const map = { recharge: '充值/开卡', consume: '消费', refund: '退款', close: '销卡', adjust: '调整' }; + const cls = t === 'consume' || t === 'close' ? 'badge-yellow' : 'badge-green'; + return `${map[t] || escapeHtml(t || '-')}`; +} + +function modal(title, body, onSave) { + const overlay = document.createElement('div'); overlay.className = 'modal-overlay'; + overlay.innerHTML = ``; + document.body.appendChild(overlay); const close = () => document.body.removeChild(overlay); + overlay.querySelector('.modal-close').onclick = close; overlay.querySelector('#crmCancel').onclick = close; + overlay.querySelector('#crmSave').onclick = async () => { try { await onSave(); close(); loadTab(); } catch(e) { document.getElementById('crmModalErr').textContent = e.message || '保存失败'; } }; +} +function val(id) { return document.getElementById(id)?.value.trim(); } +function dateInput(d) { + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} +function jsonList(s) { return s ? s.split(/[,,\n]/).map(x => x.trim()).filter(Boolean) : []; } +function fillMemberPicker(prefix) { + const input = document.getElementById(`${prefix}MemberKeyword`); + const dropdown = document.getElementById(`${prefix}MemberDropdown`); + const idEl = document.getElementById(`${prefix}Member`); + const manualEl = document.getElementById(`${prefix}MemberManual`); + if (!input || !dropdown || !idEl) return; + let timer = null; + const search = async () => { + const kw = input.value.trim(); + idEl.value = ''; + if (!kw) { dropdown.innerHTML = ''; dropdown.classList.remove('open'); return; } + try { + const res = await api.getCrmMembers(new URLSearchParams({ page: 1, page_size: 10, keyword: kw }).toString()); + const list = res.data?.list || []; + dropdown.innerHTML = list.length ? list.map(m => `
${escapeHtml(m.name || '-')}${escapeHtml(m.phone || '-')}
`).join('') : '
未找到客户
'; + dropdown.classList.add('open'); + dropdown.querySelectorAll('.member-option[data-id]').forEach(opt => opt.onclick = () => { + idEl.value = opt.dataset.id; + input.value = opt.dataset.label; + if (manualEl) manualEl.value = ''; + dropdown.classList.remove('open'); + input.dispatchEvent(new CustomEvent('member-selected', { detail: { id: opt.dataset.id } })); + }); + } catch (e) { + dropdown.innerHTML = `
搜索失败:${escapeHtml(e.message)}
`; + dropdown.classList.add('open'); + } + }; + input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(search, 250); }); + input.addEventListener('focus', () => { if (dropdown.innerHTML) dropdown.classList.add('open'); }); + document.addEventListener('click', (e) => { if (!e.target.closest(`#${prefix}MemberBox`)) dropdown.classList.remove('open'); }); +} +function memberPicker(prefix, label = '客户') { + return `
`; +} +function pickedMember(prefix) { return val(`${prefix}Member`) || val(`${prefix}MemberManual`); } +function mekai66Form(prefix, values = {}) { + const groups = {}; + MEKAI66_FIELDS.forEach(f => { (groups[f.category] ||= []).push(f); }); + return `
${Object.entries(groups).map(([cat, fields]) => `
${cat}
${fields.map(f => ``).join('')}
`).join('')}
`; +} +function collectMekai66(prefix) { + const data = {}; + MEKAI66_FIELDS.forEach(f => { + const value = val(`${prefix}Mekai_${f.key}`); + if (value) data[f.key] = value; + }); + return data; +} + +function showMemberDialog() { + modal('新增客户', ` +
+
+
+
+
+
+
+
+
+
+
+ ${mekai66Form('m')} +
`, + () => api.createCrmMember({ + name: val('mName'), phone: val('mPhone'), wechat: val('mWechat'), level: val('mLevel'), + beautyConcerns: jsonList(val('mBeauty')), healthIssues: jsonList(val('mHealth')), + allergies: val('mAllergies'), mekaiTags: collectMekai66('m'), notes: val('mNotes') + }) + ); +} +function showEditMemberDialog(m) { + modal('编辑客户', ` +
+
+
+
+
+
+
+
+
+
+
+ ${mekai66Form('em', m.mekaiTags || {})} +
`, + () => api.updateCrmMember(m.id, { + name: val('emName'), phone: val('emPhone'), wechat: val('emWechat'), level: val('emLevel'), + beautyConcerns: jsonList(val('emBeauty')), healthIssues: jsonList(val('emHealth')), + allergies: val('emAllergies'), mekaiTags: collectMekai66('em'), notes: val('emNotes') + }) + ); +} + +function showVisitDialog(defaultMemberId = '') { + modal('新增到店记录', ` + ${memberPicker('v')} +
+
+
+
`, + () => api.createCrmVisit({ memberId: pickedMember('v'), employeeId: val('vEmp'), arriveAt: val('vArrive'), leaveAt: val('vLeave'), serviceItems: jsonList(val('vItems')), consumptionAmount: val('vAmount'), satisfaction: val('vSat') }) + ); + fillMemberPicker('v'); + if (defaultMemberId) document.getElementById('vMemberManual').value = defaultMemberId; +} +function showAccountDialog(defaultMemberId = '') { + modal('开卡/建账户', ` + ${memberPicker('a')} +
+
+
`, + () => api.createCrmAccount({ memberId: pickedMember('a'), cardName: val('aName'), accountType: val('aType'), totalAmount: val('aAmount'), totalCount: val('aCount'), validStart: val('aStart'), validEnd: val('aEnd') }) + ); + fillMemberPicker('a'); + if (defaultMemberId) document.getElementById('aMemberManual').value = defaultMemberId; +} +function showBodyStatusDialog(defaultMemberId = '') { + modal('新增身体变化状态', ` + ${memberPicker('bs')} +
+
+
+
`, + () => api.createCrmBodyStatus({ memberId: pickedMember('bs'), weight: val('bsWeight'), waistline: val('bsWaist'), metrics: { name: val('bsMetricName'), status: val('bsMetricStatus'), value: val('bsMetricValue') }, notes: val('bsNotes') }) + ); + fillMemberPicker('bs'); + if (defaultMemberId) document.getElementById('bsMemberManual').value = defaultMemberId; +} +function showProductDialog() { + modal('新增产品/套餐', ` +
+
+
+
`, + () => api.createCrmProduct({ productName: val('pName'), category: val('pCategory'), productType: val('pType'), defaultCount: val('pCount'), price: val('pPrice'), description: val('pDesc') }) + ); +} +async function showMemberPurchaseDialog(memberId) { + try { + const res = await api.getCrmProducts('page=1&page_size=100&status=1'); + const products = res.data?.list || []; + if (!products.length) { alert('暂无产品,请先到产品管理新增产品/套餐'); return; } + const today = new Date(); + const nextYear = new Date(today); nextYear.setFullYear(today.getFullYear() + 1); + modal('客户购买产品/套餐', ` + +
+
+
+
+
`, + () => api.purchaseCrmProduct({ productId: val('buyProductSelect'), memberId, unitPrice: val('buyFixedUnit'), purchaseCount: val('buyFixedCount'), discount: Number(val('buyFixedDiscount') || 10) / 10, totalCount: val('buyFixedCount'), totalAmount: val('buyFixedAmount'), validStart: val('buyFixedStart'), validEnd: val('buyFixedEnd'), notes: val('buyFixedNotes') }) + ); + const recalc = () => { document.getElementById('buyFixedAmount').value = (Number(val('buyFixedUnit') || 0) * Number(val('buyFixedCount') || 0) * (Number(val('buyFixedDiscount') || 10) / 10)).toFixed(2); }; + document.getElementById('buyProductSelect').onchange = (e) => { + const opt = e.target.selectedOptions[0]; + document.getElementById('buyFixedUnit').value = opt.dataset.price || 0; + document.getElementById('buyFixedCount').value = opt.dataset.count || 1; + recalc(); + }; + ['buyFixedUnit','buyFixedCount','buyFixedDiscount'].forEach(id => document.getElementById(id).oninput = recalc); + } catch (e) { alert('加载产品失败:' + e.message); } +} +function showPurchaseDialog(productId, productName, count, price) { + modal(`客户购买 - ${escapeHtml(productName || '')}`, ` + ${memberPicker('buy')} +
+
+
`, + () => api.purchaseCrmProduct({ productId, memberId: pickedMember('buy'), totalCount: val('buyCount'), totalAmount: val('buyAmount'), validStart: val('buyStart'), validEnd: val('buyEnd'), notes: val('buyNotes') }) + ); + fillMemberPicker('buy'); +} +function showProductConsumeDialog(memberProductId, productName = '') { + modal(`套餐消费 - ${escapeHtml(productName || '')}`, ` +
+
+
`, + () => api.consumeCrmProduct(memberProductId, { consumeCount: val('pcCount'), consumeAmount: val('pcAmount'), visitId: val('pcVisit'), notes: val('pcNotes') }) + ); +} +function showConsumeDialog(accountId, cardName = '') { + modal(`账户消费 ${cardName ? ' - ' + escapeHtml(cardName) : ''}`, ` +
+
+
`, + () => api.consumeCrmAccount(accountId, { amount: val('xAmount'), countChange: val('xCount'), visitId: val('xVisit'), notes: val('xNotes') }) + ); +} +function showCloseDialog(accountId) { modal('销卡', `
如包含“不满意/没效果/投诉/退款”等关键词,系统会自动创建待修复问题。
`, () => api.closeCrmCard({ accountId, reason: val('cReason'), refundAmount: val('cRefund'), feedbackRecordId: val('cFeedback'), assignedTo: val('cAssigned') })); } +function showSuggestionDialog() { modal('新增建议', `
`, () => api.createCrmSuggestion({ content: val('sContent'), category: val('sCategory') })); } +function showIssueDialog() { modal('新增问题', `
`, () => api.createCrmIssue({ title: val('iTitle'), category: val('iCategory'), severity: val('iSeverity'), description: val('iDesc'), assignedTo: val('iAssigned') })); } +function showSuggestionStatusDialog(id, status) { + const titleMap = { adopting: '标记采纳中', adopted: '标记已采纳', ignored: '忽略建议' }; + const title = titleMap[status] || '更新建议'; + const noteLabel = status === 'ignored' ? '忽略原因/处理说明' : '采纳方案/处理说明'; + modal(title, `
`, + () => api.updateCrmSuggestionStatus(id, { + status, + handleNotes: val('sHandleNotes'), + rejectedReason: status === 'rejected' ? val('sHandleNotes') : '' + }) + ); +} +async function updateIssue(id, data) { await api.updateCrmIssue(id, data); loadTab(); } +function bindDetailButtons(list) { + document.querySelectorAll('[data-detail]').forEach(btn => { + btn.onclick = async () => { + try { + const res = await api.getCrmMember(btn.dataset.detail); + showMemberDetail(res.data || {}); + } catch (e) { + alert(e.message || '加载客户详情失败'); + } + }; + }); +} + +function showMemberDetail(m) { + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + document.getElementById('memberDetailClose').onclick = close; + document.getElementById('memberDetailCloseBtn').onclick = close; + document.getElementById('detailAddBody').onclick = () => { close(); showBodyStatusDialog(m.id); }; + document.getElementById('detailBuyProduct').onclick = () => { close(); showMemberPurchaseDialog(m.id); }; + document.getElementById('detailAddAppointment').onclick = () => { close(); showAppointmentDialog(m.id); }; + document.getElementById('detailAddVisit').onclick = () => { close(); showVisitDialog(m.id); }; + document.getElementById('detailAddAccount').onclick = () => { close(); showAccountDialog(m.id); }; + document.getElementById('detailEditMember').onclick = () => { close(); showEditMemberDialog(m); }; + overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); }); +} + +function bodyTrendSection(list) { + if (!list || list.length < 2) return ''; + const sorted = [...list].reverse(); + const first = sorted[0]; + const last = sorted[sorted.length - 1]; + const delta = (key, unit = '') => { + if (first[key] == null || last[key] == null) return '-'; + const d = Number(last[key]) - Number(first[key]); + return `${d > 0 ? '+' : ''}${d}${unit}`; + }; + const latestMetrics = (list || []).slice(0, 3).map(b => `${escapeHtml(b.metrics?.name || '身体状态')}:${escapeHtml(b.metrics?.status || '-')} ${b.notes ? '· ' + escapeHtml(b.notes) : ''}`).join('
') || '-'; + return `
身体变化趋势
体重变化
${delta('weight', 'kg')}
腰围变化
${delta('waistline', 'cm')}
最近标签变化
${latestMetrics}
`; +} + +function detailSection(title, body) { + return `
${title}
${body}
`; +} + +function timelineSection(title, list, render) { + const rows = (list || []).length + ? list.map(item => `
  • ${render(item)}
  • `).join('') + : '
  • 暂无
  • '; + return `
    ${title}
      ${rows}
    `; +} + +window.CrmForms = { + 'crm.member.create': (payload = {}) => { + showMemberDialog(); + setTimeout(() => { + FormCopilot.fill({ + mName: payload.name, + mPhone: payload.phone, + mBeauty: payload.beautyConcerns, + mHealth: payload.healthIssues, + mNotes: payload.notes, + }); + if (payload.gender) document.getElementById('mMekai_gender') && (document.getElementById('mMekai_gender').value = payload.gender === 1 ? '男' : '女'); + Object.entries(payload.mekaiTags || {}).forEach(([k, v]) => FormCopilot.setValue(`mMekai_${k}`, v)); + }, 80); + }, + 'crm.product.create': (payload = {}) => { + showProductDialog(); + setTimeout(() => FormCopilot.fill({ + pName: payload.productName, + pCategory: payload.category, + pType: payload.productType, + pCount: payload.defaultCount, + pPrice: payload.price, + pDesc: payload.description, + }), 80); + }, + 'crm.appointment.create': (payload = {}) => { + showAppointmentDialog('', '', ''); + setTimeout(() => { + FormCopilot.fill({ aptStart: normalizeStartHint(payload.startHint), aptProductName: payload.serviceKeyword }); + if (payload.employeeName) selectEmployeeByName('aptEmp', payload.employeeName); + }, 120); + }, + 'crm.body_status.create': (payload = {}) => showBodyStatusDialog(payload.memberId || ''), + 'crm.product.purchase': (payload = {}) => showMemberPurchaseDialog(payload.memberId || ''), + 'crm.suggestion.create': (payload = {}) => showSuggestionDialog(payload.content || ''), +}; + +function selectEmployeeByName(selectId, name) { + const sel = document.getElementById(selectId); if (!sel || !name) return; + const opt = Array.from(sel.options).find(o => o.textContent.includes(name)); + if (opt) sel.value = opt.value; +} +function normalizeStartHint(hint) { + if (!hint) return ''; + const base = new Date(); + if (hint.includes('明天')) base.setDate(base.getDate() + 1); + if (hint.includes('后天')) base.setDate(base.getDate() + 2); + let hour = 10; + const cn = { '一':1, '二':2, '两':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '十':10 }; + const m = hint.match(/(\d{1,2}|[一二两三四五六七八九十])点/); + if (m) hour = /^\d+$/.test(m[1]) ? Number(m[1]) : cn[m[1]] || hour; + if (hint.includes('下午') && hour < 12) hour += 12; + return `${dateInput(base)}T${String(hour).padStart(2,'0')}:00`; +} diff --git a/main/feedback-backend/admin-ui/js/pages/dashboard.js b/main/feedback-backend/admin-ui/js/pages/dashboard.js new file mode 100644 index 000000000..c52f90461 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/pages/dashboard.js @@ -0,0 +1,254 @@ +// Dashboard - 统计概览 +import { api } from '../api.js'; + +export async function renderDashboard(container) { + container.innerHTML = '

    加载中...

    '; + + try { + const [overviewRes, dailyRes, storeRes, employeeKpiRes] = await Promise.all([ + api.getOverview(), + api.getDailyStats(), + api.getStoreStats(), + api.getEmployeeKpi(), + ]); + + const overview = overviewRes.data || {}; + const daily = dailyRes.data || []; + const storeStats = storeRes.data || []; + const employeeKpi = employeeKpiRes.data || []; + + container.innerHTML = ` + +
    +
    +
    📋
    +
    +
    总反馈数
    +
    ${overview.total_records || 0}
    +
    +
    +
    +
    😊
    +
    +
    满意率
    +
    ${overview.satisfaction_rate || 0}%
    +
    满意 ${overview.satisfied || 0} + 非常满意 ${overview.very_satisfied || 0}
    +
    +
    +
    +
    😕
    +
    +
    不满意
    +
    ${overview.unsatisfied || 0}
    +
    +
    +
    +
    😡
    +
    +
    很差
    +
    ${overview.very_bad || 0}
    +
    +
    +
    + +
    + +
    +
    满意度分布
    +
    +
    + + +
    +
    每日反馈趋势
    +
    +
    +
    + + +
    +
    门店统计
    +
    + + + + + + + + + + + + + + + ${storeStats.length === 0 ? '' : + storeStats.map(s => { + const storeName = s.storeName || s.store_name || '-'; + const storeCode = s.storeCode || s.store_code || '-'; + const totalRecords = s.totalRecords ?? s.total_records ?? 0; + const satisfactionRate = s.satisfactionRate ?? s.satisfaction_rate ?? 0; + const satisfactionDistribution = s.satisfactionDistribution || s.satisfaction_distribution || {}; + return ` + + + + + + + + + + `; + }).join('')} + +
    门店编码反馈数满意率非常满意满意不满意很差
    暂无数据
    ${escapeHtml(storeName)}${storeCode}${totalRecords}${satisfactionRate}%${satisfactionDistribution.very_satisfied || 0}${satisfactionDistribution.satisfied || 0}${satisfactionDistribution.unsatisfied || 0}${satisfactionDistribution.very_bad || 0}
    +
    +
    + +
    +
    员工KPI(好评 / 中评 / 差评)
    +
    + + + + ${employeeKpi.length === 0 ? '' : employeeKpi.map(e => ` + + + + + + + + + + `).join('')} + +
    员工工号总反馈好评中评差评好评率操作
    暂无员工评价数据
    ${escapeHtml(e.employeeName || '-')}${escapeHtml(e.employeeNumber || '-')}${e.total || 0}${e.good || 0}${e.middle || 0}${e.bad || 0}${e.goodRate || 0}%
    +
    +
    `; + + document.querySelectorAll('.employee-records-btn').forEach(btn => { + btn.addEventListener('click', () => showEmployeeRecords(btn.dataset.id, btn.dataset.name)); + }); + + // Render simple charts (no ECharts dependency - pure canvas) + renderSatChart(overview); + renderTrendChart(daily); + + } catch (e) { + container.innerHTML = `
    ⚠️

    加载失败: ${e.message}

    `; + } +} + +function showEmployeeRecords(employeeId, employeeName) { + if (!employeeId) return; + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + document.getElementById('empRecClose').onclick = close; + document.getElementById('empRecCloseBtn').onclick = close; + document.getElementById('empRecSearch').onclick = () => loadEmployeeRecords(employeeId); + loadEmployeeRecords(employeeId); +} + +async function loadEmployeeRecords(employeeId) { + const body = document.getElementById('empRecBody'); + if (!body) return; + body.innerHTML = '
    '; + const params = new URLSearchParams({ employee_id: employeeId, page: 1, page_size: 50 }); + const group = document.getElementById('empRecGroup')?.value; + if (group) params.set('satisfaction_group', group); + try { + const res = await api.getEmployeeRecords(params.toString()); + const list = res.data?.list || []; + body.innerHTML = list.length ? `
    ${list.map(r => ``).join('')}
    满意度点评/反馈时间
    ${satisfactionBadge(r.satisfaction)}
    ${escapeHtml(r.reviewLong || r.reviewShort || truncate(r.cleanedText || r.rawAsrText || '-', 160))}
    反馈ID:${escapeHtml(r.id)}
    ${formatDate(r.createDate)}
    ` : '
    暂无评价明细
    '; + } catch (e) { + body.innerHTML = `
    加载失败:${escapeHtml(e.message)}
    `; + } +} + +function renderSatChart(overview) { + const el = document.getElementById('satChart'); + if (!el) return; + + const dist = overview.satisfactionDistribution || overview.satisfaction_distribution || {}; + const data = [ + { label: '非常满意', value: dist.very_satisfied || 0, color: '#059669', bg: '#ECFDF5' }, + { label: '满意', value: dist.satisfied || 0, color: '#10B981', bg: '#F0FDF4' }, + { label: '不满意', value: dist.unsatisfied || 0, color: '#F59E0B', bg: '#FFFBEB' }, + { label: '很差', value: dist.very_bad || 0, color: '#EF4444', bg: '#FEF2F2' }, + ]; + + const total = data.reduce((s, d) => s + d.value, 0); + if (total === 0) { + el.innerHTML = '

    暂无满意度数据

    '; + return; + } + + el.innerHTML = ` +
    +
    ${total}
    +
    总反馈
    满意率 ${overview.satisfaction_rate || 0}%
    +
    +
    + ${data.map(d => { + const percent = total > 0 ? Math.round(d.value / total * 100) : 0; + return ` +
    +
    + + ${d.label} + ${d.value} · ${percent}% +
    +
    +
    `; + }).join('')} +
    `; +} + +function renderTrendChart(daily) { + const el = document.getElementById('trendChart'); + if (!el) return; + + if (!daily || daily.length === 0) { + el.innerHTML = '

    暂无趋势数据

    '; + return; + } + + const recent = daily.slice(-14); + const maxVal = Math.max(...recent.map(d => d.count || 0), 1); + el.innerHTML = ` +
    + ${recent.map(d => { + const value = d.count || 0; + const height = Math.max(8, Math.round(value / maxVal * 150)); + const dateStr = d.date ? d.date.substring(5) : ''; + return ` +
    +
    ${value}
    +
    +
    ${dateStr}
    +
    `; + }).join('')} +
    `; +} diff --git a/main/feedback-backend/admin-ui/js/pages/employees.js b/main/feedback-backend/admin-ui/js/pages/employees.js new file mode 100644 index 000000000..bfa22963b --- /dev/null +++ b/main/feedback-backend/admin-ui/js/pages/employees.js @@ -0,0 +1,186 @@ +// Employees - 员工管理 +import { api } from '../api.js'; + +let currentPage = 1; +const pageSize = 20; + +export async function renderEmployees(container) { + container.innerHTML = ` +
    +
    + + + +
    + +
    +
    + + + + + + + + + + + + + + + + +
    ID姓名工号门店ID类型状态创建时间操作
    +
    + +
    `; + + document.getElementById('filterBtn').addEventListener('click', () => { currentPage = 1; loadEmployees(); }); + document.getElementById('addEmpBtn').addEventListener('click', () => showEmployeeForm()); + loadEmployees(); +} + +async function loadEmployees() { + const tbody = document.getElementById('empsBody'); + if (!tbody) return; + + const storeId = document.getElementById('filterStoreId')?.value.trim() || ''; + const name = document.getElementById('filterName')?.value.trim() || ''; + const params = new URLSearchParams({ page: currentPage, page_size: pageSize }); + if (storeId) params.set('store_id', storeId); + if (name) params.set('name', name); + + try { + const res = await api.getEmployees(params.toString()); + const data = res.data || {}; + + if (!data.list || data.list.length === 0) { + tbody.innerHTML = '

    暂无员工

    '; + return; + } + + tbody.innerHTML = data.list.map(e => ` + + ${escapeHtml(e.id).substring(0,8)}... + ${escapeHtml(e.name)} + ${e.number} + ${escapeHtml(e.storeId)} + ${employeeTypeBadge(e.employeeType)} + ${statusBadge(e.status)} + ${formatDate(e.createDate)} + + + + + `).join(''); + + tbody.querySelectorAll('.edit-emp-btn').forEach(btn => { + btn.addEventListener('click', () => { + const emp = data.list.find(e => e.id === btn.dataset.id); + if (emp) showEmployeeForm(emp); + }); + }); + + tbody.querySelectorAll('.del-emp-btn').forEach(btn => { + btn.addEventListener('click', async () => { + if (!confirm('确定删除该员工?')) return; + await api.deleteEmployee(btn.dataset.id); + loadEmployees(); + }); + }); + + const total = data.total || 0; + const totalPages = Math.ceil(total / pageSize); + document.getElementById('pagination').innerHTML = ` +
    共 ${total} 条
    +
    + + + +
    `; + document.getElementById('prevPage')?.addEventListener('click', () => { if (currentPage > 1) { currentPage--; loadEmployees(); } }); + document.getElementById('nextPage')?.addEventListener('click', () => { if (currentPage < totalPages) { currentPage++; loadEmployees(); } }); + + } catch (e) { + tbody.innerHTML = `

    加载失败: ${e.message}

    `; + } +} + +function showEmployeeForm(emp = null) { + const isEdit = !!emp; + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + document.getElementById('closeForm').addEventListener('click', close); + document.getElementById('cancelBtn').addEventListener('click', close); + overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); }); + + document.getElementById('saveBtn').addEventListener('click', async () => { + const errEl = document.getElementById('formError'); + errEl.textContent = ''; + + const name = document.getElementById('formName').value.trim(); + const number = parseInt(document.getElementById('formNumber').value); + const storeId = document.getElementById('formStoreId').value.trim(); + const empType = document.getElementById('formType').value; + + if (!name || !number || !storeId) { + errEl.textContent = '姓名、工号、门店ID 不能为空'; + return; + } + + try { + if (isEdit) { + await api.updateEmployee(emp.id, { name, number, employee_type: empType }); + } else { + await api.createEmployee({ name, number, store_id: storeId, employee_type: empType }); + } + close(); + loadEmployees(); + } catch (e) { + errEl.textContent = '保存失败: ' + e.message; + } + }); +} diff --git a/main/feedback-backend/admin-ui/js/pages/records.js b/main/feedback-backend/admin-ui/js/pages/records.js new file mode 100644 index 000000000..8d481a746 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/pages/records.js @@ -0,0 +1,334 @@ +// Records - 反馈记录列表 +import { api } from '../api.js'; + +let currentPage = 1; +const pageSize = 20; + +export async function renderRecords(container) { + container.innerHTML = ` +
    +
    + + + + + + +
    +
    + + + + + + + + + + + + + + + + + +
    #门店客户满意度原始文本清洗文本点评时间操作
    +
    + +
    `; + + document.getElementById('filterBtn').addEventListener('click', () => { + currentPage = 1; + loadRecords(); + }); + document.getElementById('filterStore').addEventListener('change', async () => { + await loadEmployeeOptions(document.getElementById('filterStore').value); + }); + + loadFilterOptions().then(loadRecords); +} + +async function loadFilterOptions() { + const storeSelect = document.getElementById('filterStore'); + if (!storeSelect) return; + if (api.isStoreManager) { + const storeId = api.storeId; + const storeName = localStorage.getItem('feedback_admin_store_name') || storeId; + storeSelect.innerHTML = ``; + storeSelect.value = storeId; + storeSelect.disabled = true; + await loadEmployeeOptions(storeId); + return; + } + try { + const res = await api.getStores('page=1&page_size=100'); + const stores = res.data?.list || []; + storeSelect.innerHTML = '' + stores.map(s => ``).join(''); + } catch (e) { + storeSelect.innerHTML = ''; + } + await loadEmployeeOptions(''); +} + +async function loadEmployeeOptions(storeId = '') { + const empSelect = document.getElementById('filterEmployee'); + if (!empSelect) return; + const params = new URLSearchParams({ page: 1, page_size: 100 }); + if (storeId) params.set('store_id', storeId); + try { + const res = await api.getEmployees(params.toString()); + const employees = res.data?.list || []; + empSelect.innerHTML = '' + employees.map(e => ``).join(''); + } catch (e) { + empSelect.innerHTML = ''; + } +} + +async function loadRecords() { + const tbody = document.getElementById('recordsBody'); + if (!tbody) return; + + const storeId = document.getElementById('filterStore')?.value || ''; + const employeeId = document.getElementById('filterEmployee')?.value || ''; + const satisfaction = document.getElementById('filterSatisfaction')?.value || ''; + const startDate = document.getElementById('filterStart')?.value || ''; + const endDate = document.getElementById('filterEnd')?.value || ''; + + const params = new URLSearchParams({ + page: currentPage, + page_size: pageSize, + }); + if (storeId) params.set('store_id', storeId); + if (employeeId) params.set('employee_id', employeeId); + if (satisfaction) params.set('satisfaction', satisfaction); + if (startDate) params.set('start_date', startDate); + if (endDate) params.set('end_date', endDate); + + try { + const res = await api.getRecords(params.toString()); + const data = res.data || {}; + + if (!data.list || data.list.length === 0) { + tbody.innerHTML = '
    📋

    暂无反馈记录

    '; + return; + } + + tbody.innerHTML = data.list.map((r, i) => ` + + ${(currentPage - 1) * pageSize + i + 1} + ${escapeHtml(r.storeName || r.storeId || '-')} + ${renderCustomerCell(r)} + ${satisfactionBadge(r.satisfaction)} + ${truncate(r.rawAsrText, 40)} + ${truncate(r.cleanedText, 40)} + ${r.reviewLong ? '✅ ' + truncate(r.reviewLong, 30) : '-'} + ${formatDate(r.createDate)} + + `).join(''); + + // Detail buttons + tbody.querySelectorAll('.view-record-btn').forEach(btn => { + btn.addEventListener('click', () => showRecordDetail(btn.dataset.id, data.list)); + }); + + // Pagination + renderPagination(data); + + } catch (e) { + tbody.innerHTML = `

    加载失败: ${e.message}

    `; + } +} + +function renderPagination(data) { + const el = document.getElementById('pagination'); + if (!el) return; + + const total = data.total || 0; + const totalPages = Math.ceil(total / pageSize); + + el.innerHTML = ` +
    共 ${total} 条记录,第 ${currentPage}/${totalPages || 1} 页
    +
    + + + +
    `; + + document.getElementById('prevPage')?.addEventListener('click', () => { + if (currentPage > 1) { currentPage--; loadRecords(); } + }); + document.getElementById('nextPage')?.addEventListener('click', () => { + if (currentPage < totalPages) { currentPage++; loadRecords(); } + }); +} + +function renderCustomerCell(r) { + const name = r.memberName || r.customerName || '-'; + const phone = r.memberPhone ? maskPhone(r.memberPhone) : (r.phoneTail ? `尾号${r.phoneTail}` : ''); + const status = r.memberMatchStatus === 'conflict' + ? '
    尾号冲突,按称呼区分
    ' + : r.memberMatchStatus === 'not_found' + ? '
    未匹配客户档案
    ' + : ''; + return `${escapeHtml(name)}${phone ? `
    ${escapeHtml(phone)}
    ` : ''}${status}`; +} + +function maskPhone(phone) { + const s = String(phone || ''); + return s.length >= 7 ? `${s.slice(0, 3)}****${s.slice(-4)}` : s; +} + +function renderCustomerDetail(r) { + const candidates = r.memberMatchCandidates || []; + const candidateText = candidates.length + ? candidates.map(c => `${c.name || '-'} ${maskPhone(c.phone || '')}${c.nickname ? `(${c.nickname})` : ''}`).join(';') + : '-'; + const statusMap = { matched: '已匹配', conflict: '尾号冲突', not_found: '未匹配' }; + return `${escapeHtml(r.memberName || r.customerName || '-')} + ${r.memberPhone ? ` ${escapeHtml(maskPhone(r.memberPhone))}` : r.phoneTail ? ` 尾号${escapeHtml(r.phoneTail)}` : ''} +
    匹配状态:${escapeHtml(statusMap[r.memberMatchStatus] || '-')}
    +
    候选客户:${escapeHtml(candidateText)}
    `; +} + +function showRecordDetail(id, records) { + const r = records.find(rec => rec.id === id); + if (!r) return; + + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + document.getElementById('closeDetail').addEventListener('click', close); + document.getElementById('closeDetailBtn').addEventListener('click', close); + document.getElementById('bindMemberBtn').addEventListener('click', () => showBindFeedbackDialog(r)); + document.getElementById('createSuggestionBtn').addEventListener('click', () => showCreateSuggestionDialog(r)); + document.getElementById('createIssueBtn').addEventListener('click', () => showCreateIssueDialog(r)); + overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); }); +} + +function showSmallModal(title, body, onSave) { + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + overlay.querySelector('.modal-close').onclick = close; + overlay.querySelector('#recordCrmCancel').onclick = close; + overlay.querySelector('#recordCrmSave').onclick = async () => { + try { await onSave(); close(); alert('操作成功'); } + catch (e) { document.getElementById('recordCrmError').textContent = e.message || '操作失败'; } + }; +} + +function inputVal(id) { return document.getElementById(id)?.value.trim(); } +function memberPicker(prefix, label = '客户') { + return `
    `; +} +function pickedMember(prefix) { return inputVal(`${prefix}Member`) || inputVal(`${prefix}MemberManual`); } +function fillMemberPicker(prefix, defaultMemberId = '') { + const input = document.getElementById(`${prefix}MemberKeyword`); + const dropdown = document.getElementById(`${prefix}MemberDropdown`); + const idEl = document.getElementById(`${prefix}Member`); + const manualEl = document.getElementById(`${prefix}MemberManual`); + if (defaultMemberId && manualEl) manualEl.value = defaultMemberId; + if (!input || !dropdown || !idEl) return; + let timer = null; + const search = async () => { + const kw = input.value.trim(); + idEl.value = ''; + if (!kw) { dropdown.innerHTML = ''; dropdown.classList.remove('open'); return; } + try { + const res = await api.getCrmMembers(new URLSearchParams({ page: 1, page_size: 10, keyword: kw }).toString()); + const list = res.data?.list || []; + dropdown.innerHTML = list.length ? list.map(m => `
    ${escapeHtml(m.name || '-')}${escapeHtml(m.phone || '-')}
    `).join('') : '
    未找到客户
    '; + dropdown.classList.add('open'); + dropdown.querySelectorAll('.member-option[data-id]').forEach(opt => opt.onclick = () => { + idEl.value = opt.dataset.id; + input.value = opt.dataset.label; + if (manualEl) manualEl.value = ''; + dropdown.classList.remove('open'); + input.dispatchEvent(new CustomEvent('member-selected', { detail: { id: opt.dataset.id } })); + }); + } catch (e) { dropdown.innerHTML = `
    搜索失败:${escapeHtml(e.message)}
    `; dropdown.classList.add('open'); } + }; + input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(search, 250); }); + input.addEventListener('focus', () => { if (dropdown.innerHTML) dropdown.classList.add('open'); }); + document.addEventListener('click', (e) => { if (!e.target.closest(`#${prefix}MemberBox`)) dropdown.classList.remove('open'); }); +} + +function showBindFeedbackDialog(r) { + showSmallModal('绑定反馈到CRM', ` + ${memberPicker('bind', '选择客户')} +
    +
    `, + () => api.bindCrmFeedback(r.id, { memberId: pickedMember('bind'), visitId: inputVal('bindVisitId'), cardCloseId: inputVal('bindCardCloseId') }) + ); + fillMemberPicker('bind', r.memberId || ''); +} + +function showCreateSuggestionDialog(r) { + const content = r.cleanedText || r.rawAsrText || ''; + showSmallModal('从反馈创建建议', ` +
    +
    + ${memberPicker('recordSuggestion', '提出客户(可选)')}`, + () => api.createCrmSuggestion({ content: inputVal('recordSuggestionContent'), category: inputVal('recordSuggestionCategory'), memberId: pickedMember('recordSuggestion'), feedbackRecordId: r.id, storeId: r.storeId }) + ); + fillMemberPicker('recordSuggestion', r.memberId || ''); +} + +function showCreateIssueDialog(r) { + const content = r.cleanedText || r.rawAsrText || ''; + showSmallModal('从反馈创建问题', ` +
    +
    +
    + ${memberPicker('recordIssue', '关联客户(可选)')}`, + () => api.createCrmIssue({ title: inputVal('recordIssueTitle'), category: inputVal('recordIssueCategory'), severity: inputVal('recordIssueSeverity'), description: inputVal('recordIssueDesc'), memberId: pickedMember('recordIssue'), feedbackRecordId: r.id, storeId: r.storeId }) + ); + fillMemberPicker('recordIssue', r.memberId || ''); +} diff --git a/main/feedback-backend/admin-ui/js/pages/stores.js b/main/feedback-backend/admin-ui/js/pages/stores.js new file mode 100644 index 000000000..53572eb28 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/pages/stores.js @@ -0,0 +1,184 @@ +// Stores - 门店管理 +import { api } from '../api.js'; + +let currentPage = 1; +const pageSize = 20; + +export async function renderStores(container) { + container.innerHTML = ` +
    +
    + + +
    + +
    +
    + + + + + + + + + + + + + + + + +
    ID编码门店名称店长智能体ID状态创建时间操作
    +
    + +
    `; + + document.getElementById('filterBtn').addEventListener('click', () => { currentPage = 1; loadStores(); }); + document.getElementById('addStoreBtn').addEventListener('click', () => showStoreForm()); + loadStores(); +} + +async function loadStores() { + const tbody = document.getElementById('storesBody'); + if (!tbody) return; + + const storeName = document.getElementById('filterStoreName')?.value.trim() || ''; + const params = new URLSearchParams({ page: currentPage, page_size: pageSize }); + if (storeName) params.set('store_name', storeName); + + try { + const res = await api.getStores(params.toString()); + const data = res.data || {}; + + if (!data.list || data.list.length === 0) { + tbody.innerHTML = '

    暂无门店

    '; + return; + } + + tbody.innerHTML = data.list.map(s => ` + + ${escapeHtml(s.id).substring(0,8)}... + ${escapeHtml(s.storeCode)} + ${escapeHtml(s.storeName)} + ${escapeHtml(s.manager || '-')} + ${escapeHtml(s.agentId || '-')} + ${statusBadge(s.status)} + ${formatDate(s.createDate)} + + + + + `).join(''); + + tbody.querySelectorAll('.edit-store-btn').forEach(btn => { + btn.addEventListener('click', () => { + const store = data.list.find(s => s.id === btn.dataset.id); + if (store) showStoreForm(store); + }); + }); + + tbody.querySelectorAll('.del-store-btn').forEach(btn => { + btn.addEventListener('click', async () => { + if (!confirm('确定删除该门店?')) return; + await api.deleteStore(btn.dataset.id); + loadStores(); + }); + }); + + const total = data.total || 0; + const totalPages = Math.ceil(total / pageSize); + document.getElementById('pagination').innerHTML = ` +
    共 ${total} 条
    +
    + + + +
    `; + document.getElementById('prevPage')?.addEventListener('click', () => { if (currentPage > 1) { currentPage--; loadStores(); } }); + document.getElementById('nextPage')?.addEventListener('click', () => { if (currentPage < totalPages) { currentPage++; loadStores(); } }); + + } catch (e) { + tbody.innerHTML = `

    加载失败: ${e.message}

    `; + } +} + +function showStoreForm(store = null) { + const isEdit = !!store; + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + + document.body.appendChild(overlay); + const close = () => document.body.removeChild(overlay); + document.getElementById('closeForm').addEventListener('click', close); + document.getElementById('cancelBtn').addEventListener('click', close); + overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); }); + + document.getElementById('saveBtn').addEventListener('click', async () => { + const errEl = document.getElementById('formError'); + errEl.textContent = ''; + + const code = document.getElementById('formStoreCode').value.trim(); + const name = document.getElementById('formStoreName').value.trim(); + const manager = document.getElementById('formManager').value.trim(); + const agentId = document.getElementById('formAgentId').value.trim(); + + if (!code || !name) { + errEl.textContent = '门店编码和名称不能为空'; + return; + } + if (!/^\d{6}$/.test(code)) { + errEl.textContent = '门店编码必须为6位数字'; + return; + } + + try { + if (isEdit) { + await api.updateStore(store.id, { + store_code: code, store_name: name, manager, agent_id: agentId || null + }); + } else { + await api.createStore({ store_code: code, store_name: name, manager, agent_id: agentId || null }); + } + close(); + loadStores(); + } catch (e) { + errEl.textContent = '保存失败: ' + e.message; + } + }); +} diff --git a/main/feedback-backend/admin-ui/js/voice-widget/voice-session.js b/main/feedback-backend/admin-ui/js/voice-widget/voice-session.js new file mode 100644 index 000000000..9a2820ac6 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/voice-widget/voice-session.js @@ -0,0 +1,84 @@ +// AI Voice Widget - WebSocket session scaffold +// 后台数字人长连接通道:文本持续会话 + 心跳 + 自动重连由上层控制。 + +export class VoiceSession { + constructor({ url, onOpen, onClose, onText, onAudio, onError } = {}) { + this.url = url; + this.ws = null; + this.onOpen = onOpen; + this.onClose = onClose; + this.onText = onText; + this.onAudio = onAudio; + this.onError = onError; + this.heartbeatTimer = null; + } + + get isOpen() { + return this.ws?.readyState === WebSocket.OPEN; + } + + connect() { + if (!this.url) throw new Error('VoiceSession url is required'); + if (this.ws && [WebSocket.CONNECTING, WebSocket.OPEN].includes(this.ws.readyState)) return; + this.ws = new WebSocket(this.url); + this.ws.binaryType = 'arraybuffer'; + this.ws.onopen = () => { + this._startHeartbeat(); + this.onOpen?.(); + }; + this.ws.onclose = (e) => { + this._stopHeartbeat(); + this.onClose?.(e); + }; + this.ws.onerror = (e) => this.onError?.(e); + this.ws.onmessage = (event) => { + if (typeof event.data === 'string') { + let data = event.data; + try { data = JSON.parse(event.data); } catch (e) {} + this.onText?.(data); + } else { + this.onAudio?.(event.data); + } + }; + } + + sendJson(data) { + if (this.isOpen) { + this.ws.send(JSON.stringify(data)); + return true; + } + return false; + } + + sendText(text) { + return this.sendJson({ type: 'message', text }); + } + + sendBinary(data) { + if (this.isOpen) { + this.ws.send(data); + return true; + } + return false; + } + + close(code = 1000, reason = 'client close') { + this._stopHeartbeat(); + try { this.ws?.close(code, reason); } catch (e) {} + this.ws = null; + } + + _startHeartbeat() { + this._stopHeartbeat(); + this.heartbeatTimer = window.setInterval(() => { + this.sendJson({ type: 'ping' }); + }, 25000); + } + + _stopHeartbeat() { + if (this.heartbeatTimer) { + window.clearInterval(this.heartbeatTimer); + this.heartbeatTimer = null; + } + } +} diff --git a/main/feedback-backend/admin-ui/js/voice-widget/voice-widget.js b/main/feedback-backend/admin-ui/js/voice-widget/voice-widget.js new file mode 100644 index 000000000..d24aa8770 --- /dev/null +++ b/main/feedback-backend/admin-ui/js/voice-widget/voice-widget.js @@ -0,0 +1,242 @@ +// AI Voice Widget - lightweight continuous voice interaction component +// 当前版本:浏览器 ASR + speechSynthesis TTS + 状态回调;可配合后台 WebSocket 长连接使用。 + +import { VoiceSession } from './voice-session.js'; + +export function createVoiceWidget(options = {}) { + return new VoiceWidget(options); +} + +export class VoiceWidget { + constructor({ onUserText, onSessionMessage, onSessionOpen, onSessionClose, onStatus, onReplyStart, onReplyEnd, onError, voiceEnabled = true, sessionUrl = '' } = {}) { + this.onUserText = onUserText; + this.onSessionMessage = onSessionMessage; + this.onSessionOpen = onSessionOpen; + this.onSessionClose = onSessionClose; + this.onStatus = onStatus; + this.onReplyStart = onReplyStart; + this.onReplyEnd = onReplyEnd; + this.onError = onError; + this.voiceEnabled = voiceEnabled; + this.sessionUrl = sessionUrl; + this.recognition = null; + this.listening = false; + this.session = null; + this.continuousMode = false; + this.manualStop = false; + this.paused = false; + this.speaking = false; + this.restartTimer = null; + this.restartDelay = 450; + } + + setVoiceEnabled(enabled) { + this.voiceEnabled = !!enabled; + if (!this.voiceEnabled) this.stopSpeaking(); + } + + isContinuous() { + return this.continuousMode && !this.manualStop; + } + + async startListening(options = {}) { + const continuous = !!options.continuous; + const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; + if (!SpeechRecognition) { + const err = new Error('当前浏览器不支持语音输入,请使用 Chrome/Edge,或先用文字输入。'); + this.onError?.(err); + throw err; + } + if (this.listening && this.recognition) { + if (continuous && this.continuousMode) return true; + this.stopListening(false); + } + this._clearRestartTimer(); + this.manualStop = false; + this.paused = false; + + const recognition = new SpeechRecognition(); + this.recognition = recognition; + recognition.lang = 'zh-CN'; + recognition.interimResults = true; + recognition.continuous = continuous; + recognition.maxAlternatives = 1; + this.listening = true; + this.onStatus?.('listening', continuous ? '长聊中 · 我会持续听你说话' : '正在听你说话...'); + let finalText = ''; + + recognition.onresult = (event) => { + let interim = ''; + for (let i = event.resultIndex; i < event.results.length; i++) { + const transcript = event.results[i][0].transcript; + if (event.results[i].isFinal) { + if (continuous) { + const text = transcript.trim(); + if (text) this.onUserText?.(text); + } else { + finalText += transcript; + } + } else { + interim += transcript; + } + } + this.onStatus?.('listening', finalText || interim || (continuous ? '长聊中 · 我会持续听你说话' : '正在听你说话...')); + }; + recognition.onstart = () => { + this.listening = true; + this.onStatus?.('listening', continuous ? '长聊中 · 我会持续听你说话' : '正在听你说话...'); + }; + recognition.onerror = (event) => { + const error = event.error || '语音识别失败'; + // Chrome 在 stop()/切换页面/播放 TTS 时经常抛 aborted/no-speech,属于可恢复状态,不展示成聊天消息。 + if (['aborted', 'no-speech'].includes(error)) { + this.onStatus?.('listening', this.continuousMode ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字'); + if (!this.manualStop && this.continuousMode && !this.paused && !this.speaking) { + this._scheduleRestart(); + } + return; + } + this.onError?.(new Error(error)); + }; + recognition.onend = () => { + this.listening = false; + this.recognition = null; + if (!continuous) { + const text = finalText.trim(); + if (text) this.onUserText?.(text); + } + if (this.continuousMode && !this.manualStop && !this.paused && !this.speaking) { + this._scheduleRestart(); + } else if (!this.speaking && !this.paused) { + this.onStatus?.('', this.continuousMode ? '长聊已暂停' : '待命中 · 可语音或打字'); + } + }; + try { + recognition.start(); + } catch (err) { + this.listening = false; + this.recognition = null; + if (continuous && !this.manualStop) this._scheduleRestart(); + else this.onError?.(err); + return false; + } + return true; + } + + async startContinuous() { + this.continuousMode = true; + this.manualStop = false; + this.paused = false; + return this.startListening({ continuous: true }); + } + + stopListening(manual = true) { + this.manualStop = manual; + if (manual) this.continuousMode = false; + this._clearRestartTimer(); + try { this.recognition?.stop(); } catch (e) {} + this.recognition = null; + this.listening = false; + if (manual) this.onStatus?.('', '待命中 · 可语音或打字'); + } + + pauseContinuous(text = '正在思考...') { + if (!this.continuousMode) return; + this.paused = true; + this._clearRestartTimer(); + try { this.recognition?.stop(); } catch (e) {} + this.onStatus?.('thinking', text); + } + + resumeContinuous() { + if (!this.continuousMode || this.manualStop || this.speaking) return; + this.paused = false; + this._scheduleRestart(); + } + + speak(text) { + if (!this.voiceEnabled || !window.speechSynthesis || !text) { + this.resumeContinuous(); + return; + } + this.stopSpeaking(); + this.speaking = true; + this.pauseContinuous('AI正在回复...'); + const utter = new SpeechSynthesisUtterance(String(text).replace(/<[^>]+>/g, '').slice(0, 260)); + utter.lang = 'zh-CN'; + utter.rate = 1.05; + utter.pitch = 1.0; + utter.onstart = () => { + this.onStatus?.('speaking', 'AI正在回复...'); + this.onReplyStart?.(); + }; + utter.onend = () => { + this.speaking = false; + this.paused = false; + this.onStatus?.(this.continuousMode ? 'listening' : '', this.continuousMode ? '长聊中 · 我会持续听你说话' : '待命中 · 可语音或打字'); + this.onReplyEnd?.(); + this.resumeContinuous(); + }; + utter.onerror = () => { + this.speaking = false; + this.paused = false; + this.onReplyEnd?.(); + this.resumeContinuous(); + }; + window.speechSynthesis.speak(utter); + } + + stopSpeaking() { + try { window.speechSynthesis?.cancel(); } catch (e) {} + this.speaking = false; + } + + connectSession(url = '') { + if (url) this.sessionUrl = url; + if (!this.sessionUrl) return null; + if (this.session?.isOpen) return this.session; + this.session = new VoiceSession({ + url: this.sessionUrl, + onOpen: () => { + this.onStatus?.('connected', '长连接已建立 · 可持续对话'); + this.onSessionOpen?.(); + }, + onClose: (event) => { + this.onStatus?.('', this.continuousMode ? '长连接已断开 · 语音长聊仍可使用' : '长连接已关闭'); + this.onSessionClose?.(event); + }, + onText: (data) => this.onSessionMessage?.(data), + onError: (e) => this.onError?.(e), + }); + this.session.connect(); + return this.session; + } + + sendText(text) { + return this.session?.sendText(text) || false; + } + + destroy() { + this.stopListening(true); + this.stopSpeaking(); + this.session?.close(); + } + + _scheduleRestart() { + if (!this.continuousMode || this.manualStop || this.paused || this.speaking || this.listening) return; + this._clearRestartTimer(); + this.restartTimer = window.setTimeout(() => { + this.restartTimer = null; + if (this.continuousMode && !this.manualStop && !this.paused && !this.speaking && !this.listening) { + this.startListening({ continuous: true }).catch(err => this.onError?.(err)); + } + }, this.restartDelay); + } + + _clearRestartTimer() { + if (this.restartTimer) { + window.clearTimeout(this.restartTimer); + this.restartTimer = null; + } + } +} diff --git a/main/feedback-backend/admin-ui/libs/cubism4.min.js b/main/feedback-backend/admin-ui/libs/cubism4.min.js new file mode 100644 index 000000000..f0e4a50aa --- /dev/null +++ b/main/feedback-backend/admin-ui/libs/cubism4.min.js @@ -0,0 +1 @@ +var __pow=Math.pow,__async=(t,e,i)=>new Promise(((s,r)=>{var a=t=>{try{n(i.next(t))}catch(e){r(e)}},o=t=>{try{n(i.throw(t))}catch(e){r(e)}},n=t=>t.done?s(t.value):Promise.resolve(t.value).then(a,o);n((i=i.apply(t,e)).next())}));!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("@pixi/utils"),require("@pixi/math"),require("@pixi/core"),require("@pixi/display")):"function"==typeof define&&define.amd?define(["exports","@pixi/utils","@pixi/math","@pixi/core","@pixi/display"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI.utils,t.PIXI,t.PIXI,t.PIXI)}(this,(function(t,e,i,s,r){"use strict";class a{constructor(){this._breathParameters=[],this._currentTime=0}static create(){return new a}setParameters(t){this._breathParameters=t}getParameters(){return this._breathParameters}updateParameters(t,e){this._currentTime+=e;const i=2*this._currentTime*3.14159;for(let s=0;s=1&&(s=1,this._blinkingState=h.EyeState_Closed,this._stateStartTimeSeconds=this._userTimeSeconds),i=1-s;break;case h.EyeState_Closed:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,s>=1&&(this._blinkingState=h.EyeState_Opening,this._stateStartTimeSeconds=this._userTimeSeconds),i=0;break;case h.EyeState_Opening:s=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,s>=1&&(s=1,this._blinkingState=h.EyeState_Interval,this._nextBlinkingTime=this.determinNextBlinkingTiming()),i=s;break;case h.EyeState_Interval:this._nextBlinkingTime(t[t.EyeState_First=0]="EyeState_First",t[t.EyeState_Interval=1]="EyeState_Interval",t[t.EyeState_Closing=2]="EyeState_Closing",t[t.EyeState_Closed=3]="EyeState_Closed",t[t.EyeState_Opening=4]="EyeState_Opening",t))(h||{});class u{static create(t){const e=new u;"number"==typeof t.FadeInTime&&(e._fadeTimeSeconds=t.FadeInTime,e._fadeTimeSeconds<=0&&(e._fadeTimeSeconds=.5));const i=t.Groups,s=i.length;for(let r=0;r.001){if(r>=0)break;r=n,a=t.getPartOpacityByIndex(i),a+=e/this._fadeTimeSeconds,a>1&&(a=1)}}r<0&&(r=0,a=1);for(let n=i;n.15&&(i=1-.15/(1-a)),s>i&&(s=i),t.setPartOpacityByIndex(e,s)}}}constructor(){this._fadeTimeSeconds=.5,this._lastModel=void 0,this._partGroups=[],this._partGroupCounts=[]}}class d{constructor(t){this.parameterIndex=0,this.partIndex=0,this.partId="",this.link=[],null!=t&&this.assignment(t)}assignment(t){return this.partId=t.partId,this.link=t.link.map((t=>t.clone())),this}initialize(t){this.parameterIndex=t.getParameterIndex(this.partId),this.partIndex=t.getPartIndex(this.partId),t.setParameterValueByIndex(this.parameterIndex,1)}clone(){const t=new d;return t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=this.link.map((t=>t.clone())),t}}class c{constructor(t,e){this.x=t||0,this.y=e||0}add(t){const e=new c(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new c(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new c(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new c(t,t))}division(t){const e=new c(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new c(t,t))}getLength(){return Math.sqrt(this.x*this.x+this.y*this.y)}getDistanceWith(t){return Math.sqrt((this.x-t.x)*(this.x-t.x)+(this.y-t.y)*(this.y-t.y))}dot(t){return this.x*t.x+this.y*t.y}normalize(){const t=Math.pow(this.x*this.x+this.y*this.y,.5);this.x=this.x/t,this.y=this.y/t}isEqual(t){return this.x==t.x&&this.y==t.y}isNotEqual(t){return!this.isEqual(t)}}const m=class{static range(t,e,i){return ti&&(t=i),t}static sin(t){return Math.sin(t)}static cos(t){return Math.cos(t)}static abs(t){return Math.abs(t)}static sqrt(t){return Math.sqrt(t)}static cbrt(t){if(0===t)return t;let e=t;const i=e<0;let s;return i&&(e=-e),e===1/0?s=1/0:(s=Math.exp(Math.log(e)/3),s=(e/(s*s)+2*s)/3),i?-s:s}static getEasingSine(t){return t<0?0:t>1?1:.5-.5*this.cos(t*Math.PI)}static max(t,e){return t>e?t:e}static min(t,e){return t>e?e:t}static degreesToRadian(t){return t/180*Math.PI}static radianToDegrees(t){return 180*t/Math.PI}static directionToRadian(t,e){let i=Math.atan2(e.y,e.x)-Math.atan2(t.y,t.x);for(;i<-Math.PI;)i+=2*Math.PI;for(;i>Math.PI;)i-=2*Math.PI;return i}static directionToDegrees(t,e){const i=this.directionToRadian(t,e);let s=this.radianToDegrees(i);return e.x-t.x>0&&(s=-s),s}static radianToDirection(t){const e=new c;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(t,e,i){return this.abs(t)1&&(t=1),e<0?e=0:e>1&&(e=1),i<0?i=0:i>1&&(i=1),s<0?s=0:s>1&&(s=1),this._modelColor.R=t,this._modelColor.G=e,this._modelColor.B=i,this._modelColor.A=s}getModelColor(){return Object.assign({},this._modelColor)}setIsPremultipliedAlpha(t){this._isPremultipliedAlpha=t}isPremultipliedAlpha(){return this._isPremultipliedAlpha}setIsCulling(t){this._isCulling=t}isCulling(){return this._isCulling}setAnisotropy(t){this._anisortopy=t}getAnisotropy(){return this._anisortopy}getModel(){return this._model}constructor(){this._isCulling=!1,this._isPremultipliedAlpha=!1,this._anisortopy=0,this._modelColor=new y,this._mvpMatrix4x4=new p,this._mvpMatrix4x4.loadIdentity()}}var f=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(f||{});class y{constructor(){this.R=1,this.G=1,this.B=1,this.A=1}}let x,v=!1,M=!1;const P={vertexOffset:0,vertexStep:2};class C{static startUp(t){if(v)return I("CubismFramework.startUp() is already done."),v;if(Live2DCubismCore._isStarted)return v=!0,!0;if(Live2DCubismCore._isStarted=!0,x=t,x&&Live2DCubismCore.Logging.csmSetLogFunction(x.logFunction),v=!0,v){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;I("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return I("CubismFramework.startUp() is complete."),v}static cleanUp(){v=!1,M=!1,x=void 0}static initialize(){v?M?L("CubismFramework.initialize() skipped, already initialized."):(M=!0,I("CubismFramework.initialize() is complete.")):L("CubismFramework is not started.")}static dispose(){v?M?(_.staticRelease(),M=!1,I("CubismFramework.dispose() is complete.")):L("CubismFramework.dispose() skipped, not initialized."):L("CubismFramework is not started.")}static isStarted(){return v}static isInitialized(){return M}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=x?x.loggingLevel:S.LogLevel_Off}constructor(){}}var S=(t=>(t[t.LogLevel_Verbose=0]="LogLevel_Verbose",t[t.LogLevel_Debug=1]="LogLevel_Debug",t[t.LogLevel_Info=2]="LogLevel_Info",t[t.LogLevel_Warning=3]="LogLevel_Warning",t[t.LogLevel_Error=4]="LogLevel_Error",t[t.LogLevel_Off=5]="LogLevel_Off",t))(S||{});const b=()=>{};function w(t,...e){E.print(S.LogLevel_Debug,"[CSM][D]"+t+"\n",e)}function I(t,...e){E.print(S.LogLevel_Info,"[CSM][I]"+t+"\n",e)}function L(t,...e){E.print(S.LogLevel_Warning,"[CSM][W]"+t+"\n",e)}function T(t,...e){E.print(S.LogLevel_Error,"[CSM][E]"+t+"\n",e)}class E{static print(t,e,i){if(ti[e])))}static dumpBytes(t,e,i){for(let s=0;s0?this.print(t,"\n"):s%8==0&&s>0&&this.print(t," "),this.print(t,"{0} ",[255&e[s]]);this.print(t,"\n")}constructor(){}}class D{update(){this._model.update(),this._model.drawables.resetDynamicFlags()}getCanvasWidth(){return null==this._model?0:this._model.canvasinfo.CanvasWidth/this._model.canvasinfo.PixelsPerUnit}getCanvasHeight(){return null==this._model?0:this._model.canvasinfo.CanvasHeight/this._model.canvasinfo.PixelsPerUnit}saveParameters(){const t=this._model.parameters.count,e=this._savedParameters.length;for(let i=0;ie&&(e=this._model.parameters.minimumValues[t]),this._parameterValues[t]=1==i?e:this._parameterValues[t]=this._parameterValues[t]*(1-i)+e*i)}setParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.setParameterValueByIndex(s,e,i)}addParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)+e*i)}addParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.addParameterValueByIndex(s,e,i)}multiplyParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.multiplyParameterValueByIndex(s,e,i)}multiplyParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)*(1+(e-1)*i))}getDrawableIds(){return this._drawableIds.slice()}getDrawableIndex(t){const e=this._model.drawables.count;for(let i=0;ie&&(t=e);for(let i=0;i0&&e.getEndTime()(t[t.ExpressionBlendType_Add=0]="ExpressionBlendType_Add",t[t.ExpressionBlendType_Multiply=1]="ExpressionBlendType_Multiply",t[t.ExpressionBlendType_Overwrite=2]="ExpressionBlendType_Overwrite",t))(U||{});t.CubismConfig=void 0,(k=t.CubismConfig||(t.CubismConfig={})).supportMoreMaskDivisions=!0,k.setOpacityFromMotion=!1;var N=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(N||{}),V=(t=>(t[t.CubismMotionSegmentType_Linear=0]="CubismMotionSegmentType_Linear",t[t.CubismMotionSegmentType_Bezier=1]="CubismMotionSegmentType_Bezier",t[t.CubismMotionSegmentType_Stepped=2]="CubismMotionSegmentType_Stepped",t[t.CubismMotionSegmentType_InverseStepped=3]="CubismMotionSegmentType_InverseStepped",t))(V||{});class j{constructor(t=0,e=0){this.time=t,this.value=e}}class G{constructor(){this.basePointIndex=0,this.segmentType=0}}class X{constructor(){this.id="",this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class z{constructor(){this.fireTime=0,this.value=""}}class W{constructor(){this.duration=0,this.loop=!1,this.curveCount=0,this.eventCount=0,this.fps=0,this.curves=[],this.segments=[],this.points=[],this.events=[]}}class H{constructor(t){this._json=t}release(){this._json=void 0}getMotionDuration(){return this._json.Meta.Duration}isMotionLoop(){return this._json.Meta.Loop||!1}getEvaluationOptionFlag(t){return Y.EvaluationOptionFlag_AreBeziersRistricted==t&&!!this._json.Meta.AreBeziersRestricted}getMotionCurveCount(){return this._json.Meta.CurveCount}getMotionFps(){return this._json.Meta.Fps}getMotionTotalSegmentCount(){return this._json.Meta.TotalSegmentCount}getMotionTotalPointCount(){return this._json.Meta.TotalPointCount}getMotionFadeInTime(){return this._json.Meta.FadeInTime}getMotionFadeOutTime(){return this._json.Meta.FadeOutTime}getMotionCurveTarget(t){return this._json.Curves[t].Target}getMotionCurveId(t){return this._json.Curves[t].Id}getMotionCurveFadeInTime(t){return this._json.Curves[t].FadeInTime}getMotionCurveFadeOutTime(t){return this._json.Curves[t].FadeOutTime}getMotionCurveSegmentCount(t){return this._json.Curves[t].Segments.length}getMotionCurveSegment(t,e){return this._json.Curves[t].Segments[e]}getEventCount(){return this._json.Meta.UserDataCount||0}getTotalEventValueSize(){return this._json.Meta.TotalUserDataSize}getEventTime(t){return this._json.UserData[t].Time}getEventValue(t){return this._json.UserData[t].Value}}var Y=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Y||{});function q(t,e,i){const s=new j;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function $(t,e){let i=(e-t[0].time)/(t[1].time-t[0].time);return i<0&&(i=0),t[0].value+(t[1].value-t[0].value)*i}function Z(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=q(t[0],t[1],i),r=q(t[1],t[2],i),a=q(t[2],t[3],i),o=q(s,r,i),n=q(r,a,i);return q(o,n,i).value}function J(t,e){const i=e,s=t[0].time,r=t[3].time,a=t[1].time,o=t[2].time,n=r-3*o+3*a-s,l=3*o-6*a+3*s,h=3*a-3*s,u=s-i,d=g.cardanoAlgorithmForBezier(n,l,h,u),c=q(t[0],t[1],d),m=q(t[1],t[2],d),p=q(t[2],t[3],d),_=q(c,m,d),f=q(m,p,d);return q(_,f,d).value}function Q(t,e){return t[0].value}function K(t,e){return t[1].value}function tt(t,e,i){const s=t.curves[e];let r=-1;const a=s.baseSegmentIndex+s.segmentCount;let o=0;for(let l=s.baseSegmentIndex;li){r=l;break}if(-1==r)return t.points[o].value;const n=t.segments[r];return n.evaluate(t.points.slice(n.basePointIndex),i)}class et extends R{constructor(){super(),this._eyeBlinkParameterIds=[],this._lipSyncParameterIds=[],this._sourceFrameRate=30,this._loopDurationSeconds=-1,this._isLoop=!1,this._isLoopFadeIn=!0,this._lastWeight=0}static create(t,e){const i=new et;return i.parse(t),i._sourceFrameRate=i._motionData.fps,i._loopDurationSeconds=i._motionData.duration,i._onFinishedMotion=e,i}doUpdateParameters(e,i,s,r){null==this._modelCurveIdEyeBlink&&(this._modelCurveIdEyeBlink="EyeBlink"),null==this._modelCurveIdLipSync&&(this._modelCurveIdLipSync="LipSync");let a=i-r.getStartTime();a<0&&(a=0);let o=Number.MAX_VALUE,n=Number.MAX_VALUE;const l=64;let h=0,u=0;this._eyeBlinkParameterIds.length>l&&w("too many eye blink targets : {0}",this._eyeBlinkParameterIds.length),this._lipSyncParameterIds.length>l&&w("too many lip sync targets : {0}",this._lipSyncParameterIds.length);const d=this._fadeInSeconds<=0?1:g.getEasingSine((i-r.getFadeInStartTime())/this._fadeInSeconds),c=this._fadeOutSeconds<=0||r.getEndTime()<0?1:g.getEasingSine((r.getEndTime()-i)/this._fadeOutSeconds);let m,p,_,f=a;if(this._isLoop)for(;f>this._motionData.duration;)f-=this._motionData.duration;const y=this._motionData.curves;for(p=0;p>t&1)continue;const r=i+(n-i)*s;e.setParameterValueById(this._eyeBlinkParameterIds[t],r)}if(o!=Number.MAX_VALUE)for(let t=0;t>t&1)continue;const r=i+(o-i)*s;e.setParameterValueById(this._lipSyncParameterIds[t],r)}for(;p=this._motionData.duration&&(this._isLoop?(r.setStartTime(i),this._isLoopFadeIn&&r.setFadeInStartTime(i)):(this._onFinishedMotion&&this._onFinishedMotion(this),r.setIsFinished(!0))),this._lastWeight=s}setIsLoop(t){this._isLoop=t}isLoop(){return this._isLoop}setIsLoopFadeIn(t){this._isLoopFadeIn=t}isLoopFadeIn(){return this._isLoopFadeIn}getDuration(){return this._isLoop?-1:this._loopDurationSeconds}getLoopDuration(){return this._loopDurationSeconds}setParameterFadeInTime(t,e){const i=this._motionData.curves;for(let s=0;snew X)),this._motionData.segments=Array.from({length:e.getMotionTotalSegmentCount()}).map((()=>new G)),this._motionData.events=Array.from({length:this._motionData.eventCount}).map((()=>new z)),this._motionData.points=[];let a=0,o=0;for(let n=0;nt&&this._motionData.events[i].fireTime<=e&&this._firedEventValues.push(this._motionData.events[i].value);return this._firedEventValues}}class it{constructor(){this._autoDelete=!1,this._available=!0,this._finished=!1,this._started=!1,this._startTimeSeconds=-1,this._fadeInStartTimeSeconds=0,this._endTimeSeconds=-1,this._stateTimeSeconds=0,this._stateWeight=0,this._lastEventCheckSeconds=0,this._motionQueueEntryHandle=this,this._fadeOutSeconds=0,this._isTriggeredFadeOut=!1}release(){this._autoDelete&&this._motion&&this._motion.release()}setFadeOut(t){this._fadeOutSeconds=t,this._isTriggeredFadeOut=!0}startFadeOut(t,e){const i=e+t;this._isTriggeredFadeOut=!0,(this._endTimeSeconds<0||inull!=e&&e._motionQueueEntryHandle==t))}setEventCallback(t,e=null){this._eventCallBack=t,this._eventCustomData=e}doUpdateMotion(t,e){let i=!1,s=0;for(;s(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(at||{}),ot=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(ot||{});class nt{constructor(){this.initialPosition=new c(0,0),this.position=new c(0,0),this.lastPosition=new c(0,0),this.lastGravity=new c(0,0),this.force=new c(0,0),this.velocity=new c(0,0)}}class lt{constructor(){this.normalizationPosition={},this.normalizationAngle={}}}class ht{constructor(){this.source={}}}class ut{constructor(){this.destination={},this.translationScale=new c(0,0)}}class dt{constructor(){this.settings=[],this.inputs=[],this.outputs=[],this.particles=[],this.gravity=new c(0,0),this.wind=new c(0,0)}}class ct{constructor(t){this._json=t}release(){this._json=void 0}getGravity(){const t=new c(0,0);return t.x=this._json.Meta.EffectiveForces.Gravity.X,t.y=this._json.Meta.EffectiveForces.Gravity.Y,t}getWind(){const t=new c(0,0);return t.x=this._json.Meta.EffectiveForces.Wind.X,t.y=this._json.Meta.EffectiveForces.Wind.Y,t}getSubRigCount(){return this._json.Meta.PhysicsSettingCount}getTotalInputCount(){return this._json.Meta.TotalInputCount}getTotalOutputCount(){return this._json.Meta.TotalOutputCount}getVertexCount(){return this._json.Meta.VertexCount}getNormalizationPositionMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Minimum}getNormalizationPositionMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Maximum}getNormalizationPositionDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Position.Default}getNormalizationAngleMinimumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Minimum}getNormalizationAngleMaximumValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Maximum}getNormalizationAngleDefaultValue(t){return this._json.PhysicsSettings[t].Normalization.Angle.Default}getInputCount(t){return this._json.PhysicsSettings[t].Input.length}getInputWeight(t,e){return this._json.PhysicsSettings[t].Input[e].Weight}getInputReflect(t,e){return this._json.PhysicsSettings[t].Input[e].Reflect}getInputType(t,e){return this._json.PhysicsSettings[t].Input[e].Type}getInputSourceId(t,e){return this._json.PhysicsSettings[t].Input[e].Source.Id}getOutputCount(t){return this._json.PhysicsSettings[t].Output.length}getOutputVertexIndex(t,e){return this._json.PhysicsSettings[t].Output[e].VertexIndex}getOutputAngleScale(t,e){return this._json.PhysicsSettings[t].Output[e].Scale}getOutputWeight(t,e){return this._json.PhysicsSettings[t].Output[e].Weight}getOutputDestinationId(t,e){return this._json.PhysicsSettings[t].Output[e].Destination.Id}getOutputType(t,e){return this._json.PhysicsSettings[t].Output[e].Type}getOutputReflect(t,e){return this._json.PhysicsSettings[t].Output[e].Reflect}getParticleCount(t){return this._json.PhysicsSettings[t].Vertices.length}getParticleMobility(t,e){return this._json.PhysicsSettings[t].Vertices[e].Mobility}getParticleDelay(t,e){return this._json.PhysicsSettings[t].Vertices[e].Delay}getParticleAcceleration(t,e){return this._json.PhysicsSettings[t].Vertices[e].Acceleration}getParticleRadius(t,e){return this._json.PhysicsSettings[t].Vertices[e].Radius}getParticlePosition(t,e){const i=new c(0,0);return i.x=this._json.PhysicsSettings[t].Vertices[e].Position.X,i.y=this._json.PhysicsSettings[t].Vertices[e].Position.Y,i}}const mt="Angle";class gt{static create(t){const e=new gt;return e.parse(t),e._physicsRig.gravity.y=0,e}evaluate(t,e){let i,s,r,a;const o=new c;let n,l,h,u,d,m,p,_;d=t.getModel().parameters.values,m=t.getModel().parameters.maximumValues,p=t.getModel().parameters.minimumValues,_=t.getModel().parameters.defaultValues;for(let f=0;f=n.particleCount)break;-1==h[e].destinationParameterIndex&&(h[e].destinationParameterIndex=t.getParameterIndex(h[e].destination.id));const s=new c;s.x=u[i].position.x-u[i-1].position.x,s.y=u[i].position.y-u[i-1].position.y,a=h[e].getValue(s,u,i,h[e].reflect,this._options.gravity);const r=h[e].destinationParameterIndex,o=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(d.subarray(r))):d.slice(r);It(o,p[r],m[r],a,h[e]);for(let t=r,e=0;t=2?e[i-1].position.substract(e[i-2].position):r.multiplyByScaler(-1),a=g.directionToRadian(r,t),s&&(a*=-1),a}function Pt(t,e){return Math.min(t,e)+function(t,e){return Math.abs(Math.max(t,e)-Math.min(t,e))}(t,e)/2}function Ct(t,e){return t.x}function St(t,e){return t.y}function bt(t,e){return e}function wt(t,e,i,s,r,a,o,n){let l,h,u,d,m=new c(0,0),p=new c(0,0),_=new c(0,0),f=new c(0,0);t[0].position=new c(i.x,i.y),l=g.degreesToRadian(s),d=g.radianToDirection(l),d.normalize();for(let y=1;yi&&(o>r.valueExceededMaximum&&(r.valueExceededMaximum=o),o=i),n=r.weight/100,n>=1||(o=t[0]*(1-n)+o*n),t[0]=o}function Lt(t,e,i,s,r,a,o,n){let l=0;const h=g.max(i,e);ht&&(t=u);const d=g.min(r,a),c=g.max(r,a),m=o,p=Pt(u,h),_=t-p;switch(Math.sign(_)){case 1:{const t=c-m,e=h-p;0!=e&&(l=_*(t/e),l+=m);break}case-1:{const t=d-m,e=u-p;0!=e&&(l=_*(t/e),l+=m);break}case 0:l=m}return n?l:-1*l}class Tt{constructor(t=0,e=0,i=0,s=0){this.x=t,this.y=e,this.width=i,this.height=s}getCenterX(){return this.x+.5*this.width}getCenterY(){return this.y+.5*this.height}getRight(){return this.x+this.width}getBottom(){return this.y+this.height}setRect(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}expand(t,e){this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e}}let Et,Dt,Ft;class At{getChannelFlagAsColor(t){return this._channelColors[t]}getMaskRenderTexture(){let t=0;if(this._maskTexture&&0!=this._maskTexture.texture&&(this._maskTexture.frameNo=this._currentFrameNo,t=this._maskTexture.texture),0==t){const e=this._clippingMaskBufferSize;this._colorBuffer=this.gl.createTexture(),this.gl.bindTexture(this.gl.TEXTURE_2D,this._colorBuffer),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,e,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindTexture(this.gl.TEXTURE_2D,null),t=this.gl.createFramebuffer(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,t),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this._colorBuffer,0),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Ft),this._maskTexture=new Bt(this._currentFrameNo,t)}return t}setGL(t){this.gl=t}calcClippedDrawTotalBounds(t,e){let i=Number.MAX_VALUE,s=Number.MAX_VALUE,r=Number.MIN_VALUE,a=Number.MIN_VALUE;const o=e._clippedDrawableIndexList.length;for(let n=0;nc&&(c=e),im&&(m=i)}if(u!=Number.MAX_VALUE)if(ur&&(r=c),m>a&&(a=m),i==Number.MAX_VALUE)e._allClippedDrawRect.x=0,e._allClippedDrawRect.y=0,e._allClippedDrawRect.width=0,e._allClippedDrawRect.height=0,e._isUsing=!1;else{e._isUsing=!0;const t=r-i,o=a-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=o}}}constructor(){this._maskRenderTexture=null,this._colorBuffer=null,this._currentFrameNo=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=[],this._clippingContextListForDraw=[],this._channelColors=[],this._tmpBoundsOnModel=new Tt,this._tmpMatrix=new p,this._tmpMatrixForMask=new p,this._tmpMatrixForDraw=new p;let t=new y;t.R=1,t.G=0,t.B=0,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=1,t.B=0,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=0,t.B=1,t.A=0,this._channelColors.push(t),t=new y,t.R=0,t.G=0,t.B=0,t.A=1,this._channelColors.push(t)}release(){var t,e,i;const s=this;for(let r=0;r0){this.gl.viewport(0,0,this._clippingMaskBufferSize,this._clippingMaskBufferSize),this._maskRenderTexture=this.getMaskRenderTexture(),e.getMvpMatrix(),e.preDraw(),this.setupLayoutBounds(i),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._maskRenderTexture),this.gl.clearColor(1,1,1,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT);for(let i=0;i(t[t.ShaderNames_SetupMask=0]="ShaderNames_SetupMask",t[t.ShaderNames_NormalPremultipliedAlpha=1]="ShaderNames_NormalPremultipliedAlpha",t[t.ShaderNames_NormalMaskedPremultipliedAlpha=2]="ShaderNames_NormalMaskedPremultipliedAlpha",t[t.ShaderNames_NomralMaskedInvertedPremultipliedAlpha=3]="ShaderNames_NomralMaskedInvertedPremultipliedAlpha",t[t.ShaderNames_AddPremultipliedAlpha=4]="ShaderNames_AddPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlpha=5]="ShaderNames_AddMaskedPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlphaInverted=6]="ShaderNames_AddMaskedPremultipliedAlphaInverted",t[t.ShaderNames_MultPremultipliedAlpha=7]="ShaderNames_MultPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlpha=8]="ShaderNames_MultMaskedPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlphaInverted=9]="ShaderNames_MultMaskedPremultipliedAlphaInverted",t))(kt||{});const Ut="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Nt="precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}",Vt="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",jt="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Gt="precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;void main(){ gl_FragColor = texture2D(s_texture0 , v_texCoord) * u_baseColor;}",Xt="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;void main(){ vec4 col_formask = texture2D(s_texture0 , v_texCoord) * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}",zt="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;void main(){vec4 col_formask = texture2D(s_texture0, v_texCoord) * u_baseColor;vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;col_formask = col_formask * (1.0 - maskVal);gl_FragColor = col_formask;}";class Wt extends _{constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._clippingManager=new At,this.firstDraw=!0,this._textures={},this._sortedDrawableIndexList=[],this._bufferData={vertex:null,uv:null,index:null}}initialize(t){t.isUsingMasking()&&(this._clippingManager=new At,this._clippingManager.initialize(t,t.getDrawableCount(),t.getDrawableMasks(),t.getDrawableMaskCounts()));for(let e=t.getDrawableCount()-1;e>=0;e--)this._sortedDrawableIndexList[e]=0;super.initialize(t)}bindTexture(t,e){this._textures[t]=e}getBindedTextures(){return this._textures}setClippingMaskBufferSize(t){this._clippingManager.release(),this._clippingManager=new At,this._clippingManager.setClippingMaskBufferSize(t),this._clippingManager.initialize(this.getModel(),this.getModel().getDrawableCount(),this.getModel().getDrawableMasks(),this.getModel().getDrawableMaskCounts())}getClippingMaskBufferSize(){return this._clippingManager.getClippingMaskBufferSize()}release(){var t,e,i;const s=this;this._clippingManager.release(),s._clippingManager=void 0,null==(t=this.gl)||t.deleteBuffer(this._bufferData.vertex),this._bufferData.vertex=null,null==(e=this.gl)||e.deleteBuffer(this._bufferData.uv),this._bufferData.uv=null,null==(i=this.gl)||i.deleteBuffer(this._bufferData.index),this._bufferData.index=null,s._bufferData=void 0,s._textures=void 0}doDrawModel(){this.preDraw(),null!=this._clippingManager&&this._clippingManager.setupClippingContext(this.getModel(),this);const t=this.getModel().getDrawableCount(),e=this.getModel().getDrawableRenderOrders();for(let i=0;i{Wt.doStaticRelease()};class Ht{constructor(t){this.groups=t.Groups,this.hitAreas=t.HitAreas,this.layout=t.Layout,this.moc=t.FileReferences.Moc,this.expressions=t.FileReferences.Expressions,this.motions=t.FileReferences.Motions,this.textures=t.FileReferences.Textures,this.physics=t.FileReferences.Physics,this.pose=t.FileReferences.Pose}getEyeBlinkParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"EyeBlink"===t.Name)))?void 0:e.Ids}getLipSyncParameters(){var t,e;return null==(e=null==(t=this.groups)?void 0:t.find((t=>"LipSync"===t.Name)))?void 0:e.Ids}}const Yt="ParamAngleX",qt="ParamAngleY",$t="ParamAngleZ",Zt="ParamEyeBallX",Jt="ParamEyeBallY",Qt="ParamBodyAngleX",Kt="ParamBreath";var te;t.config=void 0,(te=t.config||(t.config={})).LOG_LEVEL_VERBOSE=0,te.LOG_LEVEL_WARNING=1,te.LOG_LEVEL_ERROR=2,te.LOG_LEVEL_NONE=999,te.logLevel=te.LOG_LEVEL_WARNING,te.sound=!0,te.motionSync=!0,te.motionFadingDuration=500,te.idleMotionFadingDuration=2e3,te.expressionFadingDuration=500,te.preserveExpressionOnMotion=!0,te.cubism4=t.CubismConfig;const ee={log(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_VERBOSE&&console.log(`[${e}]`,...i)},warn(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_WARNING&&console.warn(`[${e}]`,...i)},error(e,...i){t.config.logLevel<=t.config.LOG_LEVEL_ERROR&&console.error(`[${e}]`,...i)}};function ie(t,e,i){return ti?i:t}function se(t,e){e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))}))}))}function re(t){let e=t.lastIndexOf("/");return-1!=e&&(t=t.slice(0,e)),e=t.lastIndexOf("/"),-1!==e&&(t=t.slice(e+1)),t}function ae(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}class oe extends e.EventEmitter{constructor(t,e){super(),this.expressions=[],this.reserveExpressionIndex=-1,this.destroyed=!1,this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createExpression({},void 0),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}loadExpression(t){return __async(this,null,(function*(){if(!this.definitions[t])return void ee.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void ee.warn(this.tag,`Cannot set expression at [${t}] because it's already failed in loading.`);if(this.expressions[t])return this.expressions[t];const e=yield this._loadExpression(t);return this.expressions[t]=e,e}))}_loadExpression(t){throw new Error("Not implemented.")}setRandomExpression(){return __async(this,null,(function*(){if(this.definitions.length){const t=[];for(let e=0;e-1&&tl&&(a*=l/n,o*=l/n),this.vx+=a,this.vy+=o;const h=Math.sqrt(__pow(this.vx,2)+__pow(this.vy,2)),u=.5*(Math.sqrt(__pow(l,2)+8*l*s)-l);h>u&&(this.vx*=u/h,this.vy*=u/h),this.x+=this.vx,this.y+=this.vy}}class le{constructor(t){this.json=t;let e=t.url;if("string"!=typeof e)throw new TypeError("The `url` field in settings JSON must be defined as a string.");this.url=e,this.name=re(this.url)}resolveURL(t){return e.url.resolve(this.url,t)}replaceFiles(t){this.moc=t(this.moc,"moc"),void 0!==this.pose&&(this.pose=t(this.pose,"pose")),void 0!==this.physics&&(this.physics=t(this.physics,"physics"));for(let e=0;e(t.push(e),e))),t}validateFiles(t){const e=(e,i)=>{const s=this.resolveURL(e);if(!t.includes(s)){if(i)throw new Error(`File "${e}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach((t=>e(t,!0)));return this.getDefinedFiles().filter((t=>e(t,!1)))}}var he=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(he||{});class ue{constructor(){this.debug=!1,this.currentPriority=0,this.reservePriority=0}reserve(t,e,i){if(i<=0)return ee.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return ee.log(this.tag,"Motion is already playing.",this.dump(t,e)),!1;if(t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex)return ee.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return ee.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return ee.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(t,e)),!1;this.setReservedIdle(t,e)}else{if(i<3){if(i<=this.currentPriority)return ee.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(t,e)),!1;if(i<=this.reservePriority)return ee.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(t,e)),!1}this.setReserved(t,e,i)}return!0}start(t,e,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return ee.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,i)),!1}else{if(e!==this.reservedGroup||i!==this.reservedIndex)return ee.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(e,i)),!1;this.setReserved(void 0,void 0,0)}return!!t&&(this.setCurrent(e,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(t,e,i){this.currentPriority=i,this.currentGroup=t,this.currentIndex=e}setReserved(t,e,i){this.reservePriority=i,this.reservedGroup=t,this.reservedIndex=e}setReservedIdle(t,e){this.reservedIdleGroup=t,this.reservedIdleIndex=e}isActive(t,e){return t===this.currentGroup&&e===this.currentIndex||t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex}reset(){this.setCurrent(void 0,void 0,0),this.setReserved(void 0,void 0,0),this.setReservedIdle(void 0,void 0)}shouldRequestIdleMotion(){return void 0===this.currentGroup&&void 0===this.reservedIdleGroup}shouldOverrideExpression(){return!t.config.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map((t=>"["+t+"] "+this[t])).join("\n")}return""}}class de{static get volume(){return this._volume}static set volume(t){this._volume=(t>1?1:t<0?0:t)||0,this.audios.forEach((t=>t.volume=this._volume))}static add(t,e,i){const s=new Audio(t);return s.volume=this._volume,s.preload="auto",s.addEventListener("ended",(()=>{this.dispose(s),null==e||e()})),s.addEventListener("error",(e=>{this.dispose(s),ee.warn("SoundManager",`Error occurred on "${t}"`,e.error),null==i||i(e.error)})),this.audios.push(s),s}static play(t){return new Promise(((e,i)=>{var s;null==(s=t.play())||s.catch((e=>{t.dispatchEvent(new ErrorEvent("error",{error:e})),i(e)})),t.readyState===t.HAVE_ENOUGH_DATA?e():t.addEventListener("canplaythrough",e)}))}static dispose(t){t.pause(),t.removeAttribute("src"),ae(this.audios,t)}static destroy(){for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}de.audios=[],de._volume=.5;var ce=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(ce||{});class me extends e.EventEmitter{constructor(t,e){super(),this.motionGroups={},this.state=new ue,this.playing=!1,this.destroyed=!1,this.settings=t,this.tag=`MotionManager(${t.name})`,this.state.tag=this.tag}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let e;switch(null==t?void 0:t.motionPreload){case"NONE":return;case"ALL":e=Object.keys(this.definitions);break;default:e=[this.groups.idle]}for(const i of e)if(this.definitions[i])for(let t=0;tthis.currentAudio=void 0),(()=>this.currentAudio=void 0)),this.currentAudio=o}catch(l){ee.warn(this.tag,"Failed to create audio",t,l)}}const n=yield this.loadMotion(e,i);if(o){const e=de.play(o).catch((t=>ee.warn(this.tag,"Failed to play audio",o.src,t)));t.config.motionSync&&(yield e)}return this.state.start(n,e,i,s)?(ee.log(this.tag,"Start motion:",this.getMotionName(a)),this.emit("motionStart",e,i,o),this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),this.playing=!0,this._startMotion(n),!0):(o&&(de.dispose(o),this.currentAudio=void 0),!1)}))}startRandomMotion(t,e){return __async(this,null,(function*(){const i=this.definitions[t];if(null==i?void 0:i.length){const s=[];for(let e=0;et.index>=0));for(const e of t)this.hitAreas[e.name]=e}hitTest(t,e){return Object.keys(this.hitAreas).filter((i=>this.isHit(i,t,e)))}isHit(t,e,i){if(!this.hitAreas[t])return!1;const s=this.hitAreas[t].index,r=this.getDrawableBounds(s,ge);return r.x<=e&&e<=r.x+r.width&&r.y<=i&&i<=r.y+r.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],a=i[1],o=i[1];for(let n=0;n{200!==a.status&&0!==a.status||!a.response?a.onerror():s(a.response)},a.onerror=()=>{ee.warn("XHRLoader",`Failed to load resource as ${a.responseType} (Status ${a.status}): ${e}`),r(new _e("Network error.",e,a.status))},a.onabort=()=>r(new _e("Aborted.",e,a.status,!0)),a.onloadend=()=>{var e;fe.allXhrSet.delete(a),t&&(null==(e=fe.xhrMap.get(t))||e.delete(a))},a}static cancelXHRs(){var t;null==(t=fe.xhrMap.get(this))||t.forEach((t=>{t.abort(),fe.allXhrSet.delete(t)})),fe.xhrMap.delete(this)}static release(){fe.allXhrSet.forEach((t=>t.abort())),fe.allXhrSet.clear(),fe.xhrMap=new WeakMap}};let ye=fe;function xe(t,e){let i=-1;return function s(r,a){if(a)return Promise.reject(a);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const o=t[r];if(!o)return Promise.resolve();try{return Promise.resolve(o(e,s.bind(null,r+1)))}catch(n){return Promise.reject(n)}}(0)}ye.xhrMap=new WeakMap,ye.allXhrSet=new Set,ye.loader=(t,e)=>new Promise(((e,i)=>{fe.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,(i=>{t.result=i,e()}),i).send()}));class ve{static load(t){return xe(this.middlewares,t).then((()=>t.result))}}ve.middlewares=[ye.loader];const Me="Live2DFactory",Pe=(t,e)=>__async(this,null,(function*(){if("string"==typeof t.source){const e=yield ve.load({url:t.source,type:"json",target:t.live2dModel});e.url=t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()})),Ce=(t,e)=>__async(this,null,(function*(){if(t.source instanceof le)return t.settings=t.source,e();if("object"==typeof t.source){const i=Te.findRuntime(t.source);if(i){const s=i.createModelSettings(t.source);return t.settings=s,t.live2dModel.emit("settingsLoaded",s),e()}}throw new TypeError("Unknown settings format.")})),Se=(t,e)=>{if(t.settings){const i=Te.findRuntime(t.settings);if(i)return i.ready().then(e)}return e()},be=(t,e)=>__async(this,null,(function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=Te.findRuntime(e);if(s){const r=[];e.pose&&r.push(ve.load({settings:e,url:e.pose,type:"json",target:i}).then((e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)})).catch((e=>{t.live2dModel.emit("poseLoadError",e),ee.warn(Me,"Failed to load pose.",e)}))),e.physics&&r.push(ve.load({settings:e,url:e.physics,type:"json",target:i}).then((e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)})).catch((e=>{t.live2dModel.emit("physicsLoadError",e),ee.warn(Me,"Failed to load physics.",e)}))),r.length&&(yield Promise.all(r))}}})),we=(t,e)=>__async(this,null,(function*(){if(!t.settings)throw new TypeError("Missing settings.");{const i=t.live2dModel,r=t.settings.textures.map((e=>function(t,e={}){const i={resourceOptions:{crossorigin:e.crossOrigin}};if(s.Texture.fromURL)return s.Texture.fromURL(t,i).catch((t=>{if(t instanceof Error)throw t;const e=new Error("Texture loading error");throw e.event=t,e}));i.resourceOptions.autoLoad=!1;const r=s.Texture.from(t,i);if(r.baseTexture.valid)return Promise.resolve(r);const a=r.baseTexture.resource;return null!=a._live2d_load||(a._live2d_load=new Promise(((t,e)=>{const i=t=>{a.source.removeEventListener("error",i);const s=new Error("Texture loading error");s.event=t,e(s)};a.source.addEventListener("error",i),a.load().then((()=>t(r))).catch(i)}))),a._live2d_load}(t.settings.resolveURL(e),{crossOrigin:t.options.crossOrigin})));if(yield e(),!t.internalModel)throw new TypeError("Missing internal model.");i.internalModel=t.internalModel,i.emit("modelLoaded",t.internalModel),i.textures=yield Promise.all(r),i.emit("textureLoaded",i.textures)}})),Ie=(t,e)=>__async(this,null,(function*(){const i=t.settings;if(i instanceof le){const s=Te.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield ve.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const a=s.createCoreModel(r);return t.internalModel=s.createInternalModel(a,i,t.options),e()}throw new TypeError("Missing settings.")})),Le=class{static registerRuntime(t){Le.runtimes.push(t),Le.runtimes.sort(((t,e)=>e.version-t.version))}static findRuntime(t){for(const e of Le.runtimes)if(e.test(t))return e}static setupLive2DModel(t,e,i){return __async(this,null,(function*(){const s=new Promise((e=>t.once("textureLoaded",e))),r=new Promise((e=>t.once("modelLoaded",e))),a=Promise.all([s,r]).then((()=>t.emit("ready")));yield xe(Le.live2DModelMiddlewares,{live2dModel:t,source:e,options:i||{}}),yield a,t.emit("load")}))}static loadMotion(t,e,i){var s;const r=s=>t.emit("motionLoadError",e,i,s);try{const a=null==(s=t.definitions[e])?void 0:s[i];if(!a)return Promise.resolve(void 0);t.listeners("destroy").includes(Le.releaseTasks)||t.once("destroy",Le.releaseTasks);let o=Le.motionTasksMap.get(t);o||(o={},Le.motionTasksMap.set(t,o));let n=o[e];n||(n=[],o[e]=n);const l=t.getMotionFile(a);return null!=n[i]||(n[i]=ve.load({url:l,settings:t.settings,type:t.motionDataType,target:t}).then((s=>{var r;const o=null==(r=Le.motionTasksMap.get(t))?void 0:r[e];o&&delete o[i];const n=t.createMotion(s,e,a);return t.emit("motionLoaded",e,i,n),n})).catch((e=>{ee.warn(t.tag,`Failed to load motion: ${l}\n`,e),r(e)}))),n[i]}catch(a){ee.warn(t.tag,`Failed to load motion at "${e}"[${i}]\n`,a),r(a)}return Promise.resolve(void 0)}static loadExpression(t,e){const i=i=>t.emit("expressionLoadError",e,i);try{const s=t.definitions[e];if(!s)return Promise.resolve(void 0);t.listeners("destroy").includes(Le.releaseTasks)||t.once("destroy",Le.releaseTasks);let r=Le.expressionTasksMap.get(t);r||(r=[],Le.expressionTasksMap.set(t,r));const a=t.getExpressionFile(s);return null!=r[e]||(r[e]=ve.load({url:a,settings:t.settings,type:"json",target:t}).then((i=>{const r=Le.expressionTasksMap.get(t);r&&delete r[e];const a=t.createExpression(i,s);return t.emit("expressionLoaded",e,a),a})).catch((e=>{ee.warn(t.tag,`Failed to load expression: ${a}\n`,e),i(e)}))),r[e]}catch(s){ee.warn(t.tag,`Failed to load expression at [${e}]\n`,s),i(s)}return Promise.resolve(void 0)}static releaseTasks(){this instanceof me?Le.motionTasksMap.delete(this):Le.expressionTasksMap.delete(this)}};let Te=Le;Te.runtimes=[],Te.urlToJSON=Pe,Te.jsonToSettings=Ce,Te.waitUntilReady=Se,Te.setupOptionals=be,Te.setupEssentials=we,Te.createInternalModel=Ie,Te.live2DModelMiddlewares=[Pe,Ce,Se,be,we,Ie],Te.motionTasksMap=new WeakMap,Te.expressionTasksMap=new WeakMap,me.prototype._loadMotion=function(t,e){return Te.loadMotion(this,t,e)},oe.prototype._loadExpression=function(t){return Te.loadExpression(this,t)};class Ee{constructor(){this._autoInteract=!1}get autoInteract(){return this._autoInteract}set autoInteract(t){t!==this._autoInteract&&(t?this.on("pointertap",De,this):this.off("pointertap",De,this),this._autoInteract=t)}registerInteraction(t){t!==this.interactionManager&&(this.unregisterInteraction(),this._autoInteract&&t&&(this.interactionManager=t,t.on("pointermove",Fe,this)))}unregisterInteraction(){var t;this.interactionManager&&(null==(t=this.interactionManager)||t.off("pointermove",Fe,this),this.interactionManager=void 0)}}function De(t){this.tap(t.data.global.x,t.data.global.y)}function Fe(t){this.focus(t.data.global.x,t.data.global.y)}class Ae extends i.Transform{}const Be=new i.Point,Re=new i.Matrix;let Oe;class ke extends r.Container{constructor(t){super(),this.tag="Live2DModel(uninitialized)",this.textures=[],this.transform=new Ae,this.anchor=new i.ObservablePoint(this.onAnchorChange,this,0,0),this.glContextID=-1,this.elapsedTime=performance.now(),this.deltaTime=0,this._autoUpdate=!1,this.once("modelLoaded",(()=>this.init(t)))}static from(t,e){const i=new this(e);return Te.setupLive2DModel(i,t,e).then((()=>i))}static fromSync(t,e){const i=new this(e);return Te.setupLive2DModel(i,t,e).then(null==e?void 0:e.onLoad).catch(null==e?void 0:e.onError),i}static registerTicker(t){Oe=t}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;Oe||(Oe=null==(e=window.PIXI)?void 0:e.Ticker),t?this._destroyed||(Oe?(Oe.shared.add(this.onTickerUpdate,this),this._autoUpdate=!0):ee.warn(this.tag,"No Ticker registered, please call Live2DModel.registerTicker(Ticker).")):(null==Oe||Oe.shared.remove(this.onTickerUpdate,this),this._autoUpdate=!1)}init(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`;const e=Object.assign({autoUpdate:!0,autoInteract:!0},t);e.autoInteract&&(this.interactive=!0),this.autoInteract=e.autoInteract,this.autoUpdate=e.autoUpdate}onAnchorChange(){this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i):this.internalModel.motionManager.startMotion(t,e,i)}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){Be.x=t,Be.y=e,this.toModelPosition(Be,Be,!0);let s=Be.x/this.internalModel.originalWidth*2-1,r=Be.y/this.internalModel.originalHeight*2-1,a=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(a),-Math.sin(a),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&(ee.log(this.tag,"Hit",i),this.emit("hit",i))}hitTest(t,e){return Be.x=t,Be.y=e,this.toModelPosition(Be,Be),this.internalModel.hitTest(Be.x,Be.y)}toModelPosition(t,e=t.clone(),i){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.transform.worldTransform.applyInverse(t,e),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.getBounds(!0).contains(t.x,t.y)}_calculateBounds(){this._bounds.addFrame(this.transform,0,0,this.internalModel.width,this.internalModel.height)}onTickerUpdate(){this.update(Oe.shared.deltaMS)}update(t){this.deltaTime+=t,this.elapsedTime+=t}_render(t){this.registerInteraction(t.plugins.interaction),t.batch.reset(),t.geometry.reset(),t.shader.reset(),t.state.reset();let e=!1;this.glContextID!==t.CONTEXT_UID&&(this.glContextID=t.CONTEXT_UID,this.internalModel.updateWebGLContext(t.gl,this.glContextID),e=!0);for(let r=0;re.destroy(t.baseTexture))),this.internalModel.destroy(),super.destroy(t)}}se(ke,[Ee]);const Ue=class{static resolveURL(t,e){var i;const s=null==(i=Ue.filesMap[t])?void 0:i[e];if(void 0===s)throw new Error("Cannot find this file from uploaded files: "+e);return s}static upload(t,i){return __async(this,null,(function*(){const s={};for(const r of i.getDefinedFiles()){const a=decodeURI(e.url.resolve(i.url,r)),o=t.find((t=>t.webkitRelativePath===a));o&&(s[r]=URL.createObjectURL(o))}Ue.filesMap[i._objectURL]=s}))}static createSettings(t){return __async(this,null,(function*(){const e=t.find((t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json")));if(!e)throw new TypeError("Settings file not found");const i=yield Ue.readText(e),s=JSON.parse(i);s.url=e.webkitRelativePath;const r=Te.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");const a=r.createModelSettings(s);return a._objectURL=URL.createObjectURL(e),a}))}static readText(t){return __async(this,null,(function*(){return new Promise(((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")}))}))}};let Ne=Ue;Ne.filesMap={},Ne.factory=(t,e)=>__async(this,null,(function*(){if(Array.isArray(t.source)&&t.source[0]instanceof File){const e=t.source;let i=e.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield Ue.createSettings(e);i.validateFiles(e.map((t=>encodeURI(t.webkitRelativePath)))),yield Ue.upload(e,i),i.resolveURL=function(t){return Ue.resolveURL(this._objectURL,t)},t.source=i,t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){const t=this.settings._objectURL;if(URL.revokeObjectURL(t),Ue.filesMap[t])for(const e of Object.values(Ue.filesMap[t]))URL.revokeObjectURL(e);delete Ue.filesMap[t]}))}))}return e()})),Te.live2DModelMiddlewares.unshift(Ne.factory);const Ve=class{static unzip(t,i){return __async(this,null,(function*(){const s=yield Ve.getFilePaths(t),r=[];for(const t of i.getDefinedFiles()){const a=decodeURI(e.url.resolve(i.url,t));s.includes(a)&&r.push(a)}const a=yield Ve.getFiles(t,r);for(let t=0;tt.endsWith("model.json")||t.endsWith("model3.json")));if(!e)throw new Error("Settings file not found");const i=yield Ve.readText(t,e);if(!i)throw new Error("Empty settings file: "+e);const s=JSON.parse(i);s.url=e;const r=Te.findRuntime(s);if(!r)throw new Error("Unknown settings JSON");return r.createModelSettings(s)}))}static zipReader(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFilePaths(t){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static getFiles(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static readText(t,e){return __async(this,null,(function*(){throw new Error("Not implemented")}))}static releaseReader(t){}};let je=Ve;if(je.ZIP_PROTOCOL="zip://",je.uid=0,je.factory=(t,e)=>__async(this,null,(function*(){const i=t.source;let s,r,a;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(Ve.ZIP_PROTOCOL))?(s=i.startsWith(Ve.ZIP_PROTOCOL)?i.slice(Ve.ZIP_PROTOCOL.length):i,r=yield ve.load({url:s,type:"blob",target:t.live2dModel})):Array.isArray(i)&&1===i.length&&i[0]instanceof File&&i[0].name.endsWith(".zip")&&(r=i[0],s=URL.createObjectURL(r),a=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield Ve.zipReader(r,s);a||(a=yield Ve.createSettings(e)),a._objectURL=Ve.ZIP_PROTOCOL+Ve.uid+"/"+a.url;const i=yield Ve.unzip(e,a);i.settings=a,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",(t=>{t.once("destroy",(function(){URL.revokeObjectURL(s)}))})),Ve.releaseReader(e)}return e()})),Te.live2DModelMiddlewares.unshift(je.factory),!window.Live2DCubismCore)throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");class Ge extends oe{constructor(t,e){var i;super(t,e),this.queueManager=new st,this.definitions=null!=(i=t.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex((e=>e.Name===t))}getExpressionFile(t){return t.File}createExpression(t,e){return O.create(t)}_setExpression(t){return this.queueManager.startMotion(t,!1,performance.now())}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}}class Xe extends le{constructor(t){if(super(t),!Xe.isValidJSON(t))throw new TypeError("Invalid JSON.");Object.assign(this,new Ht(t))}static isValidJSON(t){var e;return!!(null==t?void 0:t.FileReferences)&&"string"==typeof t.FileReferences.Moc&&(null==(e=t.FileReferences.Textures)?void 0:e.length)>0&&t.FileReferences.Textures.every((t=>"string"==typeof t))}replaceFiles(t){if(super.replaceFiles(t),this.motions)for(const[e,i]of Object.entries(this.motions))for(let s=0;s{this.emit("motion:"+e)}))}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e){return t.setFinishedMotionHandler(e),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1,performance.now())}_stopAllMotions(){this.queueManager.stopAllMotions()}createMotion(e,i,s){const r=et.create(e),a=new H(e),o=(i===this.groups.idle?t.config.idleMotionFadingDuration:t.config.motionFadingDuration)/1e3;return void 0===a.getMotionFadeInTime()&&r.setFadeInTime(s.FadeInTime>0?s.FadeInTime:o),void 0===a.getMotionFadeOutTime()&&r.setFadeOutTime(s.FadeOutTime>0?s.FadeOutTime:o),r.setEffectIds(this.eyeBlinkIds,this.lipSyncIds),r}getMotionFile(t){return t.File}getMotionName(t){return t.File}getSoundFile(t){return t.Sound}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}}const We=new p;class He extends pe{constructor(t,e,s){super(),this.lipSync=!0,this.breath=a.create(),this.renderer=new Wt,this.idParamAngleX=Yt,this.idParamAngleY=qt,this.idParamAngleZ=$t,this.idParamEyeBallX=Zt,this.idParamEyeBallY=Jt,this.idParamBodyAngleX=Qt,this.idParamBreath=Kt,this.pixelsPerUnit=1,this.centeringTransform=new i.Matrix,this.coreModel=t,this.settings=e,this.motionManager=new ze(e,s),this.init()}init(){var t;super.init(),(null==(t=this.settings.getEyeBlinkParameters())?void 0:t.length)>0&&(this.eyeBlink=l.create(this.settings)),this.breath.setParameters([new o(this.idParamAngleX,0,15,6.5345,.5),new o(this.idParamAngleY,0,8,3.5345,.5),new o(this.idParamAngleZ,0,10,5.5345,.5),new o(this.idParamBodyAngleX,0,4,15.5345,.5),new o(this.idParamBreath,0,.5,3.2345,.5)]),this.renderer.initialize(this.coreModel),this.renderer.setIsPremultipliedAlpha(!0)}getSize(){return[this.coreModel.getModel().canvasinfo.CanvasWidth,this.coreModel.getModel().canvasinfo.CanvasHeight]}getLayout(){const t={};if(this.settings.layout)for(const e of Object.keys(this.settings.layout)){t[e.charAt(0).toLowerCase()+e.slice(1)]=this.settings.layout[e]}return t}setupLayout(){super.setupLayout(),this.pixelsPerUnit=this.coreModel.getModel().canvasinfo.PixelsPerUnit,this.centeringTransform.scale(this.pixelsPerUnit,this.pixelsPerUnit).translate(this.originalWidth/2,this.originalHeight/2)}updateWebGLContext(t,e){this.renderer.firstDraw=!0,this.renderer._bufferData={vertex:null,uv:null,index:null},this.renderer.startUp(t),this.renderer._clippingManager._currentFrameNo=e,this.renderer._clippingManager._maskTexture=void 0,Ot.getInstance()._shaderSets=[]}bindTexture(t,e){this.renderer.bindTexture(t,e)}getHitAreaDefs(){var t,e;return null!=(e=null==(t=this.settings.hitAreas)?void 0:t.map((t=>({id:t.Id,name:t.Name,index:this.coreModel.getDrawableIndex(t.Id)}))))?e:[]}getDrawableIDs(){return this.coreModel.getDrawableIds()}getDrawableIndex(t){return this.coreModel.getDrawableIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawableIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);const e=this.coreModel.getDrawableVertices(t).slice();for(let i=0;i{!function i(){try{Ze(),t()}catch(s){if(qe--,qe<0){const t=new Error("Failed to start up Cubism 4 framework.");return t.cause=s,void e(t)}ee.log("Cubism4","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()}))),Ye)}function Ze(t){t=Object.assign({logFunction:console.log,loggingLevel:S.LogLevel_Verbose},t),C.startUp(t),C.initialize()}function Je(){var t;null==(t=this.__moc)||t.release()}Te.registerRuntime({version:4,ready:$e,test:t=>t instanceof Xe||Xe.isValidJSON(t),isValidMoc(t){if(t.byteLength<4)return!1;const e=new Int8Array(t,0,4);return"MOC3"===String.fromCharCode(...e)},createModelSettings:t=>new Xe(t),createCoreModel(t){const e=F.create(t);try{const t=e.createModel();return t.__moc=e,t}catch(i){try{e.release()}catch(s){}throw i}},createInternalModel(t,e,i){const s=new He(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",Je)),s},createPhysics:(t,e)=>gt.create(e),createPose:(t,e)=>u.create(e)}),t.ACubismMotion=R,t.BreathParameterData=o,t.CSM_ASSERT=b,t.Constant=P,t.Cubism4ExpressionManager=Ge,t.Cubism4InternalModel=He,t.Cubism4ModelSettings=Xe,t.Cubism4MotionManager=ze,t.CubismBlendMode=f,t.CubismBreath=a,t.CubismClippingContext=Rt,t.CubismClippingManager_WebGL=At,t.CubismDebug=E,t.CubismExpressionMotion=O,t.CubismEyeBlink=l,t.CubismFramework=C,t.CubismLogDebug=w,t.CubismLogError=T,t.CubismLogInfo=I,t.CubismLogVerbose=function(t,...e){E.print(S.LogLevel_Verbose,"[CSM][V]"+t+"\n",e)},t.CubismLogWarning=L,t.CubismMath=g,t.CubismMatrix44=p,t.CubismMoc=F,t.CubismModel=D,t.CubismModelSettingsJson=Ht,t.CubismModelUserData=B,t.CubismModelUserDataJson=A,t.CubismMotion=et,t.CubismMotionCurve=X,t.CubismMotionCurveTarget=N,t.CubismMotionData=W,t.CubismMotionEvent=z,t.CubismMotionJson=H,t.CubismMotionManager=class extends st{constructor(){super(),this._currentPriority=0,this._reservePriority=0}getCurrentPriority(){return this._currentPriority}getReservePriority(){return this._reservePriority}setReservePriority(t){this._reservePriority=t}startMotionPriority(t,e,i){return i==this._reservePriority&&(this._reservePriority=0),this._currentPriority=i,super.startMotion(t,e,this._userTimeSeconds)}updateMotion(t,e){this._userTimeSeconds+=e;const i=super.doUpdateMotion(t,this._userTimeSeconds);return this.isFinished()&&(this._currentPriority=0),i}reserveMotion(t){return!(t<=this._reservePriority||t<=this._currentPriority)&&(this._reservePriority=t,!0)}},t.CubismMotionPoint=j,t.CubismMotionQueueEntry=it,t.CubismMotionQueueManager=st,t.CubismMotionSegment=G,t.CubismMotionSegmentType=V,t.CubismPhysics=gt,t.CubismPhysicsInput=ht,t.CubismPhysicsJson=ct,t.CubismPhysicsOutput=ut,t.CubismPhysicsParticle=nt,t.CubismPhysicsRig=dt,t.CubismPhysicsSource=ot,t.CubismPhysicsSubRig=lt,t.CubismPhysicsTargetType=at,t.CubismPose=u,t.CubismRenderTextureResource=Bt,t.CubismRenderer=_,t.CubismRenderer_WebGL=Wt,t.CubismShader_WebGL=Ot,t.CubismTextureColor=y,t.CubismVector2=c,t.EvaluationOptionFlag=Y,t.ExpressionBlendType=U,t.ExpressionManager=oe,t.EyeState=h,t.FileLoader=Ne,t.FocusController=ne,t.HitAreaBody="Body",t.HitAreaHead="Head",t.HitAreaPrefix="HitArea",t.InteractionMixin=Ee,t.InternalModel=pe,t.InvalidMotionQueueEntryHandleValue=rt,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DFactory=Te,t.Live2DLoader=ve,t.Live2DModel=ke,t.Live2DTransform=Ae,t.LogLevel=S,t.ModelSettings=le,t.MotionManager=me,t.MotionPreloadStrategy=ce,t.MotionPriority=he,t.MotionState=ue,t.Options=pt,t.ParamAngleX=Yt,t.ParamAngleY=qt,t.ParamAngleZ=$t,t.ParamArmLA="ParamArmLA",t.ParamArmLB="ParamArmLB",t.ParamArmRA="ParamArmRA",t.ParamArmRB="ParamArmRB",t.ParamBaseX="ParamBaseX",t.ParamBaseY="ParamBaseY",t.ParamBodyAngleX=Qt,t.ParamBodyAngleY="ParamBodyAngleY",t.ParamBodyAngleZ="ParamBodyAngleZ",t.ParamBreath=Kt,t.ParamBrowLAngle="ParamBrowLAngle",t.ParamBrowLForm="ParamBrowLForm",t.ParamBrowLX="ParamBrowLX",t.ParamBrowLY="ParamBrowLY",t.ParamBrowRAngle="ParamBrowRAngle",t.ParamBrowRForm="ParamBrowRForm",t.ParamBrowRX="ParamBrowRX",t.ParamBrowRY="ParamBrowRY",t.ParamBustX="ParamBustX",t.ParamBustY="ParamBustY",t.ParamCheek="ParamCheek",t.ParamEyeBallForm="ParamEyeBallForm",t.ParamEyeBallX=Zt,t.ParamEyeBallY=Jt,t.ParamEyeLOpen="ParamEyeLOpen",t.ParamEyeLSmile="ParamEyeLSmile",t.ParamEyeROpen="ParamEyeROpen",t.ParamEyeRSmile="ParamEyeRSmile",t.ParamHairBack="ParamHairBack",t.ParamHairFluffy="ParamHairFluffy",t.ParamHairFront="ParamHairFront",t.ParamHairSide="ParamHairSide",t.ParamHandL="ParamHandL",t.ParamHandR="ParamHandR",t.ParamMouthForm="ParamMouthForm",t.ParamMouthOpenY="ParamMouthOpenY",t.ParamNONE="NONE:",t.ParamShoulderY="ParamShoulderY",t.PartData=d,t.PartsArmLPrefix="Parts01ArmL_",t.PartsArmPrefix="Parts01Arm_",t.PartsArmRPrefix="Parts01ArmR_",t.PartsIdCore="Parts01Core",t.PhysicsJsonEffectiveForces=class{constructor(){this.gravity=new c(0,0),this.wind=new c(0,0)}},t.ShaderNames=kt,t.SoundManager=de,t.VERSION="0.4.0",t.XHRLoader=ye,t.ZipLoader=je,t.applyMixins=se,t.clamp=ie,t.copyArray=function(t,e,i,s,r){const a=e[s];Array.isArray(a)&&(i[r]=a.filter((e=>null!==e&&typeof e===t)))},t.copyProperty=function(t,e,i,s,r){const a=e[s];null!==a&&typeof a===t&&(i[r]=a)},t.csmRect=Tt,t.cubism4Ready=$e,t.folderName=re,t.fragmentShaderSrcMaskInvertedPremultipliedAlpha=zt,t.fragmentShaderSrcMaskPremultipliedAlpha=Xt,t.fragmentShaderSrcPremultipliedAlpha=Gt,t.fragmentShaderSrcsetupMask=Nt,t.logger=ee,t.rand=function(t,e){return Math.random()*(e-t)+t},t.remove=ae,t.startUpCubism4=Ze,t.vertexShaderSrc=Vt,t.vertexShaderSrcMasked=jt,t.vertexShaderSrcSetupMask=Ut,Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})); diff --git a/main/feedback-backend/admin-ui/libs/libopus.js b/main/feedback-backend/admin-ui/libs/libopus.js new file mode 100644 index 000000000..bff6b2a52 --- /dev/null +++ b/main/feedback-backend/admin-ui/libs/libopus.js @@ -0,0 +1,266 @@ +var Module = function(Module) { + Module = Module || {}; + + var b;b||(b=eval("(function() { try { return Module || {} } catch(e) { return {} } })()"));var f={},l;for(l in b)b.hasOwnProperty(l)&&(f[l]=b[l]);var p=!1,q=!1,r=!1,t=!1; + if(b.ENVIRONMENT)if("WEB"===b.ENVIRONMENT)p=!0;else if("WORKER"===b.ENVIRONMENT)q=!0;else if("NODE"===b.ENVIRONMENT)r=!0;else if("SHELL"===b.ENVIRONMENT)t=!0;else throw Error("The provided Module['ENVIRONMENT'] value is not valid. It must be one of: WEB|WORKER|NODE|SHELL.");else p="object"===typeof window,q="function"===typeof importScripts,r="object"===typeof process&&"function"===typeof require&&!p&&!q,t=!p&&!r&&!q; + if(r){b.print||(b.print=console.log);b.printErr||(b.printErr=console.warn);var u,v;b.read=function(a,c){u||(u=null);v||(v=require("path"));a=v.normalize(a);var d=u.readFileSync(a);d||a==v.resolve(a)||(a=path.join(__dirname,"..","src",a),d=u.readFileSync(a));d&&!c&&(d=d.toString());return d};b.readBinary=function(a){a=b.read(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a};b.load=function(a){aa(read(a))};b.thisProgram||(b.thisProgram=1 0) var gc = undefined");else if(p||q)b.read=function(a){var c=new XMLHttpRequest;c.open("GET",a,!1);c.send(null);return c.responseText},b.readAsync=function(a,c,d){var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=function(){200== + e.status||0==e.status&&e.response?c(e.response):d()};e.onerror=d;e.send(null)},"undefined"!=typeof arguments&&(b.arguments=arguments),"undefined"!==typeof console?(b.print||(b.print=function(a){console.log(a)}),b.printErr||(b.printErr=function(a){console.warn(a)})):b.print||(b.print=function(){}),q&&(b.load=importScripts),"undefined"===typeof b.setWindowTitle&&(b.setWindowTitle=function(a){document.title=a});else throw"Unknown runtime environment. Where are we?";function aa(a){eval.call(null,a)} + !b.load&&b.read&&(b.load=function(a){aa(b.read(a))});b.print||(b.print=function(){});b.printErr||(b.printErr=b.print);b.arguments||(b.arguments=[]);b.thisProgram||(b.thisProgram="./this.program");b.print=b.print;b.m=b.printErr;b.preRun=[];b.postRun=[];for(l in f)f.hasOwnProperty(l)&&(b[l]=f[l]); + var f=void 0,y={B:function(a){tempRet0=a},w:function(){return tempRet0},g:function(){return x},c:function(a){x=a},q:function(a){switch(a){case "i1":case "i8":return 1;case "i16":return 2;case "i32":return 4;case "i64":return 8;case "float":return 4;case "double":return 8;default:return"*"===a[a.length-1]?y.i:"i"===a[0]?(a=parseInt(a.substr(1)),assert(0===a%8),a/8):0}},v:function(a){return Math.max(y.q(a),y.i)},C:16,Q:function(a,c){"double"===c||"i64"===c?a&7&&(assert(4===(a&7)),a+=4):assert(0===(a& + 3));return a},K:function(a,c,d){return d||"i64"!=a&&"double"!=a?a?Math.min(c||(a?y.v(a):0),y.i):Math.min(c,8):8},k:function(a,c,d){return d&&d.length?(d.splice||(d=Array.prototype.slice.call(d)),d.splice(0,0,c),b["dynCall_"+a].apply(null,d)):b["dynCall_"+a].call(null,c)},e:[],r:function(a){for(var c=0;c=F)G("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+ + F+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which adjusts the size at runtime but prevents some optimizations, (3) set Module.TOTAL_MEMORY to a higher value before the program runs, or if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 "),a=!0;return a?(E=c,0):c},p:function(a,c){return Math.ceil(a/(c?c:16))*(c?c:16)},P:function(a,c,d){return d?+(a>>>0)+4294967296*+(c>>>0):+(a>>>0)+4294967296*+(c|0)},h:8,i:4,D:0};b.Runtime=y;y.addFunction=y.r; + y.removeFunction=y.A;var H=!1;function assert(a,c){a||G("Assertion failed: "+c)}function ba(a){var c=b["_"+a];if(!c)try{c=eval("_"+a)}catch(d){}assert(c,"Cannot call unknown function "+a+" (perhaps LLVM optimizations or closure removed it?)");return c}var ca,da; + (function(){function a(a){a=a.toString().match(g).slice(1);return{arguments:a[0],body:a[1],returnValue:a[2]}}function c(){if(!k){k={};for(var c in d)d.hasOwnProperty(c)&&(k[c]=a(d[c]))}}var d={stackSave:function(){y.g()},stackRestore:function(){y.c()},arrayToC:function(a){var c=y.f(a.length);ea(a,c);return c},stringToC:function(a){var c=0;null!==a&&void 0!==a&&0!==a&&(c=y.f((a.length<<2)+1),fa(a,c));return c}},e={string:d.stringToC,array:d.arrayToC};da=function(a,c,d,g,k){a=ba(a);var C=[],D=0;if(g)for(var n= + 0;n>0]=c;break;case "i8":J[a>>0]=c;break;case "i16":L[a>>1]=c;break;case "i32":M[a>>2]=c;break;case "i64":tempI64=[c>>>0,(tempDouble=c,1<=+ha(tempDouble)?0>>0:~~+ka((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)];M[a>>2]=tempI64[0];M[a+4>>2]=tempI64[1];break;case "float":N[a>>2]=c;break;case "double":la[a>>3]=c;break;default:G("invalid type for setValue: "+ + d)}}b.setValue=ga;function ma(a,c){c=c||"i8";"*"===c.charAt(c.length-1)&&(c="i32");switch(c){case "i1":return J[a>>0];case "i8":return J[a>>0];case "i16":return L[a>>1];case "i32":return M[a>>2];case "i64":return M[a>>2];case "float":return N[a>>2];case "double":return la[a>>3];default:G("invalid type for setValue: "+c)}return null}b.getValue=ma;b.ALLOC_NORMAL=0;b.ALLOC_STACK=1;b.ALLOC_STATIC=2;b.ALLOC_DYNAMIC=3;b.ALLOC_NONE=4; + function O(a,c,d,e){var g,k;"number"===typeof a?(g=!0,k=a):(g=!1,k=a.length);var h="string"===typeof c?c:null;d=4==d?e:["function"===typeof Q?Q:y.o,y.f,y.o,y.b][void 0===d?2:d](Math.max(k,h?1:c.length));if(g){e=d;assert(0==(d&3));for(a=d+(k&-4);e>2]=0;for(a=d+k;e>0]=0;return d}if("i8"===h)return a.subarray||a.slice?R.set(a,d):R.set(new Uint8Array(a),d),d;e=0;for(var A,m;e>0];d|=e;if(0==e&&!c)break;g++;if(c&&g==c)break}c||(c=g);e="";if(128>d){for(;0>0];if(!d)return c;c+=String.fromCharCode(d)}};b.stringToAscii=function(a,c){return pa(a,c,!1)}; + function qa(a,c){for(var d,e,g,k,h,A,m="";;){d=a[c++];if(!d)return m;d&128?(e=a[c++]&63,192==(d&224)?m+=String.fromCharCode((d&31)<<6|e):(g=a[c++]&63,224==(d&240)?d=(d&15)<<12|e<<6|g:(k=a[c++]&63,240==(d&248)?d=(d&7)<<18|e<<12|g<<6|k:(h=a[c++]&63,248==(d&252)?d=(d&3)<<24|e<<18|g<<12|k<<6|h:(A=a[c++]&63,d=(d&1)<<30|e<<24|g<<18|k<<12|h<<6|A))),65536>d?m+=String.fromCharCode(d):(d-=65536,m+=String.fromCharCode(55296|d>>10,56320|d&1023)))):m+=String.fromCharCode(d)}}b.UTF8ArrayToString=qa; + b.UTF8ToString=function(a){return qa(R,a)}; + function ra(a,c,d,e){if(!(0=h&&(h=65536+((h&1023)<<10)|a.charCodeAt(++k)&1023);if(127>=h){if(d>=e)break;c[d++]=h}else{if(2047>=h){if(d+1>=e)break;c[d++]=192|h>>6}else{if(65535>=h){if(d+2>=e)break;c[d++]=224|h>>12}else{if(2097151>=h){if(d+3>=e)break;c[d++]=240|h>>18}else{if(67108863>=h){if(d+4>=e)break;c[d++]=248|h>>24}else{if(d+5>=e)break;c[d++]=252|h>>30;c[d++]=128|h>>24&63}c[d++]=128|h>>18&63}c[d++]=128| + h>>12&63}c[d++]=128|h>>6&63}c[d++]=128|h&63}}c[d]=0;return d-g}b.stringToUTF8Array=ra;b.stringToUTF8=function(a,c,d){return ra(a,R,c,d)};function sa(a){for(var c=0,d=0;d=e&&(e=65536+((e&1023)<<10)|a.charCodeAt(++d)&1023);127>=e?++c:c=2047>=e?c+2:65535>=e?c+3:2097151>=e?c+4:67108863>=e?c+5:c+6}return c}b.lengthBytesUTF8=sa; + function ta(){return ua().replace(/__Z[\w\d_]+/g,function(a){var c;a:{if(b.___cxa_demangle)try{var d=Q(a.length);fa(a.substr(1),d);var e=Q(4),g=b.___cxa_demangle(d,0,0,e);if(0===ma(e,"i32")&&g){c=I(g);break a}}catch(k){c=a;break a}finally{d&&va(d),e&&va(e),g&&va(g)}y.d("warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling");c=a}return a===c?a:a+" ["+c+"]"})} + function ua(){var a=Error();if(!a.stack){try{throw Error(0);}catch(c){a=c}if(!a.stack)return"(no stack trace available)"}return a.stack.toString()}b.stackTrace=function(){return ta()};function wa(){var a=E;0U?2*U:U+16777216;U!==F&&(F=U);b.buffer?buffer=b.buffer:buffer=new ArrayBuffer(F);b.HEAP8=J=new Int8Array(buffer); + b.HEAP16=L=new Int16Array(buffer);b.HEAP32=M=new Int32Array(buffer);b.HEAPU8=R=new Uint8Array(buffer);b.HEAPU16=xa=new Uint16Array(buffer);b.HEAPU32=ya=new Uint32Array(buffer);b.HEAPF32=N=new Float32Array(buffer);b.HEAPF64=la=new Float64Array(buffer);M[0]=255;if(255!==R[0]||0!==R[3])throw"Typed arrays 2 must be run on a little-endian system";b.HEAP=void 0;b.buffer=buffer;b.HEAP8=J;b.HEAP16=L;b.HEAP32=M;b.HEAPU8=R;b.HEAPU16=xa;b.HEAPU32=ya;b.HEAPF32=N;b.HEAPF64=la; + function V(a){for(;0>0]=a[d],d+=1}b.writeStringToMemory=fa;function ea(a,c){for(var d=0;d>0]=a[d]}b.writeArrayToMemory=ea; + function pa(a,c,d){for(var e=0;e>0]=a.charCodeAt(e);d||(J[c>>0]=0)}b.writeAsciiToMemory=pa;Math.imul&&-5===Math.imul(4294967295,5)||(Math.imul=function(a,c){var d=a&65535,e=c&65535;return d*e+((a>>>16)*e+d*(c>>>16)<<16)|0});Math.O=Math.imul;Math.clz32||(Math.clz32=function(a){a=a>>>0;for(var c=0;32>c;c++)if(a&1<<31-c)return c;return 32});Math.H=Math.clz32;var ha=Math.abs,ka=Math.ceil,ja=Math.floor,La=Math.pow,ia=Math.min,W=0,Ma=null,X=null; + b.addRunDependency=function(){W++;b.monitorRunDependencies&&b.monitorRunDependencies(W)};b.removeRunDependency=function(){W--;b.monitorRunDependencies&&b.monitorRunDependencies(W);if(0==W&&(null!==Ma&&(clearInterval(Ma),Ma=null),X)){var a=X;X=null;a()}};b.preloadedImages={};b.preloadedAudios={};za=8;z=za+31072;Ea.push(); + O([1,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,2,0,0,0,1,0,0,0,7,0,0,0,0,0,0,0,4,0,0,0,3,0,0,0,6,0,0,0,1,0,0,0,5,0,0,0,2,0,0,0,15,0,0,0,0,0,0,0,8,0,0,0,7,0,0,0,12,0,0,0,3,0,0,0,11,0,0,0,4,0,0,0,14,0,0,0,1,0,0,0,9,0,0,0,6,0,0,0,13,0,0,0,2,0,0,0,10,0,0,0,5,0,0,0,0,0,157,62,0,64,94,62,0,192,4,62,0,128,237,62,0,64,137,62,0,0,0,0,0,192,76,63,0,0,205,61,0,0,0,0,190,98,0,0,198,98,0,0,215,98,0,0,232,98,0,0,247,98,0,0,8,99,0,0,32,99,0,0,46,99,0,0,0,0,128,63,0,0,0,64,0,0,64,64,0,0,128,64,0,0,160,64,0,0,192,64,0,0,224, + 64,0,0,0,65,0,0,128,65,0,0,192,65,0,0,16,66,0,0,48,66,0,0,72,66,0,0,96,66,0,0,120,66,0,0,134,66,0,0,144,66,0,0,158,66,0,0,176,66,0,0,212,66,0,0,6,67,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,64,64,0,0,64,64,0,0,128,64,0,0,160,64,0,0,192,64,0,0,0,65,0,0,0,65,168,1,0,0,104,4,0,0,36,7,0,0,220,9,0,0,144,12,0,0,64,15,0,0,236,17,0,0,84,19,0,0,16,20,0,0,132,20,0,0,208,20,0,0,8,21,0,0,40,21,0,0,64,21,0,0, + 76,21,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0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,0,155,0,0,0,157,0,0,0,159,0,0,0,161,0,0,0,163,0,0,0,165,0,0,0,167,0,0,0,169,0,0,0,171,0,0,0,173,0,0,0,175,0,0,0,177,0,0,0,179,0,0,0,181,0,0,0,183,0,0,0,185,0,0,0,187,0,0,0,189,0,0,0,191,0,0,0,193,0,0,0,195,0,0,0,197,0,0,0,199,0,0,0,201,0,0,0,203,0,0,0,205,0,0,0,207,0,0,0,209,0,0,0,211,0,0,0,213,0,0,0,215,0,0,0,217,0,0,0,219,0,0,0,221,0,0,0,223,0,0,0,225,0,0,0,227,0,0,0,229,0,0,0,231,0,0,0,233,0,0,0,235,0,0,0,237,0,0,0,239,0,0,0,241,0,0,0,243,0,0,0,245,0,0,0,247,0,0,0,249,0, + 0,0,251,0,0,0,253,0,0,0,255,0,0,0,1,1,0,0,3,1,0,0,5,1,0,0,7,1,0,0,9,1,0,0,11,1,0,0,13,1,0,0,15,1,0,0,17,1,0,0,19,1,0,0,21,1,0,0,23,1,0,0,25,1,0,0,27,1,0,0,29,1,0,0,31,1,0,0,33,1,0,0,35,1,0,0,37,1,0,0,39,1,0,0,41,1,0,0,43,1,0,0,45,1,0,0,47,1,0,0,49,1,0,0,51,1,0,0,53,1,0,0,55,1,0,0,57,1,0,0,59,1,0,0,61,1,0,0,63,1,0,0,65,1,0,0,67,1,0,0,69,1,0,0,71,1,0,0,73,1,0,0,75,1,0,0,77,1,0,0,79,1,0,0,81,1,0,0,83,1,0,0,85,1,0,0,87,1,0,0,89,1,0,0,91,1,0,0,93,1,0,0,95,1,0,0,13,0,0,0,25,0,0,0,41,0,0,0,61,0,0,0,85,0, + 0,0,113,0,0,0,145,0,0,0,181,0,0,0,221,0,0,0,9,1,0,0,57,1,0,0,109,1,0,0,165,1,0,0,225,1,0,0,33,2,0,0,101,2,0,0,173,2,0,0,249,2,0,0,73,3,0,0,157,3,0,0,245,3,0,0,81,4,0,0,177,4,0,0,21,5,0,0,125,5,0,0,233,5,0,0,89,6,0,0,205,6,0,0,69,7,0,0,193,7,0,0,65,8,0,0,197,8,0,0,77,9,0,0,217,9,0,0,105,10,0,0,253,10,0,0,149,11,0,0,49,12,0,0,209,12,0,0,117,13,0,0,29,14,0,0,201,14,0,0,121,15,0,0,45,16,0,0,229,16,0,0,161,17,0,0,97,18,0,0,37,19,0,0,237,19,0,0,185,20,0,0,137,21,0,0,93,22,0,0,53,23,0,0,17,24,0,0,241,24, + 0,0,213,25,0,0,189,26,0,0,169,27,0,0,153,28,0,0,141,29,0,0,133,30,0,0,129,31,0,0,129,32,0,0,133,33,0,0,141,34,0,0,153,35,0,0,169,36,0,0,189,37,0,0,213,38,0,0,241,39,0,0,17,41,0,0,53,42,0,0,93,43,0,0,137,44,0,0,185,45,0,0,237,46,0,0,37,48,0,0,97,49,0,0,161,50,0,0,229,51,0,0,45,53,0,0,121,54,0,0,201,55,0,0,29,57,0,0,117,58,0,0,209,59,0,0,49,61,0,0,149,62,0,0,253,63,0,0,105,65,0,0,217,66,0,0,77,68,0,0,197,69,0,0,65,71,0,0,193,72,0,0,69,74,0,0,205,75,0,0,89,77,0,0,233,78,0,0,125,80,0,0,21,82,0,0,177, + 83,0,0,81,85,0,0,245,86,0,0,157,88,0,0,73,90,0,0,249,91,0,0,173,93,0,0,101,95,0,0,33,97,0,0,225,98,0,0,165,100,0,0,109,102,0,0,57,104,0,0,9,106,0,0,221,107,0,0,181,109,0,0,145,111,0,0,113,113,0,0,85,115,0,0,61,117,0,0,41,119,0,0,25,121,0,0,13,123,0,0,5,125,0,0,1,127,0,0,1,129,0,0,5,131,0,0,13,133,0,0,25,135,0,0,41,137,0,0,61,139,0,0,85,141,0,0,113,143,0,0,145,145,0,0,181,147,0,0,221,149,0,0,9,152,0,0,57,154,0,0,109,156,0,0,165,158,0,0,225,160,0,0,33,163,0,0,101,165,0,0,173,167,0,0,249,169,0,0,73, + 172,0,0,157,174,0,0,245,176,0,0,81,179,0,0,177,181,0,0,21,184,0,0,125,186,0,0,233,188,0,0,89,191,0,0,205,193,0,0,69,196,0,0,193,198,0,0,65,201,0,0,197,203,0,0,77,206,0,0,217,208,0,0,105,211,0,0,253,213,0,0,149,216,0,0,49,219,0,0,209,221,0,0,117,224,0,0,29,227,0,0,201,229,0,0,121,232,0,0,45,235,0,0,229,237,0,0,161,240,0,0,63,0,0,0,129,0,0,0,231,0,0,0,121,1,0,0,63,2,0,0,65,3,0,0,135,4,0,0,25,6,0,0,255,7,0,0,65,10,0,0,231,12,0,0,249,15,0,0,127,19,0,0,129,23,0,0,7,28,0,0,25,33,0,0,191,38,0,0,1,45,0,0, + 231,51,0,0,121,59,0,0,191,67,0,0,193,76,0,0,135,86,0,0,25,97,0,0,127,108,0,0,193,120,0,0,231,133,0,0,249,147,0,0,255,162,0,0,1,179,0,0,7,196,0,0,25,214,0,0,63,233,0,0,129,253,0,0,231,18,1,0,121,41,1,0,63,65,1,0,65,90,1,0,135,116,1,0,25,144,1,0,255,172,1,0,65,203,1,0,231,234,1,0,249,11,2,0,127,46,2,0,129,82,2,0,7,120,2,0,25,159,2,0,191,199,2,0,1,242,2,0,231,29,3,0,121,75,3,0,191,122,3,0,193,171,3,0,135,222,3,0,25,19,4,0,127,73,4,0,193,129,4,0,231,187,4,0,249,247,4,0,255,53,5,0,1,118,5,0,7,184,5,0, + 25,252,5,0,63,66,6,0,129,138,6,0,231,212,6,0,121,33,7,0,63,112,7,0,65,193,7,0,135,20,8,0,25,106,8,0,255,193,8,0,65,28,9,0,231,120,9,0,249,215,9,0,127,57,10,0,129,157,10,0,7,4,11,0,25,109,11,0,191,216,11,0,1,71,12,0,231,183,12,0,121,43,13,0,191,161,13,0,193,26,14,0,135,150,14,0,25,21,15,0,127,150,15,0,193,26,16,0,231,161,16,0,249,43,17,0,255,184,17,0,1,73,18,0,7,220,18,0,25,114,19,0,63,11,20,0,129,167,20,0,231,70,21,0,121,233,21,0,63,143,22,0,65,56,23,0,135,228,23,0,25,148,24,0,255,70,25,0,65,253, + 25,0,231,182,26,0,249,115,27,0,127,52,28,0,129,248,28,0,7,192,29,0,25,139,30,0,191,89,31,0,1,44,32,0,231,1,33,0,121,219,33,0,191,184,34,0,193,153,35,0,135,126,36,0,25,103,37,0,127,83,38,0,193,67,39,0,231,55,40,0,249,47,41,0,255,43,42,0,1,44,43,0,7,48,44,0,25,56,45,0,63,68,46,0,129,84,47,0,231,104,48,0,121,129,49,0,63,158,50,0,65,191,51,0,135,228,52,0,25,14,54,0,255,59,55,0,65,110,56,0,231,164,57,0,249,223,58,0,127,31,60,0,129,99,61,0,7,172,62,0,25,249,63,0,191,74,65,0,1,161,66,0,231,251,67,0,121, + 91,69,0,191,191,70,0,193,40,72,0,135,150,73,0,25,9,75,0,127,128,76,0,193,252,77,0,231,125,79,0,249,3,81,0,255,142,82,0,1,31,84,0,7,180,85,0,25,78,87,0,63,237,88,0,129,145,90,0,231,58,92,0,121,233,93,0,63,157,95,0,65,86,97,0,135,20,99,0,25,216,100,0,255,160,102,0,65,111,104,0,231,66,106,0,249,27,108,0,127,250,109,0,65,1,0,0,169,2,0,0,9,5,0,0,193,8,0,0,65,14,0,0,9,22,0,0,169,32,0,0,193,46,0,0,1,65,0,0,41,88,0,0,9,117,0,0,129,152,0,0,129,195,0,0,9,247,0,0,41,52,1,0,1,124,1,0,193,207,1,0,169,48,2,0,9, + 160,2,0,65,31,3,0,193,175,3,0,9,83,4,0,169,10,5,0,65,216,5,0,129,189,6,0,41,188,7,0,9,214,8,0,1,13,10,0,1,99,11,0,9,218,12,0,41,116,14,0,129,51,16,0,65,26,18,0,169,42,20,0,9,103,22,0,193,209,24,0,65,109,27,0,9,60,30,0,169,64,33,0,193,125,36,0,1,246,39,0,41,172,43,0,9,163,47,0,129,221,51,0,129,94,56,0,9,41,61,0,41,64,66,0,1,167,71,0,193,96,77,0,169,112,83,0,9,218,89,0,65,160,96,0,193,198,103,0,9,81,111,0,169,66,119,0,65,159,127,0,129,106,136,0,41,168,145,0,9,92,155,0,1,138,165,0,1,54,176,0,9,100,187, + 0,41,24,199,0,129,86,211,0,65,35,224,0,169,130,237,0,9,121,251,0,193,10,10,1,65,60,25,1,9,18,41,1,169,144,57,1,193,188,74,1,1,155,92,1,41,48,111,1,9,129,130,1,129,146,150,1,129,105,171,1,9,11,193,1,41,124,215,1,1,194,238,1,193,225,6,2,169,224,31,2,9,196,57,2,65,145,84,2,193,77,112,2,9,255,140,2,169,170,170,2,65,86,201,2,129,7,233,2,41,196,9,3,9,146,43,3,1,119,78,3,1,121,114,3,9,158,151,3,41,236,189,3,129,105,229,3,65,28,14,4,169,10,56,4,9,59,99,4,193,179,143,4,65,123,189,4,9,152,236,4,169,16,29,5, + 193,235,78,5,1,48,130,5,41,228,182,5,9,15,237,5,129,183,36,6,129,228,93,6,9,157,152,6,41,232,212,6,1,205,18,7,193,82,82,7,169,128,147,7,9,94,214,7,65,242,26,8,193,68,97,8,9,93,169,8,169,66,243,8,65,253,62,9,129,148,140,9,41,16,220,9,9,120,45,10,1,212,128,10,1,44,214,10,9,136,45,11,41,240,134,11,129,108,226,11,65,5,64,12,169,194,159,12,9,173,1,13,193,204,101,13,65,42,204,13,9,206,52,14,169,192,159,14,193,10,13,15,1,181,124,15,41,200,238,15,9,77,99,16,129,76,218,16,129,207,83,17,9,223,207,17,41,132, + 78,18,1,200,207,18,193,179,83,19,169,80,218,19,9,168,99,20,65,195,239,20,193,171,126,21,9,107,16,22,169,10,165,22,65,148,60,23,129,17,215,23,41,140,116,24,9,14,21,25,1,161,184,25,1,79,95,26,9,34,9,27,41,36,182,27,129,95,102,28,65,222,25,29,169,170,208,29,9,207,138,30,193,85,72,31,65,73,9,32,9,180,205,32,169,160,149,33,193,25,97,34,1,42,48,35,41,220,2,36,9,59,217,36,129,81,179,37,147,6,0,0,69,14,0,0,15,28,0,0,17,51,0,0,91,87,0,0,13,142,0,0,119,221,0,0,57,77,1,0,99,230,1,0,149,179,2,0,31,193,3,0,33, + 29,5,0,171,215,6,0,221,2,9,0,7,179,11,0,201,254,14,0,51,255,18,0,229,207,23,0,47,143,29,0,49,94,36,0,251,96,44,0,173,190,53,0,151,161,64,0,89,55,77,0,3,177,91,0,53,67,108,0,63,38,127,0,65,150,148,0,75,211,172,0,125,33,200,0,39,201,230,0,233,22,9,1,211,91,47,1,133,237,89,1,79,38,137,1,81,101,189,1,155,14,247,1,77,139,54,2,183,73,124,2,121,189,200,2,163,95,28,3,213,174,119,3,95,47,219,3,97,107,71,4,235,242,188,4,29,92,60,5,71,67,198,5,9,75,91,6,115,28,252,6,37,103,169,7,111,225,99,8,113,72,44,9,59, + 96,3,10,237,243,233,10,215,213,224,11,153,223,232,12,67,242,2,14,117,246,47,15,127,220,112,16,129,156,198,17,139,54,50,19,189,178,180,20,103,33,79,22,41,155,2,24,19,65,208,25,197,60,185,27,143,192,190,29,145,7,226,31,219,85,36,34,141,248,134,36,247,69,11,39,185,157,178,41,227,104,126,44,21,26,112,47,159,45,137,50,161,41,203,53,43,158,55,57,93,37,208,60,135,99,150,64,73,7,140,68,179,201,178,72,101,110,12,77,175,195,154,81,177,162,95,86,123,239,92,91,45,153,148,96,23,154,8,102,217,247,186,107,131,195, + 173,113,181,25,227,119,191,34,93,126,29,35,0,0,113,77,0,0,145,156,0,0,253,38,1,0,101,12,2,0,233,119,3,0,153,162,5,0,53,214,8,0,45,112,13,0,225,228,19,0,33,195,28,0,237,183,40,0,117,146,56,0,89,72,77,0,41,250,103,0,37,248,137,0,61,199,180,0,81,38,234,0,177,19,44,1,221,210,124,1,133,242,222,1,201,82,85,2,185,43,227,2,21,20,140,3,77,8,84,4,193,113,63,5,65,46,83,6,205,151,148,7,149,140,9,9,57,119,184,10,73,87,168,12,5,202,224,14,93,19,106,17,49,39,77,20,209,178,147,23,189,38,72,27,165,192,117,31,169, + 149,40,36,217,156,109,41,245,185,82,47,109,200,230,53,161,166,57,61,97,65,92,69,173,159,96,78,181,238,89,88,25,142,92,99,105,28,126,111,229,131,213,124,255,189,0,0,1,168,1,0,143,107,3,0,241,158,6,0,63,35,12,0,193,61,21,0,143,182,35,0,241,252,57,0,255,81,91,0,1,250,139,0,15,117,209,0,113,191,50,1,63,154,184,1,193,220,109,2,15,207,95,3,113,142,158,4,255,123,61,6,1,182,83,8,143,156,252,10,241,97,88,14,63,167,140,18,193,37,197,23,143,101,52,30,241,129,20,38,255,251,167,47,1,156,58,59,15,98,34,73,113, + 134,192,89,63,138,130,109,193,88,227,132,1,14,4,0,145,33,9,0,17,44,19,0,65,238,37,0,65,79,71,0,145,67,128,0,17,247,221,0,1,70,115,1,1,146,90,2,17,1,184,3,145,53,188,5,65,143,167,8,65,6,206,12,17,178,155,18,145,15,154,26,1,26,118,37,1,76,7,52,145,158,87,71,17,157,172,96,65,166,145,129,35,81,22,0,197,158,50,0,23,185,107,0,153,246,216,0,107,137,160,1,13,196,254,2,31,1,80,5,33,217,29,9,51,108,48,15,213,162,164,24,167,103,8,39,41,253,125,60,123,181,231,91,29,119,29,137,175,160,45,201,173,142,123,0,137, + 230,25,1,57,150,94,2,61,22,216,4,181,99,119,9,225,40,198,17,33,3,52,32,117,72,130,56,125,87,87,96,191,91,175,2,129,216,39,6,247,132,94,13,233,254,173,27,127,139,235,54,129,183,229,104,23,3,156,193,193,12,255,14,57,106,133,34,25,238,145,75,129,120,43,158,51,225,9,84,149,139,0,0,55,152,0,0,255,165,0,0,4,181,0,0,103,197,0,0,69,215,0,0,193,234,0,0,255,255,0,0,172,21,0,0,128,187,0,0,120,0,0,0,21,0,0,0,21,0,0,0,0,154,89,63,0,0,0,0,0,0,128,63,0,0,128,63,72,87,0,0,3,0,0,0,8,0,0,0,120,0,0,0,11,0,0,0,249,99, + 0,0,116,87,0,0,24,22,0,0,128,7,0,0,3,0,0,0,248,23,0,0,48,39,0,0,104,39,0,0,160,39,0,0,216,39,0,0,136,1,0,0,166,94,0,0,224,100,0,0,104,102,0,0,106,28,141,56,82,187,30,58,8,105,220,58,130,237,87,59,137,99,178,59,3,42,5,60,48,220,57,60,180,62,119,60,28,163,158,60,209,242,197,60,254,134,241,60,155,171,16,61,5,173,42,61,132,194,70,61,83,230,100,61,17,137,130,61,135,159,147,61,203,178,165,61,209,190,184,61,58,191,204,61,84,175,225,61,20,138,247,61,14,37,7,62,217,244,18,62,95,49,31,62,104,215,43,62,138, + 227,56,62,48,82,70,62,148,31,84,62,191,71,98,62,142,198,112,62,176,151,127,62,82,91,135,62,96,15,143,62,152,229,150,62,121,219,158,62,112,238,166,62,216,27,175,62,251,96,183,62,17,187,191,62,70,39,200,62,183,162,208,62,120,42,217,62,148,187,225,62,12,83,234,62,222,237,242,62,6,137,251,62,190,16,2,63,31,90,6,63,36,159,10,63,80,222,14,63,43,22,19,63,65,69,23,63,37,106,27,63,115,131,31,63,206,143,35,63,230,141,39,63,116,124,43,63,63,90,47,63,25,38,51,63,231,222,54,63,153,131,58,63,51,19,62,63,197,140, + 65,63,119,239,68,63,127,58,72,63,39,109,75,63,206,134,78,63,229,134,81,63,241,108,84,63,142,56,87,63,105,233,89,63,69,127,92,63,250,249,94,63,115,89,97,63,175,157,99,63,193,198,101,63,207,212,103,63,17,200,105,63,210,160,107,63,110,95,109,63,80,4,111,63,244,143,112,63,230,2,114,63,189,93,115,63,31,161,116,63,191,205,117,63,87,228,118,63,176,229,119,63,151,210,120,63,227,171,121,63,115,114,122,63,39,39,123,63,231,202,123,63,157,94,124,63,53,227,124,63,156,89,125,63,189,194,125,63,134,31,126,63,222, + 112,126,63,171,183,126,63,207,244,126,63,38,41,127,63,134,85,127,63,190,122,127,63,150,153,127,63,204,178,127,63,20,199,127,63,28,215,127,63,130,227,127,63,221,236,127,63,182,243,127,63,138,248,127,63,200,251,127,63,214,253,127,63,7,255,127,63,165,255,127,63,232,255,127,63,253,255,127,63,0,0,128,63,224,1,0,0,135,136,8,59,255,255,255,255,5,0,96,0,3,0,32,0,4,0,8,0,2,0,4,0,4,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,158,87,0,0,48,24,0,0,0,0,0,0,0,0,128,63,0,0,0,128,99,250,127,63,191,117,86,188,139,233,127,63,10, + 113,214,188,121,205,127,63,231,206,32,189,47,166,127,63,58,94,86,189,175,115,127,63,19,242,133,189,249,53,127,63,42,175,160,189,18,237,126,63,51,101,187,189,253,152,126,63,4,19,214,189,188,57,126,63,115,183,240,189,85,207,125,63,168,168,5,190,203,89,125,63,187,239,18,190,37,217,124,63,92,48,32,190,103,77,124,63,245,105,45,190,152,182,123,63,243,155,58,190,190,20,123,63,194,197,71,190,226,103,122,63,205,230,84,190,9,176,121,63,130,254,97,190,60,237,120,63,77,12,111,190,132,31,120,63,156,15,124,190, + 234,70,119,63,238,131,132,190,119,99,118,63,62,250,138,190,54,117,117,63,117,106,145,190,48,124,116,63,76,212,151,190,113,120,115,63,122,55,158,190,3,106,114,63,183,147,164,190,244,80,113,63,188,232,170,190,79,45,112,63,65,54,177,190,33,255,110,63,1,124,183,190,118,198,109,63,180,185,189,190,94,131,108,63,21,239,195,190,231,53,107,63,222,27,202,190,30,222,105,63,201,63,208,190,18,124,104,63,146,90,214,190,212,15,103,63,243,107,220,190,116,153,101,63,170,115,226,190,1,25,100,63,113,113,232,190,141, + 142,98,63,7,101,238,190,40,250,96,63,39,78,244,190,230,91,95,63,144,44,250,190,215,179,93,63,0,0,0,191,15,2,92,63,27,228,2,191,160,70,90,63,119,194,5,191,158,129,88,63,246,154,8,191,29,179,86,63,119,109,11,191,49,219,84,63,218,57,14,191,239,249,82,63,0,0,17,191,108,15,81,63,202,191,19,191,189,27,79,63,24,121,22,191,248,30,77,63,205,43,25,191,52,25,75,63,202,215,27,191,136,10,73,63,241,124,30,191,10,243,70,63,36,27,33,191,209,210,68,63,70,178,35,191,247,169,66,63,58,66,38,191,147,120,64,63,227,202, + 40,191,189,62,62,63,37,76,43,191,143,252,59,63,227,197,45,191,34,178,57,63,1,56,48,191,144,95,55,63,101,162,50,191,243,4,53,63,243,4,53,191,101,162,50,63,144,95,55,191,1,56,48,63,34,178,57,191,227,197,45,63,143,252,59,191,37,76,43,63,189,62,62,191,227,202,40,63,147,120,64,191,58,66,38,63,247,169,66,191,70,178,35,63,209,210,68,191,36,27,33,63,10,243,70,191,241,124,30,63,136,10,73,191,202,215,27,63,52,25,75,191,205,43,25,63,248,30,77,191,24,121,22,63,189,27,79,191,202,191,19,63,108,15,81,191,0,0,17, + 63,239,249,82,191,218,57,14,63,49,219,84,191,119,109,11,63,29,179,86,191,246,154,8,63,158,129,88,191,119,194,5,63,160,70,90,191,27,228,2,63,15,2,92,191,0,0,0,63,215,179,93,191,144,44,250,62,230,91,95,191,39,78,244,62,40,250,96,191,7,101,238,62,141,142,98,191,113,113,232,62,1,25,100,191,170,115,226,62,116,153,101,191,243,107,220,62,212,15,103,191,146,90,214,62,18,124,104,191,201,63,208,62,30,222,105,191,222,27,202,62,231,53,107,191,21,239,195,62,94,131,108,191,180,185,189,62,118,198,109,191,1,124, + 183,62,33,255,110,191,65,54,177,62,79,45,112,191,188,232,170,62,244,80,113,191,183,147,164,62,3,106,114,191,122,55,158,62,113,120,115,191,76,212,151,62,48,124,116,191,117,106,145,62,54,117,117,191,62,250,138,62,119,99,118,191,238,131,132,62,234,70,119,191,156,15,124,62,132,31,120,191,77,12,111,62,60,237,120,191,130,254,97,62,9,176,121,191,205,230,84,62,226,103,122,191,194,197,71,62,190,20,123,191,243,155,58,62,152,182,123,191,245,105,45,62,103,77,124,191,92,48,32,62,37,217,124,191,187,239,18,62,203, + 89,125,191,168,168,5,62,85,207,125,191,115,183,240,61,188,57,126,191,4,19,214,61,253,152,126,191,51,101,187,61,18,237,126,191,42,175,160,61,249,53,127,191,19,242,133,61,175,115,127,191,58,94,86,61,47,166,127,191,231,206,32,61,121,205,127,191,10,113,214,60,139,233,127,191,191,117,86,60,99,250,127,191,0,48,141,36,0,0,128,191,191,117,86,188,99,250,127,191,10,113,214,188,139,233,127,191,231,206,32,189,121,205,127,191,58,94,86,189,47,166,127,191,19,242,133,189,175,115,127,191,42,175,160,189,249,53,127, + 191,51,101,187,189,18,237,126,191,4,19,214,189,253,152,126,191,115,183,240,189,188,57,126,191,168,168,5,190,85,207,125,191,187,239,18,190,203,89,125,191,92,48,32,190,37,217,124,191,245,105,45,190,103,77,124,191,243,155,58,190,152,182,123,191,194,197,71,190,190,20,123,191,205,230,84,190,226,103,122,191,130,254,97,190,9,176,121,191,77,12,111,190,60,237,120,191,156,15,124,190,132,31,120,191,238,131,132,190,234,70,119,191,62,250,138,190,119,99,118,191,117,106,145,190,54,117,117,191,76,212,151,190,48, + 124,116,191,122,55,158,190,113,120,115,191,183,147,164,190,3,106,114,191,188,232,170,190,244,80,113,191,65,54,177,190,79,45,112,191,1,124,183,190,33,255,110,191,180,185,189,190,118,198,109,191,21,239,195,190,94,131,108,191,222,27,202,190,231,53,107,191,201,63,208,190,30,222,105,191,146,90,214,190,18,124,104,191,243,107,220,190,212,15,103,191,170,115,226,190,116,153,101,191,113,113,232,190,1,25,100,191,7,101,238,190,141,142,98,191,39,78,244,190,40,250,96,191,144,44,250,190,230,91,95,191,0,0,0,191, + 215,179,93,191,27,228,2,191,15,2,92,191,119,194,5,191,160,70,90,191,246,154,8,191,158,129,88,191,119,109,11,191,29,179,86,191,218,57,14,191,49,219,84,191,0,0,17,191,239,249,82,191,202,191,19,191,108,15,81,191,24,121,22,191,189,27,79,191,205,43,25,191,248,30,77,191,202,215,27,191,52,25,75,191,241,124,30,191,136,10,73,191,36,27,33,191,10,243,70,191,70,178,35,191,209,210,68,191,58,66,38,191,247,169,66,191,227,202,40,191,147,120,64,191,37,76,43,191,189,62,62,191,227,197,45,191,143,252,59,191,1,56,48, + 191,34,178,57,191,101,162,50,191,144,95,55,191,243,4,53,191,243,4,53,191,144,95,55,191,101,162,50,191,34,178,57,191,1,56,48,191,143,252,59,191,227,197,45,191,189,62,62,191,37,76,43,191,147,120,64,191,227,202,40,191,247,169,66,191,58,66,38,191,209,210,68,191,70,178,35,191,10,243,70,191,36,27,33,191,136,10,73,191,241,124,30,191,52,25,75,191,202,215,27,191,248,30,77,191,205,43,25,191,189,27,79,191,24,121,22,191,108,15,81,191,202,191,19,191,239,249,82,191,0,0,17,191,49,219,84,191,218,57,14,191,29,179, + 86,191,119,109,11,191,158,129,88,191,246,154,8,191,160,70,90,191,119,194,5,191,15,2,92,191,27,228,2,191,215,179,93,191,0,0,0,191,230,91,95,191,144,44,250,190,40,250,96,191,39,78,244,190,141,142,98,191,7,101,238,190,1,25,100,191,113,113,232,190,116,153,101,191,170,115,226,190,212,15,103,191,243,107,220,190,18,124,104,191,146,90,214,190,30,222,105,191,201,63,208,190,231,53,107,191,222,27,202,190,94,131,108,191,21,239,195,190,118,198,109,191,180,185,189,190,33,255,110,191,1,124,183,190,79,45,112,191, + 65,54,177,190,244,80,113,191,188,232,170,190,3,106,114,191,183,147,164,190,113,120,115,191,122,55,158,190,48,124,116,191,76,212,151,190,54,117,117,191,117,106,145,190,119,99,118,191,62,250,138,190,234,70,119,191,238,131,132,190,132,31,120,191,156,15,124,190,60,237,120,191,77,12,111,190,9,176,121,191,130,254,97,190,226,103,122,191,205,230,84,190,190,20,123,191,194,197,71,190,152,182,123,191,243,155,58,190,103,77,124,191,245,105,45,190,37,217,124,191,92,48,32,190,203,89,125,191,187,239,18,190,85,207, + 125,191,168,168,5,190,188,57,126,191,115,183,240,189,253,152,126,191,4,19,214,189,18,237,126,191,51,101,187,189,249,53,127,191,42,175,160,189,175,115,127,191,19,242,133,189,47,166,127,191,58,94,86,189,121,205,127,191,231,206,32,189,139,233,127,191,10,113,214,188,99,250,127,191,191,117,86,188,0,0,128,191,0,48,13,165,99,250,127,191,191,117,86,60,139,233,127,191,10,113,214,60,121,205,127,191,231,206,32,61,47,166,127,191,58,94,86,61,175,115,127,191,19,242,133,61,249,53,127,191,42,175,160,61,18,237,126, + 191,51,101,187,61,253,152,126,191,4,19,214,61,188,57,126,191,115,183,240,61,85,207,125,191,168,168,5,62,203,89,125,191,187,239,18,62,37,217,124,191,92,48,32,62,103,77,124,191,245,105,45,62,152,182,123,191,243,155,58,62,190,20,123,191,194,197,71,62,226,103,122,191,205,230,84,62,9,176,121,191,130,254,97,62,60,237,120,191,77,12,111,62,132,31,120,191,156,15,124,62,234,70,119,191,238,131,132,62,119,99,118,191,62,250,138,62,54,117,117,191,117,106,145,62,48,124,116,191,76,212,151,62,113,120,115,191,122, + 55,158,62,3,106,114,191,183,147,164,62,244,80,113,191,188,232,170,62,79,45,112,191,65,54,177,62,33,255,110,191,1,124,183,62,118,198,109,191,180,185,189,62,94,131,108,191,21,239,195,62,231,53,107,191,222,27,202,62,30,222,105,191,201,63,208,62,18,124,104,191,146,90,214,62,212,15,103,191,243,107,220,62,116,153,101,191,170,115,226,62,1,25,100,191,113,113,232,62,141,142,98,191,7,101,238,62,40,250,96,191,39,78,244,62,230,91,95,191,144,44,250,62,215,179,93,191,0,0,0,63,15,2,92,191,27,228,2,63,160,70,90, + 191,119,194,5,63,158,129,88,191,246,154,8,63,29,179,86,191,119,109,11,63,49,219,84,191,218,57,14,63,239,249,82,191,0,0,17,63,108,15,81,191,202,191,19,63,189,27,79,191,24,121,22,63,248,30,77,191,205,43,25,63,52,25,75,191,202,215,27,63,136,10,73,191,241,124,30,63,10,243,70,191,36,27,33,63,209,210,68,191,70,178,35,63,247,169,66,191,58,66,38,63,147,120,64,191,227,202,40,63,189,62,62,191,37,76,43,63,143,252,59,191,227,197,45,63,34,178,57,191,1,56,48,63,144,95,55,191,101,162,50,63,243,4,53,191,243,4,53, + 63,101,162,50,191,144,95,55,63,1,56,48,191,34,178,57,63,227,197,45,191,143,252,59,63,37,76,43,191,189,62,62,63,227,202,40,191,147,120,64,63,58,66,38,191,247,169,66,63,70,178,35,191,209,210,68,63,36,27,33,191,10,243,70,63,241,124,30,191,136,10,73,63,202,215,27,191,52,25,75,63,205,43,25,191,248,30,77,63,24,121,22,191,189,27,79,63,202,191,19,191,108,15,81,63,0,0,17,191,239,249,82,63,218,57,14,191,49,219,84,63,119,109,11,191,29,179,86,63,246,154,8,191,158,129,88,63,119,194,5,191,160,70,90,63,27,228,2, + 191,15,2,92,63,0,0,0,191,215,179,93,63,144,44,250,190,230,91,95,63,39,78,244,190,40,250,96,63,7,101,238,190,141,142,98,63,113,113,232,190,1,25,100,63,170,115,226,190,116,153,101,63,243,107,220,190,212,15,103,63,146,90,214,190,18,124,104,63,201,63,208,190,30,222,105,63,222,27,202,190,231,53,107,63,21,239,195,190,94,131,108,63,180,185,189,190,118,198,109,63,1,124,183,190,33,255,110,63,65,54,177,190,79,45,112,63,188,232,170,190,244,80,113,63,183,147,164,190,3,106,114,63,122,55,158,190,113,120,115,63, + 76,212,151,190,48,124,116,63,117,106,145,190,54,117,117,63,62,250,138,190,119,99,118,63,238,131,132,190,234,70,119,63,156,15,124,190,132,31,120,63,77,12,111,190,60,237,120,63,130,254,97,190,9,176,121,63,205,230,84,190,226,103,122,63,194,197,71,190,190,20,123,63,243,155,58,190,152,182,123,63,245,105,45,190,103,77,124,63,92,48,32,190,37,217,124,63,187,239,18,190,203,89,125,63,168,168,5,190,85,207,125,63,115,183,240,189,188,57,126,63,4,19,214,189,253,152,126,63,51,101,187,189,18,237,126,63,42,175,160, + 189,249,53,127,63,19,242,133,189,175,115,127,63,58,94,86,189,47,166,127,63,231,206,32,189,121,205,127,63,10,113,214,188,139,233,127,63,191,117,86,188,99,250,127,63,0,200,83,165,0,0,128,63,191,117,86,60,99,250,127,63,10,113,214,60,139,233,127,63,231,206,32,61,121,205,127,63,58,94,86,61,47,166,127,63,19,242,133,61,175,115,127,63,42,175,160,61,249,53,127,63,51,101,187,61,18,237,126,63,4,19,214,61,253,152,126,63,115,183,240,61,188,57,126,63,168,168,5,62,85,207,125,63,187,239,18,62,203,89,125,63,92,48, + 32,62,37,217,124,63,245,105,45,62,103,77,124,63,243,155,58,62,152,182,123,63,194,197,71,62,190,20,123,63,205,230,84,62,226,103,122,63,130,254,97,62,9,176,121,63,77,12,111,62,60,237,120,63,156,15,124,62,132,31,120,63,238,131,132,62,234,70,119,63,62,250,138,62,119,99,118,63,117,106,145,62,54,117,117,63,76,212,151,62,48,124,116,63,122,55,158,62,113,120,115,63,183,147,164,62,3,106,114,63,188,232,170,62,244,80,113,63,65,54,177,62,79,45,112,63,1,124,183,62,33,255,110,63,180,185,189,62,118,198,109,63,21, + 239,195,62,94,131,108,63,222,27,202,62,231,53,107,63,201,63,208,62,30,222,105,63,146,90,214,62,18,124,104,63,243,107,220,62,212,15,103,63,170,115,226,62,116,153,101,63,113,113,232,62,1,25,100,63,7,101,238,62,141,142,98,63,39,78,244,62,40,250,96,63,144,44,250,62,230,91,95,63,0,0,0,63,215,179,93,63,27,228,2,63,15,2,92,63,119,194,5,63,160,70,90,63,246,154,8,63,158,129,88,63,119,109,11,63,29,179,86,63,218,57,14,63,49,219,84,63,0,0,17,63,239,249,82,63,202,191,19,63,108,15,81,63,24,121,22,63,189,27,79, + 63,205,43,25,63,248,30,77,63,202,215,27,63,52,25,75,63,241,124,30,63,136,10,73,63,36,27,33,63,10,243,70,63,70,178,35,63,209,210,68,63,58,66,38,63,247,169,66,63,227,202,40,63,147,120,64,63,37,76,43,63,189,62,62,63,227,197,45,63,143,252,59,63,1,56,48,63,34,178,57,63,101,162,50,63,144,95,55,63,243,4,53,63,243,4,53,63,144,95,55,63,101,162,50,63,34,178,57,63,1,56,48,63,143,252,59,63,227,197,45,63,189,62,62,63,37,76,43,63,147,120,64,63,227,202,40,63,247,169,66,63,58,66,38,63,209,210,68,63,70,178,35,63, + 10,243,70,63,36,27,33,63,136,10,73,63,241,124,30,63,52,25,75,63,202,215,27,63,248,30,77,63,205,43,25,63,189,27,79,63,24,121,22,63,108,15,81,63,202,191,19,63,239,249,82,63,0,0,17,63,49,219,84,63,218,57,14,63,29,179,86,63,119,109,11,63,158,129,88,63,246,154,8,63,160,70,90,63,119,194,5,63,15,2,92,63,27,228,2,63,215,179,93,63,0,0,0,63,230,91,95,63,144,44,250,62,40,250,96,63,39,78,244,62,141,142,98,63,7,101,238,62,1,25,100,63,113,113,232,62,116,153,101,63,170,115,226,62,212,15,103,63,243,107,220,62,18, + 124,104,63,146,90,214,62,30,222,105,63,201,63,208,62,231,53,107,63,222,27,202,62,94,131,108,63,21,239,195,62,118,198,109,63,180,185,189,62,33,255,110,63,1,124,183,62,79,45,112,63,65,54,177,62,244,80,113,63,188,232,170,62,3,106,114,63,183,147,164,62,113,120,115,63,122,55,158,62,48,124,116,63,76,212,151,62,54,117,117,63,117,106,145,62,119,99,118,63,62,250,138,62,234,70,119,63,238,131,132,62,132,31,120,63,156,15,124,62,60,237,120,63,77,12,111,62,9,176,121,63,130,254,97,62,226,103,122,63,205,230,84,62, + 190,20,123,63,194,197,71,62,152,182,123,63,243,155,58,62,103,77,124,63,245,105,45,62,37,217,124,63,92,48,32,62,203,89,125,63,187,239,18,62,85,207,125,63,168,168,5,62,188,57,126,63,115,183,240,61,253,152,126,63,4,19,214,61,18,237,126,63,51,101,187,61,249,53,127,63,42,175,160,61,175,115,127,63,19,242,133,61,47,166,127,63,58,94,86,61,121,205,127,63,231,206,32,61,139,233,127,63,10,113,214,60,99,250,127,63,191,117,86,60,240,0,0,0,137,136,136,59,1,0,0,0,5,0,48,0,3,0,16,0,4,0,4,0,4,0,1,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,94,91,0,0,48,24,0,0,0,0,0,0,120,0,0,0,136,136,8,60,2,0,0,0,5,0,24,0,3,0,8,0,2,0,4,0,4,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,62,93,0,0,48,24,0,0,0,0,0,0,60,0,0,0,137,136,136,60,3,0,0,0,5,0,12,0,3,0,4,0,4,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,46,94,0,0,48,24,0,0,0,0,0,0,255,255,127,63,142,255,127,63,106,254,127,63,147,252,127,63,7,250,127,63,200,246,127,63,214,242,127,63,48,238,127,63,214,232,127,63,200,226,127,63,7,220,127,63,147,212,127,63],"i8",4,y.h); + O([107,204,127,63,143,195,127,63,0,186,127,63,189,175,127,63,199,164,127,63,29,153,127,63,192,140,127,63,176,127,127,63,236,113,127,63,118,99,127,63,75,84,127,63,110,68,127,63,222,51,127,63,154,34,127,63,163,16,127,63,250,253,126,63,157,234,126,63,141,214,126,63,203,193,126,63,86,172,126,63,46,150,126,63,83,127,126,63,198,103,126,63,134,79,126,63,148,54,126,63,239,28,126,63,152,2,126,63,143,231,125,63,211,203,125,63,102,175,125,63,70,146,125,63,116,116,125,63,241,85,125,63,188,54,125,63,213,22,125, + 63,60,246,124,63,242,212,124,63,246,178,124,63,73,144,124,63,235,108,124,63,219,72,124,63,27,36,124,63,169,254,123,63,135,216,123,63,180,177,123,63,48,138,123,63,252,97,123,63,23,57,123,63,130,15,123,63,61,229,122,63,72,186,122,63,162,142,122,63,77,98,122,63,72,53,122,63,148,7,122,63,48,217,121,63,29,170,121,63,90,122,121,63,233,73,121,63,200,24,121,63,249,230,120,63,123,180,120,63,78,129,120,63,115,77,120,63,234,24,120,63,178,227,119,63,205,173,119,63,58,119,119,63,249,63,119,63,10,8,119,63,110, + 207,118,63,37,150,118,63,47,92,118,63,140,33,118,63,60,230,117,63,64,170,117,63,151,109,117,63,66,48,117,63,65,242,116,63,148,179,116,63,59,116,116,63,55,52,116,63,135,243,115,63,44,178,115,63,38,112,115,63,118,45,115,63,26,234,114,63,20,166,114,63,100,97,114,63,10,28,114,63,5,214,113,63,87,143,113,63,0,72,113,63,255,255,112,63,85,183,112,63,2,110,112,63,6,36,112,63,98,217,111,63,21,142,111,63,32,66,111,63,132,245,110,63,63,168,110,63,83,90,110,63,192,11,110,63,134,188,109,63,165,108,109,63,29,28, + 109,63,239,202,108,63,27,121,108,63,161,38,108,63,128,211,107,63,187,127,107,63,80,43,107,63,64,214,106,63,140,128,106,63,50,42,106,63,53,211,105,63,147,123,105,63,77,35,105,63,100,202,104,63,216,112,104,63,168,22,104,63,213,187,103,63,96,96,103,63,72,4,103,63,143,167,102,63,51,74,102,63,54,236,101,63,151,141,101,63,87,46,101,63,119,206,100,63,245,109,100,63,212,12,100,63,18,171,99,63,177,72,99,63,176,229,98,63,16,130,98,63,209,29,98,63,243,184,97,63,119,83,97,63,92,237,96,63,164,134,96,63,78,31, + 96,63,91,183,95,63,203,78,95,63,158,229,94,63,213,123,94,63,112,17,94,63,110,166,93,63,210,58,93,63,154,206,92,63,198,97,92,63,89,244,91,63,81,134,91,63,174,23,91,63,114,168,90,63,157,56,90,63,46,200,89,63,39,87,89,63,135,229,88,63,79,115,88,63,127,0,88,63,23,141,87,63,24,25,87,63,130,164,86,63,86,47,86,63,147,185,85,63,58,67,85,63,75,204,84,63,199,84,84,63,174,220,83,63,1,100,83,63,191,234,82,63,233,112,82,63,127,246,81,63,130,123,81,63,242,255,80,63,207,131,80,63,26,7,80,63,210,137,79,63,250,11, + 79,63,144,141,78,63,148,14,78,63,9,143,77,63,237,14,77,63,65,142,76,63,5,13,76,63,59,139,75,63,225,8,75,63,249,133,74,63,131,2,74,63,127,126,73,63,238,249,72,63,207,116,72,63,36,239,71,63,237,104,71,63,41,226,70,63,218,90,70,63,0,211,69,63,155,74,69,63,172,193,68,63,50,56,68,63,47,174,67,63,162,35,67,63,141,152,66,63,239,12,66,63,200,128,65,63,26,244,64,63,229,102,64,63,40,217,63,63,229,74,63,63,27,188,62,63,204,44,62,63,247,156,61,63,157,12,61,63,190,123,60,63,92,234,59,63,117,88,59,63,10,198,58, + 63,29,51,58,63,173,159,57,63,187,11,57,63,71,119,56,63,81,226,55,63,218,76,55,63,227,182,54,63,107,32,54,63,116,137,53,63,253,241,52,63,7,90,52,63,147,193,51,63,160,40,51,63,48,143,50,63,66,245,49,63,216,90,49,63,241,191,48,63,142,36,48,63,175,136,47,63,85,236,46,63,129,79,46,63,50,178,45,63,105,20,45,63,39,118,44,63,107,215,43,63,55,56,43,63,139,152,42,63,103,248,41,63,204,87,41,63,186,182,40,63,50,21,40,63,51,115,39,63,191,208,38,63,214,45,38,63,121,138,37,63,167,230,36,63,97,66,36,63,169,157,35, + 63,125,248,34,63,223,82,34,63,207,172,33,63,77,6,33,63,91,95,32,63,248,183,31,63,37,16,31,63,226,103,30,63,48,191,29,63,16,22,29,63,129,108,28,63,132,194,27,63,26,24,27,63,67,109,26,63,0,194,25,63,81,22,25,63,54,106,24,63,177,189,23,63,193,16,23,63,103,99,22,63,163,181,21,63,118,7,21,63,225,88,20,63,228,169,19,63,127,250,18,63,179,74,18,63,128,154,17,63,231,233,16,63,232,56,16,63,132,135,15,63,187,213,14,63,142,35,14,63,254,112,13,63,10,190,12,63,179,10,12,63,250,86,11,63,223,162,10,63,99,238,9,63, + 134,57,9,63,73,132,8,63,172,206,7,63,175,24,7,63,84,98,6,63,155,171,5,63,131,244,4,63,15,61,4,63,61,133,3,63,15,205,2,63,134,20,2,63,161,91,1,63,97,162,0,63,143,209,255,62,167,93,254,62,14,233,252,62,194,115,251,62,198,253,249,62,27,135,248,62,193,15,247,62,186,151,245,62,6,31,244,62,168,165,242,62,158,43,241,62,236,176,239,62,145,53,238,62,144,185,236,62,232,60,235,62,154,191,233,62,169,65,232,62,21,195,230,62,223,67,229,62,8,196,227,62,145,67,226,62,124,194,224,62,200,64,223,62,120,190,221,62,140, + 59,220,62,6,184,218,62,230,51,217,62,46,175,215,62,223,41,214,62,249,163,212,62,125,29,211,62,110,150,209,62,204,14,208,62,151,134,206,62,210,253,204,62,125,116,203,62,153,234,201,62,39,96,200,62,40,213,198,62,159,73,197,62,138,189,195,62,236,48,194,62,198,163,192,62,25,22,191,62,230,135,189,62,45,249,187,62,241,105,186,62,50,218,184,62,241,73,183,62,47,185,181,62,238,39,180,62,47,150,178,62,242,3,177,62,57,113,175,62,4,222,173,62,86,74,172,62,47,182,170,62,144,33,169,62,122,140,167,62,239,246,165, + 62,239,96,164,62,124,202,162,62,151,51,161,62,64,156,159,62,122,4,158,62,68,108,156,62,161,211,154,62,145,58,153,62,22,161,151,62,48,7,150,62,225,108,148,62,41,210,146,62,11,55,145,62,135,155,143,62,158,255,141,62,81,99,140,62,162,198,138,62,145,41,137,62,32,140,135,62,80,238,133,62,34,80,132,62,151,177,130,62,176,18,129,62,222,230,126,62,169,167,123,62,195,103,120,62,47,39,117,62,238,229,113,62,4,164,110,62,115,97,107,62,60,30,104,62,98,218,100,62,232,149,97,62,207,80,94,62,26,11,91,62,204,196,87, + 62,230,125,84,62,107,54,81,62,93,238,77,62,191,165,74,62,146,92,71,62,218,18,68,62,151,200,64,62,206,125,61,62,128,50,58,62,174,230,54,62,93,154,51,62,141,77,48,62,66,0,45,62,125,178,41,62,66,100,38,62,145,21,35,62,110,198,31,62,219,118,28,62,218,38,25,62,109,214,21,62,152,133,18,62,91,52,15,62,186,226,11,62,183,144,8,62,84,62,5,62,148,235,1,62,240,48,253,61,6,138,246,61,113,226,239,61,51,58,233,61,79,145,226,61,207,231,219,61,181,61,213,61,3,147,206,61,192,231,199,61,242,59,193,61,156,143,186,61, + 195,226,179,61,108,53,173,61,155,135,166,61,85,217,159,61,159,42,153,61,126,123,146,61,246,203,139,61,11,28,133,61,135,215,124,61,70,118,111,61,93,20,98,61,214,177,84,61,185,78,71,61,16,235,57,61,229,134,44,61,64,34,31,61,44,189,17,61,178,87,4,61,181,227,237,60,96,23,211,60,118,74,184,60,11,125,157,60,50,175,130,60,250,193,79,60,254,36,26,60,42,15,201,59,153,167,59,59,46,125,214,185,210,70,113,187,171,222,227,187,166,140,39,188,129,41,93,188,225,98,137,188,160,48,164,188,236,253,190,188,179,202,217, + 188,224,150,244,188,49,177,7,189,147,22,21,189,140,123,34,189,19,224,47,189,30,68,61,189,165,167,74,189,157,10,88,189,254,108,101,189,190,206,114,189,234,23,128,189,27,200,134,189,237,119,141,189,92,39,148,189,99,214,154,189,253,132,161,189,38,51,168,189,217,224,174,189,17,142,181,189,202,58,188,189,254,230,194,189,170,146,201,189,200,61,208,189,84,232,214,189,74,146,221,189,164,59,228,189,93,228,234,189,114,140,241,189,221,51,248,189,154,218,254,189,82,192,2,190,252,18,6,190,71,101,9,190,50,183, + 12,190,186,8,16,190,221,89,19,190,152,170,22,190,234,250,25,190,208,74,29,190,71,154,32,190,78,233,35,190,225,55,39,190,0,134,42,190,166,211,45,190,211,32,49,190,131,109,52,190,181,185,55,190,101,5,59,190,147,80,62,190,58,155,65,190,90,229,68,190,240,46,72,190,249,119,75,190,116,192,78,190,93,8,82,190,179,79,85,190,115,150,88,190,156,220,91,190,42,34,95,190,27,103,98,190,109,171,101,190,31,239,104,190,44,50,108,190,148,116,111,190,84,182,114,190,106,247,117,190,211,55,121,190,141,119,124,190,150, + 182,127,190,117,122,129,190,69,25,131,190,185,183,132,190,208,85,134,190,136,243,135,190,225,144,137,190,218,45,139,190,112,202,140,190,164,102,142,190,116,2,144,190,223,157,145,190,228,56,147,190,129,211,148,190,182,109,150,190,129,7,152,190,226,160,153,190,215,57,155,190,95,210,156,190,121,106,158,190,35,2,160,190,94,153,161,190,38,48,163,190,125,198,164,190,96,92,166,190,206,241,167,190,198,134,169,190,71,27,171,190,80,175,172,190,224,66,174,190,245,213,175,190,143,104,177,190,173,250,178,190, + 77,140,180,190,110,29,182,190,16,174,183,190,48,62,185,190,207,205,186,190,234,92,188,190,130,235,189,190,148,121,191,190,31,7,193,190,35,148,194,190,159,32,196,190,145,172,197,190,248,55,199,190,211,194,200,190,34,77,202,190,226,214,203,190,19,96,205,190,181,232,206,190,197,112,208,190,66,248,209,190,45,127,211,190,131,5,213,190,67,139,214,190,109,16,216,190,255,148,217,190,249,24,219,190,89,156,220,190,29,31,222,190,70,161,223,190,211,34,225,190,193,163,226,190,16,36,228,190,190,163,229,190,204, + 34,231,190,56,161,232,190,0,31,234,190,36,156,235,190,162,24,237,190,122,148,238,190,171,15,240,190,51,138,241,190,18,4,243,190,70,125,244,190,207,245,245,190,170,109,247,190,217,228,248,190,88,91,250,190,40,209,251,190,71,70,253,190,181,186,254,190,56,23,0,191,187,208,0,191,228,137,1,191,178,66,2,191,37,251,2,191,59,179,3,191,246,106,4,191,83,34,5,191,83,217,5,191,245,143,6,191,56,70,7,191,29,252,7,191,162,177,8,191,199,102,9,191,140,27,10,191,240,207,10,191,243,131,11,191,147,55,12,191,209,234, + 12,191,172,157,13,191,36,80,14,191,56,2,15,191,232,179,15,191,50,101,16,191,24,22,17,191,151,198,17,191,176,118,18,191,99,38,19,191,174,213,19,191,145,132,20,191,13,51,21,191,31,225,21,191,200,142,22,191,8,60,23,191,221,232,23,191,72,149,24,191,72,65,25,191,220,236,25,191,4,152,26,191,192,66,27,191,15,237,27,191,240,150,28,191,99,64,29,191,104,233,29,191,254,145,30,191,37,58,31,191,220,225,31,191,35,137,32,191,250,47,33,191,95,214,33,191,82,124,34,191,212,33,35,191,227,198,35,191,127,107,36,191,167, + 15,37,191,92,179,37,191,157,86,38,191,104,249,38,191,191,155,39,191,160,61,40,191,11,223,40,191,255,127,41,191,125,32,42,191,131,192,42,191,17,96,43,191,39,255,43,191,196,157,44,191,232,59,45,191,146,217,45,191,195,118,46,191,121,19,47,191,180,175,47,191,115,75,48,191,183,230,48,191,127,129,49,191,203,27,50,191,153,181,50,191,234,78,51,191,189,231,51,191,18,128,52,191,232,23,53,191,63,175,53,191,22,70,54,191,110,220,54,191,69,114,55,191,156,7,56,191,113,156,56,191,197,48,57,191,150,196,57,191,230, + 87,58,191,178,234,58,191,252,124,59,191,194,14,60,191,3,160,60,191,193,48,61,191,250,192,61,191,173,80,62,191,219,223,62,191,131,110,63,191,165,252,63,191,64,138,64,191,83,23,65,191,224,163,65,191,228,47,66,191,96,187,66,191,83,70,67,191,190,208,67,191,158,90,68,191,246,227,68,191,194,108,69,191,5,245,69,191,188,124,70,191,232,3,71,191,137,138,71,191,157,16,72,191,37,150,72,191,32,27,73,191,142,159,73,191,111,35,74,191,193,166,74,191,134,41,75,191,188,171,75,191,99,45,76,191,122,174,76,191,2,47,77, + 191,250,174,77,191,98,46,78,191,57,173,78,191,126,43,79,191,51,169,79,191,85,38,80,191,230,162,80,191,228,30,81,191,80,154,81,191,40,21,82,191,109,143,82,191,30,9,83,191,59,130,83,191,195,250,83,191,183,114,84,191,22,234,84,191,223,96,85,191,18,215,85,191,176,76,86,191,183,193,86,191,39,54,87,191,0,170,87,191,66,29,88,191,236,143,88,191,254,1,89,191,120,115,89,191,89,228,89,191,162,84,90,191,81,196,90,191,102,51,91,191,226,161,91,191,195,15,92,191,10,125,92,191,183,233,92,191,200,85,93,191,62,193, + 93,191,24,44,94,191,87,150,94,191,249,255,94,191,255,104,95,191,104,209,95,191,51,57,96,191,98,160,96,191,243,6,97,191,229,108,97,191,58,210,97,191,240,54,98,191,8,155,98,191,128,254,98,191,89,97,99,191,146,195,99,191,44,37,100,191,37,134,100,191,126,230,100,191,55,70,101,191,78,165,101,191,197,3,102,191,154,97,102,191,205,190,102,191,94,27,103,191,77,119,103,191,154,210,103,191,68,45,104,191,75,135,104,191,174,224,104,191,111,57,105,191,139,145,105,191,4,233,105,191,217,63,106,191,9,150,106,191, + 148,235,106,191,123,64,107,191,188,148,107,191,89,232,107,191,79,59,108,191,160,141,108,191,75,223,108,191,79,48,109,191,173,128,109,191,101,208,109,191,117,31,110,191,223,109,110,191,161,187,110,191,187,8,111,191,46,85,111,191,248,160,111,191,27,236,111,191,149,54,112,191,103,128,112,191,144,201,112,191,15,18,113,191,230,89,113,191,19,161,113,191,151,231,113,191,113,45,114,191,160,114,114,191,38,183,114,191,1,251,114,191,50,62,115,191,184,128,115,191,148,194,115,191,196,3,116,191,73,68,116,191,34, + 132,116,191,80,195,116,191,210,1,117,191,168,63,117,191,210,124,117,191,80,185,117,191,33,245,117,191,69,48,118,191,189,106,118,191,136,164,118,191,166,221,118,191,22,22,119,191,217,77,119,191,239,132,119,191,87,187,119,191,17,241,119,191,29,38,120,191,122,90,120,191,42,142,120,191,43,193,120,191,125,243,120,191,33,37,121,191,22,86,121,191,92,134,121,191,242,181,121,191,218,228,121,191,18,19,122,191,154,64,122,191,115,109,122,191,157,153,122,191,22,197,122,191,223,239,122,191,248,25,123,191,97,67, + 123,191,26,108,123,191,34,148,123,191,122,187,123,191,32,226,123,191,23,8,124,191,92,45,124,191,240,81,124,191,211,117,124,191,5,153,124,191,134,187,124,191,85,221,124,191,115,254,124,191,223,30,125,191,154,62,125,191,163,93,125,191,250,123,125,191,159,153,125,191,146,182,125,191,211,210,125,191,98,238,125,191,63,9,126,191,105,35,126,191,225,60,126,191,167,85,126,191,186,109,126,191,27,133,126,191,201,155,126,191,196,177,126,191,13,199,126,191,162,219,126,191,133,239,126,191,181,2,127,191,50,21,127, + 191,252,38,127,191,19,56,127,191,118,72,127,191,39,88,127,191,36,103,127,191,110,117,127,191,5,131,127,191,232,143,127,191,25,156,127,191,149,167,127,191,95,178,127,191,116,188,127,191,215,197,127,191,133,206,127,191,129,214,127,191,200,221,127,191,93,228,127,191,61,234,127,191,106,239,127,191,227,243,127,191,169,247,127,191,187,250,127,191,25,253,127,191,196,254,127,191,187,255,127,191,250,255,127,63,57,254,127,63,169,249,127,63,75,242,127,63,30,232,127,63,35,219,127,63,89,203,127,63,193,184,127, + 63,91,163,127,63,40,139,127,63,39,112,127,63,90,82,127,63,191,49,127,63,88,14,127,63,37,232,126,63,38,191,126,63,92,147,126,63,200,100,126,63,105,51,126,63,65,255,125,63,79,200,125,63,150,142,125,63,20,82,125,63,203,18,125,63,188,208,124,63,231,139,124,63,77,68,124,63,239,249,123,63,205,172,123,63,233,92,123,63,67,10,123,63,221,180,122,63,182,92,122,63,209,1,122,63,46,164,121,63,206,67,121,63,178,224,120,63,220,122,120,63,76,18,120,63,4,167,119,63,4,57,119,63,79,200,118,63,228,84,118,63,198,222,117, + 63,246,101,117,63,117,234,116,63,68,108,116,63,101,235,115,63,218,103,115,63,163,225,114,63,194,88,114,63,57,205,113,63,9,63,113,63,52,174,112,63,187,26,112,63,160,132,111,63,228,235,110,63,138,80,110,63,147,178,109,63,1,18,109,63,213,110,108,63,17,201,107,63,183,32,107,63,201,117,106,63,73,200,105,63,57,24,105,63,155,101,104,63,111,176,103,63,186,248,102,63,124,62,102,63,184,129,101,63,111,194,100,63,164,0,100,63,90,60,99,63,145,117,98,63,76,172,97,63,142,224,96,63,89,18,96,63,174,65,95,63,145,110, + 94,63,3,153,93,63,8,193,92,63,160,230,91,63,207,9,91,63,152,42,90,63,251,72,89,63,253,100,88,63,159,126,87,63,229,149,86,63,208,170,85,63,99,189,84,63,161,205,83,63,140,219,82,63,39,231,81,63,117,240,80,63,121,247,79,63,52,252,78,63,171,254,77,63,223,254,76,63,212,252,75,63,140,248,74,63,10,242,73,63,82,233,72,63,101,222,71,63,71,209,70,63,251,193,69,63,132,176,68,63,229,156,67,63,32,135,66,63,58,111,65,63,52,85,64,63,19,57,63,63,216,26,62,63,136,250,60,63,38,216,59,63,180,179,58,63,54,141,57,63, + 175,100,56,63,34,58,55,63,147,13,54,63,5,223,52,63,124,174,51,63,249,123,50,63,130,71,49,63,25,17,48,63,194,216,46,63,127,158,45,63,86,98,44,63,72,36,43,63,90,228,41,63,144,162,40,63,235,94,39,63,113,25,38,63,37,210,36,63,9,137,35,63,35,62,34,63,117,241,32,63,4,163,31,63,210,82,30,63,228,0,29,63,61,173,27,63,225,87,26,63,211,0,25,63,25,168,23,63,180,77,22,63,170,241,20,63,253,147,19,63,178,52,18,63,204,211,16,63,80,113,15,63,66,13,14,63,164,167,12,63,124,64,11,63,205,215,9,63,154,109,8,63,233,1,7, + 63,189,148,5,63,25,38,4,63,3,182,2,63,126,68,1,63,28,163,255,62,110,186,252,62,250,206,249,62,202,224,246,62,228,239,243,62,81,252,240,62,26,6,238,62,71,13,235,62,224,17,232,62,237,19,229,62,119,19,226,62,135,16,223,62,36,11,220,62,88,3,217,62,42,249,213,62,164,236,210,62,205,221,207,62,175,204,204,62,82,185,201,62,191,163,198,62,254,139,195,62,24,114,192,62,22,86,189,62,0,56,186,62,224,23,183,62,189,245,179,62,161,209,176,62,149,171,173,62,162,131,170,62,207,89,167,62,39,46,164,62,178,0,161,62,121, + 209,157,62,133,160,154,62,223,109,151,62,143,57,148,62,160,3,145,62,26,204,141,62,5,147,138,62,107,88,135,62,86,28,132,62,205,222,128,62,182,63,123,62,16,191,116,62,187,59,110,62,201,181,103,62,77,45,97,62,89,162,90,62,255,20,84,62,81,133,77,62,99,243,70,62,70,95,64,62,13,201,57,62,202,48,51,62,144,150,44,62,114,250,37,62,130,92,31,62,210,188,24,62,118,27,18,62,127,120,11,62,1,212,4,62,29,92,252,61,114,13,239,61,41,188,225,61,102,104,212,61,78,18,199,61,8,186,185,61,184,95,172,61,132,3,159,61,146, + 165,145,61,7,70,132,61,18,202,109,61,122,5,83,61,145,62,56,61,164,117,29,61,252,170,2,61,202,189,207,60,86,35,154,60,97,14,73,60,197,167,187,59,61,122,86,186,9,70,241,187,18,221,99,188,80,138,167,188,65,36,221,188,227,93,9,189,35,40,36,189,150,240,62,189,242,182,89,189,234,122,116,189,26,158,135,189,66,253,148,189,200,90,162,189,134,182,175,189,87,16,189,189,22,104,202,189,155,189,215,189,195,16,229,189,105,97,242,189,101,175,255,189,74,125,6,190,104,33,13,190,250,195,19,190,237,100,26,190,46,4,33, + 190,172,161,39,190,83,61,46,190,16,215,52,190,210,110,59,190,134,4,66,190,25,152,72,190,121,41,79,190,148,184,85,190,86,69,92,190,174,207,98,190,137,87,105,190,214,220,111,190,128,95,118,190,120,223,124,190,84,174,129,190,129,235,132,190,56,39,136,190,114,97,139,190,36,154,142,190,69,209,145,190,205,6,149,190,179,58,152,190,238,108,155,190,116,157,158,190,61,204,161,190,64,249,164,190,115,36,168,190,207,77,171,190,73,117,174,190,218,154,177,190,120,190,180,190,27,224,183,190,186,255,186,190,75,29, + 190,190,199,56,193,190,37,82,196,190,91,105,199,190,97,126,202,190,48,145,205,190,188,161,208,190,0,176,211,190,241,187,214,190,135,197,217,190,186,204,220,190,129,209,223,190,211,211,226,190,169,211,229,190,250,208,232,190,189,203,235,190,234,195,238,190,120,185,241,190,96,172,244,190,154,156,247,190,28,138,250,190,223,116,253,190,109,46,0,191,3,161,1,191,45,18,3,191,230,129,4,191,44,240,5,191,250,92,7,191,76,200,8,191,30,50,10,191,108,154,11,191,50,1,13,191,108,102,14,191,23,202,15,191,45,44,17, + 191,172,140,18,191,144,235,19,191,213,72,21,191,118,164,22,191,113,254,23,191,192,86,25,191,98,173,26,191,81,2,28,191,138,85,29,191,9,167,30,191,203,246,31,191,204,68,33,191,9,145,34,191,124,219,35,191,36,36,37,191,253,106,38,191,2,176,39,191,48,243,40,191,132,52,42,191,250,115,43,191,143,177,44,191,63,237,45,191,7,39,47,191,227,94,48,191,208,148,49,191,202,200,50,191,206,250,51,191,218,42,53,191,232,88,54,191,247,132,55,191,2,175,56,191,7,215,57,191,3,253,58,191,241,32,60,191,207,66,61,191,154,98, + 62,191,79,128,63,191,233,155,64,191,104,181,65,191,198,204,66,191,1,226,67,191,23,245,68,191,3,6,70,191,196,20,71,191,86,33,72,191,182,43,73,191,225,51,74,191,212,57,75,191,141,61,76,191,9,63,77,191,68,62,78,191,61,59,79,191,240,53,80,191,90,46,81,191,121,36,82,191,74,24,83,191,202,9,84,191,247,248,84,191,206,229,85,191,77,208,86,191,112,184,87,191,55,158,88,191,156,129,89,191,160,98,90,191,62,65,91,191,117,29,92,191,65,247,92,191,162,206,93,191,148,163,94,191,20,118,95,191,34,70,96,191,186,19,97, + 191,217,222,97,191,127,167,98,191,169,109,99,191,84,49,100,191,126,242,100,191,38,177,101,191,73,109,102,191,229,38,103,191,248,221,103,191,128,146,104,191,123,68,105,191,232,243,105,191,195,160,106,191,12,75,107,191,192,242,107,191,222,151,108,191,100,58,109,191,80,218,109,191,160,119,110,191,83,18,111,191,102,170,111,191,217,63,112,191,169,210,112,191,213,98,113,191,91,240,113,191,58,123,114,191,113,3,115,191,253,136,115,191,222,11,116,191,17,140,116,191,150,9,117,191,107,132,117,191,143,252,117, + 191,0,114,118,191,189,228,118,191,198,84,119,191,24,194,119,191,178,44,120,191,147,148,120,191,187,249,120,191,40,92,121,191,217,187,121,191,205,24,122,191,2,115,122,191,121,202,122,191,47,31,123,191,36,113,123,191,88,192,123,191,201,12,124,191,118,86,124,191,95,157,124,191,130,225,124,191,224,34,125,191,119,97,125,191,71,157,125,191,79,214,125,191,142,12,126,191,4,64,126,191,176,112,126,191,146,158,126,191,169,201,126,191,245,241,126,191,117,23,127,191,41,58,127,191,16,90,127,191,43,119,127,191, + 120,145,127,191,248,168,127,191,170,189,127,191,143,207,127,191,165,222,127,191,237,234,127,191,102,244,127,191,17,251,127,191,237,254,127,191,234,255,127,63,229,248,127,63,166,230,127,63,45,201,127,63,124,160,127,63,149,108,127,63,121,45,127,63,44,227,126,63,177,141,126,63,11,45,126,63,63,193,125,63,82,74,125,63,72,200,124,63,40,59,124,63,247,162,123,63,189,255,122,63,128,81,122,63,72,152,121,63,30,212,120,63,9,5,120,63,19,43,119,63,70,70,118,63,172,86,117,63,78,92,116,63,56,87,115,63,118,71,114, + 63,19,45,113,63,28,8,112,63,158,216,110,63,165,158,109,63,64,90,108,63,126,11,107,63,107,178,105,63,25,79,104,63,150,225,102,63,242,105,101,63,62,232,99,63,139,92,98,63,234,198,96,63,109,39,95,63,38,126,93,63,40,203,91,63,133,14,90,63,83,72,88,63,163,120,86,63,139,159,84,63,32,189,82,63,118,209,80,63,163,220,78,63,189,222,76,63,219,215,74,63,19,200,72,63,124,175,70,63,46,142,68,63,65,100,66,63,206,49,64,63,236,246,61,63,180,179,59,63,66,104,57,63,173,20,55,63,16,185,52,63,134,85,50,63,41,234,47,63, + 21,119,45,63,101,252,42,63,53,122,40,63,161,240,37,63,198,95,35,63,192,199,32,63,172,40,30,63,169,130,27,63,212,213,24,63,74,34,22,63,42,104,19,63,147,167,16,63,164,224,13,63,123,19,11,63,57,64,8,63,253,102,5,63,231,135,2,63,45,70,255,62,91,113,249,62,151,145,243,62,36,167,237,62,69,178,231,62,60,179,225,62,76,170,219,62,186,151,213,62,201,123,207,62,190,86,201,62,223,40,195,62,112,242,188,62,183,179,182,62,251,108,176,62,129,30,170,62,146,200,163,62,115,107,157,62,108,7,151,62,197,156,144,62,199, + 43,138,62,185,180,131,62,199,111,122,62,33,107,109,62,17,92,96,62,41,67,83,62,253,32,70,62,32,246,56,62,38,195,43,62,164,136,30,62,45,71,17,62,87,255,3,62,110,99,237,61,194,189,210,61,218,14,184,61,222,87,157,61,251,153,130,61,188,172,79,61,101,28,26,61,153,10,201,60,42,167,59,60,193,120,214,186,45,68,113,188,87,215,227,188,76,129,39,189,148,15,93,189,21,74,137,189,90,6,164,189,109,187,190,189,34,104,217,189,78,11,244,189,227,81,7,190,47,152,20,190,247,215,33,190,165,16,47,190,166,65,60,190,100,106, + 73,190,77,138,86,190,205,160,99,190,80,173,112,190,69,175,125,190,13,83,133,190,158,200,139,190,13,56,146,190,18,161,152,190,102,3,159,190,191,94,165,190,216,178,171,190,105,255,177,190,43,68,184,190,216,128,190,190,42,181,196,190,219,224,202,190,165,3,209,190,69,29,215,190,117,45,221,190,241,51,227,190,118,48,233,190,192,34,239,190,141,10,245,190,155,231,250,190,211,92,0,191,56,64,3,191,219,29,6,191,155,245,8,191,90,199,11,191,247,146,14,191,84,88,17,191,80,23,20,191,205,207,22,191,172,129,25,191, + 208,44,28,191,26,209,30,191,109,110,33,191,171,4,36,191,183,147,38,191,116,27,41,191,199,155,43,191,147,20,46,191,187,133,48,191,38,239,50,191,183,80,53,191,85,170,55,191,227,251,57,191,74,69,60,191,110,134,62,191,55,191,64,191,139,239,66,191,83,23,69,191,117,54,71,191,218,76,73,191,107,90,75,191,16,95,77,191,179,90,79,191,62,77,81,191,154,54,83,191,179,22,85,191,114,237,86,191,197,186,88,191,149,126,90,191,208,56,92,191,98,233,93,191,56,144,95,191,64,45,97,191,103,192,98,191,156,73,100,191,206,200, + 101,191,235,61,103,191,227,168,104,191,167,9,106,191,39,96,107,191,84,172,108,191,31,238,109,191,122,37,111,191,88,82,112,191,171,116,113,191,103,140,114,191,127,153,115,191,231,155,116,191,149,147,117,191,126,128,118,191,150,98,119,191,212,57,120,191,47,6,121,191,158,199,121,191,23,126,122,191,148,41,123,191,13,202,123,191,122,95,124,191,213,233,124,191,24,105,125,191,62,221,125,191,64,70,126,191,28,164,126,191,204,246,126,191,77,62,127,191,156,122,127,191,182,171,127,191,153,209,127,191,67,236, + 127,191,180,251,127,191,166,255,127,63,148,227,127,63,156,154,127,63,204,36,127,63,56,130,126,63,253,178,125,63,63,183,124,63,42,143,123,63,243,58,122,63,212,186,120,63,17,15,119,63,246,55,117,63,213,53,115,63,8,9,113,63,241,177,110,63,249,48,108,63,144,134,105,63,47,179,102,63,83,183,99,63,132,147,96,63,78,72,93,63,69,214,89,63,3,62,86,63,43,128,82,63,101,157,78,63,94,150,74,63,204,107,70,63,106,30,66,63,249,174,61,63,64,30,57,63,13,109,52,63,50,156,47,63,135,172,42,63,235,158,37,63,63,116,32,63, + 109,45,27,63,97,203,21,63,13,79,16,63,104,185,10,63,107,11,5,63,46,140,254,62,221,212,242,62,241,242,230,62,127,232,218,62,166,183,206,62,136,98,194,62,78,235,181,62,42,84,169,62,81,159,156,62,253,206,143,62,109,229,130,62,206,201,107,62,98,159,81,62,48,80,55,62,211,224,28,62,241,85,2,62,98,104,207,61,124,0,154,61,36,251,72,61,27,164,187,60,243,119,86,187,100,61,241,188,187,192,99,189,103,93,167,189,20,189,220,189,3,251,8,190,115,127,35,190,52,231,61,190,164,45,88,190,38,78,114,190,18,34,134,190, + 137,5,147,190,52,207,159,190,213,124,172,190,51,12,185,190,26,123,197,190,91,199,209,190,205,238,221,190,80,239,233,190,199,198,245,190,144,185,0,191,38,121,6,191,36,33,12,191,141,176,17,191,102,38,23,191,186,129,28,191,152,193,33,191,21,229,38,191,74,235,43,191,86,211,48,191,91,156,53,191,131,69,58,191,253,205,62,191,252,52,67,191,188,121,71,191,125,155,75,191,132,153,79,191,31,115,83,191,161,39,87,191,99,182,90,191,198,30,94,191,48,96,97,191,15,122,100,191,216,107,103,191,7,53,106,191,31,213,108, + 191,169,75,111,191,55,152,113,191,98,186,115,191,201,177,117,191,22,126,119,191,246,30,121,191,33,148,122,191,85,221,123,191,89,250,124,191,250,234,125,191,14,175,126,191,116,70,127,191,15,177,127,191,206,238,127,191,0,0,0,0,0,0,0,0,3,0,0,0,2,0,0,0,3,0,0,0,2,0,0,0,5,0,0,0,2,0,0,0,3,0,0,0,2,0,0,0,3,0,0,0,2,0,0,0,5,0,0,0,2,0,0,0,3,0,0,0,2,0,0,0,0,0,206,64,0,0,200,64,0,0,184,64,0,0,170,64,0,0,162,64,0,0,154,64,0,0,144,64,0,0,140,64,0,0,156,64,0,0,150,64,0,0,146,64,0,0,142,64,0,0,156,64,0,0,148,64,0, + 0,138,64,0,0,144,64,0,0,140,64,0,0,148,64,0,0,152,64,0,0,142,64,0,0,112,64,0,0,112,64,0,0,112,64,0,0,112,64,0,0,112,64,0,134,107,63,0,20,46,63,0,112,189,62,0,208,76,62,0,0,102,63,0,0,76,63,0,0,38,63,0,0,0,63,15,0,0,0,10,0,0,0,5,0,0,0,6,0,0,0,4,0,0,0,3,0,0,0,191,104,0,0,199,104,0,0,215,104,0,0,247,104,0,0,255,104,0,0,15,105,0,0,47,105,0,0,87,105,0,0,167,105,0,0,71,106,0,0,79,106,0,0,95,106,0,0,32,0,10,0,20,46,100,1,130,106,0,0,194,107,0,0,2,108,0,0,20,108,0,0,180,108,0,0,252,108,0,0,134,95,0,0,32, + 0,16,0,102,38,171,1,68,109,0,0,68,111,0,0,132,111,0,0,162,111,0,0,162,112,0,0,234,112,0,0,156,95,0,0,0,0,0,0,64,31,0,0,184,36,0,0,236,44,0,0,188,52,0,0,92,68,0,0,168,97,0,0,128,56,1,0,0,0,0,0,40,35,0,0,224,46,0,0,164,56,0,0,68,72,0,0,180,95,0,0,172,138,0,0,128,56,1,0,0,0,0,0,4,41,0,0,176,54,0,0,104,66,0,0,252,83,0,0,84,111,0,0,16,164,0,0,128,56,1,0,77,113,0,0,80,113,0,0,10,103,242,14,86,205,228,29,10,103,242,14,117,82,130,12,89,154,4,25,117,82,130,12,70,17,49,10,237,3,98,20,70,17,49,10,218,2,215, + 7,249,198,173,15,218,2,215,7,34,182,82,5,218,250,164,10,34,182,82,5,70,243,46,30,43,227,75,14,31,102,128,24,28,44,29,10,218,97,72,18,237,156,244,6,236,48,19,11,227,144,165,4,237,164,29,2,10,223,107,3,48,117,0,0,112,23,0,0,32,209,255,255,32,209,255,255,0,64,0,0,108,34,0,0,66,15,0,0,18,6,0,0,77,2,0,0,219,0,0,0,237,0,0,0,153,0,0,0,73,0,0,0,30,0,0,0,12,0,0,0,7,0,0,0,0,64,0,0,147,93,0,0,189,112,0,0,237,121,0,0,178,125,0,0,36,127,0,0,0,250,0,0,128,62,0,0,160,140,0,0,128,62,0,0,248,42,0,0,232,3,0,0,176, + 54,0,0,232,3,0,0,8,82,0,0,208,7,0,0,96,109,0,0,208,7,0,0,224,46,0,0,232,3,0,0,80,70,0,0,208,7,0,0,8,82,0,0,208,7,0,0,48,117,0,0,208,7,0,0,248,42,0,0,232,3,0,0,176,54,0,0,232,3,0,0,104,66,0,0,232,3,0,0,8,82,0,0,208,7,0,0,224,46,0,0,232,3,0,0,152,58,0,0,232,3,0,0,80,70,0,0,208,7,0,0,240,85,0,0,208,7,0,0,230,90,52,56,119,78,51,57,211,217,201,57,146,145,51,58,204,96,140,58,97,251,201,58,153,126,9,59,203,128,51,59,213,37,99,59,119,46,140,59,168,138,169,59,69,184,201,59,135,166,236,59,232,46,9,60,174,102, + 29,60,247,2,51,60,147,255,73,60,79,88,98,60,94,17,124,60,46,145,139,60,189,199,153,60,92,172,168,60,243,60,184,60,129,121,200,60,238,95,217,60,57,240,234,60,99,42,253,60,53,7,8,61,16,204,17,61,205,228,27,61,97,80,38,61,203,14,49,61,0,31,60,61,254,128,71,61,198,52,83,61,63,56,95,61,105,139,107,61,69,46,120,61,105,144,130,61,123,48,137,61,224,247,143,61,138,229,150,61,123,249,157,61,177,51,165,61,33,147,172,61,80,24,180,61,51,194,187,61,79,145,195,61,18,132,203,61,2,155,211,61,31,214,219,61,215,51, + 228,61,175,180,236,61,33,88,245,61,168,29,254,61,161,130,3,62,242,6,8,62,199,155,12,62,221,64,17,62,52,246,21,62,69,187,26,62,17,144,31,62,84,116,36,62,203,103,41,62,51,106,46,62,141,123,51,62,82,155,56,62,197,201,61,62,28,6,67,62,89,80,72,62,122,168,77,62,183,13,83,62,82,128,88,62,8,0,94,62,84,140,99,62,242,36,105,62,37,202,110,62,36,123,116,62,172,55,122,62,0,0,128,62,171,233,130,62,249,216,133,62,133,205,136,62,80,199,139,62,55,198,142,62,247,201,145,62,179,210,148,62,38,224,151,62,15,242,154, + 62,108,8,158,62,28,35,161,62,255,65,164,62,208,100,167,62,177,139,170,62,28,182,173,62,84,228,176,62,211,21,180,62,186,74,183,62,232,130,186,62,249,189,189,62,13,252,192,62,226,60,196,62,86,128,199,62,71,198,202,62,149,14,206,62,251,88,209,62,122,165,212,62,241,243,215,62,28,68,219,62,217,149,222,62,8,233,225,62,167,61,229,62,83,147,232,62,12,234,235,62,175,65,239,62,28,154,242,62,14,243,245,62,136,76,249,62,34,166,252,62,0,0,0,63,239,172,1,63,188,89,3,63,121,6,5,63,242,178,6,63,41,95,8,63,250,10, + 10,63,86,182,11,63,44,97,13,63,124,11,15,63,19,181,16,63,242,93,18,63,8,6,20,63,67,173,21,63,130,83,23,63,182,248,24,63,220,156,26,63,213,63,28,63,143,225,29,63,249,129,31,63,4,33,33,63,140,190,34,63,163,90,36,63,23,245,37,63,214,141,39,63,242,36,41,63,40,186,42,63,152,77,44,63,1,223,45,63,114,110,47,63,202,251,48,63,249,134,50,63,237,15,52,63,167,150,53,63,4,27,55,63,229,156,56,63,88,28,58,63,61,153,59,63,131,19,61,63,42,139,62,63,0,0,64,63,21,114,65,63,55,225,66,63,119,77,68,63,195,182,69,63,235, + 28,71,63,254,127,72,63,236,223,73,63,146,60,75,63,225,149,76,63,234,235,77,63,121,62,79,63,143,141,80,63,43,217,81,63,29,33,83,63,115,101,84,63,13,166,85,63,235,226,86,63,252,27,88,63,47,81,89,63,115,130,90,63,201,175,91,63,14,217,92,63,67,254,93,63,88,31,95,63,75,60,96,63,252,84,97,63,106,105,98,63,133,121,99,63,60,133,100,63,160,140,101,63,126,143,102,63,214,141,103,63,186,135,104,63,246,124,105,63,156,109,106,63,138,89,107,63,209,64,108,63,79,35,109,63,4,1,110,63,241,217,110,63,243,173,111,63, + 28,125,112,63,73,71,113,63,124,12,114,63,180,204,114,63,240,135,115,63,16,62,116,63,19,239,116,63,250,154,117,63,179,65,118,63,63,227,118,63,141,127,119,63,173,22,120,63,126,168,120,63,1,53,121,63,52,188,121,63,24,62,122,63,157,186,122,63,194,49,123,63,119,163,123,63,187,15,124,63,159,118,124,63,2,216,124,63,244,51,125,63,101,138,125,63,68,219,125,63,179,38,126,63,143,108,126,63,235,172,126,63,163,231,126,63,218,28,127,63,127,76,127,63,129,118,127,63,2,155,127,63,208,185,127,63,28,211,127,63,197, + 230,127,63,203,244,127,63,47,253,127,63,0,0,128,63,2,0,0,0,4,0,0,0,6,0,0,0,8,0,0,0,10,0,0,0,12,0,0,0,14,0,0,0,16,0,0,0,20,0,0,0,24,0,0,0,28,0,0,0,32,0,0,0,40,0,0,0,48,0,0,0,56,0,0,0,68,0,0,0,80,0,0,0,96,0,0,0,120,0,0,0,1,0,0,0,2,0,0,0,4,0,0,0,6,0,0,0,8,0,0,0,10,0,0,0,12,0,0,0,14,0,0,0,16,0,0,0,20,0,0,0,24,0,0,0,28,0,0,0,32,0,0,0,40,0,0,0,48,0,0,0,56,0,0,0,68,0,0,0,80,0,0,0,96,0,0,0,120,0,0,0,160,0,0,0,200,0,0,0,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62, + 0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,0,0,128,62,208,37,180,62,151,57,173,62,9,165,159,62,250,237,139,62,205,172,101,62,248,169,42,62,52,48,210,61,90,241,13,61,90,241,13,189,52,48,210,189,248,169,42,190,205,172,101,190,250,237,139,190,9,165,159,190,151,57,173,190,208,37,180,190,135,138,177,62,27,131,150,62,96,35,73,62,196,66,141,61,196,66,141,189,96,35,73,190,27,131,150,190,135,138,177,190,135,138,177,190,27,131,150,190,96,35,73,190,196,66,141,189,196,66,141, + 61,96,35,73,62,27,131,150,62,135,138,177,62,151,57,173,62,205,172,101,62,90,241,13,61,248,169,42,190,9,165,159,190,208,37,180,190,250,237,139,190,52,48,210,189,52,48,210,61,250,237,139,62,208,37,180,62,9,165,159,62,248,169,42,62,90,241,13,189,205,172,101,190,151,57,173,190,125,61,167,62,210,139,10,62,210,139,10,190,125,61,167,190,125,61,167,190,210,139,10,190,210,139,10,62,125,61,167,62,125,61,167,62,210,139,10,62,210,139,10,190,125,61,167,190,125,61,167,190,210,139,10,190,210,139,10,62,125,61,167, + 62,9,165,159,62,90,241,13,61,250,237,139,190,151,57,173,190,52,48,210,189,205,172,101,62,208,37,180,62,248,169,42,62,248,169,42,190,208,37,180,190,205,172,101,190,52,48,210,61,151,57,173,62,250,237,139,62,90,241,13,189,9,165,159,190,27,131,150,62,196,66,141,189,135,138,177,190,96,35,73,190,96,35,73,62,135,138,177,62,196,66,141,61,27,131,150,190,27,131,150,190,196,66,141,61,135,138,177,62,96,35,73,62,96,35,73,190,135,138,177,190,196,66,141,189,27,131,150,62,250,237,139,62,248,169,42,190,151,57,173, + 190,90,241,13,61,208,37,180,62,52,48,210,61,9,165,159,190,205,172,101,190,205,172,101,62,9,165,159,62,52,48,210,189,208,37,180,190,90,241,13,189,151,57,173,62,248,169,42,62,250,237,139,190,0,0,0,0,5,193,35,61,233,125,163,61,37,150,244,61,226,116,34,62,172,28,74,62,221,37,113,62,52,186,139,62,180,119,158,62,228,191,176,62,173,136,194,62,37,201,211,62,24,122,228,62,24,149,244,62,200,10,2,63,28,124,9,63,73,157,16,63,202,109,23,63,192,237,29,63,159,29,36,63,84,254,41,63,46,145,47,63,224,215,52,63,99, + 212,57,63,240,136,62,63,211,247,66,63,171,35,71,63,23,15,75,63,216,188,78,63,173,47,82,63,106,106,85,63,206,111,88,63,154,66,91,63,142,229,93,63,75,91,96,63,110,166,98,63,100,201,100,63,155,198,102,63,111,160,104,63,247,88,106,63,128,242,107,63,223,110,109,63,11,208,110,63,202,23,112,63,224,71,113,63,225,97,114,63,77,103,115,63,150,89,116,63,12,58,117,63,255,9,118,63,138,202,118,63,187,124,119,63,192,33,120,63,98,186,120,63,157,71,121,63,75,202,121,63,36,67,122,63,242,178,122,63,59,26,123,63,200, + 121,123,63,32,210,123,63,200,35,124,63,55,111,124,63,242,180,124,63,94,245,124,63,224,48,125,63,236,103,125,63,183,154,125,63,180,201,125,63,6,245,125,63,17,29,126,63,24,66,126,63,78,100,126,63,211,131,126,63,253,160,126,63,237,187,126,63,195,212,126,63,179,235,126,63,239,0,127,63,135,20,127,63,141,38,127,63,67,55,127,63,170,70,127,63,227,84,127,63,15,98,127,63,47,110,127,63,100,121,127,63,190,131,127,63,63,141,127,63,24,150,127,63,56,158,127,63,194,165,127,63,163,172,127,63,16,179,127,63,245,184, + 127,63,119,190,127,63,114,195,127,63,25,200,127,63,108,204,127,63,91,208,127,63,6,212,127,63,111,215,127,63,131,218,127,63,102,221,127,63,21,224,127,63,130,226,127,63,205,228,127,63,230,230,127,63,205,232,127,63,146,234,127,63,70,236,127,63,200,237,127,63,40,239,127,63,120,240,127,63,166,241,127,63,195,242,127,63,191,243,127,63,186,244,127,63,148,245,127,63,94,246,127,63,39,247,127,63,207,247,127,63,119,248,127,63,253,248,127,63,148,249,127,63,9,250,127,63,127,250,127,63,244,250,127,63,89,251,127, + 63,173,251,127,63,1,252,127,63,84,252,127,63,152,252,127,63,219,252,127,63,30,253,127,63,80,253,127,63,130,253,127,63,181,253,127,63,231,253,127,63,9,254,127,63,59,254,127,63,93,254,127,63,126,254,127,63,143,254,127,63,176,254,127,63,210,254,127,63,227,254,127,63,244,254,127,63,21,255,127,63,38,255,127,63,55,255,127,63,71,255,127,63,88,255,127,63,88,255,127,63,105,255,127,63,122,255,127,63,122,255,127,63,139,255,127,63,155,255,127,63,155,255,127,63,155,255,127,63,172,255,127,63,172,255,127,63,189, + 255,127,63,189,255,127,63,189,255,127,63,206,255,127,63,206,255,127,63,206,255,127,63],"i8",4,y.h+10240); + O([206,255,127,63,206,255,127,63,222,255,127,63,222,255,127,63,222,255,127,63,222,255,127,63,222,255,127,63,222,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,239,255,127,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,3,0,0,0,148,80,0,0,160,80,0,0,25,0,0,0,15,0,0,0,2,0,0,0,14,190, + 192,189,172,31,155,190,149,130,26,191,150,149,70,190,84,114,62,190,146,3,26,191,6,152,62,189,2,160,234,189,182,43,212,189,185,114,30,191,106,190,162,190,28,7,46,190,107,243,143,189,90,158,23,62,33,173,209,62,10,102,12,63,125,60,188,62,20,33,253,190,143,169,67,63,8,119,235,191,10,243,46,62,117,147,76,65,80,83,139,191,108,236,162,191,181,21,130,193,28,107,193,65,162,98,178,192,255,231,48,190,47,79,39,190,158,206,101,190,255,87,194,189,155,60,149,189,203,248,135,190,44,97,205,189,203,33,83,189,64,166, + 21,190,238,35,247,189,160,253,56,190,219,167,3,62,233,95,226,62,213,202,252,190,29,203,43,62,231,168,83,62,1,79,74,190,247,3,214,62,71,119,192,63,173,249,69,191,64,164,32,193,43,194,205,62,192,178,62,64,201,118,115,65,100,204,241,191,39,165,152,191,23,204,233,60,134,193,132,187,201,232,144,61,84,72,7,60,154,231,189,189,103,71,42,188,59,137,140,187,159,122,160,187,88,90,145,189,85,196,39,187,169,11,34,61,177,219,103,62,241,54,5,61,52,17,38,62,170,10,205,189,86,185,248,62,108,4,2,62,86,102,146,62,228, + 254,126,60,106,251,215,61,159,142,67,64,136,70,147,63,57,40,129,191,71,90,234,191,139,84,84,64,210,53,91,192,13,253,243,189,232,39,38,189,25,31,226,59,241,90,147,60,171,170,28,189,237,238,195,59,5,106,150,188,246,141,249,58,37,201,19,190,106,115,50,189,210,214,129,58,161,100,98,62,158,210,17,62,128,215,247,62,221,12,207,62,124,15,3,63,250,242,114,190,55,139,119,62,47,110,179,62,183,13,51,191,136,99,38,65,18,165,41,64,83,208,27,192,53,7,134,192,125,150,135,63,60,247,218,63,12,212,218,59,186,186,147, + 189,191,192,34,189,69,144,20,61,38,112,235,189,208,37,193,188,210,156,6,60,124,58,104,188,114,11,7,189,31,26,17,189,171,204,53,59,154,208,148,190,218,230,146,191,140,104,163,190,89,193,47,191,163,233,188,62,64,50,245,62,253,245,58,62,163,119,210,190,8,144,97,63,39,107,147,192,33,31,188,63,224,243,171,62,161,214,232,191,245,91,241,193,8,172,177,64,252,177,255,58,106,21,253,189,37,245,148,189,41,102,131,189,252,233,90,189,35,134,221,189,20,249,191,189,43,237,142,189,75,171,225,188,167,236,68,190,122, + 110,225,189,172,28,146,62,105,170,207,190,7,203,189,61,35,101,147,190,201,231,89,191,252,194,203,189,212,95,111,190,111,129,164,191,13,108,145,63,155,201,71,64,187,39,143,189,66,91,238,191,113,201,41,64,120,238,233,192,26,168,28,64,135,138,146,186,54,152,129,189,127,33,26,189,138,114,25,190,229,100,18,62,247,202,60,62,113,202,252,61,117,220,154,61,70,65,240,61,200,40,191,61,71,193,141,61,22,144,172,61,175,81,144,61,27,166,113,61,173,246,192,61,61,209,229,190,92,47,215,60,148,107,138,62,106,78,134, + 190,98,186,48,62,49,37,0,64,133,9,35,190,99,96,29,61,26,81,35,65,182,248,132,64,7,206,21,192,120,99,97,189,79,18,30,60,98,186,16,190,8,223,224,60,187,222,12,61,136,166,71,189,97,152,194,61,35,245,253,187,158,146,24,189,185,155,179,187,187,236,135,189,45,182,196,61,230,206,76,190,12,24,41,189,251,87,22,63,48,68,83,61,142,172,172,62,218,226,90,63,93,26,43,63,202,82,235,189,178,75,104,192,37,89,239,190,177,164,92,190,57,98,39,64,145,238,207,62,180,142,174,191,203,61,46,61,20,5,250,61,210,98,191,61,67, + 4,252,61,160,165,11,61,155,226,17,190,245,130,15,61,15,250,72,189,55,41,150,61,113,52,108,61,83,235,253,61,185,215,83,189,147,139,129,190,69,47,23,63,113,89,21,62,238,95,161,62,207,217,98,62,177,168,24,190,79,89,93,62,127,251,178,190,253,135,196,65,161,131,126,191,11,66,29,63,242,82,150,193,27,76,53,192,69,128,55,191,84,196,177,190,253,130,245,62,128,238,123,190,215,96,155,61,137,150,12,62,211,19,54,190,185,51,243,61,46,253,141,186,175,7,115,190,129,34,182,62,33,7,5,190,218,78,96,189,101,28,163,190, + 21,171,166,190,107,211,56,62,171,31,128,189,183,155,16,62,40,41,176,62,24,207,192,62,95,126,23,191,102,247,186,64,170,241,194,190,46,56,99,62,239,172,181,191,48,108,229,201,122,170,171,63,218,31,232,60,27,113,55,189,162,59,173,188,127,121,210,188,9,192,100,60,236,86,170,60,101,102,48,188,198,207,53,60,202,13,112,61,62,180,207,188,178,134,6,189,121,35,243,61,78,38,94,190,247,62,21,62,230,93,245,61,106,111,187,189,198,21,247,189,41,83,161,189,106,23,19,190,134,89,24,191,188,116,147,191,198,109,160, + 191,181,224,149,191,42,227,138,64,64,26,110,201,249,102,175,191,204,76,36,189,13,168,87,62,141,239,11,190,159,57,11,62,64,87,86,189,28,28,54,61,199,207,107,60,239,56,135,59,170,27,158,188,226,177,95,62,162,178,225,189,236,163,1,192,165,17,107,63,28,8,29,192,134,3,153,63,184,86,123,189,48,18,246,191,186,192,157,62,172,202,254,62,42,144,105,63,102,75,86,62,147,24,22,192,95,94,12,64,39,20,207,192,144,78,217,63,169,161,57,191,112,218,66,60,77,206,26,61,109,235,98,61,109,130,185,60,243,67,144,189,93,3, + 246,188,182,124,73,60,72,233,136,187,62,158,140,189,125,64,0,61,219,50,32,61,194,108,186,62,242,165,193,189,126,80,188,60,194,81,50,190,228,218,168,62,44,239,234,61,112,182,153,62,62,33,219,61,18,136,7,62,8,148,185,64,125,118,104,63,80,195,103,191,88,202,86,192,248,56,67,62,207,161,60,62,50,116,44,191,208,94,109,62,213,29,112,189,65,74,108,62,216,101,224,190,240,193,123,62,23,72,48,190,182,123,179,61,121,115,56,191,85,106,38,62,85,187,139,60,143,114,208,61,117,230,198,62,213,38,170,63,2,241,138,63, + 108,177,111,191,51,167,23,192,66,9,215,192,144,102,92,192,241,215,8,64,116,181,99,65,82,68,157,64,20,203,69,192,16,18,27,193,252,170,68,191,164,228,229,63,75,35,97,61,17,82,39,62,16,59,163,61,253,223,12,61,211,175,99,189,237,178,165,187,217,102,153,60,110,201,5,61,34,162,189,60,175,119,31,62,154,15,67,61,75,120,130,190,151,255,204,63,210,28,77,191,119,132,35,64,65,213,60,63,19,102,174,191,221,9,50,191,71,90,28,192,62,174,221,191,131,250,124,64,205,1,242,63,101,224,248,62,75,89,53,193,128,147,112, + 74,249,75,195,190,126,29,248,61,94,44,104,191,249,20,60,64,51,196,209,63,231,255,97,63,2,213,95,63,45,207,155,63,46,226,95,191,166,182,164,62,93,249,72,63,160,81,114,63,134,55,19,191,62,203,93,192,34,137,98,63,173,62,189,61,144,131,30,193,116,93,200,62,10,242,35,62,170,43,3,192,240,167,132,64,210,22,140,61,58,60,20,190,123,16,146,190,69,44,194,62,116,70,148,191,167,29,227,188,154,153,29,193,16,93,154,192,51,167,109,64,139,224,119,64,26,163,97,64,0,64,202,69,27,76,255,82,130,90,179,98,162,107,96,117, + 0,0,1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,10,0,12,0,14,0,16,0,20,0,24,0,28,0,34,0,40,0,48,0,60,0,78,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,8,0,8,0,8,0,16,0,16,0,16,0,21,0,21,0,24,0,29,0,34,0,36,0,0,0,96,0,192,0,32,1,128,1,32,0,128,0,224,0,64,1,160,1,64,0,160,0,0,1,96,1,192,1,8,0,104,0,200,0,40,1,136,1,40,0,136,0,232,0,72,1,168,1,72,0,168,0,8,1,104,1,200,1,16,0,112,0,208,0,48,1,144,1,48,0,144,0,240,0,80,1,176,1,80,0,176,0,16,1,112,1,208,1,24,0,120,0,216,0,56,1,152,1,56,0,152,0,248,0,88,1,184,1,88,0, + 184,0,24,1,120,1,216,1,4,0,100,0,196,0,36,1,132,1,36,0,132,0,228,0,68,1,164,1,68,0,164,0,4,1,100,1,196,1,12,0,108,0,204,0,44,1,140,1,44,0,140,0,236,0,76,1,172,1,76,0,172,0,12,1,108,1,204,1,20,0,116,0,212,0,52,1,148,1,52,0,148,0,244,0,84,1,180,1,84,0,180,0,20,1,116,1,212,1,28,0,124,0,220,0,60,1,156,1,60,0,156,0,252,0,92,1,188,1,92,0,188,0,28,1,124,1,220,1,1,0,97,0,193,0,33,1,129,1,33,0,129,0,225,0,65,1,161,1,65,0,161,0,1,1,97,1,193,1,9,0,105,0,201,0,41,1,137,1,41,0,137,0,233,0,73,1,169,1,73,0,169, + 0,9,1,105,1,201,1,17,0,113,0,209,0,49,1,145,1,49,0,145,0,241,0,81,1,177,1,81,0,177,0,17,1,113,1,209,1,25,0,121,0,217,0,57,1,153,1,57,0,153,0,249,0,89,1,185,1,89,0,185,0,25,1,121,1,217,1,5,0,101,0,197,0,37,1,133,1,37,0,133,0,229,0,69,1,165,1,69,0,165,0,5,1,101,1,197,1,13,0,109,0,205,0,45,1,141,1,45,0,141,0,237,0,77,1,173,1,77,0,173,0,13,1,109,1,205,1,21,0,117,0,213,0,53,1,149,1,53,0,149,0,245,0,85,1,181,1,85,0,181,0,21,1,117,1,213,1,29,0,125,0,221,0,61,1,157,1,61,0,157,0,253,0,93,1,189,1,93,0,189, + 0,29,1,125,1,221,1,2,0,98,0,194,0,34,1,130,1,34,0,130,0,226,0,66,1,162,1,66,0,162,0,2,1,98,1,194,1,10,0,106,0,202,0,42,1,138,1,42,0,138,0,234,0,74,1,170,1,74,0,170,0,10,1,106,1,202,1,18,0,114,0,210,0,50,1,146,1,50,0,146,0,242,0,82,1,178,1,82,0,178,0,18,1,114,1,210,1,26,0,122,0,218,0,58,1,154,1,58,0,154,0,250,0,90,1,186,1,90,0,186,0,26,1,122,1,218,1,6,0,102,0,198,0,38,1,134,1,38,0,134,0,230,0,70,1,166,1,70,0,166,0,6,1,102,1,198,1,14,0,110,0,206,0,46,1,142,1,46,0,142,0,238,0,78,1,174,1,78,0,174,0,14, + 1,110,1,206,1,22,0,118,0,214,0,54,1,150,1,54,0,150,0,246,0,86,1,182,1,86,0,182,0,22,1,118,1,214,1,30,0,126,0,222,0,62,1,158,1,62,0,158,0,254,0,94,1,190,1,94,0,190,0,30,1,126,1,222,1,3,0,99,0,195,0,35,1,131,1,35,0,131,0,227,0,67,1,163,1,67,0,163,0,3,1,99,1,195,1,11,0,107,0,203,0,43,1,139,1,43,0,139,0,235,0,75,1,171,1,75,0,171,0,11,1,107,1,203,1,19,0,115,0,211,0,51,1,147,1,51,0,147,0,243,0,83,1,179,1,83,0,179,0,19,1,115,1,211,1,27,0,123,0,219,0,59,1,155,1,59,0,155,0,251,0,91,1,187,1,91,0,187,0,27,1, + 123,1,219,1,7,0,103,0,199,0,39,1,135,1,39,0,135,0,231,0,71,1,167,1,71,0,167,0,7,1,103,1,199,1,15,0,111,0,207,0,47,1,143,1,47,0,143,0,239,0,79,1,175,1,79,0,175,0,15,1,111,1,207,1,23,0,119,0,215,0,55,1,151,1,55,0,151,0,247,0,87,1,183,1,87,0,183,0,23,1,119,1,215,1,31,0,127,0,223,0,63,1,159,1,63,0,159,0,255,0,95,1,191,1,95,0,191,0,31,1,127,1,223,1,0,0,48,0,96,0,144,0,192,0,16,0,64,0,112,0,160,0,208,0,32,0,80,0,128,0,176,0,224,0,4,0,52,0,100,0,148,0,196,0,20,0,68,0,116,0,164,0,212,0,36,0,84,0,132,0,180, + 0,228,0,8,0,56,0,104,0,152,0,200,0,24,0,72,0,120,0,168,0,216,0,40,0,88,0,136,0,184,0,232,0,12,0,60,0,108,0,156,0,204,0,28,0,76,0,124,0,172,0,220,0,44,0,92,0,140,0,188,0,236,0,1,0,49,0,97,0,145,0,193,0,17,0,65,0,113,0,161,0,209,0,33,0,81,0,129,0,177,0,225,0,5,0,53,0,101,0,149,0,197,0,21,0,69,0,117,0,165,0,213,0,37,0,85,0,133,0,181,0,229,0,9,0,57,0,105,0,153,0,201,0,25,0,73,0,121,0,169,0,217,0,41,0,89,0,137,0,185,0,233,0,13,0,61,0,109,0,157,0,205,0,29,0,77,0,125,0,173,0,221,0,45,0,93,0,141,0,189,0, + 237,0,2,0,50,0,98,0,146,0,194,0,18,0,66,0,114,0,162,0,210,0,34,0,82,0,130,0,178,0,226,0,6,0,54,0,102,0,150,0,198,0,22,0,70,0,118,0,166,0,214,0,38,0,86,0,134,0,182,0,230,0,10,0,58,0,106,0,154,0,202,0,26,0,74,0,122,0,170,0,218,0,42,0,90,0,138,0,186,0,234,0,14,0,62,0,110,0,158,0,206,0,30,0,78,0,126,0,174,0,222,0,46,0,94,0,142,0,190,0,238,0,3,0,51,0,99,0,147,0,195,0,19,0,67,0,115,0,163,0,211,0,35,0,83,0,131,0,179,0,227,0,7,0,55,0,103,0,151,0,199,0,23,0,71,0,119,0,167,0,215,0,39,0,87,0,135,0,183,0,231, + 0,11,0,59,0,107,0,155,0,203,0,27,0,75,0,123,0,171,0,219,0,43,0,91,0,139,0,187,0,235,0,15,0,63,0,111,0,159,0,207,0,31,0,79,0,127,0,175,0,223,0,47,0,95,0,143,0,191,0,239,0,0,0,24,0,48,0,72,0,96,0,8,0,32,0,56,0,80,0,104,0,16,0,40,0,64,0,88,0,112,0,4,0,28,0,52,0,76,0,100,0,12,0,36,0,60,0,84,0,108,0,20,0,44,0,68,0,92,0,116,0,1,0,25,0,49,0,73,0,97,0,9,0,33,0,57,0,81,0,105,0,17,0,41,0,65,0,89,0,113,0,5,0,29,0,53,0,77,0,101,0,13,0,37,0,61,0,85,0,109,0,21,0,45,0,69,0,93,0,117,0,2,0,26,0,50,0,74,0,98,0,10, + 0,34,0,58,0,82,0,106,0,18,0,42,0,66,0,90,0,114,0,6,0,30,0,54,0,78,0,102,0,14,0,38,0,62,0,86,0,110,0,22,0,46,0,70,0,94,0,118,0,3,0,27,0,51,0,75,0,99,0,11,0,35,0,59,0,83,0,107,0,19,0,43,0,67,0,91,0,115,0,7,0,31,0,55,0,79,0,103,0,15,0,39,0,63,0,87,0,111,0,23,0,47,0,71,0,95,0,119,0,0,0,12,0,24,0,36,0,48,0,4,0,16,0,28,0,40,0,52,0,8,0,20,0,32,0,44,0,56,0,1,0,13,0,25,0,37,0,49,0,5,0,17,0,29,0,41,0,53,0,9,0,21,0,33,0,45,0,57,0,2,0,14,0,26,0,38,0,50,0,6,0,18,0,30,0,42,0,54,0,10,0,22,0,34,0,46,0,58,0,3,0,15, + 0,27,0,39,0,51,0,7,0,19,0,31,0,43,0,55,0,11,0,23,0,35,0,47,0,59,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,41,0,41,0,41,0,82,0,82,0,123,0,164,0,200,0,222,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,41,0,41,0,41,0,41,0,123,0,123,0,123,0,164,0,164,0,240,0,10,1,27,1,39,1,41,0,41,0,41,0,41,0,41,0,41,0,41,0,41,0,123,0,123,0,123,0,123,0,240,0,240,0,240,0,10,1,10,1,49,1,62,1,72,1,80,1,123,0,123,0,123,0,123,0,123,0,123,0,123,0,123,0,240,0,240,0,240,0,240,0,49,1,49,1,49,1,62,1, + 62,1,87,1,95,1,102,1,108,1,240,0,240,0,240,0,240,0,240,0,240,0,240,0,240,0,49,1,49,1,49,1,49,1,87,1,87,1,87,1,95,1,95,1,114,1,120,1,126,1,131,1,184,126,154,121,154,121,102,102,184,126,51,115,16,48,250,0,3,0,6,0,3,0,3,0,3,0,4,0,3,0,3,0,3,0,205,1,100,0,3,0,40,0,3,0,3,0,3,0,5,0,14,0,14,0,10,0,11,0,3,0,8,0,9,0,7,0,3,0,91,1,18,0,29,0,38,0,40,0,46,0,52,0,62,0,84,0,92,202,190,216,182,223,154,226,156,230,120,236,122,244,204,252,52,3,134,11,136,19,100,25,102,29,74,32,66,39,164,53,100,0,240,0,32,0,100,0,205, + 60,0,48,0,32,30,161,36,42,0,32,254,31,246,31,234,31,216,31,194,31,168,31,136,31,98,31,58,31,10,31,216,30,160,30,98,30,34,30,220,29,144,29,66,29,238,28,150,28,58,28,216,27,114,27,10,27,156,26,42,26,180,25,58,25,188,24,60,24,182,23,46,23,160,22,16,22,126,21,232,20,78,20,176,19,16,19,110,18,200,17,30,17,116,16,198,15,22,15,100,14,174,13,248,12,64,12,132,11,200,10,10,10,74,9,138,8,198,7,2,7,62,6,120,5,178,4,234,3,34,3,90,2,146,1,202,0,0,0,54,255,110,254,166,253,222,252,22,252,78,251,136,250,194,249,254, + 248,58,248,118,247,182,246,246,245,56,245,124,244,192,243,8,243,82,242,156,241,234,240,58,240,140,239,226,238,56,238,146,237,240,236,80,236,178,235,24,235,130,234,240,233,96,233,210,232,74,232,196,231,68,231,198,230,76,230,214,229,100,229,246,228,142,228,40,228,198,227,106,227,18,227,190,226,112,226,36,226,222,225,158,225,96,225,40,225,246,224,198,224,158,224,120,224,88,224,62,224,40,224,22,224,10,224,2,224,0,224,210,6,138,58,171,152,198,26,169,100,246,216,42,175,213,201,207,255,64,0,17,0,99,255, + 97,1,16,254,163,0,39,43,189,86,217,255,6,0,91,0,86,255,186,0,23,0,128,252,192,24,216,77,237,255,220,255,102,0,167,255,232,255,72,1,73,252,8,10,37,62,135,199,61,201,64,0,128,0,134,255,36,0,54,1,0,253,72,2,51,36,69,69,12,0,128,0,18,0,114,255,32,1,139,255,159,252,27,16,123,56,104,2,13,200,246,255,39,0,58,0,210,255,172,255,120,0,184,0,197,254,227,253,4,5,4,21,64,35,230,62,198,196,243,255,0,0,20,0,26,0,5,0,225,255,213,255,252,255,65,0,90,0,7,0,99,255,8,255,212,255,81,2,47,6,52,10,199,12,228,87,5,197,3, + 0,242,255,236,255,241,255,2,0,25,0,37,0,25,0,240,255,185,255,149,255,177,255,50,0,36,1,111,2,214,3,8,5,184,5,148,107,103,196,17,0,12,0,8,0,1,0,246,255,234,255,226,255,224,255,234,255,3,0,44,0,100,0,168,0,243,0,61,1,125,1,173,1,199,1,19,245,149,230,89,18,243,41,31,6,84,32,189,0,168,253,105,2,103,119,117,0,97,255,210,251,8,116,52,0,221,0,168,246,116,110,252,255,17,2,234,242,229,102,208,255,246,2,140,240,165,93,176,255,137,3,117,239,6,83,157,255,204,3,130,239,102,71,149,255,199,3,139,240,39,59,153,255, + 128,3,97,242,174,46,165,255,5,3,207,244,94,34,185,255,99,2,161,247,152,22,210,255,169,1,161,250,180,11,0,1,1,1,2,3,3,3,2,3,3,3,2,3,3,3,0,3,12,15,48,51,60,63,192,195,204,207,240,243,252,255,0,255,0,255,0,255,0,255,0,255,0,254,1,0,1,255,0,254,0,253,2,0,1,255,0,254,0,253,3,0,1,255,117,110,107,110,111,119,110,32,101,114,114,111,114,0,115,117,99,99,101,115,115,0,105,110,118,97,108,105,100,32,97,114,103,117,109,101,110,116,0,98,117,102,102,101,114,32,116,111,111,32,115,109,97,108,108,0,105,110,116,101, + 114,110,97,108,32,101,114,114,111,114,0,99,111,114,114,117,112,116,101,100,32,115,116,114,101,97,109,0,114,101,113,117,101,115,116,32,110,111,116,32,105,109,112,108,101,109,101,110,116,101,100,0,105,110,118,97,108,105,100,32,115,116,97,116,101,0,109,101,109,111,114,121,32,97,108,108,111,99,97,116,105,111,110,32,102,97,105,108,101,100,0,108,105,98,111,112,117,115,32,49,46,49,46,50,0,2,1,0,255,255,156,110,86,70,59,51,45,40,37,33,31,28,26,25,23,22,21,20,19,18,17,16,16,15,15,14,13,13,12,12,12,12,11,11, + 11,10,10,10,9,9,9,9,9,9,8,8,8,8,8,7,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,25,23,2,0,126,124,119,109,87,41,19,9,4,2,0,2,1,0,25,23,2,0,126,124,119,109,87,41,19,9,4,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,90,80,75,69,63,56,49,40,34,29,20,18,10,0,0,0,0,0,0,0,0,110,100,90,84,78,71,65,58,51,45,39,32,26,20,12,0,0,0,0,0,0,118,110,103,93,86,80,75,70,65,59,53,47,40,31,23,15,4,0,0,0,0,126, + 119,112,104,95,89,83,78,72,66,60,54,47,39,32,25,17,12,1,0,0,134,127,120,114,103,97,91,85,78,72,66,60,54,47,41,35,29,23,16,10,1,144,137,130,124,113,107,101,95,88,82,76,70,64,57,51,45,39,33,26,15,1,152,145,138,132,123,117,111,105,98,92,86,80,74,67,61,55,49,43,36,20,1,162,155,148,142,133,127,121,115,108,102,96,90,84,77,71,65,59,53,46,30,1,172,165,158,152,143,137,131,125,118,112,106,100,94,87,81,75,69,63,56,45,20,200,200,200,200,200,200,200,200,198,193,188,183,178,173,168,163,158,153,148,129,104,40,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,40,15,23,28,31,34,36,38,39,41,42,43,44,45,46,47,47,49,50,51,52,53,54,55,55,57,58,59,60,61,62,63,63,65,66,67,68,69,70,71,71,40,20,33,41,48,53,57,61,64,66,69,71,73,75,76,78,80,82,85,87,89,91,92,94,96,98,101,103,105,107,108,110,112,114,117,119,121,123,124,126,128,40,23,39,51,60,67,73,79,83,87,91,94,97,100,102,105,107,111,115,118,121,124,126,129,131,135,139,142,145,148,150,153,155,159,163,166,169,172,174,177,179,35,28,49,65, + 78,89,99,107,114,120,126,132,136,141,145,149,153,159,165,171,176,180,185,189,192,199,205,211,216,220,225,229,232,239,245,251,21,33,58,79,97,112,125,137,148,157,166,174,182,189,195,201,207,217,227,235,243,251,17,35,63,86,106,123,139,152,165,177,187,197,206,214,222,230,237,250,25,31,55,75,91,105,117,128,138,146,154,161,168,174,180,185,190,200,208,215,222,229,235,240,245,255,16,36,65,89,110,128,144,159,173,185,196,207,217,226,234,242,250,11,41,74,103,128,151,172,191,209,225,241,255,9,43,79,110,138,163, + 186,207,227,246,12,39,71,99,123,144,164,182,198,214,228,241,253,9,44,81,113,142,168,192,214,235,255,7,49,90,127,160,191,220,247,6,51,95,134,170,203,234,7,47,87,123,155,184,212,237,6,52,97,137,174,208,240,5,57,106,151,192,231,5,59,111,158,202,243,5,55,103,147,187,224,5,60,113,161,206,248,4,65,122,175,224,4,67,127,182,234,224,224,224,224,224,224,224,224,160,160,160,160,185,185,185,178,178,168,134,61,37,224,224,224,224,224,224,224,224,240,240,240,240,207,207,207,198,198,183,144,66,40,160,160,160,160, + 160,160,160,160,185,185,185,185,193,193,193,183,183,172,138,64,38,240,240,240,240,240,240,240,240,207,207,207,207,204,204,204,193,193,180,143,66,40,185,185,185,185,185,185,185,185,193,193,193,193,193,193,193,183,183,172,138,65,39,207,207,207,207,207,207,207,207,204,204,204,204,201,201,201,188,188,176,141,66,40,193,193,193,193,193,193,193,193,193,193,193,193,194,194,194,184,184,173,139,65,39,204,204,204,204,204,204,204,204,201,201,201,201,198,198,198,187,187,175,140,66,40,72,127,65,129,66,128,65,128, + 64,128,62,128,64,128,64,128,92,78,92,79,92,78,90,79,116,41,115,40,114,40,132,26,132,26,145,17,161,12,176,10,177,11,24,179,48,138,54,135,54,132,53,134,56,133,55,132,55,132,61,114,70,96,74,88,75,88,87,74,89,66,91,67,100,59,108,50,120,40,122,37,97,43,78,50,83,78,84,81,88,75,86,74,87,71,90,73,93,74,93,74,109,40,114,36,117,34,117,34,143,17,145,18,146,19,162,12,165,10,178,7,189,6,190,8,177,9,23,178,54,115,63,102,66,98,69,99,74,89,71,91,73,91,78,89,86,80,92,66,93,64,102,59,103,60,104,60,117,52,123,44,138, + 35,133,31,97,38,77,45,61,90,93,60,105,42,107,41,110,45,116,38,113,38,112,38,124,26,132,27,136,19,140,20,155,14,159,16,158,18,170,13,177,10,187,8,192,6,175,9,159,10,21,178,59,110,71,86,75,85,84,83,91,66,88,73,87,72,92,75,98,72,105,58,107,54,115,52,114,55,112,56,129,51,132,40,150,33,140,29,98,35,77,42,42,121,96,66,108,43,111,40,117,44,123,32,120,36,119,33,127,33,134,34,139,21,147,23,152,20,158,25,154,26,166,21,173,16,184,13,184,10,150,13,139,15,22,178,63,114,74,82,84,83,92,82,103,62,96,72,96,67,101, + 73,107,72,113,55,118,52,125,52,118,52,117,55,135,49,137,39,157,32,145,29,97,33,77,40,2,1,0,0,8,13,16,19,21,23,24,26,27,28,29,30,31,32,32,33,34,34,35,36,36,37,37,224,112,44,15,3,2,1,0,254,237,192,132,70,23,4,0,255,252,226,155,61,11,2,0,250,245,234,203,71,50,42,38,35,33,31,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,179,99,0,71,56,43,30,21,12,6,0,199,165,144,124,109,96,84,71,61,51,42,32,23,15,8,0,241,225,211,199,187,175,164,153,142,132,123,114,105,96,88,80,72,64, + 57,50,44,38,33,29,24,20,16,12,9,5,2,0,15,131,138,138,155,155,173,173,69,93,115,118,131,138,141,138,150,150,155,150,155,160,166,160,131,128,134,141,141,141,145,145,145,150,155,155,155,155,160,160,160,160,166,166,173,173,182,192,182,192,192,192,205,192,205,224,4,6,24,7,5,0,0,2,0,0,12,28,41,13,252,247,15,42,25,14,1,254,62,41,247,246,37,65,252,3,250,4,66,7,248,16,14,38,253,33,13,22,39,23,12,255,36,64,27,250,249,10,55,43,17,1,1,8,1,1,6,245,74,53,247,244,55,76,244,8,253,3,93,27,252,26,39,59,3,248,2,0,77, + 11,9,248,22,44,250,7,40,9,26,3,9,249,20,101,249,4,3,248,42,26,0,241,33,68,2,23,254,55,46,254,15,3,255,21,16,41,250,27,61,39,5,245,42,88,4,1,254,60,65,6,252,255,251,73,56,1,247,19,94,29,247,0,12,99,6,4,8,237,102,46,243,3,2,13,3,2,9,235,84,72,238,245,46,104,234,8,18,38,48,23,0,240,70,83,235,11,5,245,117,22,248,250,23,117,244,3,3,248,95,28,4,246,15,77,60,241,255,4,124,2,252,3,38,84,24,231,2,13,42,13,31,21,252,56,46,255,255,35,79,243,19,249,65,88,247,242,20,4,81,49,227,20,0,75,3,239,5,247,44,92,248,1, + 253,22,69,31,250,95,41,244,5,39,67,16,252,1,0,250,120,55,220,243,44,122,4,232,81,5,11,3,7,2,0,9,10,88,46,2,90,87,93,91,82,98,109,120,118,12,113,115,117,119,99,59,87,111,63,111,112,80,126,124,125,124,129,121,126,23,132,127,127,127,126,127,122,133,130,134,101,118,119,145,126,86,124,120,123,119,170,173,107,109,8,16,32,12,35,60,83,108,132,157,180,206,228,15,32,55,77,101,125,151,175,201,225,19,42,66,89,114,137,162,184,209,230,12,25,50,72,97,120,147,172,200,223,26,44,69,90,114,135,159,180,205,225,13,22, + 53,80,106,130,156,180,205,228,15,25,44,64,90,115,142,168,196,222,19,24,62,82,100,120,145,168,190,214,22,31,50,79,103,120,151,170,203,227,21,29,45,65,106,124,150,171,196,224,30,49,75,97,121,142,165,186,209,229,19,25,52,70,93,116,143,166,192,219,26,34,62,75,97,118,145,167,194,217,25,33,56,70,91,113,143,165,196,223,21,34,51,72,97,117,145,171,196,222,20,29,50,67,90,117,144,168,197,221,22,31,48,66,95,117,146,168,196,222,24,33,51,77,116,134,158,180,200,224,21,28,70,87,106,124,149,170,194,217,26,33,53,64, + 83,117,152,173,204,225,27,34,65,95,108,129,155,174,210,225,20,26,72,99,113,131,154,176,200,219,34,43,61,78,93,114,155,177,205,229,23,29,54,97,124,138,163,179,209,229,30,38,56,89,118,129,158,178,200,231,21,29,49,63,85,111,142,163,193,222,27,48,77,103,133,158,179,196,215,232,29,47,74,99,124,151,176,198,220,237,33,42,61,76,93,121,155,174,207,225,29,53,87,112,136,154,170,188,208,227,24,30,52,84,131,150,166,186,203,229,37,48,64,84,104,118,156,177,201,230,212,178,148,129,108,96,85,82,79,77,61,59,57,56, + 51,49,48,45,42,41,40,38,36,34,31,30,21,12,10,3,1,0,255,245,244,236,233,225,217,203,190,176,175,161,149,136,125,114,102,91,81,71,60,52,43,35,28,20,19,18,12,11,5,0,179,138,140,148,151,149,153,151,163,116,67,82,59,92,72,100,89,92,16,0,0,0,0,99,66,36,36,34,36,34,34,34,34,83,69,36,52,34,116,102,70,68,68,176,102,68,68,34,65,85,68,84,36,116,141,152,139,170,132,187,184,216,137,132,249,168,185,139,104,102,100,68,68,178,218,185,185,170,244,216,187,187,170,244,187,187,219,138,103,155,184,185,137,116,183,155, + 152,136,132,217,184,184,170,164,217,171,155,139,244,169,184,185,170,164,216,223,218,138,214,143,188,218,168,244,141,136,155,170,168,138,220,219,139,164,219,202,216,137,168,186,246,185,139,116,185,219,185,138,100,100,134,100,102,34,68,68,100,68,168,203,221,218,168,167,154,136,104,70,164,246,171,137,139,137,155,218,219,139,255,254,253,238,14,3,2,1,0,255,254,252,218,35,3,2,1,0,255,254,250,208,59,4,2,1,0,255,254,246,194,71,10,2,1,0,255,252,236,183,82,8,2,1,0,255,252,235,180,90,17,2,1,0,255,248,224,171, + 97,30,4,1,0,255,254,236,173,95,37,7,1,0,255,255,255,131,6,145,255,255,255,255,255,236,93,15,96,255,255,255,255,255,194,83,25,71,221,255,255,255,255,162,73,34,66,162,255,255,255,210,126,73,43,57,173,255,255,255,201,125,71,48,58,130,255,255,255,166,110,73,57,62,104,210,255,255,251,123,65,55,68,100,171,255,7,23,38,54,69,85,100,116,131,147,162,178,193,208,223,239,13,25,41,55,69,83,98,112,127,142,157,171,187,203,220,236,15,21,34,51,61,78,92,106,126,136,152,167,185,205,225,240,10,21,36,50,63,79,95,110, + 126,141,157,173,189,205,221,237,17,20,37,51,59,78,89,107,123,134,150,164,184,205,224,240,10,15,32,51,67,81,96,112,129,142,158,173,189,204,220,236,8,21,37,51,65,79,98,113,126,138,155,168,179,192,209,218,12,15,34,55,63,78,87,108,118,131,148,167,185,203,219,236,16,19,32,36,56,79,91,108,118,136,154,171,186,204,220,237,11,28,43,58,74,89,105,120,135,150,165,180,196,211,226,241,6,16,33,46,60,75,92,107,123,137,156,169,185,199,214,225,11,19,30,44,57,74,89,105,121,135,152,169,186,202,218,234,12,19,29,46,57, + 71,88,100,120,132,148,165,182,199,216,233,17,23,35,46,56,77,92,106,123,134,152,167,185,204,222,237,14,17,45,53,63,75,89,107,115,132,151,171,188,206,221,240,9,16,29,40,56,71,88,103,119,137,154,171,189,205,222,237,16,19,36,48,57,76,87,105,118,132,150,167,185,202,218,236,12,17,29,54,71,81,94,104,126,136,149,164,182,201,221,237,15,28,47,62,79,97,115,129,142,155,168,180,194,208,223,238,8,14,30,45,62,78,94,111,127,143,159,175,192,207,223,239,17,30,49,62,79,92,107,119,132,145,160,174,190,204,220,235,14, + 19,36,45,61,76,91,108,121,138,154,172,189,205,222,238,12,18,31,45,60,76,91,107,123,138,154,171,187,204,221,236,13,17,31,43,53,70,83,103,114,131,149,167,185,203,220,237,17,22,35,42,58,78,93,110,125,139,155,170,188,206,224,240,8,15,34,50,67,83,99,115,131,146,162,178,193,209,224,239,13,16,41,66,73,86,95,111,128,137,150,163,183,206,225,241,17,25,37,52,63,75,92,102,119,132,144,160,175,191,212,231,19,31,49,65,83,100,117,133,147,161,174,187,200,213,227,242,18,31,52,68,88,103,117,126,138,149,163,177,192, + 207,223,239,16,29,47,61,76,90,106,119,133,147,161,176,193,209,224,240,15,21,35,50,61,73,86,97,110,119,129,141,175,198,218,237,225,204,201,184,183,175,158,154,153,135,119,115,113,110,109,99,98,95,79,68,52,50,48,45,43,32,31,27,18,10,3,0,255,251,235,230,212,201,196,182,167,166,163,151,138,124,110,104,90,78,76,70,69,57,45,34,24,21,11,6,5,4,3,0,175,148,160,176,178,173,174,164,177,174,196,182,198,192,182,68,62,66,60,72,117,85,90,118,136,151,142,160,142,155,0,0,0,0,0,0,0,1,100,102,102,68,68,36,34,96,164, + 107,158,185,180,185,139,102,64,66,36,34,34,0,1,32,208,139,141,191,152,185,155,104,96,171,104,166,102,102,102,132,1,0,0,0,0,16,16,0,80,109,78,107,185,139,103,101,208,212,141,139,173,153,123,103,36,0,0,0,0,0,0,1,48,0,0,0,0,0,0,32,68,135,123,119,119,103,69,98,68,103,120,118,118,102,71,98,134,136,157,184,182,153,139,134,208,168,248,75,189,143,121,107,32,49,34,34,34,0,17,2,210,235,139,123,185,137,105,134,98,135,104,182,100,183,171,134,100,70,68,70,66,66,34,131,64,166,102,68,36,2,1,0,134,166,102,68,34, + 34,66,132,212,246,158,139,107,107,87,102,100,219,125,122,137,118,103,132,114,135,137,105,171,106,50,34,164,214,141,143,185,151,121,103,192,34,0,0,0,0,0,1,208,109,74,187,134,249,159,137,102,110,154,118,87,101,119,101,0,2,0,36,36,66,68,35,96,164,102,100,36,0,2,33,167,138,174,102,100,84,2,2,100,107,120,119,36,197,24,0,255,254,253,244,12,3,2,1,0,255,254,252,224,38,3,2,1,0,255,254,251,209,57,4,2,1,0,255,254,244,195,69,4,2,1,0,255,251,232,184,84,7,2,1,0,255,254,240,186,86,14,2,1,0,255,254,239,178,91,30, + 5,1,0,255,248,227,177,100,19,2,1,0,255,255,255,156,4,154,255,255,255,255,255,227,102,15,92,255,255,255,255,255,213,83,24,72,236,255,255,255,255,150,76,33,63,214,255,255,255,190,121,77,43,55,185,255,255,255,245,137,71,43,59,139,255,255,255,255,131,66,50,66,107,194,255,255,166,116,76,55,53,125,255,255,249,247,246,245,244,234,210,202,201,200,197,174,82,59,56,55,54,46,22,12,11,10,9,7,0,64,0,203,150,0,215,195,166,125,110,82,0,120,0,128,64,0,232,158,10,0,230,0,243,221,192,181,0,171,85,0,192,128,64,0,205, + 154,102,51,0,213,171,128,85,43,0,224,192,160,128,96,64,32,0,100,40,16,7,3,1,0,253,250,244,233,212,182,150,131,120,110,98,85,72,60,49,40,32,25,19,15,13,11,9,8,7,6,5,4,3,2,1,0,210,208,206,203,199,193,183,168,142,104,74,52,37,27,20,14,10,6,4,2,0,223,201,183,167,152,138,124,111,98,88,79,70,62,56,50,44,39,35,31,27,24,21,18,16,14,12,10,8,6,4,3,2,1,0,188,176,155,138,119,97,67,43,26,10,0,165,119,80,61,47,35,27,20,14,9,4,0,113,63,0,8,10,12,16,125,51,26,18,15,12,11,10,9,8,7,6,5,4,3,2,1,0,198,105,45,22,15,12, + 11,10,9,8,7,6,5,4,3,2,1,0,213,162,116,83,59,43,32,24,18,15,12,9,7,6,5,3,2,0,239,187,116,59,28,16,11,10,9,8,7,6,5,4,3,2,1,0,250,229,188,135,86,51,30,19,13,10,8,6,5,4,3,2,1,0,249,235,213,185,156,128,103,83,66,53,42,33,26,21,17,13,10,0,254,249,235,206,164,118,77,46,27,16,10,7,5,4,3,2,1,0,255,253,249,239,220,191,156,119,85,57,37,23,15,10,6,4,2,0,255,253,251,246,237,223,203,179,152,124,98,75,55,40,29,21,15,0,255,254,253,247,220,162,106,67,42,28,18,12,9,6,4,3,2,0,31,57,107,160,205,205,255,255,255,255,255, + 255,255,255,255,255,255,255,69,47,67,111,166,205,255,255,255,255,255,255,255,255,255,255,255,255,82,74,79,95,109,128,145,160,173,205,205,205,224,255,255,224,255,224,125,74,59,69,97,141,182,255,255,255,255,255,255,255,255,255,255,255,173,115,85,73,76,92,115,145,173,205,224,224,255,255,255,255,255,255,166,134,113,102,101,102,107,118,125,138,145,155,166,182,192,192,205,150,224,182,134,101,83,79,85,97,120,145,173,205,224,255,255,255,255,255,255,224,192,150,120,101,92,89,93,102,118,134,160,182,192,224, + 224,224,255,224,224,182,155,134,118,109,104,102,106,111,118,131,145,160,173,131,241,190,178,132,87,74,41,14,0,223,193,157,140,106,57,39,18,0,131,74,141,79,80,138,95,104,134,95,99,91,125,93,76,123,115,123,128,0,214,42,0,235,128,21,0,244,184,72,11,0,248,214,128,42,7,0,248,225,170,80,25,5,0,251,236,198,126,54,18,3,0,250,238,211,159,82,35,15,5,0,250,231,203,168,128,88,53,25,6,0,252,238,216,185,148,108,71,40,18,4,0,253,243,225,199,166,128,90,57,31,13,3,0,254,246,233,212,183,147,109,73,44,23,10,2,0,255, + 250,240,223,198,166,128,90,58,33,16,6,1,0,255,251,244,231,210,181,146,110,75,46,25,12,5,1,0,255,253,248,238,221,196,164,128,92,60,35,18,8,3,1,0,255,253,249,242,229,208,180,146,110,76,48,27,14,7,3,1,0,129,0,207,50,0,236,129,20,0,245,185,72,10,0,249,213,129,42,6,0,250,226,169,87,27,4,0,251,233,194,130,62,20,4,0,250,236,207,160,99,47,17,3,0,255,240,217,182,131,81,41,11,1,0,255,254,233,201,159,107,61,20,2,1,0,255,249,233,206,170,128,86,50,23,7,1,0,255,250,238,217,186,148,108,70,39,18,6,1,0,255,252,243, + 226,200,166,128,90,56,30,13,4,1,0,255,252,245,231,209,180,146,110,76,47,25,11,4,1,0,255,253,248,237,219,194,163,128,93,62,37,19,8,3,1,0,255,254,250,241,226,205,177,145,111,79,51,30,15,6,2,1,0,129,0,203,54,0,234,129,23,0,245,184,73,10,0,250,215,129,41,5,0,252,232,173,86,24,3,0,253,240,200,129,56,15,2,0,253,244,217,164,94,38,10,1,0,253,245,226,189,132,71,27,7,1,0,253,246,231,203,159,105,56,23,6,1,0,255,248,235,213,179,133,85,47,19,5,1,0,255,254,243,221,194,159,117,70,37,12,2,1,0,255,254,248,234,208, + 171,128,85,48,22,8,2,1,0,255,254,250,240,220,189,149,107,67,36,16,6,2,1,0,255,254,251,243,227,201,166,128,90,55,29,13,5,2,1,0,255,254,252,246,234,213,183,147,109,73,43,22,10,4,2,1,0,130,0,200,58,0,231,130,26,0,244,184,76,12,0,249,214,130,43,6,0,252,232,173,87,24,3,0,253,241,203,131,56,14,2,0,254,246,221,167,94,35,8,1,0,254,249,232,193,130,65,23,5,1,0,255,251,239,211,162,99,45,15,4,1,0,255,251,243,223,186,131,74,33,11,3,1,0,255,252,245,230,202,158,105,57,24,8,2,1,0,255,253,247,235,214,179,132,84,44, + 19,7,2,1,0,255,254,250,240,223,196,159,112,69,36,15,6,2,1,0,255,254,253,245,231,209,176,136,93,55,27,11,3,2,1,0,255,254,253,252,239,221,194,158,117,76,42,18,4,3,2,1,0,0,0,2,5,9,14,20,27,35,44,54,65,77,90,104,119,135,254,49,67,77,82,93,99,198,11,18,24,31,36,45,255,46,66,78,87,94,104,208,14,21,32,42,51,66,255,94,104,109,112,115,118,248,53,69,80,88,95,102,0,15,8,7,4,11,12,3,2,13,10,5,6,9,14,1,0,9,6,3,4,5,8,1,2,7,0,1,0,0,0,1,0,0,1,255,1,255,2,254,2,254,3,253,0,1,0,1,255,2,255,2,254,3,254,3,253,7,254, + 7,0,2,255,255,255,0,0,1,1,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,255,2,1,0,1,1,0,0,255,255,0,0,1,255,0,1,255,0,255,1,254,2,254,254,2,253,2,3,253,252,3,252,4,4,251,5,250,251,6,249,6,5,8,247,0,0,1,0,0,0,0,0,0,0,255,1,0,0,1,255,0,1,255,255,1,255,2,1,255,2,254,254,2,254,2,2,3,253,0,1,0,0,0,0,0,0,1,0,1,0,0,1,255,1,0,0,2,1,255,2,255,255,2,255,2,2,255,3,254,254,254,3,0,1,0,0,1,0,1,255,2,255,2,255,2,3,254,3,254,254,4,4,253,5,253,252,6,252,6,5,251,8,250,251,249,9,251,8,255,6,255,6,252,10,250,10, + 254,6,255,6,251,10,247,12,253,7,254,7,249,13,16,24,34,6,0,3,0,7,3,0,1,10,0,2,6,18,10,12,4,0,2,0,0,0,9,4,7,4,0,3,12,7,7,255,255],"i8",4,y.h+20480);var Na=z,z=z+16;function Oa(a){b.___errno_location&&(M[b.___errno_location()>>2]=a);return a}b._i64Add=Pa;b._bitshift64Ashr=Qa;b._memset=Ra;b._memcpy=Sa;var Ta=ha;function S(a){S.a||(E=wa(),S.a=!0,assert(y.b),S.u=y.b,y.b=function(){G("cannot dynamically allocate, sbrk now has control")});var c=E;return 0==a||S.u(a)?c:4294967295} + function Y(){Y.a||(Y.a=[]);Y.a.push(y.g());return Y.a.length-1}b._memmove=Ua; + var Aa=x=y.p(z),na=!0,Ba=Aa+Ca,E=y.p(Ba),Va=O([8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1, + 0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0],"i8",3);b.s={Math:Math,Int8Array:Int8Array,Int16Array:Int16Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Uint16Array:Uint16Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array,NaN:NaN,Infinity:Infinity}; + b.t={abort:G,assert:assert,invoke_viiiiiii:function(a,c,d,e,g,k,h,A){try{b.dynCall_viiiiiii(a,c,d,e,g,k,h,A)}catch(m){if("number"!==typeof m&&"longjmp"!==m)throw m;Z.setThrew(1,0)}},_llvm_pow_f64:La,_pthread_self:function(){return 0},_abort:function(){b.abort()},___setErrNo:Oa,_llvm_stacksave:Y,_sbrk:S,_time:function(a){var c=Date.now()/1E3|0;a&&(M[a>>2]=c);return c},_llvm_fabs_f64:Ta,_emscripten_memcpy_big:function(a,c,d){R.set(R.subarray(c,c+d),a);return a},_llvm_stackrestore:function(a){var c= + Y.a[a];Y.a.splice(a,1);y.c(c)},_sysconf:function(a){switch(a){case 30:return 4096;case 85:return U/4096;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 79:return 0;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:return-1; + case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1E3;case 89:return 700;case 71:return 256; + case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return"object"===typeof navigator?navigator.hardwareConcurrency||1:1}Oa(22);return-1},STACKTOP:x,STACK_MAX:Ba,tempDoublePtr:Na,ABORT:H,cttz_i8:Va};// EMSCRIPTEN_START_ASM + var Z=(function(global,env,buffer) { + "use asm";var a=new global.Int8Array(buffer);var b=new global.Int16Array(buffer);var c=new global.Int32Array(buffer);var d=new global.Uint8Array(buffer);var e=new global.Uint16Array(buffer);var f=new global.Uint32Array(buffer);var g=new global.Float32Array(buffer);var h=new global.Float64Array(buffer);var i=env.STACKTOP|0;var j=env.STACK_MAX|0;var k=env.tempDoublePtr|0;var l=env.ABORT|0;var m=env.cttz_i8|0;var n=0;var o=0;var p=0;var q=0;var r=global.NaN,s=global.Infinity;var t=0,u=0,v=0,w=0,x=0.0,y=0,z=0,A=0,B=0.0;var C=0;var D=0;var E=0;var F=0;var G=0;var H=0;var I=0;var J=0;var K=0;var L=0;var M=global.Math.floor;var N=global.Math.abs;var O=global.Math.sqrt;var P=global.Math.pow;var Q=global.Math.cos;var R=global.Math.sin;var S=global.Math.tan;var T=global.Math.acos;var U=global.Math.asin;var V=global.Math.atan;var W=global.Math.atan2;var X=global.Math.exp;var Y=global.Math.log;var Z=global.Math.ceil;var _=global.Math.imul;var $=global.Math.min;var aa=global.Math.clz32;var ba=env.abort;var ca=env.assert;var da=env.invoke_viiiiiii;var ea=env._llvm_pow_f64;var fa=env._pthread_self;var ga=env._abort;var ha=env.___setErrNo;var ia=env._llvm_stacksave;var ja=env._sbrk;var ka=env._time;var la=env._llvm_fabs_f64;var ma=env._emscripten_memcpy_big;var na=env._llvm_stackrestore;var oa=env._sysconf;var pa=0.0; + // EMSCRIPTEN_START_FUNCS + function Lb(a,d,e,f,h,j,k){a=a|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;var l=0,m=0.0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ja=0,ka=0,la=0,ma=0,oa=0,pa=0,qa=0,ra=0,sa=0,ta=0,ua=0;ta=i;i=i+304|0;X=ta+288|0;Y=ta+284|0;l=ta+280|0;Z=ta+276|0;$=ta+272|0;aa=ta+268|0;ba=ta+264|0;ca=ta+260|0;ha=ta+256|0;ka=ta+252|0;ga=ta+248|0;M=ta+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536|0;W=ka+4532|0;ja=ka+4528|0;$=ka+4524|0;ga=ka+4520|0;h=ka+4516|0;S=ka+4512|0;Z=ka+4508|0;U=ka+4504|0;T=ka+4500|0;R=ka+4496|0;M=ka+4492|0;V=ka+4488|0;Q=ka+4484|0;P=ka+4480|0;K=ka+4476|0;A=ka+4472|0;F=ka+4468|0;l=ka+4464|0;w=ka+368|0;t=ka+360|0;r=ka+356|0;o=ka+352|0;s=ka+348|0;z=ka+344|0;y=ka+340|0;x=ka+336|0;B=ka+332|0;q=ka+232|0;D=ka+136|0;m=ka+128|0;n=ka+124|0;u=ka+120|0;v=ka+116|0;H=ka+112|0;E=ka+16|0;p=ka+12|0;I=ka+8|0;G=ka+4|0;J=ka;c[aa>>2]=a;c[ba>>2]=d;c[L>>2]=e;c[ca>>2]=c[(c[aa>>2]|0)+8>>2];c[ha>>2]=c[c[aa>>2]>>2];c[W>>2]=c[(c[ha>>2]|0)+8>>2];c[ja>>2]=c[(c[ha>>2]|0)+4>>2];c[S>>2]=c[(c[ha>>2]|0)+32>>2];c[da>>2]=0;do{a=(c[aa>>2]|0)+84+((_(c[da>>2]|0,2048+(c[ja>>2]|0)|0)|0)<<2)|0;c[ea+(c[da>>2]<<2)>>2]=a;c[Y+(c[da>>2]<<2)>>2]=(c[ea+(c[da>>2]<<2)>>2]|0)+8192+(0-(c[ba>>2]|0)<<2);a=(c[da>>2]|0)+1|0;c[da>>2]=a}while((a|0)<(c[ca>>2]|0));c[C>>2]=(c[aa>>2]|0)+84+((_(2048+(c[ja>>2]|0)|0,c[ca>>2]|0)|0)<<2);c[X>>2]=(c[C>>2]|0)+((c[ca>>2]|0)*24<<2);c[j>>2]=(c[X>>2]|0)+(c[W>>2]<<1<<2);c[k>>2]=(c[j>>2]|0)+(c[W>>2]<<1<<2);c[N>>2]=(c[k>>2]|0)+(c[W>>2]<<1<<2);c[ga>>2]=c[(c[aa>>2]|0)+48>>2];c[$>>2]=c[(c[aa>>2]|0)+20>>2];c[h>>2]=((c[ga>>2]|0)>=5?1:(c[$>>2]|0)!=0)&1;if(c[h>>2]|0){c[U>>2]=c[(c[aa>>2]|0)+24>>2];if((c[U>>2]|0)<(c[(c[ha>>2]|0)+12>>2]|0))e=c[U>>2]|0;else e=c[(c[ha>>2]|0)+12>>2]|0;do if((c[$>>2]|0)<=(e|0))if((c[U>>2]|0)<(c[(c[ha>>2]|0)+12>>2]|0)){e=c[U>>2]|0;break}else{e=c[(c[ha>>2]|0)+12>>2]|0;break}else e=c[$>>2]|0;while(0);c[T>>2]=e;K=_(c[ca>>2]|0,c[ba>>2]|0)|0;c[M>>2]=ia()|0;d=i;i=i+((1*(K<<2)|0)+15&-16)|0;g[R>>2]=(c[ga>>2]|0)==0?1.5:.5;c[da>>2]=0;do{c[fa>>2]=c[$>>2];while(1){e=c[da>>2]|0;if((c[fa>>2]|0)>=(c[U>>2]|0))break;J=_(e,c[W>>2]|0)|0;K=_(c[da>>2]|0,c[W>>2]|0)|0;e=_(c[da>>2]|0,c[W>>2]|0)|0;e=e+(c[fa>>2]|0)|0;if(+g[(c[N>>2]|0)+(J+(c[fa>>2]|0)<<2)>>2]>+g[(c[X>>2]|0)+(K+(c[fa>>2]|0)<<2)>>2]-+g[R>>2])f=+g[(c[N>>2]|0)+(e<<2)>>2];else f=+g[(c[X>>2]|0)+(e<<2)>>2]-+g[R>>2];K=_(c[da>>2]|0,c[W>>2]|0)|0;g[(c[X>>2]|0)+(K+(c[fa>>2]|0)<<2)>>2]=f;c[fa>>2]=(c[fa>>2]|0)+1}K=e+1|0;c[da>>2]=K}while((K|0)<(c[ca>>2]|0));c[Z>>2]=c[(c[aa>>2]|0)+36>>2];c[da>>2]=0;while(1){if((c[da>>2]|0)>=(c[ca>>2]|0))break;c[fa>>2]=c[$>>2];while(1){if((c[fa>>2]|0)>=(c[T>>2]|0))break;W=_(c[ba>>2]|0,c[da>>2]|0)|0;c[Q>>2]=W+(b[(c[S>>2]|0)+(c[fa>>2]<<1)>>1]<>2]);c[P>>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2)>>2];c[fa>>2]=0;while(1){if((c[fa>>2]|0)>=1024)break;g[w+(c[fa>>2]<<2)>>2]=+g[(c[s>>2]|0)+(1024+(c[fa>>2]|0)<<2)>>2];c[fa>>2]=(c[fa>>2]|0)+1}if(!(c[ga>>2]|0)){Yc(w,q,c[K>>2]|0,c[ja>>2]|0,24,1024,c[(c[aa>>2]|0)+32>>2]|0)|0;g[q>>2]=+g[q>>2]*1.000100016593933;c[fa>>2]=1;while(1){if((c[fa>>2]|0)>24)break;ha=q+(c[fa>>2]<<2)|0;g[ha>>2]=+g[ha>>2]-+g[q+(c[fa>>2]<<2)>>2]*6.400000711437315e-05*+(c[fa>>2]|0)*+(c[fa>>2]|0);c[fa>>2]=(c[fa>>2]|0)+1}Uc((c[C>>2]|0)+((c[da>>2]|0)*24<<2)|0,q,24)}c[x>>2]=(c[F>>2]<<1|0)<1024?c[F>>2]<<1:1024;c[fa>>2]=0;while(1){if((c[fa>>2]|0)>=24)break;g[D+(c[fa>>2]<<2)>>2]=+g[(c[s>>2]|0)+(2048-(c[x>>2]|0)-1-(c[fa>>2]|0)<<2)>>2];c[fa>>2]=(c[fa>>2]|0)+1}Vc(w+4096+(0-(c[x>>2]|0)<<2)|0,(c[C>>2]|0)+((c[da>>2]|0)*24<<2)|0,w+4096+(0-(c[x>>2]|0)<<2)|0,c[x>>2]|0,24,D,c[(c[aa>>2]|0)+32>>2]|0);g[m>>2]=1.0;g[n>>2]=1.0;c[u>>2]=c[x>>2]>>1;c[fa>>2]=0;while(1){if((c[fa>>2]|0)>=(c[u>>2]|0))break;g[v>>2]=+g[w+(1024-(c[u>>2]|0)+(c[fa>>2]|0)<<2)>>2];g[m>>2]=+g[m>>2]+ +g[v>>2]*+g[v>>2];g[v>>2]=+g[w+(1024-(c[u>>2]<<1)+(c[fa>>2]|0)<<2)>>2];g[n>>2]=+g[n>>2]+ +g[v>>2]*+g[v>>2];c[fa>>2]=(c[fa>>2]|0)+1}g[m>>2]=+g[m>>2]<+g[n>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=(c[fa>>2]|0)+1}a:do if(+g[o>>2]>+g[p>>2]*.20000000298023224){if(+g[o>>2]<+g[p>>2]){g[G>>2]=+O(+((+g[o>>2]+1.0)/(+g[p>>2]+1.0)));c[fa>>2]=0;while(1){if((c[fa>>2]|0)>=(c[ja>>2]|0))break;g[J>>2]=1.0-+g[(c[K>>2]|0)+(c[fa>>2]<<2)>>2]*(1.0-+g[G>>2]);g[(c[s>>2]|0)+(2048-(c[ba>>2]|0)+(c[fa>>2]|0)<<2)>>2]=+g[J>>2]*+g[(c[s>>2]|0)+(2048-(c[ba>>2]|0)+(c[fa>>2]|0)<<2)>>2];c[fa>>2]=(c[fa>>2]|0)+1}c[fa>>2]=c[ja>>2];while(1){if((c[fa>>2]|0)>=(c[y>>2]|0))break a;g[(c[s>>2]|0)+(2048-(c[ba>>2]|0)+(c[fa>>2]|0)<<2)>>2]=+g[G>>2]*+g[(c[s>>2]|0)+(2048-(c[ba>>2]|0)+(c[fa>>2]|0)<<2)>>2];c[fa>>2]=(c[fa>>2]|0)+1}}}else{c[fa>>2]=0;while(1){if((c[fa>>2]|0)>=(c[y>>2]|0))break a;g[(c[s>>2]|0)+(2048-(c[ba>>2]|0)+(c[fa>>2]|0)<<2)>>2]=0.0;c[fa>>2]=(c[fa>>2]|0)+1}}while(0);cb(e,(c[s>>2]|0)+8192|0,c[(c[aa>>2]|0)+52>>2]|0,c[(c[aa>>2]|0)+52>>2]|0,c[ja>>2]|0,-+g[(c[aa>>2]|0)+60>>2],-+g[(c[aa>>2]|0)+60>>2],c[(c[aa>>2]|0)+68>>2]|0,c[(c[aa>>2]|0)+68>>2]|0,0,0,c[(c[aa>>2]|0)+32>>2]|0);c[fa>>2]=0;while(1){if((c[fa>>2]|0)>=((c[ja>>2]|0)/2|0|0))break;g[(c[s>>2]|0)+(2048+(c[fa>>2]|0)<<2)>>2]=+g[(c[K>>2]|0)+(c[fa>>2]<<2)>>2]*+g[e+((c[ja>>2]|0)-1-(c[fa>>2]|0)<<2)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+g[(c[A>>2]|0)+(c[w>>2]<<2)>>2]+ +g[x>>2]+1.0000000031710769e-30;g[x>>2]=+g[v>>2]*+g[z>>2];D=_(c[w>>2]|0,c[o>>2]|0)|0;g[(c[B>>2]|0)+(D<<2)>>2]=+g[z>>2]*.000030517578125;c[w>>2]=(c[w>>2]|0)+1}while(0);g[(c[q>>2]|0)+(c[u>>2]<<2)>>2]=+g[x>>2];b:do if(c[t>>2]|0){c[w>>2]=0;while(1){if((c[w>>2]|0)>=(c[s>>2]|0))break b;E=+g[e+((_(c[w>>2]|0,c[p>>2]|0)|0)<<2)>>2]*.000030517578125;D=_(c[w>>2]|0,c[o>>2]|0)|0;g[(c[B>>2]|0)+(D<<2)>>2]=E;c[w>>2]=(c[w>>2]|0)+1}}while(0);D=(c[u>>2]|0)+1|0;c[u>>2]=D}while((D|0)<(c[o>>2]|0));na(c[r>>2]|0);i=C;return}function Qb(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;a=(c[(c[d>>2]|0)+20>>2]|0)-(32-(aa(c[(c[d>>2]|0)+28>>2]|0)|0))|0;i=b;return a|0}function Rb(b,d,e,f,g,h){b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0;x=i;i=i+64|0;j=x+52|0;k=x+48|0;l=x+44|0;m=x+40|0;n=x+36|0;o=x+32|0;r=x+28|0;q=x+24|0;v=x+20|0;w=x+16|0;u=x+12|0;s=x+8|0;p=x+4|0;t=x;c[j>>2]=b;c[k>>2]=d;c[l>>2]=e;c[m>>2]=f;c[n>>2]=g;c[o>>2]=h;c[p>>2]=c[(c[o>>2]|0)+4>>2]<<3;c[t>>2]=Qb(c[o>>2]|0)|0;c[s>>2]=c[l>>2]|0?2:4;if((c[n>>2]|0)>0)g=((c[t>>2]|0)+(c[s>>2]|0)+1|0)>>>0<=(c[p>>2]|0)>>>0;else g=0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zb(a){a=a|0;var b=0,e=0,f=0;e=i;i=i+16|0;b=e;c[b>>2]=a;if((c[(c[b>>2]|0)+24>>2]|0)>>>0>=(c[(c[b>>2]|0)+4>>2]|0)>>>0){a=0;i=e;return a|0}f=(c[b>>2]|0)+24|0;a=c[f>>2]|0;c[f>>2]=a+1;a=d[(c[c[b>>2]>>2]|0)+a>>0]|0;i=e;return a|0}function _b(a){a=a|0;var b=0,d=0,e=0;e=i;i=i+16|0;b=e+4|0;d=e;c[b>>2]=a;while(1){if((c[(c[b>>2]|0)+28>>2]|0)>>>0>8388608)break;a=(c[b>>2]|0)+20|0;c[a>>2]=(c[a>>2]|0)+8;a=(c[b>>2]|0)+28|0;c[a>>2]=c[a>>2]<<8;c[d>>2]=c[(c[b>>2]|0)+40>>2];a=Zb(c[b>>2]|0)|0;c[(c[b>>2]|0)+40>>2]=a;c[d>>2]=(c[d>>2]<<8|c[(c[b>>2]|0)+40>>2])>>1;c[(c[b>>2]|0)+32>>2]=(c[(c[b>>2]|0)+32>>2]<<8)+(255&~c[d>>2])&2147483647}i=e;return}function $b(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0;f=i;i=i+16|0;g=f+8|0;e=f+4|0;d=f;c[g>>2]=a;c[e>>2]=b;a=ac(c[(c[g>>2]|0)+28>>2]|0,c[e>>2]|0)|0;c[(c[g>>2]|0)+36>>2]=a;c[d>>2]=((c[(c[g>>2]|0)+32>>2]|0)>>>0)/((c[(c[g>>2]|0)+36>>2]|0)>>>0)|0;i=f;return (c[e>>2]|0)-((c[d>>2]|0)+1+((c[e>>2]|0)-((c[d>>2]|0)+1)&0-((c[e>>2]|0)>>>0<((c[d>>2]|0)+1|0)>>>0&1)))|0}function ac(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>>>0)/((c[d>>2]|0)>>>0)|0|0}function bc(a,b){a=a|0;b=b|0;var d=0,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>>2]|0)+1|0,c[f>>2]|0);c[d>>2]=c[j>>2];k=c[d>>2]|0;i=l;return k|0}c[h>>2]=(c[h>>2]|0)-8;c[g>>2]=((c[f>>2]|0)>>>(c[h>>2]|0))+1;c[j>>2]=$b(c[e>>2]|0,c[g>>2]|0)|0;cc(c[e>>2]|0,c[j>>2]|0,(c[j>>2]|0)+1|0,c[g>>2]|0);j=c[j>>2]<>2];c[k>>2]=j|(gc(c[e>>2]|0,c[h>>2]|0)|0);if((c[k>>2]|0)>>>0<=(c[f>>2]|0)>>>0){c[d>>2]=c[k>>2];k=c[d>>2]|0;i=l;return k|0}else{c[(c[e>>2]|0)+44>>2]=1;c[d>>2]=c[f>>2];k=c[d>>2]|0;i=l;return k|0}return 0}function gc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0;j=i;i=i+32|0;d=j+16|0;e=j+12|0;h=j+8|0;f=j+4|0;g=j;c[d>>2]=a;c[e>>2]=b;c[h>>2]=c[(c[d>>2]|0)+12>>2];c[f>>2]=c[(c[d>>2]|0)+16>>2];if((c[f>>2]|0)>>>0<(c[e>>2]|0)>>>0)do{a=hc(c[d>>2]|0)|0;c[h>>2]=c[h>>2]|a<>2];c[f>>2]=(c[f>>2]|0)+8}while((c[f>>2]|0)<=24);c[g>>2]=c[h>>2]&(1<>2])-1;c[h>>2]=(c[h>>2]|0)>>>(c[e>>2]|0);c[f>>2]=(c[f>>2]|0)-(c[e>>2]|0);c[(c[d>>2]|0)+12>>2]=c[h>>2];c[(c[d>>2]|0)+16>>2]=c[f>>2];h=(c[d>>2]|0)+20|0;c[h>>2]=(c[h>>2]|0)+(c[e>>2]|0);i=j;return c[g>>2]|0}function hc(a){a=a|0;var b=0,e=0,f=0,g=0;e=i;i=i+16|0;b=e;c[b>>2]=a;if((c[(c[b>>2]|0)+8>>2]|0)>>>0>=(c[(c[b>>2]|0)+4>>2]|0)>>>0){a=0;i=e;return a|0}f=c[(c[b>>2]|0)+4>>2]|0;g=(c[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;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>>>0)/((c[d>>2]|0)>>>0)|0|0}function lc(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;while(1){if((c[(c[b>>2]|0)+28>>2]|0)>>>0>8388608)break;mc(c[b>>2]|0,(c[(c[b>>2]|0)+32>>2]|0)>>>23);c[(c[b>>2]|0)+32>>2]=c[(c[b>>2]|0)+32>>2]<<8&2147483647;a=(c[b>>2]|0)+28|0;c[a>>2]=c[a>>2]<<8;a=(c[b>>2]|0)+20|0;c[a>>2]=(c[a>>2]|0)+8}i=d;return}function mc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0;h=i;i=i+16|0;d=h+12|0;e=h+8|0;f=h+4|0;g=h;c[d>>2]=a;c[e>>2]=b;if((c[e>>2]|0)==255){g=(c[d>>2]|0)+36|0;c[g>>2]=(c[g>>2]|0)+1;i=h;return}c[f>>2]=c[e>>2]>>8;if((c[(c[d>>2]|0)+40>>2]|0)>=0){b=nc(c[d>>2]|0,(c[(c[d>>2]|0)+40>>2]|0)+(c[f>>2]|0)|0)|0;a=(c[d>>2]|0)+44|0;c[a>>2]=c[a>>2]|b}if((c[(c[d>>2]|0)+36>>2]|0)>>>0>0){c[g>>2]=255+(c[f>>2]|0)&255;do{f=nc(c[d>>2]|0,c[g>>2]|0)|0;a=(c[d>>2]|0)+44|0;c[a>>2]=c[a>>2]|f;a=(c[d>>2]|0)+36|0;f=(c[a>>2]|0)+-1|0;c[a>>2]=f}while(f>>>0>0)}c[(c[d>>2]|0)+40>>2]=c[e>>2]&255;i=h;return}function nc(b,d){b=b|0;d=d|0;var e=0,f=0,g=0,h=0;h=i;i=i+16|0;e=h+8|0;f=h+4|0;g=h;c[f>>2]=b;c[g>>2]=d;if(((c[(c[f>>2]|0)+24>>2]|0)+(c[(c[f>>2]|0)+8>>2]|0)|0)>>>0>=(c[(c[f>>2]|0)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,c[f>>2]|0,(c[f>>2]|0)+1|0,(c[g>>2]|0)+1|0);i=l;return}}function sc(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+16|0;f=k+12|0;g=k+8|0;j=k+4|0;h=k;c[e>>2]=a;c[f>>2]=b;c[g>>2]=d;c[j>>2]=c[(c[e>>2]|0)+12>>2];c[h>>2]=c[(c[e>>2]|0)+16>>2];if(((c[h>>2]|0)+(c[g>>2]|0)|0)>>>0>32)do{b=tc(c[e>>2]|0,c[j>>2]&255)|0;a=(c[e>>2]|0)+44|0;c[a>>2]=c[a>>2]|b;c[j>>2]=(c[j>>2]|0)>>>8;c[h>>2]=(c[h>>2]|0)-8}while((c[h>>2]|0)>=8);c[j>>2]=c[j>>2]|c[f>>2]<>2];c[h>>2]=(c[h>>2]|0)+(c[g>>2]|0);c[(c[e>>2]|0)+12>>2]=c[j>>2];c[(c[e>>2]|0)+16>>2]=c[h>>2];j=(c[e>>2]|0)+20|0;c[j>>2]=(c[j>>2]|0)+(c[g>>2]|0);i=k;return}function tc(b,d){b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;h=i;i=i+16|0;e=h+8|0;f=h+4|0;g=h;c[f>>2]=b;c[g>>2]=d;if(((c[(c[f>>2]|0)+24>>2]|0)+(c[(c[f>>2]|0)+8>>2]|0)|0)>>>0>=(c[(c[f>>2]|0)+4>>2]|0)>>>0){c[e>>2]=-1;d=c[e>>2]|0;i=h;return d|0}else{g=c[g>>2]&255;b=c[(c[f>>2]|0)+4>>2]|0;j=(c[f>>2]|0)+8|0;d=(c[j>>2]|0)+1|0;c[j>>2]=d;a[(c[c[f>>2]>>2]|0)+(b-d)>>0]=g;c[e>>2]=0;d=c[e>>2]|0;i=h;return d|0}return 0}function uc(b,e,f){b=b|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;g=m+16|0;h=m+12|0;j=m+8|0;l=m+4|0;k=m;c[g>>2]=b;c[h>>2]=e;c[j>>2]=f;c[l>>2]=8-(c[j>>2]|0);c[k>>2]=(1<>2])-1<>2];f=c[g>>2]|0;if((c[(c[g>>2]|0)+24>>2]|0)>>>0>0){a[c[c[g>>2]>>2]>>0]=(d[c[f>>2]>>0]|0)&~c[k>>2]|c[h>>2]<>2];i=m;return}b=c[g>>2]|0;if((c[f+40>>2]|0)>=0){c[(c[g>>2]|0)+40>>2]=c[b+40>>2]&~c[k>>2]|c[h>>2]<>2];i=m;return}f=c[g>>2]|0;if((c[b+28>>2]|0)>>>0<=-2147483648>>>(c[j>>2]|0)>>>0){c[(c[g>>2]|0)+32>>2]=c[f+32>>2]&~(c[k>>2]<<23)|c[h>>2]<<23+(c[l>>2]|0);i=m;return}else{c[f+44>>2]=-1;i=m;return}}function vc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;d=i;i=i+16|0;e=d+4|0;f=d;c[e>>2]=a;c[f>>2]=b;qj((c[c[e>>2]>>2]|0)+(c[f>>2]|0)+(0-(c[(c[e>>2]|0)+8>>2]|0))|0,(c[c[e>>2]>>2]|0)+(c[(c[e>>2]|0)+4>>2]|0)+(0-(c[(c[e>>2]|0)+8>>2]|0))|0,(c[(c[e>>2]|0)+8>>2]|0)+0|0)|0;c[(c[e>>2]|0)+4>>2]=c[f>>2];i=d;return}function wc(b){b=b|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;g=l+20|0;k=l+16|0;j=l+12|0;e=l+8|0;f=l+4|0;h=l;c[g>>2]=b;c[h>>2]=32-(32-(aa(c[(c[g>>2]|0)+28>>2]|0)|0));c[e>>2]=2147483647>>>(c[h>>2]|0);c[f>>2]=(c[(c[g>>2]|0)+32>>2]|0)+(c[e>>2]|0)&~c[e>>2];if((c[f>>2]|c[e>>2])>>>0>=((c[(c[g>>2]|0)+32>>2]|0)+(c[(c[g>>2]|0)+28>>2]|0)|0)>>>0){c[h>>2]=(c[h>>2]|0)+1;c[e>>2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0,o=0;o=i;i=i+64|0;e=o+60|0;f=o+56|0;l=o+52|0;k=o+48|0;m=o+44|0;g=o+40|0;h=o+8|0;j=o+4|0;n=o;c[e>>2]=a;c[f>>2]=d;if((c[(c[e>>2]|0)+8>>2]|0)>0)d=c[(c[e>>2]|0)+8>>2]|0;else d=0;c[n>>2]=d;c[h>>2]=1;c[g>>2]=0;do{c[m>>2]=b[(c[e>>2]|0)+12+(c[g>>2]<<1<<1)>>1];c[k>>2]=b[(c[e>>2]|0)+12+((c[g>>2]<<1)+1<<1)>>1];a=_(c[h+(c[g>>2]<<2)>>2]|0,c[m>>2]|0)|0;c[h+((c[g>>2]|0)+1<<2)>>2]=a;c[g>>2]=(c[g>>2]|0)+1}while((c[k>>2]|0)!=1);c[k>>2]=b[(c[e>>2]|0)+12+((c[g>>2]<<1)-1<<1)>>1];c[j>>2]=(c[g>>2]|0)-1;while(1){if((c[j>>2]|0)<0)break;if(c[j>>2]|0)c[l>>2]=b[(c[e>>2]|0)+12+((c[j>>2]<<1)-1<<1)>>1];else c[l>>2]=1;switch(b[(c[e>>2]|0)+12+(c[j>>2]<<1<<1)>>1]|0){case 2:{yc(c[f>>2]|0,c[k>>2]|0,c[h+(c[j>>2]<<2)>>2]|0);break}case 4:{zc(c[f>>2]|0,c[h+(c[j>>2]<<2)>>2]<>2],c[e>>2]|0,c[k>>2]|0,c[h+(c[j>>2]<<2)>>2]|0,c[l>>2]|0);break}case 3:{Ac(c[f>>2]|0,c[h+(c[j>>2]<<2)>>2]<>2],c[e>>2]|0,c[k>>2]|0,c[h+(c[j>>2]<<2)>>2]|0,c[l>>2]|0);break}case 5:{Bc(c[f>>2]|0,c[h+(c[j>>2]<<2)>>2]<>2],c[e>>2]|0,c[k>>2]|0,c[h+(c[j>>2]<<2)>>2]|0,c[l>>2]|0);break}default:{}}c[k>>2]=c[l>>2];c[j>>2]=(c[j>>2]|0)+-1}i=o;return}function yc(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,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0)>>>0){c[l>>2]=0-(c[l>>2]|0);break}else{c[k>>2]=(c[k>>2]|0)+(c[j>>2]|0);break}}while(0);a=c[e>>2]|0;d=c[k>>2]|0;if(((c[k>>2]|0)+(c[j>>2]|0)|0)>>>0>=32768){k=32768;cc(a,d,k,32768);l=c[l>>2]|0;i=m;return l|0}k=(c[k>>2]|0)+(c[j>>2]|0)|0;cc(a,d,k,32768);l=c[l>>2]|0;i=m;return l|0}function Gc(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+32|0;b=h+16|0;d=h+12|0;f=h+8|0;e=h+4|0;g=h;c[b>>2]=a;c[f>>2]=0;c[e>>2]=32-(aa(c[b>>2]|0)|0)-1>>1;c[d>>2]=1<>2];do{c[g>>2]=(c[f>>2]<<1)+(c[d>>2]|0)<>2];if((c[g>>2]|0)>>>0<=(c[b>>2]|0)>>>0){c[f>>2]=(c[f>>2]|0)+(c[d>>2]|0);c[b>>2]=(c[b>>2]|0)-(c[g>>2]|0)}c[d>>2]=(c[d>>2]|0)>>>1;c[e>>2]=(c[e>>2]|0)+-1}while((c[e>>2]|0)>=0);i=h;return c[f>>2]|0}function Hc(a,d,e,f,h,j,k,l){a=a|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;l=l|0;var m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0.0;U=i;i=i+160|0;V=U+144|0;o=U+140|0;p=U+136|0;q=U+132|0;r=U+128|0;m=U+124|0;s=U+120|0;x=U+112|0;n=U+108|0;u=U+104|0;v=U+100|0;B=U+96|0;G=U+92|0;A=U+88|0;t=U+84|0;J=U+80|0;K=U+76|0;O=U+72|0;H=U+68|0;I=U+64|0;P=U+60|0;C=U+56|0;L=U+48|0;D=U+44|0;E=U+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=(c[R>>2]|0)+-8;c[x>>2]=(c[x>>2]|0)+1}c[L>>2]=(c[o>>2]|0)+(c[q>>2]<<2)+-4;c[S>>2]=c[o>>2];c[G>>2]=c[p>>2];c[H>>2]=(c[p>>2]|0)+(c[q>>2]<<2)+-4;c[x>>2]=0;while(1){if((c[x>>2]|0)>=((c[q>>2]|0)/2|0|0))break;g[I>>2]=+g[c[L>>2]>>2];g[J>>2]=+g[c[S>>2]>>2];W=+g[c[H>>2]>>2]*+g[J>>2]-+g[c[G>>2]>>2]*+g[I>>2];U=c[S>>2]|0;c[S>>2]=U+4;g[U>>2]=W;W=+g[c[G>>2]>>2]*+g[J>>2]+ +g[c[H>>2]>>2]*+g[I>>2];U=c[L>>2]|0;c[L>>2]=U+-4;g[U>>2]=W;c[G>>2]=(c[G>>2]|0)+4;c[H>>2]=(c[H>>2]|0)+-4;c[x>>2]=(c[x>>2]|0)+1}i=V;return}function Jc(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;h=l+20|0;e=l+16|0;f=l+12|0;j=l+8|0;k=l+4|0;g=l;c[e>>2]=a;c[f>>2]=b;c[j>>2]=d;c[k>>2]=0;a:while(1){if((c[k>>2]|0)>=1){e=12;break}c[g>>2]=0;while(1){if((c[g>>2]|0)>=4)break;if((c[e>>2]|0)==(c[c[5544+(c[k>>2]<<2)>>2]>>2]|0)?(c[f>>2]<>2]|0)==(_(c[(c[5544+(c[k>>2]<<2)>>2]|0)+44>>2]|0,c[(c[5544+(c[k>>2]<<2)>>2]|0)+40>>2]|0)|0):0){e=7;break a}c[g>>2]=(c[g>>2]|0)+1}c[k>>2]=(c[k>>2]|0)+1}if((e|0)==7){if(c[j>>2]|0)c[c[j>>2]>>2]=0;c[h>>2]=c[5544+(c[k>>2]<<2)>>2];k=c[h>>2]|0;i=l;return k|0}else if((e|0)==12){if(c[j>>2]|0)c[c[j>>2]>>2]=-1;c[h>>2]=0;k=c[h>>2]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+4>>2]>>2])*.5}Yc(c[j>>2]|0,n,0,0,4,c[k>>2]>>1,c[m>>2]|0)|0;g[n>>2]=+g[n>>2]*1.000100016593933;c[p>>2]=1;while(1){if((c[p>>2]|0)>4)break;b=n+(c[p>>2]<<2)|0;g[b>>2]=+g[b>>2]-+g[n+(c[p>>2]<<2)>>2]*(+(c[p>>2]|0)*.00800000037997961)*(+(c[p>>2]|0)*.00800000037997961);c[p>>2]=(c[p>>2]|0)+1}Uc(q,n,4);c[p>>2]=0;while(1){if((c[p>>2]|0)>=4)break;g[t>>2]=+g[t>>2]*.8999999761581421;g[q+(c[p>>2]<<2)>>2]=+g[q+(c[p>>2]<<2)>>2]*+g[t>>2];c[p>>2]=(c[p>>2]|0)+1}g[r>>2]=+g[q>>2]+.800000011920929;g[r+4>>2]=+g[q+4>>2]+ +g[o>>2]*+g[q>>2];g[r+8>>2]=+g[q+8>>2]+ +g[o>>2]*+g[q+4>>2];g[r+12>>2]=+g[q+12>>2]+ +g[o>>2]*+g[q+8>>2];g[r+16>>2]=+g[o>>2]*+g[q+12>>2];Lc(c[j>>2]|0,r,c[j>>2]|0,c[k>>2]>>1,s);i=u;return}function Lc(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0;y=i;i=i+80|0;h=y+64|0;z=y+60|0;j=y+56|0;k=y+52|0;l=y+48|0;m=y+44|0;s=y+40|0;t=y+36|0;u=y+32|0;v=y+28|0;w=y+24|0;n=y+20|0;o=y+16|0;p=y+12|0;q=y+8|0;r=y+4|0;x=y;c[h>>2]=a;c[z>>2]=b;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;g[s>>2]=+g[c[z>>2]>>2];g[t>>2]=+g[(c[z>>2]|0)+4>>2];g[u>>2]=+g[(c[z>>2]|0)+8>>2];g[v>>2]=+g[(c[z>>2]|0)+12>>2];g[w>>2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g[M>>2];g[P>>2]=+g[f+(c[w>>2]<<2)>>2]+ +g[f+(c[x>>2]<<2)>>2];g[D>>2]=+g[L>>2]/+O(+(+g[K>>2]*2.0*1.0*+g[P>>2]+1.0));do if((N((c[w>>2]|0)-(c[r>>2]|0)|0)|0)<=1)g[A>>2]=+g[s>>2];else{if((N((c[w>>2]|0)-(c[r>>2]|0)|0)|0)<=2?(l=_((c[E>>2]|0)*5|0,c[E>>2]|0)|0,(l|0)<(c[v>>2]|0)):0){g[A>>2]=+g[s>>2]*.5;break}g[A>>2]=0.0}while(0);if(.30000001192092896>+g[C>>2]*.699999988079071-+g[A>>2])j=.30000001192092896;else j=+g[C>>2]*.699999988079071-+g[A>>2];g[I>>2]=j;if((c[w>>2]|0)>=((c[o>>2]|0)*3|0)){if((c[w>>2]|0)<(c[o>>2]<<1|0)){if(.5>+g[C>>2]*.8999999761581421-+g[A>>2])j=.5;else j=+g[C>>2]*.8999999761581421-+g[A>>2];g[I>>2]=j}}else{if(.4000000059604645>+g[C>>2]*.8500000238418579-+g[A>>2])j=.4000000059604645;else j=+g[C>>2]*.8500000238418579-+g[A>>2];g[I>>2]=j}if(+g[D>>2]>+g[I>>2]){g[y>>2]=+g[L>>2];g[z>>2]=+g[P>>2];c[u>>2]=c[w>>2];g[B>>2]=+g[D>>2]}c[E>>2]=(c[E>>2]|0)+1}g[y>>2]=0.0>+g[y>>2]?0.0:+g[y>>2];if(+g[z>>2]<=+g[y>>2])g[H>>2]=1.0;else g[H>>2]=+g[y>>2]/(+g[z>>2]+1.0);c[E>>2]=0;while(1){if((c[E>>2]|0)>=3)break;j=+Oc(c[m>>2]|0,(c[m>>2]|0)+(0-((c[u>>2]|0)+(c[E>>2]|0)-1)<<2)|0,c[p>>2]|0);g[J+(c[E>>2]<<2)>>2]=j;c[E>>2]=(c[E>>2]|0)+1}do if(!(+g[J+8>>2]-+g[J>>2]>(+g[J+4>>2]-+g[J>>2])*.699999988079071))if(+g[J>>2]-+g[J+8>>2]>(+g[J+4>>2]-+g[J+8>>2])*.699999988079071){c[G>>2]=-1;break}else{c[G>>2]=0;break}else c[G>>2]=1;while(0);if(+g[H>>2]>+g[B>>2])g[H>>2]=+g[B>>2];c[c[q>>2]>>2]=(c[u>>2]<<1)+(c[G>>2]|0);if((c[c[q>>2]>>2]|0)>=(c[F>>2]|0)){j=+g[H>>2];P=c[t>>2]|0;na(P|0);i=Q;return +j}c[c[q>>2]>>2]=c[F>>2];j=+g[H>>2];P=c[t>>2]|0;na(P|0);i=Q;return +j}function Sc(a,b,d,e,f,h){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;var j=0.0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;t=i;i=i+48|0;k=t+32|0;l=t+28|0;m=t+24|0;n=t+20|0;o=t+16|0;p=t+12|0;q=t+8|0;r=t+4|0;s=t;c[k>>2]=a;c[l>>2]=b;c[m>>2]=d;c[n>>2]=e;c[o>>2]=f;c[p>>2]=h;g[r>>2]=0.0;g[s>>2]=0.0;c[q>>2]=0;while(1){j=+g[r>>2];if((c[q>>2]|0)>=(c[n>>2]|0))break;g[r>>2]=j+ +g[(c[k>>2]|0)+(c[q>>2]<<2)>>2]*+g[(c[l>>2]|0)+(c[q>>2]<<2)>>2];g[s>>2]=+g[s>>2]+ +g[(c[k>>2]|0)+(c[q>>2]<<2)>>2]*+g[(c[m>>2]|0)+(c[q>>2]<<2)>>2];c[q>>2]=(c[q>>2]|0)+1}g[c[o>>2]>>2]=j;g[c[p>>2]>>2]=+g[s>>2];i=t;return}function Tc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>>>0)/((c[d>>2]|0)>>>0)|0|0}function Uc(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;q=i;i=i+48|0;r=q+40|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0)==15){i=q;return}}function Vc(a,b,d,e,f,h,j){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;v=i;i=i+64|0;k=v+60|0;l=v+56|0;m=v+52|0;n=v+48|0;o=v+44|0;p=v+40|0;r=v+32|0;s=v+28|0;q=v+24|0;t=v+8|0;u=v;c[k>>2]=a;c[l>>2]=b;c[m>>2]=d;c[n>>2]=e;c[o>>2]=f;c[p>>2]=h;c[v+36>>2]=j;a=c[o>>2]|0;c[q>>2]=ia()|0;e=i;i=i+((1*(a<<2)|0)+15&-16)|0;a=i;i=i+((1*((c[n>>2]|0)+(c[o>>2]|0)<<2)|0)+15&-16)|0;c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[o>>2]|0))break;g[e+(c[r>>2]<<2)>>2]=+g[(c[l>>2]|0)+((c[o>>2]|0)-(c[r>>2]|0)-1<<2)>>2];c[r>>2]=(c[r>>2]|0)+1}c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[o>>2]|0))break;g[a+(c[r>>2]<<2)>>2]=+g[(c[p>>2]|0)+((c[o>>2]|0)-(c[r>>2]|0)-1<<2)>>2];c[r>>2]=(c[r>>2]|0)+1}c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[n>>2]|0))break;g[a+((c[r>>2]|0)+(c[o>>2]|0)<<2)>>2]=+g[(c[k>>2]|0)+(c[r>>2]<<2)>>2];c[r>>2]=(c[r>>2]|0)+1}c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[o>>2]|0))break;g[(c[p>>2]|0)+(c[r>>2]<<2)>>2]=+g[(c[k>>2]|0)+((c[n>>2]|0)-(c[r>>2]|0)-1<<2)>>2];c[r>>2]=(c[r>>2]|0)+1}c[r>>2]=0;while(1){if((c[r>>2]|0)>=((c[n>>2]|0)-3|0))break;c[t>>2]=0;c[t+4>>2]=0;c[t+8>>2]=0;c[t+12>>2]=0;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(c[C>>2]|0)>>1;c[aa>>2]=0;c[I>>2]=0;c[za>>2]=c[ma>>2];while(1){m=c[za>>2]|0;c[za>>2]=m+-1;if((m|0)<=(c[ba>>2]|0))break;c[F>>2]=(c[(c[G>>2]|0)+(c[za>>2]<<2)>>2]|0)+((_(c[E>>2]|0,c[(c[H>>2]|0)+(c[za>>2]<<2)>>2]|0)|0)>>6);if(!(c[I>>2]|0?1:(c[F>>2]|0)>=(c[(c[Q>>2]|0)+(c[za>>2]<<2)>>2]|0))){if((c[F>>2]|0)<(c[R>>2]|0))continue;c[aa>>2]=(c[aa>>2]|0)+(c[R>>2]|0);continue}c[I>>2]=1;if((c[F>>2]|0)<(c[(c[na>>2]|0)+(c[za>>2]<<2)>>2]|0))w=c[F>>2]|0;else w=c[(c[na>>2]|0)+(c[za>>2]<<2)>>2]|0;c[aa>>2]=(c[aa>>2]|0)+w}w=c[E>>2]|0;if((c[aa>>2]|0)>(c[Z>>2]|0))c[C>>2]=w;else c[J>>2]=w;c[D>>2]=(c[D>>2]|0)+1}c[aa>>2]=0;c[I>>2]=0;c[za>>2]=c[ma>>2];while(1){F=c[za>>2]|0;c[za>>2]=F+-1;if((F|0)<=(c[ba>>2]|0))break;c[K>>2]=(c[(c[G>>2]|0)+(c[za>>2]<<2)>>2]|0)+((_(c[J>>2]|0,c[(c[H>>2]|0)+(c[za>>2]<<2)>>2]|0)|0)>>6);do if(!(c[I>>2]|0?1:(c[K>>2]|0)>=(c[(c[Q>>2]|0)+(c[za>>2]<<2)>>2]|0)))if((c[K>>2]|0)>=(c[R>>2]|0)){c[K>>2]=c[R>>2];break}else{c[K>>2]=0;break}else c[I>>2]=1;while(0);if((c[K>>2]|0)<(c[(c[na>>2]|0)+(c[za>>2]<<2)>>2]|0))w=c[K>>2]|0;else w=c[(c[na>>2]|0)+(c[za>>2]<<2)>>2]|0;c[K>>2]=w;c[(c[ha>>2]|0)+(c[za>>2]<<2)>>2]=c[K>>2];c[aa>>2]=(c[aa>>2]|0)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2]=(c[u>>2]|0)+1}}while(0);c[k>>2]=od(c[k>>2]|0,c[m>>2]|0)|0;c[s>>2]=0;while(1){if((c[s>>2]|0)>=(c[m>>2]|0))break;if((c[l>>2]|0)>=0){v=(c[j>>2]|0)+((_(c[s>>2]|0,c[k>>2]|0)|0)<<2)|0;pd(v,c[k>>2]|0,1,+g[p>>2],-+g[t>>2]);if(c[u>>2]|0){v=(c[j>>2]|0)+((_(c[s>>2]|0,c[k>>2]|0)|0)<<2)|0;pd(v,c[k>>2]|0,c[u>>2]|0,+g[t>>2],-+g[p>>2])}}else{if(c[u>>2]|0){v=(c[j>>2]|0)+((_(c[s>>2]|0,c[k>>2]|0)|0)<<2)|0;pd(v,c[k>>2]|0,c[u>>2]|0,+g[t>>2],+g[p>>2])}v=(c[j>>2]|0)+((_(c[s>>2]|0,c[k>>2]|0)|0)<<2)|0;pd(v,c[k>>2]|0,1,+g[p>>2],+g[t>>2])}c[s>>2]=(c[s>>2]|0)+1}i=w;return}function od(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>>>0)/((c[d>>2]|0)>>>0)|0|0}function pd(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=+e;f=+f;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;u=i;i=i+48|0;h=u+44|0;j=u+40|0;k=u+36|0;l=u+32|0;m=u+28|0;o=u+24|0;p=u+20|0;n=u+16|0;q=u+12|0;s=u+8|0;r=u+4|0;t=u;c[h>>2]=a;c[j>>2]=b;c[k>>2]=d;g[l>>2]=e;g[m>>2]=f;c[n>>2]=c[h>>2];g[p>>2]=-+g[m>>2];c[o>>2]=0;while(1){if((c[o>>2]|0)>=((c[j>>2]|0)-(c[k>>2]|0)|0))break;g[q>>2]=+g[c[n>>2]>>2];g[s>>2]=+g[(c[n>>2]|0)+(c[k>>2]<<2)>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+48|0;m=l+32|0;f=l+28|0;n=l+24|0;j=l+16|0;p=l+12|0;h=l+8|0;o=l+4|0;k=l;c[m>>2]=a;c[f>>2]=b;g[n>>2]=d;c[l+20>>2]=e;g[p>>2]=+ud(c[m>>2]|0,c[m>>2]|0,c[f>>2]|0)+1.0000000036274937e-15;g[o>>2]=+g[p>>2];d=1.0/+O(+(+g[o>>2]));g[h>>2]=d*+g[n>>2];c[k>>2]=c[m>>2];c[j>>2]=0;while(1){if((c[j>>2]|0)>=(c[f>>2]|0))break;g[c[k>>2]>>2]=+g[h>>2]*+g[c[k>>2]>>2];c[k>>2]=(c[k>>2]|0)+4;c[j>>2]=(c[j>>2]|0)+1}i=l;return}function ud(a,b,d){a=a|0;b=b|0;d=d|0;var e=0.0,f=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;f=m+16|0;h=m+12|0;j=m+8|0;k=m+4|0;l=m;c[f>>2]=a;c[h>>2]=b;c[j>>2]=d;g[l>>2]=0.0;c[k>>2]=0;while(1){e=+g[l>>2];if((c[k>>2]|0)>=(c[j>>2]|0))break;g[l>>2]=e+ +g[(c[f>>2]|0)+(c[k>>2]<<2)>>2]*+g[(c[h>>2]|0)+(c[k>>2]<<2)>>2];c[k>>2]=(c[k>>2]|0)+1}i=m;return +e}function vd(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0.0;t=i;i=i+64|0;h=t+48|0;j=t+44|0;u=t+40|0;k=t+36|0;n=t+28|0;o=t+24|0;q=t+20|0;s=t+16|0;l=t+12|0;m=t+8|0;p=t+4|0;r=t;c[h>>2]=a;c[j>>2]=b;c[u>>2]=d;c[k>>2]=e;c[t+32>>2]=f;g[m>>2]=1.0000000036274937e-15;g[l>>2]=1.0000000036274937e-15;a:do if(c[u>>2]|0){c[n>>2]=0;while(1){if((c[n>>2]|0)>=(c[k>>2]|0))break a;g[p>>2]=+g[(c[h>>2]|0)+(c[n>>2]<<2)>>2]+ +g[(c[j>>2]|0)+(c[n>>2]<<2)>>2];g[r>>2]=+g[(c[h>>2]|0)+(c[n>>2]<<2)>>2]-+g[(c[j>>2]|0)+(c[n>>2]<<2)>>2];g[l>>2]=+g[l>>2]+ +g[p>>2]*+g[p>>2];g[m>>2]=+g[m>>2]+ +g[r>>2]*+g[r>>2];c[n>>2]=(c[n>>2]|0)+1}}else{v=+ud(c[h>>2]|0,c[h>>2]|0,c[k>>2]|0);g[l>>2]=+g[l>>2]+v;v=+ud(c[j>>2]|0,c[j>>2]|0,c[k>>2]|0);g[m>>2]=+g[m>>2]+v}while(0);g[q>>2]=+O(+(+g[l>>2]));g[s>>2]=+O(+(+g[m>>2]));c[o>>2]=~~+M(+(+W(+(+g[s>>2]),+(+g[q>>2]))*10430.3818359375+.5));i=t;return c[o>>2]|0}function wd(a){a=a|0;var d=0,e=0,f=0,g=0,h=0;h=i;i=i+16|0;d=h+12|0;g=h+8|0;f=h+4|0;e=h;c[d>>2]=a;c[f>>2]=32767/((c[(c[d>>2]|0)+2340>>2]|0)+1|0)|0;c[e>>2]=0;c[g>>2]=0;while(1){if((c[g>>2]|0)>=(c[(c[d>>2]|0)+2340>>2]|0))break;c[e>>2]=(c[e>>2]|0)+(c[f>>2]|0);b[(c[d>>2]|0)+2772+1280+(c[g>>2]<<1)>>1]=c[e>>2];c[g>>2]=(c[g>>2]|0)+1}c[(c[d>>2]|0)+2772+1376>>2]=0;c[(c[d>>2]|0)+2772+1380>>2]=3176576;i=h;return} + function cg(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;t=i;i=i+48|0;f=t+40|0;g=t+36|0;h=t+32|0;m=t+28|0;j=t+24|0;n=t+20|0;o=t+16|0;k=t+44|0;l=t+12|0;r=t+8|0;q=t+4|0;p=t;c[f>>2]=a;c[g>>2]=d;c[h>>2]=e;c[j>>2]=0;c[o>>2]=0;while(1){if((c[o>>2]|0)>=20)break;c[r>>2]=(b[c[f>>2]>>1]|0)-(b[c[g>>2]>>1]|0);c[j>>2]=0;c[m>>2]=1;while(1){if((c[m>>2]|0)>((c[h>>2]|0)-1|0))break;c[l>>2]=(b[(c[f>>2]|0)+(c[m>>2]<<1)>>1]|0)-((b[(c[f>>2]|0)+((c[m>>2]|0)-1<<1)>>1]|0)+(b[(c[g>>2]|0)+(c[m>>2]<<1)>>1]|0));if((c[l>>2]|0)<(c[r>>2]|0)){c[r>>2]=c[l>>2];c[j>>2]=c[m>>2]}c[m>>2]=(c[m>>2]|0)+1}c[l>>2]=32768-((b[(c[f>>2]|0)+((c[h>>2]|0)-1<<1)>>1]|0)+(b[(c[g>>2]|0)+(c[h>>2]<<1)>>1]|0));if((c[l>>2]|0)<(c[r>>2]|0)){c[r>>2]=c[l>>2];c[j>>2]=c[h>>2]}if((c[r>>2]|0)>=0){s=41;break}do if(!(c[j>>2]|0))b[c[f>>2]>>1]=b[c[g>>2]>>1]|0;else{if((c[j>>2]|0)==(c[h>>2]|0)){b[(c[f>>2]|0)+((c[h>>2]|0)-1<<1)>>1]=32768-(b[(c[g>>2]|0)+(c[h>>2]<<1)>>1]|0);break}c[q>>2]=0;c[n>>2]=0;while(1){if((c[n>>2]|0)>=(c[j>>2]|0))break;c[q>>2]=(c[q>>2]|0)+(b[(c[g>>2]|0)+(c[n>>2]<<1)>>1]|0);c[n>>2]=(c[n>>2]|0)+1}c[q>>2]=(c[q>>2]|0)+(b[(c[g>>2]|0)+(c[j>>2]<<1)>>1]>>1);c[p>>2]=32768;c[n>>2]=c[h>>2];while(1){if((c[n>>2]|0)<=(c[j>>2]|0))break;c[p>>2]=(c[p>>2]|0)-(b[(c[g>>2]|0)+(c[n>>2]<<1)>>1]|0);c[n>>2]=(c[n>>2]|0)+-1}c[p>>2]=(c[p>>2]|0)-(b[(c[g>>2]|0)+(c[j>>2]<<1)>>1]>>1);e=((b[(c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g>>2]|0)+(c[j>>2]<<1)>>1]>>1);b[(c[f>>2]|0)+(c[j>>2]<<1)>>1]=(b[(c[f>>2]|0)+((c[j>>2]|0)-1<<1)>>1]|0)+(b[(c[g>>2]|0)+(c[j>>2]<<1)>>1]|0)}while(0);c[o>>2]=(c[o>>2]|0)+1}if((s|0)==41){i=t;return}if((c[o>>2]|0)!=20){i=t;return}vg(c[f>>2]|0,c[h>>2]|0);s=(dg(b[c[f>>2]>>1]|0,b[c[g>>2]>>1]|0)|0)&65535;b[c[f>>2]>>1]=s;c[m>>2]=1;while(1){if((c[m>>2]|0)>=(c[h>>2]|0))break;s=(dg(b[(c[f>>2]|0)+(c[m>>2]<<1)>>1]|0,(b[(c[f>>2]|0)+((c[m>>2]|0)-1<<1)>>1]|0)+(b[(c[g>>2]|0)+(c[m>>2]<<1)>>1]|0)|0)|0)&65535;b[(c[f>>2]|0)+(c[m>>2]<<1)>>1]=s;c[m>>2]=(c[m>>2]|0)+1}s=(eg(b[(c[f>>2]|0)+((c[h>>2]|0)-1<<1)>>1]|0,32768-(b[(c[g>>2]|0)+(c[h>>2]<<1)>>1]|0)|0)|0)&65535;b[(c[f>>2]|0)+((c[h>>2]|0)-1<<1)>>1]=s;c[m>>2]=(c[h>>2]|0)-2;while(1){if((c[m>>2]|0)<0)break;s=(eg(b[(c[f>>2]|0)+(c[m>>2]<<1)>>1]|0,(b[(c[f>>2]|0)+((c[m>>2]|0)+1<<1)>>1]|0)-(b[(c[g>>2]|0)+((c[m>>2]|0)+1<<1)>>1]|0)|0)|0)&65535;b[(c[f>>2]|0)+(c[m>>2]<<1)>>1]=s;c[m>>2]=(c[m>>2]|0)+-1}i=t;return}function dg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function eg(a,b){a=a|0;b=b|0;var d=0,e=0,f=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65535;b[(c[f>>2]|0)+((c[h>>2]|0)-1<<1)>>1]=l;i=m;return}function gg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function hg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function ig(b,d,e,f){b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0;m=i;i=i+32|0;g=m+20|0;h=m+16|0;j=m+12|0;k=m+8|0;n=m+4|0;l=m;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;c[n>>2]=f;oj(c[h>>2]|0,0,300)|0;d=(c[j>>2]|0)!=8e3&(c[j>>2]|0)!=12e3&(c[j>>2]|0)!=16e3;do if(c[n>>2]|0){if(!(d&(c[j>>2]|0)!=24e3&(c[j>>2]|0)!=48e3)?!((c[k>>2]|0)!=8e3&(c[k>>2]|0)!=12e3&(c[k>>2]|0)!=16e3):0){c[(c[h>>2]|0)+292>>2]=a[30493+((((c[j>>2]>>12)-((c[j>>2]|0)>16e3&1)>>((c[j>>2]|0)>24e3&1))-1|0)*3|0)+(((c[k>>2]>>12)-((c[k>>2]|0)>16e3&1)>>((c[k>>2]|0)>24e3&1))-1)>>0];break}c[g>>2]=-1;n=c[g>>2]|0;i=m;return n|0}else{if(!d?!((c[k>>2]|0)!=8e3&(c[k>>2]|0)!=12e3&(c[k>>2]|0)!=16e3&(c[k>>2]|0)!=24e3&(c[k>>2]|0)!=48e3):0){c[(c[h>>2]|0)+292>>2]=a[30508+((((c[j>>2]>>12)-((c[j>>2]|0)>16e3&1)>>((c[j>>2]|0)>24e3&1))-1|0)*5|0)+(((c[k>>2]>>12)-((c[k>>2]|0)>16e3&1)>>((c[k>>2]|0)>24e3&1))-1)>>0];break}c[g>>2]=-1;n=c[g>>2]|0;i=m;return n|0}while(0);c[(c[h>>2]|0)+284>>2]=(c[j>>2]|0)/1e3|0;c[(c[h>>2]|0)+288>>2]=(c[k>>2]|0)/1e3|0;c[(c[h>>2]|0)+268>>2]=(c[(c[h>>2]|0)+284>>2]|0)*10;c[l>>2]=0;e=c[k>>2]|0;b=c[j>>2]|0;do if((c[k>>2]|0)>(c[j>>2]|0)){d=(c[h>>2]|0)+264|0;if((e|0)==(b<<1|0)){c[d>>2]=1;break}else{c[d>>2]=2;c[l>>2]=1;break}}else{d=(c[h>>2]|0)+264|0;if((e|0)>=(b|0)){c[d>>2]=0;break}c[d>>2]=3;if((c[k>>2]<<2|0)==((c[j>>2]|0)*3|0)){c[(c[h>>2]|0)+280>>2]=3;c[(c[h>>2]|0)+276>>2]=18;c[(c[h>>2]|0)+296>>2]=24846;break}if(((c[k>>2]|0)*3|0)==(c[j>>2]<<1|0)){c[(c[h>>2]|0)+280>>2]=2;c[(c[h>>2]|0)+276>>2]=18;c[(c[h>>2]|0)+296>>2]=24904;break}if((c[k>>2]<<1|0)==(c[j>>2]|0)){c[(c[h>>2]|0)+280>>2]=1;c[(c[h>>2]|0)+276>>2]=24;c[(c[h>>2]|0)+296>>2]=24944;break}if(((c[k>>2]|0)*3|0)==(c[j>>2]|0)){c[(c[h>>2]|0)+280>>2]=1;c[(c[h>>2]|0)+276>>2]=36;c[(c[h>>2]|0)+296>>2]=24972;break}if((c[k>>2]<<2|0)==(c[j>>2]|0)){c[(c[h>>2]|0)+280>>2]=1;c[(c[h>>2]|0)+276>>2]=36;c[(c[h>>2]|0)+296>>2]=25012;break}if(((c[k>>2]|0)*6|0)==(c[j>>2]|0)){c[(c[h>>2]|0)+280>>2]=1;c[(c[h>>2]|0)+276>>2]=36;c[(c[h>>2]|0)+296>>2]=25052;break}c[g>>2]=-1;n=c[g>>2]|0;i=m;return n|0}while(0);c[(c[h>>2]|0)+272>>2]=((c[j>>2]<<14+(c[l>>2]|0)|0)/(c[k>>2]|0)|0)<<2;while(1){n=_(c[(c[h>>2]|0)+272>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;n=n+((_(c[(c[h>>2]|0)+272>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16)|0;n=n+(_(c[(c[h>>2]|0)+272>>2]|0,(c[k>>2]>>15)+1>>1)|0)|0;if((n|0)>=(c[j>>2]<>2]|0))break;n=(c[h>>2]|0)+272|0;c[n>>2]=(c[n>>2]|0)+1}c[g>>2]=0;n=c[g>>2]|0;i=m;return n|0}function jg(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;f=l+16|0;g=l+12|0;h=l+8|0;j=l+4|0;k=l;c[f>>2]=a;c[g>>2]=b;c[h>>2]=d;c[j>>2]=e;c[k>>2]=(c[(c[f>>2]|0)+284>>2]|0)-(c[(c[f>>2]|0)+292>>2]|0);pj((c[f>>2]|0)+168+(c[(c[f>>2]|0)+292>>2]<<1)|0,c[h>>2]|0,c[k>>2]<<1|0)|0;switch(c[(c[f>>2]|0)+264>>2]|0){case 1:{sg(c[f>>2]|0,c[g>>2]|0,(c[f>>2]|0)+168|0,c[(c[f>>2]|0)+284>>2]|0);sg(c[f>>2]|0,(c[g>>2]|0)+(c[(c[f>>2]|0)+288>>2]<<1)|0,(c[h>>2]|0)+(c[k>>2]<<1)|0,(c[j>>2]|0)-(c[(c[f>>2]|0)+284>>2]|0)|0);break}case 2:{pg(c[f>>2]|0,c[g>>2]|0,(c[f>>2]|0)+168|0,c[(c[f>>2]|0)+284>>2]|0);pg(c[f>>2]|0,(c[g>>2]|0)+(c[(c[f>>2]|0)+288>>2]<<1)|0,(c[h>>2]|0)+(c[k>>2]<<1)|0,(c[j>>2]|0)-(c[(c[f>>2]|0)+284>>2]|0)|0);break}case 3:{ng(c[f>>2]|0,c[g>>2]|0,(c[f>>2]|0)+168|0,c[(c[f>>2]|0)+284>>2]|0);ng(c[f>>2]|0,(c[g>>2]|0)+(c[(c[f>>2]|0)+288>>2]<<1)|0,(c[h>>2]|0)+(c[k>>2]<<1)|0,(c[j>>2]|0)-(c[(c[f>>2]|0)+284>>2]|0)|0);break}default:{pj(c[g>>2]|0,(c[f>>2]|0)+168|0,c[(c[f>>2]|0)+284>>2]<<1|0)|0;pj((c[g>>2]|0)+(c[(c[f>>2]|0)+288>>2]<<1)|0,(c[h>>2]|0)+(c[k>>2]<<1)|0,(c[j>>2]|0)-(c[(c[f>>2]|0)+284>>2]|0)<<1|0)|0}}pj((c[f>>2]|0)+168|0,(c[h>>2]|0)+((c[j>>2]|0)-(c[(c[f>>2]|0)+292>>2]|0)<<1)|0,c[(c[f>>2]|0)+292>>2]<<1|0)|0;i=l;return 0}function kg(a,d,e,f){a=a|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;q=i;i=i+1968|0;g=q+1964|0;h=q+1960|0;j=q+1956|0;k=q+1952|0;o=q+1948|0;n=q+1944|0;p=q+1940|0;m=q+1936|0;l=q;c[g>>2]=a;c[h>>2]=d;c[j>>2]=e;c[k>>2]=f;d=c[g>>2]|0;c[l>>2]=c[d>>2];c[l+4>>2]=c[d+4>>2];c[l+8>>2]=c[d+8>>2];c[l+12>>2]=c[d+12>>2];while(1){c[o>>2]=(c[k>>2]|0)<480?c[k>>2]|0:480;mg((c[g>>2]|0)+16|0,l+16|0,c[j>>2]|0,25092,c[o>>2]|0);c[m>>2]=l;c[n>>2]=c[o>>2];while(1){if((c[n>>2]|0)<=2)break;d=_(c[c[m>>2]>>2]>>16,b[12548]|0)|0;c[p>>2]=d+((_(c[c[m>>2]>>2]&65535,b[12548]|0)|0)>>16);d=_(c[(c[m>>2]|0)+4>>2]>>16,b[12549]|0)|0;c[p>>2]=(c[p>>2]|0)+(d+((_(c[(c[m>>2]|0)+4>>2]&65535,b[12549]|0)|0)>>16));d=_(c[(c[m>>2]|0)+8>>2]>>16,b[12551]|0)|0;c[p>>2]=(c[p>>2]|0)+(d+((_(c[(c[m>>2]|0)+8>>2]&65535,b[12551]|0)|0)>>16));d=_(c[(c[m>>2]|0)+12>>2]>>16,b[12550]|0)|0;c[p>>2]=(c[p>>2]|0)+(d+((_(c[(c[m>>2]|0)+12>>2]&65535,b[12550]|0)|0)>>16));if(((c[p>>2]>>5)+1>>1|0)<=32767)if(((c[p>>2]>>5)+1>>1|0)<-32768)a=-32768;else a=(c[p>>2]>>5)+1>>1;else a=32767;d=c[h>>2]|0;c[h>>2]=d+2;b[d>>1]=a;d=_(c[(c[m>>2]|0)+4>>2]>>16,b[12550]|0)|0;c[p>>2]=d+((_(c[(c[m>>2]|0)+4>>2]&65535,b[12550]|0)|0)>>16);d=_(c[(c[m>>2]|0)+8>>2]>>16,b[12551]|0)|0;c[p>>2]=(c[p>>2]|0)+(d+((_(c[(c[m>>2]|0)+8>>2]&65535,b[12551]|0)|0)>>16));d=_(c[(c[m>>2]|0)+12>>2]>>16,b[12549]|0)|0;c[p>>2]=(c[p>>2]|0)+(d+((_(c[(c[m>>2]|0)+12>>2]&65535,b[12549]|0)|0)>>16));d=_(c[(c[m>>2]|0)+16>>2]>>16,b[12548]|0)|0;c[p>>2]=(c[p>>2]|0)+(d+((_(c[(c[m>>2]|0)+16>>2]&65535,b[12548]|0)|0)>>16));if(((c[p>>2]>>5)+1>>1|0)<=32767)if(((c[p>>2]>>5)+1>>1|0)<-32768)a=-32768;else a=(c[p>>2]>>5)+1>>1;else a=32767;d=c[h>>2]|0;c[h>>2]=d+2;b[d>>1]=a;c[m>>2]=(c[m>>2]|0)+12;c[n>>2]=(c[n>>2]|0)-3}c[j>>2]=(c[j>>2]|0)+(c[o>>2]<<1);c[k>>2]=(c[k>>2]|0)-(c[o>>2]|0);if((c[k>>2]|0)<=0)break;d=l+(c[o>>2]<<2)|0;c[l>>2]=c[d>>2];c[l+4>>2]=c[d+4>>2];c[l+8>>2]=c[d+8>>2];c[l+12>>2]=c[d+12>>2]}p=c[g>>2]|0;o=l+(c[o>>2]<<2)|0;c[p>>2]=c[o>>2];c[p+4>>2]=c[o+4>>2];c[p+8>>2]=c[o+8>>2];c[p+12>>2]=c[o+12>>2];i=q;return}function lg(a,d,e,f){a=a|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;q=i;i=i+48|0;g=q+36|0;h=q+32|0;j=q+28|0;r=q+24|0;n=q+20|0;o=q+16|0;m=q+12|0;p=q+8|0;l=q+4|0;k=q;c[g>>2]=a;c[h>>2]=d;c[j>>2]=e;c[r>>2]=f;c[o>>2]=c[r>>2]>>1;c[n>>2]=0;while(1){if((c[n>>2]|0)>=(c[o>>2]|0))break;c[m>>2]=b[(c[j>>2]|0)+(c[n>>2]<<1<<1)>>1]<<10;c[l>>2]=(c[m>>2]|0)-(c[c[g>>2]>>2]|0);r=_(c[l>>2]>>16,-25727)|0;c[k>>2]=(c[l>>2]|0)+(r+((_(c[l>>2]&65535,-25727)|0)>>16));c[p>>2]=(c[c[g>>2]>>2]|0)+(c[k>>2]|0);c[c[g>>2]>>2]=(c[m>>2]|0)+(c[k>>2]|0);c[m>>2]=b[(c[j>>2]|0)+((c[n>>2]<<1)+1<<1)>>1]<<10;c[l>>2]=(c[m>>2]|0)-(c[(c[g>>2]|0)+4>>2]|0);c[k>>2]=((c[l>>2]>>16)*9872|0)+((c[l>>2]&65535)*9872>>16);c[p>>2]=(c[p>>2]|0)+(c[(c[g>>2]|0)+4>>2]|0);c[p>>2]=(c[p>>2]|0)+(c[k>>2]|0);c[(c[g>>2]|0)+4>>2]=(c[m>>2]|0)+(c[k>>2]|0);if(((c[p>>2]>>10)+1>>1|0)<=32767)if(((c[p>>2]>>10)+1>>1|0)<-32768)a=-32768;else a=(c[p>>2]>>10)+1>>1;else a=32767;b[(c[h>>2]|0)+(c[n>>2]<<1)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[(c[l>>2]|0)+296>>2]|0)+4;c[m>>2]=c[(c[l>>2]|0)+272>>2];while(1){if((c[h>>2]|0)<(c[(c[l>>2]|0)+268>>2]|0))d=c[h>>2]|0;else d=c[(c[l>>2]|0)+268>>2]|0;c[o>>2]=d;mg(c[l>>2]|0,a+(c[(c[l>>2]|0)+276>>2]<<2)|0,c[g>>2]|0,c[(c[l>>2]|0)+296>>2]|0,c[o>>2]|0);c[n>>2]=c[o>>2]<<16;c[f>>2]=og(c[f>>2]|0,a,c[k>>2]|0,c[(c[l>>2]|0)+276>>2]|0,c[(c[l>>2]|0)+280>>2]|0,c[n>>2]|0,c[m>>2]|0)|0;c[g>>2]=(c[g>>2]|0)+(c[o>>2]<<1);c[h>>2]=(c[h>>2]|0)-(c[o>>2]|0);if((c[h>>2]|0)<=1)break;pj(a|0,a+(c[o>>2]<<2)|0,c[(c[l>>2]|0)+276>>2]<<2|0)|0}pj((c[l>>2]|0)+24|0,a+(c[o>>2]<<2)|0,c[(c[l>>2]|0)+276>>2]<<2|0)|0;na(c[j>>2]|0);i=p;return}function og(a,d,e,f,g,h,j){a=a|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;v=i;i=i+48|0;n=v+44|0;o=v+40|0;p=v+36|0;w=v+32|0;k=v+28|0;q=v+24|0;r=v+20|0;t=v+16|0;u=v+12|0;s=v+8|0;l=v+4|0;m=v;c[n>>2]=a;c[o>>2]=d;c[p>>2]=e;c[w>>2]=f;c[k>>2]=g;c[q>>2]=h;c[r>>2]=j;switch(c[w>>2]|0){case 18:{c[t>>2]=0;while(1){if((c[t>>2]|0)>=(c[q>>2]|0))break;c[s>>2]=(c[o>>2]|0)+(c[t>>2]>>16<<2);w=_((c[t>>2]&65535)>>16,(c[k>>2]&65535)<<16>>16)|0;c[l>>2]=w+((_(c[t>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16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u>>2]=(c[u>>2]|0)+(w+((_(c[(c[s>>2]|0)+44>>2]&65535,b[(c[m>>2]|0)+12>>1]|0)|0)>>16));w=_(c[(c[s>>2]|0)+40>>2]>>16,b[(c[m>>2]|0)+14>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+((_(c[(c[s>>2]|0)+40>>2]&65535,b[(c[m>>2]|0)+14>>1]|0)|0)>>16));w=_(c[(c[s>>2]|0)+36>>2]>>16,b[(c[m>>2]|0)+16>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+((_(c[(c[s>>2]|0)+36>>2]&65535,b[(c[m>>2]|0)+16>>1]|0)|0)>>16));if(((c[u>>2]>>5)+1>>1|0)<=32767)if(((c[u>>2]>>5)+1>>1|0)<-32768)e=-32768;else e=(c[u>>2]>>5)+1>>1;else e=32767;w=c[n>>2]|0;c[n>>2]=w+2;b[w>>1]=e;c[t>>2]=(c[t>>2]|0)+(c[r>>2]|0)}w=c[n>>2]|0;i=v;return w|0}case 24:{c[t>>2]=0;while(1){if((c[t>>2]|0)>=(c[q>>2]|0))break;c[s>>2]=(c[o>>2]|0)+(c[t>>2]>>16<<2);w=_((c[c[s>>2]>>2]|0)+(c[(c[s>>2]|0)+92>>2]|0)>>16,b[c[p>>2]>>1]|0)|0;c[u>>2]=w+((_((c[c[s>>2]>>2]|0)+(c[(c[s>>2]|0)+92>>2]|0)&65535,b[c[p>>2]>>1]|0)|0)>>16);w=_((c[(c[s>>2]|0)+4>>2]|0)+(c[(c[s>>2]|0)+88>>2]|0)>>16,b[(c[p>>2]|0)+2>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+((_((c[(c[s>>2]|0)+4>>2]|0)+(c[(c[s>>2]|0)+88>>2]|0)&65535,b[(c[p>>2]|0)+2>>1]|0)|0)>>16));w=_((c[(c[s>>2]|0)+8>>2]|0)+(c[(c[s>>2]|0)+84>>2]|0)>>16,b[(c[p>>2]|0)+4>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+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]|0)+(c[(c[s>>2]|0)+60>>2]|0)>>16,b[(c[p>>2]|0)+16>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+((_((c[(c[s>>2]|0)+32>>2]|0)+(c[(c[s>>2]|0)+60>>2]|0)&65535,b[(c[p>>2]|0)+16>>1]|0)|0)>>16));w=_((c[(c[s>>2]|0)+36>>2]|0)+(c[(c[s>>2]|0)+56>>2]|0)>>16,b[(c[p>>2]|0)+18>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+((_((c[(c[s>>2]|0)+36>>2]|0)+(c[(c[s>>2]|0)+56>>2]|0)&65535,b[(c[p>>2]|0)+18>>1]|0)|0)>>16));w=_((c[(c[s>>2]|0)+40>>2]|0)+(c[(c[s>>2]|0)+52>>2]|0)>>16,b[(c[p>>2]|0)+20>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+((_((c[(c[s>>2]|0)+40>>2]|0)+(c[(c[s>>2]|0)+52>>2]|0)&65535,b[(c[p>>2]|0)+20>>1]|0)|0)>>16));w=_((c[(c[s>>2]|0)+44>>2]|0)+(c[(c[s>>2]|0)+48>>2]|0)>>16,b[(c[p>>2]|0)+22>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+((_((c[(c[s>>2]|0)+44>>2]|0)+(c[(c[s>>2]|0)+48>>2]|0)&65535,b[(c[p>>2]|0)+22>>1]|0)|0)>>16));if(((c[u>>2]>>5)+1>>1|0)<=32767)if(((c[u>>2]>>5)+1>>1|0)<-32768)e=-32768;else e=(c[u>>2]>>5)+1>>1;else e=32767;w=c[n>>2]|0;c[n>>2]=w+2;b[w>>1]=e;c[t>>2]=(c[t>>2]|0)+(c[r>>2]|0)}w=c[n>>2]|0;i=v;return w|0}case 36:{c[t>>2]=0;while(1){if((c[t>>2]|0)>=(c[q>>2]|0))break;c[s>>2]=(c[o>>2]|0)+(c[t>>2]>>16<<2);w=_((c[c[s>>2]>>2]|0)+(c[(c[s>>2]|0)+140>>2]|0)>>16,b[c[p>>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2]|0)+72>>2]|0)>>16,b[(c[p>>2]|0)+34>>1]|0)|0;c[u>>2]=(c[u>>2]|0)+(w+((_((c[(c[s>>2]|0)+68>>2]|0)+(c[(c[s>>2]|0)+72>>2]|0)&65535,b[(c[p>>2]|0)+34>>1]|0)|0)>>16));if(((c[u>>2]>>5)+1>>1|0)<=32767)if(((c[u>>2]>>5)+1>>1|0)<-32768)e=-32768;else e=(c[u>>2]>>5)+1>>1;else e=32767;w=c[n>>2]|0;c[n>>2]=w+2;b[w>>1]=e;c[t>>2]=(c[t>>2]|0)+(c[r>>2]|0)}w=c[n>>2]|0;i=v;return w|0}default:{w=c[n>>2]|0;i=v;return w|0}}return 0}function pg(a,d,e,f){a=a|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;p=i;i=i+48|0;q=p+32|0;g=p+28|0;h=p+24|0;j=p+20|0;l=p+16|0;o=p+12|0;n=p+8|0;m=p+4|0;k=p;c[q>>2]=a;c[g>>2]=d;c[h>>2]=e;c[j>>2]=f;c[l>>2]=c[q>>2];d=(c[(c[l>>2]|0)+268>>2]<<1)+8|0;c[k>>2]=ia()|0;a=i;i=i+((1*(d<<1)|0)+15&-16)|0;d=(c[l>>2]|0)+24|0;b[a>>1]=b[d>>1]|0;b[a+2>>1]=b[d+2>>1]|0;b[a+4>>1]=b[d+4>>1]|0;b[a+6>>1]=b[d+6>>1]|0;b[a+8>>1]=b[d+8>>1]|0;b[a+10>>1]=b[d+10>>1]|0;b[a+12>>1]=b[d+12>>1]|0;b[a+14>>1]=b[d+14>>1]|0;c[m>>2]=c[(c[l>>2]|0)+272>>2];while(1){if((c[j>>2]|0)<(c[(c[l>>2]|0)+268>>2]|0))e=c[j>>2]|0;else e=c[(c[l>>2]|0)+268>>2]|0;c[o>>2]=e;rg(c[l>>2]|0,a+16|0,c[h>>2]|0,c[o>>2]|0);c[n>>2]=c[o>>2]<<17;c[g>>2]=qg(c[g>>2]|0,a,c[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)+4>>1]|0)|0);c[n>>2]=(c[n>>2]|0)+(_(b[(c[l>>2]|0)+6>>1]|0,b[25104+(c[o>>2]<<3)+6>>1]|0)|0);c[n>>2]=(c[n>>2]|0)+(_(b[(c[l>>2]|0)+8>>1]|0,b[25104+(11-(c[o>>2]|0)<<3)+6>>1]|0)|0);c[n>>2]=(c[n>>2]|0)+(_(b[(c[l>>2]|0)+10>>1]|0,b[25104+(11-(c[o>>2]|0)<<3)+4>>1]|0)|0);c[n>>2]=(c[n>>2]|0)+(_(b[(c[l>>2]|0)+12>>1]|0,b[25104+(11-(c[o>>2]|0)<<3)+2>>1]|0)|0);c[n>>2]=(c[n>>2]|0)+(_(b[(c[l>>2]|0)+14>>1]|0,b[25104+(11-(c[o>>2]|0)<<3)>>1]|0)|0);if(((c[n>>2]>>14)+1>>1|0)<=32767)if(((c[n>>2]>>14)+1>>1|0)<-32768)d=-32768;else d=(c[n>>2]>>14)+1>>1;else d=32767;a=c[g>>2]|0;c[g>>2]=a+2;b[a>>1]=d;c[m>>2]=(c[m>>2]|0)+(c[k>>2]|0)}i=p;return c[g>>2]|0}function rg(a,d,e,f){a=a|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;r=i;i=i+48|0;g=r+36|0;h=r+32|0;j=r+28|0;k=r+24|0;o=r+20|0;n=r+16|0;p=r+12|0;q=r+8|0;m=r+4|0;l=r;c[g>>2]=a;c[h>>2]=d;c[j>>2]=e;c[k>>2]=f;c[o>>2]=0;while(1){if((c[o>>2]|0)>=(c[k>>2]|0))break;c[n>>2]=b[(c[j>>2]|0)+(c[o>>2]<<1)>>1]<<10;c[m>>2]=(c[n>>2]|0)-(c[c[g>>2]>>2]|0);d=_(c[m>>2]>>16,b[12417]|0)|0;c[l>>2]=d+((_(c[m>>2]&65535,b[12417]|0)|0)>>16);c[p>>2]=(c[c[g>>2]>>2]|0)+(c[l>>2]|0);c[c[g>>2]>>2]=(c[n>>2]|0)+(c[l>>2]|0);c[m>>2]=(c[p>>2]|0)-(c[(c[g>>2]|0)+4>>2]|0);d=_(c[m>>2]>>16,b[12418]|0)|0;c[l>>2]=d+((_(c[m>>2]&65535,b[12418]|0)|0)>>16);c[q>>2]=(c[(c[g>>2]|0)+4>>2]|0)+(c[l>>2]|0);c[(c[g>>2]|0)+4>>2]=(c[p>>2]|0)+(c[l>>2]|0);c[m>>2]=(c[q>>2]|0)-(c[(c[g>>2]|0)+8>>2]|0);d=_(c[m>>2]>>16,b[12419]|0)|0;c[l>>2]=(c[m>>2]|0)+(d+((_(c[m>>2]&65535,b[12419]|0)|0)>>16));c[p>>2]=(c[(c[g>>2]|0)+8>>2]|0)+(c[l>>2]|0);c[(c[g>>2]|0)+8>>2]=(c[q>>2]|0)+(c[l>>2]|0);if(((c[p>>2]>>9)+1>>1|0)<=32767)if(((c[p>>2]>>9)+1>>1|0)<-32768)a=-32768;else a=(c[p>>2]>>9)+1>>1;else a=32767;b[(c[h>>2]|0)+(c[o>>2]<<1<<1)>>1]=a;c[m>>2]=(c[n>>2]|0)-(c[(c[g>>2]|0)+12>>2]|0);d=_(c[m>>2]>>16,b[12420]|0)|0;c[l>>2]=d+((_(c[m>>2]&65535,b[12420]|0)|0)>>16);c[p>>2]=(c[(c[g>>2]|0)+12>>2]|0)+(c[l>>2]|0);c[(c[g>>2]|0)+12>>2]=(c[n>>2]|0)+(c[l>>2]|0);c[m>>2]=(c[p>>2]|0)-(c[(c[g>>2]|0)+16>>2]|0);d=_(c[m>>2]>>16,b[12421]|0)|0;c[l>>2]=d+((_(c[m>>2]&65535,b[12421]|0)|0)>>16);c[q>>2]=(c[(c[g>>2]|0)+16>>2]|0)+(c[l>>2]|0);c[(c[g>>2]|0)+16>>2]=(c[p>>2]|0)+(c[l>>2]|0);c[m>>2]=(c[q>>2]|0)-(c[(c[g>>2]|0)+20>>2]|0);d=_(c[m>>2]>>16,b[12422]|0)|0;c[l>>2]=(c[m>>2]|0)+(d+((_(c[m>>2]&65535,b[12422]|0)|0)>>16));c[p>>2]=(c[(c[g>>2]|0)+20>>2]|0)+(c[l>>2]|0);c[(c[g>>2]|0)+20>>2]=(c[q>>2]|0)+(c[l>>2]|0);if(((c[p>>2]>>9)+1>>1|0)<=32767)if(((c[p>>2]>>9)+1>>1|0)<-32768)a=-32768;else a=(c[p>>2]>>9)+1>>1;else a=32767;b[(c[h>>2]|0)+((c[o>>2]<<1)+1<<1)>>1]=a;c[o>>2]=(c[o>>2]|0)+1}i=r;return}function sg(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0;f=i;i=i+32|0;l=f+16|0;j=f+12|0;h=f+8|0;g=f+4|0;k=f;c[l>>2]=a;c[j>>2]=b;c[h>>2]=d;c[g>>2]=e;c[k>>2]=c[l>>2];rg(c[k>>2]|0,c[j>>2]|0,c[h>>2]|0,c[g>>2]|0);i=f;return}function tg(a){a=a|0;var b=0,d=0,e=0,f=0;f=i;i=i+16|0;b=f+8|0;d=f+4|0;e=f;c[d>>2]=a;a=c[d>>2]|0;if((c[d>>2]|0)<0){c[d>>2]=0-a;if((c[d>>2]|0)>=192){c[b>>2]=0;e=c[b>>2]|0;i=f;return e|0}else{c[e>>2]=c[d>>2]>>5;c[b>>2]=(c[17960+(c[e>>2]<<2)>>2]|0)-(_((c[17984+(c[e>>2]<<2)>>2]&65535)<<16>>16,(c[d>>2]&31)<<16>>16)|0);e=c[b>>2]|0;i=f;return e|0}}else if((a|0)>=192){c[b>>2]=32767;e=c[b>>2]|0;i=f;return e|0}else{c[e>>2]=c[d>>2]>>5;c[b>>2]=(c[18008+(c[e>>2]<<2)>>2]|0)+(_((c[17984+(c[e>>2]<<2)>>2]&65535)<<16>>16,(c[d>>2]&31)<<16>>16)|0);e=c[b>>2]|0;i=f;return e|0}return 0}function ug(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0;n=i;i=i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);c[j>>2]=0;while(1){if((c[j>>2]|0)>=2)break;a=ec(c[e>>2]|0,29031,8)|0;c[g+((c[j>>2]|0)*12|0)>>2]=a;a=ec(c[e>>2]|0,29038,8)|0;c[g+((c[j>>2]|0)*12|0)+4>>2]=a;c[j>>2]=(c[j>>2]|0)+1}c[j>>2]=0;while(1){if((c[j>>2]|0)>=2)break;a=g+((c[j>>2]|0)*12|0)|0;c[a>>2]=(c[a>>2]|0)+((c[g+((c[j>>2]|0)*12|0)+8>>2]|0)*3|0);c[h>>2]=b[24526+(c[g+((c[j>>2]|0)*12|0)>>2]<<1)>>1];c[k>>2]=(((b[24526+((c[g+((c[j>>2]|0)*12|0)>>2]|0)+1<<1)>>1]|0)-(c[h>>2]|0)>>16)*6554|0)+(((b[24526+((c[g+((c[j>>2]|0)*12|0)>>2]|0)+1<<1)>>1]|0)-(c[h>>2]|0)&65535)*6554>>16);a=(c[h>>2]|0)+(_((c[k>>2]&65535)<<16>>16,((c[g+((c[j>>2]|0)*12|0)+4>>2]<<1)+1&65535)<<16>>16)|0)|0;c[(c[f>>2]|0)+(c[j>>2]<<2)>>2]=a;c[j>>2]=(c[j>>2]|0)+1}k=c[f>>2]|0;c[k>>2]=(c[k>>2]|0)-(c[(c[f>>2]|0)+4>>2]|0);i=l;return}function yg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;d=i;i=i+16|0;f=d+4|0;e=d;c[f>>2]=a;c[e>>2]=b;a=ec(c[f>>2]|0,29003,8)|0;c[c[e>>2]>>2]=a;i=d;return}function zg(b,d){b=b|0;d=d|0;var e=0,f=0,g=0,h=0;h=i;i=i+16|0;e=h+8|0;f=h+4|0;g=h;c[e>>2]=b;c[f>>2]=d;c[g>>2]=((a[(c[f>>2]|0)+2>>0]|0)*5|0)+(a[(c[f>>2]|0)+3+2>>0]|0);qc(c[e>>2]|0,c[g>>2]|0,28978,8);c[g>>2]=0;while(1){if((c[g>>2]|0)>=2)break;qc(c[e>>2]|0,a[(c[f>>2]|0)+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c[m>>2]|0)>0?w:0-w|0)|0;c[n>>2]=c[n>>2]>>1;w=c[c[p>>2]>>2]|0;v=Fg(c[k>>2]|0)|0;v=_((v<>2])-(c[c[p>>2]>>2]|0)>>16,(c[h>>2]&65535)<<16>>16)|0;u=Fg(c[k>>2]|0)|0;u=w+(v+((_((u<>2])-(c[c[p>>2]>>2]|0)&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[c[p>>2]>>2]=u;u=_(c[j>>2]>>16,(c[q>>2]&65535)<<16>>16)|0;c[l>>2]=(c[l>>2]|0)-(u+((_(c[j>>2]&65535,(c[q>>2]&65535)<<16>>16)|0)>>16)<<4);u=_(c[k>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[l>>2]=(c[l>>2]|0)+(u+((_(c[k>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16)<<6);u=c[(c[p>>2]|0)+4>>2]|0;v=Fg(c[l>>2]|0)|0;v=_((v<>2])-(c[(c[p>>2]|0)+4>>2]|0)>>16,(c[h>>2]&65535)<<16>>16)|0;w=Fg(c[l>>2]|0)|0;w=u+(v+((_((w<>2])-(c[(c[p>>2]|0)+4>>2]|0)&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[(c[p>>2]|0)+4>>2]=w;if((c[c[p>>2]>>2]|0)>1)f=c[c[p>>2]>>2]|0;else f=1;w=Dg(c[(c[p>>2]|0)+4>>2]|0,f,14)|0;c[c[o>>2]>>2]=w;if((c[c[o>>2]>>2]|0)>32767){v=32767;w=c[o>>2]|0;c[w>>2]=v;w=c[q>>2]|0;i=r;return w|0}if((c[c[o>>2]>>2]|0)<0){v=0;w=c[o>>2]|0;c[w>>2]=v;w=c[q>>2]|0;i=r;return w|0}v=c[c[o>>2]>>2]|0;w=c[o>>2]|0;c[w>>2]=v;w=c[q>>2]|0;i=r;return w|0}function Cg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Dg(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;h=i;i=i+48|0;f=h+40|0;q=h+36|0;p=h+32|0;j=h+28|0;l=h+24|0;k=h+20|0;g=h+16|0;m=h+12|0;n=h+8|0;o=h+4|0;e=h;c[q>>2]=a;c[p>>2]=b;c[j>>2]=d;b=c[q>>2]|0;c[l>>2]=(Eg((c[q>>2]|0)>0?b:0-b|0)|0)-1;c[n>>2]=c[q>>2]<>2];b=c[p>>2]|0;c[k>>2]=(Eg((c[p>>2]|0)>0?b:0-b|0)|0)-1;c[o>>2]=c[p>>2]<>2];c[m>>2]=536870911/(c[o>>2]>>16|0)|0;b=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=b+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16);b=c[n>>2]|0;a=c[o>>2]|0;d=c[e>>2]|0;d=yj(a|0,((a|0)<0)<<31>>31|0,d|0,((d|0)<0)<<31>>31|0)|0;d=nj(d|0,C|0,32)|0;c[n>>2]=b-(d<<3);d=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=(c[e>>2]|0)+(d+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16));c[g>>2]=29+(c[l>>2]|0)-(c[k>>2]|0)-(c[j>>2]|0);d=c[g>>2]|0;if((c[g>>2]|0)>=0)if((d|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];q=c[f>>2]|0;i=h;return q|0}else{c[f>>2]=0;q=c[f>>2]|0;i=h;return q|0}a=c[e>>2]|0;b=0-(c[g>>2]|0)|0;do if((-2147483648>>0-d|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>b|0)){d=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){d=2147483647>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>b|0)){d=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){d=-2147483648>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}while(0);c[f>>2]=d<<0-(c[g>>2]|0);q=c[f>>2]|0;i=h;return q|0}function Eg(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function Fg(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+32|0;b=h+16|0;d=h+12|0;g=h+8|0;f=h+4|0;e=h;c[d>>2]=a;if((c[d>>2]|0)<=0){c[b>>2]=0;g=c[b>>2]|0;i=h;return g|0}Gg(c[d>>2]|0,f,e);if(c[f>>2]&1|0)c[g>>2]=32768;else c[g>>2]=46214;c[g>>2]=c[g>>2]>>(c[f>>2]>>1);a=_(c[g>>2]>>16,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0;c[g>>2]=(c[g>>2]|0)+(a+((_(c[g>>2]&65535,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0)>>16));c[b>>2]=c[g>>2];g=c[b>>2]|0;i=h;return g|0}function Gg(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;e=i;i=i+16|0;h=e+12|0;j=e+8|0;f=e+4|0;g=e;c[h>>2]=a;c[j>>2]=b;c[f>>2]=d;c[g>>2]=Eg(c[h>>2]|0)|0;c[c[j>>2]>>2]=c[g>>2];b=(Hg(c[h>>2]|0,24-(c[g>>2]|0)|0)|0)&127;c[c[f>>2]>>2]=b;i=e;return}function Hg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+20|0;d=k+16|0;f=k+12|0;j=k+8|0;h=k+4|0;g=k;c[d>>2]=a;c[f>>2]=b;c[j>>2]=c[d>>2];c[h>>2]=c[f>>2];c[g>>2]=0-(c[f>>2]|0);if(!(c[f>>2]|0)){c[e>>2]=c[d>>2];j=c[e>>2]|0;i=k;return j|0}d=c[j>>2]|0;if((c[f>>2]|0)<0){c[e>>2]=d<>2]|(c[j>>2]|0)>>>(32-(c[g>>2]|0)|0);j=c[e>>2]|0;i=k;return j|0}else{c[e>>2]=d<<32-(c[h>>2]|0)|(c[j>>2]|0)>>>(c[h>>2]|0);j=c[e>>2]|0;i=k;return j|0}return 0}function Ig(d,e){d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;r=i;i=i+48|0;f=r+40|0;g=r+36|0;k=r+32|0;l=r+28|0;o=r+24|0;m=r+20|0;q=r+16|0;n=r+12|0;j=r+8|0;h=r+4|0;p=r;c[f>>2]=d;c[g>>2]=e;c[p>>2]=0;c[o>>2]=0;while(1){if((c[o>>2]|0)>=2)break;c[j>>2]=2147483647;c[k>>2]=0;a:while(1){if((c[k>>2]|0)>=15)break;c[m>>2]=b[24526+(c[k>>2]<<1)>>1];c[q>>2]=(((b[24526+((c[k>>2]|0)+1<<1)>>1]|0)-(c[m>>2]|0)>>16)*6554|0)+(((b[24526+((c[k>>2]|0)+1<<1)>>1]|0)-(c[m>>2]|0)&65535)*6554>>16);c[l>>2]=0;while(1){if((c[l>>2]|0)>=5)break;c[n>>2]=(c[m>>2]|0)+(_((c[q>>2]&65535)<<16>>16,((c[l>>2]<<1)+1&65535)<<16>>16)|0);d=(c[(c[f>>2]|0)+(c[o>>2]<<2)>>2]|0)-(c[n>>2]|0)|0;c[h>>2]=((c[(c[f>>2]|0)+(c[o>>2]<<2)>>2]|0)-(c[n>>2]|0)|0)>0?d:0-d|0;if((c[h>>2]|0)>=(c[j>>2]|0))break a;c[j>>2]=c[h>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c[d>>2]|0)+5128+2|0)|0;b=c[d>>2]|0;if((c[(c[d>>2]|0)+4556>>2]|0)>=13){c[b+6116>>2]=0;c[(c[d>>2]|0)+6112>>2]=0;a[(c[d>>2]|0)+4768+29>>0]=1;a[(c[d>>2]|0)+4752+(c[(c[d>>2]|0)+5780>>2]|0)>>0]=1;i=e;return}a[b+4768+29>>0]=0;b=(c[d>>2]|0)+6116|0;c[b>>2]=(c[b>>2]|0)+1;b=c[d>>2]|0;if((c[(c[d>>2]|0)+6116>>2]|0)>=10){if((c[b+6116>>2]|0)>30){c[(c[d>>2]|0)+6116>>2]=10;c[(c[d>>2]|0)+6112>>2]=0}}else c[b+6112>>2]=0;a[(c[d>>2]|0)+4752+(c[(c[d>>2]|0)+5780>>2]|0)>>0]=0;i=e;return}function Ng(d,e,f,h,j,k){d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;var l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0;X=i;i=i+15152|0;o=X+13856|0;p=X+13852|0;q=X+13848|0;r=X+13844|0;s=X+13840|0;t=X+13836|0;u=X+13832|0;Q=X+12920|0;I=X+12916|0;J=X+12912|0;K=X+12908|0;A=X+12904|0;z=X+12900|0;P=X+12896|0;n=X+12892|0;m=X+12888|0;W=X+11608|0;l=X+8920|0;T=X+8872|0;U=X+8824|0;R=X+4444|0;S=X+64|0;V=X+60|0;L=X+56|0;M=X+52|0;N=X+48|0;C=X+44|0;D=X+40|0;F=X+36|0;G=X+32|0;H=X+28|0;B=X+13862|0;x=X+13860|0;y=X+24|0;v=X+15139|0;O=X+8|0;w=X+13864|0;E=X;c[p>>2]=d;c[q>>2]=e;c[r>>2]=f;c[s>>2]=h;c[t>>2]=j;c[u>>2]=k;c[P>>2]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>2]|0)+4768+34>>0];b[x>>1]=b[(c[p>>2]|0)+5804>>1]|0;c[y>>2]=c[(c[p>>2]|0)+5800>>2];c[J>>2]=0;while(1){do if((c[F>>2]|0)!=(c[G>>2]|0)){if((c[F>>2]|0)==(c[H>>2]|0)){c[L>>2]=c[N>>2];break}if((c[J>>2]|0)>0){h=c[r>>2]|0;j=T;e=h+48|0;do{c[h>>2]=c[j>>2];h=h+4|0;j=j+4|0}while((h|0)<(e|0));pj((c[p>>2]|0)+144|0,R|0,4380)|0;a[(c[p>>2]|0)+4768+34>>0]=c[V>>2];b[(c[p>>2]|0)+5804>>1]=b[x>>1]|0;c[(c[p>>2]|0)+5800>>2]=c[y>>2]}Bh(c[p>>2]|0,Q,(c[p>>2]|0)+4768|0,(c[p>>2]|0)+144|0,(c[p>>2]|0)+4804|0,W);Xd(c[p>>2]|0,c[r>>2]|0,c[(c[p>>2]|0)+5780>>2]|0,0,c[s>>2]|0);Yd(c[r>>2]|0,a[(c[p>>2]|0)+4768+29>>0]|0,a[(c[p>>2]|0)+4768+30>>0]|0,(c[p>>2]|0)+4804|0,c[(c[p>>2]|0)+4608>>2]|0);c[L>>2]=Rg(c[r>>2]|0)|0;if((c[u>>2]|0)==0&(c[J>>2]|0)==0?(c[L>>2]|0)<=(c[t>>2]|0):0)break a}else c[L>>2]=c[M>>2];while(0);if((c[J>>2]|0)==(c[K>>2]|0))break;do if((c[L>>2]|0)>(c[t>>2]|0))if((c[z>>2]|0)==0&(c[J>>2]|0)>=2){n=Q+852|0;g[n>>2]=+g[n>>2]*1.5;c[A>>2]=0;c[H>>2]=-1;break}else{c[A>>2]=1;c[N>>2]=c[L>>2];c[D>>2]=b[B>>1];c[H>>2]=c[F>>2];break}else{if((c[L>>2]|0)>=((c[t>>2]|0)-5|0))break a;c[z>>2]=1;c[M>>2]=c[L>>2];c[C>>2]=b[B>>1];if((c[F>>2]|0)!=(c[G>>2]|0)){c[G>>2]=c[F>>2];h=U;j=c[r>>2]|0;e=h+48|0;do{c[h>>2]=c[j>>2];h=h+4|0;j=j+4|0}while((h|0)<(e|0));pj(w|0,c[c[r>>2]>>2]|0,c[(c[r>>2]|0)+24>>2]|0)|0;pj(S|0,(c[p>>2]|0)+144|0,4380)|0;a[v>>0]=a[(c[p>>2]|0)+7200>>0]|0}}while(0);do if(c[z>>2]&c[A>>2]){n=_((c[D>>2]|0)-(c[C>>2]|0)|0,(c[t>>2]|0)-(c[M>>2]|0)|0)|0;b[B>>1]=(c[C>>2]|0)+((n|0)/((c[N>>2]|0)-(c[M>>2]|0)|0)|0);if((b[B>>1]|0)>((c[C>>2]|0)+((c[D>>2]|0)-(c[C>>2]|0)>>2)|0)){b[B>>1]=(c[C>>2]|0)+((c[D>>2]|0)-(c[C>>2]|0)>>2);break}if((b[B>>1]|0)<((c[D>>2]|0)-((c[D>>2]|0)-(c[C>>2]|0)>>2)|0))b[B>>1]=(c[D>>2]|0)-((c[D>>2]|0)-(c[C>>2]|0)>>2)}else{c[E>>2]=Wf((((c[L>>2]|0)-(c[t>>2]|0)<<7|0)/(c[(c[p>>2]|0)+4608>>2]|0)|0)+2048|0)|0;c[E>>2]=Sg(c[E>>2]|0,131072)|0;if((c[L>>2]|0)>(c[t>>2]|0))c[E>>2]=Tg(c[E>>2]|0,85197)|0;n=_(c[E>>2]>>16,b[B>>1]|0)|0;b[B>>1]=n+((_(c[E>>2]&65535,b[B>>1]|0)|0)>>16)}while(0);c[I>>2]=0;while(1){if((c[I>>2]|0)>=(c[(c[p>>2]|0)+4604>>2]|0))break;n=_(c[Q+892+(c[I>>2]<<2)>>2]>>16,b[B>>1]|0)|0;if((n+((_(c[Q+892+(c[I>>2]<<2)>>2]&65535,b[B>>1]|0)|0)>>16)|0)<=8388607){n=_(c[Q+892+(c[I>>2]<<2)>>2]>>16,b[B>>1]|0)|0;if((n+((_(c[Q+892+(c[I>>2]<<2)>>2]&65535,b[B>>1]|0)|0)>>16)|0)<-8388608)h=-8388608;else{h=_(c[Q+892+(c[I>>2]<<2)>>2]>>16,b[B>>1]|0)|0;h=h+((_(c[Q+892+(c[I>>2]<<2)>>2]&65535,b[B>>1]|0)|0)>>16)|0}}else h=8388607;c[O+(c[I>>2]<<2)>>2]=h<<8;c[I>>2]=(c[I>>2]|0)+1}a[(c[p>>2]|0)+7200>>0]=a[Q+908>>0]|0;_d((c[p>>2]|0)+4768|0,O,(c[p>>2]|0)+7200|0,(c[s>>2]|0)==2&1,c[(c[p>>2]|0)+4604>>2]|0);c[F>>2]=ce((c[p>>2]|0)+4768|0,c[(c[p>>2]|0)+4604>>2]|0)|0;c[I>>2]=0;while(1){if((c[I>>2]|0)>=(c[(c[p>>2]|0)+4604>>2]|0))break;g[Q+(c[I>>2]<<2)>>2]=+(c[O+(c[I>>2]<<2)>>2]|0)/65536.0;c[I>>2]=(c[I>>2]|0)+1}c[J>>2]=(c[J>>2]|0)+1}if(c[z>>2]|0){if((c[F>>2]|0)!=(c[G>>2]|0)?(c[L>>2]|0)<=(c[t>>2]|0):0)break;h=c[r>>2]|0;j=U;e=h+48|0;do{c[h>>2]=c[j>>2];h=h+4|0;j=j+4|0}while((h|0)<(e|0));pj(c[c[r>>2]>>2]|0,w|0,c[U+24>>2]|0)|0;pj((c[p>>2]|0)+144|0,S|0,4380)|0;a[(c[p>>2]|0)+7200>>0]=a[v>>0]|0}}while(0);qj((c[p>>2]|0)+9356|0,(c[p>>2]|0)+9356+(c[(c[p>>2]|0)+4608>>2]<<2)|0,(c[(c[p>>2]|0)+4616>>2]|0)+((c[(c[p>>2]|0)+4600>>2]|0)*5|0)<<2|0)|0;if(c[(c[p>>2]|0)+4712>>2]|0){c[c[q>>2]>>2]=0;c[o>>2]=c[P>>2];W=c[o>>2]|0;i=X;return W|0}else{c[(c[p>>2]|0)+4568>>2]=c[Q+228+((c[(c[p>>2]|0)+4604>>2]|0)-1<<2)>>2];a[(c[p>>2]|0)+4565>>0]=a[(c[p>>2]|0)+4768+29>>0]|0;c[(c[p>>2]|0)+4696>>2]=0;W=(Rg(c[r>>2]|0)|0)+7>>3;c[c[q>>2]>>2]=W;c[o>>2]=c[P>>2];W=c[o>>2]|0;i=X;return W|0}return 0}function Og(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0;k=i;i=i+16|0;f=k+12|0;h=k+8|0;l=k+4|0;j=k;c[f>>2]=a;c[h>>2]=d;c[l>>2]=e;c[j>>2]=(c[l>>2]|0)-1;while(1){if((c[j>>2]|0)<0)break;g[(c[f>>2]|0)+(c[j>>2]<<2)>>2]=+(b[(c[h>>2]|0)+(c[j>>2]<<1)>>1]|0);c[j>>2]=(c[j>>2]|0)+-1}i=k;return}function Pg(d,e,f,h){d=d|0;e=e|0;f=f|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0;s=i;i=i+4448|0;j=s+4432|0;k=s+4428|0;l=s+4424|0;m=s+4420|0;p=s+4416|0;n=s+4400|0;o=s+4384|0;q=s+4380|0;r=s;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;c[m>>2]=h;c[q>>2]=(c[j>>2]|0)+6132+((c[(c[j>>2]|0)+5780>>2]|0)*36|0);if(!(c[(c[j>>2]|0)+6124>>2]|0)){i=s;return}if((c[(c[j>>2]|0)+4556>>2]|0)<=77){i=s;return}c[(c[j>>2]|0)+4756+(c[(c[j>>2]|0)+5780>>2]<<2)>>2]=1;pj(r|0,(c[j>>2]|0)+144|0,4380)|0;h=c[q>>2]|0;d=(c[j>>2]|0)+4768|0;e=h+36|0;do{b[h>>1]=b[d>>1]|0;h=h+2|0;d=d+2|0}while((h|0)<(e|0));pj(o|0,c[k>>2]|0,c[(c[j>>2]|0)+4604>>2]<<2|0)|0;if(!((c[(c[j>>2]|0)+5780>>2]|0)!=0?(c[(c[j>>2]|0)+4756+((c[(c[j>>2]|0)+5780>>2]|0)-1<<2)>>2]|0)!=0:0)){a[(c[j>>2]|0)+4564>>0]=a[(c[j>>2]|0)+7200>>0]|0;f=c[q>>2]|0;a[f>>0]=(a[f>>0]|0)+(c[(c[j>>2]|0)+6128>>2]|0);f=(Qg(a[c[q>>2]>>0]|0,63)|0)&255;a[c[q>>2]>>0]=f}ae(n,c[q>>2]|0,(c[j>>2]|0)+4564|0,(c[m>>2]|0)==2&1,c[(c[j>>2]|0)+4604>>2]|0);c[p>>2]=0;while(1){if((c[p>>2]|0)>=(c[(c[j>>2]|0)+4604>>2]|0))break;g[(c[k>>2]|0)+(c[p>>2]<<2)>>2]=+(c[n+(c[p>>2]<<2)>>2]|0)*.0000152587890625;c[p>>2]=(c[p>>2]|0)+1}Bh(c[j>>2]|0,c[k>>2]|0,c[q>>2]|0,r,(c[j>>2]|0)+6240+((c[(c[j>>2]|0)+5780>>2]|0)*320|0)|0,c[l>>2]|0);pj(c[k>>2]|0,o|0,c[(c[j>>2]|0)+4604>>2]<<2|0)|0;i=s;return}function Qg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Rg(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;a=(c[(c[d>>2]|0)+20>>2]|0)-(32-(aa(c[(c[d>>2]|0)+28>>2]|0)|0))|0;i=b;return a|0}function Sg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Tg(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Ug(b,d,e,f){b=b|0;d=d|0;e=e|0;f=+f;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;v=i;i=i+1744|0;j=v+1700|0;k=v+1696|0;l=v+1692|0;h=v+1688|0;q=v+1684|0;u=v+1680|0;o=v+1616|0;r=v+1608|0;s=v+1604|0;t=v+1600|0;n=v+1704|0;p=v+1536|0;m=v;c[j>>2]=b;c[k>>2]=d;c[l>>2]=e;g[h>>2]=f;c[u>>2]=(c[(c[j>>2]|0)+4612>>2]|0)+(c[(c[j>>2]|0)+4664>>2]|0);a[(c[j>>2]|0)+4768+31>>0]=4;g[r>>2]=+Eh(o,c[l>>2]|0,+g[h>>2],c[u>>2]|0,c[(c[j>>2]|0)+4604>>2]|0,c[(c[j>>2]|0)+4664>>2]|0);a:do if((c[(c[j>>2]|0)+4656>>2]|0?(c[(c[j>>2]|0)+4696>>2]|0)==0:0)?(c[(c[j>>2]|0)+4604>>2]|0)==4:0){f=+Eh(p,(c[l>>2]|0)+(c[u>>2]<<1<<2)|0,+g[h>>2],c[u>>2]|0,2,c[(c[j>>2]|0)+4664>>2]|0);g[r>>2]=+g[r>>2]-f;xh(c[k>>2]|0,p,c[(c[j>>2]|0)+4664>>2]|0);g[s>>2]=3402823466385288598117041.0e14;c[q>>2]=3;while(1){if((c[q>>2]|0)<0)break a;de(n,(c[j>>2]|0)+4524|0,c[k>>2]|0,c[q>>2]|0,c[(c[j>>2]|0)+4664>>2]|0);zh(p,n,c[(c[j>>2]|0)+4664>>2]|0);Zg(m,p,c[l>>2]|0,c[u>>2]<<1,c[(c[j>>2]|0)+4664>>2]|0);f=+Gh(m+(c[(c[j>>2]|0)+4664>>2]<<2)|0,(c[u>>2]|0)-(c[(c[j>>2]|0)+4664>>2]|0)|0);g[t>>2]=f+ +Gh(m+(c[(c[j>>2]|0)+4664>>2]<<2)+(c[u>>2]<<2)|0,(c[u>>2]|0)-(c[(c[j>>2]|0)+4664>>2]|0)|0);f=+g[t>>2];if(!(+g[t>>2]<+g[r>>2])){if(f>+g[s>>2])break a}else{g[r>>2]=f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96>>2];g[z>>2]=+g[z>>2]*.01666666753590107;ph(c[v>>2]|0,A+(c[H>>2]<<2)|0,+g[z>>2],5);sh(c[v>>2]|0,5,u,c[C>>2]|0);m=+qh(c[C>>2]|0,c[v>>2]|0,u,+g[A+(c[H>>2]<<2)>>2],5);g[x+(c[H>>2]<<2)>>2]=m;g[J>>2]=+g[(c[q>>2]|0)+(c[H>>2]<<2)>>2]/(+g[x+(c[H>>2]<<2)>>2]*+g[(c[q>>2]|0)+(c[H>>2]<<2)>>2]+ +(c[r>>2]|0)*.009999999776482582);Uh(c[v>>2]|0,+g[J>>2],25);g[K+(c[H>>2]<<2)>>2]=+g[(c[v>>2]|0)+48>>2];c[y>>2]=(c[y>>2]|0)+(c[r>>2]<<2);c[C>>2]=(c[C>>2]|0)+20;c[v>>2]=(c[v>>2]|0)+100;c[H>>2]=(c[H>>2]|0)+1}if(c[o>>2]|0){g[s>>2]=9.999999974752427e-07;g[t>>2]=0.0;c[H>>2]=0;while(1){if((c[H>>2]|0)>=(c[B>>2]|0))break;g[t>>2]=+g[t>>2]+ +g[A+(c[H>>2]<<2)>>2]*+g[(c[q>>2]|0)+(c[H>>2]<<2)>>2];g[s>>2]=+g[s>>2]+ +g[x+(c[H>>2]<<2)>>2]*+g[(c[q>>2]|0)+(c[H>>2]<<2)>>2];c[H>>2]=(c[H>>2]|0)+1}m=+Wg(+g[t>>2]/+g[s>>2])*3.0;g[c[o>>2]>>2]=m}c[C>>2]=c[n>>2];c[H>>2]=0;while(1){if((c[H>>2]|0)>=(c[B>>2]|0))break;g[D+(c[H>>2]<<2)>>2]=0.0;c[G>>2]=0;while(1){if((c[G>>2]|0)>=5)break;O=D+(c[H>>2]<<2)|0;g[O>>2]=+g[O>>2]+ +g[(c[C>>2]|0)+(c[G>>2]<<2)>>2];c[G>>2]=(c[G>>2]|0)+1}c[C>>2]=(c[C>>2]|0)+20;c[H>>2]=(c[H>>2]|0)+1}g[J>>2]=1.0000000474974513e-03;c[H>>2]=0;while(1){if((c[H>>2]|0)>=(c[B>>2]|0))break;g[J>>2]=+g[J>>2]+ +g[K+(c[H>>2]<<2)>>2];c[H>>2]=(c[H>>2]|0)+1}g[I>>2]=0.0;c[H>>2]=0;while(1){if((c[H>>2]|0)>=(c[B>>2]|0))break;g[I>>2]=+g[I>>2]+ +g[D+(c[H>>2]<<2)>>2]*+g[K+(c[H>>2]<<2)>>2];c[H>>2]=(c[H>>2]|0)+1}g[I>>2]=+g[I>>2]/+g[J>>2];c[C>>2]=c[n>>2];c[H>>2]=0;while(1){if((c[H>>2]|0)>=(c[B>>2]|0))break;g[F>>2]=.10000000149011612/(+g[K+(c[H>>2]<<2)>>2]+.10000000149011612)*(+g[I>>2]-+g[D+(c[H>>2]<<2)>>2]);g[J>>2]=0.0;c[G>>2]=0;while(1){if((c[G>>2]|0)>=5)break;if(+g[(c[C>>2]|0)+(c[G>>2]<<2)>>2]>.10000000149011612)m=+g[(c[C>>2]|0)+(c[G>>2]<<2)>>2];else m=.10000000149011612;g[E+(c[G>>2]<<2)>>2]=m;g[J>>2]=+g[J>>2]+ +g[E+(c[G>>2]<<2)>>2];c[G>>2]=(c[G>>2]|0)+1}g[J>>2]=+g[F>>2]/+g[J>>2];c[G>>2]=0;while(1){if((c[G>>2]|0)>=5)break;g[(c[C>>2]|0)+(c[G>>2]<<2)>>2]=+g[(c[C>>2]|0)+(c[G>>2]<<2)>>2]+ +g[E+(c[G>>2]<<2)>>2]*+g[J>>2];c[G>>2]=(c[G>>2]|0)+1}c[C>>2]=(c[C>>2]|0)+20;c[H>>2]=(c[H>>2]|0)+1}i=L;return}function Wg(a){a=+a;var b=0,c=0;b=i;i=i+16|0;c=b;h[c>>3]=a;a=+hj(+h[c>>3])*3.32192809488736;i=b;return +a}function Xg(d,e,f,h,j){d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0;p=i;i=i+1792|0;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+4672>>2]|0);Fh(s,c[(c[k>>2]|0)+4672>>2]|0,.9900000095367432);Zg(c[m>>2]|0,s,c[r>>2]|0,c[q>>2]|0,c[(c[k>>2]|0)+4672>>2]|0);if(a[(c[k>>2]|0)+4768+29>>0]|0?(c[(c[k>>2]|0)+4696>>2]|0)==0:0){g[o>>2]=.6000000238418579;g[o>>2]=+g[o>>2]-+(c[(c[k>>2]|0)+4672>>2]|0)*.004000000189989805;g[o>>2]=+g[o>>2]-+(c[(c[k>>2]|0)+4556>>2]|0)*.10000000149011612*.00390625;g[o>>2]=+g[o>>2]-+(a[(c[k>>2]|0)+4565>>0]>>1|0)*.15000000596046448;g[o>>2]=+g[o>>2]-+(c[(c[k>>2]|0)+4744>>2]|0)*.10000000149011612*.000030517578125;z=(Lh(c[m>>2]|0,(c[l>>2]|0)+228|0,(c[k>>2]|0)+4768+26|0,(c[k>>2]|0)+4768+28|0,(c[k>>2]|0)+12236|0,c[(c[k>>2]|0)+4568>>2]|0,+(c[(c[k>>2]|0)+4676>>2]|0)/65536.0,+g[o>>2],c[(c[k>>2]|0)+4600>>2]|0,c[(c[k>>2]|0)+4668>>2]|0,c[(c[k>>2]|0)+4604>>2]|0,c[n>>2]|0)|0)==0;k=(c[k>>2]|0)+4768+29|0;if(z){a[k>>0]=2;i=p;return}else{a[k>>0]=1;i=p;return}}z=(c[l>>2]|0)+228|0;c[z>>2]=0;c[z+4>>2]=0;c[z+8>>2]=0;c[z+12>>2]=0;b[(c[k>>2]|0)+4768+26>>1]=0;a[(c[k>>2]|0)+4768+28>>0]=0;g[(c[k>>2]|0)+12236>>2]=0.0;i=p;return}function Yg(d,e,f,h,j){d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0.0;y=i;i=i+2048|0;l=y+2004|0;m=y+2e3|0;n=y+1996|0;o=y+1992|0;p=y+1988|0;t=y+1984|0;r=y+1584|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m+4524|0;l=m+32|0;do{b[m>>1]=b[k>>1]|0;m=m+2|0;k=k+2|0}while((m|0)<(l|0));i=y;return}}function Zg(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;g=m+16|0;h=m+12|0;j=m+8|0;k=m+4|0;l=m;c[g>>2]=a;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;switch(c[l>>2]|0){case 6:{_g(c[g>>2]|0,c[h>>2]|0,c[j>>2]|0,c[k>>2]|0);break}case 8:{$g(c[g>>2]|0,c[h>>2]|0,c[j>>2]|0,c[k>>2]|0);break}case 10:{ah(c[g>>2]|0,c[h>>2]|0,c[j>>2]|0,c[k>>2]|0);break}case 12:{bh(c[g>>2]|0,c[h>>2]|0,c[j>>2]|0,c[k>>2]|0);break}case 16:{ch(c[g>>2]|0,c[h>>2]|0,c[j>>2]|0,c[k>>2]|0);break}default:{}}oj(c[g>>2]|0,0,c[l>>2]<<2|0)|0;i=m;return}function _g(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0;o=i;i=i+32|0;f=o+24|0;h=o+20|0;j=o+16|0;k=o+12|0;m=o+8|0;l=o+4|0;n=o;c[f>>2]=a;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;c[m>>2]=6;while(1){if((c[m>>2]|0)>=(c[k>>2]|0))break;c[n>>2]=(c[j>>2]|0)+((c[m>>2]|0)-1<<2);g[l>>2]=+g[c[n>>2]>>2]*+g[c[h>>2]>>2]+ +g[(c[n>>2]|0)+-4>>2]*+g[(c[h>>2]|0)+4>>2]+ +g[(c[n>>2]|0)+-8>>2]*+g[(c[h>>2]|0)+8>>2]+ +g[(c[n>>2]|0)+-12>>2]*+g[(c[h>>2]|0)+12>>2]+ +g[(c[n>>2]|0)+-16>>2]*+g[(c[h>>2]|0)+16>>2]+ +g[(c[n>>2]|0)+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c[t>>2]=(c[t>>2]|0)+1}c[t>>2]=0;while(1){if((c[t>>2]|0)>=((c[o>>2]|0)+(c[q>>2]|0)|0))break;g[(c[s>>2]|0)+(c[t>>2]<<2)>>2]=+g[(c[y>>2]|0)+(c[t>>2]<<2)>>2];c[v>>2]=0;while(1){if((c[v>>2]|0)>=5)break;B=(c[s>>2]|0)+(c[t>>2]<<2)|0;g[B>>2]=+g[B>>2]-+g[r+(c[v>>2]<<2)>>2]*+g[(c[x>>2]|0)+(2-(c[v>>2]|0)<<2)>>2];c[v>>2]=(c[v>>2]|0)+1}B=(c[s>>2]|0)+(c[t>>2]<<2)|0;g[B>>2]=+g[B>>2]*+g[u>>2];c[x>>2]=(c[x>>2]|0)+4;c[t>>2]=(c[t>>2]|0)+1}c[s>>2]=(c[s>>2]|0)+((c[o>>2]|0)+(c[q>>2]|0)<<2);c[y>>2]=(c[y>>2]|0)+(c[o>>2]<<2);c[w>>2]=(c[w>>2]|0)+1}i=z;return}function eh(d,e,f){d=d|0;e=e|0;f=f|0;var h=0.0,j=0,k=0,l=0,m=0,n=0;m=i;i=i+16|0;k=m+12|0;l=m+8|0;n=m+4|0;j=m;c[k>>2]=d;c[l>>2]=e;c[n>>2]=f;f=c[k>>2]|0;if(!(c[n>>2]|0)){c[j>>2]=(c[f+4640>>2]|0)+(c[(c[k>>2]|0)+5776>>2]|0);if(!(+(c[j>>2]|0)*+g[(c[l>>2]|0)+872>>2]*.10000000149011612>2.0))if(+(c[j>>2]|0)*+g[(c[l>>2]|0)+872>>2]*.10000000149011612<0.0)h=0.0;else h=+(c[j>>2]|0)*+g[(c[l>>2]|0)+872>>2]*.10000000149011612;else h=2.0;a[(c[k>>2]|0)+4768+33>>0]=~~h}else a[f+4768+33>>0]=0;g[(c[l>>2]|0)+224>>2]=+(b[24566+(a[(c[k>>2]|0)+4768+33>>0]<<1)>>1]|0)/16384.0;i=m;return}function fh(b,d,e,f){b=b|0;d=d|0;e=e|0;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,Q=0.0,R=0;M=i;i=i+1152|0;D=M+1140|0;E=M+1136|0;h=M+1132|0;R=M+1128|0;K=M+1124|0;J=M+1120|0;m=M+1116|0;q=M+1112|0;F=M+1108|0;G=M+1104|0;H=M+1100|0;w=M+1096|0;x=M+1092|0;k=M+1088|0;l=M+1084|0;j=M+1080|0;s=M+1076|0;o=M+1072|0;p=M+1068|0;v=M+1064|0;u=M+1060|0;L=M+1056|0;I=M+1052|0;A=M+1048|0;C=M+88|0;r=M+20|0;B=M+16|0;n=M+12|0;y=M+8|0;z=M+4|0;t=M;c[D>>2]=b;c[E>>2]=d;c[h>>2]=e;c[R>>2]=f;c[K>>2]=(c[D>>2]|0)+7200;c[B>>2]=(c[R>>2]|0)+(0-(c[(c[D>>2]|0)+4624>>2]|0)<<2);g[q>>2]=+(c[(c[D>>2]|0)+4748>>2]|0)*.0078125;g[(c[E>>2]|0)+856>>2]=+((c[(c[D>>2]|0)+4728>>2]|0)+(c[(c[D>>2]|0)+4728+4>>2]|0)|0)*.5*.000030517578125;Q=+gh((+g[q>>2]-20.0)*.25);g[(c[E>>2]|0)+860>>2]=Q;if(!(c[(c[D>>2]|0)+4708>>2]|0)){g[I>>2]=1.0-+(c[(c[D>>2]|0)+4556>>2]|0)*.00390625;g[q>>2]=+g[q>>2]-+g[(c[E>>2]|0)+860>>2]*2.0*(+g[(c[E>>2]|0)+856>>2]*.5+.5)*+g[I>>2]*+g[I>>2]}e=c[D>>2]|0;if((a[(c[D>>2]|0)+4768+29>>0]|0)==2)g[q>>2]=+g[q>>2]+ +g[e+12236>>2]*2.0;else g[q>>2]=+g[q>>2]+(+(c[e+4748>>2]|0)*-.4000000059604645*.0078125+6.0)*(1.0-+g[(c[E>>2]|0)+856>>2]);e=c[D>>2]|0;if((a[(c[D>>2]|0)+4768+29>>0]|0)==2){a[e+4768+30>>0]=0;g[(c[E>>2]|0)+864>>2]=0.0}else{c[m>>2]=c[e+4600>>2]<<1;g[j>>2]=0.0;g[l>>2]=0.0;c[n>>2]=c[h>>2];c[J>>2]=0;while(1){if((c[J>>2]|0)>=((((c[(c[D>>2]|0)+4604>>2]&65535)<<16>>16)*5|0)/2|0|0))break;Q=+(c[m>>2]|0);g[w>>2]=Q+ +Gh(c[n>>2]|0,c[m>>2]|0);g[k>>2]=+hh(+g[w>>2]);if((c[J>>2]|0)>0){Q=+N(+(+g[k>>2]-+g[l>>2]));g[j>>2]=+g[j>>2]+Q}g[l>>2]=+g[k>>2];c[n>>2]=(c[n>>2]|0)+(c[m>>2]<<2);c[J>>2]=(c[J>>2]|0)+1}Q=+gh((+g[j>>2]-5.0)*.4000000059604645);g[(c[E>>2]|0)+864>>2]=Q;e=(c[D>>2]|0)+4768+30|0;if(+g[(c[E>>2]|0)+864>>2]>.75)a[e>>0]=0;else a[e>>0]=1;g[q>>2]=+g[q>>2]+(+g[(c[E>>2]|0)+864>>2]-.5)*2.0}g[L>>2]=+g[(c[E>>2]|0)+868>>2]*1.0000000474974513e-03;Q=.949999988079071/(+g[L>>2]*+g[L>>2]+1.0);g[p>>2]=Q;g[o>>2]=Q;g[s>>2]=(1.0-+g[(c[E>>2]|0)+860>>2]*.75)*.009999999776482582;g[o>>2]=+g[o>>2]-+g[s>>2];g[p>>2]=+g[p>>2]+ +g[s>>2];g[o>>2]=+g[o>>2]/+g[p>>2];if((c[(c[D>>2]|0)+4704>>2]|0)>0)g[A>>2]=+(c[(c[D>>2]|0)+4704>>2]|0)/65536.0+ +g[(c[E>>2]|0)+860>>2]*.009999999776482582;else g[A>>2]=0.0;c[J>>2]=0;while(1){if((c[J>>2]|0)>=(c[(c[D>>2]|0)+4604>>2]|0))break;c[t>>2]=(c[(c[D>>2]|0)+4600>>2]|0)*3;c[z>>2]=((c[(c[D>>2]|0)+4628>>2]|0)-(c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E>>2]|0)+244+(c[J>>2]<<4<<2)|0,c[(c[D>>2]|0)+4660>>2]|0);g[(c[E>>2]|0)+788+(c[J>>2]<<2)>>2]=1.0-(1.0-+g[x>>2]/+g[w>>2])*.699999988079071;jh((c[E>>2]|0)+500+(c[J>>2]<<4<<2)|0,(c[E>>2]|0)+244+(c[J>>2]<<4<<2)|0,+g[A>>2],3.999000072479248,c[(c[D>>2]|0)+4660>>2]|0);c[J>>2]=(c[J>>2]|0)+1}g[v>>2]=+P(2.0,+(+g[q>>2]*-.1599999964237213));g[u>>2]=+P(2.0,.3199999928474426);c[J>>2]=0;while(1){if((c[J>>2]|0)>=(c[(c[D>>2]|0)+4604>>2]|0))break;R=(c[E>>2]|0)+(c[J>>2]<<2)|0;g[R>>2]=+g[R>>2]*+g[v>>2];R=(c[E>>2]|0)+(c[J>>2]<<2)|0;g[R>>2]=+g[R>>2]+ +g[u>>2];c[J>>2]=(c[J>>2]|0)+1}g[v>>2]=+g[(c[E>>2]|0)+860>>2]*.10000000149011612+1.0499999523162842;c[J>>2]=0;while(1){if((c[J>>2]|0)>=(c[(c[D>>2]|0)+4604>>2]|0))break;R=(c[E>>2]|0)+788+(c[J>>2]<<2)|0;g[R>>2]=+g[R>>2]*+g[v>>2];c[J>>2]=(c[J>>2]|0)+1}g[L>>2]=((+(c[(c[D>>2]|0)+4728>>2]|0)*.000030517578125-1.0)*.5+1.0)*4.0;g[L>>2]=+g[L>>2]*(+(c[(c[D>>2]|0)+4556>>2]|0)*.00390625);if((a[(c[D>>2]|0)+4768+29>>0]|0)==2){c[J>>2]=0;while(1){e=c[D>>2]|0;if((c[J>>2]|0)>=(c[(c[D>>2]|0)+4604>>2]|0))break;g[I>>2]=.20000000298023224/+(c[e+4600>>2]|0)+3.0/+(c[(c[E>>2]|0)+228+(c[J>>2]<<2)>>2]|0);g[(c[E>>2]|0)+756+(c[J>>2]<<2)>>2]=+g[I>>2]+-1.0;g[(c[E>>2]|0)+772+(c[J>>2]<<2)>>2]=1.0-+g[I>>2]-+g[I>>2]*+g[L>>2];c[J>>2]=(c[J>>2]|0)+1}g[H>>2]=-.25-+(c[e+4556>>2]|0)*.26249998807907104*.00390625}else{g[I>>2]=1.2999999523162842/+(c[(c[D>>2]|0)+4600>>2]|0);g[(c[E>>2]|0)+756>>2]=+g[I>>2]+-1.0;g[(c[E>>2]|0)+772>>2]=1.0-+g[I>>2]-+g[I>>2]*+g[L>>2]*.6000000238418579;c[J>>2]=1;while(1){if((c[J>>2]|0)>=(c[(c[D>>2]|0)+4604>>2]|0))break;g[(c[E>>2]|0)+756+(c[J>>2]<<2)>>2]=+g[(c[E>>2]|0)+756>>2];g[(c[E>>2]|0)+772+(c[J>>2]<<2)>>2]=+g[(c[E>>2]|0)+772>>2];c[J>>2]=(c[J>>2]|0)+1}g[H>>2]=-.25}g[F>>2]=(1.0-+g[(c[E>>2]|0)+860>>2])*.10000000149011612*+g[(c[D>>2]|0)+12236>>2];g[F>>2]=+g[F>>2]+(1.0-+g[(c[E>>2]|0)+856>>2])*.10000000149011612;if((a[(c[D>>2]|0)+4768+29>>0]|0)==2){g[G>>2]=.30000001192092896;g[G>>2]=+g[G>>2]+(1.0-(1.0-+g[(c[E>>2]|0)+860>>2])*+g[(c[E>>2]|0)+856>>2])*.20000000298023224;Q=+O(+(+g[(c[D>>2]|0)+12236>>2]));g[G>>2]=+g[G>>2]*Q}else g[G>>2]=0.0;c[J>>2]=0;while(1){if((c[J>>2]|0)>=(c[(c[D>>2]|0)+4604>>2]|0))break;R=(c[K>>2]|0)+4|0;g[R>>2]=+g[R>>2]+(+g[F>>2]-+g[(c[K>>2]|0)+4>>2])*.4000000059604645;g[(c[E>>2]|0)+804+(c[J>>2]<<2)>>2]=+g[(c[K>>2]|0)+4>>2];R=(c[K>>2]|0)+8|0;g[R>>2]=+g[R>>2]+(+g[G>>2]-+g[(c[K>>2]|0)+8>>2])*.4000000059604645;g[(c[E>>2]|0)+836+(c[J>>2]<<2)>>2]=+g[(c[K>>2]|0)+8>>2];R=(c[K>>2]|0)+12|0;g[R>>2]=+g[R>>2]+(+g[H>>2]-+g[(c[K>>2]|0)+12>>2])*.4000000059604645;g[(c[E>>2]|0)+820+(c[J>>2]<<2)>>2]=+g[(c[K>>2]|0)+12>>2];c[J>>2]=(c[J>>2]|0)+1}i=M;return}function gh(a){a=+a;var b=0,c=0;b=i;i=i+16|0;c=b;g[c>>2]=a;a=1.0/(+X(+-+g[c>>2])+1.0);i=b;return +a}function hh(a){a=+a;var b=0,c=0;b=i;i=i+16|0;c=b;h[c>>3]=a;a=+hj(+h[c>>3])*3.32192809488736;i=b;return +a}function ih(a,b,d){a=a|0;b=+b;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0;k=i;i=i+32|0;e=k+16|0;f=k+12|0;l=k+8|0;j=k+4|0;h=k;c[e>>2]=a;g[f>>2]=b;c[l>>2]=d;g[f>>2]=-+g[f>>2];g[h>>2]=+g[(c[e>>2]|0)+((c[l>>2]|0)-1<<2)>>2];c[j>>2]=(c[l>>2]|0)-2;while(1){b=+g[f>>2]*+g[h>>2];if((c[j>>2]|0)<0)break;g[h>>2]=b+ +g[(c[e>>2]|0)+(c[j>>2]<<2)>>2];c[j>>2]=(c[j>>2]|0)+-1}i=k;return +(1.0/(1.0-b))}function jh(a,b,d,e,f){a=a|0;b=b|0;d=+d;e=+e;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;v=i;i=i+64|0;h=v+48|0;j=v+44|0;k=v+40|0;l=v+36|0;m=v+32|0;q=v+28|0;s=v+24|0;r=v+20|0;u=v+16|0;t=v+12|0;n=v+8|0;p=v+4|0;o=v;c[h>>2]=a;c[j>>2]=b;g[k>>2]=d;g[l>>2]=e;c[m>>2]=f;c[r>>2]=0;c[q>>2]=(c[m>>2]|0)-1;while(1){d=+g[k>>2];if((c[q>>2]|0)<=0)break;f=(c[h>>2]|0)+((c[q>>2]|0)-1<<2)|0;g[f>>2]=+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>2]=(c[q>>2]|0)+1}g[p>>2]=1.0/+g[p>>2];g[o>>2]=1.0/+g[o>>2];c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[m>>2]|0))break;f=(c[h>>2]|0)+(c[q>>2]<<2)|0;g[f>>2]=+g[f>>2]*+g[p>>2];f=(c[j>>2]|0)+(c[q>>2]<<2)|0;g[f>>2]=+g[f>>2]*+g[o>>2];c[q>>2]=(c[q>>2]|0)+1}g[n>>2]=.9900000095367432-(+(c[s>>2]|0)*.10000000149011612+.800000011920929)*(+g[t>>2]-+g[l>>2])/(+g[t>>2]*+((c[r>>2]|0)+1|0));Fh(c[h>>2]|0,c[m>>2]|0,+g[n>>2]);Fh(c[j>>2]|0,c[m>>2]|0,+g[n>>2]);c[q>>2]=(c[m>>2]|0)-1;while(1){d=+g[k>>2];if((c[q>>2]|0)<=0)break;f=(c[h>>2]|0)+((c[q>>2]|0)-1<<2)|0;g[f>>2]=+g[f>>2]-d*+g[(c[h>>2]|0)+(c[q>>2]<<2)>>2];f=(c[j>>2]|0)+((c[q>>2]|0)-1<<2)|0;g[f>>2]=+g[f>>2]-+g[k>>2]*+g[(c[j>>2]|0)+(c[q>>2]<<2)>>2];c[q>>2]=(c[q>>2]|0)+-1}g[p>>2]=(1.0-d*+g[k>>2])/(+g[k>>2]*+g[c[h>>2]>>2]+1.0);g[o>>2]=(1.0-+g[k>>2]*+g[k>>2])/(+g[k>>2]*+g[c[j>>2]>>2]+1.0);c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[m>>2]|0))break;f=(c[h>>2]|0)+(c[q>>2]<<2)|0;g[f>>2]=+g[f>>2]*+g[p>>2];f=(c[j>>2]|0)+(c[q>>2]<<2)|0;g[f>>2]=+g[f>>2]*+g[o>>2];c[q>>2]=(c[q>>2]|0)+1}c[s>>2]=(c[s>>2]|0)+1}if((b|0)==31){i=v;return}}function kh(b,d,e,f){b=b|0;d=d|0;e=e|0;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0;y=i;i=i+464|0;h=y+460|0;j=y+456|0;z=y+452|0;A=y+448|0;q=y+444|0;s=y+440|0;t=y+436|0;u=y+432|0;n=y+428|0;r=y+424|0;p=y+420|0;o=y+416|0;l=y+408|0;k=y+404|0;v=y+400|0;w=y+396|0;m=y+384|0;x=y;c[h>>2]=b;c[j>>2]=d;c[z>>2]=e;c[A>>2]=f;c[q>>2]=(c[h>>2]|0)+7216;c[v>>2]=c[A>>2];c[w>>2]=c[z>>2];c[u>>2]=c[(c[q>>2]|0)+2136>>2];c[t>>2]=0;while(1){b=c[h>>2]|0;if((c[t>>2]|0)>=(c[(c[h>>2]|0)+4604>>2]|0))break;if((a[b+4768+29>>0]|0)==2)c[u>>2]=c[(c[j>>2]|0)+228+(c[t>>2]<<2)>>2];g[n>>2]=+g[(c[j>>2]|0)+836+(c[t>>2]<<2)>>2]*(1.0-+g[(c[j>>2]|0)+804+(c[t>>2]<<2)>>2]);g[m>>2]=+g[n>>2]*.25;g[m+4>>2]=+g[n>>2]*.4999847412109375;g[m+8>>2]=+g[n>>2]*.25;g[r>>2]=+g[(c[j>>2]|0)+820+(c[t>>2]<<2)>>2];g[p>>2]=+g[(c[j>>2]|0)+756+(c[t>>2]<<2)>>2];g[o>>2]=+g[(c[j>>2]|0)+772+(c[t>>2]<<2)>>2];c[k>>2]=(c[j>>2]|0)+244+(c[t>>2]<<4<<2);lh((c[q>>2]|0)+2048|0,x,c[k>>2]|0,c[v>>2]|0,+(c[(c[h>>2]|0)+4704>>2]|0)/65536.0,c[(c[h>>2]|0)+4612>>2]|0,c[(c[h>>2]|0)+4660>>2]|0);g[l>>2]=+g[(c[j>>2]|0)+788+(c[t>>2]<<2)>>2];g[l+4>>2]=-+g[(c[j>>2]|0)+788+(c[t>>2]<<2)>>2]*(+g[(c[j>>2]|0)+804+(c[t>>2]<<2)>>2]*+g[n>>2]+.05000000074505806+ +g[(c[j>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,t=0.0;s=i;i=i+64|0;p=s+48|0;q=s+44|0;h=s+40|0;n=s+36|0;l=s+32|0;m=s+16|0;o=s+12|0;j=s+8|0;k=s+4|0;r=s;c[p>>2]=d;c[q>>2]=e;c[h>>2]=f;c[n>>2]=(c[p>>2]|0)+7200;a:do if((a[(c[p>>2]|0)+4768+29>>0]|0)==2){g[o>>2]=1.0-+oh((+g[(c[q>>2]|0)+872>>2]-12.0)*.25)*.5;c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[(c[p>>2]|0)+4604>>2]|0))break a;e=(c[q>>2]|0)+(c[l>>2]<<2)|0;g[e>>2]=+g[e>>2]*+g[o>>2];c[l>>2]=(c[l>>2]|0)+1}}while(0);t=+P(2.0,+((21.0-+(c[(c[p>>2]|0)+4748>>2]|0)*.0078125)*.33000001311302185));g[j>>2]=t/+(c[(c[p>>2]|0)+4612>>2]|0);c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[(c[p>>2]|0)+4604>>2]|0))break;g[k>>2]=+g[(c[q>>2]|0)+(c[l>>2]<<2)>>2];g[k>>2]=+O(+(+g[k>>2]*+g[k>>2]+ +g[(c[q>>2]|0)+876+(c[l>>2]<<2)>>2]*+g[j>>2]));g[(c[q>>2]|0)+(c[l>>2]<<2)>>2]=+g[k>>2]<32767.0?+g[k>>2]:32767.0;c[l>>2]=(c[l>>2]|0)+1}c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[(c[p>>2]|0)+4604>>2]|0))break;c[m+(c[l>>2]<<2)>>2]=~~(+g[(c[q>>2]|0)+(c[l>>2]<<2)>>2]*65536.0);c[l>>2]=(c[l>>2]|0)+1}pj((c[q>>2]|0)+892|0,m|0,c[(c[p>>2]|0)+4604>>2]<<2|0)|0;a[(c[q>>2]|0)+908>>0]=a[c[n>>2]>>0]|0;_d((c[p>>2]|0)+4768|0,m,c[n>>2]|0,(c[h>>2]|0)==2&1,c[(c[p>>2]|0)+4604>>2]|0);c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[(c[p>>2]|0)+4604>>2]|0))break;g[(c[q>>2]|0)+(c[l>>2]<<2)>>2]=+(c[m+(c[l>>2]<<2)>>2]|0)/65536.0;c[l>>2]=(c[l>>2]|0)+1}do if((a[(c[p>>2]|0)+4768+29>>0]|0)==2){h=(c[p>>2]|0)+4768+30|0;if(+g[(c[q>>2]|0)+872>>2]+ +(c[(c[p>>2]|0)+4744>>2]|0)*.000030517578125>1.0){a[h>>0]=0;break}else{a[h>>0]=1;break}}while(0);g[r>>2]=+(b[24558+(a[(c[p>>2]|0)+4768+29>>0]>>1<<2)+(a[(c[p>>2]|0)+4768+30>>0]<<1)>>1]|0)/1024.0;g[(c[q>>2]|0)+852>>2]=+(c[(c[p>>2]|0)+4652>>2]|0)*-.05000000074505806+1.2000000476837158+ +(c[(c[p>>2]|0)+4556>>2]|0)*-.20000000298023224*.00390625+ +g[(c[q>>2]|0)+856>>2]*-.10000000149011612+ +g[(c[q>>2]|0)+860>>2]*-.20000000298023224+ +g[r>>2]*.800000011920929;i=s;return}function oh(a){a=+a;var b=0,c=0;b=i;i=i+16|0;c=b;g[c>>2]=a;a=1.0/(+X(+-+g[c>>2])+1.0);i=b;return +a}function ph(a,b,d,e){a=a|0;b=b|0;d=+d;e=e|0;var f=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;f=m+16|0;h=m+12|0;j=m+8|0;k=m+4|0;l=m;c[f>>2]=a;c[h>>2]=b;g[j>>2]=d;c[k>>2]=e;c[l>>2]=0;while(1){d=+g[j>>2];if((c[l>>2]|0)>=(c[k>>2]|0))break;b=_(c[l>>2]|0,c[k>>2]|0)|0;b=(c[f>>2]|0)+(b+(c[l>>2]|0)<<2)|0;g[b>>2]=+g[b>>2]+d;c[l>>2]=(c[l>>2]|0)+1}l=c[h>>2]|0;g[l>>2]=+g[l>>2]+d;i=m;return}function qh(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=+e;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p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|0,c[o>>2]|0);g[(c[k>>2]|0)+12>>2]=v;i=t;return}function sh(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;n=i;i=i+1184|0;p=n+1168|0;f=n+1164|0;o=n+1160|0;h=n+1156|0;m=n+1152|0;k=n+128|0;l=n+64|0;j=n;c[p>>2]=a;c[f>>2]=b;c[o>>2]=d;c[h>>2]=e;th(c[p>>2]|0,c[f>>2]|0,k,j);uh(k,c[f>>2]|0,c[o>>2]|0,l);c[m>>2]=0;while(1){if((c[m>>2]|0)>=(c[f>>2]|0))break;g[l+(c[m>>2]<<2)>>2]=+g[l+(c[m>>2]<<2)>>2]*+g[j+(c[m>>2]<<2)>>2];c[m>>2]=(c[m>>2]|0)+1}vh(k,c[f>>2]|0,l,c[h>>2]|0);i=n;return}function th(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0;y=i;i=i+192|0;f=y+184|0;j=y+180|0;k=y+176|0;l=y+172|0;p=y+168|0;q=y+164|0;r=y+160|0;s=y+156|0;o=y+152|0;t=y+148|0;u=y+144|0;v=y+8|0;n=y;w=y+80|0;m=y+16|0;c[f>>2]=a;c[j>>2]=b;c[k>>2]=d;c[l>>2]=e;c[o>>2]=1;b=(_(c[j>>2]|0,c[j>>2]|0)|0)-1|0;h[n>>3]=(+g[c[f>>2]>>2]+ +g[(c[f>>2]|0)+(b<<2)>>2])*4.999999873689376e-06;c[s>>2]=0;while(1){if(!((c[s>>2]|0)<(c[j>>2]|0)?(c[o>>2]|0)==1:0))break;c[o>>2]=0;c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[j>>2]|0))break;c[t>>2]=(c[k>>2]|0)+((_(c[q>>2]|0,c[j>>2]|0)|0)+0<<2);b=_(c[q>>2]|0,c[j>>2]|0)|0;h[v>>3]=+g[(c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n>>2]<<3)|0;h[f>>3]=+h[f>>3]+ +h[r>>3]*+h[s>>3];c[q>>2]=(c[q>>2]|0)+1}c[p>>2]=0;while(1){if((c[p>>2]|0)>=((c[n>>2]|0)+1|0))break;g[(c[j>>2]|0)+(c[p>>2]<<2)>>2]=+h[o+(c[p>>2]<<3)>>3];c[p>>2]=(c[p>>2]|0)+1}i=u;return}function xh(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0;l=i;i=i+80|0;e=l+76|0;f=l+72|0;h=l+68|0;k=l+64|0;j=l;c[e>>2]=a;c[f>>2]=b;c[h>>2]=d;c[k>>2]=0;while(1){if((c[k>>2]|0)>=(c[h>>2]|0))break;b=yh(+g[(c[f>>2]|0)+(c[k>>2]<<2)>>2]*65536.0)|0;c[j+(c[k>>2]<<2)>>2]=b;c[k>>2]=(c[k>>2]|0)+1}Hf(c[e>>2]|0,j,c[h>>2]|0);i=l;return}function yh(a){a=+a;var b=0,c=0;c=i;i=i+16|0;b=c;g[b>>2]=a;b=ij(+g[b>>2])|0;i=c;return b|0}function zh(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0,m=0;l=i;i=i+48|0;f=l+12|0;m=l+8|0;h=l+4|0;k=l;j=l+16|0;c[f>>2]=a;c[m>>2]=d;c[h>>2]=e;ag(j,c[m>>2]|0,c[h>>2]|0);c[k>>2]=0;while(1){if((c[k>>2]|0)>=(c[h>>2]|0))break;g[(c[f>>2]|0)+(c[k>>2]<<2)>>2]=+(b[j+(c[k>>2]<<1)>>1]|0)*.000244140625;c[k>>2]=(c[k>>2]|0)+1}i=l;return}function Ah(a,d,e,f){a=a|0;d=d|0;e=e|0;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;n=i;i=i+96|0;h=n+20|0;j=n+16|0;p=n+12|0;o=n+8|0;l=n+4|0;m=n;k=n+24|0;c[h>>2]=a;c[j>>2]=d;c[p>>2]=e;c[o>>2]=f;pf(c[h>>2]|0,k,c[p>>2]|0,c[o>>2]|0);c[m>>2]=0;while(1){if((c[m>>2]|0)>=2)break;c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[(c[h>>2]|0)+4664>>2]|0))break;g[(c[j>>2]|0)+(c[m>>2]<<6)+(c[l>>2]<<2)>>2]=+(b[k+(c[m>>2]<<5)+(c[l>>2]<<1)>>1]|0)*.000244140625;c[l>>2]=(c[l>>2]|0)+1}c[m>>2]=(c[m>>2]|0)+1}i=n;return}function Bh(d,e,f,h,j,k){d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;var l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0;D=i;i=i+1632|0;l=D+1388|0;m=D+1384|0;n=D+1380|0;o=D+1376|0;p=D+1372|0;q=D+1368|0;A=D+1364|0;B=D+1360|0;C=D+80|0;s=D+64|0;y=D+1560|0;v=D+1520|0;w=D+56|0;r=D+1392|0;u=D+40|0;x=D+32|0;z=D+16|0;t=D;c[l>>2]=d;c[m>>2]=e;c[n>>2]=f;c[o>>2]=h;c[p>>2]=j;c[q>>2]=k;c[A>>2]=0;while(1){if((c[A>>2]|0)>=(c[(c[l>>2]|0)+4604>>2]|0))break;c[B>>2]=0;while(1){d=c[A>>2]|0;if((c[B>>2]|0)>=(c[(c[l>>2]|0)+4660>>2]|0))break;k=(yh(+g[(c[m>>2]|0)+500+((d<<4)+(c[B>>2]|0)<<2)>>2]*8192.0)|0)&65535;b[r+((c[A>>2]<<4)+(c[B>>2]|0)<<1)>>1]=k;c[B>>2]=(c[B>>2]|0)+1}c[A>>2]=d+1}c[A>>2]=0;while(1){if((c[A>>2]|0)>=(c[(c[l>>2]|0)+4604>>2]|0))break;k=(yh(+g[(c[m>>2]|0)+772+(c[A>>2]<<2)>>2]*16384.0)|0)<<16;k=k|(yh(+g[(c[m>>2]|0)+756+(c[A>>2]<<2)>>2]*16384.0)|0)&65535;c[u+(c[A>>2]<<2)>>2]=k;k=yh(+g[(c[m>>2]|0)+820+(c[A>>2]<<2)>>2]*16384.0)|0;c[z+(c[A>>2]<<2)>>2]=k;k=yh(+g[(c[m>>2]|0)+836+(c[A>>2]<<2)>>2]*16384.0)|0;c[t+(c[A>>2]<<2)>>2]=k;c[A>>2]=(c[A>>2]|0)+1}c[x>>2]=yh(+g[(c[m>>2]|0)+852>>2]*1024.0)|0;c[A>>2]=0;while(1){if((c[A>>2]|0)>=((c[(c[l>>2]|0)+4604>>2]|0)*5|0))break;k=(yh(+g[(c[m>>2]|0)+144+(c[A>>2]<<2)>>2]*16384.0)|0)&65535;b[v+(c[A>>2]<<1)>>1]=k;c[A>>2]=(c[A>>2]|0)+1}c[B>>2]=0;while(1){k=(c[B>>2]|0)<2;c[A>>2]=0;if(!k)break;while(1){if((c[A>>2]|0)>=(c[(c[l>>2]|0)+4664>>2]|0))break;k=(yh(+g[(c[m>>2]|0)+16+(c[B>>2]<<6)+(c[A>>2]<<2)>>2]*4096.0)|0)&65535;b[y+(c[B>>2]<<5)+(c[A>>2]<<1)>>1]=k;c[A>>2]=(c[A>>2]|0)+1}c[B>>2]=(c[B>>2]|0)+1}while(1){if((c[A>>2]|0)>=(c[(c[l>>2]|0)+4604>>2]|0))break;B=yh(+g[(c[m>>2]|0)+(c[A>>2]<<2)>>2]*65536.0)|0;c[s+(c[A>>2]<<2)>>2]=B;c[A>>2]=(c[A>>2]|0)+1}if((a[(c[n>>2]|0)+29>>0]|0)==2)c[w>>2]=b[24566+(a[(c[n>>2]|0)+33>>0]<<1)>>1];else c[w>>2]=0;c[A>>2]=0;while(1){if((c[A>>2]|0)>=(c[(c[l>>2]|0)+4608>>2]|0))break;B=yh(+g[(c[q>>2]|0)+(c[A>>2]<<2)>>2]*8.0)|0;c[C+(c[A>>2]<<2)>>2]=B;c[A>>2]=(c[A>>2]|0)+1}if((c[(c[l>>2]|0)+4652>>2]|0)<=1?(c[(c[l>>2]|0)+4704>>2]|0)<=0:0){me(c[l>>2]|0,c[o>>2]|0,c[n>>2]|0,C,c[p>>2]|0,y,v,r,t,z,u,s,(c[m>>2]|0)+228|0,c[x>>2]|0,c[w>>2]|0);i=D;return}se(c[l>>2]|0,c[o>>2]|0,c[n>>2]|0,C,c[p>>2]|0,y,v,r,t,z,u,s,(c[m>>2]|0)+228|0,c[x>>2]|0,c[w>>2]|0);i=D;return}function Ch(a,d,e,f,h,j,k,l,m){a=a|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;var n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0;z=i;i=i+480|0;n=z+436|0;o=z+432|0;p=z+428|0;q=z+424|0;r=z+420|0;s=z+416|0;t=z+412|0;u=z+408|0;v=z+404|0;y=z+400|0;w=z+440|0;x=z;c[n>>2]=a;c[o>>2]=d;c[p>>2]=e;c[q>>2]=f;c[r>>2]=h;c[s>>2]=j;c[t>>2]=k;c[u>>2]=l;c[v>>2]=m;c[y>>2]=0;while(1){if((c[y>>2]|0)>=((c[u>>2]|0)*5|0))break;f=(yh(+g[(c[n>>2]|0)+(c[y>>2]<<2)>>2]*16384.0)|0)&65535;b[w+(c[y>>2]<<1)>>1]=f;c[y>>2]=(c[y>>2]|0)+1}c[y>>2]=0;while(1){if((c[y>>2]|0)>=(((c[u>>2]|0)*5|0)*5|0))break;f=yh(+g[(c[r>>2]|0)+(c[y>>2]<<2)>>2]*262144.0)|0;c[x+(c[y>>2]<<2)>>2]=f;c[y>>2]=(c[y>>2]|0)+1}df(w,c[o>>2]|0,c[p>>2]|0,c[q>>2]|0,x,c[s>>2]|0,c[t>>2]|0,c[u>>2]|0,c[v>>2]|0);c[y>>2]=0;while(1){if((c[y>>2]|0)>=((c[u>>2]|0)*5|0))break;g[(c[n>>2]|0)+(c[y>>2]<<2)>>2]=+(b[w+(c[y>>2]<<1)>>1]|0)*.00006103515625;c[y>>2]=(c[y>>2]|0)+1}i=z;return}function Dh(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0,m=0,n=0.0;m=i;i=i+32|0;f=m+16|0;h=m+12|0;j=m+8|0;k=m+4|0;l=m;c[f>>2]=a;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;if((c[k>>2]|0)>(c[j>>2]|0))c[k>>2]=c[j>>2];c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[k>>2]|0))break;n=+Hh(c[h>>2]|0,(c[h>>2]|0)+(c[l>>2]<<2)|0,(c[j>>2]|0)-(c[l>>2]|0)|0);g[(c[f>>2]|0)+(c[l>>2]<<2)>>2]=n;c[l>>2]=(c[l>>2]|0)+1}i=m;return}function Eh(a,b,d,e,f,j){a=a|0;b=b|0;d=+d;e=e|0;f=f|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0;K=i;i=i+784|0;k=K+768|0;l=K+764|0;m=K+760|0;n=K+756|0;o=K+752|0;p=K+748|0;y=K+744|0;z=K+740|0;F=K+736|0;E=K+732|0;s=K+720|0;x=K+712|0;C=K+704|0;B=K+696|0;A=K+688|0;D=K+680|0;r=K+672|0;G=K+664|0;H=K+656|0;I=K+728|0;v=K+528|0;w=K+400|0;u=K+264|0;t=K+128|0;q=K;c[k>>2]=a;c[l>>2]=b;g[m>>2]=d;c[n>>2]=e;c[o>>2]=f;c[p>>2]=j;h[s>>3]=+Gh(c[l>>2]|0,_(c[o>>2]|0,c[n>>2]|0)|0);a=v;f=a+128|0;do{c[a>>2]=0;a=a+4|0}while((a|0)<(f|0));c[F>>2]=0;while(1){if((c[F>>2]|0)>=(c[o>>2]|0))break;c[I>>2]=(c[l>>2]|0)+((_(c[F>>2]|0,c[n>>2]|0)|0)<<2);c[z>>2]=1;while(1){if((c[z>>2]|0)>=((c[p>>2]|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*+h[r>>3];h[G>>3]=+h[G>>3]+ +h[r>>3]*+h[r>>3];g[(c[k>>2]|0)+(c[y>>2]<<2)>>2]=-+h[r>>3];c[y>>2]=(c[y>>2]|0)+1}h[B>>3]=+h[B>>3]-+h[s>>3]*9.999999747378752e-06*+h[G>>3];d=+h[B>>3];i=K;return +d}c[y>>2]=0;while(1){if((c[y>>2]|0)>=(c[p>>2]|0))break;g[(c[k>>2]|0)+(c[y>>2]<<2)>>2]=-+h[q+(c[y>>2]<<3)>>3];c[y>>2]=(c[y>>2]|0)+1}c[F>>2]=0;while(1){if((c[F>>2]|0)>=(c[o>>2]|0))break;J=(c[l>>2]|0)+((_(c[F>>2]|0,c[n>>2]|0)|0)<<2)|0;d=+Gh(J,c[p>>2]|0);h[s>>3]=+h[s>>3]-d;c[F>>2]=(c[F>>2]|0)+1}h[B>>3]=+h[s>>3]*+h[x>>3];d=+h[B>>3];i=K;return +d}function Fh(a,b,d){a=a|0;b=b|0;d=+d;var e=0,f=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;e=l+16|0;f=l+12|0;h=l+8|0;k=l+4|0;j=l;c[e>>2]=a;c[f>>2]=b;g[h>>2]=d;g[j>>2]=+g[h>>2];c[k>>2]=0;while(1){d=+g[j>>2];if((c[k>>2]|0)>=((c[f>>2]|0)-1|0))break;b=(c[e>>2]|0)+(c[k>>2]<<2)|0;g[b>>2]=+g[b>>2]*d;g[j>>2]=+g[j>>2]*+g[h>>2];c[k>>2]=(c[k>>2]|0)+1}k=(c[e>>2]|0)+((c[f>>2]|0)-1<<2)|0;g[k>>2]=+g[k>>2]*d;i=l;return}function Gh(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,j=0,k=0,l=0;l=i;i=i+32|0;d=l+20|0;e=l+16|0;j=l+12|0;f=l+8|0;k=l;c[d>>2]=a;c[e>>2]=b;h[k>>3]=0.0;c[f>>2]=c[e>>2]&65532;c[j>>2]=0;while(1){if((c[j>>2]|0)>=(c[f>>2]|0))break;h[k>>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=(c[l>>2]|0)+4}while(1){if((c[l>>2]|0)>=(c[j>>2]|0))break;h[m>>3]=+h[m>>3]+ +g[(c[e>>2]|0)+(c[l>>2]<<2)>>2]*+g[(c[f>>2]|0)+(c[l>>2]<<2)>>2];c[l>>2]=(c[l>>2]|0)+1}i=n;return +(+h[m>>3])}function Ih(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+96|0;e=m+80|0;f=m+76|0;h=m+72|0;k=m+68|0;l=m+64|0;j=m;c[e>>2]=a;c[f>>2]=b;c[h>>2]=d;c[k>>2]=0;while(1){if((c[k>>2]|0)>=(c[h>>2]|0))break;c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[k>>2]|0))break;g[j+(c[l>>2]<<2)>>2]=+g[(c[e>>2]|0)+(c[l>>2]<<2)>>2];c[l>>2]=(c[l>>2]|0)+1}c[l>>2]=0;while(1){a=c[k>>2]|0;if((c[l>>2]|0)>=(c[k>>2]|0))break;b=(c[e>>2]|0)+(c[l>>2]<<2)|0;g[b>>2]=+g[b>>2]+ +g[j+(a-(c[l>>2]|0)-1<<2)>>2]*+g[(c[f>>2]|0)+(c[k>>2]<<2)>>2];c[l>>2]=(c[l>>2]|0)+1}g[(c[e>>2]|0)+(c[k>>2]<<2)>>2]=-+g[(c[f>>2]|0)+(a<<2)>>2];c[k>>2]=(c[k>>2]|0)+1}i=m;return}function Jh(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0;s=i;i=i+48|0;e=s+44|0;f=s+40|0;h=s+36|0;l=s+32|0;o=s+28|0;n=s+24|0;p=s+20|0;q=s+16|0;r=s+12|0;m=s+8|0;j=s+4|0;k=s;c[e>>2]=a;c[f>>2]=b;c[h>>2]=d;g[p>>2]=+g[c[f>>2]>>2]*9.999999960041972e-13+9.999999717180685e-10;g[q>>2]=+g[c[f>>2]>>2];g[q>>2]=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){a=a|0;b=b|0;var d=0,e=0,f=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0.0;r=i;i=i+192|0;d=r+184|0;t=r+180|0;s=r+176|0;l=r+172|0;m=r+168|0;k=r+24|0;n=r+16|0;o=r+8|0;p=r;j=r+40|0;f=r+36|0;e=r+32|0;c[t>>2]=a;c[s>>2]=b;c[e>>2]=j+((c[s>>2]&1)<<6);pj(c[e>>2]|0,c[t>>2]|0,c[s>>2]<<2|0)|0;h[k>>3]=1.0;c[l>>2]=(c[s>>2]|0)-1;while(1){if((c[l>>2]|0)<=0)break;h[n>>3]=-+g[(c[e>>2]|0)+(c[l>>2]<<2)>>2];if(+h[n>>3]>.9998999834060669|+h[n>>3]<-.9998999834060669){q=4;break}h[o>>3]=1.0-+h[n>>3]*+h[n>>3];h[p>>3]=1.0/+h[o>>3];h[k>>3]=+h[k>>3]*+h[o>>3];c[f>>2]=c[e>>2];c[e>>2]=j+((c[l>>2]&1)<<6);c[m>>2]=0;while(1){if((c[m>>2]|0)>=(c[l>>2]|0))break;g[(c[e>>2]|0)+(c[m>>2]<<2)>>2]=(+g[(c[f>>2]|0)+(c[m>>2]<<2)>>2]-+g[(c[f>>2]|0)+((c[l>>2]|0)-(c[m>>2]|0)-1<<2)>>2]*+h[n>>3])*+h[p>>3];c[m>>2]=(c[m>>2]|0)+1}c[l>>2]=(c[l>>2]|0)+-1}if((q|0)==4){g[d>>2]=0.0;u=+g[d>>2];i=r;return +u}h[n>>3]=-+g[c[e>>2]>>2];if(+h[n>>3]>.9998999834060669|+h[n>>3]<-.9998999834060669){g[d>>2]=0.0;u=+g[d>>2];i=r;return +u}else{h[o>>3]=1.0-+h[n>>3]*+h[n>>3];h[k>>3]=+h[k>>3]*+h[o>>3];g[d>>2]=+h[k>>3];u=+g[d>>2];i=r;return +u}return 0.0}function Lh(d,e,f,j,k,l,m,n,o,p,q,r){d=d|0;e=e|0;f=f|0;j=j|0;k=k|0;l=l|0;m=+m;n=+n;o=o|0;p=p|0;q=q|0;r=r|0;var s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ia=0,ja=0,ka=0,la=0,ma=0,na=0,oa=0,pa=0,qa=0,ra=0,sa=0,ta=0,ua=0,va=0,wa=0,xa=0,ya=0,za=0,Aa=0,Ba=0,Ca=0,Da=0,Ea=0,Fa=0,Ga=0,Ha=0,Ia=0,Ja=0,Ka=0,La=0;La=i;i=i+13936|0;Ca=La+10416|0;da=La+10412|0;Ea=La+10408|0;Fa=La+10404|0;Ga=La+10400|0;H=La+10396|0;I=La+10392|0;s=La+10388|0;J=La+10384|0;ya=La+10380|0;ea=La+10376|0;Da=La+10372|0;fa=La+10368|0;U=La+10364|0;Ka=La+10360|0;la=La+10356|0;qa=La+10352|0;T=La+9072|0;y=La+8432|0;z=La+13288|0;x=La+12968|0;u=La+8408|0;ba=La+8404|0;ia=La+8400|0;K=La+6016|0;G=La+5756|0;M=La+5712|0;xa=La+5708|0;P=La+5704|0;ja=La+24|0;E=La+16|0;oa=La+8|0;pa=La;R=La+5608|0;Q=La+12664|0;X=La+5600|0;W=La+5596|0;t=La+5592|0;ga=La+5588|0;N=La+5584|0;O=La+5580|0;ha=La+5576|0;Ha=La+5572|0;L=La+5568|0;za=La+5564|0;wa=La+5560|0;ma=La+5556|0;Aa=La+5552|0;Ja=La+5548|0;V=La+5544|0;$=La+5540|0;S=La+5536|0;na=La+2816|0;ka=La+96|0;ra=La+88|0;A=La+84|0;C=La+80|0;B=La+76|0;va=La+72|0;aa=La+68|0;F=La+64|0;Ba=La+60|0;ta=La+56|0;Z=La+52|0;sa=La+48|0;Y=La+44|0;D=La+40|0;ua=La+36|0;Ia=La+32|0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ea>>2]|0)>0){c[ua>>2]=11;break}else{c[ua>>2]=3;break}}else{c[Ja>>2]=3;c[Ia>>2]=30252;c[ua>>2]=3}while(0);c[Ka>>2]=0;while(1){if((c[Ka>>2]|0)>=(c[X>>2]|0))break;c[la>>2]=c[R+(c[Ka>>2]<<2)>>2];c[qa>>2]=0;while(1){if((c[qa>>2]|0)>=(c[ua>>2]|0))break;g[M+(c[qa>>2]<<2)>>2]=0.0;c[U>>2]=0;while(1){if((c[U>>2]|0)>=(c[Da>>2]|0))break;ba=_(c[U>>2]|0,c[Ja>>2]|0)|0;ca=M+(c[qa>>2]<<2)|0;g[ca>>2]=+g[ca>>2]+ +g[K+((c[U>>2]|0)*596|0)+((c[la>>2]|0)+(a[(c[Ia>>2]|0)+(ba+(c[qa>>2]|0))>>0]|0)<<2)>>2];c[U>>2]=(c[U>>2]|0)+1}c[qa>>2]=(c[qa>>2]|0)+1}g[ha>>2]=-1.0e3;c[L>>2]=0;c[U>>2]=0;while(1){if((c[U>>2]|0)>=(c[ua>>2]|0))break;if(+g[M+(c[U>>2]<<2)>>2]>+g[ha>>2]){g[ha>>2]=+g[M+(c[U>>2]<<2)>>2];c[L>>2]=c[U>>2]}c[U>>2]=(c[U>>2]|0)+1}g[V>>2]=+Oh(+(c[la>>2]|0));g[O>>2]=+g[ha>>2]-+(c[Da>>2]|0)*.20000000298023224*+g[V>>2];if((c[I>>2]|0)>0){g[S>>2]=+g[V>>2]-+g[$>>2];g[S>>2]=+g[S>>2]*+g[S>>2];g[O>>2]=+g[O>>2]-+(c[Da>>2]|0)*.20000000298023224*+g[c[H>>2]>>2]*+g[S>>2]/(+g[S>>2]+.5)}if(+g[O>>2]>+g[N>>2]?+g[ha>>2]>+(c[Da>>2]|0)*+g[J>>2]:0){g[N>>2]=+g[O>>2];g[ga>>2]=+g[ha>>2];c[za>>2]=c[la>>2];c[Ha>>2]=c[L>>2]}c[Ka>>2]=(c[Ka>>2]|0)+1}if((c[za>>2]|0)==-1){Ka=c[Ea>>2]|0;c[Ka>>2]=0;c[Ka+4>>2]=0;c[Ka+8>>2]=0;c[Ka+12>>2]=0;g[c[H>>2]>>2]=0.0;b[c[Fa>>2]>>1]=0;a[c[Ga>>2]>>0]=0;c[Ca>>2]=1;Ka=c[Ca>>2]|0;i=La;return Ka|0}g[c[H>>2]>>2]=+g[ga>>2]/+(c[Da>>2]|0);if((c[ya>>2]|0)>8){s=c[za>>2]|0;if((c[ya>>2]|0)==12)c[za>>2]=(((s&65535)<<16>>16)*3>>1)+(((c[za>>2]&65535)<<16>>16)*3&1);else c[za>>2]=s<<1;s=c[za>>2]|0;do if((c[Ba>>2]|0)>(c[sa>>2]|0))if((s|0)>(c[Ba>>2]|0)){s=c[Ba>>2]|0;break}else{s=(c[za>>2]|0)<(c[sa>>2]|0)?c[sa>>2]|0:c[za>>2]|0;break}else if((s|0)>(c[sa>>2]|0)){s=c[sa>>2]|0;break}else{s=(c[za>>2]|0)<(c[Ba>>2]|0)?c[Ba>>2]|0:c[za>>2]|0;break}while(0);c[za>>2]=s;c[wa>>2]=Ph((c[za>>2]|0)-2|0,c[Ba>>2]|0)|0;c[ma>>2]=Qh((c[za>>2]|0)+2|0,c[sa>>2]|0)|0;c[Aa>>2]=c[za>>2];c[Ha>>2]=0;g[ga>>2]=-1.0e3;Rh(ka,c[da>>2]|0,c[wa>>2]|0,c[va>>2]|0,c[Da>>2]|0,c[ea>>2]|0,c[fa>>2]|0);Sh(na,c[da>>2]|0,c[wa>>2]|0,c[va>>2]|0,c[Da>>2]|0,c[ea>>2]|0);c[ra>>2]=0;g[ia>>2]=.05000000074505806/+(c[za>>2]|0);if((c[Da>>2]|0)==4){c[ua>>2]=a[30490+(c[ea>>2]|0)>>0];c[Ja>>2]=34;c[Ia>>2]=30330}else{c[ua>>2]=12;c[Ja>>2]=12;c[Ia>>2]=30258}c[xa>>2]=(c[da>>2]|0)+((c[ya>>2]|0)*20<<2);h[pa>>3]=+Gh(c[xa>>2]|0,_(c[Da>>2]|0,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0,k=0,l=0;k=i;i=i+16|0;f=k+12|0;h=k+8|0;l=k+4|0;j=k;c[f>>2]=a;c[h>>2]=d;c[l>>2]=e;c[j>>2]=(c[l>>2]|0)-1;while(1){if((c[j>>2]|0)<0)break;if((ij(+g[(c[h>>2]|0)+(c[j>>2]<<2)>>2])|0)<=32767)if((ij(+g[(c[h>>2]|0)+(c[j>>2]<<2)>>2])|0)<-32768)d=-32768;else d=ij(+g[(c[h>>2]|0)+(c[j>>2]<<2)>>2])|0;else d=32767;b[(c[f>>2]|0)+(c[j>>2]<<1)>>1]=d;c[j>>2]=(c[j>>2]|0)+-1}i=k;return}function Nh(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0;k=i;i=i+16|0;f=k+12|0;h=k+8|0;l=k+4|0;j=k;c[f>>2]=a;c[h>>2]=d;c[l>>2]=e;c[j>>2]=(c[l>>2]|0)-1;while(1){if((c[j>>2]|0)<0)break;g[(c[f>>2]|0)+(c[j>>2]<<2)>>2]=+(b[(c[h>>2]|0)+(c[j>>2]<<1)>>1]|0);c[j>>2]=(c[j>>2]|0)+-1}i=k;return}function Oh(a){a=+a;var b=0,c=0;b=i;i=i+16|0;c=b;h[c>>3]=a;a=+hj(+h[c>>3])*3.32192809488736;i=b;return +a}function Ph(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Qh(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Rh(b,d,e,f,h,j,k){b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;var l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0;H=i;i=i+256|0;l=H+252|0;m=H+248|0;n=H+244|0;o=H+240|0;p=H+236|0;q=H+232|0;r=H+228|0;F=H+224|0;w=H+220|0;y=H+216|0;z=H+212|0;A=H+208|0;C=H+204|0;B=H+200|0;D=H+196|0;v=H+192|0;x=H+188|0;u=H+184|0;E=H+96|0;G=H+8|0;t=H+4|0;s=H;c[l>>2]=b;c[m>>2]=d;c[n>>2]=e;c[o>>2]=f;c[p>>2]=h;c[q>>2]=j;c[r>>2]=k;if((c[p>>2]|0)==4){c[t>>2]=30466+(c[q>>2]<<3);c[s>>2]=30330;c[D>>2]=a[30490+(c[q>>2]|0)>>0];c[u>>2]=34}else{c[t>>2]=30282;c[s>>2]=30258;c[D>>2]=12;c[u>>2]=12}c[F>>2]=(c[m>>2]|0)+(c[o>>2]<<2<<2);c[z>>2]=0;while(1){if((c[z>>2]|0)>=(c[p>>2]|0))break;c[A>>2]=0;c[C>>2]=a[(c[t>>2]|0)+((c[z>>2]<<1)+0)>>0];c[B>>2]=a[(c[t>>2]|0)+((c[z>>2]<<1)+1)>>0];Mc(c[F>>2]|0,(c[F>>2]|0)+(0-(c[n>>2]|0)<<2)+(0-(c[B>>2]|0)<<2)|0,G,c[o>>2]|0,(c[B>>2]|0)-(c[C>>2]|0)+1|0,c[r>>2]|0);c[y>>2]=c[C>>2];while(1){if((c[y>>2]|0)>(c[B>>2]|0))break;g[E+(c[A>>2]<<2)>>2]=+g[G+((c[B>>2]|0)-(c[y>>2]|0)<<2)>>2];c[A>>2]=(c[A>>2]|0)+1;c[y>>2]=(c[y>>2]|0)+1}c[v>>2]=a[(c[t>>2]|0)+((c[z>>2]<<1)+0)>>0];c[w>>2]=0;while(1){if((c[w>>2]|0)>=(c[D>>2]|0))break;e=_(c[z>>2]|0,c[u>>2]|0)|0;c[x>>2]=(a[(c[s>>2]|0)+(e+(c[w>>2]|0))>>0]|0)-(c[v>>2]|0);c[y>>2]=0;while(1){if((c[y>>2]|0)>=5)break;g[(c[l>>2]|0)+((c[z>>2]|0)*680|0)+((c[w>>2]|0)*20|0)+(c[y>>2]<<2)>>2]=+g[E+((c[x>>2]|0)+(c[y>>2]|0)<<2)>>2];c[y>>2]=(c[y>>2]|0)+1}c[w>>2]=(c[w>>2]|0)+1}c[F>>2]=(c[F>>2]|0)+(c[o>>2]<<2);c[z>>2]=(c[z>>2]|0)+1}i=H;return}function Sh(b,d,e,f,j,k){b=b|0;d=d|0;e=e|0;f=f|0;j=j|0;k=k|0;var l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0;G=i;i=i+176|0;l=G+168|0;m=G+164|0;n=G+160|0;o=G+156|0;p=G+152|0;q=G+148|0;F=G+144|0;t=G+140|0;w=G;A=G+136|0;x=G+132|0;z=G+128|0;B=G+124|0;D=G+120|0;v=G+116|0;y=G+112|0;u=G+108|0;C=G+104|0;E=G+16|0;s=G+12|0;r=G+8|0;c[l>>2]=b;c[m>>2]=d;c[n>>2]=e;c[o>>2]=f;c[p>>2]=j;c[q>>2]=k;if((c[p>>2]|0)==4){c[s>>2]=30466+(c[q>>2]<<3);c[r>>2]=30330;c[D>>2]=a[30490+(c[q>>2]|0)>>0];c[u>>2]=34}else{c[s>>2]=30282;c[r>>2]=30258;c[D>>2]=12;c[u>>2]=12}c[F>>2]=(c[m>>2]|0)+(c[o>>2]<<2<<2);c[A>>2]=0;while(1){if((c[A>>2]|0)>=(c[p>>2]|0))break;c[B>>2]=0;c[t>>2]=(c[F>>2]|0)+(0-((c[n>>2]|0)+(a[(c[s>>2]|0)+((c[A>>2]<<1)+0)>>0]|0))<<2);h[w>>3]=+Gh(c[t>>2]|0,c[o>>2]|0)+.001;g[E+(c[B>>2]<<2)>>2]=+h[w>>3];c[B>>2]=(c[B>>2]|0)+1;c[C>>2]=(a[(c[s>>2]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>>2]|0)+0<<2)>>2]=+g[j>>2]*+g[(c[h>>2]|0)+((c[m>>2]|0)+0<<2)>>2];g[(c[f>>2]|0)+((c[m>>2]|0)+1<<2)>>2]=+g[j>>2]*+g[(c[h>>2]|0)+((c[m>>2]|0)+1<<2)>>2];g[(c[f>>2]|0)+((c[m>>2]|0)+2<<2)>>2]=+g[j>>2]*+g[(c[h>>2]|0)+((c[m>>2]|0)+2<<2)>>2];g[(c[f>>2]|0)+((c[m>>2]|0)+3<<2)>>2]=+g[j>>2]*+g[(c[h>>2]|0)+((c[m>>2]|0)+3<<2)>>2];c[m>>2]=(c[m>>2]|0)+4}while(1){if((c[m>>2]|0)>=(c[k>>2]|0))break;g[(c[f>>2]|0)+(c[m>>2]<<2)>>2]=+g[j>>2]*+g[(c[h>>2]|0)+(c[m>>2]<<2)>>2];c[m>>2]=(c[m>>2]|0)+1}i=n;return} + function ra(a){a=a|0;var b=0;b=i;i=i+a|0;i=i+15&-16;return b|0}function sa(){return i|0}function ta(a){a=a|0;i=a}function ua(a,b){a=a|0;b=b|0;i=a;j=b}function va(a,b){a=a|0;b=b|0;if(!n){n=a;o=b}}function wa(b){b=b|0;a[k>>0]=a[b>>0];a[k+1>>0]=a[b+1>>0];a[k+2>>0]=a[b+2>>0];a[k+3>>0]=a[b+3>>0]}function xa(b){b=b|0;a[k>>0]=a[b>>0];a[k+1>>0]=a[b+1>>0];a[k+2>>0]=a[b+2>>0];a[k+3>>0]=a[b+3>>0];a[k+4>>0]=a[b+4>>0];a[k+5>>0]=a[b+5>>0];a[k+6>>0]=a[b+6>>0];a[k+7>>0]=a[b+7>>0]}function ya(a){a=a|0;C=a}function za(){return C|0}function Aa(a,b,d,e,f){a=+a;b=b|0;d=d|0;e=e|0;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0;o=i;i=i+32|0;h=o+20|0;j=o+16|0;k=o+12|0;l=o+8|0;m=o+4|0;n=o;g[h>>2]=a;c[j>>2]=b;c[k>>2]=d;c[l>>2]=e;c[m>>2]=f;c[n>>2]=0;while(1){if((c[n>>2]|0)>=(c[l>>2]|0))break;if(+g[h>>2]<+g[(c[j>>2]|0)+(c[n>>2]<<2)>>2])break;c[n>>2]=(c[n>>2]|0)+1}if((c[n>>2]|0)>(c[m>>2]|0)?+g[h>>2]<+g[(c[j>>2]|0)+(c[m>>2]<<2)>>2]+ +g[(c[k>>2]|0)+(c[m>>2]<<2)>>2]:0)c[n>>2]=c[m>>2];if((c[n>>2]|0)>=(c[m>>2]|0)){b=c[n>>2]|0;i=o;return b|0}if(!(+g[h>>2]>+g[(c[j>>2]|0)+((c[m>>2]|0)-1<<2)>>2]-+g[(c[k>>2]|0)+((c[m>>2]|0)-1<<2)>>2])){b=c[n>>2]|0;i=o;return b|0}c[n>>2]=c[m>>2];b=c[n>>2]|0;i=o;return b|0}function Ba(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;a=(_(1664525,c[d>>2]|0)|0)+1013904223|0;i=b;return a|0}function Ca(a,d,e,f,h,j){a=a|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0.0;v=i;i=i+48|0;k=v+40|0;l=v+36|0;m=v+32|0;n=v+28|0;o=v+24|0;p=v+20|0;t=v+16|0;r=v+12|0;q=v+8|0;s=v+4|0;u=v;c[k>>2]=a;c[l>>2]=d;c[m>>2]=e;c[n>>2]=f;c[o>>2]=h;c[p>>2]=j;c[s>>2]=c[(c[k>>2]|0)+32>>2];c[q>>2]=c[(c[k>>2]|0)+44>>2]<>2];c[r>>2]=0;do{c[t>>2]=0;while(1){h=c[r>>2]|0;if((c[t>>2]|0)>=(c[n>>2]|0))break;f=_(h,c[q>>2]|0)|0;a=_(c[r>>2]|0,c[q>>2]|0)|0;g[u>>2]=+Da((c[l>>2]|0)+(f+(b[(c[s>>2]|0)+(c[t>>2]<<1)>>1]<>2])<<2)|0,(c[l>>2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[r>>2]>>2]=(c[c[r>>2]>>2]|0)+(c[K>>2]|0)>>1;c[K>>2]=c[c[r>>2]>>2];if((c[c[s>>2]>>2]|0)!=2){if(!(c[c[s>>2]>>2]|0))c[K>>2]=(c[K>>2]|0)-4}else c[K>>2]=(c[K>>2]|0)+4;if((c[K>>2]|0)>22){c[c[s>>2]>>2]=2;break}o=c[s>>2]|0;if((c[K>>2]|0)>18){c[o>>2]=1;break}else{c[o>>2]=0;break}}while(0);c[M>>2]=Ha(c[M>>2]|0,c[L>>2]|0)|0;c[M>>2]=(c[M>>2]|0)+(c[c[H>>2]>>2]|0)>>1;c[c[H>>2]>>2]=c[M>>2];c[M>>2]=((c[M>>2]|0)*3|0)+((3-(c[I>>2]|0)<<7)+64)+2>>2;do if((c[M>>2]|0)>=80){if((c[M>>2]|0)<256){c[J>>2]=2;break}if((c[M>>2]|0)<384){c[J>>2]=1;break}else{c[J>>2]=0;break}}else c[J>>2]=3;while(0);c[G>>2]=c[J>>2];M=c[G>>2]|0;i=N;return M|0}function Ja(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0;n=i;i=i+32|0;e=n+24|0;f=n+20|0;h=n+16|0;j=n+12|0;k=n+8|0;l=n+4|0;m=n;c[e>>2]=a;c[f>>2]=b;c[h>>2]=d;c[f>>2]=c[f>>2]>>1;c[j>>2]=0;while(1){if((c[j>>2]|0)>=(c[h>>2]|0))break;c[k>>2]=0;while(1){if((c[k>>2]|0)>=(c[f>>2]|0))break;d=_(c[h>>2]<<1,c[k>>2]|0)|0;g[l>>2]=+g[(c[e>>2]|0)+(d+(c[j>>2]|0)<<2)>>2]*.7071067690849304;d=_(c[h>>2]|0,(c[k>>2]<<1)+1|0)|0;g[m>>2]=+g[(c[e>>2]|0)+(d+(c[j>>2]|0)<<2)>>2]*.7071067690849304;d=_(c[h>>2]<<1,c[k>>2]|0)|0;g[(c[e>>2]|0)+(d+(c[j>>2]|0)<<2)>>2]=+g[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else p=(c[y>>2]|0)-((_((c[J>>2]|0)+1-(c[V>>2]|0)|0,(c[J>>2]|0)+2-(c[V>>2]|0)|0)|0)>>1)|0;c[w>>2]=p;jc(c[Q>>2]|0,c[w>>2]|0,(c[w>>2]|0)+(c[x>>2]|0)|0,c[y>>2]|0)}while(0);c[V>>2]=Ha(c[V>>2]<<14,c[J>>2]|0)|0;if((c[R>>2]|0)!=0&(c[F>>2]|0)!=0)if(!(c[V>>2]|0)){Xa(c[I>>2]|0,c[D>>2]|0,c[E>>2]|0,c[G>>2]|0,c[H>>2]|0,c[M>>2]|0);break}else{Ya(c[D>>2]|0,c[E>>2]|0,c[M>>2]|0);break}}else if(c[F>>2]|0){if(c[R>>2]|0){c[T>>2]=(c[V>>2]|0)>8192&1;a:do if(c[T>>2]|0){c[t>>2]=0;while(1){if((c[t>>2]|0)>=(c[M>>2]|0))break a;g[(c[E>>2]|0)+(c[t>>2]<<2)>>2]=-+g[(c[E>>2]|0)+(c[t>>2]<<2)>>2];c[t>>2]=(c[t>>2]|0)+1}}while(0);Xa(c[I>>2]|0,c[D>>2]|0,c[E>>2]|0,c[G>>2]|0,c[H>>2]|0,c[M>>2]|0)}do if((c[c[N>>2]>>2]|0)>16?(c[(c[p>>2]|0)+28>>2]|0)>16:0){p=c[Q>>2]|0;if(c[R>>2]|0){pc(p,c[T>>2]|0,2);break}else{c[T>>2]=dc(p,2)|0;break}}else v=60;while(0);if((v|0)==60)c[T>>2]=0;c[V>>2]=0}while(0);ba=Xb(c[Q>>2]|0)|0;c[W>>2]=ba-(c[X>>2]|0);ba=c[N>>2]|0;c[ba>>2]=(c[ba>>2]|0)-(c[W>>2]|0);if(!(c[V>>2]|0)){c[S>>2]=32767;c[U>>2]=0;ba=c[L>>2]|0;c[ba>>2]=c[ba>>2]&(1<>2])-1;c[P>>2]=-16384;ba=c[T>>2]|0;aa=c[K>>2]|0;c[aa>>2]=ba;aa=c[S>>2]|0;ba=c[K>>2]|0;ba=ba+4|0;c[ba>>2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|0)+92+8>>2]|0)+(b[(c[(c[m>>2]|0)+92+4>>2]|0)+(g+(c[l>>2]|0)<<1)>>1]|0);if(!(c[h>>2]|0)){n=0;i=k;return n|0}n=(d[(c[j>>2]|0)+(c[h>>2]|0)>>0]|0)+1|0;i=k;return n|0}function Va(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;a=c[b>>2]|0;if((c[b>>2]|0)<8){b=a;i=d;return b|0}b=8+(a&7)<<(c[b>>2]>>3)-1;i=d;return b|0}function Wa(a,d,e,f,g){a=a|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;o=i;i=i+32|0;p=o+28|0;h=o+24|0;j=o+20|0;k=o+16|0;q=o+12|0;n=o+8|0;m=o+4|0;l=o;c[p>>2]=a;c[h>>2]=d;c[j>>2]=e;c[k>>2]=f;c[q>>2]=g;c[l>>2]=(c[p>>2]<<1)-1;if((c[q>>2]|0)!=0&(c[p>>2]|0)==2)c[l>>2]=(c[l>>2]|0)+-1;q=(c[h>>2]|0)+(_(c[l>>2]|0,c[j>>2]|0)|0)|0;c[m>>2]=La(q,c[l>>2]|0)|0;if(((c[h>>2]|0)-(c[k>>2]|0)-32|0)<(c[m>>2]|0))h=(c[h>>2]|0)-(c[k>>2]|0)-32|0;else h=c[m>>2]|0;c[m>>2]=h;c[m>>2]=64<(c[m>>2]|0)?64:c[m>>2]|0;if((c[m>>2]|0)<4){c[n>>2]=1;q=c[n>>2]|0;i=o;return q|0}else{c[n>>2]=b[22328+((c[m>>2]&7)<<1)>>1]>>14-(c[m>>2]>>3);c[n>>2]=(c[n>>2]|0)+1>>1<<1;q=c[n>>2]|0;i=o;return q|0}return 0}function Xa(a,b,d,e,f,h){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0;r=i;i=i+64|0;v=r+56|0;j=r+52|0;k=r+48|0;x=r+44|0;y=r+40|0;l=r+36|0;w=r+32|0;o=r+28|0;m=r+24|0;n=r+20|0;u=r+16|0;t=r+12|0;s=r+8|0;q=r+4|0;p=r;c[v>>2]=a;c[j>>2]=b;c[k>>2]=d;c[x>>2]=e;c[y>>2]=f;c[l>>2]=h;c[w>>2]=c[y>>2];g[u>>2]=+g[(c[x>>2]|0)+(c[w>>2]<<2)>>2];g[t>>2]=+g[(c[x>>2]|0)+((c[w>>2]|0)+(c[(c[v>>2]|0)+8>>2]|0)<<2)>>2];g[s>>2]=+O(+(+g[u>>2]*+g[u>>2]+1.0000000036274937e-15+ +g[t>>2]*+g[t>>2]))+1.0000000036274937e-15;g[m>>2]=+g[u>>2]/+g[s>>2];g[n>>2]=+g[t>>2]/+g[s>>2];c[o>>2]=0;while(1){if((c[o>>2]|0)>=(c[l>>2]|0))break;g[p>>2]=+g[(c[j>>2]|0)+(c[o>>2]<<2)>>2];g[q>>2]=+g[(c[k>>2]|0)+(c[o>>2]<<2)>>2];g[(c[j>>2]|0)+(c[o>>2]<<2)>>2]=+g[m>>2]*+g[p>>2]+ +g[n>>2]*+g[q>>2];c[o>>2]=(c[o>>2]|0)+1}i=r;return}function Ya(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;e=m+20|0;f=m+16|0;h=m+12|0;j=m+8|0;l=m+4|0;k=m;c[e>>2]=a;c[f>>2]=b;c[h>>2]=d;c[j>>2]=0;while(1){if((c[j>>2]|0)>=(c[h>>2]|0))break;g[k>>2]=+g[(c[e>>2]|0)+(c[j>>2]<<2)>>2]*.7071067690849304;g[l>>2]=+g[(c[f>>2]|0)+(c[j>>2]<<2)>>2]*.7071067690849304;g[(c[e>>2]|0)+(c[j>>2]<<2)>>2]=+g[k>>2]+ +g[l>>2];g[(c[f>>2]|0)+(c[j>>2]<<2)>>2]=+g[l>>2]-+g[k>>2];c[j>>2]=(c[j>>2]|0)+1}i=m;return}function Za(a){a=a|0;var d=0,e=0,f=0,g=0;e=i;i=i+16|0;g=e+6|0;f=e;d=e+4|0;b[g>>1]=a;c[f>>2]=4096+(_(b[g>>1]|0,b[g>>1]|0)|0)>>13;b[d>>1]=c[f>>2];b[d>>1]=32767-(b[d>>1]|0)+(16384+(_(b[d>>1]|0,((16384+(_(b[d>>1]|0,(8277+(16384+(_(-626,b[d>>1]|0)|0)>>15)&65535)<<16>>16)|0)>>15)+-7651&65535)<<16>>16)|0)>>15);i=e;return 1+(b[d>>1]|0)&65535|0}function _a(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0;d=i;i=i+16|0;f=d+12|0;e=d+8|0;g=d+4|0;h=d;c[f>>2]=a;c[e>>2]=b;c[g>>2]=32-(aa(c[e>>2]|0)|0);c[h>>2]=32-(aa(c[f>>2]|0)|0);c[e>>2]=c[e>>2]<<15-(c[g>>2]|0);c[f>>2]=c[f>>2]<<15-(c[h>>2]|0);a=((c[h>>2]|0)-(c[g>>2]|0)<<11)+(16384+(_((c[f>>2]&65535)<<16>>16,((16384+(_((c[f>>2]&65535)<<16>>16,-2597)|0)>>15)+7932&65535)<<16>>16)|0)>>15)|0;a=a-(16384+(_((c[e>>2]&65535)<<16>>16,((16384+(_((c[e>>2]&65535)<<16>>16,-2597)|0)>>15)+7932&65535)<<16>>16)|0)>>15)|0;i=d;return a|0}function $a(a,b,d,e,f){a=a|0;b=b|0;d=+d;e=e|0;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0;u=i;i=i+64|0;h=u+60|0;j=u+56|0;k=u+52|0;l=u+48|0;o=u+40|0;v=u+36|0;w=u+32|0;m=u+28|0;n=u+24|0;x=u+20|0;t=u+16|0;q=u+12|0;s=u+8|0;r=u+4|0;p=u;c[h>>2]=a;c[j>>2]=b;g[k>>2]=d;c[l>>2]=e;c[u+44>>2]=f;g[v>>2]=0.0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[q>>2]<<2)>>2];g[s>>2]=+g[s>>2]+ +g[(c[k>>2]|0)+(c[q>>2]<<2)>>2]*+g[(c[m>>2]|0)+(c[q>>2]<<2)>>2];c[q>>2]=(c[q>>2]|0)+1}g[c[o>>2]>>2]=j;g[c[p>>2]>>2]=+g[s>>2];i=t;return}function bb(a){a=a|0;var b=0,d=0,e=0,f=0;e=i;i=i+16|0;f=e+4|0;b=e;c[f>>2]=a;a=c[f>>2]|0;a:do if((a|0)<16e3)if((a|0)<12e3){switch(a|0){case 8e3:break;default:{d=7;break a}}c[b>>2]=6;break}else{switch(a|0){case 12e3:break;default:{d=7;break a}}c[b>>2]=4;break}else{if((a|0)<24e3){switch(a|0){case 16e3:break;default:{d=7;break a}}c[b>>2]=3;break}if((a|0)<48e3){switch(a|0){case 24e3:break;default:{d=7;break a}}c[b>>2]=2;break}else{switch(a|0){case 48e3:break;default:{d=7;break a}}c[b>>2]=1;break}}while(0);if((d|0)==7)c[b>>2]=0;i=e;return c[b>>2]|0}function cb(a,b,d,e,f,h,j,k,l,m,n,o){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=+h;j=+j;k=k|0;l=l|0;m=m|0;n=n|0;o=o|0;var p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0;N=i;i=i+112|0;p=N+96|0;q=N+92|0;s=N+88|0;t=N+84|0;u=N+80|0;v=N+76|0;w=N+72|0;x=N+68|0;y=N+64|0;z=N+60|0;r=N+56|0;H=N+48|0;B=N+44|0;C=N+40|0;D=N+36|0;E=N+32|0;F=N+28|0;G=N+24|0;I=N+20|0;J=N+16|0;K=N+12|0;L=N+8|0;M=N+4|0;A=N;c[p>>2]=a;c[q>>2]=b;c[s>>2]=d;c[t>>2]=e;c[u>>2]=f;g[v>>2]=h;g[w>>2]=j;c[x>>2]=k;c[y>>2]=l;c[z>>2]=m;c[r>>2]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>2]|0)>0|(c[d>>2]|0)<-7){c[b>>2]=25264;a=c[b>>2]|0;i=e;return a|0}else{c[b>>2]=c[164+(0-(c[d>>2]|0)<<2)>>2];a=c[b>>2]|0;i=e;return a|0}return 0}function gb(){return 25415}function hb(a){a=a|0;var b=0,d=0,e=0;b=i;i=i+16|0;d=b+4|0;e=b;c[d>>2]=a;c[e>>2]=Jc(48e3,960,0)|0;a=ib(c[e>>2]|0,c[d>>2]|0)|0;i=b;return a|0}function ib(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0;e=i;i=i+16|0;f=e+8|0;g=e+4|0;d=e;c[f>>2]=a;c[g>>2]=b;a=204+((_(c[g>>2]|0,c[(c[f>>2]|0)+4>>2]|0)|0)-1<<2)|0;c[d>>2]=a+(c[g>>2]<<10<<2)+((_((c[g>>2]|0)*3|0,c[(c[f>>2]|0)+8>>2]|0)|0)<<2);i=e;return c[d>>2]|0}function jb(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0;k=i;i=i+32|0;f=k+20|0;g=k+16|0;h=k+12|0;m=k+8|0;l=k+4|0;j=k;c[g>>2]=a;c[h>>2]=b;c[m>>2]=d;c[l>>2]=e;b=c[g>>2]|0;a=Jc(48e3,960,0)|0;c[j>>2]=kb(b,a,c[m>>2]|0,c[l>>2]|0)|0;if(c[j>>2]|0){c[f>>2]=c[j>>2];m=c[f>>2]|0;i=k;return m|0}else{m=bb(c[h>>2]|0)|0;c[(c[g>>2]|0)+28>>2]=m;c[f>>2]=0;m=c[f>>2]|0;i=k;return m|0}return 0}function kb(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;f=l+20|0;g=l+16|0;h=l+12|0;j=l+8|0;k=l+4|0;c[g>>2]=a;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;if((c[j>>2]|0)<0|(c[j>>2]|0)>2){c[f>>2]=-1;a=c[f>>2]|0;i=l;return a|0}if((c[g>>2]|0)==0|(c[h>>2]|0)==0){c[f>>2]=-7;a=c[f>>2]|0;i=l;return a|0}else{a=c[g>>2]|0;oj(a|0,0,ib(c[h>>2]|0,c[j>>2]|0)|0)|0;c[c[g>>2]>>2]=c[h>>2];a=c[j>>2]|0;c[(c[g>>2]|0)+4>>2]=a;c[(c[g>>2]|0)+8>>2]=a;c[(c[g>>2]|0)+28>>2]=1;c[(c[g>>2]|0)+32>>2]=0;c[(c[g>>2]|0)+36>>2]=c[(c[c[g>>2]>>2]|0)+12>>2];c[(c[g>>2]|0)+48>>2]=1;c[(c[g>>2]|0)+72>>2]=c[k>>2];c[(c[g>>2]|0)+52>>2]=1;c[(c[g>>2]|0)+16>>2]=1;c[(c[g>>2]|0)+40>>2]=-1;c[(c[g>>2]|0)+44>>2]=0;c[(c[g>>2]|0)+12>>2]=0;c[(c[g>>2]|0)+24>>2]=5;c[(c[g>>2]|0)+60>>2]=24;lb(c[g>>2]|0,4028,l)|0;c[f>>2]=0;a=c[f>>2]|0;i=l;return a|0}return 0}function lb(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0;F=i;i=i+128|0;E=F+112|0;C=F+108|0;G=F+104|0;e=F+88|0;m=F+84|0;n=F+80|0;v=F+76|0;w=F+72|0;x=F+68|0;y=F+64|0;z=F+60|0;D=F+56|0;A=F+52|0;B=F+48|0;o=F+44|0;p=F+40|0;f=F+36|0;j=F+32|0;k=F+28|0;l=F+24|0;q=F+20|0;h=F+16|0;r=F+12|0;s=F+8|0;t=F+4|0;u=F;c[C>>2]=a;c[G>>2]=b;c[e>>2]=d;do switch(c[G>>2]|0){case 4010:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[m>>2]=G;if((c[m>>2]|0)<0|(c[m>>2]|0)>10)e=41;else{c[(c[C>>2]|0)+24>>2]=c[m>>2];e=40}break}case 10010:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[n>>2]=G;if((c[n>>2]|0)>=0?(c[n>>2]|0)<(c[(c[c[C>>2]>>2]|0)+8>>2]|0):0){c[(c[C>>2]|0)+32>>2]=c[n>>2];e=40}else e=41;break}case 10012:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[v>>2]=G;if((c[v>>2]|0)>=1?(c[v>>2]|0)<=(c[(c[c[C>>2]>>2]|0)+8>>2]|0):0){c[(c[C>>2]|0)+36>>2]=c[v>>2];e=40}else e=41;break}case 10002:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[w>>2]=G;if((c[w>>2]|0)<0|(c[w>>2]|0)>2)e=41;else{c[(c[C>>2]|0)+20>>2]=(c[w>>2]|0)<=1&1;c[(c[C>>2]|0)+12>>2]=(c[w>>2]|0)==0&1;e=40}break}case 4014:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[x>>2]=G;if((c[x>>2]|0)<0|(c[x>>2]|0)>100)e=41;else{c[(c[C>>2]|0)+56>>2]=c[x>>2];e=40}break}case 4020:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[y>>2]=G;c[(c[C>>2]|0)+52>>2]=c[y>>2];e=40;break}case 4006:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[z>>2]=G;c[(c[C>>2]|0)+44>>2]=c[z>>2];e=40;break}case 4002:{d=(c[e>>2]|0)+(4-1)&~(4-1);G=c[d>>2]|0;c[e>>2]=d+4;c[D>>2]=G;if((c[D>>2]|0)<=500&(c[D>>2]|0)!=-1)e=41;else{if((c[D>>2]|0)<((c[(c[C>>2]|0)+4>>2]|0)*26e4|0))e=c[D>>2]|0;else e=(c[(c[C>>2]|0)+4>>2]|0)*26e4|0;c[D>>2]=e;c[(c[C>>2]|0)+40>>2]=c[D>>2];e=40}break}case 10008:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[A>>2]=G;if((c[A>>2]|0)<1|(c[A>>2]|0)>2)e=41;else{c[(c[C>>2]|0)+8>>2]=c[A>>2];e=40}break}case 4036:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[B>>2]=G;if((c[B>>2]|0)<8|(c[B>>2]|0)>24)e=41;else{c[(c[C>>2]|0)+60>>2]=c[B>>2];e=40}break}case 4037:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[o>>2]=G;c[c[o>>2]>>2]=c[(c[C>>2]|0)+60>>2];e=40;break}case 4040:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[p>>2]=G;c[(c[C>>2]|0)+64>>2]=c[p>>2];e=40;break}case 4028:{c[j>>2]=(c[C>>2]|0)+200+((_(c[(c[C>>2]|0)+4>>2]|0,(c[(c[c[C>>2]>>2]|0)+4>>2]|0)+1024|0)|0)<<2);c[k>>2]=(c[j>>2]|0)+((_(c[(c[C>>2]|0)+4>>2]|0,c[(c[c[C>>2]>>2]|0)+8>>2]|0)|0)<<2);c[l>>2]=(c[k>>2]|0)+((_(c[(c[C>>2]|0)+4>>2]|0,c[(c[c[C>>2]>>2]|0)+8>>2]|0)|0)<<2);oj((c[C>>2]|0)+76|0,0,(ib(c[c[C>>2]>>2]|0,c[(c[C>>2]|0)+4>>2]|0)|0)-((c[C>>2]|0)+76-(c[C>>2]|0))|0)|0;c[f>>2]=0;while(1){if((c[f>>2]|0)>=(_(c[(c[C>>2]|0)+4>>2]|0,c[(c[c[C>>2]>>2]|0)+8>>2]|0)|0))break;g[(c[l>>2]|0)+(c[f>>2]<<2)>>2]=-28.0;g[(c[k>>2]|0)+(c[f>>2]<<2)>>2]=-28.0;c[f>>2]=(c[f>>2]|0)+1}c[(c[C>>2]|0)+172>>2]=0;g[(c[C>>2]|0)+84>>2]=1.0;c[(c[C>>2]|0)+80>>2]=2;c[(c[C>>2]|0)+88>>2]=256;c[(c[C>>2]|0)+96>>2]=0;c[(c[C>>2]|0)+100>>2]=0;e=40;break}case 10016:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[q>>2]=G;c[(c[C>>2]|0)+48>>2]=c[q>>2];e=40;break}case 10022:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[h>>2]=G;if(c[h>>2]|0){pj((c[C>>2]|0)+120|0,c[h>>2]|0,28|0)|0;e=40}else e=40;break}case 10015:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[r>>2]=G;if(!(c[r>>2]|0))e=41;else{c[c[r>>2]>>2]=c[c[C>>2]>>2];e=40}break}case 4031:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[s>>2]=G;if(!(c[s>>2]|0))e=41;else{c[c[s>>2]>>2]=c[(c[C>>2]|0)+76>>2];e=40}break}case 10024:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[t>>2]=G;c[(c[C>>2]|0)+68>>2]=c[t>>2];e=40;break}case 10026:{D=(c[e>>2]|0)+(4-1)&~(4-1);G=c[D>>2]|0;c[e>>2]=D+4;c[u>>2]=G;c[(c[C>>2]|0)+192>>2]=c[u>>2];e=40;break}default:{c[E>>2]=-5;G=c[E>>2]|0;i=F;return G|0}}while(0);if((e|0)==40){c[E>>2]=0;G=c[E>>2]|0;i=F;return G|0}else if((e|0)==41){c[E>>2]=-1;G=c[E>>2]|0;i=F;return G|0}return 0}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b=0,kb=0,lb=0,nb=0,vb=0,yb=0;yb=i;i=i+448|0;gb=yb+440|0;hb=yb+436|0;s=yb+432|0;k=yb+428|0;o=yb+424|0;ib=yb+420|0;jb=yb+416|0;$a=yb+412|0;Za=yb+408|0;Ma=yb+404|0;Ga=yb+400|0;p=yb+352|0;y=yb+348|0;bb=yb+344|0;cb=yb+340|0;db=yb+336|0;Wa=yb+332|0;nb=yb+328|0;Ya=yb+324|0;Ja=yb+320|0;La=yb+316|0;T=yb+312|0;S=yb+308|0;xa=yb+304|0;wa=yb+300|0;fb=yb+296|0;_a=yb+292|0;U=yb+288|0;Qa=yb+284|0;P=yb+280|0;Fa=yb+276|0;Ua=yb+272|0;Sa=yb+268|0;Ra=yb+264|0;V=yb+260|0;X=yb+256|0;za=yb+252|0;fa=yb+248|0;ra=yb+244|0;Pa=yb+240|0;ma=yb+236|0;Va=yb+232|0;R=yb+228|0;Oa=yb+224|0;Na=yb+220|0;Xa=yb+216|0;O=yb+212|0;pa=yb+208|0;ka=yb+204|0;qa=yb+200|0;u=yb+196|0;ha=yb+192|0;Ta=yb+188|0;ab=yb+184|0;x=yb+180|0;Z=yb+176|0;M=yb+172|0;Ha=yb+168|0;vb=yb+164|0;la=yb+160|0;oa=yb+156|0;ea=yb+152|0;Ba=yb+148|0;m=yb+144|0;n=yb+140|0;q=yb+136|0;r=yb+132|0;kb=yb+128|0;t=yb+124|0;v=yb+120|0;z=yb+116|0;w=yb+112|0;I=yb+108|0;E=yb+104|0;C=yb+100|0;H=yb+96|0;G=yb+92|0;A=yb+88|0;B=yb+84|0;D=yb+80|0;F=yb+76|0;J=yb+72|0;K=yb+68|0;L=yb+64|0;N=yb+60|0;da=yb+56|0;ca=yb+52|0;Y=yb+48|0;W=yb+44|0;ba=yb+40|0;$=yb+36|0;ta=yb+32|0;ua=yb+28|0;ya=yb+24|0;ga=yb+20|0;ja=yb+16|0;va=yb+12|0;sa=yb+8|0;Da=yb+4|0;lb=yb;c[hb>>2]=a;c[s>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]|0)+148+(c[Za>>2]<<2)|0,c[t>>2]|0);r=(c[Za>>2]|0)+1|0;c[Za>>2]=r}while((r|0)<(c[Ya>>2]|0));if((c[wa>>2]|0)>3?(c[(c[hb>>2]|0)+68>>2]|0)!=0:0)if((c[fb>>2]|0)!=0|(c[Xa>>2]|0)!=0)k=0;else Q=63;else if(((c[fb>>2]|0)==0?(c[wa>>2]|0)>((c[Ja>>2]|0)*12|0):0)^1|(c[Xa>>2]|0)!=0)k=0;else Q=63;if((Q|0)==63)if(!(c[(c[hb>>2]|0)+20>>2]|0)?(c[(c[hb>>2]|0)+24>>2]|0)>=5:0){if((c[La>>2]|0)!=3?(c[(c[hb>>2]|0)+116>>2]|0)!=0:0)k=(c[(c[hb>>2]|0)+64>>2]|0)==5010;else k=0;k=k^1}else k=0;c[v>>2]=k&1;c[Va>>2]=c[(c[hb>>2]|0)+100>>2];c[R>>2]=qb(c[hb>>2]|0,e,c[y>>2]|0,c[Ya>>2]|0,c[Ma>>2]|0,c[Va>>2]|0,Ua,Sa,z,c[v>>2]|0,c[wa>>2]|0)|0;if(!(!(+g[Sa>>2]>.4000000059604645)?!(+g[(c[hb>>2]|0)+108>>2]>.4000000059604645):0))Q=70;do if((Q|0)==70){if(c[(c[hb>>2]|0)+120>>2]|0?!(+g[(c[hb>>2]|0)+120+4>>2]>.3):0)break;if(!(+(c[Ua>>2]|0)>+(c[(c[hb>>2]|0)+104>>2]|0)*1.26)?!(+(c[Ua>>2]|0)<+(c[(c[hb>>2]|0)+104>>2]|0)*.79):0)break;c[ka>>2]=1}while(0);if(!(c[R>>2]|0)){if((c[fb>>2]|0)==0?((c[ma>>2]|0)+16|0)<=(c[fa>>2]|0):0)pc(c[jb>>2]|0,0,1)}else{pc(c[jb>>2]|0,1,1);c[Ua>>2]=(c[Ua>>2]|0)+1;c[w>>2]=32-(aa(c[Ua>>2]|0)|0)-5;rc(c[jb>>2]|0,c[w>>2]|0,6);sc(c[jb>>2]|0,(c[Ua>>2]|0)-(16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}while(0);sb(c[Ta>>2]|0,c[Wa>>2]|0,e,f,c[Ja>>2]|0,c[Ya>>2]|0,c[La>>2]|0,c[(c[hb>>2]|0)+28>>2]|0,c[(c[hb>>2]|0)+72>>2]|0);if((c[Ya>>2]|0)==2&(c[Ja>>2]|0)==1)c[O>>2]=0;Ca(c[Ta>>2]|0,f,p,c[U>>2]|0,c[Ja>>2]|0,c[La>>2]|0);b:do if(c[(c[hb>>2]|0)+68>>2]|0){c[$a>>2]=2;while(1){if((c[$a>>2]|0)>=(c[_a>>2]|0))break b;if(+g[p+(c[$a>>2]<<2)>>2]<+g[p>>2]*9.999999747378752e-05)l=+g[p+(c[$a>>2]<<2)>>2];else l=+g[p>>2]*9.999999747378752e-05;g[p+(c[$a>>2]<<2)>>2]=l;if(+g[p+(c[$a>>2]<<2)>>2]>1.0000000036274937e-15)l=+g[p+(c[$a>>2]<<2)>>2];else l=1.0000000036274937e-15;g[p+(c[$a>>2]<<2)>>2]=l;c[$a>>2]=(c[$a>>2]|0)+1}}while(0);id(c[Ta>>2]|0,c[U>>2]|0,c[_a>>2]|0,p,o,c[Ja>>2]|0);z=(_(c[Ja>>2]|0,c[ab>>2]|0)|0)<<2;m=i;i=i+((1*z|0)+15&-16)|0;oj(m|0,0,c[_a>>2]<<2|0)|0;do if(!(c[fb>>2]|0)){if(!(c[(c[hb>>2]|0)+192>>2]|0))break;if(c[(c[hb>>2]|0)+68>>2]|0)break;g[H>>2]=0.0;g[G>>2]=0.0;c[A>>2]=0;if(2>(c[(c[hb>>2]|0)+92>>2]|0))k=2;else k=c[(c[hb>>2]|0)+92>>2]|0;c[I>>2]=k;c[Za>>2]=0;while(1){if((c[Za>>2]|0)>=(c[Ja>>2]|0))break;c[$a>>2]=0;while(1){if((c[$a>>2]|0)>=(c[I>>2]|0))break;z=_(c[ab>>2]|0,c[Za>>2]|0)|0;if(+g[(c[(c[hb>>2]|0)+192>>2]|0)+(z+(c[$a>>2]|0)<<2)>>2]<.25){z=_(c[ab>>2]|0,c[Za>>2]|0)|0;l=+g[(c[(c[hb>>2]|0)+192>>2]|0)+(z+(c[$a>>2]|0)<<2)>>2]}else l=.25;do if(l>-2.0){z=_(c[ab>>2]|0,c[Za>>2]|0)|0;if(!(+g[(c[(c[hb>>2]|0)+192>>2]|0)+(z+(c[$a>>2]|0)<<2)>>2]<.25)){l=.25;break}z=_(c[ab>>2]|0,c[Za>>2]|0)|0;l=+g[(c[(c[hb>>2]|0)+192>>2]|0)+(z+(c[$a>>2]|0)<<2)>>2]}else l=-2.0;while(0);g[B>>2]=l;if(+g[B>>2]>0.0)g[B>>2]=+g[B>>2]*.5;g[H>>2]=+g[H>>2]+ +g[B>>2]*+((b[(c[Z>>2]|0)+((c[$a>>2]|0)+1<<1)>>1]|0)-(b[(c[Z>>2]|0)+(c[$a>>2]<<1)>>1]|0)|0);c[A>>2]=(c[A>>2]|0)+((b[(c[Z>>2]|0)+((c[$a>>2]|0)+1<<1)>>1]|0)-(b[(c[Z>>2]|0)+(c[$a>>2]<<1)>>1]|0));g[G>>2]=+g[G>>2]+ +g[B>>2]*+(1+(c[$a>>2]<<1)-(c[I>>2]|0)|0);c[$a>>2]=(c[$a>>2]|0)+1}c[Za>>2]=(c[Za>>2]|0)+1}g[H>>2]=+g[H>>2]/+(c[A>>2]|0);g[H>>2]=+g[H>>2]+.20000000298023224;B=_(c[Ja>>2]|0,(c[I>>2]|0)-1|0)|0;B=_(B,(c[I>>2]|0)+1|0)|0;g[G>>2]=+g[G>>2]*6.0/+(_(B,c[I>>2]|0)|0);g[G>>2]=+g[G>>2]*.5;if((+g[G>>2]<.03099999949336052?+g[G>>2]:.03099999949336052)>-.03099999949336052)l=+g[G>>2]<.03099999949336052?+g[G>>2]:.03099999949336052;else l=-.03099999949336052;g[G>>2]=l;c[E>>2]=0;while(1){if((b[(c[Z>>2]|0)+((c[E>>2]|0)+1<<1)>>1]|0)>=((b[(c[Z>>2]|0)+(c[I>>2]<<1)>>1]|0)/2|0|0))break;c[E>>2]=(c[E>>2]|0)+1}c[C>>2]=0;c[$a>>2]=0;while(1){if((c[$a>>2]|0)>=(c[I>>2]|0))break;g[D>>2]=+g[H>>2]+ +g[G>>2]*+((c[$a>>2]|0)-(c[E>>2]|0)|0);l=+g[(c[(c[hb>>2]|0)+192>>2]|0)+(c[$a>>2]<<2)>>2];if((c[Ja>>2]|0)==2){if(l>+g[(c[(c[hb>>2]|0)+192>>2]|0)+((c[ab>>2]|0)+(c[$a>>2]|0)<<2)>>2])l=+g[(c[(c[hb>>2]|0)+192>>2]|0)+(c[$a>>2]<<2)>>2];else l=+g[(c[(c[hb>>2]|0)+192>>2]|0)+((c[ab>>2]|0)+(c[$a>>2]|0)<<2)>>2];g[F>>2]=l}else g[F>>2]=l;g[F>>2]=+g[F>>2]<0.0?+g[F>>2]:0.0;g[F>>2]=+g[F>>2]-+g[D>>2];if(+g[F>>2]>.25){g[m+(c[$a>>2]<<2)>>2]=+g[F>>2]-.25;c[C>>2]=(c[C>>2]|0)+1}c[$a>>2]=(c[$a>>2]|0)+1}c:do if((c[C>>2]|0)>=3){g[H>>2]=+g[H>>2]+.25;if(+g[H>>2]>0.0){g[H>>2]=0.0;g[G>>2]=0.0;oj(m|0,0,c[I>>2]<<2|0)|0;break}c[$a>>2]=0;while(1){if((c[$a>>2]|0)>=(c[I>>2]|0))break c;if(0.0>+g[m+(c[$a>>2]<<2)>>2]-.25)l=0.0;else l=+g[m+(c[$a>>2]<<2)>>2]-.25;g[m+(c[$a>>2]<<2)>>2]=l;c[$a>>2]=(c[$a>>2]|0)+1}}while(0);g[H>>2]=+g[H>>2]+.20000000298023224;g[ea>>2]=+g[G>>2]*64.0;g[la>>2]=+g[H>>2]}while(0);if(!(c[(c[hb>>2]|0)+68>>2]|0)){g[J>>2]=-10.0;g[K>>2]=0.0;if(c[Wa>>2]|0)l=+(c[La>>2]|0)*.5;else l=0.0;g[L>>2]=l;c[$a>>2]=c[fb>>2];while(1){if((c[$a>>2]|0)>=(c[_a>>2]|0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]|0,p,o,c[Ja>>2]|0);c[$a>>2]=0;while(1){if((c[$a>>2]|0)>=(_(c[Ja>>2]|0,c[ab>>2]|0)|0))break;M=j+(c[$a>>2]<<2)|0;g[M>>2]=+g[M>>2]+ +(c[La>>2]|0)*.5;c[$a>>2]=(c[$a>>2]|0)+1}g[pa>>2]=.20000000298023224}while(0);do if((c[La>>2]|0)>0){M=(ob(c[jb>>2]|0)|0)+3|0;if((M|0)>(c[fa>>2]|0))break;pc(c[jb>>2]|0,c[nb>>2]|0,3)}while(0);a=(_(c[Ja>>2]|0,c[Ma>>2]|0)|0)<<2;n=i;i=i+((1*a|0)+15&-16)|0;Ea(c[Ta>>2]|0,f,n,p,c[U>>2]|0,c[Ja>>2]|0,c[T>>2]|0);a=i;i=i+((1*(c[ab>>2]<<2)|0)+15&-16)|0;d:do if((c[fb>>2]|0)==0?(c[V>>2]|0)>=((c[Ja>>2]|0)*15|0):0){if((c[(c[hb>>2]|0)+24>>2]|0)<2){Q=192;break}if(c[(c[hb>>2]|0)+68>>2]|0){Q=192;break}do if((c[V>>2]|0)>=40){if((c[V>>2]|0)<60){c[N>>2]=6;break}if((c[V>>2]|0)<100){c[N>>2]=4;break}else{c[N>>2]=3;break}}else c[N>>2]=12;while(0);c[N>>2]=c[N>>2]<<1;c[S>>2]=ub(c[Ta>>2]|0,c[U>>2]|0,c[nb>>2]|0,a,c[N>>2]|0,n,c[Ma>>2]|0,c[La>>2]|0,P,+g[pa>>2],c[O>>2]|0)|0;c[$a>>2]=c[U>>2];while(1){if((c[$a>>2]|0)>=(c[_a>>2]|0))break d;c[a+(c[$a>>2]<<2)>>2]=c[a+((c[U>>2]|0)-1<<2)>>2];c[$a>>2]=(c[$a>>2]|0)+1}}else Q=192;while(0);if((Q|0)==192){c[P>>2]=0;c[$a>>2]=0;while(1){if((c[$a>>2]|0)>=(c[_a>>2]|0))break;c[a+(c[$a>>2]<<2)>>2]=c[nb>>2];c[$a>>2]=(c[$a>>2]|0)+1}c[S>>2]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)c[X>>2]=2>((c[X>>2]|0)-1|0)?2:(c[X>>2]|0)-1|0;c[h+(c[$a>>2]<<2)>>2]=c[W>>2];c[$a>>2]=(c[$a>>2]|0)+1}if((k|0)==2){if(c[La>>2]|0)c[Ra>>2]=Ab(c[Ta>>2]|0,n,c[La>>2]|0,c[Ma>>2]|0)|0;da=Aa(+((c[Ba>>2]|0)/1e3|0|0),196,280,21,c[(c[hb>>2]|0)+188>>2]|0)|0;c[(c[hb>>2]|0)+188>>2]=da;if((c[fb>>2]|0)>(c[(c[hb>>2]|0)+188>>2]|0))k=c[fb>>2]|0;else k=c[(c[hb>>2]|0)+188>>2]|0;do if((c[_a>>2]|0)>=(k|0))if((c[fb>>2]|0)>(c[(c[hb>>2]|0)+188>>2]|0)){k=c[fb>>2]|0;break}else{k=c[(c[hb>>2]|0)+188>>2]|0;break}else k=c[_a>>2]|0;while(0);c[(c[hb>>2]|0)+188>>2]=k}c[Fa>>2]=5;if(((c[ma>>2]|0)+48|0)<=((c[fa>>2]|0)-(c[ra>>2]|0)|0)){if(c[(c[hb>>2]|0)+68>>2]|0)c[Fa>>2]=5;else c[Fa>>2]=Bb(c[Ta>>2]|0,n,o,c[_a>>2]|0,c[La>>2]|0,c[Ja>>2]|0,c[Ma>>2]|0,(c[hb>>2]|0)+120|0,(c[hb>>2]|0)+184|0,+g[pa>>2],c[(c[hb>>2]|0)+188>>2]|0,+g[ea>>2],c[(c[hb>>2]|0)+72>>2]|0)|0;qc(c[jb>>2]|0,c[Fa>>2]|0,25564,7);c[ma>>2]=Xb(c[jb>>2]|0)|0}if((c[za>>2]|0)>0){c[va>>2]=(c[(c[Ta>>2]|0)+36>>2]|0)-(c[La>>2]|0);if((c[ib>>2]|0)<(1275>>3-(c[La>>2]|0)|0))k=c[ib>>2]|0;else k=1275>>3-(c[La>>2]|0);c[ib>>2]=k;c[ga>>2]=(c[za>>2]|0)-(((c[Ja>>2]|0)*40|0)+20<<3);if(c[(c[hb>>2]|0)+52>>2]|0)c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])|0;za=(c[hb>>2]|0)+168|0;c[za>>2]=(c[za>>2]|0)+~~(+g[ta>>2]*+(ya-(c[(c[hb>>2]|0)+172>>2]|0)-(c[(c[hb>>2]|0)+168>>2]|0)|0));c[(c[hb>>2]|0)+172>>2]=0-(c[(c[hb>>2]|0)+168>>2]|0)}do if(c[(c[hb>>2]|0)+52>>2]|0){if((c[(c[hb>>2]|0)+164>>2]|0)>=0)break;c[sa>>2]=(0-(c[(c[hb>>2]|0)+164>>2]|0)|0)/64|0;c[wa>>2]=(c[wa>>2]|0)+(c[Xa>>2]|0?0:c[sa>>2]|0);c[(c[hb>>2]|0)+164>>2]=0}while(0);if((c[ib>>2]|0)<((c[wa>>2]|0)+(c[xa>>2]|0)|0))k=c[ib>>2]|0;else k=(c[wa>>2]|0)+(c[xa>>2]|0)|0;c[ib>>2]=k;vc(c[jb>>2]|0,c[ib>>2]|0)}m=i;i=i+((1*(c[ab>>2]<<2)|0)+15&-16)|0;j=i;i=i+((1*(c[ab>>2]<<2)|0)+15&-16)|0;e=i;i=i+((1*(c[ab>>2]<<2)|0)+15&-16)|0;za=c[ib>>2]<<3<<3;c[Ga>>2]=za-(Xb(c[jb>>2]|0)|0)-1;if((c[nb>>2]|0)!=0&(c[La>>2]|0)>=2)k=(c[Ga>>2]|0)>=((c[La>>2]|0)+2<<3|0);else k=0;c[Oa>>2]=k?8:0;c[Ga>>2]=(c[Ga>>2]|0)-(c[Oa>>2]|0);c[Ha>>2]=(c[_a>>2]|0)-1;if(c[(c[hb>>2]|0)+120>>2]|0){do if((c[Ba>>2]|0)>=((c[Ja>>2]|0)*32e3|0)){if((c[Ba>>2]|0)<((c[Ja>>2]|0)*48e3|0)){c[Da>>2]=16;break}if((c[Ba>>2]|0)<((c[Ja>>2]|0)*6e4|0)){c[Da>>2]=18;break}if((c[Ba>>2]|0)<((c[Ja>>2]|0)*8e4|0)){c[Da>>2]=19;break}else{c[Da>>2]=20;break}}else c[Da>>2]=13;while(0);if((c[(c[hb>>2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l<<2)|0)+15&-16)|0;c[J>>2]=a;c[J+4>>2]=a+((c[x>>2]|0)+1024<<2);c[C>>2]=0;do{pj(c[J+(c[C>>2]<<2)>>2]|0,(c[v>>2]|0)+(c[C>>2]<<10<<2)|0,4096|0)|0;a=(c[t>>2]|0)+((_(c[C>>2]|0,(c[x>>2]|0)+(c[G>>2]|0)|0)|0)<<2)|0;pj((c[J+(c[C>>2]<<2)>>2]|0)+4096|0,a+(c[G>>2]<<2)|0,(c[x>>2]<<2)+0|0)|0;a=(c[C>>2]|0)+1|0;c[C>>2]=a}while((a|0)<(c[w>>2]|0));if(c[q>>2]|0){l=1024+(c[x>>2]|0)>>1;c[p>>2]=ia()|0;a=i;i=i+((1*(l<<2)|0)+15&-16)|0;Kc(J,a,1024+(c[x>>2]|0)|0,c[w>>2]|0,c[(c[s>>2]|0)+72>>2]|0);Pc(a+2048|0,a,c[x>>2]|0,979,I,c[(c[s>>2]|0)+72>>2]|0);c[I>>2]=1024-(c[I>>2]|0);g[D>>2]=+Rc(a,1024,15,c[x>>2]|0,I,c[(c[s>>2]|0)+104>>2]|0,+g[(c[s>>2]|0)+108>>2],c[(c[s>>2]|0)+72>>2]|0);if((c[I>>2]|0)>1022)c[I>>2]=1022;g[D>>2]=+g[D>>2]*.699999988079071;if((c[(c[s>>2]|0)+56>>2]|0)>2)g[D>>2]=+g[D>>2]*.5;if((c[(c[s>>2]|0)+56>>2]|0)>4)g[D>>2]=+g[D>>2]*.5;if((c[(c[s>>2]|0)+56>>2]|0)>8)g[D>>2]=0.0;na(c[p>>2]|0)}else{g[D>>2]=0.0;c[I>>2]=15}g[r>>2]=.20000000298023224;a=(N((c[I>>2]|0)-(c[(c[s>>2]|0)+104>>2]|0)|0)|0)*10|0;if((a|0)>(c[I>>2]|0))g[r>>2]=+g[r>>2]+.20000000298023224;if((c[o>>2]|0)<25)g[r>>2]=+g[r>>2]+.10000000149011612;if((c[o>>2]|0)<35)g[r>>2]=+g[r>>2]+.10000000149011612;if(+g[(c[s>>2]|0)+108>>2]>.4000000059604645)g[r>>2]=+g[r>>2]-.10000000149011612;if(+g[(c[s>>2]|0)+108>>2]>.550000011920929)g[r>>2]=+g[r>>2]-.10000000149011612;g[r>>2]=+g[r>>2]>.20000000298023224?+g[r>>2]:.20000000298023224;if(+g[D>>2]<+g[r>>2]){g[D>>2]=0.0;c[H>>2]=0;c[K>>2]=0}else{if(+N(+(+g[D>>2]-+g[(c[s>>2]|0)+108>>2]))<.10000000149011612)g[D>>2]=+g[(c[s>>2]|0)+108>>2];c[K>>2]=~~+M(+(+g[D>>2]*32.0/3.0+.5))-1;if(0>((7<(c[K>>2]|0)?7:c[K>>2]|0)|0))o=0;else o=7<(c[K>>2]|0)?7:c[K>>2]|0;c[K>>2]=o;g[D>>2]=+((c[K>>2]|0)+1|0)*.09375;c[H>>2]=1}c[C>>2]=0;do{c[F>>2]=(c[(c[E>>2]|0)+44>>2]|0)-(c[G>>2]|0);if((c[(c[s>>2]|0)+104>>2]|0)>15)o=c[(c[s>>2]|0)+104>>2]|0;else o=15;c[(c[s>>2]|0)+104>>2]=o;l=(c[t>>2]|0)+((_(c[C>>2]|0,(c[x>>2]|0)+(c[G>>2]|0)|0)|0)<<2)|0;a=(c[s>>2]|0)+200+((_(c[C>>2]|0,c[G>>2]|0)|0)<<2)|0;pj(l|0,a|0,(c[G>>2]<<2)+0|0)|0;if(c[F>>2]|0){a=(c[t>>2]|0)+((_(c[C>>2]|0,(c[x>>2]|0)+(c[G>>2]|0)|0)|0)<<2)|0;cb(a+(c[G>>2]<<2)|0,(c[J+(c[C>>2]<<2)>>2]|0)+4096|0,c[(c[s>>2]|0)+104>>2]|0,c[(c[s>>2]|0)+104>>2]|0,c[F>>2]|0,-+g[(c[s>>2]|0)+108>>2],-+g[(c[s>>2]|0)+108>>2],c[(c[s>>2]|0)+112>>2]|0,c[(c[s>>2]|0)+112>>2]|0,0,0,c[(c[s>>2]|0)+72>>2]|0)}a=(c[t>>2]|0)+((_(c[C>>2]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=0.0;g[t>>2]=0.0;c[p>>2]=(c[r>>2]|0)-1;while(1){if((c[p>>2]|0)<0)break;g[b+(c[p>>2]<<2)>>2]=+g[v>>2]+(+g[b+(c[p>>2]<<2)>>2]-+g[v>>2])*.125;g[v>>2]=+g[b+(c[p>>2]<<2)>>2];g[t>>2]=+g[t>>2]>+g[v>>2]?+g[t>>2]:+g[v>>2];c[p>>2]=(c[p>>2]|0)+-1}g[u>>2]=+O(+(+g[u>>2]*+g[t>>2]*.5*+(c[r>>2]|0)));g[x>>2]=+(c[r>>2]|0)/(+g[u>>2]+1.0000000036274937e-15);c[y>>2]=0;c[p>>2]=12;while(1){if((c[p>>2]|0)>=((c[r>>2]|0)-5|0))break;if(127.0<+M(+(+g[x>>2]*64.0*(+g[b+(c[p>>2]<<2)>>2]+1.0000000036274937e-15))))j=127.0;else j=+M(+(+g[x>>2]*64.0*(+g[b+(c[p>>2]<<2)>>2]+1.0000000036274937e-15)));if(!(0.0>j))if(127.0<+M(+(+g[x>>2]*64.0*(+g[b+(c[p>>2]<<2)>>2]+1.0000000036274937e-15))))j=127.0;else j=+M(+(+g[x>>2]*64.0*(+g[b+(c[p>>2]<<2)>>2]+1.0000000036274937e-15)));else j=0.0;c[q>>2]=~~j;c[y>>2]=(c[y>>2]|0)+(d[25432+(c[q>>2]|0)>>0]|0);c[p>>2]=(c[p>>2]|0)+4}c[y>>2]=(c[y>>2]<<6<<2|0)/(((c[r>>2]|0)-17|0)*6|0)|0;if((c[y>>2]|0)>(c[s>>2]|0)){c[c[n>>2]>>2]=c[o>>2];c[s>>2]=c[y>>2]}c[o>>2]=(c[o>>2]|0)+1}c[E>>2]=(c[s>>2]|0)>200&1;if(0.0>+O(+(+((c[s>>2]|0)*27|0)))-42.0)j=0.0;else j=+O(+(+((c[s>>2]|0)*27|0)))-42.0;g[F>>2]=j;if(0.0>(163.0<+g[F>>2]?163.0:+g[F>>2])*.006899999920278788-.139){j=0.0;j=+O(+j);F=c[C>>2]|0;g[F>>2]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[e>>2]=+g[j>>2];g[j>>2]=+g[l>>2];g[m>>2]=+g[f>>2];g[f>>2]=+g[k>>2];g[k>>2]=+g[m>>2]}if(+g[h>>2]>+g[f>>2])if(+g[f>>2]<+g[j>>2]){g[b>>2]=+g[h>>2]<+g[j>>2]?+g[h>>2]:+g[j>>2];o=+g[b>>2];i=n;return +o}else{g[b>>2]=+g[k>>2]<+g[f>>2]?+g[k>>2]:+g[f>>2];o=+g[b>>2];i=n;return +o}else if(+g[h>>2]<+g[j>>2]){g[b>>2]=+g[f>>2]<+g[j>>2]?+g[f>>2]:+g[j>>2];o=+g[b>>2];i=n;return +o}else{g[b>>2]=+g[h>>2]<+g[k>>2]?+g[h>>2]:+g[k>>2];o=+g[b>>2];i=n;return +o}return 0.0}function zb(a){a=a|0;var b=0,d=0,e=0,f=0,h=0,j=0,k=0.0;j=i;i=i+32|0;b=j+16|0;d=j+12|0;e=j+8|0;f=j+4|0;h=j;c[d>>2]=a;a=c[d>>2]|0;if(+g[c[d>>2]>>2]>+g[(c[d>>2]|0)+4>>2]){g[e>>2]=+g[a+4>>2];g[f>>2]=+g[c[d>>2]>>2]}else{g[e>>2]=+g[a>>2];g[f>>2]=+g[(c[d>>2]|0)+4>>2]}g[h>>2]=+g[(c[d>>2]|0)+8>>2];if(+g[f>>2]<+g[h>>2]){g[b>>2]=+g[f>>2];k=+g[b>>2];i=j;return +k}if(+g[e>>2]<+g[h>>2]){g[b>>2]=+g[h>>2];k=+g[b>>2];i=j;return +k}else{g[b>>2]=+g[e>>2];k=+g[b>>2];i=j;return +k}return 0.0}function Ab(a,d,e,f){a=a|0;d=d|0;e=e|0;f=f|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0.0;v=i;i=i+64|0;h=v+48|0;j=v+44|0;k=v+40|0;l=v+36|0;q=v+32|0;u=v+28|0;s=v+24|0;t=v+20|0;r=v+16|0;m=v+12|0;o=v+8|0;n=v+4|0;p=v;c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2]|0)+(c[H>>2]<<1)>>1]|0)<>2]);if(+g[x>>2]<+N(+(+g[w>>2])))p=+g[x>>2];else p=+N(+(+g[w>>2]));g[x>>2]=p;c[H>>2]=(c[H>>2]|0)+1}if(1.0<+N(+(+g[x>>2])))p=1.0;else p=+N(+(+g[x>>2]));g[x>>2]=p;g[z>>2]=+Y(+(1.0010000467300415-+g[y>>2]*+g[y>>2]))*1.4426950408889634;if(+g[z>>2]*.5>+Y(+(1.0010000467300415-+g[x>>2]*+g[x>>2]))*1.4426950408889634)p=+g[z>>2]*.5;else p=+Y(+(1.0010000467300415-+g[x>>2]*+g[x>>2]))*1.4426950408889634;g[A>>2]=p;g[O>>2]=+g[O>>2]+(-4.0>+g[z>>2]*.75?-4.0:+g[z>>2]*.75);if(+g[c[F>>2]>>2]+.25<-(+g[A>>2]*.5))p=+g[c[F>>2]>>2]+.25;else p=-(+g[A>>2]*.5);g[c[F>>2]>>2]=p}c[G>>2]=0;do{c[H>>2]=0;while(1){if((c[H>>2]|0)>=((c[D>>2]|0)-1|0))break;F=(c[H>>2]|0)+(_(c[G>>2]|0,c[(c[B>>2]|0)+8>>2]|0)|0)|0;g[I>>2]=+g[I>>2]+ +g[(c[C>>2]|0)+(F<<2)>>2]*+(2+(c[H>>2]<<1)-(c[D>>2]|0)|0);c[H>>2]=(c[H>>2]|0)+1}F=(c[G>>2]|0)+1|0;c[G>>2]=F}while((F|0)<(c[E>>2]|0));n=+(_(c[E>>2]|0,(c[D>>2]|0)-1|0)|0);g[I>>2]=+g[I>>2]/n;if(2.0<(+g[I>>2]+1.0)/6.0)p=2.0;else p=(+g[I>>2]+1.0)/6.0;if(!(-2.0>p))if(2.0<(+g[I>>2]+1.0)/6.0)p=2.0;else p=(+g[I>>2]+1.0)/6.0;else p=-2.0;g[O>>2]=+g[O>>2]-p;g[O>>2]=+g[O>>2]-+g[J>>2];g[O>>2]=+g[O>>2]-+g[K>>2]*2.0;if(c[c[L>>2]>>2]|0){if(2.0<(+g[(c[L>>2]|0)+8>>2]+.05000000074505806)*2.0)p=2.0;else p=(+g[(c[L>>2]|0)+8>>2]+.05000000074505806)*2.0;if(!(-2.0>p))if(2.0<(+g[(c[L>>2]|0)+8>>2]+.05000000074505806)*2.0)p=2.0;else p=(+g[(c[L>>2]|0)+8>>2]+.05000000074505806)*2.0;else p=-2.0;g[O>>2]=+g[O>>2]-p}c[P>>2]=~~+M(+(+g[O>>2]+.5));if(0>((10<(c[P>>2]|0)?10:c[P>>2]|0)|0)){O=0;c[P>>2]=O;P=c[P>>2]|0;i=Q;return P|0}O=10<(c[P>>2]|0)?10:c[P>>2]|0;c[P>>2]=O;P=c[P>>2]|0;i=Q;return P|0}function Cb(a,b,d){a=a|0;b=b|0;d=d|0;var e=0.0,f=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;f=m+16|0;h=m+12|0;j=m+8|0;k=m+4|0;l=m;c[f>>2]=a;c[h>>2]=b;c[j>>2]=d;g[l>>2]=0.0;c[k>>2]=0;while(1){e=+g[l>>2];if((c[k>>2]|0)>=(c[j>>2]|0))break;g[l>>2]=e+ +g[(c[f>>2]|0)+(c[k>>2]<<2)>>2]*+g[(c[h>>2]|0)+(c[k>>2]<<2)>>2];c[k>>2]=(c[k>>2]|0)+1}i=m;return +e}function Db(a,d,e,f,h,j,k,l,m,n,o,p,q,r,s,t,u,v,w){a=a|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;n=+n;o=o|0;p=+p;q=q|0;r=+r;s=s|0;t=t|0;u=u|0;v=+v;w=+w;var x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0;ea=i;i=i+144|0;ga=ea+140|0;D=ea+136|0;aa=ea+132|0;P=ea+128|0;X=ea+124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>>2]=+g[y>>2]<1.0?+g[y>>2]:1.0;if(+g[C>>2]*+(c[ca>>2]|0)<(+g[y>>2]-.10000000149011612)*+(c[B>>2]<<3|0))r=+g[C>>2]*+(c[ca>>2]|0);else r=(+g[y>>2]-.10000000149011612)*+(c[B>>2]<<3|0);c[ca>>2]=(c[ca>>2]|0)-~~r}c[ca>>2]=(c[ca>>2]|0)+((c[E>>2]|0)-(16<>2]));g[G>>2]=(c[F>>2]|0)==5010?.019999999552965164:.03999999910593033;c[ca>>2]=(c[ca>>2]|0)+~~((+g[V>>2]-+g[G>>2])*+(c[ca>>2]|0));if(!(c[O>>2]|0?1:(c[c[D>>2]>>2]|0)==0)){if(0.0>+g[(c[D>>2]|0)+4>>2]-.15000000596046448)r=0.0;else r=+g[(c[D>>2]|0)+4>>2]-.15000000596046448;g[L>>2]=r-.09000000357627869;c[M>>2]=(c[ca>>2]|0)+~~(+(c[J>>2]<<3|0)*1.2000000476837158*+g[L>>2]);if(c[H>>2]|0)c[M>>2]=(c[M>>2]|0)+~~(+(c[J>>2]<<3|0)*.800000011920929);c[ca>>2]=c[M>>2]}if(!((c[W>>2]|0)==0|(c[O>>2]|0)!=0)){c[K>>2]=(c[ca>>2]|0)+~~(+g[I>>2]*+(c[J>>2]<<3|0));if(((c[ca>>2]|0)/4|0|0)>(c[K>>2]|0))x=(c[ca>>2]|0)/4|0;else x=c[K>>2]|0;c[ca>>2]=x}c[R>>2]=b[(c[S>>2]|0)+((c[U>>2]|0)-2<<1)>>1]<>2];p=+((_(c[Q>>2]|0,c[R>>2]|0)|0)<<3|0);c[T>>2]=~~(p*+g[N>>2]);c[T>>2]=(c[T>>2]|0)>(c[ca>>2]>>2|0)?c[T>>2]|0:c[ca>>2]>>2;c[ca>>2]=(c[ca>>2]|0)<(c[T>>2]|0)?c[ca>>2]|0:c[T>>2]|0;if((c[W>>2]|0)==0|(c[O>>2]|0)!=0?(c[Y>>2]|0)!=0|(c[X>>2]|0)<64e3:0){if(0.0>+((c[X>>2]|0)-32e3|0)*.000030517578125)r=0.0;else r=+((c[X>>2]|0)-32e3|0)*.000030517578125;g[Z>>2]=r;if(c[Y>>2]|0)g[Z>>2]=+g[Z>>2]<.6700000166893005?+g[Z>>2]:.6700000166893005;c[ca>>2]=(c[aa>>2]|0)+~~(+g[Z>>2]*+((c[ca>>2]|0)-(c[aa>>2]|0)|0))}if(!((c[W>>2]|0)==0&+g[V>>2]<.20000000298023224)){fa=c[aa>>2]|0;fa=fa<<1;da=c[ca>>2]|0;da=(fa|0)<(da|0);fa=c[aa>>2]|0;fa=fa<<1;ga=c[ca>>2]|0;ga=da?fa:ga;c[ca>>2]=ga;ga=c[ca>>2]|0;i=ea;return ga|0}if(0>((32e3<(96e3-(c[X>>2]|0)|0)?32e3:96e3-(c[X>>2]|0)|0)|0))x=0;else x=32e3<(96e3-(c[X>>2]|0)|0)?32e3:96e3-(c[X>>2]|0)|0;g[ba>>2]=+(x|0)*3.099999958067201e-06;g[da>>2]=+g[$>>2]*+g[ba>>2];c[ca>>2]=(c[ca>>2]|0)+~~(+g[da>>2]*+(c[ca>>2]|0));fa=c[aa>>2]|0;fa=fa<<1;da=c[ca>>2]|0;da=(fa|0)<(da|0);fa=c[aa>>2]|0;fa=fa<<1;ga=c[ca>>2]|0;ga=da?fa:ga;c[ca>>2]=ga;ga=c[ca>>2]|0;i=ea;return ga|0}function Eb(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;i=d;return c[(c[b>>2]|0)+44>>2]|0}function Fb(a){a=a|0;var b=0,d=0,e=0;b=i;i=i+16|0;d=b+4|0;e=b;c[d>>2]=a;c[e>>2]=Jc(48e3,960,0)|0;a=Gb(c[e>>2]|0,c[d>>2]|0)|0;i=b;return a|0}function Gb(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0;e=i;i=i+16|0;f=e+8|0;g=e+4|0;d=e;c[f>>2]=a;c[g>>2]=b;a=88+((_(c[g>>2]|0,2048+(c[(c[f>>2]|0)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+48>>2]=0;Kb(c[f>>2]|0,4028,j)|0;c[e>>2]=0;a=c[e>>2]|0;i=j;return a|0}return 0}function Jb(){return 0}function Kb(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0;x=i;i=i+96|0;w=x+80|0;e=x+76|0;y=x+72|0;f=x+56|0;n=x+52|0;o=x+48|0;p=x+44|0;q=x+40|0;r=x+36|0;h=x+32|0;j=x+28|0;k=x+24|0;l=x+20|0;m=x+16|0;s=x+12|0;t=x+8|0;u=x+4|0;v=x;c[e>>2]=a;c[y>>2]=b;c[f>>2]=d;a:do switch(c[y>>2]|0){case 10010:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[n>>2]=y;if((c[n>>2]|0)>=0?(c[n>>2]|0)<(c[(c[c[e>>2]>>2]|0)+8>>2]|0):0){c[(c[e>>2]|0)+20>>2]=c[n>>2];e=24}else e=25;break}case 10012:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[o>>2]=y;if((c[o>>2]|0)>=1?(c[o>>2]|0)<=(c[(c[c[e>>2]>>2]|0)+8>>2]|0):0){c[(c[e>>2]|0)+24>>2]=c[o>>2];e=24}else e=25;break}case 10008:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[p>>2]=y;if((c[p>>2]|0)<1|(c[p>>2]|0)>2)e=25;else{c[(c[e>>2]|0)+12>>2]=c[p>>2];e=24}break}case 10007:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[q>>2]=y;if(!(c[q>>2]|0))e=25;else{c[c[q>>2]>>2]=c[(c[e>>2]|0)+40>>2];c[(c[e>>2]|0)+40>>2]=0;e=24}break}case 4027:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[r>>2]=y;if(!(c[r>>2]|0))e=25;else{c[c[r>>2]>>2]=(c[(c[e>>2]|0)+4>>2]|0)/(c[(c[e>>2]|0)+16>>2]|0)|0;e=24}break}case 4028:{c[j>>2]=(c[e>>2]|0)+84+((_(2048+(c[(c[e>>2]|0)+4>>2]|0)|0,c[(c[e>>2]|0)+8>>2]|0)|0)<<2);c[k>>2]=(c[j>>2]|0)+((c[(c[e>>2]|0)+8>>2]|0)*24<<2);c[l>>2]=(c[k>>2]|0)+(c[(c[c[e>>2]>>2]|0)+8>>2]<<1<<2);c[m>>2]=(c[l>>2]|0)+(c[(c[c[e>>2]>>2]|0)+8>>2]<<1<<2);oj((c[e>>2]|0)+36|0,0,(Gb(c[c[e>>2]>>2]|0,c[(c[e>>2]|0)+8>>2]|0)|0)-((c[e>>2]|0)+36-(c[e>>2]|0))|0)|0;c[h>>2]=0;while(1){if((c[h>>2]|0)>=(c[(c[c[e>>2]>>2]|0)+8>>2]<<1|0)){e=24;break a}g[(c[m>>2]|0)+(c[h>>2]<<2)>>2]=-28.0;g[(c[l>>2]|0)+(c[h>>2]<<2)>>2]=-28.0;c[h>>2]=(c[h>>2]|0)+1}}case 4033:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[s>>2]=y;if(!(c[s>>2]|0))e=25;else{c[c[s>>2]>>2]=c[(c[e>>2]|0)+52>>2];e=24}break}case 10015:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[t>>2]=y;if(!(c[t>>2]|0))e=25;else{c[c[t>>2]>>2]=c[c[e>>2]>>2];e=24}break}case 10016:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[u>>2]=y;c[(c[e>>2]|0)+28>>2]=c[u>>2];e=24;break}case 4031:{d=(c[f>>2]|0)+(4-1)&~(4-1);y=c[d>>2]|0;c[f>>2]=d+4;c[v>>2]=y;if(!(c[v>>2]|0))e=25;else{c[c[v>>2]>>2]=c[(c[e>>2]|0)+36>>2];e=24}break}default:{c[w>>2]=-5;y=c[w>>2]|0;i=x;return y|0}}while(0);if((e|0)==24){c[w>>2]=0;y=c[w>>2]|0;i=x;return y|0}else if((e|0)==25){c[w>>2]=-1;y=c[w>>2]|0;i=x;return y|0}return 0} + function ye(d,e,f,g,h,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;n=n|0;o=o|0;p=p|0;q=q|0;r=r|0;s=s|0;t=t|0;u=u|0;v=v|0;w=w|0;x=x|0;y=y|0;z=z|0;A=A|0;B=B|0;C=C|0;D=D|0;var E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ja=0,ka=0,la=0,ma=0,oa=0,pa=0,qa=0,ra=0,sa=0,ta=0,ua=0,va=0,wa=0,xa=0,ya=0,za=0,Aa=0,Ba=0,Ca=0,Da=0,Ea=0,Fa=0,Ga=0,Ha=0,Ia=0,Ja=0,Ka=0,La=0,Ma=0,Na=0,Oa=0;Na=i;i=i+256|0;E=Na+240|0;Ha=Na+236|0;N=Na+232|0;T=Na+228|0;U=Na+224|0;V=Na+220|0;W=Na+216|0;X=Na+212|0;Y=Na+208|0;Z=Na+204|0;F=Na+200|0;G=Na+196|0;H=Na+192|0;I=Na+188|0;J=Na+184|0;Oa=Na+180|0;K=Na+176|0;L=Na+172|0;Ia=Na+168|0;M=Na+164|0;O=Na+160|0;P=Na+156|0;Q=Na+152|0;Ja=Na+148|0;R=Na+144|0;S=Na+140|0;la=Na+136|0;ma=Na+132|0;La=Na+128|0;ha=Na+124|0;ga=Na+120|0;ea=Na+116|0;oa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(c[Ma>>2]|0)+1152>>2]>>16,(c[I>>2]&65535)<<16>>16)|0;c[pa>>2]=(c[pa>>2]|0)+(Oa+((_(c[(c[Ma>>2]|0)+1152>>2]&65535,(c[I>>2]&65535)<<16>>16)|0)>>16));c[pa>>2]=c[pa>>2]<<2;Oa=_(c[(c[Ma>>2]|0)+960+(c[c[R>>2]>>2]<<2)>>2]>>16,(c[J>>2]&65535)<<16>>16)|0;c[qa>>2]=Oa+((_(c[(c[Ma>>2]|0)+960+(c[c[R>>2]>>2]<<2)>>2]&65535,(c[J>>2]&65535)<<16>>16)|0)>>16);Oa=(c[qa>>2]|0)+(_(c[(c[Ma>>2]|0)+1152>>2]>>16,c[J>>2]>>16)|0)|0;c[qa>>2]=Oa+((_(c[(c[Ma>>2]|0)+1152>>2]&65535,c[J>>2]>>16)|0)>>16);c[qa>>2]=c[qa>>2]<<2;c[Ea>>2]=(c[pa>>2]|0)+(c[qa>>2]|0);c[Fa>>2]=(c[ra>>2]|0)+(c[ba>>2]|0);c[Ea>>2]=(c[Fa>>2]|0)-(c[Ea>>2]|0);c[Ea>>2]=(c[Ea>>2]>>3)+1>>1;c[ya>>2]=(c[(c[T>>2]|0)+(c[la>>2]<<2)>>2]|0)-(c[Ea>>2]|0);if((c[(c[Ma>>2]|0)+1156>>2]|0)<0)c[ya>>2]=0-(c[ya>>2]|0);if((c[ya>>2]|0)>30720)o=30720;else o=(c[ya>>2]|0)<-31744?-31744:c[ya>>2]|0;c[ya>>2]=o;c[wa>>2]=(c[ya>>2]|0)-(c[L>>2]|0);c[va>>2]=c[wa>>2]>>10;o=c[va>>2]|0;do if((c[va>>2]|0)<=0){if(!o){c[wa>>2]=c[L>>2];c[xa>>2]=(c[wa>>2]|0)+944;c[za>>2]=_((c[wa>>2]&65535)<<16>>16,(c[K>>2]&65535)<<16>>16)|0;c[Aa>>2]=_((c[xa>>2]&65535)<<16>>16,(c[K>>2]&65535)<<16>>16)|0;break}if((c[va>>2]|0)==-1){c[xa>>2]=c[L>>2];c[wa>>2]=(c[xa>>2]|0)-944;c[za>>2]=_((0-(c[wa>>2]|0)&65535)<<16>>16,(c[K>>2]&65535)<<16>>16)|0;c[Aa>>2]=_((c[xa>>2]&65535)<<16>>16,(c[K>>2]&65535)<<16>>16)|0;break}else{c[wa>>2]=(c[va>>2]<<10)+80;c[wa>>2]=(c[wa>>2]|0)+(c[L>>2]|0);c[xa>>2]=(c[wa>>2]|0)+1024;c[za>>2]=_((0-(c[wa>>2]|0)&65535)<<16>>16,(c[K>>2]&65535)<<16>>16)|0;c[Aa>>2]=_((0-(c[xa>>2]|0)&65535)<<16>>16,(c[K>>2]&65535)<<16>>16)|0;break}}else{c[wa>>2]=(o<<10)-80;c[wa>>2]=(c[wa>>2]|0)+(c[L>>2]|0);c[xa>>2]=(c[wa>>2]|0)+1024;c[za>>2]=_((c[wa>>2]&65535)<<16>>16,(c[K>>2]&65535)<<16>>16)|0;c[Aa>>2]=_((c[xa>>2]&65535)<<16>>16,(c[K>>2]&65535)<<16>>16)|0}while(0);c[Ba>>2]=(c[ya>>2]|0)-(c[wa>>2]|0);c[za>>2]=(c[za>>2]|0)+(_((c[Ba>>2]&65535)<<16>>16,(c[Ba>>2]&65535)<<16>>16)|0)>>10;c[Ba>>2]=(c[ya>>2]|0)-(c[xa>>2]|0);c[Aa>>2]=(c[Aa>>2]|0)+(_((c[Ba>>2]&65535)<<16>>16,(c[Ba>>2]&65535)<<16>>16)|0)>>10;o=c[(c[Ma>>2]|0)+1164>>2]|0;if((c[za>>2]|0)<(c[Aa>>2]|0)){c[(c[ua>>2]|0)+4>>2]=o+(c[za>>2]|0);c[(c[ua>>2]|0)+24+4>>2]=(c[(c[Ma>>2]|0)+1164>>2]|0)+(c[Aa>>2]|0);c[c[ua>>2]>>2]=c[wa>>2];c[(c[ua>>2]|0)+24>>2]=c[xa>>2]}else{c[(c[ua>>2]|0)+4>>2]=o+(c[Aa>>2]|0);c[(c[ua>>2]|0)+24+4>>2]=(c[(c[Ma>>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1}c[ja>>2]=c[(c[Ha>>2]|0)+((c[ha>>2]|0)*1168|0)+448+(c[oa>>2]<<2)>>2];c[La>>2]=0;while(1){if((c[La>>2]|0)>=(c[Ja>>2]|0))break;if((c[(c[Ha>>2]|0)+((c[La>>2]|0)*1168|0)+448+(c[oa>>2]<<2)>>2]|0)!=(c[ja>>2]|0)){c[t+((c[La>>2]|0)*48|0)+4>>2]=(c[t+((c[La>>2]|0)*48|0)+4>>2]|0)+134217727;c[t+((c[La>>2]|0)*48|0)+24+4>>2]=(c[t+((c[La>>2]|0)*48|0)+24+4>>2]|0)+134217727}c[La>>2]=(c[La>>2]|0)+1}c[da>>2]=c[t+4>>2];c[fa>>2]=c[t+24+4>>2];c[ea>>2]=0;c[ga>>2]=0;c[La>>2]=1;while(1){if((c[La>>2]|0)>=(c[Ja>>2]|0))break;if((c[t+((c[La>>2]|0)*48|0)+4>>2]|0)>(c[da>>2]|0)){c[da>>2]=c[t+((c[La>>2]|0)*48|0)+4>>2];c[ea>>2]=c[La>>2]}if((c[t+((c[La>>2]|0)*48|0)+24+4>>2]|0)<(c[fa>>2]|0)){c[fa>>2]=c[t+((c[La>>2]|0)*48|0)+24+4>>2];c[ga>>2]=c[La>>2]}c[La>>2]=(c[La>>2]|0)+1}if((c[fa>>2]|0)<(c[da>>2]|0)){pj((c[Ha>>2]|0)+((c[ea>>2]|0)*1168|0)+(c[la>>2]<<2)|0,(c[Ha>>2]|0)+((c[ga>>2]|0)*1168|0)+(c[la>>2]<<2)|0,1168-(c[la>>2]<<2)|0)|0;Oa=t+((c[ea>>2]|0)*48|0)|0;j=t+((c[ga>>2]|0)*48|0)+24|0;c[Oa>>2]=c[j>>2];c[Oa+4>>2]=c[j+4>>2];c[Oa+8>>2]=c[j+8>>2];c[Oa+12>>2]=c[j+12>>2];c[Oa+16>>2]=c[j+16>>2];c[Oa+20>>2]=c[j+20>>2]}c[Ma>>2]=(c[Ha>>2]|0)+((c[ha>>2]|0)*1168|0);if(!((c[M>>2]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]>>2]<<2)>>2]=c[$>>2];c[la>>2]=(c[la>>2]|0)+1}c[La>>2]=0;while(1){if((c[La>>2]|0)>=(c[Ja>>2]|0))break;c[Ma>>2]=(c[Ha>>2]|0)+((c[La>>2]|0)*1168|0);o=c[Ma>>2]|0;t=(c[Ma>>2]|0)+(c[Ia>>2]<<2)|0;q=o+128|0;do{c[o>>2]=c[t>>2];o=o+4|0;t=t+4|0}while((o|0)<(q|0));c[La>>2]=(c[La>>2]|0)+1}na(c[Ka>>2]|0);i=Na;return}function ze(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;c[(c[d>>2]|0)+4168>>2]=c[(c[d>>2]|0)+2328>>2]<<7;c[(c[d>>2]|0)+4168+72>>2]=65536;c[(c[d>>2]|0)+4168+72+4>>2]=65536;c[(c[d>>2]|0)+4168+88>>2]=20;c[(c[d>>2]|0)+4168+84>>2]=2;i=b;return}function Ae(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;h=m+16|0;g=m+12|0;j=m+8|0;k=m+4|0;l=m;c[h>>2]=a;c[g>>2]=b;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;if((c[(c[h>>2]|0)+2316>>2]|0)!=(c[(c[h>>2]|0)+4168+80>>2]|0)){ze(c[h>>2]|0);c[(c[h>>2]|0)+4168+80>>2]=c[(c[h>>2]|0)+2316>>2]}d=c[h>>2]|0;f=c[g>>2]|0;if(c[k>>2]|0){Be(d,f,c[j>>2]|0,c[l>>2]|0);l=(c[h>>2]|0)+4160|0;c[l>>2]=(c[l>>2]|0)+1;i=m;return}else{Ke(d,f);i=m;return}}function Be(a,d,e,f){a=a|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I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|0)|0)<<1)>>1];l=(c[(c[z>>2]|0)+4164>>2]|0)==2;f=Ee(1,c[(c[z>>2]|0)+4160>>2]|0)|0;if(l)c[w>>2]=b[24444+(f<<1)>>1];else c[w>>2]=b[24448+(f<<1)>>1];Pf((c[J>>2]|0)+14|0,c[(c[z>>2]|0)+2340>>2]|0,64881);pj(D|0,(c[J>>2]|0)+14|0,c[(c[z>>2]|0)+2340>>2]<<1|0)|0;do if(!(c[(c[z>>2]|0)+4160>>2]|0)){b[K>>1]=16384;if((c[(c[z>>2]|0)+4164>>2]|0)!=2){c[s>>2]=Yf((c[J>>2]|0)+14|0,c[(c[z>>2]|0)+2340>>2]|0)|0;c[p>>2]=Ge(134217728,c[s>>2]|0)|0;c[p>>2]=He(4194304,c[p>>2]|0)|0;c[p>>2]=c[p>>2]<<3;s=_(c[p>>2]>>16,(c[w>>2]&65535)<<16>>16)|0;c[w>>2]=s+((_(c[p>>2]&65535,(c[w>>2]&65535)<<16>>16)|0)>>16)>>14;break}c[F>>2]=0;while(1){if((c[F>>2]|0)>=5)break;b[K>>1]=(b[K>>1]|0)-(b[(c[n>>2]|0)+(c[F>>2]<<1)>>1]|0);c[F>>2]=(c[F>>2]|0)+1}b[K>>1]=Fe(3277,b[K>>1]|0)|0;b[K>>1]=(_(b[K>>1]|0,b[(c[J>>2]|0)+68>>1]|0)|0)>>14}while(0);c[L>>2]=c[(c[J>>2]|0)+52>>2];c[H>>2]=(c[c[J>>2]>>2]>>7)+1>>1;c[y>>2]=c[(c[z>>2]|0)+2336>>2];c[r>>2]=(c[(c[z>>2]|0)+2336>>2]|0)-(c[H>>2]|0)-(c[(c[z>>2]|0)+2340>>2]|0)-2;Xf(g+(c[r>>2]<<1)|0,(c[z>>2]|0)+1348+(c[r>>2]<<1)|0,D,(c[(c[z>>2]|0)+2336>>2]|0)-(c[r>>2]|0)|0,c[(c[z>>2]|0)+2340>>2]|0,c[m>>2]|0);c[t>>2]=Ie(c[(c[J>>2]|0)+72+4>>2]|0,46)|0;c[t>>2]=(c[t>>2]|0)<1073741823?c[t>>2]|0:1073741823;c[F>>2]=(c[r>>2]|0)+(c[(c[z>>2]|0)+2340>>2]|0);while(1){if((c[F>>2]|0)>=(c[(c[z>>2]|0)+2336>>2]|0))break;s=_(c[t>>2]>>16,b[g+(c[F>>2]<<1)>>1]|0)|0;s=s+((_(c[t>>2]&65535,b[g+(c[F>>2]<<1)>>1]|0)|0)>>16)|0;c[d+(c[F>>2]<<2)>>2]=s;c[F>>2]=(c[F>>2]|0)+1}c[u>>2]=0;while(1){if((c[u>>2]|0)>=(c[(c[z>>2]|0)+2324>>2]|0))break;c[v>>2]=d+((c[y>>2]|0)-(c[H>>2]|0)+2<<2);c[F>>2]=0;while(1){if((c[F>>2]|0)>=(c[(c[z>>2]|0)+2332>>2]|0))break;c[o>>2]=2;t=_(c[c[v>>2]>>2]>>16,b[c[n>>2]>>1]|0)|0;c[o>>2]=(c[o>>2]|0)+(t+((_(c[c[v>>2]>>2]&65535,b[c[n>>2]>>1]|0)|0)>>16));t=_(c[(c[v>>2]|0)+-4>>2]>>16,b[(c[n>>2]|0)+2>>1]|0)|0;c[o>>2]=(c[o>>2]|0)+(t+((_(c[(c[v>>2]|0)+-4>>2]&65535,b[(c[n>>2]|0)+2>>1]|0)|0)>>16));t=_(c[(c[v>>2]|0)+-8>>2]>>16,b[(c[n>>2]|0)+4>>1]|0)|0;c[o>>2]=(c[o>>2]|0)+(t+((_(c[(c[v>>2]|0)+-8>>2]&65535,b[(c[n>>2]|0)+4>>1]|0)|0)>>16));t=_(c[(c[v>>2]|0)+-12>>2]>>16,b[(c[n>>2]|0)+6>>1]|0)|0;c[o>>2]=(c[o>>2]|0)+(t+((_(c[(c[v>>2]|0)+-12>>2]&65535,b[(c[n>>2]|0)+6>>1]|0)|0)>>16));t=_(c[(c[v>>2]|0)+-16>>2]>>16,b[(c[n>>2]|0)+8>>1]|0)|0;c[o>>2]=(c[o>>2]|0)+(t+((_(c[(c[v>>2]|0)+-16>>2]&65535,b[(c[n>>2]|0)+8>>1]|0)|0)>>16));c[v>>2]=(c[v>>2]|0)+4;c[L>>2]=907633515+(_(c[L>>2]|0,196314165)|0);c[r>>2]=c[L>>2]>>25&127;t=_(c[(c[x>>2]|0)+(c[r>>2]<<2)>>2]>>16,b[K>>1]|0)|0;t=(c[o>>2]|0)+(t+((_(c[(c[x>>2]|0)+(c[r>>2]<<2)>>2]&65535,b[K>>1]|0)|0)>>16))<<2;c[d+(c[y>>2]<<2)>>2]=t;c[y>>2]=(c[y>>2]|0)+1;c[F>>2]=(c[F>>2]|0)+1}c[G>>2]=0;while(1){if((c[G>>2]|0)>=5)break;t=(_((c[q>>2]&65535)<<16>>16,b[(c[n>>2]|0)+(c[G>>2]<<1)>>1]|0)|0)>>15&65535;b[(c[n>>2]|0)+(c[G>>2]<<1)>>1]=t;c[G>>2]=(c[G>>2]|0)+1}b[K>>1]=(_(b[K>>1]|0,(c[w>>2]&65535)<<16>>16)|0)>>15;c[c[J>>2]>>2]=(c[c[J>>2]>>2]|0)+(((c[c[J>>2]>>2]>>16)*655|0)+((c[c[J>>2]>>2]&65535)*655>>16));t=Ge(c[c[J>>2]>>2]|0,((c[(c[z>>2]|0)+2316>>2]&65535)<<16>>16)*18<<8)|0;c[c[J>>2]>>2]=t;c[H>>2]=(c[c[J>>2]>>2]>>7)+1>>1;c[u>>2]=(c[u>>2]|0)+1}c[M>>2]=d+((c[(c[z>>2]|0)+2336>>2]|0)-16<<2);e=c[M>>2]|0;f=(c[z>>2]|0)+1284|0;a=e+64|0;do{c[e>>2]=c[f>>2];e=e+4|0;f=f+4|0}while((e|0)<(a|0));c[F>>2]=0;while(1){f=c[z>>2]|0;if((c[F>>2]|0)>=(c[(c[z>>2]|0)+2328>>2]|0))break;c[E>>2]=c[f+2340>>2]>>1;y=_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)-1<<2)>>2]>>16,b[D>>1]|0)|0;c[E>>2]=(c[E>>2]|0)+(y+((_(c[(c[M>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+((_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]&65535,(c[I+4>>2]&65535)<<16>>16)|0)>>16)|0;if(((y+(_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]|0,(c[I+4>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<-32768)f=-32768;else{f=_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]>>16,(c[I+4>>2]&65535)<<16>>16)|0;f=f+((_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]&65535,(c[I+4>>2]&65535)<<16>>16)|0)>>16)|0;f=(f+(_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]|0,(c[I+4>>2]>>15)+1>>1)|0)>>7)+1>>1}}else f=32767;if((f|0)<=32767){y=_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]>>16,(c[I+4>>2]&65535)<<16>>16)|0;y=y+((_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]&65535,(c[I+4>>2]&65535)<<16>>16)|0)>>16)|0;if(((y+(_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]|0,(c[I+4>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<=32767){y=_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]>>16,(c[I+4>>2]&65535)<<16>>16)|0;y=y+((_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]&65535,(c[I+4>>2]&65535)<<16>>16)|0)>>16)|0;if(((y+(_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]|0,(c[I+4>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<-32768)f=-32768;else{f=_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]>>16,(c[I+4>>2]&65535)<<16>>16)|0;f=f+((_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]&65535,(c[I+4>>2]&65535)<<16>>16)|0)>>16)|0;f=(f+(_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]|0,(c[I+4>>2]>>15)+1>>1)|0)>>7)+1>>1}}else f=32767;if((f|0)>=-32768){y=_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]>>16,(c[I+4>>2]&65535)<<16>>16)|0;y=y+((_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]&65535,(c[I+4>>2]&65535)<<16>>16)|0)>>16)|0;if(((y+(_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]|0,(c[I+4>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<=32767){y=_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]>>16,(c[I+4>>2]&65535)<<16>>16)|0;y=y+((_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]&65535,(c[I+4>>2]&65535)<<16>>16)|0)>>16)|0;if(((y+(_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]|0,(c[I+4>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<-32768)f=-32768;else{f=_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]>>16,(c[I+4>>2]&65535)<<16>>16)|0;f=f+((_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]&65535,(c[I+4>>2]&65535)<<16>>16)|0)>>16)|0;f=(f+(_(c[(c[M>>2]|0)+(16+(c[F>>2]|0)<<2)>>2]|0,(c[I+4>>2]>>15)+1>>1)|0)>>7)+1>>1}}else f=32767}else f=-32768}else f=32767;b[(c[B>>2]|0)+(c[F>>2]<<1)>>1]=f;c[F>>2]=(c[F>>2]|0)+1}e=f+1284|0;f=(c[M>>2]|0)+(c[(c[z>>2]|0)+2328>>2]<<2)|0;a=e+64|0;do{c[e>>2]=c[f>>2];e=e+4|0;f=f+4|0}while((e|0)<(a|0));c[(c[J>>2]|0)+52>>2]=c[L>>2];b[(c[J>>2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0,a+(c[r>>2]<<1)|0,c[r>>2]|0);na(c[t>>2]|0);i=x;return}function De(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Ee(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Fe(a,c){a=a|0;c=c|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+2|0;d=f;b[e>>1]=a;b[d>>1]=c;i=f;return ((b[e>>1]|0)>(b[d>>1]|0)?b[e>>1]|0:b[d>>1]|0)&65535|0}function Ge(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function He(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Ie(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0;h=i;i=i+48|0;f=h+32|0;n=h+28|0;d=h+24|0;j=h+20|0;g=h+16|0;k=h+12|0;m=h+8|0;l=h+4|0;e=h;c[n>>2]=a;c[d>>2]=b;b=c[n>>2]|0;c[j>>2]=(Je((c[n>>2]|0)>0?b:0-b|0)|0)-1;c[m>>2]=c[n>>2]<>2];c[k>>2]=536870911/(c[m>>2]>>16|0)|0;c[e>>2]=c[k>>2]<<16;b=_(c[m>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;c[l>>2]=536870912-(b+((_(c[m>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))<<3;b=_(c[l>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;b=(c[e>>2]|0)+(b+((_(c[l>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))|0;c[e>>2]=b+(_(c[l>>2]|0,(c[k>>2]>>15)+1>>1)|0);c[g>>2]=61-(c[j>>2]|0)-(c[d>>2]|0);b=c[g>>2]|0;if((c[g>>2]|0)>0)if((b|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];n=c[f>>2]|0;i=h;return n|0}else{c[f>>2]=0;n=c[f>>2]|0;i=h;return n|0}a=c[e>>2]|0;d=0-(c[g>>2]|0)|0;do if((-2147483648>>0-b|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>d|0)){b=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){b=2147483647>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>d|0)){b=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){b=-2147483648>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}while(0);c[f>>2]=b<<0-(c[g>>2]|0);n=c[f>>2]|0;i=h;return n|0}function Je(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function Ke(d,e){d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;r=i;i=i+48|0;f=r+40|0;g=r+36|0;h=r+32|0;o=r+28|0;j=r+24|0;k=r+20|0;l=r+16|0;m=r+12|0;p=r+8|0;n=r+4|0;q=r;c[f>>2]=d;c[g>>2]=e;c[l>>2]=(c[f>>2]|0)+4168;c[(c[f>>2]|0)+4164>>2]=a[(c[f>>2]|0)+2736+29>>0];c[h>>2]=0;a:do if((a[(c[f>>2]|0)+2736+29>>0]|0)==2){c[k>>2]=0;while(1){e=_(c[k>>2]|0,c[(c[f>>2]|0)+2332>>2]|0)|0;if((e|0)>=(c[(c[g>>2]|0)+((c[(c[f>>2]|0)+2324>>2]|0)-1<<2)>>2]|0))break;if((c[k>>2]|0)==(c[(c[f>>2]|0)+2324>>2]|0))break;c[o>>2]=0;c[j>>2]=0;while(1){if((c[j>>2]|0)>=5)break;c[o>>2]=(c[o>>2]|0)+(b[(c[g>>2]|0)+96+((((c[(c[f>>2]|0)+2324>>2]|0)-1-(c[k>>2]|0)|0)*5|0)+(c[j>>2]|0)<<1)>>1]|0);c[j>>2]=(c[j>>2]|0)+1}if((c[o>>2]|0)>(c[h>>2]|0)){c[h>>2]=c[o>>2];e=(c[l>>2]|0)+4|0;d=(c[g>>2]|0)+96+((((c[(c[f>>2]|0)+2324>>2]|0)-1-(c[k>>2]|0)&65535)<<16>>16)*5<<1)|0;b[e>>1]=b[d>>1]|0;b[e+2>>1]=b[d+2>>1]|0;b[e+4>>1]=b[d+4>>1]|0;b[e+6>>1]=b[d+6>>1]|0;b[e+8>>1]=b[d+8>>1]|0;c[c[l>>2]>>2]=c[(c[g>>2]|0)+((c[(c[f>>2]|0)+2324>>2]|0)-1-(c[k>>2]|0)<<2)>>2]<<8}c[k>>2]=(c[k>>2]|0)+1}o=(c[l>>2]|0)+4|0;c[o>>2]=0;c[o+4>>2]=0;b[o+8>>1]=0;b[(c[l>>2]|0)+4+4>>1]=c[h>>2];if((c[h>>2]|0)<11469){c[p>>2]=11744256;c[m>>2]=(c[p>>2]|0)/(((c[h>>2]|0)>1?c[h>>2]|0:1)|0)|0;c[j>>2]=0;while(1){if((c[j>>2]|0)>=5)break a;q=(_(b[(c[l>>2]|0)+4+(c[j>>2]<<1)>>1]|0,(c[m>>2]&65535)<<16>>16)|0)>>10&65535;b[(c[l>>2]|0)+4+(c[j>>2]<<1)>>1]=q;c[j>>2]=(c[j>>2]|0)+1}}if((c[h>>2]|0)>15565){c[q>>2]=255016960;c[n>>2]=(c[q>>2]|0)/(((c[h>>2]|0)>1?c[h>>2]|0:1)|0)|0;c[j>>2]=0;while(1){if((c[j>>2]|0)>=5)break a;q=(_(b[(c[l>>2]|0)+4+(c[j>>2]<<1)>>1]|0,(c[n>>2]&65535)<<16>>16)|0)>>14&65535;b[(c[l>>2]|0)+4+(c[j>>2]<<1)>>1]=q;c[j>>2]=(c[j>>2]|0)+1}}}else{c[c[l>>2]>>2]=((c[(c[f>>2]|0)+2316>>2]&65535)<<16>>16)*18<<8;q=(c[l>>2]|0)+4|0;c[q>>2]=0;c[q+4>>2]=0;b[q+8>>1]=0}while(0);pj((c[l>>2]|0)+14|0,(c[g>>2]|0)+32+32|0,c[(c[f>>2]|0)+2340>>2]<<1|0)|0;b[(c[l>>2]|0)+68>>1]=c[(c[g>>2]|0)+136>>2];q=(c[l>>2]|0)+72|0;p=(c[g>>2]|0)+16+((c[(c[f>>2]|0)+2324>>2]|0)-2<<2)|0;c[q>>2]=c[p>>2];c[q+4>>2]=c[p+4>>2];c[(c[l>>2]|0)+88>>2]=c[(c[f>>2]|0)+2332>>2];c[(c[l>>2]|0)+84>>2]=c[(c[f>>2]|0)+2324>>2];i=r;return}function Le(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;r=i;i=i+48|0;f=r+40|0;g=r+36|0;h=r+32|0;o=r+28|0;l=r+24|0;k=r+20|0;p=r+16|0;m=r+12|0;j=r+8|0;n=r+4|0;q=r;c[f>>2]=a;c[g>>2]=d;c[h>>2]=e;c[p>>2]=(c[f>>2]|0)+4168;if(c[(c[f>>2]|0)+4160>>2]|0){wg((c[p>>2]|0)+60|0,(c[p>>2]|0)+64|0,c[g>>2]|0,c[h>>2]|0);c[(c[p>>2]|0)+48>>2]=1;i=r;return}a:do if(c[(c[f>>2]|0)+4168+48>>2]|0){wg(k,l,c[g>>2]|0,c[h>>2]|0);if((c[l>>2]|0)<=(c[(c[p>>2]|0)+64>>2]|0)){if((c[l>>2]|0)<(c[(c[p>>2]|0)+64>>2]|0))c[k>>2]=c[k>>2]>>(c[(c[p>>2]|0)+64>>2]|0)-(c[l>>2]|0)}else c[(c[p>>2]|0)+60>>2]=c[(c[p>>2]|0)+60>>2]>>(c[l>>2]|0)-(c[(c[p>>2]|0)+64>>2]|0);if((c[k>>2]|0)>(c[(c[p>>2]|0)+60>>2]|0)){c[j>>2]=Je(c[(c[p>>2]|0)+60>>2]|0)|0;c[j>>2]=(c[j>>2]|0)-1;c[(c[p>>2]|0)+60>>2]=c[(c[p>>2]|0)+60>>2]<>2];a=c[k>>2]|0;c[k>>2]=a>>(He(24-(c[j>>2]|0)|0,0)|0);c[m>>2]=(c[(c[p>>2]|0)+60>>2]|0)/(((c[k>>2]|0)>1?c[k>>2]|0:1)|0)|0;c[n>>2]=(Me(c[m>>2]|0)|0)<<4;c[q>>2]=(65536-(c[n>>2]|0)|0)/(c[h>>2]|0)|0;c[q>>2]=c[q>>2]<<2;c[o>>2]=0;while(1){if((c[o>>2]|0)>=(c[h>>2]|0))break a;a=_(c[n>>2]>>16,b[(c[g>>2]|0)+(c[o>>2]<<1)>>1]|0)|0;a=a+((_(c[n>>2]&65535,b[(c[g>>2]|0)+(c[o>>2]<<1)>>1]|0)|0)>>16)&65535;b[(c[g>>2]|0)+(c[o>>2]<<1)>>1]=a;c[n>>2]=(c[n>>2]|0)+(c[q>>2]|0);if((c[n>>2]|0)>65536)break a;c[o>>2]=(c[o>>2]|0)+1}}}while(0);c[(c[p>>2]|0)+48>>2]=0;i=r;return}function Me(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+32|0;b=h+16|0;d=h+12|0;g=h+8|0;f=h+4|0;e=h;c[d>>2]=a;if((c[d>>2]|0)<=0){c[b>>2]=0;g=c[b>>2]|0;i=h;return g|0}Ne(c[d>>2]|0,f,e);if(c[f>>2]&1|0)c[g>>2]=32768;else c[g>>2]=46214;c[g>>2]=c[g>>2]>>(c[f>>2]>>1);a=_(c[g>>2]>>16,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0;c[g>>2]=(c[g>>2]|0)+(a+((_(c[g>>2]&65535,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0)>>16));c[b>>2]=c[g>>2];g=c[b>>2]|0;i=h;return g|0}function Ne(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;e=i;i=i+16|0;h=e+12|0;j=e+8|0;f=e+4|0;g=e;c[h>>2]=a;c[j>>2]=b;c[f>>2]=d;c[g>>2]=Je(c[h>>2]|0)|0;c[c[j>>2]>>2]=c[g>>2];b=(Oe(c[h>>2]|0,24-(c[g>>2]|0)|0)|0)&127;c[c[f>>2]>>2]=b;i=e;return}function Oe(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+20|0;d=k+16|0;f=k+12|0;j=k+8|0;h=k+4|0;g=k;c[d>>2]=a;c[f>>2]=b;c[j>>2]=c[d>>2];c[h>>2]=c[f>>2];c[g>>2]=0-(c[f>>2]|0);if(!(c[f>>2]|0)){c[e>>2]=c[d>>2];j=c[e>>2]|0;i=k;return j|0}d=c[j>>2]|0;if((c[f>>2]|0)<0){c[e>>2]=d<>2]|(c[j>>2]|0)>>>(32-(c[g>>2]|0)|0);j=c[e>>2]|0;i=k;return j|0}else{c[e>>2]=d<<32-(c[h>>2]|0)|(c[j>>2]|0)>>>(c[h>>2]|0);j=c[e>>2]|0;i=k;return j|0}return 0}function Pe(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0;d=i;i=i+80|0;g=d+68|0;f=d+64|0;e=d+32|0;h=d+16|0;j=d+8|0;k=d;c[g>>2]=a;c[f>>2]=b;Qe(e,c[f>>2]|0,8);Qe(h,e,4);Qe(j,h,2);Qe(k,j,1);Re(c[g>>2]|0,c[j>>2]|0,c[k>>2]|0,30015);Re(c[g>>2]|0,c[h>>2]|0,c[j>>2]|0,29863);Re(c[g>>2]|0,c[e>>2]|0,c[h>>2]|0,29711);Re(c[g>>2]|0,c[c[f>>2]>>2]|0,c[e>>2]|0,29559);Re(c[g>>2]|0,c[(c[f>>2]|0)+8>>2]|0,c[e+4>>2]|0,29559);Re(c[g>>2]|0,c[e+8>>2]|0,c[h+4>>2]|0,29711);Re(c[g>>2]|0,c[(c[f>>2]|0)+16>>2]|0,c[e+8>>2]|0,29559);Re(c[g>>2]|0,c[(c[f>>2]|0)+24>>2]|0,c[e+12>>2]|0,29559);Re(c[g>>2]|0,c[h+8>>2]|0,c[j+4>>2]|0,29863);Re(c[g>>2]|0,c[e+16>>2]|0,c[h+8>>2]|0,29711);Re(c[g>>2]|0,c[(c[f>>2]|0)+32>>2]|0,c[e+16>>2]|0,29559);Re(c[g>>2]|0,c[(c[f>>2]|0)+40>>2]|0,c[e+20>>2]|0,29559);Re(c[g>>2]|0,c[e+24>>2]|0,c[h+12>>2]|0,29711);Re(c[g>>2]|0,c[(c[f>>2]|0)+48>>2]|0,c[e+24>>2]|0,29559);Re(c[g>>2]|0,c[(c[f>>2]|0)+56>>2]|0,c[e+28>>2]|0,29559);i=d;return}function Qe(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;j=i;i=i+16|0;e=j+12|0;f=j+8|0;g=j+4|0;h=j;c[e>>2]=a;c[f>>2]=b;c[g>>2]=d;c[h>>2]=0;while(1){if((c[h>>2]|0)>=(c[g>>2]|0))break;c[(c[e>>2]|0)+(c[h>>2]<<2)>>2]=(c[(c[f>>2]|0)+(c[h>>2]<<1<<2)>>2]|0)+(c[(c[f>>2]|0)+((c[h>>2]<<1)+1<<2)>>2]|0);c[h>>2]=(c[h>>2]|0)+1}i=j;return}function Re(a,b,e,f){a=a|0;b=b|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0;l=i;i=i+16|0;g=l+12|0;h=l+8|0;j=l+4|0;k=l;c[g>>2]=a;c[h>>2]=b;c[j>>2]=e;c[k>>2]=f;if((c[j>>2]|0)<=0){i=l;return}qc(c[g>>2]|0,c[h>>2]|0,(c[k>>2]|0)+(d[30167+(c[j>>2]|0)>>0]|0)|0,8);i=l;return}function Se(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0;f=i;i=i+48|0;j=f+8|0;h=f+4|0;m=f;l=f+40|0;k=f+32|0;g=f+16|0;c[j>>2]=a;c[h>>2]=d;c[m>>2]=e;Te(l,l+2|0,c[h>>2]|0,c[m>>2]|0,30015);Te(k,k+2|0,c[h>>2]|0,b[l>>1]|0,29863);Te(g,g+2|0,c[h>>2]|0,b[k>>1]|0,29711);Te(c[j>>2]|0,(c[j>>2]|0)+2|0,c[h>>2]|0,b[g>>1]|0,29559);Te((c[j>>2]|0)+4|0,(c[j>>2]|0)+6|0,c[h>>2]|0,b[g+2>>1]|0,29559);Te(g+4|0,g+6|0,c[h>>2]|0,b[k+2>>1]|0,29711);Te((c[j>>2]|0)+8|0,(c[j>>2]|0)+10|0,c[h>>2]|0,b[g+4>>1]|0,29559);Te((c[j>>2]|0)+12|0,(c[j>>2]|0)+14|0,c[h>>2]|0,b[g+6>>1]|0,29559);Te(k+4|0,k+6|0,c[h>>2]|0,b[l+2>>1]|0,29863);Te(g+8|0,g+10|0,c[h>>2]|0,b[k+4>>1]|0,29711);Te((c[j>>2]|0)+16|0,(c[j>>2]|0)+18|0,c[h>>2]|0,b[g+8>>1]|0,29559);Te((c[j>>2]|0)+20|0,(c[j>>2]|0)+22|0,c[h>>2]|0,b[g+10>>1]|0,29559);Te(g+12|0,g+14|0,c[h>>2]|0,b[k+6>>1]|0,29711);Te((c[j>>2]|0)+24|0,(c[j>>2]|0)+26|0,c[h>>2]|0,b[g+12>>1]|0,29559);Te((c[j>>2]|0)+28|0,(c[j>>2]|0)+30|0,c[h>>2]|0,b[g+14>>1]|0,29559);i=f;return}function Te(a,e,f,g,h){a=a|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0;o=i;i=i+32|0;j=o+16|0;k=o+12|0;l=o+8|0;m=o+4|0;n=o;c[j>>2]=a;c[k>>2]=e;c[l>>2]=f;c[m>>2]=g;c[n>>2]=h;if((c[m>>2]|0)>0){h=(ec(c[l>>2]|0,(c[n>>2]|0)+(d[30167+(c[m>>2]|0)>>0]|0)|0,8)|0)&65535;b[c[j>>2]>>1]=h;b[c[k>>2]>>1]=(c[m>>2]|0)-(b[c[j>>2]>>1]|0);i=o;return}else{b[c[j>>2]>>1]=0;b[c[k>>2]>>1]=0;i=o;return}}function Ue(a){a=a|0;var b=0,d=0,e=0,f=0,g=0;g=i;i=i+16|0;d=g+8|0;e=g+4|0;f=g;c[d>>2]=a;c[f>>2]=0;a=c[d>>2]|0;b=a+112|0;do{c[a>>2]=0;a=a+4|0}while((a|0)<(b|0));c[e>>2]=0;while(1){if((c[e>>2]|0)>=4)break;b=Ve(50/((c[e>>2]|0)+1|0)|0,1)|0;c[(c[d>>2]|0)+92+(c[e>>2]<<2)>>2]=b;c[e>>2]=(c[e>>2]|0)+1}c[e>>2]=0;while(1){if((c[e>>2]|0)>=4)break;c[(c[d>>2]|0)+60+(c[e>>2]<<2)>>2]=(c[(c[d>>2]|0)+92+(c[e>>2]<<2)>>2]|0)*100;c[(c[d>>2]|0)+76+(c[e>>2]<<2)>>2]=2147483647/(c[(c[d>>2]|0)+60+(c[e>>2]<<2)>>2]|0)|0;c[e>>2]=(c[e>>2]|0)+1}c[(c[d>>2]|0)+108>>2]=15;c[e>>2]=0;while(1){if((c[e>>2]|0)>=4)break;c[(c[d>>2]|0)+40+(c[e>>2]<<2)>>2]=25600;c[e>>2]=(c[e>>2]|0)+1}i=g;return c[f>>2]|0}function Ve(a,b){a=a|0;b=b|0;var d=0,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|0)-1<<1)>>1]|0;c[l>>2]=(c[k>>2]|0)-1;while(1){if((c[l>>2]|0)<=0)break;b[f+((c[l>>2]|0)-1<<1)>>1]=b[f+((c[l>>2]|0)-1<<1)>>1]>>1;F=f+(c[l>>2]<<1)|0;b[F>>1]=(b[F>>1]|0)-(b[f+((c[l>>2]|0)-1<<1)>>1]|0);c[l>>2]=(c[l>>2]|0)+-1}b[f>>1]=(b[f>>1]|0)-(b[(c[y>>2]|0)+56>>1]|0);b[(c[y>>2]|0)+56>>1]=b[e>>1]|0;c[x>>2]=0;while(1){if((c[x>>2]|0)>=4)break;F=c[(c[s>>2]|0)+4608>>2]|0;c[k>>2]=F>>(Xe(4-(c[x>>2]|0)|0,3)|0);c[h>>2]=c[k>>2]>>2;c[j>>2]=0;c[o+(c[x>>2]<<2)>>2]=c[(c[y>>2]|0)+24+(c[x>>2]<<2)>>2];c[m>>2]=0;while(1){if((c[m>>2]|0)>=4)break;c[r>>2]=0;c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[h>>2]|0))break;c[n>>2]=b[f+((c[g+(c[x>>2]<<2)>>2]|0)+(c[l>>2]|0)+(c[j>>2]|0)<<1)>>1]>>3;c[r>>2]=(c[r>>2]|0)+(_((c[n>>2]&65535)<<16>>16,(c[n>>2]&65535)<<16>>16)|0);c[l>>2]=(c[l>>2]|0)+1}d=c[o+(c[x>>2]<<2)>>2]|0;a=c[r>>2]|0;if((c[m>>2]|0)<3){if(d+a&-2147483648|0)d=2147483647;else d=(c[o+(c[x>>2]<<2)>>2]|0)+(c[r>>2]|0)|0;c[o+(c[x>>2]<<2)>>2]=d}else{if(d+(a>>1)&-2147483648|0)d=2147483647;else d=(c[o+(c[x>>2]<<2)>>2]|0)+(c[r>>2]>>1)|0;c[o+(c[x>>2]<<2)>>2]=d}c[j>>2]=(c[j>>2]|0)+(c[h>>2]|0);c[m>>2]=(c[m>>2]|0)+1}c[(c[y>>2]|0)+24+(c[x>>2]<<2)>>2]=c[r>>2];c[x>>2]=(c[x>>2]|0)+1}Ye(o,c[y>>2]|0);c[r>>2]=0;c[p>>2]=0;c[x>>2]=0;while(1){if((c[x>>2]|0)>=4)break;c[B>>2]=(c[o+(c[x>>2]<<2)>>2]|0)-(c[(c[y>>2]|0)+60+(c[x>>2]<<2)>>2]|0);d=c[x>>2]|0;if((c[B>>2]|0)>0){a=c[o+(c[x>>2]<<2)>>2]|0;if(!(c[o+(d<<2)>>2]&-8388608))c[u+(c[x>>2]<<2)>>2]=(a<<8|0)/((c[(c[y>>2]|0)+60+(c[x>>2]<<2)>>2]|0)+1|0)|0;else c[u+(c[x>>2]<<2)>>2]=(a|0)/((c[(c[y>>2]|0)+60+(c[x>>2]<<2)>>2]>>8)+1|0)|0;c[w>>2]=(Sf(c[u+(c[x>>2]<<2)>>2]|0)|0)-1024;c[r>>2]=(c[r>>2]|0)+(_((c[w>>2]&65535)<<16>>16,(c[w>>2]&65535)<<16>>16)|0);if((c[B>>2]|0)<1048576){E=(_e(c[B>>2]|0)|0)<<6>>16;E=_(E,(c[w>>2]&65535)<<16>>16)|0;F=(_e(c[B>>2]|0)|0)<<6&65535;c[w>>2]=E+((_(F,(c[w>>2]&65535)<<16>>16)|0)>>16)}F=_(c[17944+(c[x>>2]<<2)>>2]>>16,(c[w>>2]&65535)<<16>>16)|0;c[p>>2]=(c[p>>2]|0)+(F+((_(c[17944+(c[x>>2]<<2)>>2]&65535,(c[w>>2]&65535)<<16>>16)|0)>>16))}else c[u+(d<<2)>>2]=256;c[x>>2]=(c[x>>2]|0)+1}c[r>>2]=(c[r>>2]|0)/4|0;c[q>>2]=((_e(c[r>>2]|0)|0)*3&65535)<<16>>16;c[v>>2]=tg(0+(((c[q>>2]&65535)<<16>>16)*45e3>>16)-128|0)|0;F=(tg(c[p>>2]|0)|0)-16384<<1;c[(c[s>>2]|0)+4744>>2]=F;c[B>>2]=0;c[x>>2]=0;while(1){if((c[x>>2]|0)>=4)break;F=_((c[x>>2]|0)+1|0,(c[o+(c[x>>2]<<2)>>2]|0)-(c[(c[y>>2]|0)+60+(c[x>>2]<<2)>>2]|0)>>4)|0;c[B>>2]=(c[B>>2]|0)+F;c[x>>2]=(c[x>>2]|0)+1}if((c[B>>2]|0)>0){if((c[B>>2]|0)<32768){d=c[B>>2]|0;if((c[(c[s>>2]|0)+4608>>2]|0)==((c[(c[s>>2]|0)+4600>>2]|0)*10|0)){if((d|0)>32767)d=32767;else d=(c[B>>2]|0)<-32768?-32768:c[B>>2]|0;c[B>>2]=d<<16}else{if((d|0)>65535)d=65535;else d=(c[B>>2]|0)<-65536?-65536:c[B>>2]|0;c[B>>2]=d<<15}c[B>>2]=_e(c[B>>2]|0)|0;F=_(32768+(c[B>>2]|0)>>16,(c[v>>2]&65535)<<16>>16)|0;c[v>>2]=F+((_(32768+(c[B>>2]|0)&65535,(c[v>>2]&65535)<<16>>16)|0)>>16)}}else c[v>>2]=c[v>>2]>>1;F=Xe(c[v>>2]>>7,255)|0;c[(c[s>>2]|0)+4556>>2]=F;F=_(c[v>>2]>>16,(c[v>>2]&65535)<<16>>16)|0;c[A>>2]=0+((F+((_(c[v>>2]&65535,(c[v>>2]&65535)<<16>>16)|0)>>16)&65535)<<16>>16<<12>>16);if((c[(c[s>>2]|0)+4608>>2]|0)==((c[(c[s>>2]|0)+4600>>2]|0)*10|0))c[A>>2]=c[A>>2]>>1;c[x>>2]=0;while(1){if((c[x>>2]|0)>=4)break;F=_((c[u+(c[x>>2]<<2)>>2]|0)-(c[(c[y>>2]|0)+40+(c[x>>2]<<2)>>2]|0)>>16,(c[A>>2]&65535)<<16>>16)|0;F=(c[(c[y>>2]|0)+40+(c[x>>2]<<2)>>2]|0)+(F+((_((c[u+(c[x>>2]<<2)>>2]|0)-(c[(c[y>>2]|0)+40+(c[x>>2]<<2)>>2]|0)&65535,(c[A>>2]&65535)<<16>>16)|0)>>16))|0;c[(c[y>>2]|0)+40+(c[x>>2]<<2)>>2]=F;c[w>>2]=((Sf(c[(c[y>>2]|0)+40+(c[x>>2]<<2)>>2]|0)|0)-1024|0)*3;F=tg((c[w>>2]|0)-2048>>4)|0;c[(c[s>>2]|0)+4728+(c[x>>2]<<2)>>2]=F;c[x>>2]=(c[x>>2]|0)+1}F=c[z>>2]|0;na(c[t>>2]|0);i=C;return F|0}function Xe(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Ye(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;d=m+28|0;e=m+24|0;h=m+20|0;k=m+16|0;l=m+12|0;g=m+8|0;f=m+4|0;j=m;c[d>>2]=a;c[e>>2]=b;if((c[(c[e>>2]|0)+108>>2]|0)<1e3)c[j>>2]=32767/((c[(c[e>>2]|0)+108>>2]>>4)+1|0)|0;else c[j>>2]=0;c[h>>2]=0;while(1){if((c[h>>2]|0)>=4)break;c[k>>2]=c[(c[e>>2]|0)+60+(c[h>>2]<<2)>>2];if((c[(c[d>>2]|0)+(c[h>>2]<<2)>>2]|0)+(c[(c[e>>2]|0)+92+(c[h>>2]<<2)>>2]|0)&-2147483648|0)a=2147483647;else a=(c[(c[d>>2]|0)+(c[h>>2]<<2)>>2]|0)+(c[(c[e>>2]|0)+92+(c[h>>2]<<2)>>2]|0)|0;c[l>>2]=a;c[g>>2]=2147483647/(c[l>>2]|0)|0;do if((c[l>>2]|0)<=(c[k>>2]<<3|0))if((c[l>>2]|0)<(c[k>>2]|0)){c[f>>2]=1024;break}else{a=_(c[g>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;a=a+((_(c[g>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16)|0;a=a+(_(c[g>>2]|0,(c[k>>2]>>15)+1>>1)|0)>>16<<11;b=_(c[g>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;b=b+((_(c[g>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16)|0;c[f>>2]=a+((b+(_(c[g>>2]|0,(c[k>>2]>>15)+1>>1)|0)&65535)<<11>>16);break}else c[f>>2]=128;while(0);c[f>>2]=Ze(c[f>>2]|0,c[j>>2]|0)|0;b=_((c[g>>2]|0)-(c[(c[e>>2]|0)+76+(c[h>>2]<<2)>>2]|0)>>16,(c[f>>2]&65535)<<16>>16)|0;b=(c[(c[e>>2]|0)+76+(c[h>>2]<<2)>>2]|0)+(b+((_((c[g>>2]|0)-(c[(c[e>>2]|0)+76+(c[h>>2]<<2)>>2]|0)&65535,(c[f>>2]&65535)<<16>>16)|0)>>16))|0;c[(c[e>>2]|0)+76+(c[h>>2]<<2)>>2]=b;c[k>>2]=2147483647/(c[(c[e>>2]|0)+76+(c[h>>2]<<2)>>2]|0)|0;c[k>>2]=(c[k>>2]|0)<16777215?c[k>>2]|0:16777215;c[(c[e>>2]|0)+60+(c[h>>2]<<2)>>2]=c[k>>2];c[h>>2]=(c[h>>2]|0)+1}l=(c[e>>2]|0)+108|0;c[l>>2]=(c[l>>2]|0)+1;i=m;return}function Ze(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function _e(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+32|0;b=h+16|0;d=h+12|0;g=h+8|0;f=h+4|0;e=h;c[d>>2]=a;if((c[d>>2]|0)<=0){c[b>>2]=0;g=c[b>>2]|0;i=h;return g|0}$e(c[d>>2]|0,f,e);if(c[f>>2]&1|0)c[g>>2]=32768;else c[g>>2]=46214;c[g>>2]=c[g>>2]>>(c[f>>2]>>1);a=_(c[g>>2]>>16,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0;c[g>>2]=(c[g>>2]|0)+(a+((_(c[g>>2]&65535,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0)>>16));c[b>>2]=c[g>>2];g=c[b>>2]|0;i=h;return g|0}function $e(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;e=i;i=i+16|0;h=e+12|0;j=e+8|0;f=e+4|0;g=e;c[h>>2]=a;c[j>>2]=b;c[f>>2]=d;c[g>>2]=af(c[h>>2]|0)|0;c[c[j>>2]>>2]=c[g>>2];b=(bf(c[h>>2]|0,24-(c[g>>2]|0)|0)|0)&127;c[c[f>>2]>>2]=b;i=e;return}function af(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function bf(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+20|0;d=k+16|0;f=k+12|0;j=k+8|0;h=k+4|0;g=k;c[d>>2]=a;c[f>>2]=b;c[j>>2]=c[d>>2];c[h>>2]=c[f>>2];c[g>>2]=0-(c[f>>2]|0);if(!(c[f>>2]|0)){c[e>>2]=c[d>>2];j=c[e>>2]|0;i=k;return j|0}d=c[j>>2]|0;if((c[f>>2]|0)<0){c[e>>2]=d<>2]|(c[j>>2]|0)>>>(32-(c[g>>2]|0)|0);j=c[e>>2]|0;i=k;return j|0}else{c[e>>2]=d<<32-(c[h>>2]|0)|(c[j>>2]|0)>>>(c[h>>2]|0);j=c[e>>2]|0;i=k;return j|0}return 0}function cf(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0;h=i;i=i+16|0;f=h+12|0;d=h+8|0;g=h+4|0;e=h;c[f>>2]=a;c[d>>2]=b;c[g>>2]=c[(c[f>>2]|0)+4600>>2];c[e>>2]=((c[g>>2]&65535)<<16>>16)*1e3;if(!(c[e>>2]|0)){b=c[f>>2]|0;if((c[(c[f>>2]|0)+4596>>2]|0)<(c[(c[f>>2]|0)+4580>>2]|0))b=c[b+4596>>2]|0;else b=c[b+4580>>2]|0;c[e>>2]=b;c[g>>2]=(c[e>>2]|0)/1e3|0;g=c[g>>2]|0;i=h;return g|0}if(((c[e>>2]|0)<=(c[(c[f>>2]|0)+4580>>2]|0)?(c[e>>2]|0)<=(c[(c[f>>2]|0)+4588>>2]|0):0)?(c[e>>2]|0)>=(c[(c[f>>2]|0)+4592>>2]|0):0){if((c[(c[f>>2]|0)+16+8>>2]|0)>=256)c[(c[f>>2]|0)+16+12>>2]=0;if((c[(c[f>>2]|0)+4560>>2]|0)==0?(c[(c[d>>2]|0)+60>>2]|0)==0:0){g=c[g>>2]|0;i=h;return g|0}b=c[f>>2]|0;if((((c[(c[f>>2]|0)+4600>>2]&65535)<<16>>16)*1e3|0)>(c[(c[f>>2]|0)+4596>>2]|0)){if(!(c[b+16+12>>2]|0)){c[(c[f>>2]|0)+16+8>>2]=256;e=(c[f>>2]|0)+16|0;c[e>>2]=0;c[e+4>>2]=0}b=(c[f>>2]|0)+16|0;if(c[(c[d>>2]|0)+60>>2]|0){c[b+12>>2]=0;c[g>>2]=(c[(c[f>>2]|0)+4600>>2]|0)==16?12:8;g=c[g>>2]|0;i=h;return g|0}if((c[b+8>>2]|0)<=0){c[(c[d>>2]|0)+84>>2]=1;f=(c[d>>2]|0)+52|0;c[f>>2]=(c[f>>2]|0)-(((c[(c[d>>2]|0)+52>>2]|0)*5|0)/((c[(c[d>>2]|0)+24>>2]|0)+5|0)|0);g=c[g>>2]|0;i=h;return g|0}else{c[(c[f>>2]|0)+16+12>>2]=-2;g=c[g>>2]|0;i=h;return g|0}}if((((c[b+4600>>2]&65535)<<16>>16)*1e3|0)>=(c[(c[f>>2]|0)+4596>>2]|0)){if((c[(c[f>>2]|0)+16+12>>2]|0)>=0){g=c[g>>2]|0;i=h;return g|0}c[(c[f>>2]|0)+16+12>>2]=1;g=c[g>>2]|0;i=h;return g|0}b=c[f>>2]|0;if(c[(c[d>>2]|0)+60>>2]|0){c[g>>2]=(c[b+4600>>2]|0)==8?12:16;c[(c[f>>2]|0)+16+8>>2]=0;e=(c[f>>2]|0)+16|0;c[e>>2]=0;c[e+4>>2]=0;c[(c[f>>2]|0)+16+12>>2]=1;g=c[g>>2]|0;i=h;return g|0}if(!(c[b+16+12>>2]|0)){c[(c[d>>2]|0)+84>>2]=1;f=(c[d>>2]|0)+52|0;c[f>>2]=(c[f>>2]|0)-(((c[(c[d>>2]|0)+52>>2]|0)*5|0)/((c[(c[d>>2]|0)+24>>2]|0)+5|0)|0);g=c[g>>2]|0;i=h;return g|0}else{c[(c[f>>2]|0)+16+12>>2]=1;g=c[g>>2]|0;i=h;return g|0}}c[e>>2]=c[(c[f>>2]|0)+4580>>2];if((c[e>>2]|0)<(c[(c[f>>2]|0)+4588>>2]|0))b=c[e>>2]|0;else b=c[(c[f>>2]|0)+4588>>2]|0;c[e>>2]=b;if((c[e>>2]|0)>(c[(c[f>>2]|0)+4592>>2]|0))b=c[e>>2]|0;else b=c[(c[f>>2]|0)+4592>>2]|0;c[e>>2]=b;c[g>>2]=(c[e>>2]|0)/1e3|0;g=c[g>>2]|0;i=h;return g|0}function df(d,e,f,g,h,j,k,l,m){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;var n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0;M=i;i=i+112|0;E=M+96|0;F=M+92|0;n=M+88|0;G=M+84|0;o=M+80|0;p=M+76|0;q=M+72|0;H=M+68|0;K=M+60|0;L=M+56|0;u=M+52|0;D=M+100|0;v=M+48|0;J=M+44|0;t=M+40|0;s=M+36|0;r=M+32|0;B=M+28|0;A=M+24|0;z=M+20|0;C=M+16|0;I=M+12|0;y=M+8|0;w=M+4|0;x=M;c[E>>2]=d;c[F>>2]=e;c[n>>2]=f;c[G>>2]=g;c[o>>2]=h;c[p>>2]=j;c[q>>2]=k;c[H>>2]=l;c[M+64>>2]=m;c[z>>2]=2147483647;c[I>>2]=0;c[L>>2]=0;while(1){if((c[L>>2]|0)>=3)break;c[x>>2]=51;c[v>>2]=c[17632+(c[L>>2]<<2)>>2];c[J>>2]=c[17644+(c[L>>2]<<2)>>2];c[t>>2]=c[17656+(c[L>>2]<<2)>>2];c[u>>2]=a[27263+(c[L>>2]|0)>>0];c[r>>2]=c[o>>2];c[s>>2]=c[E>>2];c[A>>2]=0;c[C>>2]=c[c[G>>2]>>2];c[K>>2]=0;while(1){if((c[K>>2]|0)>=(c[H>>2]|0))break;g=Wf(5333-(c[C>>2]|0)+896|0)|0;c[y>>2]=g-(c[x>>2]|0);ef(D+(c[K>>2]|0)|0,B,w,c[s>>2]|0,c[r>>2]|0,c[J>>2]|0,c[t>>2]|0,c[v>>2]|0,c[p>>2]|0,c[y>>2]|0,c[u>>2]|0);if((c[A>>2]|0)+(c[B>>2]|0)&-2147483648|0)d=2147483647;else d=(c[A>>2]|0)+(c[B>>2]|0)|0;c[A>>2]=d;g=c[C>>2]|0;if(0>(g+(Sf((c[x>>2]|0)+(c[w>>2]|0)|0)|0)-896|0))d=0;else{d=c[C>>2]|0;d=d+(Sf((c[x>>2]|0)+(c[w>>2]|0)|0)|0)-896|0}c[C>>2]=d;c[s>>2]=(c[s>>2]|0)+10;c[r>>2]=(c[r>>2]|0)+100;c[K>>2]=(c[K>>2]|0)+1}c[A>>2]=2147483646<(c[A>>2]|0)?2147483646:c[A>>2]|0;if((c[A>>2]|0)<(c[z>>2]|0)){c[z>>2]=c[A>>2];a[c[n>>2]>>0]=c[L>>2];pj(c[F>>2]|0,D|0,c[H>>2]|0)|0;c[I>>2]=c[C>>2]}if(c[q>>2]|0?(c[A>>2]|0)<(b[12226]|0):0)break;c[L>>2]=(c[L>>2]|0)+1}c[J>>2]=c[17644+(a[c[n>>2]>>0]<<2)>>2];c[K>>2]=0;while(1){if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65535,b[B+6>>1]|0)|0)>>16));H=_(c[(c[v>>2]|0)+96>>2]>>16,b[B+8>>1]|0)|0;c[F>>2]=H+((_(c[(c[v>>2]|0)+96>>2]&65535,b[B+8>>1]|0)|0)>>16);H=_(c[F>>2]>>16,b[B+8>>1]|0)|0;c[E>>2]=(c[E>>2]|0)+(H+((_(c[F>>2]&65535,b[B+8>>1]|0)|0)>>16));if((c[E>>2]|0)<(c[c[r>>2]>>2]|0)){c[c[r>>2]>>2]=c[E>>2];a[c[q>>2]>>0]=c[D>>2];c[c[t>>2]>>2]=c[C>>2]}c[A>>2]=(c[A>>2]|0)+5;c[D>>2]=(c[D>>2]|0)+1}i=G;return}function ff(b){b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0;j=i;i=i+32|0;k=j+20|0;f=j+16|0;d=j+12|0;e=j+8|0;g=j+4|0;h=j;c[k>>2]=b;c[h>>2]=c[k>>2];if((a[(c[h>>2]|0)+4565>>0]|0)!=2){i=j;return}c[d>>2]=((c[(c[h>>2]|0)+4600>>2]|0)*1e3<<16|0)/(c[(c[h>>2]|0)+4568>>2]|0)|0;c[e>>2]=(Sf(c[d>>2]|0)|0)-2048;c[f>>2]=c[(c[h>>2]|0)+4728>>2];l=c[e>>2]|0;b=_(0-(c[f>>2]|0)<<2>>16,(c[f>>2]&65535)<<16>>16)|0;b=b+((_(0-(c[f>>2]|0)<<2&65535,(c[f>>2]&65535)<<16>>16)|0)>>16)>>16;d=c[e>>2]|0;d=_(b,(d-((Sf(3932160)|0)-2048)&65535)<<16>>16)|0;b=_(0-(c[f>>2]|0)<<2>>16,(c[f>>2]&65535)<<16>>16)|0;b=b+((_(0-(c[f>>2]|0)<<2&65535,(c[f>>2]&65535)<<16>>16)|0)>>16)&65535;k=c[e>>2]|0;c[e>>2]=l+(d+((_(b,(k-((Sf(3932160)|0)-2048)&65535)<<16>>16)|0)>>16));c[g>>2]=(c[e>>2]|0)-(c[(c[h>>2]|0)+8>>2]>>8);if((c[g>>2]|0)<0)c[g>>2]=(c[g>>2]|0)*3;if((c[g>>2]|0)>51)d=51;else d=(c[g>>2]|0)<-51?-51:c[g>>2]|0;c[g>>2]=d;l=((_((c[(c[h>>2]|0)+4556>>2]&65535)<<16>>16,(c[g>>2]&65535)<<16>>16)|0)>>16)*6554|0;l=(c[(c[h>>2]|0)+8>>2]|0)+(l+(((_((c[(c[h>>2]|0)+4556>>2]&65535)<<16>>16,(c[g>>2]&65535)<<16>>16)|0)&65535)*6554>>16))|0;c[(c[h>>2]|0)+8>>2]=l;l=(Sf(60)|0)<<8;l=(l|0)>((Sf(100)|0)<<8|0);d=c[(c[h>>2]|0)+8>>2]|0;do if(l){if((d|0)>((Sf(60)|0)<<8|0)){d=(Sf(60)|0)<<8;break}l=c[(c[h>>2]|0)+8>>2]|0;if((l|0)<((Sf(100)|0)<<8|0)){d=(Sf(100)|0)<<8;break}else{d=c[(c[h>>2]|0)+8>>2]|0;break}}else{if((d|0)>((Sf(100)|0)<<8|0)){d=(Sf(100)|0)<<8;break}l=c[(c[h>>2]|0)+8>>2]|0;if((l|0)<((Sf(60)|0)<<8|0)){d=(Sf(60)|0)<<8;break}else{d=c[(c[h>>2]|0)+8>>2]|0;break}}while(0);c[(c[h>>2]|0)+8>>2]=d;i=j;return}function gf(f,g,h,j,k,l,m){f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;var n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0;L=i;i=i+288|0;n=L+64|0;o=L+60|0;p=L+56|0;q=L+52|0;r=L+48|0;s=L+44|0;t=L+40|0;C=L+36|0;K=L+32|0;E=L+28|0;z=L+24|0;H=L+20|0;A=L+16|0;x=L+12|0;J=L+232|0;I=L+200|0;v=L+168|0;y=L+136|0;w=L+104|0;G=L+264|0;B=L+72|0;F=L+8|0;D=L+4|0;u=L;c[n>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g>>2]>>(c[f>>2]>>1);a=_(c[g>>2]>>16,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0;c[g>>2]=(c[g>>2]|0)+(a+((_(c[g>>2]&65535,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0)>>16));c[b>>2]=c[g>>2];g=c[b>>2]|0;i=h;return g|0}function jf(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;e=i;i=i+16|0;h=e+12|0;j=e+8|0;f=e+4|0;g=e;c[h>>2]=a;c[j>>2]=b;c[f>>2]=d;c[g>>2]=kf(c[h>>2]|0)|0;c[c[j>>2]>>2]=c[g>>2];b=(lf(c[h>>2]|0,24-(c[g>>2]|0)|0)|0)&127;c[c[f>>2]>>2]=b;i=e;return}function kf(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function lf(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+20|0;d=k+16|0;f=k+12|0;j=k+8|0;h=k+4|0;g=k;c[d>>2]=a;c[f>>2]=b;c[j>>2]=c[d>>2];c[h>>2]=c[f>>2];c[g>>2]=0-(c[f>>2]|0);if(!(c[f>>2]|0)){c[e>>2]=c[d>>2];j=c[e>>2]|0;i=k;return j|0}d=c[j>>2]|0;if((c[f>>2]|0)<0){c[e>>2]=d<>2]|(c[j>>2]|0)>>>(32-(c[g>>2]|0)|0);j=c[e>>2]|0;i=k;return j|0}else{c[e>>2]=d<<32-(c[h>>2]|0)|(c[j>>2]|0)>>>(c[h>>2]|0);j=c[e>>2]|0;i=k;return j|0}return 0}function mf(a,e,f,g,h){a=a|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;t=i;i=i+48|0;j=t+36|0;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y>>1]=o;c[E>>2]=-10;while(1){if((c[E>>2]|0)>9)break;c[Q>>2]=c[E>>2]<<10;c[S>>2]=(c[Q>>2]|0)+1024;do if((c[E>>2]|0)<=0){if(!(c[E>>2]|0)){c[S>>2]=(c[S>>2]|0)-102;break}f=(c[E>>2]|0)==-1;c[Q>>2]=(c[Q>>2]|0)+102;if(!f)c[S>>2]=(c[S>>2]|0)+102}else{c[Q>>2]=(c[Q>>2]|0)-102;c[S>>2]=(c[S>>2]|0)-102}while(0);f=_(c[Q>>2]>>16,(c[p>>2]&65535)<<16>>16)|0;f=f+((_(c[Q>>2]&65535,(c[p>>2]&65535)<<16>>16)|0)>>16)|0;c[R+((c[E>>2]|0)+10<<2)>>2]=f;f=_(c[S>>2]>>16,(c[p>>2]&65535)<<16>>16)|0;f=f+((_(c[S>>2]&65535,(c[p>>2]&65535)<<16>>16)|0)>>16)|0;c[T+((c[E>>2]|0)+10<<2)>>2]=f;c[E>>2]=(c[E>>2]|0)+1}c[P>>2]=1;c[z>>2]=0;b[W>>1]=0;c[E>>2]=(b[y>>1]|0)-1;a:while(1){c[Z>>2]=(c[v>>2]|0)+(b[(c[u>>2]|0)+(c[E>>2]<<1)>>1]|0);c[V>>2]=d[(c[t>>2]|0)+(c[E>>2]|0)>>0]<<8;c[F>>2]=b[(c[r>>2]|0)+(c[E>>2]<<1)>>1];c[L>>2]=0;while(1){if((c[L>>2]|0)>=(c[P>>2]|0))break;f=_(c[V>>2]>>16,b[W+(c[L>>2]<<1)>>1]|0)|0;c[U>>2]=f+((_(c[V>>2]&65535,b[W+(c[L>>2]<<1)>>1]|0)|0)>>16);c[$>>2]=(c[F>>2]|0)-(c[U>>2]|0);f=_(b[w>>1]>>16,(c[$>>2]&65535)<<16>>16)|0;c[K>>2]=f+((_(b[w>>1]&65535,(c[$>>2]&65535)<<16>>16)|0)>>16);if((c[K>>2]|0)>9)p=9;else p=(c[K>>2]|0)<-10?-10:c[K>>2]|0;c[K>>2]=p;a[G+(c[L>>2]<<4)+(c[E>>2]|0)>>0]=c[K>>2];c[Q>>2]=c[R+((c[K>>2]|0)+10<<2)>>2];c[S>>2]=c[T+((c[K>>2]|0)+10<<2)>>2];c[Q>>2]=(c[Q>>2]|0)+(c[U>>2]|0);c[S>>2]=(c[S>>2]|0)+(c[U>>2]|0);b[W+(c[L>>2]<<1)>>1]=c[Q>>2];b[W+((c[L>>2]|0)+(c[P>>2]|0)<<1)>>1]=c[S>>2];j=c[K>>2]|0;do if(((c[K>>2]|0)+1|0)>=4){p=c[K>>2]|0;if((j+1|0)==4){c[X>>2]=d[(c[Z>>2]|0)+(p+4)>>0];c[Y>>2]=280;break}else{c[X>>2]=108+(((p&65535)<<16>>16)*43|0);c[Y>>2]=(c[X>>2]|0)+43;break}}else{p=c[K>>2]|0;if((j|0)>-4){c[X>>2]=d[(c[Z>>2]|0)+(p+4)>>0];c[Y>>2]=d[(c[Z>>2]|0)+((c[K>>2]|0)+1+4)>>0];break}if((p|0)==-4){c[X>>2]=280;c[Y>>2]=d[(c[Z>>2]|0)+((c[K>>2]|0)+1+4)>>0];break}else{c[X>>2]=108+(_(-43,(c[K>>2]&65535)<<16>>16)|0);c[Y>>2]=(c[X>>2]|0)-43;break}}while(0);c[C>>2]=c[z+(c[L>>2]<<2)>>2];c[D>>2]=(c[F>>2]|0)-(c[Q>>2]|0);f=_((c[D>>2]&65535)<<16>>16,(c[D>>2]&65535)<<16>>16)|0;f=(c[C>>2]|0)+(_(f,b[(c[s>>2]|0)+(c[E>>2]<<1)>>1]|0)|0)|0;f=f+(_((c[x>>2]&65535)<<16>>16,(c[X>>2]&65535)<<16>>16)|0)|0;c[z+(c[L>>2]<<2)>>2]=f;c[D>>2]=(c[F>>2]|0)-(c[S>>2]|0);f=_((c[D>>2]&65535)<<16>>16,(c[D>>2]&65535)<<16>>16)|0;f=(c[C>>2]|0)+(_(f,b[(c[s>>2]|0)+(c[E>>2]<<1)>>1]|0)|0)|0;f=f+(_((c[x>>2]&65535)<<16>>16,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a;return c[N>>2]|0}function pf(d,e,f,g){d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;t=i;i=i+128|0;h=t+28|0;j=t+24|0;k=t+20|0;l=t+16|0;o=t+12|0;n=t+8|0;m=t+4|0;p=t;q=t+96|0;s=t+64|0;r=t+32|0;c[h>>2]=d;c[j>>2]=e;c[k>>2]=f;c[l>>2]=g;d=_(-5,(c[(c[h>>2]|0)+4556>>2]&65535)<<16>>16)|0;c[m>>2]=3146+(d+(((c[(c[h>>2]|0)+4556>>2]&65535)<<16>>16)*59246>>16));if((c[(c[h>>2]|0)+4604>>2]|0)==2)c[m>>2]=(c[m>>2]|0)+(c[m>>2]>>1);fg(s,c[k>>2]|0,c[(c[h>>2]|0)+4664>>2]|0);if((c[(c[h>>2]|0)+4656>>2]|0)==1)e=(a[(c[h>>2]|0)+4768+31>>0]|0)<4;else e=0;c[n>>2]=e&1;a:do if(c[n>>2]|0){de(q,c[l>>2]|0,c[k>>2]|0,a[(c[h>>2]|0)+4768+31>>0]|0,c[(c[h>>2]|0)+4664>>2]|0);fg(r,q,c[(c[h>>2]|0)+4664>>2]|0);c[p>>2]=(_(a[(c[h>>2]|0)+4768+31>>0]<<16>>16,a[(c[h>>2]|0)+4768+31>>0]<<16>>16)|0)<<11;c[o>>2]=0;while(1){if((c[o>>2]|0)>=(c[(c[h>>2]|0)+4664>>2]|0))break a;d=_(b[r+(c[o>>2]<<1)>>1]>>16,(c[p>>2]&65535)<<16>>16)|0;d=(b[s+(c[o>>2]<<1)>>1]>>1)+(d+((_(b[r+(c[o>>2]<<1)>>1]&65535,(c[p>>2]&65535)<<16>>16)|0)>>16))&65535;b[s+(c[o>>2]<<1)>>1]=d;c[o>>2]=(c[o>>2]|0)+1}}while(0);gf((c[h>>2]|0)+4768+8|0,c[k>>2]|0,c[(c[h>>2]|0)+4724>>2]|0,s,c[m>>2]|0,c[(c[h>>2]|0)+4692>>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)+1}o=i;i=i+((1*(c[K>>2]<<1)|0)+15&-16)|0;n=i;i=i+((1*(c[K>>2]<<1)|0)+15&-16)|0;c[O>>2]=0;while(1){if((c[O>>2]|0)>=(c[K>>2]|0))break;c[S>>2]=((b[j+(c[O>>2]<<1)>>1]|0)+(b[j+((c[O>>2]|0)+2<<1)>>1]|0)+(b[j+((c[O>>2]|0)+1<<1)>>1]<<1)>>1)+1>>1;b[o+(c[O>>2]<<1)>>1]=c[S>>2];b[n+(c[O>>2]<<1)>>1]=(b[j+((c[O>>2]|0)+1<<1)>>1]|0)-(c[S>>2]|0);c[O>>2]=(c[O>>2]|0)+1}c[v>>2]=(c[K>>2]|0)==((c[F>>2]|0)*10|0)&1;c[E>>2]=c[v>>2]|0?328:655;q=(_((c[r>>2]&65535)<<16>>16,(c[r>>2]&65535)<<16>>16)|0)>>16;q=_(q,(c[E>>2]&65535)<<16>>16)|0;r=(_((c[r>>2]&65535)<<16>>16,(c[r>>2]&65535)<<16>>16)|0)&65535;c[E>>2]=q+((_(r,(c[E>>2]&65535)<<16>>16)|0)>>16);c[R>>2]=Bg(t,g,o,(c[J>>2]|0)+12|0,c[K>>2]|0,c[E>>2]|0)|0;c[R+4>>2]=Bg(s,h,n,(c[J>>2]|0)+12+8|0,c[K>>2]|0,c[E>>2]|0)|0;c[C>>2]=(c[s>>2]|0)+(((c[t>>2]&65535)<<16>>16)*3|0);c[C>>2]=(c[C>>2]|0)<65536?c[C>>2]|0:65536;v=(c[z>>2]|0)-(c[v>>2]|0?1200:600)|0;c[z>>2]=v;c[z>>2]=(c[z>>2]|0)<1?1:v;c[D>>2]=2e3+(((c[F>>2]&65535)<<16>>16)*900|0);c[u>>2]=(c[C>>2]|0)*3;v=rf(c[z>>2]|0,851968+(c[u>>2]|0)|0,19)|0;c[c[y>>2]>>2]=v;if((c[c[y>>2]>>2]|0)<(c[D>>2]|0)){c[c[y>>2]>>2]=c[D>>2];c[(c[y>>2]|0)+4>>2]=(c[z>>2]|0)-(c[c[y>>2]>>2]|0);v=_(65536+(c[u>>2]|0)>>16,(c[D>>2]&65535)<<16>>16)|0;c[U>>2]=rf((c[(c[y>>2]|0)+4>>2]<<1)-(c[D>>2]|0)|0,v+((_(65536+(c[u>>2]|0)&65535,(c[D>>2]&65535)<<16>>16)|0)>>16)|0,16)|0;if((c[U>>2]|0)>16384)o=16384;else o=(c[U>>2]|0)<0?0:c[U>>2]|0;c[U>>2]=o}else{c[(c[y>>2]|0)+4>>2]=(c[z>>2]|0)-(c[c[y>>2]>>2]|0);c[U>>2]=16384}v=_((c[U>>2]|0)-(b[(c[J>>2]|0)+28>>1]|0)>>16,(c[E>>2]&65535)<<16>>16)|0;E=(b[(c[J>>2]|0)+28>>1]|0)+(v+((_((c[U>>2]|0)-(b[(c[J>>2]|0)+28>>1]|0)&65535,(c[E>>2]&65535)<<16>>16)|0)>>16))&65535;b[(c[J>>2]|0)+28>>1]=E;a[c[x>>2]>>0]=0;a:do if(!(c[A>>2]|0)){do if(!(b[(c[J>>2]|0)+30>>1]|0)){if((c[z>>2]<<3|0)>=((c[D>>2]|0)*13|0)?(E=_(c[C>>2]>>16,b[(c[J>>2]|0)+28>>1]|0)|0,(E+((_(c[C>>2]&65535,b[(c[J>>2]|0)+28>>1]|0)|0)>>16)|0)>=819):0)break;c[R>>2]=(_(b[(c[J>>2]|0)+28>>1]|0,(c[R>>2]&65535)<<16>>16)|0)>>14;c[R+4>>2]=(_(b[(c[J>>2]|0)+28>>1]|0,(c[R+4>>2]&65535)<<16>>16)|0)>>14;Ig(R,c[w>>2]|0);c[U>>2]=0;c[R>>2]=0;c[R+4>>2]=0;c[c[y>>2]>>2]=c[z>>2];c[(c[y>>2]|0)+4>>2]=0;a[c[x>>2]>>0]=1;break a}while(0);do if(b[(c[J>>2]|0)+30>>1]|0){if((c[z>>2]<<3|0)>=((c[D>>2]|0)*11|0)?(E=_(c[C>>2]>>16,b[(c[J>>2]|0)+28>>1]|0)|0,(E+((_(c[C>>2]&65535,b[(c[J>>2]|0)+28>>1]|0)|0)>>16)|0)>=328):0)break;c[R>>2]=(_(b[(c[J>>2]|0)+28>>1]|0,(c[R>>2]&65535)<<16>>16)|0)>>14;c[R+4>>2]=(_(b[(c[J>>2]|0)+28>>1]|0,(c[R+4>>2]&65535)<<16>>16)|0)>>14;Ig(R,c[w>>2]|0);c[U>>2]=0;c[R>>2]=0;c[R+4>>2]=0;break a}while(0);if((b[(c[J>>2]|0)+28>>1]|0)>15565){Ig(R,c[w>>2]|0);c[U>>2]=16384;break}else{c[R>>2]=(_(b[(c[J>>2]|0)+28>>1]|0,(c[R>>2]&65535)<<16>>16)|0)>>14;c[R+4>>2]=(_(b[(c[J>>2]|0)+28>>1]|0,(c[R+4>>2]&65535)<<16>>16)|0)>>14;Ig(R,c[w>>2]|0);c[U>>2]=b[(c[J>>2]|0)+28>>1];break}}else{c[U>>2]=0;c[R>>2]=0;c[R+4>>2]=0;Ig(R,c[w>>2]|0)}while(0);do if((a[c[x>>2]>>0]|0)==1){E=(c[J>>2]|0)+32|0;b[E>>1]=(b[E>>1]|0)+((c[K>>2]|0)-(c[F>>2]<<3));if((b[(c[J>>2]|0)+32>>1]|0)<((c[F>>2]|0)*5|0)){a[c[x>>2]>>0]=0;break}else{b[(c[J>>2]|0)+32>>1]=1e4;break}}else b[(c[J>>2]|0)+32>>1]=0;while(0);if((a[c[x>>2]>>0]|0)==0?(c[(c[y>>2]|0)+4>>2]|0)<1:0){c[(c[y>>2]|0)+4>>2]=1;E=tf(1,(c[z>>2]|0)-(c[(c[y>>2]|0)+4>>2]|0)|0)|0;c[c[y>>2]>>2]=E}c[P>>2]=0-(b[c[J>>2]>>1]|0);c[Q>>2]=0-(b[(c[J>>2]|0)+2>>1]|0);c[T>>2]=b[(c[J>>2]|0)+30>>1]<<10;c[B>>2]=65536/(c[F>>2]<<3|0)|0;c[G>>2]=0-(((_(((c[R>>2]|0)-(b[c[J>>2]>>1]|0)&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0)>>15)+1>>1);c[H>>2]=0-(((_(((c[R+4>>2]|0)-(b[(c[J>>2]|0)+2>>1]|0)&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0)>>15)+1>>1);E=_((c[U>>2]|0)-(b[(c[J>>2]|0)+30>>1]|0)>>16,(c[B>>2]&65535)<<16>>16)|0;c[I>>2]=E+((_((c[U>>2]|0)-(b[(c[J>>2]|0)+30>>1]|0)&65535,(c[B>>2]&65535)<<16>>16)|0)>>16)<<10;c[O>>2]=0;while(1){if((c[O>>2]|0)>=(c[F>>2]<<3|0))break;c[P>>2]=(c[P>>2]|0)+(c[G>>2]|0);c[Q>>2]=(c[Q>>2]|0)+(c[H>>2]|0);c[T>>2]=(c[T>>2]|0)+(c[I>>2]|0);c[S>>2]=(b[(c[N>>2]|0)+(c[O>>2]<<1)>>1]|0)+(b[(c[N>>2]|0)+((c[O>>2]|0)+2<<1)>>1]|0)+(b[(c[N>>2]|0)+((c[O>>2]|0)+1<<1)>>1]<<1)<<9;D=_(c[T>>2]>>16,b[j+((c[O>>2]|0)+1<<1)>>1]|0)|0;D=D+((_(c[T>>2]&65535,b[j+((c[O>>2]|0)+1<<1)>>1]|0)|0)>>16)|0;E=_(c[S>>2]>>16,(c[P>>2]&65535)<<16>>16)|0;c[S>>2]=D+(E+((_(c[S>>2]&65535,(c[P>>2]&65535)<<16>>16)|0)>>16));E=_(b[(c[N>>2]|0)+((c[O>>2]|0)+1<<1)>>1]<<11>>16,(c[Q>>2]&65535)<<16>>16)|0;c[S>>2]=(c[S>>2]|0)+(E+((_(b[(c[N>>2]|0)+((c[O>>2]|0)+1<<1)>>1]<<11&65535,(c[Q>>2]&65535)<<16>>16)|0)>>16));if(((c[S>>2]>>7)+1>>1|0)<=32767)if(((c[S>>2]>>7)+1>>1|0)<-32768)o=-32768;else o=(c[S>>2]>>7)+1>>1;else o=32767;b[(c[M>>2]|0)+((c[O>>2]|0)-1<<1)>>1]=o;c[O>>2]=(c[O>>2]|0)+1}c[P>>2]=0-(c[R>>2]|0);c[Q>>2]=0-(c[R+4>>2]|0);c[T>>2]=c[U>>2]<<10;c[O>>2]=c[F>>2]<<3;while(1){if((c[O>>2]|0)>=(c[K>>2]|0))break;c[S>>2]=(b[(c[N>>2]|0)+(c[O>>2]<<1)>>1]|0)+(b[(c[N>>2]|0)+((c[O>>2]|0)+2<<1)>>1]|0)+(b[(c[N>>2]|0)+((c[O>>2]|0)+1<<1)>>1]<<1)<<9;H=_(c[T>>2]>>16,b[j+((c[O>>2]|0)+1<<1)>>1]|0)|0;H=H+((_(c[T>>2]&65535,b[j+((c[O>>2]|0)+1<<1)>>1]|0)|0)>>16)|0;I=_(c[S>>2]>>16,(c[P>>2]&65535)<<16>>16)|0;c[S>>2]=H+(I+((_(c[S>>2]&65535,(c[P>>2]&65535)<<16>>16)|0)>>16));I=_(b[(c[N>>2]|0)+((c[O>>2]|0)+1<<1)>>1]<<11>>16,(c[Q>>2]&65535)<<16>>16)|0;c[S>>2]=(c[S>>2]|0)+(I+((_(b[(c[N>>2]|0)+((c[O>>2]|0)+1<<1)>>1]<<11&65535,(c[Q>>2]&65535)<<16>>16)|0)>>16));if(((c[S>>2]>>7)+1>>1|0)<=32767)if(((c[S>>2]>>7)+1>>1|0)<-32768)o=-32768;else o=(c[S>>2]>>7)+1>>1;else o=32767;b[(c[M>>2]|0)+((c[O>>2]|0)-1<<1)>>1]=o;c[O>>2]=(c[O>>2]|0)+1}b[c[J>>2]>>1]=c[R>>2];b[(c[J>>2]|0)+2>>1]=c[R+4>>2];b[(c[J>>2]|0)+30>>1]=c[U>>2];na(c[L>>2]|0);i=V;return}function rf(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;h=i;i=i+48|0;f=h+40|0;q=h+36|0;p=h+32|0;j=h+28|0;l=h+24|0;k=h+20|0;g=h+16|0;m=h+12|0;n=h+8|0;o=h+4|0;e=h;c[q>>2]=a;c[p>>2]=b;c[j>>2]=d;b=c[q>>2]|0;c[l>>2]=(sf((c[q>>2]|0)>0?b:0-b|0)|0)-1;c[n>>2]=c[q>>2]<>2];b=c[p>>2]|0;c[k>>2]=(sf((c[p>>2]|0)>0?b:0-b|0)|0)-1;c[o>>2]=c[p>>2]<>2];c[m>>2]=536870911/(c[o>>2]>>16|0)|0;b=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=b+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16);b=c[n>>2]|0;a=c[o>>2]|0;d=c[e>>2]|0;d=yj(a|0,((a|0)<0)<<31>>31|0,d|0,((d|0)<0)<<31>>31|0)|0;d=nj(d|0,C|0,32)|0;c[n>>2]=b-(d<<3);d=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=(c[e>>2]|0)+(d+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16));c[g>>2]=29+(c[l>>2]|0)-(c[k>>2]|0)-(c[j>>2]|0);d=c[g>>2]|0;if((c[g>>2]|0)>=0)if((d|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];q=c[f>>2]|0;i=h;return q|0}else{c[f>>2]=0;q=c[f>>2]|0;i=h;return q|0}a=c[e>>2]|0;b=0-(c[g>>2]|0)|0;do if((-2147483648>>0-d|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>b|0)){d=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){d=2147483647>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>b|0)){d=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){d=-2147483648>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}while(0);c[f>>2]=d<<0-(c[g>>2]|0);q=c[f>>2]|0;i=h;return q|0}function sf(a){a=a|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]|0)+4>>2]|0)-(b[(c[m>>2]|0)+2>>1]|0)&65535)<<16>>16,(c[x>>2]&65535)<<16>>16)|0)>>15)+1>>1;c[u>>2]=0;while(1){if((c[u>>2]|0)>=(c[j>>2]<<3|0))break;c[o>>2]=(c[o>>2]|0)+(c[k>>2]|0);c[p>>2]=(c[p>>2]|0)+(c[l>>2]|0);c[v>>2]=(b[(c[q>>2]|0)+(c[u>>2]<<1)>>1]|0)+(b[(c[q>>2]|0)+((c[u>>2]|0)+2<<1)>>1]|0)+(b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]<<1)<<9;x=_(c[v>>2]>>16,(c[o>>2]&65535)<<16>>16)|0;c[v>>2]=(b[(c[r>>2]|0)+((c[u>>2]|0)+1<<1)>>1]<<8)+(x+((_(c[v>>2]&65535,(c[o>>2]&65535)<<16>>16)|0)>>16));x=_(b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]<<11>>16,(c[p>>2]&65535)<<16>>16)|0;c[v>>2]=(c[v>>2]|0)+(x+((_(b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]<<11&65535,(c[p>>2]&65535)<<16>>16)|0)>>16));if(((c[v>>2]>>7)+1>>1|0)<=32767)if(((c[v>>2]>>7)+1>>1|0)<-32768)h=-32768;else h=(c[v>>2]>>7)+1>>1;else h=32767;b[(c[r>>2]|0)+((c[u>>2]|0)+1<<1)>>1]=h;c[u>>2]=(c[u>>2]|0)+1}c[o>>2]=c[c[n>>2]>>2];c[p>>2]=c[(c[n>>2]|0)+4>>2];c[u>>2]=c[j>>2]<<3;while(1){if((c[u>>2]|0)>=(c[s>>2]|0))break;c[v>>2]=(b[(c[q>>2]|0)+(c[u>>2]<<1)>>1]|0)+(b[(c[q>>2]|0)+((c[u>>2]|0)+2<<1)>>1]|0)+(b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]<<1)<<9;x=_(c[v>>2]>>16,(c[o>>2]&65535)<<16>>16)|0;c[v>>2]=(b[(c[r>>2]|0)+((c[u>>2]|0)+1<<1)>>1]<<8)+(x+((_(c[v>>2]&65535,(c[o>>2]&65535)<<16>>16)|0)>>16));x=_(b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]<<11>>16,(c[p>>2]&65535)<<16>>16)|0;c[v>>2]=(c[v>>2]|0)+(x+((_(b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]<<11&65535,(c[p>>2]&65535)<<16>>16)|0)>>16));if(((c[v>>2]>>7)+1>>1|0)<=32767)if(((c[v>>2]>>7)+1>>1|0)<-32768)h=-32768;else h=(c[v>>2]>>7)+1>>1;else h=32767;b[(c[r>>2]|0)+((c[u>>2]|0)+1<<1)>>1]=h;c[u>>2]=(c[u>>2]|0)+1}b[c[m>>2]>>1]=c[c[n>>2]>>2];b[(c[m>>2]|0)+2>>1]=c[(c[n>>2]|0)+4>>2];c[u>>2]=0;while(1){if((c[u>>2]|0)>=(c[s>>2]|0))break;c[v>>2]=(b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]|0)+(b[(c[r>>2]|0)+((c[u>>2]|0)+1<<1)>>1]|0);c[t>>2]=(b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]|0)-(b[(c[r>>2]|0)+((c[u>>2]|0)+1<<1)>>1]|0);if((c[v>>2]|0)>32767)h=32767;else h=(c[v>>2]|0)<-32768?-32768:c[v>>2]|0;b[(c[q>>2]|0)+((c[u>>2]|0)+1<<1)>>1]=h;if((c[t>>2]|0)>32767)h=32767;else h=(c[t>>2]|0)<-32768?-32768:c[t>>2]|0;b[(c[r>>2]|0)+((c[u>>2]|0)+1<<1)>>1]=h;c[u>>2]=(c[u>>2]|0)+1}i=w;return}function vf(a){a=a|0;var b=0,d=0,e=0,f=0;f=i;i=i+16|0;b=f+4|0;d=f;c[d>>2]=a;if(!(((((((c[(c[d>>2]|0)+8>>2]|0)!=8e3?(c[(c[d>>2]|0)+8>>2]|0)!=12e3:0)?(c[(c[d>>2]|0)+8>>2]|0)!=16e3:0)?(c[(c[d>>2]|0)+8>>2]|0)!=24e3:0)?(c[(c[d>>2]|0)+8>>2]|0)!=32e3:0)?(c[(c[d>>2]|0)+8>>2]|0)!=44100:0)?(c[(c[d>>2]|0)+8>>2]|0)!=48e3:0))e=8;do if((e|0)==8){if(((c[(c[d>>2]|0)+20>>2]|0)!=8e3?(c[(c[d>>2]|0)+20>>2]|0)!=12e3:0)?(c[(c[d>>2]|0)+20>>2]|0)!=16e3:0)break;if(((c[(c[d>>2]|0)+12>>2]|0)!=8e3?(c[(c[d>>2]|0)+12>>2]|0)!=12e3:0)?(c[(c[d>>2]|0)+12>>2]|0)!=16e3:0)break;if(((c[(c[d>>2]|0)+16>>2]|0)!=8e3?(c[(c[d>>2]|0)+16>>2]|0)!=12e3:0)?(c[(c[d>>2]|0)+16>>2]|0)!=16e3:0)break;if(((c[(c[d>>2]|0)+16>>2]|0)<=(c[(c[d>>2]|0)+20>>2]|0)?(c[(c[d>>2]|0)+12>>2]|0)>=(c[(c[d>>2]|0)+20>>2]|0):0)?(c[(c[d>>2]|0)+16>>2]|0)<=(c[(c[d>>2]|0)+12>>2]|0):0){if((((c[(c[d>>2]|0)+24>>2]|0)!=10?(c[(c[d>>2]|0)+24>>2]|0)!=20:0)?(c[(c[d>>2]|0)+24>>2]|0)!=40:0)?(c[(c[d>>2]|0)+24>>2]|0)!=60:0){c[b>>2]=-103;e=c[b>>2]|0;i=f;return e|0}if((c[(c[d>>2]|0)+32>>2]|0)>=0?(c[(c[d>>2]|0)+32>>2]|0)<=100:0){if((c[(c[d>>2]|0)+44>>2]|0)>=0?(c[(c[d>>2]|0)+44>>2]|0)<=1:0){if((c[(c[d>>2]|0)+48>>2]|0)>=0?(c[(c[d>>2]|0)+48>>2]|0)<=1:0){do if((c[(c[d>>2]|0)+40>>2]|0)>=0){if((c[(c[d>>2]|0)+40>>2]|0)>1)break;do if((c[c[d>>2]>>2]|0)>=1){if((c[c[d>>2]>>2]|0)>2)break;do if((c[(c[d>>2]|0)+4>>2]|0)>=1){if((c[(c[d>>2]|0)+4>>2]|0)>2)break;if((c[(c[d>>2]|0)+4>>2]|0)>(c[c[d>>2]>>2]|0)){c[b>>2]=-111;e=c[b>>2]|0;i=f;return e|0}do if((c[(c[d>>2]|0)+36>>2]|0)>=0){if((c[(c[d>>2]|0)+36>>2]|0)>10)break;c[b>>2]=0;e=c[b>>2]|0;i=f;return e|0}while(0);c[b>>2]=-106;e=c[b>>2]|0;i=f;return e|0}while(0);c[b>>2]=-111;e=c[b>>2]|0;i=f;return e|0}while(0);c[b>>2]=-111;e=c[b>>2]|0;i=f;return e|0}while(0);c[b>>2]=-107;e=c[b>>2]|0;i=f;return e|0}c[b>>2]=-109;e=c[b>>2]|0;i=f;return e|0}c[b>>2]=-108;e=c[b>>2]|0;i=f;return e|0}c[b>>2]=-105;e=c[b>>2]|0;i=f;return e|0}}while(0);c[b>>2]=-102;e=c[b>>2]|0;i=f;return e|0}function wf(a,d){a=a|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;e=m+20|0;f=m+16|0;h=m+12|0;k=m+8|0;g=m+4|0;j=m;c[e>>2]=a;c[f>>2]=d;c[k>>2]=0;if((c[f>>2]|0)>8e4)d=8e4;else d=(c[f>>2]|0)<5e3?5e3:c[f>>2]|0;c[f>>2]=d;if((c[f>>2]|0)==(c[(c[e>>2]|0)+4632>>2]|0)){l=c[k>>2]|0;i=m;return l|0}c[(c[e>>2]|0)+4632>>2]=c[f>>2];do if((c[(c[e>>2]|0)+4600>>2]|0)!=8)if((c[(c[e>>2]|0)+4600>>2]|0)==12){c[j>>2]=17772;break}else{c[j>>2]=17804;break}else c[j>>2]=17740;while(0);if((c[(c[e>>2]|0)+4604>>2]|0)==2)c[f>>2]=(c[f>>2]|0)-2200;c[h>>2]=1;while(1){if((c[h>>2]|0)>=8){l=16;break}if((c[f>>2]|0)<=(c[(c[j>>2]|0)+(c[h>>2]<<2)>>2]|0))break;c[h>>2]=(c[h>>2]|0)+1}if((l|0)==16){l=c[k>>2]|0;i=m;return l|0}c[g>>2]=((c[f>>2]|0)-(c[(c[j>>2]|0)+((c[h>>2]|0)-1<<2)>>2]|0)<<6|0)/((c[(c[j>>2]|0)+(c[h>>2]<<2)>>2]|0)-(c[(c[j>>2]|0)+((c[h>>2]|0)-1<<2)>>2]|0)|0)|0;l=(b[24510+((c[h>>2]|0)-1<<1)>>1]<<6)+(_(c[g>>2]|0,(b[24510+(c[h>>2]<<1)>>1]|0)-(b[24510+((c[h>>2]|0)-1<<1)>>1]|0)|0)|0)|0;c[(c[e>>2]|0)+4748>>2]=l;l=c[k>>2]|0;i=m;return l|0}function xf(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0;e=i;i=i+16|0;f=e+8|0;g=e+4|0;d=e;c[f>>2]=a;c[g>>2]=b;c[d>>2]=0;oj(c[f>>2]|0,0,12240)|0;c[(c[f>>2]|0)+5124>>2]=c[g>>2];a=(Sf(3932160)|0)-2048<<8;c[(c[f>>2]|0)+8>>2]=a;c[(c[f>>2]|0)+12>>2]=c[(c[f>>2]|0)+8>>2];c[(c[f>>2]|0)+4696>>2]=1;a=Ue((c[f>>2]|0)+32|0)|0;c[d>>2]=(c[d>>2]|0)+a;i=e;return c[d>>2]|0}function yf(a,b,d,e,f,g){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;p=i;i=i+48|0;h=p+32|0;j=p+28|0;k=p+24|0;l=p+20|0;r=p+16|0;q=p+12|0;m=p+8|0;n=p+4|0;o=p;c[j>>2]=a;c[k>>2]=b;c[l>>2]=d;c[r>>2]=e;c[q>>2]=f;c[m>>2]=g;c[o>>2]=0;c[(c[j>>2]|0)+6108>>2]=c[(c[k>>2]|0)+44>>2];c[(c[j>>2]|0)+4708>>2]=c[(c[k>>2]|0)+48>>2];c[(c[j>>2]|0)+4580>>2]=c[(c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jg((c[d>>2]|0)+5808|0,a,h,c[g>>2]|0)|0;c[l>>2]=(c[l>>2]|0)+k;Bf((c[d>>2]|0)+9356|0,a,c[j>>2]|0);na(c[f>>2]|0);k=c[d>>2]|0;k=k+4580|0;k=c[k>>2]|0;m=c[d>>2]|0;m=m+4584|0;c[m>>2]=k;m=c[l>>2]|0;i=n;return m|0}return 0}function Af(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0;k=i;i=i+16|0;f=k+12|0;h=k+8|0;l=k+4|0;j=k;c[f>>2]=a;c[h>>2]=d;c[l>>2]=e;c[j>>2]=(c[l>>2]|0)-1;while(1){if((c[j>>2]|0)<0)break;if((ij(+g[(c[h>>2]|0)+(c[j>>2]<<2)>>2])|0)<=32767)if((ij(+g[(c[h>>2]|0)+(c[j>>2]<<2)>>2])|0)<-32768)d=-32768;else d=ij(+g[(c[h>>2]|0)+(c[j>>2]<<2)>>2])|0;else d=32767;b[(c[f>>2]|0)+(c[j>>2]<<1)>>1]=d;c[j>>2]=(c[j>>2]|0)+-1}i=k;return}function Bf(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0;k=i;i=i+16|0;f=k+12|0;h=k+8|0;l=k+4|0;j=k;c[f>>2]=a;c[h>>2]=d;c[l>>2]=e;c[j>>2]=(c[l>>2]|0)-1;while(1){if((c[j>>2]|0)<0)break;g[(c[f>>2]|0)+(c[j>>2]<<2)>>2]=+(b[(c[h>>2]|0)+(c[j>>2]<<1)>>1]|0);c[j>>2]=(c[j>>2]|0)+-1}i=k;return}function Cf(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0;k=i;i=i+16|0;h=k+12|0;g=k+8|0;f=k+4|0;j=k;c[h>>2]=b;c[g>>2]=d;c[f>>2]=e;c[j>>2]=0;if((c[f>>2]|0)!=(c[(c[h>>2]|0)+4636>>2]|0)){if((c[f>>2]|0)!=10&(c[f>>2]|0)!=20&(c[f>>2]|0)!=40&(c[f>>2]|0)!=60)c[j>>2]=-103;do if((c[f>>2]|0)<=10){c[(c[h>>2]|0)+5776>>2]=1;c[(c[h>>2]|0)+4604>>2]=(c[f>>2]|0)==10?2:1;e=_((c[f>>2]&65535)<<16>>16,(c[g>>2]&65535)<<16>>16)|0;c[(c[h>>2]|0)+4608>>2]=e;c[(c[h>>2]|0)+4572>>2]=((c[g>>2]&65535)<<16>>16)*14;e=(c[h>>2]|0)+4720|0;if((c[(c[h>>2]|0)+4600>>2]|0)==8){c[e>>2]=29174;break}else{c[e>>2]=29162;break}}else{c[(c[h>>2]|0)+5776>>2]=(c[f>>2]|0)/20|0;c[(c[h>>2]|0)+4604>>2]=4;c[(c[h>>2]|0)+4608>>2]=((c[g>>2]&65535)<<16>>16)*20;c[(c[h>>2]|0)+4572>>2]=((c[g>>2]&65535)<<16>>16)*24;e=(c[h>>2]|0)+4720|0;if((c[(c[h>>2]|0)+4600>>2]|0)==8){c[e>>2]=29151;break}else{c[e>>2]=29117;break}}while(0);c[(c[h>>2]|0)+4636>>2]=c[f>>2];c[(c[h>>2]|0)+4632>>2]=0}if((c[(c[h>>2]|0)+4600>>2]|0)==(c[g>>2]|0)){j=c[j>>2]|0;i=k;return j|0}e=(c[h>>2]|0)+7200|0;c[e>>2]=0;c[e+4>>2]=0;c[e+8>>2]=0;c[e+12>>2]=0;oj((c[h>>2]|0)+7216|0,0,2140)|0;oj((c[h>>2]|0)+144|0,0,4380)|0;e=(c[h>>2]|0)+4524|0;c[e>>2]=0;c[e+4>>2]=0;c[e+8>>2]=0;c[e+12>>2]=0;c[e+16>>2]=0;c[e+20>>2]=0;c[e+24>>2]=0;c[e+28>>2]=0;e=(c[h>>2]|0)+16|0;c[e>>2]=0;c[e+4>>2]=0;c[(c[h>>2]|0)+5772>>2]=0;c[(c[h>>2]|0)+5780>>2]=0;c[(c[h>>2]|0)+4632>>2]=0;c[(c[h>>2]|0)+4568>>2]=100;c[(c[h>>2]|0)+4696>>2]=1;c[(c[h>>2]|0)+7216+2136>>2]=100;a[(c[h>>2]|0)+7200>>0]=10;c[(c[h>>2]|0)+144+4356>>2]=100;c[(c[h>>2]|0)+144+4372>>2]=65536;a[(c[h>>2]|0)+4565>>0]=0;c[(c[h>>2]|0)+4600>>2]=c[g>>2];e=(c[(c[h>>2]|0)+4604>>2]|0)==4;d=(c[h>>2]|0)+4720|0;do if((c[(c[h>>2]|0)+4600>>2]|0)==8)if(e){c[d>>2]=29151;break}else{c[d>>2]=29174;break}else if(e){c[d>>2]=29117;break}else{c[d>>2]=29162;break}while(0);if((c[(c[h>>2]|0)+4600>>2]|0)!=8?(c[(c[h>>2]|0)+4600>>2]|0)!=12:0){c[(c[h>>2]|0)+4664>>2]=16;c[(c[h>>2]|0)+4724>>2]=17704}else{c[(c[h>>2]|0)+4664>>2]=10;c[(c[h>>2]|0)+4724>>2]=17668}c[(c[h>>2]|0)+4612>>2]=(c[g>>2]|0)*5;e=_((c[(c[h>>2]|0)+4612>>2]&65535)<<16>>16,(c[(c[h>>2]|0)+4604>>2]&65535)<<16>>16)|0;c[(c[h>>2]|0)+4608>>2]=e;c[(c[h>>2]|0)+4616>>2]=((c[g>>2]&65535)<<16>>16)*20;c[(c[h>>2]|0)+4620>>2]=(c[g>>2]&65535)<<16>>16<<1;c[(c[h>>2]|0)+4576>>2]=((c[g>>2]&65535)<<16>>16)*18;e=(c[g>>2]&65535)<<16>>16;if((c[(c[h>>2]|0)+4604>>2]|0)==4)c[(c[h>>2]|0)+4572>>2]=e*24;else c[(c[h>>2]|0)+4572>>2]=e*14;e=c[h>>2]|0;if((c[(c[h>>2]|0)+4600>>2]|0)==16){c[e+4684>>2]=10;c[(c[h>>2]|0)+4716>>2]=29049;j=c[j>>2]|0;i=k;return j|0}d=(c[h>>2]|0)+4684|0;if((c[e+4600>>2]|0)==12){c[d>>2]=13;c[(c[h>>2]|0)+4716>>2]=29043;j=c[j>>2]|0;i=k;return j|0}else{c[d>>2]=15;c[(c[h>>2]|0)+4716>>2]=29034;j=c[j>>2]|0;i=k;return j|0}return 0}function Df(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0;g=i;i=i+16|0;d=g+8|0;e=g+4|0;f=g;c[d>>2]=a;c[e>>2]=b;c[f>>2]=0;do if((c[e>>2]|0)>=2){if((c[e>>2]|0)<4){c[(c[d>>2]|0)+4668>>2]=1;c[(c[d>>2]|0)+4676>>2]=49807;c[(c[d>>2]|0)+4672>>2]=8;c[(c[d>>2]|0)+4660>>2]=10;c[(c[d>>2]|0)+4624>>2]=(c[(c[d>>2]|0)+4600>>2]|0)*5;c[(c[d>>2]|0)+4652>>2]=1;c[(c[d>>2]|0)+4656>>2]=0;c[(c[d>>2]|0)+4680>>2]=0;c[(c[d>>2]|0)+4692>>2]=4;c[(c[d>>2]|0)+4704>>2]=0;break}if((c[e>>2]|0)<6){c[(c[d>>2]|0)+4668>>2]=1;c[(c[d>>2]|0)+4676>>2]=48497;c[(c[d>>2]|0)+4672>>2]=10;c[(c[d>>2]|0)+4660>>2]=12;c[(c[d>>2]|0)+4624>>2]=(c[(c[d>>2]|0)+4600>>2]|0)*5;c[(c[d>>2]|0)+4652>>2]=2;c[(c[d>>2]|0)+4656>>2]=1;c[(c[d>>2]|0)+4680>>2]=0;c[(c[d>>2]|0)+4692>>2]=8;c[(c[d>>2]|0)+4704>>2]=(c[(c[d>>2]|0)+4600>>2]|0)*983;break}b=(c[d>>2]|0)+4668|0;if((c[e>>2]|0)<8){c[b>>2]=1;c[(c[d>>2]|0)+4676>>2]=47186;c[(c[d>>2]|0)+4672>>2]=12;c[(c[d>>2]|0)+4660>>2]=14;c[(c[d>>2]|0)+4624>>2]=(c[(c[d>>2]|0)+4600>>2]|0)*5;c[(c[d>>2]|0)+4652>>2]=3;c[(c[d>>2]|0)+4656>>2]=1;c[(c[d>>2]|0)+4680>>2]=0;c[(c[d>>2]|0)+4692>>2]=16;c[(c[d>>2]|0)+4704>>2]=(c[(c[d>>2]|0)+4600>>2]|0)*983;break}else{c[b>>2]=2;c[(c[d>>2]|0)+4676>>2]=45875;c[(c[d>>2]|0)+4672>>2]=16;c[(c[d>>2]|0)+4660>>2]=16;c[(c[d>>2]|0)+4624>>2]=(c[(c[d>>2]|0)+4600>>2]|0)*5;c[(c[d>>2]|0)+4652>>2]=4;c[(c[d>>2]|0)+4656>>2]=1;c[(c[d>>2]|0)+4680>>2]=0;c[(c[d>>2]|0)+4692>>2]=32;c[(c[d>>2]|0)+4704>>2]=(c[(c[d>>2]|0)+4600>>2]|0)*983;break}}else{c[(c[d>>2]|0)+4668>>2]=0;c[(c[d>>2]|0)+4676>>2]=52429;c[(c[d>>2]|0)+4672>>2]=6;c[(c[d>>2]|0)+4660>>2]=8;c[(c[d>>2]|0)+4624>>2]=(c[(c[d>>2]|0)+4600>>2]|0)*3;c[(c[d>>2]|0)+4652>>2]=1;c[(c[d>>2]|0)+4656>>2]=0;c[(c[d>>2]|0)+4680>>2]=1;c[(c[d>>2]|0)+4692>>2]=2;c[(c[d>>2]|0)+4704>>2]=0}while(0);a=Ef(c[(c[d>>2]|0)+4672>>2]|0,c[(c[d>>2]|0)+4664>>2]|0)|0;c[(c[d>>2]|0)+4672>>2]=a;c[(c[d>>2]|0)+4628>>2]=((c[(c[d>>2]|0)+4600>>2]|0)*5|0)+(c[(c[d>>2]|0)+4624>>2]<<1);c[(c[d>>2]|0)+4648>>2]=c[e>>2];i=g;return c[f>>2]|0}function Ef(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Ff(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0;j=i;i=i+32|0;f=j+16|0;d=j+12|0;g=j+8|0;h=j+4|0;e=j;c[f>>2]=a;c[d>>2]=b;c[h>>2]=0;c[g>>2]=c[(c[f>>2]|0)+6124>>2];c[(c[f>>2]|0)+6124>>2]=0;if(!(c[(c[f>>2]|0)+6120>>2]|0)){h=c[h>>2]|0;i=j;return h|0}if((c[(c[f>>2]|0)+4640>>2]|0)<=0){h=c[h>>2]|0;i=j;return h|0}do if((c[(c[f>>2]|0)+4600>>2]|0)!=8)if((c[(c[f>>2]|0)+4600>>2]|0)==12){c[e>>2]=14e3;break}else{c[e>>2]=16e3;break}else c[e>>2]=12e3;while(0);if((c[(c[f>>2]|0)+4640>>2]|0)<25)b=c[(c[f>>2]|0)+4640>>2]|0;else b=25;b=((_(c[e>>2]|0,125-b|0)|0)>>16)*655|0;if((c[(c[f>>2]|0)+4640>>2]|0)<25)a=c[(c[f>>2]|0)+4640>>2]|0;else a=25;c[e>>2]=b+(((_(c[e>>2]|0,125-a|0)|0)&65535)*655>>16);if((c[d>>2]|0)<=(c[e>>2]|0)){h=c[h>>2]|0;i=j;return h|0}b=c[f>>2]|0;if(!(c[g>>2]|0))c[b+6128>>2]=7;else{g=Gf(7-(((c[b+4640>>2]>>16)*26214|0)+((c[(c[f>>2]|0)+4640>>2]&65535)*26214>>16))|0,2)|0;c[(c[f>>2]|0)+6128>>2]=g}c[(c[f>>2]|0)+6124>>2]=1;h=c[h>>2]|0;i=j;return h|0}function Gf(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Hf(a,d,e){a=a|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0;D=i;i=i+160|0;f=D+156|0;g=D+152|0;h=D+148|0;p=D+144|0;q=D+140|0;r=D+136|0;m=D+132|0;u=D+128|0;o=D+124|0;x=D+120|0;w=D+116|0;y=D+112|0;A=D+108|0;z=D+104|0;B=D+100|0;v=D+96|0;s=D+92|0;n=D+88|0;j=D+52|0;l=D+16|0;k=D+8|0;t=D;c[f>>2]=a;c[g>>2]=d;c[h>>2]=e;c[k>>2]=j;c[k+4>>2]=l;c[m>>2]=c[h>>2]>>1;If(c[g>>2]|0,j,l,c[m>>2]|0);c[t>>2]=j;c[x>>2]=b[12288];c[A>>2]=Kf(c[t>>2]|0,c[x>>2]|0,c[m>>2]|0)|0;if((c[A>>2]|0)<0){b[c[f>>2]>>1]=0;c[t>>2]=l;c[A>>2]=Kf(c[t>>2]|0,c[x>>2]|0,c[m>>2]|0)|0;c[u>>2]=1}else c[u>>2]=0;c[q>>2]=1;c[p>>2]=0;c[v>>2]=0;a:while(1){c[w>>2]=b[24576+(c[q>>2]<<1)>>1];c[z>>2]=Kf(c[t>>2]|0,c[w>>2]|0,c[m>>2]|0)|0;if(!((c[A>>2]|0)<=0?(c[z>>2]|0)>=(c[v>>2]|0):0))C=7;do if((C|0)==7){C=0;if((c[A>>2]|0)>=0?(c[z>>2]|0)<=(0-(c[v>>2]|0)|0):0)break;c[q>>2]=(c[q>>2]|0)+1;c[x>>2]=c[w>>2];c[A>>2]=c[z>>2];c[v>>2]=0;if((c[q>>2]|0)<=128)continue a;c[p>>2]=(c[p>>2]|0)+1;if((c[p>>2]|0)>30)break a;Of(c[g>>2]|0,c[h>>2]|0,65536-(_((10+(c[p>>2]|0)&65535)<<16>>16,(c[p>>2]&65535)<<16>>16)|0)|0);If(c[g>>2]|0,j,l,c[m>>2]|0);c[t>>2]=j;c[x>>2]=b[12288];c[A>>2]=Kf(c[t>>2]|0,c[x>>2]|0,c[m>>2]|0)|0;if((c[A>>2]|0)<0){b[c[f>>2]>>1]=0;c[t>>2]=l;c[A>>2]=Kf(c[t>>2]|0,c[x>>2]|0,c[m>>2]|0)|0;c[u>>2]=1}else c[u>>2]=0;c[q>>2]=1;continue a}while(0);if(!(c[z>>2]|0))c[v>>2]=1;else c[v>>2]=0;c[o>>2]=-256;c[r>>2]=0;while(1){if((c[r>>2]|0)>=3)break;c[y>>2]=((c[x>>2]|0)+(c[w>>2]|0)>>1)+((c[x>>2]|0)+(c[w>>2]|0)&1);c[B>>2]=Kf(c[t>>2]|0,c[y>>2]|0,c[m>>2]|0)|0;if(!((c[A>>2]|0)<=0&(c[B>>2]|0)>=0)?!((c[A>>2]|0)>=0&(c[B>>2]|0)<=0):0){c[x>>2]=c[y>>2];c[A>>2]=c[B>>2];c[o>>2]=(c[o>>2]|0)+(128>>c[r>>2])}else{c[w>>2]=c[y>>2];c[z>>2]=c[B>>2]}c[r>>2]=(c[r>>2]|0)+1}e=c[A>>2]|0;a=c[A>>2]|0;if((((c[A>>2]|0)>0?e:0-e|0)|0)<65536){c[n>>2]=a-(c[z>>2]|0);c[s>>2]=(c[A>>2]<<5)+(c[n>>2]>>1);if(c[n>>2]|0)c[o>>2]=(c[o>>2]|0)+((c[s>>2]|0)/(c[n>>2]|0)|0)}else c[o>>2]=(c[o>>2]|0)+((a|0)/((c[A>>2]|0)-(c[z>>2]|0)>>5|0)|0);e=(Lf((c[q>>2]<<8)+(c[o>>2]|0)|0,32767)|0)&65535;b[(c[f>>2]|0)+(c[u>>2]<<1)>>1]=e;c[u>>2]=(c[u>>2]|0)+1;if((c[u>>2]|0)>=(c[h>>2]|0)){C=34;break}c[t>>2]=c[k+((c[u>>2]&1)<<2)>>2];c[x>>2]=b[24576+((c[q>>2]|0)-1<<1)>>1];c[A>>2]=1-(c[u>>2]&2)<<12}if((C|0)==34){i=D;return}b[c[f>>2]>>1]=32768/((c[h>>2]|0)+1|0)|0;c[q>>2]=1;while(1){if((c[q>>2]|0)>=(c[h>>2]|0))break;C=(_(((c[q>>2]|0)+1&65535)<<16>>16,b[c[f>>2]>>1]|0)|0)&65535;b[(c[f>>2]|0)+(c[q>>2]<<1)>>1]=C;c[q>>2]=(c[q>>2]|0)+1}i=D;return}function If(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0;l=i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]|0)+(c[g>>2]<<2)>>2]|0);c[g>>2]=(c[g>>2]|0)+-1}a=(c[d>>2]|0)+((c[f>>2]|0)-2<<2)|0;c[a>>2]=(c[a>>2]|0)-(c[(c[d>>2]|0)+(c[f>>2]<<2)>>2]<<1);c[f>>2]=(c[f>>2]|0)+1}i=h;return}function Kf(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0;k=i;i=i+32|0;e=k+20|0;l=k+16|0;f=k+12|0;g=k+8|0;h=k+4|0;j=k;c[e>>2]=a;c[l>>2]=b;c[f>>2]=d;c[j>>2]=c[(c[e>>2]|0)+(c[f>>2]<<2)>>2];c[h>>2]=c[l>>2]<<4;if(8==(c[f>>2]|0)^1^1){l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[(c[e>>2]|0)+28>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[(c[e>>2]|0)+24>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[(c[e>>2]|0)+20>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[(c[e>>2]|0)+16>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[(c[e>>2]|0)+12>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[(c[e>>2]|0)+8>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[(c[e>>2]|0)+4>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[c[e>>2]>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);l=c[j>>2]|0;i=k;return l|0}c[g>>2]=(c[f>>2]|0)-1;while(1){if((c[g>>2]|0)<0)break;l=_(c[j>>2]>>16,(c[h>>2]&65535)<<16>>16)|0;l=(c[(c[e>>2]|0)+(c[g>>2]<<2)>>2]|0)+(l+((_(c[j>>2]&65535,(c[h>>2]&65535)<<16>>16)|0)>>16))|0;c[j>>2]=l+(_(c[j>>2]|0,(c[h>>2]>>15)+1>>1)|0);c[g>>2]=(c[g>>2]|0)+-1}l=c[j>>2]|0;i=k;return l|0}function Lf(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function Mf(a,d,e,f,g){a=a|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;t=i;i=i+48|0;h=t+44|0;j=t+40|0;k=t+36|0;l=t+32|0;u=t+28|0;q=t+24|0;m=t+20|0;p=t+16|0;n=t+12|0;o=t+8|0;r=t+4|0;s=t;c[h>>2]=a;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;c[u>>2]=g;c[m>>2]=c[u>>2]>>1;c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[m>>2]|0))break;c[p>>2]=b[(c[h>>2]|0)+(c[q>>2]<<1<<1)>>1]<<10;c[o>>2]=(c[p>>2]|0)-(c[c[j>>2]>>2]|0);u=_(c[o>>2]>>16,b[12286]|0)|0;c[n>>2]=(c[o>>2]|0)+(u+((_(c[o>>2]&65535,b[12286]|0)|0)>>16));c[r>>2]=(c[c[j>>2]>>2]|0)+(c[n>>2]|0);c[c[j>>2]>>2]=(c[p>>2]|0)+(c[n>>2]|0);c[p>>2]=b[(c[h>>2]|0)+((c[q>>2]<<1)+1<<1)>>1]<<10;c[o>>2]=(c[p>>2]|0)-(c[(c[j>>2]|0)+4>>2]|0);u=_(c[o>>2]>>16,b[12287]|0)|0;c[n>>2]=u+((_(c[o>>2]&65535,b[12287]|0)|0)>>16);c[s>>2]=(c[(c[j>>2]|0)+4>>2]|0)+(c[n>>2]|0);c[(c[j>>2]|0)+4>>2]=(c[p>>2]|0)+(c[n>>2]|0);if((((c[s>>2]|0)+(c[r>>2]|0)>>10)+1>>1|0)<=32767)if((((c[s>>2]|0)+(c[r>>2]|0)>>10)+1>>1|0)<-32768)g=-32768;else g=((c[s>>2]|0)+(c[r>>2]|0)>>10)+1>>1;else g=32767;b[(c[k>>2]|0)+(c[q>>2]<<1)>>1]=g;if((((c[s>>2]|0)-(c[r>>2]|0)>>10)+1>>1|0)<=32767)if((((c[s>>2]|0)-(c[r>>2]|0)>>10)+1>>1|0)<-32768)g=-32768;else g=((c[s>>2]|0)-(c[r>>2]|0)>>10)+1>>1;else g=32767;b[(c[l>>2]|0)+(c[q>>2]<<1)>>1]=g;c[q>>2]=(c[q>>2]|0)+1}i=t;return}function Nf(a,d,e,f,g,h,j){a=a|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0;x=i;i=i+64|0;k=x+52|0;l=x+48|0;y=x+44|0;m=x+40|0;n=x+36|0;o=x+32|0;p=x+28|0;v=x+24|0;u=x+20|0;r=x+16|0;q=x+12|0;t=x+8|0;s=x+4|0;w=x;c[k>>2]=a;c[l>>2]=d;c[y>>2]=e;c[m>>2]=f;c[n>>2]=g;c[o>>2]=h;c[p>>2]=j;c[q>>2]=0-(c[c[y>>2]>>2]|0)&16383;c[r>>2]=0-(c[c[y>>2]>>2]|0)>>14;c[s>>2]=0-(c[(c[y>>2]|0)+4>>2]|0)&16383;c[t>>2]=0-(c[(c[y>>2]|0)+4>>2]|0)>>14;c[v>>2]=0;while(1){if((c[v>>2]|0)>=(c[o>>2]|0))break;y=_(c[v>>2]|0,c[p>>2]|0)|0;c[u>>2]=b[(c[k>>2]|0)+(y<<1)>>1];y=_(c[c[l>>2]>>2]>>16,(c[u>>2]&65535)<<16>>16)|0;c[w>>2]=(c[c[m>>2]>>2]|0)+(y+((_(c[c[l>>2]>>2]&65535,(c[u>>2]&65535)<<16>>16)|0)>>16))<<2;y=_(c[w>>2]>>16,(c[q>>2]&65535)<<16>>16)|0;y=(c[(c[m>>2]|0)+4>>2]|0)+((y+((_(c[w>>2]&65535,(c[q>>2]&65535)<<16>>16)|0)>>16)>>13)+1>>1)|0;c[c[m>>2]>>2]=y;y=_(c[w>>2]>>16,(c[r>>2]&65535)<<16>>16)|0;y=(c[c[m>>2]>>2]|0)+(y+((_(c[w>>2]&65535,(c[r>>2]&65535)<<16>>16)|0)>>16))|0;c[c[m>>2]>>2]=y;y=_(c[(c[l>>2]|0)+4>>2]>>16,(c[u>>2]&65535)<<16>>16)|0;y=(c[c[m>>2]>>2]|0)+(y+((_(c[(c[l>>2]|0)+4>>2]&65535,(c[u>>2]&65535)<<16>>16)|0)>>16))|0;c[c[m>>2]>>2]=y;y=_(c[w>>2]>>16,(c[s>>2]&65535)<<16>>16)|0;y=(y+((_(c[w>>2]&65535,(c[s>>2]&65535)<<16>>16)|0)>>16)>>13)+1>>1;c[(c[m>>2]|0)+4>>2]=y;y=_(c[w>>2]>>16,(c[t>>2]&65535)<<16>>16)|0;y=(c[(c[m>>2]|0)+4>>2]|0)+(y+((_(c[w>>2]&65535,(c[t>>2]&65535)<<16>>16)|0)>>16))|0;c[(c[m>>2]|0)+4>>2]=y;y=_(c[(c[l>>2]|0)+8>>2]>>16,(c[u>>2]&65535)<<16>>16)|0;y=(c[(c[m>>2]|0)+4>>2]|0)+(y+((_(c[(c[l>>2]|0)+8>>2]&65535,(c[u>>2]&65535)<<16>>16)|0)>>16))|0;c[(c[m>>2]|0)+4>>2]=y;if(((c[w>>2]|0)+16384-1>>14|0)<=32767)if(((c[w>>2]|0)+16384-1>>14|0)<-32768)e=-32768;else e=(c[w>>2]|0)+16384-1>>14;else e=32767;y=_(c[v>>2]|0,c[p>>2]|0)|0;b[(c[n>>2]|0)+(y<<1)>>1]=e;c[v>>2]=(c[v>>2]|0)+1}i=x;return}function Of(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+16|0;f=k+12|0;g=k+8|0;j=k+4|0;h=k;c[e>>2]=a;c[f>>2]=b;c[g>>2]=d;c[h>>2]=(c[g>>2]|0)-65536;c[j>>2]=0;while(1){a=c[g>>2]>>16;if((c[j>>2]|0)>=((c[f>>2]|0)-1|0))break;b=_(a,(c[(c[e>>2]|0)+(c[j>>2]<<2)>>2]&65535)<<16>>16)|0;b=b+((_(c[g>>2]&65535,(c[(c[e>>2]|0)+(c[j>>2]<<2)>>2]&65535)<<16>>16)|0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0;j=u+36|0;l=u+38|0;m=u+32|0;k=u+28|0;n=u+24|0;r=u+20|0;q=u+16|0;t=u+12|0;s=u+8|0;p=u+4|0;o=u;b[j>>1]=d;a[l>>0]=e;c[m>>2]=f;c[k>>2]=g;c[n>>2]=h;g=(c[n>>2]|0)==4;do if((c[k>>2]|0)==8)if(g){c[o>>2]=30286;c[p>>2]=11;break}else{c[o>>2]=30252;c[p>>2]=3;break}else if(g){c[o>>2]=30330;c[p>>2]=34;break}else{c[o>>2]=30258;c[p>>2]=12;break}while(0);c[t>>2]=(c[k>>2]&65535)<<16>>16<<1;c[s>>2]=((c[k>>2]&65535)<<16>>16)*18;c[r>>2]=(c[t>>2]|0)+(b[j>>1]|0);c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[n>>2]|0))break;g=_(c[q>>2]|0,c[p>>2]|0)|0;c[(c[m>>2]|0)+(c[q>>2]<<2)>>2]=(c[r>>2]|0)+(a[(c[o>>2]|0)+(g+(a[l>>0]|0))>>0]|0);g=c[(c[m>>2]|0)+(c[q>>2]<<2)>>2]|0;do if((c[t>>2]|0)>(c[s>>2]|0)){if((g|0)>(c[t>>2]|0)){g=c[t>>2]|0;break}if((c[(c[m>>2]|0)+(c[q>>2]<<2)>>2]|0)<(c[s>>2]|0)){g=c[s>>2]|0;break}else{g=c[(c[m>>2]|0)+(c[q>>2]<<2)>>2]|0;break}}else{if((g|0)>(c[s>>2]|0)){g=c[s>>2]|0;break}if((c[(c[m>>2]|0)+(c[q>>2]<<2)>>2]|0)<(c[t>>2]|0)){g=c[t>>2]|0;break}else{g=c[(c[m>>2]|0)+(c[q>>2]<<2)>>2]|0;break}}while(0);c[(c[m>>2]|0)+(c[q>>2]<<2)>>2]=g;c[q>>2]=(c[q>>2]|0)+1}i=u;return}function Rf(a,d,e,f){a=a|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0;n=i;i=i+32|0;g=n+20|0;h=n+16|0;j=n+12|0;k=n+8|0;l=n+4|0;m=n;c[g>>2]=a;c[h>>2]=d;c[j>>2]=e;c[k>>2]=f;c[m>>2]=0;c[l>>2]=0;while(1){a=c[m>>2]|0;if((c[l>>2]|0)>=(c[k>>2]|0))break;e=_(b[(c[g>>2]|0)+(c[l>>2]<<1)>>1]|0,b[(c[h>>2]|0)+(c[l>>2]<<1)>>1]|0)|0;c[m>>2]=a+(e>>c[j>>2]);c[l>>2]=(c[l>>2]|0)+1}i=n;return a|0}function Sf(a){a=a|0;var b=0,d=0,e=0,f=0;b=i;i=i+16|0;f=b+8|0;e=b+4|0;d=b;c[f>>2]=a;Tf(c[f>>2]|0,e,d);a=((_(c[d>>2]|0,128-(c[d>>2]|0)|0)|0)>>16)*179|0;a=(31-(c[e>>2]|0)<<7)+((c[d>>2]|0)+(a+(((_(c[d>>2]|0,128-(c[d>>2]|0)|0)|0)&65535)*179>>16)))|0;i=b;return a|0}function Tf(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;e=i;i=i+16|0;h=e+12|0;j=e+8|0;f=e+4|0;g=e;c[h>>2]=a;c[j>>2]=b;c[f>>2]=d;c[g>>2]=Uf(c[h>>2]|0)|0;c[c[j>>2]>>2]=c[g>>2];b=(Vf(c[h>>2]|0,24-(c[g>>2]|0)|0)|0)&127;c[c[f>>2]>>2]=b;i=e;return}function Uf(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function Vf(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+20|0;d=k+16|0;f=k+12|0;j=k+8|0;h=k+4|0;g=k;c[d>>2]=a;c[f>>2]=b;c[j>>2]=c[d>>2];c[h>>2]=c[f>>2];c[g>>2]=0-(c[f>>2]|0);if(!(c[f>>2]|0)){c[e>>2]=c[d>>2];j=c[e>>2]|0;i=k;return j|0}d=c[j>>2]|0;if((c[f>>2]|0)<0){c[e>>2]=d<>2]|(c[j>>2]|0)>>>(32-(c[g>>2]|0)|0);j=c[e>>2]|0;i=k;return j|0}else{c[e>>2]=d<<32-(c[h>>2]|0)|(c[j>>2]|0)>>>(c[h>>2]|0);j=c[e>>2]|0;i=k;return j|0}return 0}function Wf(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+16|0;d=h+12|0;e=h+8|0;g=h+4|0;f=h;c[e>>2]=a;if((c[e>>2]|0)<0){c[d>>2]=0;g=c[d>>2]|0;i=h;return g|0}if((c[e>>2]|0)>=3967){c[d>>2]=2147483647;g=c[d>>2]|0;i=h;return g|0}c[g>>2]=1<<(c[e>>2]>>7);c[f>>2]=c[e>>2]&127;a=c[g>>2]|0;b=c[g>>2]|0;if((c[e>>2]|0)<2048){e=_((_((c[f>>2]&65535)<<16>>16,(128-(c[f>>2]|0)&65535)<<16>>16)|0)>>16,-174)|0;c[g>>2]=a+((_(b,(c[f>>2]|0)+(e+((_((_((c[f>>2]&65535)<<16>>16,(128-(c[f>>2]|0)&65535)<<16>>16)|0)&65535,-174)|0)>>16))|0)|0)>>7)}else{e=_((_((c[f>>2]&65535)<<16>>16,(128-(c[f>>2]|0)&65535)<<16>>16)|0)>>16,-174)|0;c[g>>2]=a+(_(b>>7,(c[f>>2]|0)+(e+((_((_((c[f>>2]&65535)<<16>>16,(128-(c[f>>2]|0)&65535)<<16>>16)|0)&65535,-174)|0)>>16))|0)|0)}c[d>>2]=c[g>>2];g=c[d>>2]|0;i=h;return g|0}function Xf(a,d,e,f,g,h){a=a|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;t=i;i=i+48|0;j=t+40|0;k=t+36|0;l=t+32|0;m=t+28|0;n=t+24|0;q=t+16|0;p=t+12|0;s=t+8|0;r=t+4|0;o=t;c[j>>2]=a;c[k>>2]=d;c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|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+160|0;e=m+148|0;f=m+144|0;g=m+140|0;l=m+136|0;j=m+8|0;h=m+4|0;k=m;c[f>>2]=a;c[g>>2]=d;c[k>>2]=0;c[h>>2]=j+((c[g>>2]&1)<<6);c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[g>>2]|0))break;c[k>>2]=(c[k>>2]|0)+(b[(c[f>>2]|0)+(c[l>>2]<<1)>>1]|0);c[(c[h>>2]|0)+(c[l>>2]<<2)>>2]=b[(c[f>>2]|0)+(c[l>>2]<<1)>>1]<<12;c[l>>2]=(c[l>>2]|0)+1}if((c[k>>2]|0)>=4096){c[e>>2]=0;d=c[e>>2]|0;i=m;return d|0}else{c[e>>2]=Zf(j,c[g>>2]|0)|0;d=c[e>>2]|0;i=m;return d|0}return 0}function Zf(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;r=i;i=i+64|0;d=r+48|0;e=r+44|0;s=r+40|0;j=r+36|0;l=r+32|0;k=r+28|0;h=r+24|0;m=r+20|0;n=r+16|0;o=r+12|0;p=r+8|0;g=r+4|0;f=r;c[e>>2]=a;c[s>>2]=b;c[f>>2]=(c[e>>2]|0)+((c[s>>2]&1)<<6);c[h>>2]=1073741824;c[j>>2]=(c[s>>2]|0)-1;while(1){if((c[j>>2]|0)<=0)break;if((c[(c[f>>2]|0)+(c[j>>2]<<2)>>2]|0)>16773022){q=5;break}if((c[(c[f>>2]|0)+(c[j>>2]<<2)>>2]|0)<-16773022){q=5;break}c[m>>2]=0-(c[(c[f>>2]|0)+(c[j>>2]<<2)>>2]<<7);s=c[m>>2]|0;b=c[m>>2]|0;b=yj(s|0,((s|0)<0)<<31>>31|0,b|0,((b|0)<0)<<31>>31|0)|0;b=nj(b|0,C|0,32)|0;c[n>>2]=1073741824-b;b=c[n>>2]|0;c[k>>2]=32-(_f((c[n>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>>31|0)|0;s=nj(s|0,C|0,32)|0;c[n>>2]=1073741824-s;s=c[h>>2]|0;t=c[n>>2]|0;t=yj(s|0,((s|0)<0)<<31>>31|0,t|0,((t|0)<0)<<31>>31|0)|0;t=nj(t|0,C|0,32)|0;c[h>>2]=t<<2;c[d>>2]=c[h>>2];t=c[d>>2]|0;i=r;return t|0}c[d>>2]=0;t=c[d>>2]|0;i=r;return t|0}function _f(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function $f(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0;h=i;i=i+48|0;f=h+32|0;n=h+28|0;d=h+24|0;j=h+20|0;g=h+16|0;k=h+12|0;m=h+8|0;l=h+4|0;e=h;c[n>>2]=a;c[d>>2]=b;b=c[n>>2]|0;c[j>>2]=(_f((c[n>>2]|0)>0?b:0-b|0)|0)-1;c[m>>2]=c[n>>2]<>2];c[k>>2]=536870911/(c[m>>2]>>16|0)|0;c[e>>2]=c[k>>2]<<16;b=_(c[m>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;c[l>>2]=536870912-(b+((_(c[m>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))<<3;b=_(c[l>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;b=(c[e>>2]|0)+(b+((_(c[l>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))|0;c[e>>2]=b+(_(c[l>>2]|0,(c[k>>2]>>15)+1>>1)|0);c[g>>2]=61-(c[j>>2]|0)-(c[d>>2]|0);b=c[g>>2]|0;if((c[g>>2]|0)>0)if((b|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];n=c[f>>2]|0;i=h;return n|0}else{c[f>>2]=0;n=c[f>>2]|0;i=h;return n|0}a=c[e>>2]|0;d=0-(c[g>>2]|0)|0;do if((-2147483648>>0-b|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>d|0)){b=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){b=2147483647>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>d|0)){b=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){b=-2147483648>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}while(0);c[f>>2]=b<<0-(c[g>>2]|0);n=c[f>>2]|0;i=h;return n|0}function ag(a,e,f){a=a|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0;C=i;i=i+272|0;x=C+264|0;g=C+260|0;y=C+256|0;v=C+252|0;B=C+248|0;A=C+244|0;p=C+240|0;n=C+176|0;h=C+140|0;k=C+104|0;j=C+100|0;l=C+96|0;s=C+92|0;r=C+88|0;o=C+84|0;q=C+80|0;z=C+16|0;u=C+12|0;m=C+8|0;t=C+4|0;w=C;c[x>>2]=a;c[g>>2]=e;c[y>>2]=f;c[t>>2]=0;c[v>>2]=(c[y>>2]|0)==16?30226:30242;c[B>>2]=0;while(1){if((c[B>>2]|0)>=(c[y>>2]|0))break;c[s>>2]=b[(c[g>>2]|0)+(c[B>>2]<<1)>>1]>>8;c[r>>2]=(b[(c[g>>2]|0)+(c[B>>2]<<1)>>1]|0)-(c[s>>2]<<8);c[o>>2]=b[24576+(c[s>>2]<<1)>>1];c[q>>2]=(b[24576+((c[s>>2]|0)+1<<1)>>1]|0)-(c[o>>2]|0);f=((c[o>>2]<<8)+(_(c[q>>2]|0,c[r>>2]|0)|0)>>3)+1>>1;c[n+(d[(c[v>>2]|0)+(c[B>>2]|0)>>0]<<2)>>2]=f;c[B>>2]=(c[B>>2]|0)+1}c[p>>2]=c[y>>2]>>1;bg(h,n,c[p>>2]|0);bg(k,n+4|0,c[p>>2]|0);c[B>>2]=0;while(1){if((c[B>>2]|0)>=(c[p>>2]|0))break;c[j>>2]=(c[h+((c[B>>2]|0)+1<<2)>>2]|0)+(c[h+(c[B>>2]<<2)>>2]|0);c[l>>2]=(c[k+((c[B>>2]|0)+1<<2)>>2]|0)-(c[k+(c[B>>2]<<2)>>2]|0);c[z+(c[B>>2]<<2)>>2]=0-(c[l>>2]|0)-(c[j>>2]|0);c[z+((c[y>>2]|0)-(c[B>>2]|0)-1<<2)>>2]=(c[l>>2]|0)-(c[j>>2]|0);c[B>>2]=(c[B>>2]|0)+1}c[A>>2]=0;while(1){if((c[A>>2]|0)>=10)break;c[u>>2]=0;c[B>>2]=0;while(1){if((c[B>>2]|0)>=(c[y>>2]|0))break;v=c[z+(c[B>>2]<<2)>>2]|0;c[m>>2]=(c[z+(c[B>>2]<<2)>>2]|0)>0?v:0-v|0;if((c[m>>2]|0)>(c[u>>2]|0)){c[u>>2]=c[m>>2];c[t>>2]=c[B>>2]}c[B>>2]=(c[B>>2]|0)+1}c[u>>2]=(c[u>>2]>>4)+1>>1;if((c[u>>2]|0)<=32767)break;c[u>>2]=(c[u>>2]|0)<163838?c[u>>2]|0:163838;c[w>>2]=65470-(((c[u>>2]|0)-32767<<14|0)/((_(c[u>>2]|0,(c[t>>2]|0)+1|0)|0)>>2|0)|0);Of(z,c[y>>2]|0,c[w>>2]|0);c[A>>2]=(c[A>>2]|0)+1}w=(c[A>>2]|0)==10;c[B>>2]=0;a:do if(w)while(1){if((c[B>>2]|0)>=(c[y>>2]|0))break a;if(((c[z+(c[B>>2]<<2)>>2]>>4)+1>>1|0)<=32767)if(((c[z+(c[B>>2]<<2)>>2]>>4)+1>>1|0)<-32768)g=-32768;else g=(c[z+(c[B>>2]<<2)>>2]>>4)+1>>1;else g=32767;b[(c[x>>2]|0)+(c[B>>2]<<1)>>1]=g;c[z+(c[B>>2]<<2)>>2]=b[(c[x>>2]|0)+(c[B>>2]<<1)>>1]<<5;c[B>>2]=(c[B>>2]|0)+1}else while(1){if((c[B>>2]|0)>=(c[y>>2]|0))break a;b[(c[x>>2]|0)+(c[B>>2]<<1)>>1]=(c[z+(c[B>>2]<<2)>>2]>>4)+1>>1;c[B>>2]=(c[B>>2]|0)+1}while(0);c[A>>2]=0;while(1){if((c[A>>2]|0)>=16){g=31;break}if((Yf(c[x>>2]|0,c[y>>2]|0)|0)>=107374){g=31;break}Of(z,c[y>>2]|0,65536-(2<>2])|0);c[B>>2]=0;while(1){if((c[B>>2]|0)>=(c[y>>2]|0))break;b[(c[x>>2]|0)+(c[B>>2]<<1)>>1]=(c[z+(c[B>>2]<<2)>>2]>>4)+1>>1;c[B>>2]=(c[B>>2]|0)+1}c[A>>2]=(c[A>>2]|0)+1}if((g|0)==31){i=C;return}}function bg(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;e=l+20|0;f=l+16|0;g=l+12|0;j=l+8|0;k=l+4|0;h=l;c[e>>2]=a;c[f>>2]=b;c[g>>2]=d;c[c[e>>2]>>2]=65536;c[(c[e>>2]|0)+4>>2]=0-(c[c[f>>2]>>2]|0);c[j>>2]=1;while(1){if((c[j>>2]|0)>=(c[g>>2]|0))break;c[h>>2]=c[(c[f>>2]|0)+(c[j>>2]<<1<<2)>>2];d=c[(c[e>>2]|0)+((c[j>>2]|0)-1<<2)>>2]<<1;b=c[h>>2]|0;a=c[(c[e>>2]|0)+(c[j>>2]<<2)>>2]|0;a=yj(b|0,((b|0)<0)<<31>>31|0,a|0,((a|0)<0)<<31>>31|0)|0;a=nj(a|0,C|0,15)|0;a=mj(a|0,C|0,1,0)|0;a=nj(a|0,C|0,1)|0;c[(c[e>>2]|0)+((c[j>>2]|0)+1<<2)>>2]=d-a;c[k>>2]=c[j>>2];while(1){if((c[k>>2]|0)<=1)break;b=c[(c[e>>2]|0)+((c[k>>2]|0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16348>>16));c[q>>2]=(c[q>>2]|0)+1}c[h>>2]=0;c[j>>2]=0;c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[(c[l>>2]|0)+2324>>2]|0))break;if((c[(c[g>>2]|0)+16+(c[q>>2]<<2)>>2]|0)>(c[h>>2]|0)){c[h>>2]=c[(c[g>>2]|0)+16+(c[q>>2]<<2)>>2];c[j>>2]=c[q>>2]}c[q>>2]=(c[q>>2]|0)+1}qj((c[r>>2]|0)+(c[(c[l>>2]|0)+2332>>2]<<2)|0,c[r>>2]|0,(_((c[(c[l>>2]|0)+2324>>2]|0)-1|0,c[(c[l>>2]|0)+2332>>2]|0)|0)<<2|0)|0;j=_(c[j>>2]|0,c[(c[l>>2]|0)+2332>>2]|0)|0;pj(c[r>>2]|0,(c[l>>2]|0)+4+(j<<2)|0,c[(c[l>>2]|0)+2332>>2]<<2|0)|0;c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[(c[l>>2]|0)+2324>>2]|0))break a;j=(c[r>>2]|0)+1376|0;c[j>>2]=(c[j>>2]|0)+((((c[(c[g>>2]|0)+16+(c[q>>2]<<2)>>2]|0)-(c[(c[r>>2]|0)+1376>>2]|0)>>16)*4634|0)+(((c[(c[g>>2]|0)+16+(c[q>>2]<<2)>>2]|0)-(c[(c[r>>2]|0)+1376>>2]|0)&65535)*4634>>16));c[q>>2]=(c[q>>2]|0)+1}}while(0);if(!(c[(c[l>>2]|0)+4160>>2]|0)){oj((c[r>>2]|0)+1312|0,0,c[(c[l>>2]|0)+2340>>2]<<2|0)|0;i=t;return}j=(c[n>>2]|0)+16|0;c[o>>2]=ia()|0;h=i;i=i+((1*(j<<2)|0)+15&-16)|0;j=_(b[(c[l>>2]|0)+4168+56>>1]>>16,(c[(c[l>>2]|0)+4168+72+4>>2]&65535)<<16>>16)|0;j=j+((_(b[(c[l>>2]|0)+4168+56>>1]&65535,(c[(c[l>>2]|0)+4168+72+4>>2]&65535)<<16>>16)|0)>>16)|0;c[k>>2]=j+(_(b[(c[l>>2]|0)+4168+56>>1]|0,(c[(c[l>>2]|0)+4168+72+4>>2]>>15)+1>>1)|0);if((c[k>>2]|0)<2097152?(c[(c[r>>2]|0)+1376>>2]|0)<=8388608:0){j=_(c[k>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;j=j+((_(c[k>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16)|0;c[k>>2]=j+(_(c[k>>2]|0,(c[k>>2]>>15)+1>>1)|0);j=_(c[(c[r>>2]|0)+1376>>2]>>16,(c[(c[r>>2]|0)+1376>>2]&65535)<<16>>16)|0;j=j+((_(c[(c[r>>2]|0)+1376>>2]&65535,(c[(c[r>>2]|0)+1376>>2]&65535)<<16>>16)|0)>>16)|0;j=j+(_(c[(c[r>>2]|0)+1376>>2]|0,(c[(c[r>>2]|0)+1376>>2]>>15)+1>>1)|0)|0;c[k>>2]=j-(c[k>>2]<<5);c[k>>2]=(yd(c[k>>2]|0)|0)<<8}else{c[k>>2]=_(c[k>>2]>>16,c[k>>2]>>16)|0;j=_(c[(c[r>>2]|0)+1376>>2]>>16,c[(c[r>>2]|0)+1376>>2]>>16)|0;c[k>>2]=j-(c[k>>2]<<5);c[k>>2]=(yd(c[k>>2]|0)|0)<<16}Cd(h+64|0,c[r>>2]|0,c[k>>2]|0,c[n>>2]|0,(c[r>>2]|0)+1380|0);ag(p,(c[r>>2]|0)+1280|0,c[(c[l>>2]|0)+2340>>2]|0);g=h;e=(c[r>>2]|0)+1312|0;f=g+64|0;do{c[g>>2]=c[e>>2];g=g+4|0;e=e+4|0}while((g|0)<(f|0));c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[n>>2]|0))break;c[s>>2]=c[(c[l>>2]|0)+2340>>2]>>1;k=_(c[h+(16+(c[q>>2]|0)-1<<2)>>2]>>16,b[p>>1]|0)|0;c[s>>2]=(c[s>>2]|0)+(k+((_(c[h+(16+(c[q>>2]|0)-1<<2)>>2]&65535,b[p>>1]|0)|0)>>16));k=_(c[h+(16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+(c[q>>2]|0)-10<<2)>>2]>>16,b[p+18>>1]|0)|0;c[s>>2]=(c[s>>2]|0)+(k+((_(c[h+(16+(c[q>>2]|0)-10<<2)>>2]&65535,b[p+18>>1]|0)|0)>>16));if((c[(c[l>>2]|0)+2340>>2]|0)==16){k=_(c[h+(16+(c[q>>2]|0)-11<<2)>>2]>>16,b[p+20>>1]|0)|0;c[s>>2]=(c[s>>2]|0)+(k+((_(c[h+(16+(c[q>>2]|0)-11<<2)>>2]&65535,b[p+20>>1]|0)|0)>>16));k=_(c[h+(16+(c[q>>2]|0)-12<<2)>>2]>>16,b[p+22>>1]|0)|0;c[s>>2]=(c[s>>2]|0)+(k+((_(c[h+(16+(c[q>>2]|0)-12<<2)>>2]&65535,b[p+22>>1]|0)|0)>>16));k=_(c[h+(16+(c[q>>2]|0)-13<<2)>>2]>>16,b[p+24>>1]|0)|0;c[s>>2]=(c[s>>2]|0)+(k+((_(c[h+(16+(c[q>>2]|0)-13<<2)>>2]&65535,b[p+24>>1]|0)|0)>>16));k=_(c[h+(16+(c[q>>2]|0)-14<<2)>>2]>>16,b[p+26>>1]|0)|0;c[s>>2]=(c[s>>2]|0)+(k+((_(c[h+(16+(c[q>>2]|0)-14<<2)>>2]&65535,b[p+26>>1]|0)|0)>>16));k=_(c[h+(16+(c[q>>2]|0)-15<<2)>>2]>>16,b[p+28>>1]|0)|0;c[s>>2]=(c[s>>2]|0)+(k+((_(c[h+(16+(c[q>>2]|0)-15<<2)>>2]&65535,b[p+28>>1]|0)|0)>>16));k=_(c[h+(16+(c[q>>2]|0)-16<<2)>>2]>>16,b[p+30>>1]|0)|0;c[s>>2]=(c[s>>2]|0)+(k+((_(c[h+(16+(c[q>>2]|0)-16<<2)>>2]&65535,b[p+30>>1]|0)|0)>>16))}c[h+(16+(c[q>>2]|0)<<2)>>2]=(c[h+(16+(c[q>>2]|0)<<2)>>2]|0)+(c[s>>2]<<4);if(((b[(c[m>>2]|0)+(c[q>>2]<<1)>>1]|0)+((c[h+(16+(c[q>>2]|0)<<2)>>2]>>9)+1>>1)|0)<=32767)if(((b[(c[m>>2]|0)+(c[q>>2]<<1)>>1]|0)+((c[h+(16+(c[q>>2]|0)<<2)>>2]>>9)+1>>1)|0)<-32768)g=-32768;else g=(b[(c[m>>2]|0)+(c[q>>2]<<1)>>1]|0)+((c[h+(16+(c[q>>2]|0)<<2)>>2]>>9)+1>>1)|0;else g=32767;b[(c[m>>2]|0)+(c[q>>2]<<1)>>1]=g;c[q>>2]=(c[q>>2]|0)+1}g=(c[r>>2]|0)+1312|0;e=h+(c[n>>2]<<2)|0;f=g+64|0;do{c[g>>2]=c[e>>2];g=g+4|0;e=e+4|0}while((g|0)<(f|0));na(c[o>>2]|0);i=t;return}function yd(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+32|0;b=h+16|0;d=h+12|0;g=h+8|0;f=h+4|0;e=h;c[d>>2]=a;if((c[d>>2]|0)<=0){c[b>>2]=0;g=c[b>>2]|0;i=h;return g|0}zd(c[d>>2]|0,f,e);if(c[f>>2]&1|0)c[g>>2]=32768;else c[g>>2]=46214;c[g>>2]=c[g>>2]>>(c[f>>2]>>1);a=_(c[g>>2]>>16,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0;c[g>>2]=(c[g>>2]|0)+(a+((_(c[g>>2]&65535,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0)>>16));c[b>>2]=c[g>>2];g=c[b>>2]|0;i=h;return g|0}function zd(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;e=i;i=i+16|0;h=e+12|0;j=e+8|0;f=e+4|0;g=e;c[h>>2]=a;c[j>>2]=b;c[f>>2]=d;c[g>>2]=Ad(c[h>>2]|0)|0;c[c[j>>2]>>2]=c[g>>2];b=(Bd(c[h>>2]|0,24-(c[g>>2]|0)|0)|0)&127;c[c[f>>2]>>2]=b;i=e;return}function Ad(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function Bd(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+20|0;d=k+16|0;f=k+12|0;j=k+8|0;h=k+4|0;g=k;c[d>>2]=a;c[f>>2]=b;c[j>>2]=c[d>>2];c[h>>2]=c[f>>2];c[g>>2]=0-(c[f>>2]|0);if(!(c[f>>2]|0)){c[e>>2]=c[d>>2];j=c[e>>2]|0;i=k;return j|0}d=c[j>>2]|0;if((c[f>>2]|0)<0){c[e>>2]=d<>2]|(c[j>>2]|0)>>>(32-(c[g>>2]|0)|0);j=c[e>>2]|0;i=k;return j|0}else{c[e>>2]=d<<32-(c[h>>2]|0)|(c[j>>2]|0)>>>(c[h>>2]|0);j=c[e>>2]|0;i=k;return j|0}return 0}function Cd(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;q=i;i=i+48|0;g=q+32|0;h=q+28|0;j=q+24|0;k=q+20|0;l=q+16|0;p=q+12|0;n=q+8|0;o=q+4|0;m=q;c[g>>2]=a;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;c[m>>2]=255;while(1){if((c[m>>2]|0)<=(c[k>>2]|0))break;c[m>>2]=c[m>>2]>>1}c[p>>2]=c[c[l>>2]>>2];c[n>>2]=0;while(1){d=c[p>>2]|0;if((c[n>>2]|0)>=(c[k>>2]|0))break;c[p>>2]=907633515+(_(d,196314165)|0);c[o>>2]=c[p>>2]>>24&c[m>>2];f=_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]>>16,(c[j>>2]>>4&65535)<<16>>16)|0;f=f+((_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]&65535,(c[j>>2]>>4&65535)<<16>>16)|0)>>16)|0;if((f+(_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]|0,(c[j>>2]>>4>>15)+1>>1)|0)|0)<=32767){f=_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]>>16,(c[j>>2]>>4&65535)<<16>>16)|0;f=f+((_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]&65535,(c[j>>2]>>4&65535)<<16>>16)|0)>>16)|0;if((f+(_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]|0,(c[j>>2]>>4>>15)+1>>1)|0)|0)<-32768)d=-32768;else{d=_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]>>16,(c[j>>2]>>4&65535)<<16>>16)|0;d=d+((_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]&65535,(c[j>>2]>>4&65535)<<16>>16)|0)>>16)|0;d=d+(_(c[(c[h>>2]|0)+(c[o>>2]<<2)>>2]|0,(c[j>>2]>>4>>15)+1>>1)|0)|0}}else d=32767;c[(c[g>>2]|0)+(c[n>>2]<<2)>>2]=(d&65535)<<16>>16;c[n>>2]=(c[n>>2]|0)+1}c[c[l>>2]>>2]=d;i=q;return}function Dd(b,d,e,f,g,h){b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;s=i;i=i+48|0;j=s+40|0;v=s+36|0;k=s+32|0;t=s+28|0;u=s+24|0;l=s+20|0;m=s+16|0;p=s+12|0;q=s+8|0;n=s+44|0;r=s+4|0;o=s;c[j>>2]=b;c[v>>2]=d;c[k>>2]=e;c[t>>2]=f;c[u>>2]=g;c[l>>2]=h;a[n+1>>0]=0;c[r>>2]=c[v>>2];c[m>>2]=(((c[u>>2]|0)+(c[t>>2]<<1)&65535)<<16>>16)*7;c[o>>2]=30184+(c[m>>2]|0);c[k>>2]=(c[k>>2]|0)+8>>4;c[m>>2]=0;while(1){if((c[m>>2]|0)>=(c[k>>2]|0))break;c[q>>2]=c[(c[l>>2]|0)+(c[m>>2]<<2)>>2];a:do if((c[q>>2]|0)>0){a[n>>0]=a[(c[o>>2]|0)+((c[q>>2]&31|0)<6?c[q>>2]&31:6)>>0]|0;c[p>>2]=0;while(1){if((c[p>>2]|0)>=16)break a;if(a[(c[r>>2]|0)+(c[p>>2]|0)>>0]|0)qc(c[j>>2]|0,(a[(c[r>>2]|0)+(c[p>>2]|0)>>0]>>15)+1|0,n,8);c[p>>2]=(c[p>>2]|0)+1}}while(0);c[r>>2]=(c[r>>2]|0)+16;c[m>>2]=(c[m>>2]|0)+1}i=s;return}function Ed(d,e,f,g,h,j){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;t=i;i=i+48|0;k=t+40|0;w=t+36|0;l=t+32|0;u=t+28|0;v=t+24|0;m=t+20|0;n=t+16|0;q=t+12|0;r=t+8|0;o=t+44|0;s=t+4|0;p=t;c[k>>2]=d;c[w>>2]=e;c[l>>2]=f;c[u>>2]=g;c[v>>2]=h;c[m>>2]=j;a[o+1>>0]=0;c[s>>2]=c[w>>2];c[n>>2]=(((c[v>>2]|0)+(c[u>>2]<<1)&65535)<<16>>16)*7;c[p>>2]=30184+(c[n>>2]|0);c[l>>2]=(c[l>>2]|0)+8>>4;c[n>>2]=0;while(1){if((c[n>>2]|0)>=(c[l>>2]|0))break;c[r>>2]=c[(c[m>>2]|0)+(c[n>>2]<<2)>>2];a:do if((c[r>>2]|0)>0){a[o>>0]=a[(c[p>>2]|0)+((c[r>>2]&31|0)<6?c[r>>2]&31:6)>>0]|0;c[q>>2]=0;while(1){if((c[q>>2]|0)>=16)break a;if((b[(c[s>>2]|0)+(c[q>>2]<<1)>>1]|0)>0){v=((ec(c[k>>2]|0,o,8)|0)<<1)-1|0;w=(c[s>>2]|0)+(c[q>>2]<<1)|0;b[w>>1]=_(b[w>>1]|0,v)|0}c[q>>2]=(c[q>>2]|0)+1}}while(0);c[s>>2]=(c[s>>2]|0)+32;c[n>>2]=(c[n>>2]|0)+1}i=t;return}function Fd(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;oj(c[d>>2]|0,0,4260)|0;c[(c[d>>2]|0)+2376>>2]=1;c[c[d>>2]>>2]=65536;wd(c[d>>2]|0);ze(c[d>>2]|0);i=b;return 0}function Gd(d,e,f,g,h){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0;M=i;i=i+144|0;o=M+100|0;p=M+96|0;q=M+92|0;l=M+88|0;r=M+84|0;B=M+80|0;D=M+76|0;E=M+72|0;L=M+68|0;J=M+64|0;z=M+60|0;K=M+56|0;t=M+52|0;v=M+48|0;I=M+44|0;u=M+104|0;y=M+40|0;x=M+36|0;w=M+32|0;C=M+28|0;A=M+24|0;n=M+20|0;m=M+16|0;G=M+12|0;F=M+8|0;H=M+4|0;s=M;c[o>>2]=d;c[p>>2]=e;c[q>>2]=f;c[l>>2]=g;c[r>>2]=h;c[E>>2]=0;f=c[(c[o>>2]|0)+2336>>2]|0;c[s>>2]=ia()|0;g=i;i=i+((1*(f<<1)|0)+15&-16)|0;f=i;i=i+((1*((c[(c[o>>2]|0)+2336>>2]|0)+(c[(c[o>>2]|0)+2328>>2]|0)<<2)|0)+15&-16)|0;j=i;i=i+((1*(c[(c[o>>2]|0)+2332>>2]<<2)|0)+15&-16)|0;k=i;i=i+((1*((c[(c[o>>2]|0)+2332>>2]|0)+16<<2)|0)+15&-16)|0;c[m>>2]=b[24558+(a[(c[o>>2]|0)+2736+29>>0]>>1<<2)+(a[(c[o>>2]|0)+2736+30>>0]<<1)>>1];if((a[(c[o>>2]|0)+2736+31>>0]|0)<4)c[z>>2]=1;else c[z>>2]=0;c[n>>2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(c[p>>2]|0)+16+(c[D>>2]<<2)>>2]|0)!=(c[c[o>>2]>>2]|0)){c[A>>2]=Jd(c[c[o>>2]>>2]|0,c[(c[p>>2]|0)+16+(c[D>>2]<<2)>>2]|0,16)|0;c[B>>2]=0;while(1){if((c[B>>2]|0)>=16)break a;n=_(c[A>>2]>>16,(c[k+(c[B>>2]<<2)>>2]&65535)<<16>>16)|0;n=n+((_(c[A>>2]&65535,(c[k+(c[B>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;n=n+(_(c[A>>2]|0,(c[k+(c[B>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[k+(c[B>>2]<<2)>>2]=n;c[B>>2]=(c[B>>2]|0)+1}}else c[A>>2]=65536;while(0);c[c[o>>2]>>2]=c[(c[p>>2]|0)+16+(c[D>>2]<<2)>>2];if((c[(c[o>>2]|0)+4160>>2]|0?(c[(c[o>>2]|0)+4164>>2]|0)==2:0)?((c[D>>2]|0)<2?(a[(c[o>>2]|0)+2736+29>>0]|0)!=2:0):0){n=c[v>>2]|0;b[n>>1]=0;b[n+2>>1]=0;b[n+4>>1]=0;b[n+6>>1]=0;b[n+8>>1]=0;b[(c[v>>2]|0)+4>>1]=4096;c[K>>2]=2;c[(c[p>>2]|0)+(c[D>>2]<<2)>>2]=c[(c[o>>2]|0)+2308>>2]}b:do if((c[K>>2]|0)==2){c[E>>2]=c[(c[p>>2]|0)+(c[D>>2]<<2)>>2];if(c[D>>2]|0?!((c[D>>2]|0)==2&(c[z>>2]|0)!=0):0){if((c[A>>2]|0)==65536)break;c[B>>2]=0;while(1){if((c[B>>2]|0)>=((c[E>>2]|0)+2|0))break b;n=_(c[A>>2]>>16,(c[f+((c[J>>2]|0)-(c[B>>2]|0)-1<<2)>>2]&65535)<<16>>16)|0;n=n+((_(c[A>>2]&65535,(c[f+((c[J>>2]|0)-(c[B>>2]|0)-1<<2)>>2]&65535)<<16>>16)|0)>>16)|0;n=n+(_(c[A>>2]|0,(c[f+((c[J>>2]|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k+(16+(c[B>>2]|0)-10<<2)>>2]>>16,b[u+18>>1]|0)|0;c[x>>2]=(c[x>>2]|0)+(n+((_(c[k+(16+(c[B>>2]|0)-10<<2)>>2]&65535,b[u+18>>1]|0)|0)>>16));if((c[(c[o>>2]|0)+2340>>2]|0)==16){n=_(c[k+(16+(c[B>>2]|0)-11<<2)>>2]>>16,b[u+20>>1]|0)|0;c[x>>2]=(c[x>>2]|0)+(n+((_(c[k+(16+(c[B>>2]|0)-11<<2)>>2]&65535,b[u+20>>1]|0)|0)>>16));n=_(c[k+(16+(c[B>>2]|0)-12<<2)>>2]>>16,b[u+22>>1]|0)|0;c[x>>2]=(c[x>>2]|0)+(n+((_(c[k+(16+(c[B>>2]|0)-12<<2)>>2]&65535,b[u+22>>1]|0)|0)>>16));n=_(c[k+(16+(c[B>>2]|0)-13<<2)>>2]>>16,b[u+24>>1]|0)|0;c[x>>2]=(c[x>>2]|0)+(n+((_(c[k+(16+(c[B>>2]|0)-13<<2)>>2]&65535,b[u+24>>1]|0)|0)>>16));n=_(c[k+(16+(c[B>>2]|0)-14<<2)>>2]>>16,b[u+26>>1]|0)|0;c[x>>2]=(c[x>>2]|0)+(n+((_(c[k+(16+(c[B>>2]|0)-14<<2)>>2]&65535,b[u+26>>1]|0)|0)>>16));n=_(c[k+(16+(c[B>>2]|0)-15<<2)>>2]>>16,b[u+28>>1]|0)|0;c[x>>2]=(c[x>>2]|0)+(n+((_(c[k+(16+(c[B>>2]|0)-15<<2)>>2]&65535,b[u+28>>1]|0)|0)>>16));n=_(c[k+(16+(c[B>>2]|0)-16<<2)>>2]>>16,b[u+30>>1]|0)|0;c[x>>2]=(c[x>>2]|0)+(n+((_(c[k+(16+(c[B>>2]|0)-16<<2)>>2]&65535,b[u+30>>1]|0)|0)>>16))}c[k+(16+(c[B>>2]|0)<<2)>>2]=(c[(c[H>>2]|0)+(c[B>>2]<<2)>>2]|0)+(c[x>>2]<<4);n=_(c[k+(16+(c[B>>2]|0)<<2)>>2]>>16,(c[w>>2]&65535)<<16>>16)|0;n=n+((_(c[k+(16+(c[B>>2]|0)<<2)>>2]&65535,(c[w>>2]&65535)<<16>>16)|0)>>16)|0;if(((n+(_(c[k+(16+(c[B>>2]|0)<<2)>>2]|0,(c[w>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<=32767){n=_(c[k+(16+(c[B>>2]|0)<<2)>>2]>>16,(c[w>>2]&65535)<<16>>16)|0;n=n+((_(c[k+(16+(c[B>>2]|0)<<2)>>2]&65535,(c[w>>2]&65535)<<16>>16)|0)>>16)|0;if(((n+(_(c[k+(16+(c[B>>2]|0)<<2)>>2]|0,(c[w>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<-32768)h=-32768;else{h=_(c[k+(16+(c[B>>2]|0)<<2)>>2]>>16,(c[w>>2]&65535)<<16>>16)|0;h=h+((_(c[k+(16+(c[B>>2]|0)<<2)>>2]&65535,(c[w>>2]&65535)<<16>>16)|0)>>16)|0;h=(h+(_(c[k+(16+(c[B>>2]|0)<<2)>>2]|0,(c[w>>2]>>15)+1>>1)|0)>>7)+1>>1}}else h=32767;b[(c[I>>2]|0)+(c[B>>2]<<1)>>1]=h;c[B>>2]=(c[B>>2]|0)+1}h=k;d=k+(c[(c[o>>2]|0)+2332>>2]<<2)|0;e=h+64|0;do{c[h>>2]=c[d>>2];h=h+4|0;d=d+4|0}while((h|0)<(e|0));c[F>>2]=(c[F>>2]|0)+(c[(c[o>>2]|0)+2332>>2]<<2);c[I>>2]=(c[I>>2]|0)+(c[(c[o>>2]|0)+2332>>2]<<1);c[D>>2]=(c[D>>2]|0)+1}h=(c[o>>2]|0)+1284|0;d=k;e=h+64|0;do{c[h>>2]=c[d>>2];h=h+4|0;d=d+4|0}while((h|0)<(e|0));na(c[s>>2]|0);i=M;return}function Hd(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0;h=i;i=i+48|0;f=h+32|0;n=h+28|0;d=h+24|0;j=h+20|0;g=h+16|0;k=h+12|0;m=h+8|0;l=h+4|0;e=h;c[n>>2]=a;c[d>>2]=b;b=c[n>>2]|0;c[j>>2]=(Id((c[n>>2]|0)>0?b:0-b|0)|0)-1;c[m>>2]=c[n>>2]<>2];c[k>>2]=536870911/(c[m>>2]>>16|0)|0;c[e>>2]=c[k>>2]<<16;b=_(c[m>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;c[l>>2]=536870912-(b+((_(c[m>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))<<3;b=_(c[l>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;b=(c[e>>2]|0)+(b+((_(c[l>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))|0;c[e>>2]=b+(_(c[l>>2]|0,(c[k>>2]>>15)+1>>1)|0);c[g>>2]=61-(c[j>>2]|0)-(c[d>>2]|0);b=c[g>>2]|0;if((c[g>>2]|0)>0)if((b|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];n=c[f>>2]|0;i=h;return n|0}else{c[f>>2]=0;n=c[f>>2]|0;i=h;return n|0}a=c[e>>2]|0;d=0-(c[g>>2]|0)|0;do if((-2147483648>>0-b|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>d|0)){b=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){b=2147483647>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>d|0)){b=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){b=-2147483648>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}while(0);c[f>>2]=b<<0-(c[g>>2]|0);n=c[f>>2]|0;i=h;return n|0}function Id(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function Jd(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;h=i;i=i+48|0;f=h+40|0;q=h+36|0;p=h+32|0;j=h+28|0;l=h+24|0;k=h+20|0;g=h+16|0;m=h+12|0;n=h+8|0;o=h+4|0;e=h;c[q>>2]=a;c[p>>2]=b;c[j>>2]=d;b=c[q>>2]|0;c[l>>2]=(Id((c[q>>2]|0)>0?b:0-b|0)|0)-1;c[n>>2]=c[q>>2]<>2];b=c[p>>2]|0;c[k>>2]=(Id((c[p>>2]|0)>0?b:0-b|0)|0)-1;c[o>>2]=c[p>>2]<>2];c[m>>2]=536870911/(c[o>>2]>>16|0)|0;b=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=b+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16);b=c[n>>2]|0;a=c[o>>2]|0;d=c[e>>2]|0;d=yj(a|0,((a|0)<0)<<31>>31|0,d|0,((d|0)<0)<<31>>31|0)|0;d=nj(d|0,C|0,32)|0;c[n>>2]=b-(d<<3);d=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=(c[e>>2]|0)+(d+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16));c[g>>2]=29+(c[l>>2]|0)-(c[k>>2]|0)-(c[j>>2]|0);d=c[g>>2]|0;if((c[g>>2]|0)>=0)if((d|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];q=c[f>>2]|0;i=h;return q|0}else{c[f>>2]=0;q=c[f>>2]|0;i=h;return q|0}a=c[e>>2]|0;b=0-(c[g>>2]|0)|0;do if((-2147483648>>0-d|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>b|0)){d=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){d=2147483647>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>b|0)){d=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){d=-2147483648>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}while(0);c[f>>2]=d<<0-(c[g>>2]|0);q=c[f>>2]|0;i=h;return q|0}function Kd(b,d,e,f,g,h,j){b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0;x=i;i=i+192|0;k=x+180|0;l=x+176|0;m=x+172|0;n=x+168|0;o=x+164|0;p=x+160|0;q=x+156|0;s=x+152|0;t=x+148|0;v=x+144|0;u=x+4|0;r=x;c[k>>2]=b;c[l>>2]=d;c[m>>2]=e;c[n>>2]=f;c[o>>2]=g;c[p>>2]=h;c[q>>2]=j;c[v>>2]=0;c[s>>2]=c[(c[k>>2]|0)+2328>>2];c[u+136>>2]=0;do if(!(c[o>>2]|0))w=4;else{if((c[o>>2]|0)==2?(c[(c[k>>2]|0)+2420+(c[(c[k>>2]|0)+2388>>2]<<2)>>2]|0)==1:0){w=4;break}Ae(c[k>>2]|0,u,c[m>>2]|0,1,c[q>>2]|0)}while(0);if((w|0)==4){d=(c[s>>2]|0)+16-1&-16;c[r>>2]=ia()|0;w=i;i=i+((1*(d<<1)|0)+15&-16)|0;Md(c[k>>2]|0,c[l>>2]|0,c[(c[k>>2]|0)+2388>>2]|0,c[o>>2]|0,c[p>>2]|0);Nd(c[l>>2]|0,w,a[(c[k>>2]|0)+2736+29>>0]|0,a[(c[k>>2]|0)+2736+30>>0]|0,c[(c[k>>2]|0)+2328>>2]|0);Ld(c[k>>2]|0,u,c[p>>2]|0);Gd(c[k>>2]|0,u,c[m>>2]|0,w,c[q>>2]|0);Ae(c[k>>2]|0,u,c[m>>2]|0,0,c[q>>2]|0);c[(c[k>>2]|0)+4160>>2]=0;c[(c[k>>2]|0)+4164>>2]=a[(c[k>>2]|0)+2736+29>>0];c[(c[k>>2]|0)+2376>>2]=0;na(c[r>>2]|0)}c[t>>2]=(c[(c[k>>2]|0)+2336>>2]|0)-(c[(c[k>>2]|0)+2328>>2]|0);qj((c[k>>2]|0)+1348|0,(c[k>>2]|0)+1348+(c[(c[k>>2]|0)+2328>>2]<<1)|0,c[t>>2]<<1|0)|0;pj((c[k>>2]|0)+1348+(c[t>>2]<<1)|0,c[m>>2]|0,c[(c[k>>2]|0)+2328>>2]<<1|0)|0;xd(c[k>>2]|0,u,c[m>>2]|0,c[s>>2]|0);Le(c[k>>2]|0,c[m>>2]|0,c[s>>2]|0);c[(c[k>>2]|0)+2308>>2]=c[u+((c[(c[k>>2]|0)+2324>>2]|0)-1<<2)>>2];c[c[n>>2]>>2]=c[s>>2];i=x;return c[v>>2]|0}function Ld(d,e,f){d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;p=i;i=i+96|0;g=p+24|0;h=p+20|0;q=p+16|0;l=p+12|0;m=p+8|0;j=p+4|0;o=p+64|0;n=p+32|0;k=p;c[g>>2]=d;c[h>>2]=e;c[q>>2]=f;ae((c[h>>2]|0)+16|0,(c[g>>2]|0)+2736|0,(c[g>>2]|0)+2312|0,(c[q>>2]|0)==2&1,c[(c[g>>2]|0)+2324>>2]|0);ge(o,(c[g>>2]|0)+2736+8|0,c[(c[g>>2]|0)+2732>>2]|0);ag((c[h>>2]|0)+32+32|0,o,c[(c[g>>2]|0)+2340>>2]|0);if((c[(c[g>>2]|0)+2376>>2]|0)==1)a[(c[g>>2]|0)+2736+31>>0]=4;if((a[(c[g>>2]|0)+2736+31>>0]|0)<4){c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[(c[g>>2]|0)+2340>>2]|0))break;q=(b[(c[g>>2]|0)+2344+(c[l>>2]<<1)>>1]|0)+((_(a[(c[g>>2]|0)+2736+31>>0]|0,(b[o+(c[l>>2]<<1)>>1]|0)-(b[(c[g>>2]|0)+2344+(c[l>>2]<<1)>>1]|0)|0)|0)>>2)&65535;b[n+(c[l>>2]<<1)>>1]=q;c[l>>2]=(c[l>>2]|0)+1}ag((c[h>>2]|0)+32|0,n,c[(c[g>>2]|0)+2340>>2]|0)}else pj((c[h>>2]|0)+32|0,(c[h>>2]|0)+32+32|0,c[(c[g>>2]|0)+2340>>2]<<1|0)|0;pj((c[g>>2]|0)+2344|0,o|0,c[(c[g>>2]|0)+2340>>2]<<1|0)|0;if(c[(c[g>>2]|0)+4160>>2]|0){Pf((c[h>>2]|0)+32|0,c[(c[g>>2]|0)+2340>>2]|0,63570);Pf((c[h>>2]|0)+32+32|0,c[(c[g>>2]|0)+2340>>2]|0,63570)}if((a[(c[g>>2]|0)+2736+29>>0]|0)!=2){oj(c[h>>2]|0,0,c[(c[g>>2]|0)+2324>>2]<<2|0)|0;oj((c[h>>2]|0)+96|0,0,(c[(c[g>>2]|0)+2324>>2]|0)*5<<1|0)|0;a[(c[g>>2]|0)+2736+32>>0]=0;c[(c[h>>2]|0)+136>>2]=0;i=p;return}Qf(b[(c[g>>2]|0)+2736+26>>1]|0,a[(c[g>>2]|0)+2736+28>>0]|0,c[h>>2]|0,c[(c[g>>2]|0)+2316>>2]|0,c[(c[g>>2]|0)+2324>>2]|0);c[k>>2]=c[17644+(a[(c[g>>2]|0)+2736+32>>0]<<2)>>2];c[m>>2]=0;while(1){if((c[m>>2]|0)>=(c[(c[g>>2]|0)+2324>>2]|0))break;c[j>>2]=a[(c[g>>2]|0)+2736+4+(c[m>>2]|0)>>0];c[l>>2]=0;while(1){if((c[l>>2]|0)>=5)break;b[(c[h>>2]|0)+96+(((c[m>>2]|0)*5|0)+(c[l>>2]|0)<<1)>>1]=a[(c[k>>2]|0)+(((c[j>>2]|0)*5|0)+(c[l>>2]|0))>>0]<<7;c[l>>2]=(c[l>>2]|0)+1}c[m>>2]=(c[m>>2]|0)+1}c[j>>2]=a[(c[g>>2]|0)+2736+33>>0];c[(c[h>>2]|0)+136>>2]=b[24566+(c[j>>2]<<1)>>1];i=p;return}function Md(d,e,f,g,h){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;t=i;i=i+96|0;j=t+36|0;k=t+32|0;u=t+28|0;v=t+24|0;l=t+20|0;q=t+16|0;r=t+12|0;m=t+8|0;n=t+4|0;o=t;p=t+40|0;s=t+72|0;c[j>>2]=d;c[k>>2]=e;c[u>>2]=f;c[v>>2]=g;c[l>>2]=h;if(!(c[v>>2]|0)?!(c[(c[j>>2]|0)+2404+(c[u>>2]<<2)>>2]|0):0)c[m>>2]=ec(c[k>>2]|0,29024,8)|0;else c[m>>2]=(ec(c[k>>2]|0,29020,8)|0)+2;a[(c[j>>2]|0)+2736+29>>0]=c[m>>2]>>1;a[(c[j>>2]|0)+2736+30>>0]=c[m>>2]&1;f=c[k>>2]|0;if((c[l>>2]|0)==2){v=(ec(f,26771,8)|0)&255;a[(c[j>>2]|0)+2736>>0]=v}else{u=(ec(f,26747+(a[(c[j>>2]|0)+2736+29>>0]<<3)|0,8)|0)<<3&255;a[(c[j>>2]|0)+2736>>0]=u;u=((ec(c[k>>2]|0,29049,8)|0)&255)<<24>>24;v=(c[j>>2]|0)+2736|0;a[v>>0]=(a[v>>0]|0)+u}c[q>>2]=1;while(1){f=c[k>>2]|0;if((c[q>>2]|0)>=(c[(c[j>>2]|0)+2324>>2]|0))break;v=(ec(f,26771,8)|0)&255;a[(c[j>>2]|0)+2736+(c[q>>2]|0)>>0]=v;c[q>>2]=(c[q>>2]|0)+1}v=_(a[(c[j>>2]|0)+2736+29>>0]>>1,b[c[(c[j>>2]|0)+2732>>2]>>1]|0)|0;v=(ec(f,(c[(c[(c[j>>2]|0)+2732>>2]|0)+12>>2]|0)+v|0,8)|0)&255;a[(c[j>>2]|0)+2736+8>>0]=v;nf(p,s,c[(c[j>>2]|0)+2732>>2]|0,a[(c[j>>2]|0)+2736+8>>0]|0);c[q>>2]=0;while(1){if((c[q>>2]|0)>=(b[(c[(c[j>>2]|0)+2732>>2]|0)+2>>1]|0))break;c[m>>2]=ec(c[k>>2]|0,(c[(c[(c[j>>2]|0)+2732>>2]|0)+24>>2]|0)+(b[p+(c[q>>2]<<1)>>1]|0)|0,8)|0;if(c[m>>2]|0){if((c[m>>2]|0)==8){v=ec(c[k>>2]|0,29057,8)|0;c[m>>2]=(c[m>>2]|0)+v}}else{v=ec(c[k>>2]|0,29057,8)|0;c[m>>2]=(c[m>>2]|0)-v}a[(c[j>>2]|0)+2736+8+((c[q>>2]|0)+1)>>0]=(c[m>>2]|0)-4;c[q>>2]=(c[q>>2]|0)+1}if((c[(c[j>>2]|0)+2324>>2]|0)==4){v=(ec(c[k>>2]|0,29026,8)|0)&255;a[(c[j>>2]|0)+2736+31>>0]=v}else a[(c[j>>2]|0)+2736+31>>0]=4;if((a[(c[j>>2]|0)+2736+29>>0]|0)!=2){v=c[j>>2]|0;v=v+2736|0;v=v+29|0;v=a[v>>0]|0;v=v<<24>>24;u=c[j>>2]|0;u=u+2396|0;c[u>>2]=v;u=c[k>>2]|0;u=ec(u,29034,8)|0;u=u&255;v=c[j>>2]|0;v=v+2736|0;v=v+34|0;a[v>>0]=u;i=t;return}c[n>>2]=1;if(((c[l>>2]|0)==2?(c[(c[j>>2]|0)+2396>>2]|0)==2:0)?(c[o>>2]=((ec(c[k>>2]|0,29096,8)|0)&65535)<<16>>16,(c[o>>2]|0)>0):0){c[o>>2]=(c[o>>2]|0)-9;b[(c[j>>2]|0)+2736+26>>1]=(b[(c[j>>2]|0)+2400>>1]|0)+(c[o>>2]|0);c[n>>2]=0}if(c[n>>2]|0){u=((ec(c[k>>2]|0,29064,8)|0)&65535)<<16>>16;u=(_(u,c[(c[j>>2]|0)+2316>>2]>>1)|0)&65535;b[(c[j>>2]|0)+2736+26>>1]=u;u=((ec(c[k>>2]|0,c[(c[j>>2]|0)+2380>>2]|0,8)|0)&65535)<<16>>16;v=(c[j>>2]|0)+2736+26|0;b[v>>1]=(b[v>>1]|0)+u}b[(c[j>>2]|0)+2400>>1]=b[(c[j>>2]|0)+2736+26>>1]|0;v=(ec(c[k>>2]|0,c[(c[j>>2]|0)+2384>>2]|0,8)|0)&255;a[(c[j>>2]|0)+2736+28>>0]=v;v=(ec(c[k>>2]|0,26812,8)|0)&255;a[(c[j>>2]|0)+2736+32>>0]=v;c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[(c[j>>2]|0)+2324>>2]|0))break;v=(ec(c[k>>2]|0,c[17620+(a[(c[j>>2]|0)+2736+32>>0]<<2)>>2]|0,8)|0)&255;a[(c[j>>2]|0)+2736+4+(c[r>>2]|0)>>0]=v;c[r>>2]=(c[r>>2]|0)+1}if(!(c[l>>2]|0)){v=(ec(c[k>>2]|0,29017,8)|0)&255;a[(c[j>>2]|0)+2736+33>>0]=v;v=c[j>>2]|0;v=v+2736|0;v=v+29|0;v=a[v>>0]|0;v=v<<24>>24;u=c[j>>2]|0;u=u+2396|0;c[u>>2]=v;u=c[k>>2]|0;u=ec(u,29034,8)|0;u=u&255;v=c[j>>2]|0;v=v+2736|0;v=v+34|0;a[v>>0]=u;i=t;return}else{a[(c[j>>2]|0)+2736+33>>0]=0;v=c[j>>2]|0;v=v+2736|0;v=v+29|0;v=a[v>>0]|0;v=v<<24>>24;u=c[j>>2]|0;u=u+2396|0;c[u>>2]=v;u=c[k>>2]|0;u=ec(u,29034,8)|0;u=u&255;v=c[j>>2]|0;v=v+2736|0;v=v+34|0;a[v>>0]=u;i=t;return}}function Nd(a,d,e,f,g){a=a|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0;y=i;i=i+224|0;k=y+212|0;l=y+208|0;m=y+204|0;n=y+200|0;o=y+196|0;q=y+192|0;s=y+188|0;t=y+184|0;r=y+180|0;p=y+176|0;u=y+172|0;h=y+168|0;x=y+88|0;v=y+8|0;w=y+4|0;j=y;c[k>>2]=a;c[l>>2]=d;c[m>>2]=e;c[n>>2]=f;c[o>>2]=g;c[h>>2]=ec(c[k>>2]|0,29523+((c[m>>2]>>1)*9|0)|0,8)|0;c[r>>2]=c[o>>2]>>4;if((c[r>>2]<<4|0)<(c[o>>2]|0))c[r>>2]=(c[r>>2]|0)+1;c[j>>2]=29181+((c[h>>2]|0)*18|0);c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[r>>2]|0))break;c[v+(c[q>>2]<<2)>>2]=0;e=ec(c[k>>2]|0,c[j>>2]|0,8)|0;c[x+(c[q>>2]<<2)>>2]=e;while(1){h=c[q>>2]|0;if((c[x+(c[q>>2]<<2)>>2]|0)!=17)break;e=v+(h<<2)|0;c[e>>2]=(c[e>>2]|0)+1;e=ec(c[k>>2]|0,29343+((c[v+(c[q>>2]<<2)>>2]|0)==10&1)|0,8)|0;c[x+(c[q>>2]<<2)>>2]=e}c[q>>2]=h+1}c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[r>>2]|0))break;h=(c[l>>2]|0)+((c[q>>2]&65535)<<16>>16<<4<<1)|0;if((c[x+(c[q>>2]<<2)>>2]|0)>0)Se(h,c[k>>2]|0,c[x+(c[q>>2]<<2)>>2]|0);else{g=h+32|0;do{b[h>>1]=0;h=h+2|0}while((h|0)<(g|0))}c[q>>2]=(c[q>>2]|0)+1}c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[r>>2]|0))break;if((c[v+(c[q>>2]<<2)>>2]|0)>0){c[u>>2]=c[v+(c[q>>2]<<2)>>2];c[w>>2]=(c[l>>2]|0)+((c[q>>2]&65535)<<16>>16<<4<<1);c[t>>2]=0;while(1){if((c[t>>2]|0)>=16)break;c[p>>2]=b[(c[w>>2]|0)+(c[t>>2]<<1)>>1];c[s>>2]=0;while(1){h=c[p>>2]|0;if((c[s>>2]|0)>=(c[u>>2]|0))break;c[p>>2]=h<<1;j=ec(c[k>>2]|0,29015,8)|0;c[p>>2]=(c[p>>2]|0)+j;c[s>>2]=(c[s>>2]|0)+1}b[(c[w>>2]|0)+(c[t>>2]<<1)>>1]=h;c[t>>2]=(c[t>>2]|0)+1}j=x+(c[q>>2]<<2)|0;c[j>>2]=c[j>>2]|c[u>>2]<<5}c[q>>2]=(c[q>>2]|0)+1}Ed(c[k>>2]|0,c[l>>2]|0,c[o>>2]|0,c[m>>2]|0,c[n>>2]|0,x);i=y;return}function Od(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;g=l+16|0;h=l+12|0;f=l+8|0;j=l+4|0;k=l;c[g>>2]=b;c[h>>2]=d;c[f>>2]=e;c[k>>2]=0;c[(c[g>>2]|0)+2332>>2]=((c[h>>2]&65535)<<16>>16)*5;c[j>>2]=_((c[(c[g>>2]|0)+2324>>2]&65535)<<16>>16,(c[(c[g>>2]|0)+2332>>2]&65535)<<16>>16)|0;if(!((c[(c[g>>2]|0)+2316>>2]|0)==(c[h>>2]|0)?(c[(c[g>>2]|0)+2320>>2]|0)==(c[f>>2]|0):0)){b=ig((c[g>>2]|0)+2432|0,((c[h>>2]&65535)<<16>>16)*1e3|0,c[f>>2]|0,0)|0;c[k>>2]=(c[k>>2]|0)+b;c[(c[g>>2]|0)+2320>>2]=c[f>>2]}if((c[(c[g>>2]|0)+2316>>2]|0)==(c[h>>2]|0)?(c[j>>2]|0)==(c[(c[g>>2]|0)+2328>>2]|0):0){k=c[k>>2]|0;i=l;return k|0}f=(c[(c[g>>2]|0)+2324>>2]|0)==4;e=(c[g>>2]|0)+2384|0;do if((c[h>>2]|0)==8)if(f){c[e>>2]=29151;break}else{c[e>>2]=29174;break}else if(f){c[e>>2]=29117;break}else{c[e>>2]=29162;break}while(0);if((c[(c[g>>2]|0)+2316>>2]|0)!=(c[h>>2]|0)){c[(c[g>>2]|0)+2336>>2]=((c[h>>2]&65535)<<16>>16)*20;f=(c[g>>2]|0)+2340|0;if((c[h>>2]|0)==8|(c[h>>2]|0)==12){c[f>>2]=10;c[(c[g>>2]|0)+2732>>2]=17668}else{c[f>>2]=16;c[(c[g>>2]|0)+2732>>2]=17704}do if((c[h>>2]|0)!=16){if((c[h>>2]|0)==12){c[(c[g>>2]|0)+2380>>2]=29043;break}if((c[h>>2]|0)==8)c[(c[g>>2]|0)+2380>>2]=29034}else c[(c[g>>2]|0)+2380>>2]=29049;while(0);c[(c[g>>2]|0)+2376>>2]=1;c[(c[g>>2]|0)+2308>>2]=100;a[(c[g>>2]|0)+2312>>0]=10;c[(c[g>>2]|0)+4164>>2]=0;oj((c[g>>2]|0)+1348|0,0,960)|0;f=(c[g>>2]|0)+1284|0;e=f+64|0;do{c[f>>2]=0;f=f+4|0}while((f|0)<(e|0))}c[(c[g>>2]|0)+2316>>2]=c[h>>2];c[(c[g>>2]|0)+2328>>2]=c[j>>2];k=c[k>>2]|0;i=l;return k|0}function Pd(a){a=a|0;var b=0,d=0,e=0;d=i;i=i+16|0;e=d+4|0;b=d;c[e>>2]=a;c[b>>2]=0;c[c[e>>2]>>2]=8544;i=d;return c[b>>2]|0}function Qd(a){a=a|0;var b=0,d=0,e=0,f=0,g=0;g=i;i=i+16|0;b=g+12|0;e=g+8|0;f=g+4|0;d=g;c[b>>2]=a;c[f>>2]=0;c[d>>2]=c[b>>2];c[e>>2]=0;while(1){if((c[e>>2]|0)>=2)break;c[f>>2]=Fd((c[d>>2]|0)+((c[e>>2]|0)*4260|0)|0)|0;c[e>>2]=(c[e>>2]|0)+1}e=(c[b>>2]|0)+8520|0;c[e>>2]=0;c[e+4>>2]=0;c[e+8>>2]=0;c[(c[b>>2]|0)+8540>>2]=0;i=g;return c[f>>2]|0}function Rd(d,e,f,g,h,j,k,l){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;l=l|0;var m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0;P=i;i=i+784|0;y=P+128|0;R=P+124|0;z=P+120|0;A=P+116|0;Q=P+112|0;r=P+108|0;B=P+104|0;C=P+100|0;s=P+96|0;G=P+92|0;I=P+88|0;F=P+84|0;M=P+80|0;J=P+76|0;n=P+72|0;N=P+64|0;u=P+56|0;L=P+52|0;K=P+48|0;E=P+44|0;w=P+40|0;O=P+36|0;x=P+32|0;m=P+28|0;p=P+136|0;o=P+24|0;D=P+20|0;t=P+16|0;v=P+12|0;H=P;c[R>>2]=d;c[z>>2]=e;c[A>>2]=f;c[Q>>2]=g;c[r>>2]=h;c[B>>2]=j;c[C>>2]=k;c[s>>2]=l;c[F>>2]=0;c[M>>2]=0;c[u>>2]=0;c[u+4>>2]=0;c[K>>2]=c[R>>2];c[E>>2]=c[K>>2];a:do if(c[Q>>2]|0){c[I>>2]=0;while(1){if((c[I>>2]|0)>=(c[(c[z>>2]|0)+4>>2]|0))break a;c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2388>>2]=0;c[I>>2]=(c[I>>2]|0)+1}}while(0);if((c[(c[z>>2]|0)+4>>2]|0)>(c[(c[K>>2]|0)+8536>>2]|0)){R=Fd((c[E>>2]|0)+4260|0)|0;c[M>>2]=(c[M>>2]|0)+R}if((c[(c[z>>2]|0)+4>>2]|0)==1?(c[(c[K>>2]|0)+8536>>2]|0)==2:0)l=(c[(c[z>>2]|0)+12>>2]|0)==((c[(c[E>>2]|0)+2316>>2]|0)*1e3|0);else l=0;c[O>>2]=l&1;b:do if(!(c[(c[E>>2]|0)+2388>>2]|0)){c[I>>2]=0;c:while(1){if((c[I>>2]|0)>=(c[(c[z>>2]|0)+4>>2]|0))break b;do if(!(c[(c[z>>2]|0)+16>>2]|0)){c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]=1;c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2324>>2]=2}else{if((c[(c[z>>2]|0)+16>>2]|0)==10){c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]=1;c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2324>>2]=2;break}if((c[(c[z>>2]|0)+16>>2]|0)==20){c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]=1;c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2324>>2]=4;break}if((c[(c[z>>2]|0)+16>>2]|0)==40){c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]=2;c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2324>>2]=4;break}if((c[(c[z>>2]|0)+16>>2]|0)!=60){q=23;break c}c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]=3;c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2324>>2]=4}while(0);c[m>>2]=(c[(c[z>>2]|0)+12>>2]>>10)+1;if((c[m>>2]|0)!=8&(c[m>>2]|0)!=12&(c[m>>2]|0)!=16){q=25;break}R=Od((c[E>>2]|0)+((c[I>>2]|0)*4260|0)|0,c[m>>2]|0,c[(c[z>>2]|0)+8>>2]|0)|0;c[M>>2]=(c[M>>2]|0)+R;c[I>>2]=(c[I>>2]|0)+1}if((q|0)==23){c[y>>2]=-203;R=c[y>>2]|0;i=P;return R|0}else if((q|0)==25){c[y>>2]=-200;R=c[y>>2]|0;i=P;return R|0}}while(0);do if((c[c[z>>2]>>2]|0)==2?(c[(c[z>>2]|0)+4>>2]|0)==2:0){if((c[(c[K>>2]|0)+8532>>2]|0)!=1?(c[(c[K>>2]|0)+8536>>2]|0)!=1:0)break;c[(c[K>>2]|0)+8520>>2]=0;c[(c[K>>2]|0)+8520+8>>2]=0;pj((c[E>>2]|0)+4260+2432|0,(c[E>>2]|0)+2432|0,300)|0}while(0);c[(c[K>>2]|0)+8532>>2]=c[c[z>>2]>>2];c[(c[K>>2]|0)+8536>>2]=c[(c[z>>2]|0)+4>>2];if((c[(c[z>>2]|0)+8>>2]|0)<=48e3?(c[(c[z>>2]|0)+8>>2]|0)>=8e3:0){d:do if((c[A>>2]|0)!=1?(c[(c[E>>2]|0)+2388>>2]|0)==0:0){c[I>>2]=0;while(1){if((c[I>>2]|0)>=(c[(c[z>>2]|0)+4>>2]|0))break;c[G>>2]=0;while(1){R=(c[G>>2]|0)<(c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]|0);l=dc(c[r>>2]|0,1)|0;if(!R)break;c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2404+(c[G>>2]<<2)>>2]=l;c[G>>2]=(c[G>>2]|0)+1}c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2416>>2]=l;c[I>>2]=(c[I>>2]|0)+1}c[I>>2]=0;while(1){if((c[I>>2]|0)>=(c[(c[z>>2]|0)+4>>2]|0))break;R=(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2420|0;c[R>>2]=0;c[R+4>>2]=0;c[R+8>>2]=0;e:do if(c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2416>>2]|0){if((c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]|0)==1){c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2420>>2]=1;break}c[n>>2]=(ec(c[r>>2]|0,c[17836+((c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]|0)-2<<2)>>2]|0,8)|0)+1;c[G>>2]=0;while(1){if((c[G>>2]|0)>=(c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2392>>2]|0))break e;c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2420+(c[G>>2]<<2)>>2]=c[n>>2]>>c[G>>2]&1;c[G>>2]=(c[G>>2]|0)+1}}while(0);c[I>>2]=(c[I>>2]|0)+1}if(!(c[A>>2]|0)){c[G>>2]=0;while(1){if((c[G>>2]|0)>=(c[(c[E>>2]|0)+2392>>2]|0))break d;c[I>>2]=0;while(1){l=c[G>>2]|0;if((c[I>>2]|0)>=(c[(c[z>>2]|0)+4>>2]|0))break;if(c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2420+(l<<2)>>2]|0){do if((c[I>>2]|0)==0?(c[(c[z>>2]|0)+4>>2]|0)==2:0){xg(c[r>>2]|0,u);if(c[(c[E>>2]|0)+4260+2420+(c[G>>2]<<2)>>2]|0)break;yg(c[r>>2]|0,F)}while(0);do if((c[G>>2]|0)>0){if(!(c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2420+((c[G>>2]|0)-1<<2)>>2]|0)){q=64;break}c[o>>2]=2}else q=64;while(0);if((q|0)==64){q=0;c[o>>2]=0}Md((c[E>>2]|0)+((c[I>>2]|0)*4260|0)|0,c[r>>2]|0,c[G>>2]|0,1,c[o>>2]|0);Nd(c[r>>2]|0,p,a[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2736+29>>0]|0,a[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2736+30>>0]|0,c[(c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2328>>2]|0)}c[I>>2]=(c[I>>2]|0)+1}c[G>>2]=l+1}}}while(0);f:do if((c[(c[z>>2]|0)+4>>2]|0)==2){do if(c[A>>2]|0){if((c[A>>2]|0)==2?(c[(c[E>>2]|0)+2420+(c[(c[E>>2]|0)+2388>>2]<<2)>>2]|0)==1:0)break;c[I>>2]=0;while(1){if((c[I>>2]|0)>=2)break f;c[u+(c[I>>2]<<2)>>2]=b[(c[K>>2]|0)+8520+(c[I>>2]<<1)>>1];c[I>>2]=(c[I>>2]|0)+1}}while(0);xg(c[r>>2]|0,u);if(!((c[A>>2]|0)==0?!(c[(c[E>>2]|0)+4260+2404+(c[(c[E>>2]|0)+2388>>2]<<2)>>2]|0):0))q=74;do if((q|0)==74){if((c[A>>2]|0)==2?(c[(c[E>>2]|0)+4260+2420+(c[(c[E>>2]|0)+2388>>2]<<2)>>2]|0)==0:0)break;c[F>>2]=0;break f}while(0);yg(c[r>>2]|0,F)}while(0);if(((c[F>>2]|0)==0?(c[(c[z>>2]|0)+4>>2]|0)==2:0)?(c[(c[K>>2]|0)+8540>>2]|0)==1:0){oj((c[K>>2]|0)+4260+1348|0,0,960)|0;l=(c[K>>2]|0)+4260+1284|0;e=l+64|0;do{c[l>>2]=0;l=l+4|0}while((l|0)<(e|0));c[(c[K>>2]|0)+4260+2308>>2]=100;a[(c[K>>2]|0)+4260+2312>>0]=10;c[(c[K>>2]|0)+4260+4164>>2]=0;c[(c[K>>2]|0)+4260+2376>>2]=1}R=_(c[(c[z>>2]|0)+12>>2]|0,c[(c[z>>2]|0)+4>>2]|0)|0;c[x>>2]=(R|0)<(_(c[(c[z>>2]|0)+8>>2]|0,c[c[z>>2]>>2]|0)|0)&1;if(c[x>>2]|0)l=1;else l=_(c[(c[z>>2]|0)+4>>2]|0,(c[(c[E>>2]|0)+2328>>2]|0)+2|0)|0;c[D>>2]=ia()|0;e=i;i=i+((1*(l<<1)|0)+15&-16)|0;if(c[x>>2]|0){c[N>>2]=c[B>>2];c[N+4>>2]=(c[B>>2]|0)+(c[(c[E>>2]|0)+2328>>2]<<1)+4}else{c[N>>2]=e;c[N+4>>2]=e+(c[(c[E>>2]|0)+2328>>2]<<1)+4}if(!(c[A>>2]|0))c[w>>2]=((c[F>>2]|0)!=0^1)&1;else{if(c[(c[K>>2]|0)+8540>>2]|0)if((c[A>>2]|0)==2?(c[(c[z>>2]|0)+4>>2]|0)==2:0)l=(c[(c[E>>2]|0)+4260+2420+(c[(c[E>>2]|0)+4260+2388>>2]<<2)>>2]|0)==1;else l=0;else l=1;c[w>>2]=l&1}c[I>>2]=0;while(1){if((c[I>>2]|0)>=(c[(c[z>>2]|0)+4>>2]|0))break;if((c[I>>2]|0)==0|(c[w>>2]|0)!=0){c[t>>2]=(c[(c[E>>2]|0)+2388>>2]|0)-(c[I>>2]|0);g:do if((c[t>>2]|0)<=0)c[v>>2]=0;else{if((c[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+((1*(l<<1)|0)+15&-16)|0;if(c[x>>2]|0){R=(_(c[(c[z>>2]|0)+4>>2]|0,(c[(c[E>>2]|0)+2328>>2]|0)+2|0)|0)<<1;pj(e|0,c[B>>2]|0,R+0|0)|0;c[N>>2]=e;c[N+4>>2]=e+(c[(c[E>>2]|0)+2328>>2]<<1)+4}c[I>>2]=0;while(1){l=c[z>>2]|0;if((c[c[z>>2]>>2]|0)<(c[(c[z>>2]|0)+4>>2]|0))l=c[l>>2]|0;else l=c[l+4>>2]|0;if((c[I>>2]|0)>=(l|0))break;R=jg((c[E>>2]|0)+((c[I>>2]|0)*4260|0)+2432|0,c[L>>2]|0,(c[N+(c[I>>2]<<2)>>2]|0)+2|0,c[J>>2]|0)|0;c[M>>2]=(c[M>>2]|0)+R;h:do if((c[c[z>>2]>>2]|0)==2){c[G>>2]=0;while(1){if((c[G>>2]|0)>=(c[c[C>>2]>>2]|0))break h;b[(c[B>>2]|0)+((c[I>>2]|0)+(c[G>>2]<<1)<<1)>>1]=b[(c[L>>2]|0)+(c[G>>2]<<1)>>1]|0;c[G>>2]=(c[G>>2]|0)+1}}while(0);c[I>>2]=(c[I>>2]|0)+1}i:do if((c[c[z>>2]>>2]|0)==2){if((c[(c[z>>2]|0)+4>>2]|0)!=1)break;if(c[O>>2]|0){R=jg((c[E>>2]|0)+4260+2432|0,c[L>>2]|0,(c[N>>2]|0)+2|0,c[J>>2]|0)|0;c[M>>2]=(c[M>>2]|0)+R;c[G>>2]=0;while(1){if((c[G>>2]|0)>=(c[c[C>>2]>>2]|0))break i;b[(c[B>>2]|0)+(1+(c[G>>2]<<1)<<1)>>1]=b[(c[L>>2]|0)+(c[G>>2]<<1)>>1]|0;c[G>>2]=(c[G>>2]|0)+1}}else{c[G>>2]=0;while(1){if((c[G>>2]|0)>=(c[c[C>>2]>>2]|0))break i;b[(c[B>>2]|0)+(1+(c[G>>2]<<1)<<1)>>1]=b[(c[B>>2]|0)+(0+(c[G>>2]<<1)<<1)>>1]|0;c[G>>2]=(c[G>>2]|0)+1}}}while(0);if((c[(c[E>>2]|0)+4164>>2]|0)==2){c[H>>2]=c[4402];c[H+4>>2]=c[4403];c[H+8>>2]=c[4404];R=_(c[(c[E>>2]|0)+2308>>2]|0,c[H+((c[(c[E>>2]|0)+2316>>2]|0)-8>>2<<2)>>2]|0)|0;c[(c[z>>2]|0)+20>>2]=R}else c[(c[z>>2]|0)+20>>2]=0;j:do if((c[A>>2]|0)==1){c[G>>2]=0;while(1){if((c[G>>2]|0)>=(c[(c[K>>2]|0)+8536>>2]|0))break j;a[(c[K>>2]|0)+((c[G>>2]|0)*4260|0)+2312>>0]=10;c[G>>2]=(c[G>>2]|0)+1}}else c[(c[K>>2]|0)+8540>>2]=c[F>>2];while(0);c[y>>2]=c[M>>2];na(c[D>>2]|0);R=c[y>>2]|0;i=P;return R|0}c[M>>2]=-200;c[y>>2]=c[M>>2];R=c[y>>2]|0;i=P;return R|0}function Sd(a){a=a|0;var b=0,d=0,e=0;d=i;i=i+16|0;e=d+4|0;b=d;c[e>>2]=a;c[b>>2]=0;c[c[e>>2]>>2]=24568;i=d;return c[b>>2]|0}function Td(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;e=l+20|0;f=l+16|0;g=l+12|0;j=l+8|0;h=l+4|0;k=l;c[e>>2]=a;c[f>>2]=b;c[g>>2]=d;c[k>>2]=0;c[j>>2]=c[e>>2];oj(c[j>>2]|0,0,24568)|0;c[h>>2]=0;while(1){if((c[h>>2]|0)>=2)break;d=xf((c[j>>2]|0)+((c[h>>2]|0)*12240|0)|0,c[f>>2]|0)|0;c[k>>2]=(c[k>>2]|0)+d;c[h>>2]=(c[h>>2]|0)+1}c[(c[j>>2]|0)+24544>>2]=1;c[(c[j>>2]|0)+24548>>2]=1;j=Ud(c[e>>2]|0,c[g>>2]|0)|0;c[k>>2]=(c[k>>2]|0)+j;i=l;return c[k>>2]|0}function Ud(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0;g=i;i=i+32|0;j=g+16|0;d=g+12|0;e=g+8|0;f=g+4|0;h=g;c[j>>2]=a;c[d>>2]=b;c[e>>2]=0;c[h>>2]=c[j>>2];c[f>>2]=c[h>>2];c[c[d>>2]>>2]=c[(c[h>>2]|0)+24544>>2];c[(c[d>>2]|0)+4>>2]=c[(c[h>>2]|0)+24548>>2];c[(c[d>>2]|0)+8>>2]=c[(c[f>>2]|0)+4580>>2];c[(c[d>>2]|0)+12>>2]=c[(c[f>>2]|0)+4588>>2];c[(c[d>>2]|0)+16>>2]=c[(c[f>>2]|0)+4592>>2];c[(c[d>>2]|0)+20>>2]=c[(c[f>>2]|0)+4596>>2];c[(c[d>>2]|0)+24>>2]=c[(c[f>>2]|0)+4636>>2];c[(c[d>>2]|0)+28>>2]=c[(c[f>>2]|0)+4632>>2];c[(c[d>>2]|0)+32>>2]=c[(c[f>>2]|0)+4640>>2];c[(c[d>>2]|0)+36>>2]=c[(c[f>>2]|0)+4648>>2];c[(c[d>>2]|0)+40>>2]=c[(c[f>>2]|0)+6120>>2];c[(c[d>>2]|0)+44>>2]=c[(c[f>>2]|0)+6108>>2];c[(c[d>>2]|0)+48>>2]=c[(c[f>>2]|0)+4708>>2];c[(c[d>>2]|0)+68>>2]=((c[(c[f>>2]|0)+4600>>2]&65535)<<16>>16)*1e3;c[(c[d>>2]|0)+72>>2]=c[(c[f>>2]|0)+4560>>2];if((c[(c[f>>2]|0)+4600>>2]|0)!=16){h=0;h=h&1;j=c[d>>2]|0;j=j+76|0;c[j>>2]=h;j=c[e>>2]|0;i=g;return j|0}h=(c[(c[f>>2]|0)+16+12>>2]|0)==0;h=h&1;j=c[d>>2]|0;j=j+76|0;c[j>>2]=h;j=c[e>>2]|0;i=g;return j|0}function Vd(d,e,f,g,h,j,k){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;var l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t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>>2]|0)+24480+12>>2]=0,c[(c[U>>2]|0)+24480+12+4>>2]=1,c[(c[U>>2]|0)+24480+12+8>>2]=0,c[(c[U>>2]|0)+24480+12+12>>2]=1,b[(c[U>>2]|0)+24480+30>>1]=0,b[(c[U>>2]|0)+24480+28>>1]=16384,(c[(c[U>>2]|0)+24544>>2]|0)==2):0){pj((c[U>>2]|0)+12240+5808|0,(c[U>>2]|0)+5808|0,300)|0;Z=(c[U>>2]|0)+12240|0;f=c[U>>2]|0;c[Z>>2]=c[f>>2];c[Z+4>>2]=c[f+4>>2]}if((c[(c[Q>>2]|0)+24>>2]|0)!=(c[(c[U>>2]|0)+4636>>2]|0))e=1;else e=(c[(c[U>>2]|0)+24548>>2]|0)!=(c[(c[Q>>2]|0)+4>>2]|0);c[n>>2]=e&1;c[(c[U>>2]|0)+24544>>2]=c[c[Q>>2]>>2];c[(c[U>>2]|0)+24548>>2]=c[(c[Q>>2]|0)+4>>2];c[G>>2]=((c[p>>2]|0)*100|0)/(c[(c[Q>>2]|0)+8>>2]|0)|0;c[M>>2]=(c[G>>2]|0)>1?c[G>>2]>>1:1;c[z>>2]=0;e=c[G>>2]|0;a:do if(!(c[R>>2]|0)){Z=_(e,c[(c[Q>>2]|0)+8>>2]|0)|0;if((c[p>>2]|0)<0?1:(Z|0)!=((c[p>>2]|0)*100|0)){c[P>>2]=-101;Z=c[P>>2]|0;i=Y;return Z|0}if(((c[p>>2]|0)*1e3|0)>(_(c[(c[Q>>2]|0)+24>>2]|0,c[(c[Q>>2]|0)+8>>2]|0)|0)){c[P>>2]=-101;Z=c[P>>2]|0;i=Y;return Z|0}}else{if((e|0)!=1){c[P>>2]=-101;Z=c[P>>2]|0;i=Y;return Z|0}c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[(c[Q>>2]|0)+4>>2]|0))break;c[V>>2]=xf((c[U>>2]|0)+((c[T>>2]|0)*12240|0)|0,c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+5124>>2]|0)|0;c[T>>2]=(c[T>>2]|0)+1}c[X>>2]=c[(c[Q>>2]|0)+24>>2];c[(c[Q>>2]|0)+24>>2]=10;c[W>>2]=c[(c[Q>>2]|0)+36>>2];c[(c[Q>>2]|0)+36>>2]=0;c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[(c[Q>>2]|0)+4>>2]|0))break a;c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4700>>2]=0;c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4712>>2]=1;c[T>>2]=(c[T>>2]|0)+1}}while(0);c[u>>2]=c[(c[Q>>2]|0)+28>>2]>>(c[(c[Q>>2]|0)+4>>2]|0)-1;c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[(c[Q>>2]|0)+4>>2]|0))break;if((c[T>>2]|0)==1)e=c[(c[U>>2]|0)+4600>>2]|0;else e=0;c[l>>2]=e;Z=yf((c[U>>2]|0)+((c[T>>2]|0)*12240|0)|0,c[Q>>2]|0,c[u>>2]|0,c[(c[U>>2]|0)+24560>>2]|0,c[T>>2]|0,c[l>>2]|0)|0;c[V>>2]=Z;if(Z|0){O=28;break}b:do if(c[n>>2]|0?1:(c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4696>>2]|0)!=0){c[B>>2]=0;while(1){if((c[B>>2]|0)>=(c[(c[U>>2]|0)+5776>>2]|0))break b;c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4756+(c[B>>2]<<2)>>2]=0;c[B>>2]=(c[B>>2]|0)+1}}while(0);c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+6112>>2]=c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+6108>>2];c[T>>2]=(c[T>>2]|0)+1}if((O|0)==28){c[P>>2]=c[V>>2];Z=c[P>>2]|0;i=Y;return Z|0}c[J>>2]=_((c[G>>2]|0)*10|0,c[(c[U>>2]|0)+4600>>2]|0)|0;Z=_(c[J>>2]|0,c[(c[U>>2]|0)+4580>>2]|0)|0;c[m>>2]=(Z|0)/((c[(c[U>>2]|0)+4600>>2]|0)*1e3|0)|0;Z=c[m>>2]|0;c[S>>2]=ia()|0;d=i;i=i+((1*(Z<<1)|0)+15&-16)|0;while(1){c[I>>2]=(c[(c[U>>2]|0)+4608>>2]|0)-(c[(c[U>>2]|0)+5772>>2]|0);c[I>>2]=(c[I>>2]|0)<(c[J>>2]|0)?c[I>>2]|0:c[J>>2]|0;Z=_(c[I>>2]|0,c[(c[U>>2]|0)+4580>>2]|0)|0;c[H>>2]=(Z|0)/((c[(c[U>>2]|0)+4600>>2]|0)*1e3|0)|0;if((c[c[Q>>2]>>2]|0)==2?(c[(c[Q>>2]|0)+4>>2]|0)==2:0){c[D>>2]=c[(c[U>>2]|0)+5780>>2];c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[H>>2]|0))break;b[d+(c[T>>2]<<1)>>1]=b[(c[o>>2]|0)+(c[T>>2]<<1<<1)>>1]|0;c[T>>2]=(c[T>>2]|0)+1}if((c[D>>2]|0)==0?(c[(c[U>>2]|0)+24552>>2]|0)==1:0)pj((c[U>>2]|0)+12240+5808|0,(c[U>>2]|0)+5808|0,300)|0;Z=jg((c[U>>2]|0)+5808|0,(c[U>>2]|0)+5128+((c[(c[U>>2]|0)+5772>>2]|0)+2<<1)|0,d,c[H>>2]|0)|0;c[V>>2]=(c[V>>2]|0)+Z;Z=(c[U>>2]|0)+5772|0;c[Z>>2]=(c[Z>>2]|0)+(c[I>>2]|0);c[I>>2]=(c[(c[U>>2]|0)+12240+4608>>2]|0)-(c[(c[U>>2]|0)+12240+5772>>2]|0);if((c[I>>2]|0)<(_((c[G>>2]|0)*10|0,c[(c[U>>2]|0)+12240+4600>>2]|0)|0))e=c[I>>2]|0;else e=_((c[G>>2]|0)*10|0,c[(c[U>>2]|0)+12240+4600>>2]|0)|0;c[I>>2]=e;c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[H>>2]|0))break;b[d+(c[T>>2]<<1)>>1]=b[(c[o>>2]|0)+((c[T>>2]<<1)+1<<1)>>1]|0;c[T>>2]=(c[T>>2]|0)+1}Z=jg((c[U>>2]|0)+12240+5808|0,(c[U>>2]|0)+12240+5128+((c[(c[U>>2]|0)+12240+5772>>2]|0)+2<<1)|0,d,c[H>>2]|0)|0;c[V>>2]=(c[V>>2]|0)+Z;Z=(c[U>>2]|0)+12240+5772|0;c[Z>>2]=(c[Z>>2]|0)+(c[I>>2]|0)}else O=49;do if((O|0)==49){O=0;if((c[c[Q>>2]>>2]|0)==2?(c[(c[Q>>2]|0)+4>>2]|0)==1:0){c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[H>>2]|0))break;c[L>>2]=(b[(c[o>>2]|0)+(c[T>>2]<<1<<1)>>1]|0)+(b[(c[o>>2]|0)+((c[T>>2]<<1)+1<<1)>>1]|0);b[d+(c[T>>2]<<1)>>1]=(c[L>>2]>>1)+(c[L>>2]&1);c[T>>2]=(c[T>>2]|0)+1}Z=jg((c[U>>2]|0)+5808|0,(c[U>>2]|0)+5128+((c[(c[U>>2]|0)+5772>>2]|0)+2<<1)|0,d,c[H>>2]|0)|0;c[V>>2]=(c[V>>2]|0)+Z;c:do if((c[(c[U>>2]|0)+24552>>2]|0)==2?(c[(c[U>>2]|0)+5780>>2]|0)==0:0){Z=jg((c[U>>2]|0)+12240+5808|0,(c[U>>2]|0)+12240+5128+((c[(c[U>>2]|0)+12240+5772>>2]|0)+2<<1)|0,d,c[H>>2]|0)|0;c[V>>2]=(c[V>>2]|0)+Z;c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[(c[U>>2]|0)+4608>>2]|0))break c;b[(c[U>>2]|0)+5128+((c[(c[U>>2]|0)+5772>>2]|0)+(c[T>>2]|0)+2<<1)>>1]=(b[(c[U>>2]|0)+5128+((c[(c[U>>2]|0)+5772>>2]|0)+(c[T>>2]|0)+2<<1)>>1]|0)+(b[(c[U>>2]|0)+12240+5128+((c[(c[U>>2]|0)+12240+5772>>2]|0)+(c[T>>2]|0)+2<<1)>>1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)+5776>>2]|0)-2<<2)>>2]|0,8);c[T>>2]=(c[T>>2]|0)+1}c[B>>2]=0;while(1){Z=(c[B>>2]|0)<(c[(c[U>>2]|0)+5776>>2]|0);c[T>>2]=0;if(!Z)break;while(1){e=c[B>>2]|0;if((c[T>>2]|0)>=(c[(c[Q>>2]|0)+4>>2]|0))break;if(c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4756+(e<<2)>>2]|0){if(((c[T>>2]|0)==0?(c[(c[Q>>2]|0)+4>>2]|0)==2:0)?(zg(c[q>>2]|0,(c[U>>2]|0)+24480+34+((c[B>>2]|0)*6|0)|0),(c[(c[U>>2]|0)+12240+4756+(c[B>>2]<<2)>>2]|0)==0):0)Ag(c[q>>2]|0,a[(c[U>>2]|0)+24480+52+(c[B>>2]|0)>>0]|0);if((c[B>>2]|0)>0?c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4756+((c[B>>2]|0)-1<<2)>>2]|0:0)c[x>>2]=2;else c[x>>2]=0;Xd((c[U>>2]|0)+((c[T>>2]|0)*12240|0)|0,c[q>>2]|0,c[B>>2]|0,1,c[x>>2]|0);Yd(c[q>>2]|0,a[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+6132+((c[B>>2]|0)*36|0)+29>>0]|0,a[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+6132+((c[B>>2]|0)*36|0)+30>>0]|0,(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+6240+((c[B>>2]|0)*320|0)|0,c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4608>>2]|0)}c[T>>2]=(c[T>>2]|0)+1}c[B>>2]=e+1}while(1){if((c[T>>2]|0)>=(c[(c[Q>>2]|0)+4>>2]|0))break;Z=(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4756|0;c[Z>>2]=0;c[Z+4>>2]=0;c[Z+8>>2]=0;c[T>>2]=(c[T>>2]|0)+1}Z=Wd(c[q>>2]|0)|0;c[(c[U>>2]|0)+24536>>2]=Z}ff(c[U>>2]|0);c[F>>2]=(_(c[(c[Q>>2]|0)+28>>2]|0,c[(c[Q>>2]|0)+24>>2]|0)|0)/1e3|0;if(!(c[R>>2]|0))c[F>>2]=(c[F>>2]|0)-(c[(c[U>>2]|0)+24536>>2]|0);c[F>>2]=(c[F>>2]|0)/(c[(c[U>>2]|0)+5776>>2]|0)|0;e=(c[F>>2]&65535)<<16>>16;if((c[(c[Q>>2]|0)+24>>2]|0)==10)c[u>>2]=e*100;else c[u>>2]=e*50;c[u>>2]=(c[u>>2]|0)-(((c[(c[U>>2]|0)+24540>>2]|0)*1e3|0)/500|0);if((c[R>>2]|0)==0?(c[(c[U>>2]|0)+5780>>2]|0)>0:0){Z=Wd(c[q>>2]|0)|0;c[v>>2]=Z-(c[(c[U>>2]|0)+24536>>2]|0)-(_(c[F>>2]|0,c[(c[U>>2]|0)+5780>>2]|0)|0);c[u>>2]=(c[u>>2]|0)-(((c[v>>2]|0)*1e3|0)/500|0)}e=c[u>>2]|0;do if((c[(c[Q>>2]|0)+28>>2]|0)>5e3)if((e|0)>(c[(c[Q>>2]|0)+28>>2]|0)){e=c[(c[Q>>2]|0)+28>>2]|0;break}else{e=(c[u>>2]|0)<5e3?5e3:c[u>>2]|0;break}else if((e|0)<=5e3)if((c[u>>2]|0)<(c[(c[Q>>2]|0)+28>>2]|0)){e=c[(c[Q>>2]|0)+28>>2]|0;break}else{e=c[u>>2]|0;break}else e=5e3;while(0);c[u>>2]=e;e=c[U>>2]|0;if((c[(c[Q>>2]|0)+4>>2]|0)==2){qf(e+24480|0,(c[U>>2]|0)+5128+4|0,(c[U>>2]|0)+12240+5128+4|0,(c[U>>2]|0)+24480+34+((c[(c[U>>2]|0)+5780>>2]|0)*6|0)|0,(c[U>>2]|0)+24480+52+(c[(c[U>>2]|0)+5780>>2]|0)|0,t,c[u>>2]|0,c[(c[U>>2]|0)+4556>>2]|0,c[(c[Q>>2]|0)+56>>2]|0,c[(c[U>>2]|0)+4600>>2]|0,c[(c[U>>2]|0)+4608>>2]|0);e=c[U>>2]|0;if(!(a[(c[U>>2]|0)+24480+52+(c[(c[U>>2]|0)+5780>>2]|0)>>0]|0)){if((c[e+24564>>2]|0)==1){Z=(c[U>>2]|0)+12240+7200|0;c[Z>>2]=0;c[Z+4>>2]=0;c[Z+8>>2]=0;c[Z+12>>2]=0;oj((c[U>>2]|0)+12240+7216|0,0,2140)|0;oj((c[U>>2]|0)+12240+144|0,0,4380)|0;Z=(c[U>>2]|0)+12240+4524|0;c[Z>>2]=0;c[Z+4>>2]=0;c[Z+8>>2]=0;c[Z+12>>2]=0;c[Z+16>>2]=0;c[Z+20>>2]=0;c[Z+24>>2]=0;c[Z+28>>2]=0;Z=(c[U>>2]|0)+12240+16|0;c[Z>>2]=0;c[Z+4>>2]=0;c[(c[U>>2]|0)+12240+4568>>2]=100;c[(c[U>>2]|0)+12240+144+4356>>2]=100;a[(c[U>>2]|0)+12240+7200>>0]=10;a[(c[U>>2]|0)+12240+4565>>0]=0;c[(c[U>>2]|0)+12240+144+4372>>2]=65536;c[(c[U>>2]|0)+12240+4696>>2]=1}Mg((c[U>>2]|0)+12240|0)}else a[(c[U>>2]|0)+12240+4752+(c[e+5780>>2]|0)>>0]=0;if((c[R>>2]|0)==0?(zg(c[q>>2]|0,(c[U>>2]|0)+24480+34+((c[(c[U>>2]|0)+5780>>2]|0)*6|0)|0),(a[(c[U>>2]|0)+12240+4752+(c[(c[U>>2]|0)+5780>>2]|0)>>0]|0)==0):0)Ag(c[q>>2]|0,a[(c[U>>2]|0)+24480+52+(c[(c[U>>2]|0)+5780>>2]|0)>>0]|0)}else{c[e+5128>>2]=c[(c[U>>2]|0)+24480+4>>2];Z=(c[U>>2]|0)+24480+4|0;n=(c[U>>2]|0)+5128+(c[(c[U>>2]|0)+4608>>2]<<1)|0;b[Z>>1]=b[n>>1]|0;b[Z+2>>1]=b[n+2>>1]|0}Mg(c[U>>2]|0);c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[(c[Q>>2]|0)+4>>2]|0))break;c[E>>2]=c[(c[Q>>2]|0)+52>>2];do if(!((c[M>>2]|0)==2&(c[z>>2]|0)==0)){if((c[M>>2]|0)==3){if(!(c[z>>2]|0)){c[E>>2]=(c[E>>2]<<1|0)/5|0;break}if((c[z>>2]|0)!=1)break;c[E>>2]=((c[E>>2]|0)*3|0)/4|0}}else c[E>>2]=((c[E>>2]|0)*3|0)/5|0;while(0);if(c[(c[Q>>2]|0)+48>>2]|0)e=(c[z>>2]|0)==((c[M>>2]|0)-1|0);else e=0;c[N>>2]=e&1;do if((c[(c[Q>>2]|0)+4>>2]|0)==1)c[w>>2]=c[u>>2];else{c[w>>2]=c[t+(c[T>>2]<<2)>>2];if(c[T>>2]|0)break;if((c[t+4>>2]|0)<=0)break;c[N>>2]=0;c[E>>2]=(c[E>>2]|0)-((c[(c[Q>>2]|0)+52>>2]|0)/(c[M>>2]<<1|0)|0)}while(0);if((c[w>>2]|0)>0){wf((c[U>>2]|0)+((c[T>>2]|0)*12240|0)|0,c[w>>2]|0)|0;d:do if(((c[(c[U>>2]|0)+5780>>2]|0)-(c[T>>2]|0)|0)<=0)c[y>>2]=0;else{do if((c[T>>2]|0)>0){if(!(c[(c[U>>2]|0)+24564>>2]|0))break;c[y>>2]=1;break d}while(0);c[y>>2]=2}while(0);c[V>>2]=Ng((c[U>>2]|0)+((c[T>>2]|0)*12240|0)|0,c[r>>2]|0,c[q>>2]|0,c[y>>2]|0,c[E>>2]|0,c[N>>2]|0)|0}c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4700>>2]=0;c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+5772>>2]=0;Z=(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+5780|0;c[Z>>2]=(c[Z>>2]|0)+1;c[T>>2]=(c[T>>2]|0)+1}c[(c[U>>2]|0)+24564>>2]=a[(c[U>>2]|0)+24480+52+((c[(c[U>>2]|0)+5780>>2]|0)-1)>>0];do if((c[c[r>>2]>>2]|0)>0?(c[(c[U>>2]|0)+5780>>2]|0)==(c[(c[U>>2]|0)+5776>>2]|0):0){c[A>>2]=0;c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[(c[Q>>2]|0)+4>>2]|0))break;c[B>>2]=0;while(1){Z=(c[B>>2]|0)<(c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+5776>>2]|0);c[A>>2]=c[A>>2]<<1;if(!Z)break;c[A>>2]=c[A>>2]|a[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4752+(c[B>>2]|0)>>0];c[B>>2]=(c[B>>2]|0)+1}c[A>>2]=c[A>>2]|a[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4755>>0];c[T>>2]=(c[T>>2]|0)+1}if(!(c[R>>2]|0))uc(c[q>>2]|0,c[A>>2]|0,_((c[(c[U>>2]|0)+5776>>2]|0)+1|0,c[(c[Q>>2]|0)+4>>2]|0)|0);do if(c[(c[U>>2]|0)+6112>>2]|0){if((c[(c[Q>>2]|0)+4>>2]|0)!=1?(c[(c[U>>2]|0)+12240+6112>>2]|0)==0:0)break;c[c[r>>2]>>2]=0}while(0);n=(c[U>>2]|0)+24540|0;c[n>>2]=(c[n>>2]|0)+(c[c[r>>2]>>2]<<3);n=(_(c[(c[Q>>2]|0)+28>>2]|0,c[(c[Q>>2]|0)+24>>2]|0)|0)/1e3|0;Z=(c[U>>2]|0)+24540|0;c[Z>>2]=(c[Z>>2]|0)-n;do if((c[(c[U>>2]|0)+24540>>2]|0)>1e4)e=1e4;else{if((c[(c[U>>2]|0)+24540>>2]|0)<0){e=0;break}e=c[(c[U>>2]|0)+24540>>2]|0}while(0);c[(c[U>>2]|0)+24540>>2]=e;c[K>>2]=13+(0+(((c[(c[U>>2]|0)+24556>>2]&65535)<<16>>16)*3188>>16));e=(c[U>>2]|0)+24560|0;if((c[(c[U>>2]|0)+4556>>2]|0)<(c[K>>2]|0)){c[e>>2]=1;c[(c[U>>2]|0)+24556>>2]=0;break}else{c[e>>2]=0;Z=(c[U>>2]|0)+24556|0;c[Z>>2]=(c[Z>>2]|0)+(c[(c[Q>>2]|0)+24>>2]|0);break}}while(0);if(!(c[p>>2]|0))break;c[z>>2]=(c[z>>2]|0)+1}c[(c[U>>2]|0)+24552>>2]=c[(c[Q>>2]|0)+4>>2];c[(c[Q>>2]|0)+72>>2]=c[(c[U>>2]|0)+24560>>2];if((c[(c[U>>2]|0)+4600>>2]|0)==16)e=(c[(c[U>>2]|0)+16+12>>2]|0)==0;else e=0;c[(c[Q>>2]|0)+76>>2]=e&1;c[(c[Q>>2]|0)+68>>2]=((c[(c[U>>2]|0)+4600>>2]&65535)<<16>>16)*1e3;if(c[(c[Q>>2]|0)+56>>2]|0)e=0;else e=b[(c[U>>2]|0)+24480+28>>1]|0;c[(c[Q>>2]|0)+80>>2]=e;e:do if(c[R>>2]|0){c[(c[Q>>2]|0)+24>>2]=c[X>>2];c[(c[Q>>2]|0)+36>>2]=c[W>>2];c[T>>2]=0;while(1){if((c[T>>2]|0)>=(c[(c[Q>>2]|0)+4>>2]|0))break e;c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4700>>2]=0;c[(c[U>>2]|0)+((c[T>>2]|0)*12240|0)+4712>>2]=0;c[T>>2]=(c[T>>2]|0)+1}}while(0);c[P>>2]=c[V>>2];na(c[S>>2]|0);Z=c[P>>2]|0;i=Y;return Z|0}function Wd(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;a=(c[(c[d>>2]|0)+20>>2]|0)-(32-(aa(c[(c[d>>2]|0)+28>>2]|0)|0))|0;i=b;return a|0}function Xd(d,e,f,g,h){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0;y=i;i=i+112|0;n=y+48|0;o=y+44|0;j=y+40|0;k=y+36|0;p=y+32|0;t=y+28|0;u=y+24|0;l=y+20|0;s=y+16|0;q=y+12|0;r=y+56|0;m=y+88|0;x=y+8|0;v=y+4|0;w=y;c[n>>2]=d;c[o>>2]=e;c[j>>2]=f;c[k>>2]=g;c[p>>2]=h;if(c[k>>2]|0)c[x>>2]=(c[n>>2]|0)+6132+((c[j>>2]|0)*36|0);else c[x>>2]=(c[n>>2]|0)+4768;c[l>>2]=(a[(c[x>>2]|0)+29>>0]<<1)+(a[(c[x>>2]|0)+30>>0]|0);j=c[o>>2]|0;f=c[l>>2]|0;if((c[k>>2]|0)!=0|(c[l>>2]|0)>=2)qc(j,f-2|0,29020,8);else qc(j,f,29024,8);j=c[o>>2]|0;f=a[c[x>>2]>>0]|0;if((c[p>>2]|0)==2)qc(j,f,26771,8);else{qc(j,f>>3,26747+(a[(c[x>>2]|0)+29>>0]<<3)|0,8);qc(c[o>>2]|0,a[c[x>>2]>>0]&7,29049,8)}c[t>>2]=1;while(1){j=c[o>>2]|0;if((c[t>>2]|0)>=(c[(c[n>>2]|0)+4604>>2]|0))break;qc(j,a[(c[x>>2]|0)+(c[t>>2]|0)>>0]|0,26771,8);c[t>>2]=(c[t>>2]|0)+1}l=_(a[(c[x>>2]|0)+29>>0]>>1,b[c[(c[n>>2]|0)+4724>>2]>>1]|0)|0;qc(j,a[(c[x>>2]|0)+8>>0]|0,(c[(c[(c[n>>2]|0)+4724>>2]|0)+12>>2]|0)+l|0,8);nf(r,m,c[(c[n>>2]|0)+4724>>2]|0,a[(c[x>>2]|0)+8>>0]|0);c[t>>2]=0;while(1){if((c[t>>2]|0)>=(b[(c[(c[n>>2]|0)+4724>>2]|0)+2>>1]|0))break;do if((a[(c[x>>2]|0)+8+((c[t>>2]|0)+1)>>0]|0)<4){j=c[o>>2]|0;f=c[t>>2]|0;if((a[(c[x>>2]|0)+8+((c[t>>2]|0)+1)>>0]|0)<=-4){qc(j,0,(c[(c[(c[n>>2]|0)+4724>>2]|0)+24>>2]|0)+(b[r+(f<<1)>>1]|0)|0,8);qc(c[o>>2]|0,0-(a[(c[x>>2]|0)+8+((c[t>>2]|0)+1)>>0]|0)-4|0,29057,8);break}else{qc(j,(a[(c[x>>2]|0)+8+(f+1)>>0]|0)+4|0,(c[(c[(c[n>>2]|0)+4724>>2]|0)+24>>2]|0)+(b[r+(c[t>>2]<<1)>>1]|0)|0,8);break}}else{qc(c[o>>2]|0,8,(c[(c[(c[n>>2]|0)+4724>>2]|0)+24>>2]|0)+(b[r+(c[t>>2]<<1)>>1]|0)|0,8);qc(c[o>>2]|0,(a[(c[x>>2]|0)+8+((c[t>>2]|0)+1)>>0]|0)-4|0,29057,8)}while(0);c[t>>2]=(c[t>>2]|0)+1}if((c[(c[n>>2]|0)+4604>>2]|0)==4)qc(c[o>>2]|0,a[(c[x>>2]|0)+31>>0]|0,29026,8);if((a[(c[x>>2]|0)+29>>0]|0)!=2){v=c[x>>2]|0;v=v+29|0;v=a[v>>0]|0;v=v<<24>>24;w=c[n>>2]|0;w=w+5800|0;c[w>>2]=v;w=c[o>>2]|0;x=c[x>>2]|0;x=x+34|0;x=a[x>>0]|0;x=x<<24>>24;qc(w,x,29034,8);i=y;return}c[s>>2]=1;if((c[p>>2]|0)==2?(c[(c[n>>2]|0)+5800>>2]|0)==2:0){c[q>>2]=(b[(c[x>>2]|0)+26>>1]|0)-(b[(c[n>>2]|0)+5804>>1]|0);if((c[q>>2]|0)<-8|(c[q>>2]|0)>11)c[q>>2]=0;else{c[q>>2]=(c[q>>2]|0)+9;c[s>>2]=0}qc(c[o>>2]|0,c[q>>2]|0,29096,8)}if(c[s>>2]|0){c[v>>2]=(b[(c[x>>2]|0)+26>>1]|0)/(c[(c[n>>2]|0)+4600>>2]>>1|0)|0;c[w>>2]=(b[(c[x>>2]|0)+26>>1]|0)-(_((c[v>>2]&65535)<<16>>16,(c[(c[n>>2]|0)+4600>>2]>>1&65535)<<16>>16)|0);qc(c[o>>2]|0,c[v>>2]|0,29064,8);qc(c[o>>2]|0,c[w>>2]|0,c[(c[n>>2]|0)+4716>>2]|0,8)}b[(c[n>>2]|0)+5804>>1]=b[(c[x>>2]|0)+26>>1]|0;qc(c[o>>2]|0,a[(c[x>>2]|0)+28>>0]|0,c[(c[n>>2]|0)+4720>>2]|0,8);qc(c[o>>2]|0,a[(c[x>>2]|0)+32>>0]|0,26812,8);c[u>>2]=0;while(1){if((c[u>>2]|0)>=(c[(c[n>>2]|0)+4604>>2]|0))break;qc(c[o>>2]|0,a[(c[x>>2]|0)+4+(c[u>>2]|0)>>0]|0,c[17620+(a[(c[x>>2]|0)+32>>0]<<2)>>2]|0,8);c[u>>2]=(c[u>>2]|0)+1}if(c[p>>2]|0){v=c[x>>2]|0;v=v+29|0;v=a[v>>0]|0;v=v<<24>>24;w=c[n>>2]|0;w=w+5800|0;c[w>>2]=v;w=c[o>>2]|0;x=c[x>>2]|0;x=x+34|0;x=a[x>>0]|0;x=x<<24>>24;qc(w,x,29034,8);i=y;return}qc(c[o>>2]|0,a[(c[x>>2]|0)+33>>0]|0,29017,8);v=c[x>>2]|0;v=v+29|0;v=a[v>>0]|0;v=v<<24>>24;w=c[n>>2]|0;w=w+5800|0;c[w>>2]=v;w=c[o>>2]|0;x=c[x>>2]|0;x=x+34|0;x=a[x>>0]|0;x=x<<24>>24;qc(w,x,29034,8);i=y;return}function Yd(b,e,f,g,h){b=b|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0;F=i;i=i+128|0;r=F+116|0;s=F+112|0;t=F+108|0;u=F+104|0;v=F+100|0;z=F+96|0;C=F+92|0;B=F+88|0;A=F+84|0;y=F+80|0;D=F+76|0;o=F+72|0;j=F+68|0;x=F+64|0;l=F+60|0;p=F+56|0;n=F+24|0;k=F+16|0;E=F+12|0;q=F+8|0;m=F+4|0;w=F;c[r>>2]=b;c[s>>2]=e;c[t>>2]=f;c[u>>2]=g;c[v>>2]=h;c[j>>2]=0;c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;e=Zd(n,n,d[29179]|0,2)|0;c[o>>2]=(c[o>>2]|0)+e;e=Zd(g+(c[z>>2]<<2)|0,n,d[29180]|0,1)|0;c[o>>2]=(c[o>>2]|0)+e;if(!(c[o>>2]|0))break;e=f+(c[z>>2]<<2)|0;c[e>>2]=(c[e>>2]|0)+1;c[C>>2]=0;while(1){if((c[C>>2]|0)>=16)continue a;c[(c[k>>2]|0)+(c[C>>2]<<2)>>2]=c[(c[k>>2]|0)+(c[C>>2]<<2)>>2]>>1;c[C>>2]=(c[C>>2]|0)+1}}c[k>>2]=(c[k>>2]|0)+64;c[z>>2]=(c[z>>2]|0)+1}c[l>>2]=2147483647;c[C>>2]=0;while(1){if((c[C>>2]|0)>=9)break;c[m>>2]=29361+((c[C>>2]|0)*18|0);c[p>>2]=d[29541+((c[s>>2]>>1)*9|0)+(c[C>>2]|0)>>0];c[z>>2]=0;while(1){if((c[z>>2]|0)>=(c[A>>2]|0))break;if((c[f+(c[z>>2]<<2)>>2]|0)>0)c[p>>2]=(c[p>>2]|0)+(d[(c[m>>2]|0)+17>>0]|0);else c[p>>2]=(c[p>>2]|0)+(d[(c[m>>2]|0)+(c[g+(c[z>>2]<<2)>>2]|0)>>0]|0);c[z>>2]=(c[z>>2]|0)+1}if((c[p>>2]|0)<(c[l>>2]|0)){c[l>>2]=c[p>>2];c[j>>2]=c[C>>2]}c[C>>2]=(c[C>>2]|0)+1}qc(c[r>>2]|0,c[j>>2]|0,29523+((c[s>>2]>>1)*9|0)|0,8);c[q>>2]=29181+((c[j>>2]|0)*18|0);c[z>>2]=0;while(1){if((c[z>>2]|0)>=(c[A>>2]|0))break;h=c[r>>2]|0;if(!(c[f+(c[z>>2]<<2)>>2]|0))qc(h,c[g+(c[z>>2]<<2)>>2]|0,c[q>>2]|0,8);else{qc(h,17,c[q>>2]|0,8);c[C>>2]=0;while(1){h=c[r>>2]|0;if((c[C>>2]|0)>=((c[f+(c[z>>2]<<2)>>2]|0)-1|0))break;qc(h,17,29343,8);c[C>>2]=(c[C>>2]|0)+1}qc(h,c[g+(c[z>>2]<<2)>>2]|0,29343,8)}c[z>>2]=(c[z>>2]|0)+1}c[z>>2]=0;while(1){if((c[z>>2]|0)>=(c[A>>2]|0))break;if((c[g+(c[z>>2]<<2)>>2]|0)>0)Pe(c[r>>2]|0,b+(c[z>>2]<<4<<2)|0);c[z>>2]=(c[z>>2]|0)+1}c[z>>2]=0;while(1){if((c[z>>2]|0)>=(c[A>>2]|0))break;b:do if((c[f+(c[z>>2]<<2)>>2]|0)>0){c[E>>2]=(c[u>>2]|0)+(c[z>>2]<<4);c[D>>2]=(c[f+(c[z>>2]<<2)>>2]|0)-1;c[C>>2]=0;while(1){if((c[C>>2]|0)>=16)break b;q=a[(c[E>>2]|0)+(c[C>>2]|0)>>0]|0;c[x>>2]=(((a[(c[E>>2]|0)+(c[C>>2]|0)>>0]|0)>0?q:0-q|0)&255)<<24>>24;c[B>>2]=c[D>>2];while(1){h=c[x>>2]|0;if((c[B>>2]|0)<=0)break;c[y>>2]=h>>c[B>>2]&1;qc(c[r>>2]|0,c[y>>2]|0,29015,8);c[B>>2]=(c[B>>2]|0)+-1}c[y>>2]=h&1;qc(c[r>>2]|0,c[y>>2]|0,29015,8);c[C>>2]=(c[C>>2]|0)+1}}while(0);c[z>>2]=(c[z>>2]|0)+1}Dd(c[r>>2]|0,c[u>>2]|0,c[v>>2]|0,c[s>>2]|0,c[t>>2]|0,g);na(c[w>>2]|0);i=F;return}function Zd(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0;n=i;i=i+32|0;m=n+24|0;f=n+20|0;g=n+16|0;h=n+12|0;j=n+8|0;k=n+4|0;l=n;c[f>>2]=a;c[g>>2]=b;c[h>>2]=d;c[j>>2]=e;c[k>>2]=0;while(1){if((c[k>>2]|0)>=(c[j>>2]|0)){f=6;break}c[l>>2]=(c[(c[g>>2]|0)+(c[k>>2]<<1<<2)>>2]|0)+(c[(c[g>>2]|0)+((c[k>>2]<<1)+1<<2)>>2]|0);if((c[l>>2]|0)>(c[h>>2]|0)){f=4;break}c[(c[f>>2]|0)+(c[k>>2]<<2)>>2]=c[l>>2];c[k>>2]=(c[k>>2]|0)+1}if((f|0)==4){c[m>>2]=1;m=c[m>>2]|0;i=n;return m|0}else if((f|0)==6){c[m>>2]=0;m=c[m>>2]|0;i=n;return m|0}return 0}function _d(b,d,e,f,g){b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;p=i;i=i+32|0;h=p+24|0;j=p+20|0;k=p+16|0;l=p+12|0;m=p+8|0;o=p+4|0;n=p;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;c[m>>2]=g;c[o>>2]=0;while(1){if((c[o>>2]|0)>=(c[m>>2]|0))break;Sf(c[(c[j>>2]|0)+(c[o>>2]<<2)>>2]|0)|0;e=0+((((Sf(c[(c[j>>2]|0)+(c[o>>2]<<2)>>2]|0)|0)-2090&65535)<<16>>16)*2251>>16)&255;a[(c[h>>2]|0)+(c[o>>2]|0)>>0]=e;if((a[(c[h>>2]|0)+(c[o>>2]|0)>>0]|0)<(a[c[k>>2]>>0]|0)){e=(c[h>>2]|0)+(c[o>>2]|0)|0;a[e>>0]=(a[e>>0]|0)+1<<24>>24}if((a[(c[h>>2]|0)+(c[o>>2]|0)>>0]|0)<=63)if((a[(c[h>>2]|0)+(c[o>>2]|0)>>0]|0)<0)f=0;else f=a[(c[h>>2]|0)+(c[o>>2]|0)>>0]|0;else f=63;a[(c[h>>2]|0)+(c[o>>2]|0)>>0]=f;if((c[o>>2]|0)==0&(c[l>>2]|0)==0){f=a[(c[h>>2]|0)+(c[o>>2]|0)>>0]|0;do if(((a[c[k>>2]>>0]|0)+-4|0)>63){if((f|0)>((a[c[k>>2]>>0]|0)+-4|0)){f=(a[c[k>>2]>>0]|0)+-4|0;break}if((a[(c[h>>2]|0)+(c[o>>2]|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1}i=p;return}function $d(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)<(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function ae(b,d,e,f,g){b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;q=i;i=i+32|0;h=q+28|0;j=q+24|0;k=q+20|0;l=q+16|0;m=q+12|0;p=q+8|0;o=q+4|0;n=q;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;c[m>>2]=g;c[p>>2]=0;while(1){if((c[p>>2]|0)>=(c[m>>2]|0))break;f=a[(c[j>>2]|0)+(c[p>>2]|0)>>0]|0;do if(!((c[p>>2]|0)==0&(c[l>>2]|0)==0)){c[o>>2]=f+-4;c[n>>2]=8+(a[c[k>>2]>>0]|0);f=c[o>>2]|0;if((c[o>>2]|0)>(c[n>>2]|0)){e=c[k>>2]|0;a[e>>0]=(a[e>>0]|0)+((f<<1)-(c[n>>2]|0));break}else{e=c[k>>2]|0;a[e>>0]=(a[e>>0]|0)+f;break}}else{e=(be(f,(a[c[k>>2]>>0]|0)-16|0)|0)&255;a[c[k>>2]>>0]=e}while(0);if((a[c[k>>2]>>0]|0)<=63)if((a[c[k>>2]>>0]|0)<0)f=0;else f=a[c[k>>2]>>0]|0;else f=63;a[c[k>>2]>>0]=f;e=Wf($d(((a[c[k>>2]>>0]<<16>>16)*29|0)+((a[c[k>>2]>>0]<<16>>16)*7281>>16)+2090|0,3967)|0)|0;c[(c[h>>2]|0)+(c[p>>2]<<2)>>2]=e;c[p>>2]=(c[p>>2]|0)+1}i=q;return}function be(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;f=i;i=i+16|0;e=f+4|0;d=f;c[e>>2]=a;c[d>>2]=b;i=f;return ((c[e>>2]|0)>(c[d>>2]|0)?c[e>>2]|0:c[d>>2]|0)|0}function ce(b,d){b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;j=i;i=i+16|0;e=j+12|0;f=j+8|0;h=j+4|0;g=j;c[e>>2]=b;c[f>>2]=d;c[g>>2]=0;c[h>>2]=0;while(1){if((c[h>>2]|0)>=(c[f>>2]|0))break;c[g>>2]=(a[(c[e>>2]|0)+(c[h>>2]|0)>>0]|0)+(c[g>>2]<<8);c[h>>2]=(c[h>>2]|0)+1}i=j;return c[g>>2]|0}function de(a,d,e,f,g){a=a|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0;o=i;i=i+32|0;h=o+20|0;j=o+16|0;k=o+12|0;l=o+8|0;m=o+4|0;n=o;c[h>>2]=a;c[j>>2]=d;c[k>>2]=e;c[l>>2]=f;c[m>>2]=g;c[n>>2]=0;while(1){if((c[n>>2]|0)>=(c[m>>2]|0))break;a=(b[(c[j>>2]|0)+(c[n>>2]<<1)>>1]|0)+((_(((b[(c[k>>2]|0)+(c[n>>2]<<1)>>1]|0)-(b[(c[j>>2]|0)+(c[n>>2]<<1)>>1]|0)&65535)<<16>>16,(c[l>>2]&65535)<<16>>16)|0)>>2)&65535;b[(c[h>>2]|0)+(c[n>>2]<<1)>>1]=a;c[n>>2]=(c[n>>2]|0)+1}i=o;return}function ee(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+48|0;g=m+36|0;h=m+32|0;j=m+28|0;l=m+16|0;k=m+8|0;e=m+4|0;f=m;c[g>>2]=a;c[h>>2]=b;c[j>>2]=d;c[e>>2]=0;c[f>>2]=0;if(!(c[(c[g>>2]|0)+12>>2]|0)){i=m;return}c[e>>2]=256-(c[(c[g>>2]|0)+8>>2]|0)<<10;c[f>>2]=c[e>>2]>>16;c[e>>2]=(c[e>>2]|0)-(c[f>>2]<<16);fe(l,k,c[f>>2]|0,c[e>>2]|0);if(((c[(c[g>>2]|0)+8>>2]|0)+(c[(c[g>>2]|0)+12>>2]|0)|0)<=256)if(((c[(c[g>>2]|0)+8>>2]|0)+(c[(c[g>>2]|0)+12>>2]|0)|0)<0)e=0;else e=(c[(c[g>>2]|0)+8>>2]|0)+(c[(c[g>>2]|0)+12>>2]|0)|0;else e=256;c[(c[g>>2]|0)+8>>2]=e;Nf(c[h>>2]|0,l,k,c[g>>2]|0,c[h>>2]|0,c[j>>2]|0,1);i=m;return}function fe(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0;m=i;i=i+32|0;f=m+20|0;g=m+16|0;h=m+12|0;j=m+8|0;l=m+4|0;k=m;c[f>>2]=a;c[g>>2]=b;c[h>>2]=d;c[j>>2]=e;if((c[h>>2]|0)>=4){l=c[f>>2]|0;c[l>>2]=c[4473];c[l+4>>2]=c[4474];c[l+8>>2]=c[4475];l=c[g>>2]|0;c[l>>2]=c[4484];c[l+4>>2]=c[4485];i=m;return}if((c[j>>2]|0)<=0){l=c[f>>2]|0;k=17844+((c[h>>2]|0)*12|0)|0;c[l>>2]=c[k>>2];c[l+4>>2]=c[k+4>>2];c[l+8>>2]=c[k+8>>2];l=c[g>>2]|0;k=17904+(c[h>>2]<<3)|0;c[l>>2]=c[k>>2];c[l+4>>2]=c[k+4>>2];i=m;return}d=(c[j>>2]|0)<32768;c[l>>2]=0;if(d){while(1){if((c[l>>2]|0)>=3)break;d=_((c[17844+(((c[h>>2]|0)+1|0)*12|0)+(c[l>>2]<<2)>>2]|0)-(c[17844+((c[h>>2]|0)*12|0)+(c[l>>2]<<2)>>2]|0)>>16,(c[j>>2]&65535)<<16>>16)|0;d=(c[17844+((c[h>>2]|0)*12|0)+(c[l>>2]<<2)>>2]|0)+(d+((_((c[17844+(((c[h>>2]|0)+1|0)*12|0)+(c[l>>2]<<2)>>2]|0)-(c[17844+((c[h>>2]|0)*12|0)+(c[l>>2]<<2)>>2]|0)&65535,(c[j>>2]&65535)<<16>>16)|0)>>16))|0;c[(c[f>>2]|0)+(c[l>>2]<<2)>>2]=d;c[l>>2]=(c[l>>2]|0)+1}c[k>>2]=0;while(1){if((c[k>>2]|0)>=2)break;l=_((c[17904+((c[h>>2]|0)+1<<3)+(c[k>>2]<<2)>>2]|0)-(c[17904+(c[h>>2]<<3)+(c[k>>2]<<2)>>2]|0)>>16,(c[j>>2]&65535)<<16>>16)|0;l=(c[17904+(c[h>>2]<<3)+(c[k>>2]<<2)>>2]|0)+(l+((_((c[17904+((c[h>>2]|0)+1<<3)+(c[k>>2]<<2)>>2]|0)-(c[17904+(c[h>>2]<<3)+(c[k>>2]<<2)>>2]|0)&65535,(c[j>>2]&65535)<<16>>16)|0)>>16))|0;c[(c[g>>2]|0)+(c[k>>2]<<2)>>2]=l;c[k>>2]=(c[k>>2]|0)+1}i=m;return}else{while(1){if((c[l>>2]|0)>=3)break;d=_((c[17844+(((c[h>>2]|0)+1|0)*12|0)+(c[l>>2]<<2)>>2]|0)-(c[17844+((c[h>>2]|0)*12|0)+(c[l>>2]<<2)>>2]|0)>>16,((c[j>>2]|0)-65536&65535)<<16>>16)|0;d=(c[17844+(((c[h>>2]|0)+1|0)*12|0)+(c[l>>2]<<2)>>2]|0)+(d+((_((c[17844+(((c[h>>2]|0)+1|0)*12|0)+(c[l>>2]<<2)>>2]|0)-(c[17844+((c[h>>2]|0)*12|0)+(c[l>>2]<<2)>>2]|0)&65535,((c[j>>2]|0)-65536&65535)<<16>>16)|0)>>16))|0;c[(c[f>>2]|0)+(c[l>>2]<<2)>>2]=d;c[l>>2]=(c[l>>2]|0)+1}c[k>>2]=0;while(1){if((c[k>>2]|0)>=2)break;l=_((c[17904+((c[h>>2]|0)+1<<3)+(c[k>>2]<<2)>>2]|0)-(c[17904+(c[h>>2]<<3)+(c[k>>2]<<2)>>2]|0)>>16,((c[j>>2]|0)-65536&65535)<<16>>16)|0;l=(c[17904+((c[h>>2]|0)+1<<3)+(c[k>>2]<<2)>>2]|0)+(l+((_((c[17904+((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|0,c[(c[n>>2]|0)+32>>2]|0,b[(c[n>>2]|0)+2>>1]|0);i=t;return}function he(e,f,g,h,j){e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0;r=i;i=i+32|0;k=r+24|0;l=r+20|0;m=r+16|0;n=r+12|0;s=r+28|0;o=r+8|0;p=r+4|0;q=r;c[k>>2]=e;c[l>>2]=f;c[m>>2]=g;c[n>>2]=h;b[s>>1]=j;c[p>>2]=0;c[o>>2]=(b[s>>1]|0)-1;while(1){if((c[o>>2]|0)<0)break;c[q>>2]=(_((c[p>>2]&65535)<<16>>16,d[(c[m>>2]|0)+(c[o>>2]|0)>>0]|0)|0)>>8;c[p>>2]=a[(c[l>>2]|0)+(c[o>>2]|0)>>0]<<10;f=c[p>>2]|0;if((c[p>>2]|0)<=0){if((f|0)<0)c[p>>2]=(c[p>>2]|0)+102}else c[p>>2]=f-102;s=_(c[p>>2]>>16,(c[n>>2]&65535)<<16>>16)|0;c[p>>2]=(c[q>>2]|0)+(s+((_(c[p>>2]&65535,(c[n>>2]&65535)<<16>>16)|0)>>16));b[(c[k>>2]|0)+(c[o>>2]<<1)>>1]=c[p>>2];c[o>>2]=(c[o>>2]|0)+-1}i=r;return}function ie(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+32|0;b=h+16|0;d=h+12|0;g=h+8|0;f=h+4|0;e=h;c[d>>2]=a;if((c[d>>2]|0)<=0){c[b>>2]=0;g=c[b>>2]|0;i=h;return g|0}je(c[d>>2]|0,f,e);if(c[f>>2]&1|0)c[g>>2]=32768;else c[g>>2]=46214;c[g>>2]=c[g>>2]>>(c[f>>2]>>1);a=_(c[g>>2]>>16,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0;c[g>>2]=(c[g>>2]|0)+(a+((_(c[g>>2]&65535,(((c[e>>2]&65535)<<16>>16)*213&65535)<<16>>16)|0)>>16));c[b>>2]=c[g>>2];g=c[b>>2]|0;i=h;return g|0}function je(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;e=i;i=i+16|0;h=e+12|0;j=e+8|0;f=e+4|0;g=e;c[h>>2]=a;c[j>>2]=b;c[f>>2]=d;c[g>>2]=ke(c[h>>2]|0)|0;c[c[j>>2]>>2]=c[g>>2];b=(le(c[h>>2]|0,24-(c[g>>2]|0)|0)|0)&127;c[c[f>>2]>>2]=b;i=e;return}function ke(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function le(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;e=k+20|0;d=k+16|0;f=k+12|0;j=k+8|0;h=k+4|0;g=k;c[d>>2]=a;c[f>>2]=b;c[j>>2]=c[d>>2];c[h>>2]=c[f>>2];c[g>>2]=0-(c[f>>2]|0);if(!(c[f>>2]|0)){c[e>>2]=c[d>>2];j=c[e>>2]|0;i=k;return j|0}d=c[j>>2]|0;if((c[f>>2]|0)<0){c[e>>2]=d<>2]|(c[j>>2]|0)>>>(32-(c[g>>2]|0)|0);j=c[e>>2]|0;i=k;return j|0}else{c[e>>2]=d<<32-(c[h>>2]|0)|(c[j>>2]|0)>>>(c[h>>2]|0);j=c[e>>2]|0;i=k;return j|0}return 0}function me(d,e,f,g,h,j,k,l,m,n,o,p,q,r,s){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;n=n|0;o=o|0;p=p|0;q=q|0;r=r|0;s=s|0;var t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0;T=i;i=i+112|0;t=T+100|0;u=T+96|0;B=T+92|0;C=T+88|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[y>>2]=65536;c[A>>2]=(c[B>>2]>>7)+1>>1;c[z>>2]=0;while(1){if((c[z>>2]|0)>=(c[(c[o>>2]|0)+4612>>2]|0))break;E=_(c[(c[r>>2]|0)+(c[z>>2]<<2)>>2]>>16,(c[A>>2]&65535)<<16>>16)|0;E=E+((_(c[(c[r>>2]|0)+(c[z>>2]<<2)>>2]&65535,(c[A>>2]&65535)<<16>>16)|0)>>16)|0;E=E+(_(c[(c[r>>2]|0)+(c[z>>2]<<2)>>2]|0,(c[A>>2]>>15)+1>>1)|0)|0;c[(c[s>>2]|0)+(c[z>>2]<<2)>>2]=E;c[z>>2]=(c[z>>2]|0)+1}c[(c[p>>2]|0)+4372>>2]=c[(c[x>>2]|0)+(c[v>>2]<<2)>>2];a:do if(c[(c[p>>2]|0)+4376>>2]|0){if(!(c[v>>2]|0)){E=_(c[B>>2]>>16,(c[w>>2]&65535)<<16>>16)|0;c[B>>2]=E+((_(c[B>>2]&65535,(c[w>>2]&65535)<<16>>16)|0)>>16)<<2}c[z>>2]=(c[(c[p>>2]|0)+4360>>2]|0)-(c[C>>2]|0)-2;while(1){if((c[z>>2]|0)>=(c[(c[p>>2]|0)+4360>>2]|0))break a;E=_(c[B>>2]>>16,b[(c[t>>2]|0)+(c[z>>2]<<1)>>1]|0)|0;E=E+((_(c[B>>2]&65535,b[(c[t>>2]|0)+(c[z>>2]<<1)>>1]|0)|0)>>16)|0;c[(c[u>>2]|0)+(c[z>>2]<<2)>>2]=E;c[z>>2]=(c[z>>2]|0)+1}}while(0);if((c[y>>2]|0)==65536){i=D;return}c[z>>2]=(c[(c[p>>2]|0)+4364>>2]|0)-(c[(c[o>>2]|0)+4616>>2]|0);while(1){if((c[z>>2]|0)>=(c[(c[p>>2]|0)+4364>>2]|0))break;E=_(c[y>>2]>>16,(c[(c[p>>2]|0)+1280+(c[z>>2]<<2)>>2]&65535)<<16>>16)|0;E=E+((_(c[y>>2]&65535,(c[(c[p>>2]|0)+1280+(c[z>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;E=E+(_(c[y>>2]|0,(c[(c[p>>2]|0)+1280+(c[z>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[p>>2]|0)+1280+(c[z>>2]<<2)>>2]=E;c[z>>2]=(c[z>>2]|0)+1}b:do if((c[q>>2]|0)==2?(c[(c[p>>2]|0)+4376>>2]|0)==0:0){c[z>>2]=(c[(c[p>>2]|0)+4360>>2]|0)-(c[C>>2]|0)-2;while(1){if((c[z>>2]|0)>=(c[(c[p>>2]|0)+4360>>2]|0))break b;E=_(c[y>>2]>>16,(c[(c[u>>2]|0)+(c[z>>2]<<2)>>2]&65535)<<16>>16)|0;E=E+((_(c[y>>2]&65535,(c[(c[u>>2]|0)+(c[z>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;E=E+(_(c[y>>2]|0,(c[(c[u>>2]|0)+(c[z>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[u>>2]|0)+(c[z>>2]<<2)>>2]=E;c[z>>2]=(c[z>>2]|0)+1}}while(0);E=_(c[y>>2]>>16,(c[(c[p>>2]|0)+4352>>2]&65535)<<16>>16)|0;E=E+((_(c[y>>2]&65535,(c[(c[p>>2]|0)+4352>>2]&65535)<<16>>16)|0)>>16)|0;E=E+(_(c[y>>2]|0,(c[(c[p>>2]|0)+4352>>2]>>15)+1>>1)|0)|0;c[(c[p>>2]|0)+4352>>2]=E;c[z>>2]=0;while(1){if((c[z>>2]|0)>=32)break;E=_(c[y>>2]>>16,(c[(c[p>>2]|0)+3840+(c[z>>2]<<2)>>2]&65535)<<16>>16)|0;E=E+((_(c[y>>2]&65535,(c[(c[p>>2]|0)+3840+(c[z>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;E=E+(_(c[y>>2]|0,(c[(c[p>>2]|0)+3840+(c[z>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[p>>2]|0)+3840+(c[z>>2]<<2)>>2]=E;c[z>>2]=(c[z>>2]|0)+1}c[z>>2]=0;while(1){if((c[z>>2]|0)>=16)break;E=_(c[y>>2]>>16,(c[(c[p>>2]|0)+4288+(c[z>>2]<<2)>>2]&65535)<<16>>16)|0;E=E+((_(c[y>>2]&65535,(c[(c[p>>2]|0)+4288+(c[z>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;E=E+(_(c[y>>2]|0,(c[(c[p>>2]|0)+4288+(c[z>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[p>>2]|0)+4288+(c[z>>2]<<2)>>2]=E;c[z>>2]=(c[z>>2]|0)+1}i=D;return}function oe(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0;h=i;i=i+48|0;f=h+32|0;n=h+28|0;d=h+24|0;j=h+20|0;g=h+16|0;k=h+12|0;m=h+8|0;l=h+4|0;e=h;c[n>>2]=a;c[d>>2]=b;b=c[n>>2]|0;c[j>>2]=(pe((c[n>>2]|0)>0?b:0-b|0)|0)-1;c[m>>2]=c[n>>2]<>2];c[k>>2]=536870911/(c[m>>2]>>16|0)|0;c[e>>2]=c[k>>2]<<16;b=_(c[m>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;c[l>>2]=536870912-(b+((_(c[m>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))<<3;b=_(c[l>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;b=(c[e>>2]|0)+(b+((_(c[l>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))|0;c[e>>2]=b+(_(c[l>>2]|0,(c[k>>2]>>15)+1>>1)|0);c[g>>2]=61-(c[j>>2]|0)-(c[d>>2]|0);b=c[g>>2]|0;if((c[g>>2]|0)>0)if((b|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];n=c[f>>2]|0;i=h;return n|0}else{c[f>>2]=0;n=c[f>>2]|0;i=h;return n|0}a=c[e>>2]|0;d=0-(c[g>>2]|0)|0;do if((-2147483648>>0-b|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>d|0)){b=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){b=2147483647>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>d|0)){b=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){b=-2147483648>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}while(0);c[f>>2]=b<<0-(c[g>>2]|0);n=c[f>>2]|0;i=h;return n|0}function pe(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function qe(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;h=i;i=i+48|0;f=h+40|0;q=h+36|0;p=h+32|0;j=h+28|0;l=h+24|0;k=h+20|0;g=h+16|0;m=h+12|0;n=h+8|0;o=h+4|0;e=h;c[q>>2]=a;c[p>>2]=b;c[j>>2]=d;b=c[q>>2]|0;c[l>>2]=(pe((c[q>>2]|0)>0?b:0-b|0)|0)-1;c[n>>2]=c[q>>2]<>2];b=c[p>>2]|0;c[k>>2]=(pe((c[p>>2]|0)>0?b:0-b|0)|0)-1;c[o>>2]=c[p>>2]<>2];c[m>>2]=536870911/(c[o>>2]>>16|0)|0;b=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=b+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16);b=c[n>>2]|0;a=c[o>>2]|0;d=c[e>>2]|0;d=yj(a|0,((a|0)<0)<<31>>31|0,d|0,((d|0)<0)<<31>>31|0)|0;d=nj(d|0,C|0,32)|0;c[n>>2]=b-(d<<3);d=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=(c[e>>2]|0)+(d+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16));c[g>>2]=29+(c[l>>2]|0)-(c[k>>2]|0)-(c[j>>2]|0);d=c[g>>2]|0;if((c[g>>2]|0)>=0)if((d|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];q=c[f>>2]|0;i=h;return q|0}else{c[f>>2]=0;q=c[f>>2]|0;i=h;return q|0}a=c[e>>2]|0;b=0-(c[g>>2]|0)|0;do if((-2147483648>>0-d|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>b|0)){d=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){d=2147483647>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>b|0)){d=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){d=-2147483648>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}while(0);c[f>>2]=d<<0-(c[g>>2]|0);q=c[f>>2]|0;i=h;return q|0}function re(d,e,f,g,h,j,k,l,m,n,o,p,q,r,s,t,u,v,w){d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;n=n|0;o=o|0;p=p|0;q=q|0;r=r|0;s=s|0;t=t|0;u=u|0;v=v|0;w=w|0;var x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ia=0,ja=0,ka=0,la=0,ma=0,na=0;ma=i;i=i+176|0;ka=ma+168|0;x=ma+164|0;F=ma+160|0;G=ma+156|0;H=ma+152|0;I=ma+148|0;J=ma+144|0;K=ma+140|0;L=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0)+((c[T>>2]|0)-1<<1)>>1]|0)|0)>>16));c[ha>>2]=c[(c[ka>>2]|0)+4288+((c[T>>2]|0)+0<<2)>>2];c[(c[ka>>2]|0)+4288+((c[T>>2]|0)+0<<2)>>2]=c[ia>>2];na=_(c[ia>>2]>>16,b[(c[L>>2]|0)+(c[T>>2]<<1)>>1]|0)|0;c[U>>2]=(c[U>>2]|0)+(na+((_(c[ia>>2]&65535,b[(c[L>>2]|0)+(c[T>>2]<<1)>>1]|0)|0)>>16));c[T>>2]=(c[T>>2]|0)+2}c[(c[ka>>2]|0)+4288+((c[D>>2]|0)-1<<2)>>2]=c[ha>>2];na=_(c[ha>>2]>>16,b[(c[L>>2]|0)+((c[D>>2]|0)-1<<1)>>1]|0)|0;c[U>>2]=(c[U>>2]|0)+(na+((_(c[ha>>2]&65535,b[(c[L>>2]|0)+((c[D>>2]|0)-1<<1)>>1]|0)|0)>>16));c[U>>2]=c[U>>2]<<1;na=_(c[(c[ka>>2]|0)+4352>>2]>>16,(c[z>>2]&65535)<<16>>16)|0;c[U>>2]=(c[U>>2]|0)+(na+((_(c[(c[ka>>2]|0)+4352>>2]&65535,(c[z>>2]&65535)<<16>>16)|0)>>16));na=_(c[(c[ka>>2]|0)+1280+((c[(c[ka>>2]|0)+4364>>2]|0)-1<<2)>>2]>>16,(c[A>>2]&65535)<<16>>16)|0;c[V>>2]=na+((_(c[(c[ka>>2]|0)+1280+((c[(c[ka>>2]|0)+4364>>2]|0)-1<<2)>>2]&65535,(c[A>>2]&65535)<<16>>16)|0)>>16);na=(c[V>>2]|0)+(_(c[(c[ka>>2]|0)+4352>>2]>>16,c[A>>2]>>16)|0)|0;c[V>>2]=na+((_(c[(c[ka>>2]|0)+4352>>2]&65535,c[A>>2]>>16)|0)>>16);c[ha>>2]=(c[P>>2]<<2)-(c[U>>2]|0);c[ha>>2]=(c[ha>>2]|0)-(c[V>>2]|0);if((c[M>>2]|0)>0){na=_((c[c[ga>>2]>>2]|0)+(c[(c[ga>>2]|0)+-8>>2]|0)>>16,(c[y>>2]&65535)<<16>>16)|0;c[W>>2]=na+((_((c[c[ga>>2]>>2]|0)+(c[(c[ga>>2]|0)+-8>>2]|0)&65535,(c[y>>2]&65535)<<16>>16)|0)>>16);na=(c[W>>2]|0)+(_(c[(c[ga>>2]|0)+-4>>2]>>16,c[y>>2]>>16)|0)|0;c[W>>2]=na+((_(c[(c[ga>>2]|0)+-4>>2]&65535,c[y>>2]>>16)|0)>>16);c[W>>2]=c[W>>2]<<1;c[ga>>2]=(c[ga>>2]|0)+4;c[ia>>2]=(c[Q>>2]|0)-(c[W>>2]|0);c[ha>>2]=(c[ia>>2]|0)+(c[ha>>2]<<1);c[ha>>2]=(c[ha>>2]>>2)+1>>1}else c[ha>>2]=(c[ha>>2]>>1)+1>>1;c[ba>>2]=(c[(c[F>>2]|0)+(c[S>>2]<<2)>>2]|0)-(c[ha>>2]|0);if((c[(c[ka>>2]|0)+4368>>2]|0)<0)c[ba>>2]=0-(c[ba>>2]|0);if((c[ba>>2]|0)>30720)m=30720;else m=(c[ba>>2]|0)<-31744?-31744:c[ba>>2]|0;c[ba>>2]=m;c[$>>2]=(c[ba>>2]|0)-(c[C>>2]|0);c[Z>>2]=c[$>>2]>>10;m=c[Z>>2]|0;do if((c[Z>>2]|0)<=0){if(!m){c[$>>2]=c[C>>2];c[aa>>2]=(c[$>>2]|0)+944;c[ca>>2]=_((c[$>>2]&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0;c[da>>2]=_((c[aa>>2]&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0;break}if((c[Z>>2]|0)==-1){c[aa>>2]=c[C>>2];c[$>>2]=(c[aa>>2]|0)-944;c[ca>>2]=_((0-(c[$>>2]|0)&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0;c[da>>2]=_((c[aa>>2]&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0;break}else{c[$>>2]=(c[Z>>2]<<10)+80;c[$>>2]=(c[$>>2]|0)+(c[C>>2]|0);c[aa>>2]=(c[$>>2]|0)+1024;c[ca>>2]=_((0-(c[$>>2]|0)&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0;c[da>>2]=_((0-(c[aa>>2]|0)&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0;break}}else{c[$>>2]=(m<<10)-80;c[$>>2]=(c[$>>2]|0)+(c[C>>2]|0);c[aa>>2]=(c[$>>2]|0)+1024;c[ca>>2]=_((c[$>>2]&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0;c[da>>2]=_((c[aa>>2]&65535)<<16>>16,(c[B>>2]&65535)<<16>>16)|0}while(0);c[ea>>2]=(c[ba>>2]|0)-(c[$>>2]|0);c[ca>>2]=(c[ca>>2]|0)+(_((c[ea>>2]&65535)<<16>>16,(c[ea>>2]&65535)<<16>>16)|0);c[ea>>2]=(c[ba>>2]|0)-(c[aa>>2]|0);c[da>>2]=(c[da>>2]|0)+(_((c[ea>>2]&65535)<<16>>16,(c[ea>>2]&65535)<<16>>16)|0);if((c[da>>2]|0)<(c[ca>>2]|0))c[$>>2]=c[aa>>2];a[(c[G>>2]|0)+(c[S>>2]|0)>>0]=(c[$>>2]>>9)+1>>1;c[R>>2]=c[$>>2]<<4;if((c[(c[ka>>2]|0)+4368>>2]|0)<0)c[R>>2]=0-(c[R>>2]|0);c[O>>2]=(c[R>>2]|0)+(c[Q>>2]<<1);c[ja>>2]=(c[O>>2]|0)+(c[P>>2]<<4);na=_(c[ja>>2]>>16,(c[N>>2]&65535)<<16>>16)|0;na=na+((_(c[ja>>2]&65535,(c[N>>2]&65535)<<16>>16)|0)>>16)|0;if(((na+(_(c[ja>>2]|0,(c[N>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<=32767){na=_(c[ja>>2]>>16,(c[N>>2]&65535)<<16>>16)|0;na=na+((_(c[ja>>2]&65535,(c[N>>2]&65535)<<16>>16)|0)>>16)|0;if(((na+(_(c[ja>>2]|0,(c[N>>2]>>15)+1>>1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=0,ga=0,ha=0;ca=i;i=i+272|0;S=ca+264|0;T=ca+260|0;x=ca+256|0;y=ca+252|0;W=ca+248|0;z=ca+244|0;A=ca+240|0;B=ca+236|0;C=ca+232|0;D=ca+228|0;t=ca+224|0;u=ca+220|0;U=ca+216|0;v=ca+212|0;w=ca+208|0;Z=ca+204|0;M=ca+200|0;N=ca+196|0;Q=ca+192|0;I=ca+188|0;K=ca+184|0;R=ca+180|0;$=ca+176|0;P=ca+172|0;Y=ca+168|0;F=ca+164|0;G=ca+160|0;E=ca+156|0;ba=ca+152|0;H=ca+148|0;O=ca+144|0;J=ca+140|0;X=ca+136|0;aa=ca+132|0;V=ca+128|0;L=ca;c[S>>2]=d;c[T>>2]=e;c[x>>2]=f;c[y>>2]=g;c[W>>2]=h;c[z>>2]=j;c[A>>2]=k;c[B>>2]=l;c[C>>2]=m;c[D>>2]=n;c[t>>2]=o;c[u>>2]=p;c[U>>2]=q;c[v>>2]=r;c[w>>2]=s;c[N>>2]=c[(c[T>>2]|0)+4356>>2];g=c[(c[S>>2]|0)+4652>>2]|0;c[V>>2]=ia()|0;k=i;i=i+((1*(g*1168|0)|0)+15&-16)|0;oj(k|0,0,(c[(c[S>>2]|0)+4652>>2]|0)*1168|0)|0;c[M>>2]=0;while(1){if((c[M>>2]|0)>=(c[(c[S>>2]|0)+4652>>2]|0))break;c[aa>>2]=k+((c[M>>2]|0)*1168|0);c[(c[aa>>2]|0)+1156>>2]=(c[M>>2]|0)+(a[(c[x>>2]|0)+34>>0]|0)&3;c[(c[aa>>2]|0)+1160>>2]=c[(c[aa>>2]|0)+1156>>2];c[(c[aa>>2]|0)+1164>>2]=0;c[(c[aa>>2]|0)+1152>>2]=c[(c[T>>2]|0)+4352>>2];c[(c[aa>>2]|0)+960>>2]=c[(c[T>>2]|0)+1280+((c[(c[S>>2]|0)+4616>>2]|0)-1<<2)>>2];l=c[aa>>2]|0;p=(c[T>>2]|0)+3840|0;m=l+128|0;do{c[l>>2]=c[p>>2];l=l+4|0;p=p+4|0}while((l|0)<(m|0));l=(c[aa>>2]|0)+1088|0;p=(c[T>>2]|0)+4288|0;m=l+64|0;do{c[l>>2]=c[p>>2];l=l+4|0;p=p+4|0}while((l|0)<(m|0));c[M>>2]=(c[M>>2]|0)+1}c[O>>2]=b[24558+(a[(c[x>>2]|0)+29>>0]>>1<<2)+(a[(c[x>>2]|0)+30>>0]<<1)>>1];c[P>>2]=0;c[Y>>2]=te(32,c[(c[S>>2]|0)+4612>>2]|0)|0;a:do if((a[(c[x>>2]|0)+29>>0]|0)!=2){if((c[N>>2]|0)>0)c[Y>>2]=te(c[Y>>2]|0,(c[N>>2]|0)-2-1|0)|0}else{c[M>>2]=0;while(1){if((c[M>>2]|0)>=(c[(c[S>>2]|0)+4604>>2]|0))break a;c[Y>>2]=te(c[Y>>2]|0,(c[(c[U>>2]|0)+(c[M>>2]<<2)>>2]|0)-2-1|0)|0;c[M>>2]=(c[M>>2]|0)+1}}while(0);if((a[(c[x>>2]|0)+31>>0]|0)==4)c[I>>2]=0;else c[I>>2]=1;l=i;i=i+((1*((c[(c[S>>2]|0)+4616>>2]|0)+(c[(c[S>>2]|0)+4608>>2]|0)<<2)|0)+15&-16)|0;p=i;i=i+((1*((c[(c[S>>2]|0)+4616>>2]|0)+(c[(c[S>>2]|0)+4608>>2]|0)<<1)|0)+15&-16)|0;m=i;i=i+((1*(c[(c[S>>2]|0)+4612>>2]<<2)|0)+15&-16)|0;c[ba>>2]=(c[T>>2]|0)+(c[(c[S>>2]|0)+4616>>2]<<1);c[(c[T>>2]|0)+4364>>2]=c[(c[S>>2]|0)+4616>>2];c[(c[T>>2]|0)+4360>>2]=c[(c[S>>2]|0)+4616>>2];c[R>>2]=0;c[M>>2]=0;while(1){if((c[M>>2]|0)>=(c[(c[S>>2]|0)+4604>>2]|0))break;c[F>>2]=(c[z>>2]|0)+((c[M>>2]>>1|1-(c[I>>2]|0))<<4<<1);c[G>>2]=(c[A>>2]|0)+((c[M>>2]|0)*5<<1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>>2]}c[M>>2]=(c[M>>2]|0)+1}c[aa>>2]=k+((c[K>>2]|0)*1168|0);a[(c[x>>2]|0)+34>>0]=c[(c[aa>>2]|0)+1160>>2];c[$>>2]=(c[P>>2]|0)+(c[Y>>2]|0);c[X>>2]=c[(c[u>>2]|0)+((c[(c[S>>2]|0)+4604>>2]|0)-1<<2)>>2]>>6;c[Z>>2]=0;while(1){if((c[Z>>2]|0)>=(c[Y>>2]|0))break;c[$>>2]=(c[$>>2]|0)-1&31;a[(c[W>>2]|0)+((c[Z>>2]|0)-(c[Y>>2]|0))>>0]=(c[(c[aa>>2]|0)+576+(c[$>>2]<<2)>>2]>>9)+1>>1;ha=_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]>>16,(c[X>>2]&65535)<<16>>16)|0;ha=ha+((_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]&65535,(c[X>>2]&65535)<<16>>16)|0)>>16)|0;if(((ha+(_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]|0,(c[X>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<=32767){ha=_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]>>16,(c[X>>2]&65535)<<16>>16)|0;ha=ha+((_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]&65535,(c[X>>2]&65535)<<16>>16)|0)>>16)|0;if(((ha+(_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]|0,(c[X>>2]>>15)+1>>1)|0)>>7)+1>>1|0)<-32768)l=-32768;else{l=_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]>>16,(c[X>>2]&65535)<<16>>16)|0;l=l+((_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]&65535,(c[X>>2]&65535)<<16>>16)|0)>>16)|0;l=(l+(_(c[(c[aa>>2]|0)+704+(c[$>>2]<<2)>>2]|0,(c[X>>2]>>15)+1>>1)|0)>>7)+1>>1}}else l=32767;b[(c[ba>>2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>16,(c[D>>2]&65535)<<16>>16)|0;c[H>>2]=M+((_(c[H>>2]&65535,(c[D>>2]&65535)<<16>>16)|0)>>16)<<2}c[F>>2]=(c[(c[s>>2]|0)+4360>>2]|0)-(c[J>>2]|0)-2;while(1){if((c[F>>2]|0)>=(c[(c[s>>2]|0)+4360>>2]|0))break a;M=_(c[H>>2]>>16,b[(c[z>>2]|0)+(c[F>>2]<<1)>>1]|0)|0;M=M+((_(c[H>>2]&65535,b[(c[z>>2]|0)+(c[F>>2]<<1)>>1]|0)|0)>>16)|0;c[(c[A>>2]|0)+(c[F>>2]<<2)>>2]=M;c[F>>2]=(c[F>>2]|0)+1}}while(0);if((c[E>>2]|0)==65536){i=L;return}c[F>>2]=(c[(c[s>>2]|0)+4364>>2]|0)-(c[(c[r>>2]|0)+4616>>2]|0);while(1){if((c[F>>2]|0)>=(c[(c[s>>2]|0)+4364>>2]|0))break;M=_(c[E>>2]>>16,(c[(c[s>>2]|0)+1280+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0;M=M+((_(c[E>>2]&65535,(c[(c[s>>2]|0)+1280+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;M=M+(_(c[E>>2]|0,(c[(c[s>>2]|0)+1280+(c[F>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[s>>2]|0)+1280+(c[F>>2]<<2)>>2]=M;c[F>>2]=(c[F>>2]|0)+1}b:do if((c[u>>2]|0)==2?(c[(c[s>>2]|0)+4376>>2]|0)==0:0){c[F>>2]=(c[(c[s>>2]|0)+4360>>2]|0)-(c[J>>2]|0)-2;while(1){if((c[F>>2]|0)>=((c[(c[s>>2]|0)+4360>>2]|0)-(c[v>>2]|0)|0))break b;M=_(c[E>>2]>>16,(c[(c[A>>2]|0)+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0;M=M+((_(c[E>>2]&65535,(c[(c[A>>2]|0)+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;M=M+(_(c[E>>2]|0,(c[(c[A>>2]|0)+(c[F>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[A>>2]|0)+(c[F>>2]<<2)>>2]=M;c[F>>2]=(c[F>>2]|0)+1}}while(0);c[I>>2]=0;while(1){if((c[I>>2]|0)>=(c[C>>2]|0))break;c[K>>2]=(c[w>>2]|0)+((c[I>>2]|0)*1168|0);M=_(c[E>>2]>>16,(c[(c[K>>2]|0)+1152>>2]&65535)<<16>>16)|0;M=M+((_(c[E>>2]&65535,(c[(c[K>>2]|0)+1152>>2]&65535)<<16>>16)|0)>>16)|0;M=M+(_(c[E>>2]|0,(c[(c[K>>2]|0)+1152>>2]>>15)+1>>1)|0)|0;c[(c[K>>2]|0)+1152>>2]=M;c[F>>2]=0;while(1){if((c[F>>2]|0)>=32)break;M=_(c[E>>2]>>16,(c[(c[K>>2]|0)+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0;M=M+((_(c[E>>2]&65535,(c[(c[K>>2]|0)+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;M=M+(_(c[E>>2]|0,(c[(c[K>>2]|0)+(c[F>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[K>>2]|0)+(c[F>>2]<<2)>>2]=M;c[F>>2]=(c[F>>2]|0)+1}c[F>>2]=0;while(1){if((c[F>>2]|0)>=16)break;M=_(c[E>>2]>>16,(c[(c[K>>2]|0)+1088+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0;M=M+((_(c[E>>2]&65535,(c[(c[K>>2]|0)+1088+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;M=M+(_(c[E>>2]|0,(c[(c[K>>2]|0)+1088+(c[F>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[K>>2]|0)+1088+(c[F>>2]<<2)>>2]=M;c[F>>2]=(c[F>>2]|0)+1}c[F>>2]=0;while(1){if((c[F>>2]|0)>=32)break;M=_(c[E>>2]>>16,(c[(c[K>>2]|0)+832+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0;M=M+((_(c[E>>2]&65535,(c[(c[K>>2]|0)+832+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;M=M+(_(c[E>>2]|0,(c[(c[K>>2]|0)+832+(c[F>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[K>>2]|0)+832+(c[F>>2]<<2)>>2]=M;M=_(c[E>>2]>>16,(c[(c[K>>2]|0)+960+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0;M=M+((_(c[E>>2]&65535,(c[(c[K>>2]|0)+960+(c[F>>2]<<2)>>2]&65535)<<16>>16)|0)>>16)|0;M=M+(_(c[E>>2]|0,(c[(c[K>>2]|0)+960+(c[F>>2]<<2)>>2]>>15)+1>>1)|0)|0;c[(c[K>>2]|0)+960+(c[F>>2]<<2)>>2]=M;c[F>>2]=(c[F>>2]|0)+1}c[I>>2]=(c[I>>2]|0)+1}i=L;return}function ve(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0;h=i;i=i+48|0;f=h+32|0;n=h+28|0;d=h+24|0;j=h+20|0;g=h+16|0;k=h+12|0;m=h+8|0;l=h+4|0;e=h;c[n>>2]=a;c[d>>2]=b;b=c[n>>2]|0;c[j>>2]=(we((c[n>>2]|0)>0?b:0-b|0)|0)-1;c[m>>2]=c[n>>2]<>2];c[k>>2]=536870911/(c[m>>2]>>16|0)|0;c[e>>2]=c[k>>2]<<16;b=_(c[m>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;c[l>>2]=536870912-(b+((_(c[m>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))<<3;b=_(c[l>>2]>>16,(c[k>>2]&65535)<<16>>16)|0;b=(c[e>>2]|0)+(b+((_(c[l>>2]&65535,(c[k>>2]&65535)<<16>>16)|0)>>16))|0;c[e>>2]=b+(_(c[l>>2]|0,(c[k>>2]>>15)+1>>1)|0);c[g>>2]=61-(c[j>>2]|0)-(c[d>>2]|0);b=c[g>>2]|0;if((c[g>>2]|0)>0)if((b|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];n=c[f>>2]|0;i=h;return n|0}else{c[f>>2]=0;n=c[f>>2]|0;i=h;return n|0}a=c[e>>2]|0;d=0-(c[g>>2]|0)|0;do if((-2147483648>>0-b|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>d|0)){b=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){b=2147483647>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>d|0)){b=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){b=-2147483648>>0-(c[g>>2]|0);break}else{b=c[e>>2]|0;break}}while(0);c[f>>2]=b<<0-(c[g>>2]|0);n=c[f>>2]|0;i=h;return n|0}function we(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;if(!(c[b>>2]|0)){a=32;i=d;return a|0}a=32-(32-(aa(c[b>>2]|0)|0))|0;i=d;return a|0}function xe(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;h=i;i=i+48|0;f=h+40|0;q=h+36|0;p=h+32|0;j=h+28|0;l=h+24|0;k=h+20|0;g=h+16|0;m=h+12|0;n=h+8|0;o=h+4|0;e=h;c[q>>2]=a;c[p>>2]=b;c[j>>2]=d;b=c[q>>2]|0;c[l>>2]=(we((c[q>>2]|0)>0?b:0-b|0)|0)-1;c[n>>2]=c[q>>2]<>2];b=c[p>>2]|0;c[k>>2]=(we((c[p>>2]|0)>0?b:0-b|0)|0)-1;c[o>>2]=c[p>>2]<>2];c[m>>2]=536870911/(c[o>>2]>>16|0)|0;b=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=b+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16);b=c[n>>2]|0;a=c[o>>2]|0;d=c[e>>2]|0;d=yj(a|0,((a|0)<0)<<31>>31|0,d|0,((d|0)<0)<<31>>31|0)|0;d=nj(d|0,C|0,32)|0;c[n>>2]=b-(d<<3);d=_(c[n>>2]>>16,(c[m>>2]&65535)<<16>>16)|0;c[e>>2]=(c[e>>2]|0)+(d+((_(c[n>>2]&65535,(c[m>>2]&65535)<<16>>16)|0)>>16));c[g>>2]=29+(c[l>>2]|0)-(c[k>>2]|0)-(c[j>>2]|0);d=c[g>>2]|0;if((c[g>>2]|0)>=0)if((d|0)<32){c[f>>2]=c[e>>2]>>c[g>>2];q=c[f>>2]|0;i=h;return q|0}else{c[f>>2]=0;q=c[f>>2]|0;i=h;return q|0}a=c[e>>2]|0;b=0-(c[g>>2]|0)|0;do if((-2147483648>>0-d|0)>(2147483647>>0-(c[g>>2]|0)|0)){if((a|0)>(-2147483648>>b|0)){d=-2147483648>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(2147483647>>0-(c[g>>2]|0)|0)){d=2147483647>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}else{if((a|0)>(2147483647>>b|0)){d=2147483647>>0-(c[g>>2]|0);break}if((c[e>>2]|0)<(-2147483648>>0-(c[g>>2]|0)|0)){d=-2147483648>>0-(c[g>>2]|0);break}else{d=c[e>>2]|0;break}}while(0);c[f>>2]=d<<0-(c[g>>2]|0);q=c[f>>2]|0;i=h;return q|0} + function Uh(a,b,d){a=a|0;b=+b;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;e=l+16|0;f=l+12|0;h=l+8|0;k=l+4|0;j=l;c[e>>2]=a;g[f>>2]=b;c[h>>2]=d;c[j>>2]=c[h>>2]&65532;c[k>>2]=0;while(1){if((c[k>>2]|0)>=(c[j>>2]|0))break;d=(c[e>>2]|0)+((c[k>>2]|0)+0<<2)|0;g[d>>2]=+g[d>>2]*+g[f>>2];d=(c[e>>2]|0)+((c[k>>2]|0)+1<<2)|0;g[d>>2]=+g[d>>2]*+g[f>>2];d=(c[e>>2]|0)+((c[k>>2]|0)+2<<2)|0;g[d>>2]=+g[d>>2]*+g[f>>2];d=(c[e>>2]|0)+((c[k>>2]|0)+3<<2)|0;g[d>>2]=+g[d>>2]*+g[f>>2];c[k>>2]=(c[k>>2]|0)+4}while(1){if((c[k>>2]|0)>=(c[h>>2]|0))break;j=(c[e>>2]|0)+(c[k>>2]<<2)|0;g[j>>2]=+g[j>>2]*+g[f>>2];c[k>>2]=(c[k>>2]|0)+1}i=l;return}function Vh(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0.0;p=i;i=i+176|0;e=p+168|0;f=p+164|0;h=p+160|0;m=p+156|0;n=p+152|0;j=p+16|0;k=p+8|0;l=p+4|0;o=p;c[e>>2]=a;c[f>>2]=b;c[h>>2]=d;c[m>>2]=0;while(1){if((c[m>>2]|0)>=((c[h>>2]|0)+1|0))break;q=+g[(c[f>>2]|0)+(c[m>>2]<<2)>>2];g[j+(c[m>>2]<<3)+4>>2]=q;g[j+(c[m>>2]<<3)>>2]=q;c[m>>2]=(c[m>>2]|0)+1}c[m>>2]=0;while(1){if((c[m>>2]|0)>=(c[h>>2]|0))break;g[o>>2]=-+g[j+((c[m>>2]|0)+1<<3)>>2]/(+g[j+4>>2]>9.999999717180685e-10?+g[j+4>>2]:9.999999717180685e-10);g[(c[e>>2]|0)+(c[m>>2]<<2)>>2]=+g[o>>2];c[n>>2]=0;while(1){if((c[n>>2]|0)>=((c[h>>2]|0)-(c[m>>2]|0)|0))break;g[k>>2]=+g[j+((c[n>>2]|0)+(c[m>>2]|0)+1<<3)>>2];g[l>>2]=+g[j+(c[n>>2]<<3)+4>>2];g[j+((c[n>>2]|0)+(c[m>>2]|0)+1<<3)>>2]=+g[k>>2]+ +g[l>>2]*+g[o>>2];g[j+(c[n>>2]<<3)+4>>2]=+g[l>>2]+ +g[k>>2]*+g[o>>2];c[n>>2]=(c[n>>2]|0)+1}c[m>>2]=(c[m>>2]|0)+1}i=p;return +(+g[j+4>>2])}function Wh(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0;o=i;i=i+32|0;f=o+24|0;h=o+20|0;j=o+16|0;k=o+12|0;n=o+8|0;l=o+4|0;m=o;c[f>>2]=a;c[h>>2]=b;c[j>>2]=d;c[k>>2]=e;c[l>>2]=0;while(1){if((c[l>>2]|0)>=(c[k>>2]|0))break;c[(c[h>>2]|0)+(c[l>>2]<<2)>>2]=c[l>>2];c[l>>2]=(c[l>>2]|0)+1}c[l>>2]=1;while(1){if((c[l>>2]|0)>=(c[k>>2]|0))break;g[n>>2]=+g[(c[f>>2]|0)+(c[l>>2]<<2)>>2];c[m>>2]=(c[l>>2]|0)-1;while(1){if((c[m>>2]|0)<0)break;if(!(+g[n>>2]>+g[(c[f>>2]|0)+(c[m>>2]<<2)>>2]))break;g[(c[f>>2]|0)+((c[m>>2]|0)+1<<2)>>2]=+g[(c[f>>2]|0)+(c[m>>2]<<2)>>2];c[(c[h>>2]|0)+((c[m>>2]|0)+1<<2)>>2]=c[(c[h>>2]|0)+(c[m>>2]<<2)>>2];c[m>>2]=(c[m>>2]|0)+-1}g[(c[f>>2]|0)+((c[m>>2]|0)+1<<2)>>2]=+g[n>>2];c[(c[h>>2]|0)+((c[m>>2]|0)+1<<2)>>2]=c[l>>2];c[l>>2]=(c[l>>2]|0)+1}c[l>>2]=c[k>>2];while(1){if((c[l>>2]|0)>=(c[j>>2]|0))break;g[n>>2]=+g[(c[f>>2]|0)+(c[l>>2]<<2)>>2];if(+g[n>>2]>+g[(c[f>>2]|0)+((c[k>>2]|0)-1<<2)>>2]){c[m>>2]=(c[k>>2]|0)-2;while(1){if((c[m>>2]|0)<0)break;if(!(+g[n>>2]>+g[(c[f>>2]|0)+(c[m>>2]<<2)>>2]))break;g[(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<<2)>>2])f=1.0;else{e=_(c[r>>2]|0,c[k>>2]|0)|0;f=+g[(c[x>>2]|0)+(e<<2)>>2]}if(!(-1.0>f)){e=_(c[r>>2]|0,c[k>>2]|0)|0;if(1.0<+g[(c[x>>2]|0)+(e<<2)>>2])f=1.0;else{e=_(c[r>>2]|0,c[k>>2]|0)|0;f=+g[(c[x>>2]|0)+(e<<2)>>2]}}else f=-1.0;e=_(c[r>>2]|0,c[k>>2]|0)|0;g[(c[x>>2]|0)+(e<<2)>>2]=f;c[r>>2]=(c[r>>2]|0)+1}}while(0);c[o>>2]=c[q>>2]}while((c[o>>2]|0)!=(c[j>>2]|0));if((z|0)==23){z=0;g[m>>2]=0.0}g[(c[l>>2]|0)+(c[n>>2]<<2)>>2]=+g[m>>2];c[n>>2]=(c[n>>2]|0)+1}i=A;return}function Yh(b,e){b=b|0;e=e|0;var f=0,g=0,h=0,j=0;j=i;i=i+16|0;f=j+8|0;g=j+4|0;h=j;c[g>>2]=b;c[h>>2]=e;e=c[g>>2]|0;if((c[g>>2]|0)<252){a[c[h>>2]>>0]=e;c[f>>2]=1;h=c[f>>2]|0;i=j;return h|0}else{a[c[h>>2]>>0]=252+(e&3);a[(c[h>>2]|0)+1>>0]=(c[g>>2]|0)-(d[c[h>>2]>>0]|0)>>2;c[f>>2]=2;h=c[f>>2]|0;i=j;return h|0}return 0}function Zh(a,b){a=a|0;b=b|0;var e=0,f=0,g=0,h=0;h=i;i=i+16|0;e=h+8|0;f=h+4|0;g=h;c[e>>2]=a;c[f>>2]=b;b=d[c[e>>2]>>0]|0;if((d[c[e>>2]>>0]|0)&128|0){c[g>>2]=b>>3&3;c[g>>2]=(c[f>>2]<>2]|0)/400|0;g=c[g>>2]|0;i=h;return g|0}a=d[c[e>>2]>>0]|0;if((b&96|0)!=96){c[g>>2]=a>>3&3;b=c[f>>2]|0;if((c[g>>2]|0)==3){c[g>>2]=(b*60|0)/1e3|0;g=c[g>>2]|0;i=h;return g|0}else{c[g>>2]=(b<>2]|0)/100|0;g=c[g>>2]|0;i=h;return g|0}}else{b=c[f>>2]|0;if(a&8|0)b=(b|0)/50|0;else b=(b|0)/100|0;c[g>>2]=b;g=c[g>>2]|0;i=h;return g|0}return 0}function _h(e,f,g,h,j,k,l,m){e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;var n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0;J=i;i=i+80|0;n=J+72|0;o=J+68|0;p=J+64|0;q=J+60|0;r=J+56|0;s=J+52|0;t=J+48|0;u=J+44|0;v=J+40|0;C=J+36|0;w=J+32|0;z=J+28|0;x=J+24|0;y=J+77|0;H=J+76|0;B=J+20|0;D=J+16|0;F=J+12|0;A=J+8|0;E=J+4|0;G=J;c[o>>2]=e;c[p>>2]=f;c[q>>2]=g;c[r>>2]=h;c[s>>2]=j;c[t>>2]=k;c[u>>2]=l;c[v>>2]=m;c[F>>2]=0;c[A>>2]=c[o>>2];if(!(c[t>>2]|0)){c[n>>2]=-1;I=c[n>>2]|0;i=J;return I|0}c[B>>2]=Zh(c[o>>2]|0,48e3)|0;c[x>>2]=0;k=c[o>>2]|0;c[o>>2]=k+1;a[H>>0]=a[k>>0]|0;c[p>>2]=(c[p>>2]|0)+-1;c[D>>2]=c[p>>2];a:do switch(d[H>>0]&3|0){case 0:{c[z>>2]=1;break}case 1:{c[z>>2]=2;c[x>>2]=1;if(!(c[q>>2]|0)){if(!(c[p>>2]&1)){c[D>>2]=(c[p>>2]|0)/2|0;b[c[t>>2]>>1]=c[D>>2];break a}c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}break}case 2:{c[z>>2]=2;c[w>>2]=$h(c[o>>2]|0,c[p>>2]|0,c[t>>2]|0)|0;c[p>>2]=(c[p>>2]|0)-(c[w>>2]|0);if((b[c[t>>2]>>1]|0)>=0?(b[c[t>>2]>>1]|0)<=(c[p>>2]|0):0){c[o>>2]=(c[o>>2]|0)+(c[w>>2]|0);c[D>>2]=(c[p>>2]|0)-(b[c[t>>2]>>1]|0);break a}c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}default:{if((c[p>>2]|0)<1){c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}k=c[o>>2]|0;c[o>>2]=k+1;a[y>>0]=a[k>>0]|0;c[z>>2]=d[y>>0]&63;if((c[z>>2]|0)>0?(_(c[B>>2]|0,c[z>>2]|0)|0)<=5760:0){c[p>>2]=(c[p>>2]|0)+-1;b:do if(d[y>>0]&64|0){while(1){if((c[p>>2]|0)<=0)break;k=c[o>>2]|0;c[o>>2]=k+1;c[E>>2]=d[k>>0];c[p>>2]=(c[p>>2]|0)+-1;c[G>>2]=(c[E>>2]|0)==255?254:c[E>>2]|0;c[p>>2]=(c[p>>2]|0)-(c[G>>2]|0);c[F>>2]=(c[F>>2]|0)+(c[G>>2]|0);if((c[E>>2]|0)!=255)break b}c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}while(0);if((c[p>>2]|0)<0){c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}c[x>>2]=((d[y>>0]&128|0)!=0^1)&1;if(c[x>>2]|0){if(c[q>>2]|0)break a;c[D>>2]=(c[p>>2]|0)/(c[z>>2]|0)|0;I=_(c[D>>2]|0,c[z>>2]|0)|0;if((I|0)!=(c[p>>2]|0)){c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}c[C>>2]=0;while(1){if((c[C>>2]|0)>=((c[z>>2]|0)-1|0))break a;b[(c[t>>2]|0)+(c[C>>2]<<1)>>1]=c[D>>2];c[C>>2]=(c[C>>2]|0)+1}}c[D>>2]=c[p>>2];c[C>>2]=0;while(1){if((c[C>>2]|0)>=((c[z>>2]|0)-1|0))break;c[w>>2]=$h(c[o>>2]|0,c[p>>2]|0,(c[t>>2]|0)+(c[C>>2]<<1)|0)|0;c[p>>2]=(c[p>>2]|0)-(c[w>>2]|0);if((b[(c[t>>2]|0)+(c[C>>2]<<1)>>1]|0)<0){I=29;break}if((b[(c[t>>2]|0)+(c[C>>2]<<1)>>1]|0)>(c[p>>2]|0)){I=29;break}c[o>>2]=(c[o>>2]|0)+(c[w>>2]|0);c[D>>2]=(c[D>>2]|0)-((c[w>>2]|0)+(b[(c[t>>2]|0)+(c[C>>2]<<1)>>1]|0));c[C>>2]=(c[C>>2]|0)+1}if((I|0)==29){c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}if((c[D>>2]|0)>=0)break a;c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}}while(0);c:do if(c[q>>2]|0){c[w>>2]=$h(c[o>>2]|0,c[p>>2]|0,(c[t>>2]|0)+(c[z>>2]<<1)+-2|0)|0;c[p>>2]=(c[p>>2]|0)-(c[w>>2]|0);if((b[(c[t>>2]|0)+((c[z>>2]|0)-1<<1)>>1]|0)>=0?(b[(c[t>>2]|0)+((c[z>>2]|0)-1<<1)>>1]|0)<=(c[p>>2]|0):0){c[o>>2]=(c[o>>2]|0)+(c[w>>2]|0);if(!(c[x>>2]|0)){if(((c[w>>2]|0)+(b[(c[t>>2]|0)+((c[z>>2]|0)-1<<1)>>1]|0)|0)<=(c[D>>2]|0))break;c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}I=_(b[(c[t>>2]|0)+((c[z>>2]|0)-1<<1)>>1]|0,c[z>>2]|0)|0;if((I|0)>(c[p>>2]|0)){c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}c[C>>2]=0;while(1){if((c[C>>2]|0)>=((c[z>>2]|0)-1|0))break c;b[(c[t>>2]|0)+(c[C>>2]<<1)>>1]=b[(c[t>>2]|0)+((c[z>>2]|0)-1<<1)>>1]|0;c[C>>2]=(c[C>>2]|0)+1}}c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}else{if((c[D>>2]|0)<=1275){b[(c[t>>2]|0)+((c[z>>2]|0)-1<<1)>>1]=c[D>>2];break}c[n>>2]=-4;I=c[n>>2]|0;i=J;return I|0}while(0);if(c[u>>2]|0)c[c[u>>2]>>2]=(c[o>>2]|0)-(c[A>>2]|0);c[C>>2]=0;while(1){if((c[C>>2]|0)>=(c[z>>2]|0))break;if(c[s>>2]|0)c[(c[s>>2]|0)+(c[C>>2]<<2)>>2]=c[o>>2];c[o>>2]=(c[o>>2]|0)+(b[(c[t>>2]|0)+(c[C>>2]<<1)>>1]|0);c[C>>2]=(c[C>>2]|0)+1}if(c[v>>2]|0)c[c[v>>2]>>2]=(c[F>>2]|0)+((c[o>>2]|0)-(c[A>>2]|0));if(c[r>>2]|0)a[c[r>>2]>>0]=a[H>>0]|0;c[n>>2]=c[z>>2];I=c[n>>2]|0;i=J;return I|0}function $h(a,e,f){a=a|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0;l=i;i=i+16|0;g=l+12|0;h=l+8|0;j=l+4|0;k=l;c[h>>2]=a;c[j>>2]=e;c[k>>2]=f;if((c[j>>2]|0)<1){b[c[k>>2]>>1]=-1;c[g>>2]=-1;f=c[g>>2]|0;i=l;return f|0}if((d[c[h>>2]>>0]|0|0)<252){b[c[k>>2]>>1]=d[c[h>>2]>>0]|0;c[g>>2]=1;f=c[g>>2]|0;i=l;return f|0}if((c[j>>2]|0)<2){b[c[k>>2]>>1]=-1;c[g>>2]=-1;f=c[g>>2]|0;i=l;return f|0}else{b[c[k>>2]>>1]=((d[(c[h>>2]|0)+1>>0]|0)<<2)+(d[c[h>>2]>>0]|0);c[g>>2]=2;f=c[g>>2]|0;i=l;return f|0}return 0}function ai(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+32|0;b=h+16|0;d=h+12|0;g=h+8|0;e=h+4|0;f=h;c[d>>2]=a;if((c[d>>2]|0)<1|(c[d>>2]|0)>2){c[b>>2]=0;g=c[b>>2]|0;i=h;return g|0}c[f>>2]=Pd(g)|0;if(c[f>>2]|0){c[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2]=c[(c[f>>2]|0)+8>>2];c[k>>2]=Qd(c[m>>2]|0)|0;if(c[k>>2]|0){c[e>>2]=-3;n=c[e>>2]|0;i=o;return n|0}c[k>>2]=Hb(c[j>>2]|0,c[g>>2]|0,c[h>>2]|0)|0;if(c[k>>2]|0){c[e>>2]=-3;n=c[e>>2]|0;i=o;return n|0}else{a=c[j>>2]|0;c[n>>2]=0;Kb(a,10016,n)|0;c[(c[f>>2]|0)+60>>2]=0;c[(c[f>>2]|0)+64>>2]=(c[g>>2]|0)/400|0;n=di()|0;c[(c[f>>2]|0)+44>>2]=n;c[e>>2]=0;n=c[e>>2]|0;i=o;return n|0}}c[e>>2]=-1;n=c[e>>2]|0;i=o;return n|0}function di(){return 0}function ei(a,d,e,f,h,j,k,l,m){a=a|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;var n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0;N=i;i=i+208|0;G=N+88|0;H=N+84|0;n=N+80|0;o=N+76|0;I=N+72|0;J=N+68|0;p=N+64|0;q=N+60|0;r=N+56|0;s=N+52|0;v=N+48|0;w=N+44|0;t=N+40|0;x=N+36|0;F=N+192|0;z=N+32|0;y=N+28|0;A=N+24|0;B=N+20|0;E=N+96|0;K=N+16|0;L=N+12|0;u=N+8|0;C=N+4|0;D=N;c[H>>2]=a;c[n>>2]=d;c[o>>2]=e;c[I>>2]=f;c[J>>2]=h;c[p>>2]=j;c[q>>2]=k;c[r>>2]=l;c[s>>2]=m;if((c[p>>2]|0)<0|(c[p>>2]|0)>1){c[G>>2]=-1;M=c[G>>2]|0;i=N;return M|0}if((c[p>>2]|0)!=0|(c[o>>2]|0)==0|(c[n>>2]|0)==0?(c[J>>2]|0)%((c[(c[H>>2]|0)+12>>2]|0)/400|0|0)|0|0:0){c[G>>2]=-1;M=c[G>>2]|0;i=N;return M|0}if((c[o>>2]|0)==0|(c[n>>2]|0)==0){c[K>>2]=0;while(1){n=(c[I>>2]|0)+((_(c[K>>2]|0,c[(c[H>>2]|0)+8>>2]|0)|0)<<2)|0;c[L>>2]=fi(c[H>>2]|0,0,0,n,(c[J>>2]|0)-(c[K>>2]|0)|0,0)|0;n=c[L>>2]|0;if((c[L>>2]|0)<0){M=9;break}c[K>>2]=(c[K>>2]|0)+n;if((c[K>>2]|0)>=(c[J>>2]|0)){M=11;break}}if((M|0)==9){c[G>>2]=n;M=c[G>>2]|0;i=N;return M|0}else if((M|0)==11){ii()|0;c[(c[H>>2]|0)+72>>2]=c[K>>2];c[G>>2]=c[K>>2];M=c[G>>2]|0;i=N;return M|0}}if((c[o>>2]|0)<0){c[G>>2]=-1;M=c[G>>2]|0;i=N;return M|0}c[A>>2]=ji(c[n>>2]|0)|0;c[y>>2]=ki(c[n>>2]|0)|0;c[z>>2]=Zh(c[n>>2]|0,c[(c[H>>2]|0)+12>>2]|0)|0;c[B>>2]=li(c[n>>2]|0)|0;c[t>>2]=_h(c[n>>2]|0,c[o>>2]|0,c[q>>2]|0,F,0,E,x,c[r>>2]|0)|0;if((c[t>>2]|0)<0){c[G>>2]=c[t>>2];M=c[G>>2]|0;i=N;return M|0}c[n>>2]=(c[n>>2]|0)+(c[x>>2]|0);if(c[p>>2]|0){if(!((c[A>>2]|0)==1002?1:(c[J>>2]|0)<(c[z>>2]|0))?(c[(c[H>>2]|0)+56>>2]|0)!=1002:0){c[u>>2]=c[(c[H>>2]|0)+72>>2];if((c[J>>2]|0)-(c[z>>2]|0)|0?(c[C>>2]=ei(c[H>>2]|0,0,0,c[I>>2]|0,(c[J>>2]|0)-(c[z>>2]|0)|0,0,0,0,c[s>>2]|0)|0,(c[C>>2]|0)<0):0){c[(c[H>>2]|0)+72>>2]=c[u>>2];c[G>>2]=c[C>>2];M=c[G>>2]|0;i=N;return M|0}c[(c[H>>2]|0)+56>>2]=c[A>>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2]|0,c[w>>2]|0,c[(c[H>>2]|0)+8>>2]|0,(c[H>>2]|0)+76|0);else{g[(c[H>>2]|0)+76+4>>2]=0.0;g[(c[H>>2]|0)+76>>2]=0.0}c[G>>2]=c[w>>2];M=c[G>>2]|0;i=N;return M|0}function fi(d,e,f,h,j,k){d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;var l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ja=0,ka=0,la=0,ma=0,oa=0,pa=0,qa=0,ra=0,sa=0,ta=0;ta=i;i=i+320|0;fa=ta+80|0;ea=ta+72|0;da=ta+64|0;ca=ta+56|0;ba=ta+48|0;aa=ta+40|0;$=ta+32|0;Z=ta+24|0;Y=ta+16|0;y=ta+8|0;x=ta;qa=ta+308|0;ra=ta+304|0;A=ta+300|0;B=ta+296|0;ja=ta+292|0;ka=ta+288|0;C=ta+284|0;t=ta+280|0;H=ta+276|0;N=ta+272|0;v=ta+268|0;pa=ta+264|0;L=ta+216|0;u=ta+212|0;o=ta+208|0;z=ta+204|0;m=ta+200|0;P=ta+196|0;S=ta+192|0;sa=ta+188|0;O=ta+184|0;W=ta+180|0;V=ta+176|0;Q=ta+172|0;R=ta+168|0;K=ta+164|0;F=ta+160|0;D=ta+156|0;E=ta+152|0;n=ta+148|0;oa=ta+144|0;ga=ta+140|0;T=ta+136|0;G=ta+132|0;l=ta+128|0;la=ta+124|0;ma=ta+120|0;r=ta+116|0;p=ta+112|0;s=ta+108|0;q=ta+104|0;w=ta+100|0;I=ta+96|0;U=ta+312|0;J=ta+92|0;M=ta+88|0;ha=ta+84|0;c[ra>>2]=d;c[A>>2]=e;c[B>>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>2]=(c[ja>>2]|0)+(pa<<2);c[sa>>2]=(c[sa>>2]|0)-(c[l>>2]|0);if((c[sa>>2]|0)<=0){k=22;break}}if((k|0)==20){c[qa>>2]=e;sa=c[qa>>2]|0;i=ta;return sa|0}else if((k|0)==22){c[qa>>2]=c[ka>>2];sa=c[qa>>2]|0;i=ta;return sa|0}}if((c[sa>>2]|0)<(c[oa>>2]|0)){if((c[sa>>2]|0)>(c[n>>2]|0)){c[sa>>2]=c[n>>2];break}if(((c[O>>2]|0)!=1e3?(c[sa>>2]|0)>(c[E>>2]|0):0)?(c[sa>>2]|0)<(c[n>>2]|0):0)c[sa>>2]=c[E>>2]}}else{c[sa>>2]=c[(c[ra>>2]|0)+64>>2];c[O>>2]=c[(c[ra>>2]|0)+56>>2];Yb(L,c[A>>2]|0,c[B>>2]|0)}while(0);c[G>>2]=0;c[z>>2]=1;c[m>>2]=1;do if(c[A>>2]|0?(c[(c[ra>>2]|0)+60>>2]|0)>0:0){if(!(((c[O>>2]|0)==1002?(c[(c[ra>>2]|0)+60>>2]|0)!=1002:0)?!(c[(c[ra>>2]|0)+68>>2]|0):0)){if((c[O>>2]|0)==1002)break;if((c[(c[ra>>2]|0)+60>>2]|0)!=1002)break}c[W>>2]=1;e=_(c[E>>2]|0,c[(c[ra>>2]|0)+8>>2]|0)|0;if((c[O>>2]|0)==1002){c[m>>2]=e;break}else{c[z>>2]=e;break}}while(0);m=c[m>>2]|0;c[la>>2]=ia()|0;e=i;i=i+((1*(m<<2)|0)+15&-16)|0;if((c[W>>2]|0)!=0&(c[O>>2]|0)==1002){c[P>>2]=e;fi(c[ra>>2]|0,0,0,c[P>>2]|0,(c[E>>2]|0)<(c[sa>>2]|0)?c[E>>2]|0:c[sa>>2]|0,0)|0}a:do if((c[sa>>2]|0)>(c[ka>>2]|0)){c[qa>>2]=-1;c[ma>>2]=1}else{c[ka>>2]=c[sa>>2];if((c[O>>2]|0)==1002|(c[G>>2]|0)!=0)e=1;else e=_((c[n>>2]|0)>(c[ka>>2]|0)?c[n>>2]|0:c[ka>>2]|0,c[(c[ra>>2]|0)+8>>2]|0)|0;c[o>>2]=e;j=i;i=i+((1*(c[o>>2]<<1)|0)+15&-16)|0;b:do if((c[O>>2]|0)!=1002){c[s>>2]=j;if((c[(c[ra>>2]|0)+60>>2]|0)==1002)Qd(c[t>>2]|0)|0;if(10>(((c[sa>>2]|0)*1e3|0)/(c[(c[ra>>2]|0)+12>>2]|0)|0|0))e=10;else e=((c[sa>>2]|0)*1e3|0)/(c[(c[ra>>2]|0)+12>>2]|0)|0;c[(c[ra>>2]|0)+16+16>>2]=e;do if(c[A>>2]|0){c[(c[ra>>2]|0)+16+4>>2]=c[(c[ra>>2]|0)+48>>2];e=c[ra>>2]|0;if((c[O>>2]|0)!=1e3){c[e+16+12>>2]=16e3;break}k=c[ra>>2]|0;if((c[e+52>>2]|0)==1101){c[k+16+12>>2]=8e3;break}if((c[k+52>>2]|0)==1102){c[(c[ra>>2]|0)+16+12>>2]=12e3;break}else{c[(c[ra>>2]|0)+16+12>>2]=16e3;break}}while(0);c[r>>2]=(c[A>>2]|0)==0?1:c[C>>2]<<1;c[p>>2]=0;c:while(1){c[q>>2]=(c[p>>2]|0)==0&1;c[v>>2]=Rd(c[t>>2]|0,(c[ra>>2]|0)+16|0,c[r>>2]|0,c[q>>2]|0,L,c[s>>2]|0,u,c[(c[ra>>2]|0)+44>>2]|0)|0;d:do if(c[v>>2]|0){if(!(c[r>>2]|0))break c;c[u>>2]=c[ka>>2];c[N>>2]=0;while(1){if((c[N>>2]|0)>=(_(c[ka>>2]|0,c[(c[ra>>2]|0)+8>>2]|0)|0))break d;b[(c[s>>2]|0)+(c[N>>2]<<1)>>1]=0;c[N>>2]=(c[N>>2]|0)+1}}while(0);o=_(c[u>>2]|0,c[(c[ra>>2]|0)+8>>2]|0)|0;c[s>>2]=(c[s>>2]|0)+(o<<1);c[p>>2]=(c[p>>2]|0)+(c[u>>2]|0);if((c[p>>2]|0)>=(c[ka>>2]|0))break b}c[qa>>2]=-3;c[ma>>2]=1;break a}while(0);c[V>>2]=0;if((c[C>>2]|0)==0&(c[O>>2]|0)!=1002&(c[A>>2]|0)!=0?(v=(gi(L)|0)+17|0,(v+(((c[(c[ra>>2]|0)+56>>2]|0)==1001&1)*20|0)|0)<=(c[B>>2]<<3|0)):0){if((c[O>>2]|0)==1001)c[Q>>2]=dc(L,12)|0;else c[Q>>2]=1;if(c[Q>>2]|0){c[K>>2]=dc(L,1)|0;if((c[O>>2]|0)==1001)e=(fc(L,256)|0)+2|0;else{e=c[B>>2]|0;e=e-((gi(L)|0)+7>>3)|0}c[R>>2]=e;c[B>>2]=(c[B>>2]|0)-(c[R>>2]|0);v=c[B>>2]<<3;if((v|0)<(gi(L)|0)){c[B>>2]=0;c[R>>2]=0;c[Q>>2]=0}v=L+4|0;c[v>>2]=(c[v>>2]|0)-(c[R>>2]|0)}}if((c[O>>2]|0)!=1002)c[V>>2]=17;c[w>>2]=21;switch(c[(c[ra>>2]|0)+52>>2]|0){case 1101:{c[w>>2]=13;break}case 1103:case 1102:{c[w>>2]=17;break}case 1104:{c[w>>2]=19;break}case 1105:{c[w>>2]=21;break}default:{}}v=c[H>>2]|0;c[x>>2]=c[w>>2];Kb(v,10012,x)|0;x=c[H>>2]|0;c[y>>2]=c[(c[ra>>2]|0)+48>>2];Kb(x,10008,y)|0;if(c[Q>>2]|0){c[W>>2]=0;c[z>>2]=1}e=i;i=i+((1*(c[z>>2]<<2)|0)+15&-16)|0;if((c[W>>2]|0)!=0&(c[O>>2]|0)!=1002){c[P>>2]=e;fi(c[ra>>2]|0,0,0,c[P>>2]|0,(c[E>>2]|0)<(c[sa>>2]|0)?c[E>>2]|0:c[sa>>2]|0,0)|0}if(c[Q>>2]|0)e=_(c[E>>2]|0,c[(c[ra>>2]|0)+8>>2]|0)|0;else e=1;c[S>>2]=e;e=i;i=i+((1*(c[S>>2]<<2)|0)+15&-16)|0;if((c[Q>>2]|0)!=0&(c[K>>2]|0)!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>>2]<<2)>>2]=+g[ha>>2];c[N>>2]=(c[N>>2]|0)+1}}while(0);if((c[B>>2]|0)<=1)c[(c[ra>>2]|0)+84>>2]=0;else c[(c[ra>>2]|0)+84>>2]=c[L+28>>2]^c[T>>2];c[(c[ra>>2]|0)+60>>2]=c[O>>2];if(c[Q>>2]|0)e=(c[K>>2]|0)!=0^1;else e=0;c[(c[ra>>2]|0)+68>>2]=e&1;if((c[pa>>2]|0)>=0)ii()|0;c[qa>>2]=(c[pa>>2]|0)<0?c[pa>>2]|0:c[sa>>2]|0;c[ma>>2]=1}while(0);na(c[la>>2]|0);sa=c[qa>>2]|0;i=ta;return sa|0}function gi(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;a=(c[(c[d>>2]|0)+20>>2]|0)-(32-(aa(c[(c[d>>2]|0)+28>>2]|0)|0))|0;i=b;return a|0}function hi(a,b,d,e,f,h,j){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;u=i;i=i+48|0;k=u+40|0;l=u+36|0;m=u+32|0;n=u+28|0;o=u+24|0;p=u+20|0;v=u+16|0;r=u+12|0;q=u+8|0;s=u+4|0;t=u;c[k>>2]=a;c[l>>2]=b;c[m>>2]=d;c[n>>2]=e;c[o>>2]=f;c[p>>2]=h;c[v>>2]=j;c[s>>2]=48e3/(c[v>>2]|0)|0;c[q>>2]=0;while(1){if((c[q>>2]|0)>=(c[o>>2]|0))break;c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[n>>2]|0))break;h=_(c[r>>2]|0,c[s>>2]|0)|0;e=_(c[r>>2]|0,c[s>>2]|0)|0;g[t>>2]=+g[(c[p>>2]|0)+(h<<2)>>2]*+g[(c[p>>2]|0)+(e<<2)>>2];e=_(c[r>>2]|0,c[o>>2]|0)|0;h=_(c[r>>2]|0,c[o>>2]|0)|0;v=_(c[r>>2]|0,c[o>>2]|0)|0;g[(c[m>>2]|0)+(v+(c[q>>2]|0)<<2)>>2]=+g[t>>2]*+g[(c[l>>2]|0)+(e+(c[q>>2]|0)<<2)>>2]+(1.0-+g[t>>2])*+g[(c[k>>2]|0)+(h+(c[q>>2]|0)<<2)>>2];c[r>>2]=(c[r>>2]|0)+1}c[q>>2]=(c[q>>2]|0)+1}i=u;return}function ii(){return 0}function ji(a){a=a|0;var b=0,e=0,f=0;f=i;i=i+16|0;b=f+4|0;e=f;c[b>>2]=a;do if(!((d[c[b>>2]>>0]|0)&128|0))if(((d[c[b>>2]>>0]|0)&96|0)==96){c[e>>2]=1001;break}else{c[e>>2]=1e3;break}else c[e>>2]=1002;while(0);i=f;return c[e>>2]|0}function ki(a){a=a|0;var b=0,e=0,f=0,g=0;g=i;i=i+16|0;b=g+4|0;f=g;c[b>>2]=a;e=d[c[b>>2]>>0]|0;if((d[c[b>>2]>>0]|0)&128|0){e=1102+(e>>5&3)|0;c[f>>2]=e;c[f>>2]=(c[f>>2]|0)==1102?1101:e;f=c[f>>2]|0;i=g;return f|0}a=d[c[b>>2]>>0]|0;if((e&96|0)==96){c[f>>2]=a&16|0?1105:1104;f=c[f>>2]|0;i=g;return f|0}else{c[f>>2]=1101+(a>>5&3);f=c[f>>2]|0;i=g;return f|0}return 0}function li(a){a=a|0;var b=0,e=0;e=i;i=i+16|0;b=e;c[b>>2]=a;i=e;return ((d[c[b>>2]>>0]|0)&4|0?2:1)|0}function mi(a,d,e,f,h,j){a=a|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;v=i;i=i+48|0;l=v+40|0;m=v+36|0;n=v+32|0;o=v+28|0;p=v+24|0;q=v+20|0;r=v+16|0;u=v+12|0;t=v+8|0;k=v+4|0;s=v;c[m>>2]=a;c[n>>2]=d;c[o>>2]=e;c[p>>2]=f;c[q>>2]=h;c[r>>2]=j;if((c[q>>2]|0)<=0){c[l>>2]=-1;u=c[l>>2]|0;i=v;return u|0}do if(!((c[n>>2]|0)!=0&(c[o>>2]|0)>0^1|(c[r>>2]|0)!=0)){c[k>>2]=ni(c[m>>2]|0,c[n>>2]|0,c[o>>2]|0)|0;if((c[k>>2]|0)>0){c[q>>2]=(c[q>>2]|0)<(c[k>>2]|0)?c[q>>2]|0:c[k>>2]|0;break}c[l>>2]=-4;u=c[l>>2]|0;i=v;return u|0}while(0);a=_(c[q>>2]|0,c[(c[m>>2]|0)+8>>2]|0)|0;c[s>>2]=ia()|0;d=i;i=i+((1*(a<<2)|0)+15&-16)|0;c[u>>2]=ei(c[m>>2]|0,c[n>>2]|0,c[o>>2]|0,d,c[q>>2]|0,c[r>>2]|0,0,0,1)|0;a:do if((c[u>>2]|0)>0){c[t>>2]=0;while(1){if((c[t>>2]|0)>=(_(c[u>>2]|0,c[(c[m>>2]|0)+8>>2]|0)|0))break a;r=qi(+g[d+(c[t>>2]<<2)>>2])|0;b[(c[p>>2]|0)+(c[t>>2]<<1)>>1]=r;c[t>>2]=(c[t>>2]|0)+1}}while(0);c[l>>2]=c[u>>2];na(c[s>>2]|0);u=c[l>>2]|0;i=v;return u|0}function ni(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0;e=i;i=i+16|0;f=e+8|0;h=e+4|0;g=e;c[f>>2]=a;c[h>>2]=b;c[g>>2]=d;b=oi(c[h>>2]|0,c[g>>2]|0,c[(c[f>>2]|0)+12>>2]|0)|0;i=e;return b|0}function oi(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0;j=i;i=i+32|0;e=j+20|0;f=j+16|0;l=j+12|0;g=j+8|0;h=j+4|0;k=j;c[f>>2]=a;c[l>>2]=b;c[g>>2]=d;c[k>>2]=pi(c[f>>2]|0,c[l>>2]|0)|0;d=c[k>>2]|0;if((c[k>>2]|0)<0){c[e>>2]=d;l=c[e>>2]|0;i=j;return l|0}c[h>>2]=_(d,Zh(c[f>>2]|0,c[g>>2]|0)|0)|0;if(((c[h>>2]|0)*25|0)>((c[g>>2]|0)*3|0)){c[e>>2]=-4;l=c[e>>2]|0;i=j;return l|0}else{c[e>>2]=c[h>>2];l=c[e>>2]|0;i=j;return l|0}return 0}function pi(a,b){a=a|0;b=b|0;var e=0,f=0,g=0,h=0,j=0;j=i;i=i+16|0;e=j+12|0;f=j+8|0;g=j+4|0;h=j;c[f>>2]=a;c[g>>2]=b;do if((c[g>>2]|0)>=1){c[h>>2]=(d[c[f>>2]>>0]|0)&3;if(!(c[h>>2]|0)){c[e>>2]=1;break}if((c[h>>2]|0)!=3){c[e>>2]=2;break}if((c[g>>2]|0)<2){c[e>>2]=-4;break}else{c[e>>2]=(d[(c[f>>2]|0)+1>>0]|0)&63;break}}else c[e>>2]=-1;while(0);i=j;return c[e>>2]|0}function qi(a){a=+a;var b=0,c=0;c=i;i=i+16|0;b=c;g[b>>2]=a;g[b>>2]=+g[b>>2]*32768.0;g[b>>2]=+g[b>>2]>-32768.0?+g[b>>2]:-32768.0;g[b>>2]=+g[b>>2]<32767.0?+g[b>>2]:32767.0;b=(ij(+g[b>>2])|0)&65535;i=c;return b|0}function ri(a,b,d,e,f,g){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;p=i;i=i+32|0;h=p+24|0;j=p+20|0;k=p+16|0;l=p+12|0;m=p+8|0;n=p+4|0;o=p;c[j>>2]=a;c[k>>2]=b;c[l>>2]=d;c[m>>2]=e;c[n>>2]=f;c[o>>2]=g;if((c[n>>2]|0)<=0){c[h>>2]=-1;a=c[h>>2]|0;i=p;return a|0}else{c[h>>2]=ei(c[j>>2]|0,c[k>>2]|0,c[l>>2]|0,c[m>>2]|0,c[n>>2]|0,c[o>>2]|0,0,0,0)|0;a=c[h>>2]|0;i=p;return a|0}return 0}function si(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;t=i;i=i+80|0;q=t+8|0;r=t+76|0;e=t+72|0;u=t+68|0;s=t+64|0;f=t+48|0;h=t+44|0;g=t+40|0;j=t+36|0;k=t+32|0;l=t+28|0;m=t+24|0;n=t+20|0;o=t+16|0;p=t+12|0;c[e>>2]=a;c[u>>2]=b;c[s>>2]=0;c[h>>2]=(c[e>>2]|0)+(c[(c[e>>2]|0)+4>>2]|0);c[g>>2]=(c[e>>2]|0)+(c[c[e>>2]>>2]|0);c[f>>2]=d;a:do switch(c[u>>2]|0){case 4009:{d=(c[f>>2]|0)+(4-1)&~(4-1);u=c[d>>2]|0;c[f>>2]=d+4;c[j>>2]=u;if(c[j>>2]|0){c[c[j>>2]>>2]=c[(c[e>>2]|0)+52>>2];e=20}else e=21;break}case 4031:{d=(c[f>>2]|0)+(4-1)&~(4-1);u=c[d>>2]|0;c[f>>2]=d+4;c[k>>2]=u;if(c[k>>2]|0){c[c[k>>2]>>2]=c[(c[e>>2]|0)+84>>2];e=20}else e=21;break}case 4028:{oj((c[e>>2]|0)+48|0,0,88-((c[e>>2]|0)+48-(c[e>>2]|0))|0)|0;Kb(c[g>>2]|0,4028,t)|0;Qd(c[h>>2]|0)|0;c[(c[e>>2]|0)+48>>2]=c[(c[e>>2]|0)+8>>2];c[(c[e>>2]|0)+64>>2]=(c[(c[e>>2]|0)+12>>2]|0)/400|0;e=20;break}case 4029:{d=(c[f>>2]|0)+(4-1)&~(4-1);u=c[d>>2]|0;c[f>>2]=d+4;c[l>>2]=u;if(c[l>>2]|0){c[c[l>>2]>>2]=c[(c[e>>2]|0)+12>>2];e=20}else e=21;break}case 4033:{d=(c[f>>2]|0)+(4-1)&~(4-1);u=c[d>>2]|0;c[f>>2]=d+4;c[m>>2]=u;if(c[m>>2]|0)if((c[(c[e>>2]|0)+60>>2]|0)==1002){e=c[g>>2]|0;c[q>>2]=(c[m>>2]|0)+((((c[m>>2]|0)-(c[m>>2]|0)|0)/4|0)<<2);Kb(e,4033,q)|0;e=20;break a}else{c[c[m>>2]>>2]=c[(c[e>>2]|0)+16+20>>2];e=20;break a}else e=21;break}case 4045:{d=(c[f>>2]|0)+(4-1)&~(4-1);u=c[d>>2]|0;c[f>>2]=d+4;c[n>>2]=u;if(c[n>>2]|0){c[c[n>>2]>>2]=c[(c[e>>2]|0)+40>>2];e=20}else e=21;break}case 4034:{d=(c[f>>2]|0)+(4-1)&~(4-1);u=c[d>>2]|0;c[f>>2]=d+4;c[o>>2]=u;if((c[o>>2]|0)<-32768|(c[o>>2]|0)>32767)e=21;else{c[(c[e>>2]|0)+40>>2]=c[o>>2];e=20}break}case 4039:{d=(c[f>>2]|0)+(4-1)&~(4-1);u=c[d>>2]|0;c[f>>2]=d+4;c[p>>2]=u;if(c[p>>2]|0){c[c[p>>2]>>2]=c[(c[e>>2]|0)+72>>2];e=20}else e=21;break}default:{c[s>>2]=-5;e=20}}while(0);if((e|0)==20){c[r>>2]=c[s>>2];u=c[r>>2]|0;i=t;return u|0}else if((e|0)==21){c[r>>2]=-1;u=c[r>>2]|0;i=t;return u|0}return 0}function ti(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;h=i;i=i+32|0;b=h+16|0;d=h+12|0;g=h+8|0;e=h+4|0;f=h;c[d>>2]=a;if((c[d>>2]|0)<1|(c[d>>2]|0)>2){c[b>>2]=0;g=c[b>>2]|0;i=h;return g|0}c[f>>2]=Sd(g)|0;if(c[f>>2]|0){c[b>>2]=0;g=c[b>>2]|0;i=h;return g|0}else{c[g>>2]=ui(c[g>>2]|0)|0;c[e>>2]=hb(c[d>>2]|0)|0;f=ui(18220)|0;c[b>>2]=f+(c[g>>2]|0)+(c[e>>2]|0);g=c[b>>2]|0;i=h;return g|0}return 0}function ui(a){a=a|0;var b=0,d=0,e=0;b=i;i=i+16|0;e=b+4|0;d=b;c[e>>2]=a;c[d>>2]=4;a=_((((c[e>>2]|0)+(c[d>>2]|0)-1|0)>>>0)/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>2]=t;c[(c[j>>2]|0)+14344>>2]=1;c[(c[j>>2]|0)+14320>>2]=1001;c[(c[j>>2]|0)+14336>>2]=1105;Yi((c[j>>2]|0)+172|0);c[h>>2]=0;t=c[h>>2]|0;i=u;return t|0}}c[h>>2]=-1;t=c[h>>2]|0;i=u;return t|0}function wi(){return 0}function xi(a,b,d,e,f,h,j){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;u=i;i=i+48|0;v=u+40|0;k=u+36|0;l=u+32|0;m=u+28|0;n=u+24|0;o=u+20|0;p=u+16|0;t=u+12|0;s=u+8|0;r=u+4|0;q=u;c[v>>2]=a;c[k>>2]=b;c[l>>2]=d;c[m>>2]=e;c[n>>2]=f;c[o>>2]=h;c[p>>2]=j;c[t>>2]=c[v>>2];c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[l>>2]|0))break;v=_((c[r>>2]|0)+(c[m>>2]|0)|0,c[p>>2]|0)|0;g[(c[k>>2]|0)+(c[r>>2]<<2)>>2]=+g[(c[t>>2]|0)+(v+(c[n>>2]|0)<<2)>>2]*32768.0;c[r>>2]=(c[r>>2]|0)+1}a:do if((c[o>>2]|0)<=-1){if((c[o>>2]|0)==-2){c[q>>2]=1;while(1){if((c[q>>2]|0)>=(c[p>>2]|0))break a;c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[l>>2]|0))break;d=_((c[r>>2]|0)+(c[m>>2]|0)|0,c[p>>2]|0)|0;v=(c[k>>2]|0)+(c[r>>2]<<2)|0;g[v>>2]=+g[v>>2]+ +g[(c[t>>2]|0)+(d+(c[q>>2]|0)<<2)>>2]*32768.0;c[r>>2]=(c[r>>2]|0)+1}c[q>>2]=(c[q>>2]|0)+1}}}else{c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[l>>2]|0))break a;d=_((c[r>>2]|0)+(c[m>>2]|0)|0,c[p>>2]|0)|0;v=(c[k>>2]|0)+(c[r>>2]<<2)|0;g[v>>2]=+g[v>>2]+ +g[(c[t>>2]|0)+(d+(c[o>>2]|0)<<2)>>2]*32768.0;c[r>>2]=(c[r>>2]|0)+1}}while(0);g[s>>2]=1.0;if((c[p>>2]|0)==-2)g[s>>2]=+g[s>>2]/+(c[p>>2]|0);else g[s>>2]=+g[s>>2]/2.0;c[r>>2]=0;while(1){if((c[r>>2]|0)>=(c[l>>2]|0))break;v=(c[k>>2]|0)+(c[r>>2]<<2)|0;g[v>>2]=+g[v>>2]*+g[s>>2];c[r>>2]=(c[r>>2]|0)+1}i=u;return}function yi(a,d,e,f,h,j,k){a=a|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;var l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;v=i;i=i+48|0;w=v+40|0;l=v+36|0;m=v+32|0;n=v+28|0;o=v+24|0;p=v+20|0;q=v+16|0;u=v+12|0;t=v+8|0;s=v+4|0;r=v;c[w>>2]=a;c[l>>2]=d;c[m>>2]=e;c[n>>2]=f;c[o>>2]=h;c[p>>2]=j;c[q>>2]=k;c[u>>2]=c[w>>2];c[s>>2]=0;while(1){if((c[s>>2]|0)>=(c[m>>2]|0))break;w=_((c[s>>2]|0)+(c[n>>2]|0)|0,c[q>>2]|0)|0;g[(c[l>>2]|0)+(c[s>>2]<<2)>>2]=+(b[(c[u>>2]|0)+(w+(c[o>>2]|0)<<1)>>1]|0);c[s>>2]=(c[s>>2]|0)+1}a:do if((c[p>>2]|0)<=-1){if((c[p>>2]|0)==-2){c[r>>2]=1;while(1){if((c[r>>2]|0)>=(c[q>>2]|0))break a;c[s>>2]=0;while(1){if((c[s>>2]|0)>=(c[m>>2]|0))break;e=_((c[s>>2]|0)+(c[n>>2]|0)|0,c[q>>2]|0)|0;w=(c[l>>2]|0)+(c[s>>2]<<2)|0;g[w>>2]=+g[w>>2]+ +(b[(c[u>>2]|0)+(e+(c[r>>2]|0)<<1)>>1]|0);c[s>>2]=(c[s>>2]|0)+1}c[r>>2]=(c[r>>2]|0)+1}}}else{c[s>>2]=0;while(1){if((c[s>>2]|0)>=(c[m>>2]|0))break a;e=_((c[s>>2]|0)+(c[n>>2]|0)|0,c[q>>2]|0)|0;w=(c[l>>2]|0)+(c[s>>2]<<2)|0;g[w>>2]=+g[w>>2]+ +(b[(c[u>>2]|0)+(e+(c[p>>2]|0)<<1)>>1]|0);c[s>>2]=(c[s>>2]|0)+1}}while(0);g[t>>2]=.000030517578125;if((c[q>>2]|0)==-2)g[t>>2]=+g[t>>2]/+(c[q>>2]|0);else g[t>>2]=+g[t>>2]/2.0;c[s>>2]=0;while(1){if((c[s>>2]|0)>=(c[m>>2]|0))break;w=(c[l>>2]|0)+(c[s>>2]<<2)|0;g[w>>2]=+g[w>>2]*+g[t>>2];c[s>>2]=(c[s>>2]|0)+1}i=v;return}function zi(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+32|0;f=k+16|0;g=k+12|0;e=k+8|0;h=k+4|0;j=k;c[g>>2]=a;c[e>>2]=b;c[h>>2]=d;if((c[g>>2]|0)<((c[h>>2]|0)/400|0|0)){c[f>>2]=-1;j=c[f>>2]|0;i=k;return j|0}do if((c[e>>2]|0)==5e3)c[j>>2]=c[g>>2];else{if((c[e>>2]|0)==5010){c[j>>2]=(c[h>>2]|0)/50|0;break}if(!((c[e>>2]|0)>=5001&(c[e>>2]|0)<=5006)){c[f>>2]=-1;j=c[f>>2]|0;i=k;return j|0}d=c[h>>2]|0;if((((c[h>>2]|0)*3|0)/50|0|0)<(((c[h>>2]|0)/400|0)<<(c[e>>2]|0)-5001|0))d=(d*3|0)/50|0;else d=((d|0)/400|0)<<(c[e>>2]|0)-5001;c[j>>2]=d}while(0);if((c[j>>2]|0)>(c[g>>2]|0)){c[f>>2]=-1;j=c[f>>2]|0;i=k;return j|0}if(((((((c[j>>2]|0)*400|0)!=(c[h>>2]|0)?((c[j>>2]|0)*200|0)!=(c[h>>2]|0):0)?((c[j>>2]|0)*100|0)!=(c[h>>2]|0):0)?((c[j>>2]|0)*50|0)!=(c[h>>2]|0):0)?((c[j>>2]|0)*25|0)!=(c[h>>2]|0):0)?((c[j>>2]|0)*50|0)!=((c[h>>2]|0)*3|0):0){c[f>>2]=-1;j=c[f>>2]|0;i=k;return j|0}c[f>>2]=c[j>>2];j=c[f>>2]|0;i=k;return j|0}function Ai(a,b,d,e,f,g,h,j,k){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;var l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;w=i;i=i+48|0;l=w+40|0;m=w+36|0;n=w+32|0;o=w+28|0;p=w+24|0;q=w+20|0;r=w+16|0;s=w+12|0;t=w+8|0;u=w+4|0;v=w;c[m>>2]=a;c[n>>2]=b;c[o>>2]=d;c[p>>2]=e;c[q>>2]=f;c[r>>2]=g;c[s>>2]=h;c[t>>2]=j;c[u>>2]=k;if((c[o>>2]|0)==5010?(c[n>>2]|0)>=((c[q>>2]|0)/200|0|0):0){c[v>>2]=3;c[v>>2]=Bi(c[m>>2]|0,c[n>>2]|0,c[p>>2]|0,c[q>>2]|0,c[r>>2]|0,0.0,c[u>>2]|0,c[s>>2]|0,c[t>>2]|0)|0;while(1){if((((c[q>>2]|0)/400|0)<>2]|0)<=(c[n>>2]|0))break;c[v>>2]=(c[v>>2]|0)+-1}c[n>>2]=((c[q>>2]|0)/400|0)<>2]}else c[n>>2]=zi(c[n>>2]|0,c[o>>2]|0,c[q>>2]|0)|0;if((c[n>>2]|0)<0){c[l>>2]=-1;d=c[l>>2]|0;i=w;return d|0}else{c[l>>2]=c[n>>2];d=c[l>>2]|0;i=w;return d|0}return 0}function Bi(a,b,d,e,f,h,j,k,l){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=+h;j=j|0;k=k|0;l=l|0;var m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0;H=i;i=i+304|0;n=H+296|0;m=H+292|0;o=H+288|0;I=H+284|0;p=H+280|0;q=H+276|0;r=H+272|0;s=H+268|0;t=H+264|0;v=H+260|0;z=H+256|0;x=H+144|0;y=H+36|0;B=H+32|0;w=H+28|0;E=H+24|0;D=H+20|0;C=H+16|0;u=H+12|0;F=H+8|0;G=H+4|0;A=H;c[n>>2]=a;c[m>>2]=b;c[o>>2]=d;c[I>>2]=e;c[p>>2]=f;g[q>>2]=h;c[r>>2]=j;c[s>>2]=k;c[t>>2]=l;c[w>>2]=0;c[E>>2]=(c[I>>2]|0)/400|0;a=c[E>>2]|0;c[u>>2]=ia()|0;e=i;i=i+((1*(a<<2)|0)+15&-16)|0;g[x>>2]=+g[c[r>>2]>>2];g[y>>2]=1.0/(+g[c[r>>2]>>2]+1.0000000036274937e-15);if(c[s>>2]|0){c[C>>2]=(c[E>>2]<<1)-(c[s>>2]|0);c[m>>2]=(c[m>>2]|0)-(c[C>>2]|0);g[x+4>>2]=+g[(c[r>>2]|0)+4>>2];g[y+4>>2]=1.0/(+g[(c[r>>2]|0)+4>>2]+1.0000000036274937e-15);g[x+8>>2]=+g[(c[r>>2]|0)+8>>2];g[y+8>>2]=1.0/(+g[(c[r>>2]|0)+8>>2]+1.0000000036274937e-15);c[D>>2]=3}else{c[D>>2]=1;c[C>>2]=0}if(((c[m>>2]|0)/(c[E>>2]|0)|0|0)<24)d=(c[m>>2]|0)/(c[E>>2]|0)|0;else d=24;c[v>>2]=d;g[B>>2]=0.0;c[z>>2]=0;while(1){if((c[z>>2]|0)>=(c[v>>2]|0))break;g[F>>2]=1.0000000036274937e-15;I=_(c[z>>2]|0,c[E>>2]|0)|0;qa[c[t>>2]&3](c[n>>2]|0,e,c[E>>2]|0,I+(c[C>>2]|0)|0,0,-2,c[o>>2]|0);if(!(c[z>>2]|0))g[B>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=e;c[n>>2]=f;do if((c[n>>2]|0)>=80)if((c[n>>2]|0)>160){g[r>>2]=1.0;break}else{g[r>>2]=(+(c[n>>2]|0)-80.0)/80.0;break}else g[r>>2]=0.0;while(0);c[x>>2]=0;while(1){if((c[x>>2]|0)>=16)break;c[y+(c[x>>2]<<2)>>2]=-1;g[p+(c[x>>2]<<2)>>2]=1.0e10;c[x>>2]=(c[x>>2]|0)+1}c[x>>2]=0;while(1){if((c[x>>2]|0)>=4)break;A=+((c[m>>2]|0)+(_(c[n>>2]|0,1<>2])|0)|0);h=+g[r>>2];h=A*(h*+Di(c[j>>2]|0,c[k>>2]|0,c[x>>2]|0,(c[l>>2]|0)+1|0)+1.0);g[p+(1<>2]<<2)>>2]=h;c[y+(1<>2]<<2)>>2]=c[x>>2];c[x>>2]=(c[x>>2]|0)+1}c[x>>2]=1;while(1){if((c[x>>2]|0)>=(c[l>>2]|0))break;c[s>>2]=2;while(1){if((c[s>>2]|0)>=16)break;g[p+(c[x>>2]<<6)+(c[s>>2]<<2)>>2]=+g[p+((c[x>>2]|0)-1<<6)+((c[s>>2]|0)-1<<2)>>2];c[y+(c[x>>2]<<6)+(c[s>>2]<<2)>>2]=(c[s>>2]|0)-1;c[s>>2]=(c[s>>2]|0)+1}c[s>>2]=0;while(1){if((c[s>>2]|0)>=4)break;c[y+(c[x>>2]<<6)+(1<>2]<<2)>>2]=1;g[u>>2]=+g[p+((c[x>>2]|0)-1<<6)+4>>2];c[t>>2]=1;while(1){if((c[t>>2]|0)>=4)break;g[v>>2]=+g[p+((c[x>>2]|0)-1<<6)+((1<<(c[t>>2]|0)+1)-1<<2)>>2];if(+g[v>>2]<+g[u>>2]){c[y+(c[x>>2]<<6)+(1<>2]<<2)>>2]=(1<<(c[t>>2]|0)+1)-1;g[u>>2]=+g[v>>2]}c[t>>2]=(c[t>>2]|0)+1}A=+((c[m>>2]|0)+(_(c[n>>2]|0,1<>2])|0)|0);h=+g[r>>2];g[q>>2]=A*(h*+Di((c[j>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0))break;g[o>>2]=+g[o>>2]+ +g[(c[k>>2]|0)+(c[n>>2]<<2)>>2];g[p>>2]=+g[p>>2]+ +g[(c[l>>2]|0)+(c[n>>2]<<2)>>2];c[n>>2]=(c[n>>2]|0)+1}g[q>>2]=+g[o>>2]*+g[p>>2]/+(_(c[m>>2]|0,c[m>>2]|0)|0);if(0.0>(+g[q>>2]-2.0)*.05000000074505806)f=0.0;else f=(+g[q>>2]-2.0)*.05000000074505806;if(1.0<+O(+f)){f=1.0;i=r;return +f}if(0.0>(+g[q>>2]-2.0)*.05000000074505806)f=0.0;else f=(+g[q>>2]-2.0)*.05000000074505806;f=+O(+f);i=r;return +f}function Ei(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0.0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0;D=i;i=i+96|0;h=D+84|0;j=D+80|0;E=D+76|0;C=D+72|0;u=D+68|0;v=D+64|0;A=D+60|0;q=D+56|0;r=D+52|0;t=D+48|0;y=D+44|0;z=D+40|0;w=D+36|0;x=D+32|0;B=D+28|0;k=D+24|0;o=D+20|0;l=D+16|0;m=D+12|0;n=D+8|0;p=D+4|0;s=D;c[h>>2]=a;c[j>>2]=b;c[E>>2]=d;c[C>>2]=e;c[B>>2]=(c[E>>2]|0)/(c[j>>2]|0)|0;g[o>>2]=1.0-25.0/+((50>(c[B>>2]|0)?50:c[B>>2]|0)|0);g[t>>2]=0.0;g[r>>2]=0.0;g[q>>2]=0.0;c[k>>2]=0;while(1){if((c[k>>2]|0)>=(c[j>>2]|0))break;g[l>>2]=0.0;g[m>>2]=0.0;g[n>>2]=0.0;g[p>>2]=+g[(c[h>>2]|0)+(c[k>>2]<<1<<2)>>2];g[s>>2]=+g[(c[h>>2]|0)+((c[k>>2]<<1)+1<<2)>>2];g[l>>2]=+g[p>>2]*+g[p>>2];g[m>>2]=+g[p>>2]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0;else f=+g[(c[C>>2]|0)+4>>2];g[(c[C>>2]|0)+4>>2]=f;if(0.0>+g[(c[C>>2]|0)+8>>2])f=0.0;else f=+g[(c[C>>2]|0)+8>>2];g[(c[C>>2]|0)+8>>2]=f;h=c[C>>2]|0;if(+g[c[C>>2]>>2]>+g[(c[C>>2]|0)+8>>2])f=+g[h>>2];else f=+g[h+8>>2];if(f>7.999999797903001e-04){g[y>>2]=+O(+(+g[c[C>>2]>>2]));g[z>>2]=+O(+(+g[(c[C>>2]|0)+8>>2]));g[w>>2]=+O(+(+g[y>>2]));g[x>>2]=+O(+(+g[z>>2]));if(+g[(c[C>>2]|0)+4>>2]<+g[y>>2]*+g[z>>2])f=+g[(c[C>>2]|0)+4>>2];else f=+g[y>>2]*+g[z>>2];g[(c[C>>2]|0)+4>>2]=f;g[u>>2]=+g[(c[C>>2]|0)+4>>2]/(+g[y>>2]*+g[z>>2]+1.0000000036274937e-15);f=+N(+(+g[w>>2]-+g[x>>2]))*1.0;g[v>>2]=f/(+g[w>>2]+1.0000000036274937e-15+ +g[x>>2]);f=+O(+(1.0-+g[u>>2]*+g[u>>2]));g[A>>2]=f*+g[v>>2];h=(c[C>>2]|0)+12|0;g[h>>2]=+g[h>>2]+(+g[A>>2]-+g[(c[C>>2]|0)+12>>2])/+(c[B>>2]|0);h=c[C>>2]|0;if(+g[(c[C>>2]|0)+16>>2]-.019999999552965164/+(c[B>>2]|0)>+g[(c[C>>2]|0)+12>>2])f=+g[h+16>>2]-.019999999552965164/+(c[B>>2]|0);else f=+g[h+12>>2];g[(c[C>>2]|0)+16>>2]=f}else{g[A>>2]=0.0;g[u>>2]=1.0;g[v>>2]=0.0}if(1.0<+g[(c[C>>2]|0)+16>>2]*20.0){f=1.0;i=D;return +f}f=+g[(c[C>>2]|0)+16>>2]*20.0;i=D;return +f}function Fi(e,f,h,j,k,l,m,n,o,p,q,r,s){e=e|0;f=f|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;n=n|0;o=o|0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0)/4|0)<<2);lb(e,10015,w)|0;c[fb>>2]=0;if((c[(c[Pb>>2]|0)+8+36>>2]|0)>=7?(c[(c[Pb>>2]|0)+132>>2]|0)==48e3:0){c[S>>2]=c[(c[Pb>>2]|0)+172+8508>>2];c[T>>2]=c[(c[Pb>>2]|0)+172+8512>>2];aj((c[Pb>>2]|0)+172|0,c[$a>>2]|0,c[u>>2]|0,c[v>>2]|0,c[Gb>>2]|0,c[ca>>2]|0,c[Y>>2]|0,c[Z>>2]|0,c[(c[Pb>>2]|0)+132>>2]|0,c[ba>>2]|0,c[$>>2]|0,fb)}c[(c[Pb>>2]|0)+128>>2]=-1;c[(c[Pb>>2]|0)+18212>>2]=0;do if(c[fb>>2]|0){if((c[(c[Pb>>2]|0)+112>>2]|0)==-1e3){w=~~+M(+((1.0-+g[fb+20>>2])*100.0+.5));c[(c[Pb>>2]|0)+128>>2]=w}c[x>>2]=c[fb+24>>2];if((c[x>>2]|0)<=12){c[(c[Pb>>2]|0)+18212>>2]=1101;break}if((c[x>>2]|0)<=14){c[(c[Pb>>2]|0)+18212>>2]=1102;break}if((c[x>>2]|0)<=16){c[(c[Pb>>2]|0)+18212>>2]=1103;break}q=(c[Pb>>2]|0)+18212|0;if((c[x>>2]|0)<=18){c[q>>2]=1104;break}else{c[q>>2]=1105;break}}while(0);if((c[(c[Pb>>2]|0)+100>>2]|0)==2?(c[(c[Pb>>2]|0)+108>>2]|0)!=1:0)g[F>>2]=+Ei(c[sa>>2]|0,c[Gb>>2]|0,c[(c[Pb>>2]|0)+132>>2]|0,(c[Pb>>2]|0)+14352|0);else g[F>>2]=0.0;c[_a>>2]=c[y>>2];y=Gi(c[Pb>>2]|0,c[Gb>>2]|0,c[Ib>>2]|0)|0;c[(c[Pb>>2]|0)+148>>2]=y;c[Da>>2]=(c[(c[Pb>>2]|0)+132>>2]|0)/(c[Gb>>2]|0)|0;do if((c[Ib>>2]|0)>=3?(c[(c[Pb>>2]|0)+148>>2]|0)>=((c[Da>>2]|0)*3<<3|0):0){if((c[Da>>2]|0)<50){if((_(c[Ib>>2]|0,c[Da>>2]|0)|0)<300)break;if((c[(c[Pb>>2]|0)+148>>2]|0)<2400)break}if(!(c[(c[Pb>>2]|0)+136>>2]|0)){if((((c[(c[Pb>>2]|0)+148>>2]|0)+(c[Da>>2]<<2)|0)/(c[Da>>2]<<3|0)|0|0)<(c[Ib>>2]|0))q=((c[(c[Pb>>2]|0)+148>>2]|0)+(c[Da>>2]<<2)|0)/(c[Da>>2]<<3|0)|0;else q=c[Ib>>2]|0;c[A>>2]=q;B=_(c[A>>2]|0,c[Da>>2]<<3)|0;c[(c[Pb>>2]|0)+148>>2]=B;c[Ib>>2]=c[A>>2]}c[Ba>>2]=(_(c[Da>>2]|0,c[Ib>>2]|0)|0)<<3;c[Za>>2]=(c[(c[Pb>>2]|0)+148>>2]|0)-(_(((c[(c[Pb>>2]|0)+100>>2]|0)*40|0)+20|0,((c[(c[Pb>>2]|0)+132>>2]|0)/(c[Gb>>2]|0)|0)-50|0)|0);do if((c[(c[Pb>>2]|0)+112>>2]|0)!=3001){if((c[(c[Pb>>2]|0)+112>>2]|0)==3002){c[K>>2]=0;break}q=c[Pb>>2]|0;if((c[(c[Pb>>2]|0)+128>>2]|0)>=0){c[K>>2]=(c[q+128>>2]|0)*327>>8;if((c[(c[Pb>>2]|0)+96>>2]|0)!=2049)break;c[K>>2]=(c[K>>2]|0)<115?c[K>>2]|0:115;break}if((c[q+96>>2]|0)==2048){c[K>>2]=115;break}else{c[K>>2]=48;break}}else c[K>>2]=127;while(0);if((c[(c[Pb>>2]|0)+108>>2]|0)!=-1e3?(c[(c[Pb>>2]|0)+100>>2]|0)==2:0)c[(c[Pb>>2]|0)+14288>>2]=c[(c[Pb>>2]|0)+108>>2];else Eb=73;do if((Eb|0)==73){if((c[(c[Pb>>2]|0)+100>>2]|0)!=2){c[(c[Pb>>2]|0)+14288>>2]=c[(c[Pb>>2]|0)+100>>2];break}c[C>>2]=3e4;q=c[C>>2]|0;if((c[(c[Pb>>2]|0)+14288>>2]|0)==2)c[C>>2]=q-1e3;else c[C>>2]=q+1e3;c[(c[Pb>>2]|0)+14288>>2]=(c[Za>>2]|0)>(c[C>>2]|0)?2:1}while(0);c[Za>>2]=(c[(c[Pb>>2]|0)+148>>2]|0)-(_(((c[(c[Pb>>2]|0)+14288>>2]|0)*40|0)+20|0,((c[(c[Pb>>2]|0)+132>>2]|0)/(c[Gb>>2]|0)|0)-50|0)|0);q=c[Pb>>2]|0;do if((c[(c[Pb>>2]|0)+96>>2]|0)==2051)c[q+14320>>2]=1002;else{if((c[q+124>>2]|0)!=-1e3){c[(c[Pb>>2]|0)+14320>>2]=c[(c[Pb>>2]|0)+124>>2];break}c[E>>2]=~~((1.0-+g[F>>2])*+(c[4508]|0)+ +g[F>>2]*+(c[4510]|0));c[D>>2]=~~((1.0-+g[F>>2])*+(c[4511]|0)+ +g[F>>2]*+(c[4511]|0));F=_(c[K>>2]|0,c[K>>2]|0)|0;c[G>>2]=(c[D>>2]|0)+((_(F,(c[E>>2]|0)-(c[D>>2]|0)|0)|0)>>14);if((c[(c[Pb>>2]|0)+96>>2]|0)==2048)c[G>>2]=(c[G>>2]|0)+8e3;do if((c[(c[Pb>>2]|0)+14324>>2]|0)==1002)c[G>>2]=(c[G>>2]|0)-4e3;else{if((c[(c[Pb>>2]|0)+14324>>2]|0)<=0)break;c[G>>2]=(c[G>>2]|0)+4e3}while(0);c[(c[Pb>>2]|0)+14320>>2]=(c[Za>>2]|0)>=(c[G>>2]|0)?1002:1e3;do if(c[(c[Pb>>2]|0)+8+40>>2]|0){if((c[(c[Pb>>2]|0)+8+32>>2]|0)<=(128-(c[K>>2]|0)>>4|0))break;c[(c[Pb>>2]|0)+14320>>2]=1e3}while(0);if(!((c[K>>2]|0)>100?(c[(c[Pb>>2]|0)+8+44>>2]|0)!=0:0))break;c[(c[Pb>>2]|0)+14320>>2]=1e3}while(0);if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002?(c[Gb>>2]|0)<((c[(c[Pb>>2]|0)+132>>2]|0)/100|0|0):0)c[(c[Pb>>2]|0)+14320>>2]=1002;if(c[(c[Pb>>2]|0)+164>>2]|0)c[(c[Pb>>2]|0)+14320>>2]=1002;G=_((c[Da>>2]|0)>50?12e3:8e3,c[Gb>>2]|0)|0;if((c[Ib>>2]|0)<((G|0)/(c[(c[Pb>>2]|0)+132>>2]<<3|0)|0|0))c[(c[Pb>>2]|0)+14320>>2]=1002;do if((c[(c[Pb>>2]|0)+14288>>2]|0)==1){if((c[(c[Pb>>2]|0)+14328>>2]|0)!=2){Eb=107;break}if(c[(c[Pb>>2]|0)+8+56>>2]|0){Eb=107;break}if((c[(c[Pb>>2]|0)+14320>>2]|0)==1002){Eb=107;break}if((c[(c[Pb>>2]|0)+14324>>2]|0)==1002){Eb=107;break}c[(c[Pb>>2]|0)+8+56>>2]=1;c[(c[Pb>>2]|0)+14288>>2]=2}else Eb=107;while(0);if((Eb|0)==107)c[(c[Pb>>2]|0)+8+56>>2]=0;do if((c[(c[Pb>>2]|0)+14324>>2]|0)>0){if(!((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002?(c[(c[Pb>>2]|0)+14324>>2]|0)==1002:0)){if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002)break;if((c[(c[Pb>>2]|0)+14324>>2]|0)==1002)break}c[Jb>>2]=1;c[hb>>2]=(c[(c[Pb>>2]|0)+14320>>2]|0)!=1002&1;if(c[hb>>2]|0)break;if((c[Gb>>2]|0)>=((c[(c[Pb>>2]|0)+132>>2]|0)/100|0|0)){c[(c[Pb>>2]|0)+14320>>2]=c[(c[Pb>>2]|0)+14324>>2];c[Lb>>2]=1;break}else{c[Jb>>2]=0;break}}while(0);if(c[(c[Pb>>2]|0)+14340>>2]|0){c[Jb>>2]=1;c[hb>>2]=1;c[(c[Pb>>2]|0)+14340>>2]=0;c[Ea>>2]=1}do if(c[Jb>>2]|0){G=_(c[Ib>>2]|0,(c[(c[Pb>>2]|0)+132>>2]|0)/200|0)|0;if(257<((G|0)/((c[Gb>>2]|0)+((c[(c[Pb>>2]|0)+132>>2]|0)/200|0)|0)|0|0))q=257;else{q=_(c[Ib>>2]|0,(c[(c[Pb>>2]|0)+132>>2]|0)/200|0)|0;q=(q|0)/((c[Gb>>2]|0)+((c[(c[Pb>>2]|0)+132>>2]|0)/200|0)|0)|0}c[Kb>>2]=q;if(!(c[(c[Pb>>2]|0)+136>>2]|0))break;if((c[Kb>>2]|0)<((c[(c[Pb>>2]|0)+148>>2]|0)/1600|0|0))q=c[Kb>>2]|0;else q=(c[(c[Pb>>2]|0)+148>>2]|0)/1600|0;c[Kb>>2]=q}while(0);do if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002){if((c[(c[Pb>>2]|0)+14324>>2]|0)!=1002)break;Td(c[Ga>>2]|0,c[(c[Pb>>2]|0)+168>>2]|0,H)|0;c[Ea>>2]=1}while(0);do if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002){if(c[(c[Pb>>2]|0)+14344>>2]|0){Eb=133;break}if(c[(c[Pb>>2]|0)+8+72>>2]|0)Eb=133}else Eb=133;while(0);do if((Eb|0)==133){c[L>>2]=1105;c[O>>2]=c[Za>>2];do if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002){c[O>>2]=(_(c[O>>2]|0,45+(c[(c[Pb>>2]|0)+8+36>>2]|0)|0)|0)/50|0;if(c[(c[Pb>>2]|0)+136>>2]|0)break;c[O>>2]=(c[O>>2]|0)-1e3}while(0);do if((c[(c[Pb>>2]|0)+100>>2]|0)==2){if((c[(c[Pb>>2]|0)+108>>2]|0)==1){Eb=139;break}c[J>>2]=18048;c[I>>2]=18080}else Eb=139;while(0);if((Eb|0)==139){c[J>>2]=18112;c[I>>2]=18144}c[Xa>>2]=0;while(1){if((c[Xa>>2]|0)>=8)break;H=_(c[K>>2]|0,c[K>>2]|0)|0;H=(c[(c[I>>2]|0)+(c[Xa>>2]<<2)>>2]|0)+((_(H,(c[(c[J>>2]|0)+(c[Xa>>2]<<2)>>2]|0)-(c[(c[I>>2]|0)+(c[Xa>>2]<<2)>>2]|0)|0)|0)>>14)|0;c[N+(c[Xa>>2]<<2)>>2]=H;c[Xa>>2]=(c[Xa>>2]|0)+1}do{c[Q>>2]=c[N+((c[L>>2]|0)-1102<<1<<2)>>2];c[P>>2]=c[N+(((c[L>>2]|0)-1102<<1)+1<<2)>>2];do if(!(c[(c[Pb>>2]|0)+14344>>2]|0)){q=c[P>>2]|0;m=c[Q>>2]|0;if((c[(c[Pb>>2]|0)+14336>>2]|0)>=(c[L>>2]|0)){c[Q>>2]=m-q;break}else{c[Q>>2]=m+q;break}}while(0);if((c[O>>2]|0)>=(c[Q>>2]|0))break;K=(c[L>>2]|0)+-1|0;c[L>>2]=K}while((K|0)>1101);c[(c[Pb>>2]|0)+14336>>2]=c[L>>2];if(c[(c[Pb>>2]|0)+14344>>2]|0)break;if((c[(c[Pb>>2]|0)+14320>>2]|0)==1002)break;if(c[(c[Pb>>2]|0)+8+76>>2]|0)break;if((c[(c[Pb>>2]|0)+14336>>2]|0)<=1103)break;c[(c[Pb>>2]|0)+14336>>2]=1103}while(0);if((c[(c[Pb>>2]|0)+14336>>2]|0)>(c[(c[Pb>>2]|0)+120>>2]|0))c[(c[Pb>>2]|0)+14336>>2]=c[(c[Pb>>2]|0)+120>>2];if((c[(c[Pb>>2]|0)+116>>2]|0)!=-1e3)c[(c[Pb>>2]|0)+14336>>2]=c[(c[Pb>>2]|0)+116>>2];if((c[Ba>>2]|0)<15e3?(c[(c[Pb>>2]|0)+14320>>2]|0)!=1002:0){if((c[(c[Pb>>2]|0)+14336>>2]|0)<1103)q=c[(c[Pb>>2]|0)+14336>>2]|0;else q=1103;c[(c[Pb>>2]|0)+14336>>2]=q}do if((c[(c[Pb>>2]|0)+132>>2]|0)<=24e3){if((c[(c[Pb>>2]|0)+14336>>2]|0)<=1104)break;c[(c[Pb>>2]|0)+14336>>2]=1104}while(0);do if((c[(c[Pb>>2]|0)+132>>2]|0)<=16e3){if((c[(c[Pb>>2]|0)+14336>>2]|0)<=1103)break;c[(c[Pb>>2]|0)+14336>>2]=1103}while(0);do if((c[(c[Pb>>2]|0)+132>>2]|0)<=12e3){if((c[(c[Pb>>2]|0)+14336>>2]|0)<=1102)break;c[(c[Pb>>2]|0)+14336>>2]=1102}while(0);do if((c[(c[Pb>>2]|0)+132>>2]|0)<=8e3){if((c[(c[Pb>>2]|0)+14336>>2]|0)<=1101)break;c[(c[Pb>>2]|0)+14336>>2]=1101}while(0);do if(c[(c[Pb>>2]|0)+18212>>2]|0){if((c[(c[Pb>>2]|0)+116>>2]|0)!=-1e3)break;do if((c[Za>>2]|0)<=((c[(c[Pb>>2]|0)+14288>>2]|0)*18e3|0)){if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002){Eb=179;break}c[R>>2]=1101}else Eb=179;while(0);a:do if((Eb|0)==179){do if((c[Za>>2]|0)<=((c[(c[Pb>>2]|0)+14288>>2]|0)*24e3|0)){if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002)break;c[R>>2]=1102;break a}while(0);if((c[Za>>2]|0)<=((c[(c[Pb>>2]|0)+14288>>2]|0)*3e4|0)){c[R>>2]=1103;break}if((c[Za>>2]|0)<=((c[(c[Pb>>2]|0)+14288>>2]|0)*44e3|0)){c[R>>2]=1104;break}else{c[R>>2]=1105;break}}while(0);if((c[(c[Pb>>2]|0)+18212>>2]|0)>(c[R>>2]|0))q=c[(c[Pb>>2]|0)+18212>>2]|0;else q=c[R>>2]|0;c[(c[Pb>>2]|0)+18212>>2]=q;q=c[Pb>>2]|0;if((c[(c[Pb>>2]|0)+14336>>2]|0)<(c[(c[Pb>>2]|0)+18212>>2]|0))q=c[q+14336>>2]|0;else q=c[q+18212>>2]|0;c[(c[Pb>>2]|0)+14336>>2]=q}while(0);R=c[gb>>2]|0;c[U>>2]=c[ba>>2];lb(R,4036,U)|0;do if((c[(c[Pb>>2]|0)+14320>>2]|0)==1002){if((c[(c[Pb>>2]|0)+14336>>2]|0)!=1102)break;c[(c[Pb>>2]|0)+14336>>2]=1103}while(0);if(c[(c[Pb>>2]|0)+164>>2]|0)c[(c[Pb>>2]|0)+14336>>2]=1101;do if((c[Gb>>2]|0)>((c[(c[Pb>>2]|0)+132>>2]|0)/50|0|0)){if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002?(c[(c[Pb>>2]|0)+14336>>2]|0)<=1103:0)break;if((c[S>>2]|0)!=-1){c[(c[Pb>>2]|0)+172+8508>>2]=c[S>>2];c[(c[Pb>>2]|0)+172+8512>>2]=c[T>>2]}c[oa>>2]=(c[Gb>>2]|0)>((c[(c[Pb>>2]|0)+132>>2]|0)/25|0|0)?3:2;if(1276<(((c[aa>>2]|0)-3|0)/(c[oa>>2]|0)|0|0))q=1276;else q=((c[aa>>2]|0)-3|0)/(c[oa>>2]|0)|0;c[da>>2]=q;q=_(c[oa>>2]|0,c[da>>2]|0)|0;c[fa>>2]=ia()|0;m=i;i=i+((1*q|0)+15&-16)|0;Ti(qa)|0;c[ka>>2]=c[(c[Pb>>2]|0)+124>>2];c[ha>>2]=c[(c[Pb>>2]|0)+116>>2];c[ja>>2]=c[(c[Pb>>2]|0)+108>>2];c[(c[Pb>>2]|0)+124>>2]=c[(c[Pb>>2]|0)+14320>>2];c[(c[Pb>>2]|0)+116>>2]=c[(c[Pb>>2]|0)+14336>>2];c[(c[Pb>>2]|0)+108>>2]=c[(c[Pb>>2]|0)+14288>>2];c[la>>2]=c[(c[Pb>>2]|0)+8+56>>2];q=c[Pb>>2]|0;if(c[la>>2]|0)c[q+108>>2]=1;else c[(c[Pb>>2]|0)+14328>>2]=c[q+14288>>2];c[Xa>>2]=0;while(1){q=c[Pb>>2]|0;if((c[Xa>>2]|0)>=(c[oa>>2]|0)){Eb=219;break}c[q+8+56>>2]=0;do if(c[Lb>>2]|0){if((c[Xa>>2]|0)!=((c[oa>>2]|0)-1|0))break;c[(c[Pb>>2]|0)+124>>2]=1002}while(0);Jb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)==1001){q=_(c[(c[Pb>>2]|0)+14288>>2]|0,5e3+(((c[(c[Pb>>2]|0)+132>>2]|0)==((c[Gb>>2]|0)*100|0)&1)*1e3|0)|0)|0;c[(c[Pb>>2]|0)+8+28>>2]=q;q=(c[ra>>2]|0)-(c[(c[Pb>>2]|0)+8+28>>2]|0)|0;if((c[ib>>2]|0)==1104){ta=(c[Pb>>2]|0)+8+28|0;c[ta>>2]=(c[ta>>2]|0)+((q<<1|0)/3|0)}else{ta=(c[Pb>>2]|0)+8+28|0;c[ta>>2]=(c[ta>>2]|0)+((q*3|0)/5|0)}if((c[(c[Pb>>2]|0)+8+28>>2]|0)>((c[ra>>2]<<2|0)/5|0|0))c[(c[Pb>>2]|0)+8+28>>2]=(c[ra>>2]<<2|0)/5|0;if(c[(c[Pb>>2]|0)+14348>>2]|0)break;c[ma>>2]=(c[ra>>2]|0)-(c[(c[Pb>>2]|0)+8+28>>2]|0);c[ga>>2]=(c[ib>>2]|0)==1104?3e3:3600;g[Ya>>2]=+(c[ma>>2]|0)/(+(c[ma>>2]|0)+ +(_(c[(c[Pb>>2]|0)+14288>>2]|0,c[ga>>2]|0)|0));g[Ya>>2]=+g[Ya>>2]<.8571428656578064?+g[Ya>>2]+.1428571492433548:1.0}else c[(c[Pb>>2]|0)+8+28>>2]=c[ra>>2];while(0);do if(c[(c[Pb>>2]|0)+14348>>2]|0){if(!(c[(c[Pb>>2]|0)+136>>2]|0))break;if(c[(c[Pb>>2]|0)+164>>2]|0)break;g[xa>>2]=0.0;c[va>>2]=17;b[za>>1]=16e3;do if((c[(c[Pb>>2]|0)+14336>>2]|0)==1101){c[va>>2]=13;b[za>>1]=8e3}else{if((c[(c[Pb>>2]|0)+14336>>2]|0)!=1102)break;c[va>>2]=15;b[za>>1]=12e3}while(0);c[ua>>2]=0;while(1){if((c[ua>>2]|0)>=(c[(c[Pb>>2]|0)+100>>2]|0))break;c[Xa>>2]=0;while(1){q=c[ua>>2]|0;if((c[Xa>>2]|0)>=(c[va>>2]|0))break;if(+g[(c[(c[Pb>>2]|0)+14348>>2]|0)+((q*21|0)+(c[Xa>>2]|0)<<2)>>2]<.5)t=+g[(c[(c[Pb>>2]|0)+14348>>2]|0)+(((c[ua>>2]|0)*21|0)+(c[Xa>>2]|0)<<2)>>2];else t=.5;do if(t>-2.0){if(!(+g[(c[(c[Pb>>2]|0)+14348>>2]|0)+(((c[ua>>2]|0)*21|0)+(c[Xa>>2]|0)<<2)>>2]<.5)){t=.5;break}t=+g[(c[(c[Pb>>2]|0)+14348>>2]|0)+(((c[ua>>2]|0)*21|0)+(c[Xa>>2]|0)<<2)>>2]}else t=-2.0;while(0);g[wa>>2]=t;if(+g[wa>>2]>0.0)g[wa>>2]=+g[wa>>2]*.5;g[xa>>2]=+g[xa>>2]+ +g[wa>>2];c[Xa>>2]=(c[Xa>>2]|0)+1}c[ua>>2]=q+1}g[ya>>2]=+g[xa>>2]/+(c[va>>2]|0)*+(c[(c[Pb>>2]|0)+100>>2]|0);g[ya>>2]=+g[ya>>2]+.20000000298023224;c[Aa>>2]=~~(+(b[za>>1]|0)*+g[ya>>2]);if((c[Aa>>2]|0)>((_(-2,c[(c[Pb>>2]|0)+8+28>>2]|0)|0)/3|0|0))q=c[Aa>>2]|0;else q=(_(-2,c[(c[Pb>>2]|0)+8+28>>2]|0)|0)/3|0;c[Aa>>2]=q;do if((c[(c[Pb>>2]|0)+14336>>2]|0)==1104)Eb=281;else{if((c[(c[Pb>>2]|0)+14336>>2]|0)==1105){Eb=281;break}za=(c[Pb>>2]|0)+8+28|0;c[za>>2]=(c[za>>2]|0)+(c[Aa>>2]|0)}while(0);if((Eb|0)==281){za=(c[Pb>>2]|0)+8+28|0;c[za>>2]=(c[za>>2]|0)+(((c[Aa>>2]|0)*3|0)/5|0)}Aa=_(c[Aa>>2]|0,c[Gb>>2]|0)|0;c[Va>>2]=(c[Va>>2]|0)+((Aa|0)/(c[(c[Pb>>2]|0)+132>>2]<<3|0)|0)}while(0);c[(c[Pb>>2]|0)+8+24>>2]=((c[Gb>>2]|0)*1e3|0)/(c[(c[Pb>>2]|0)+132>>2]|0)|0;c[(c[Pb>>2]|0)+8>>2]=c[(c[Pb>>2]|0)+100>>2];c[(c[Pb>>2]|0)+8+4>>2]=c[(c[Pb>>2]|0)+14288>>2];do if((c[ib>>2]|0)!=1101){q=(c[Pb>>2]|0)+8+20|0;if((c[ib>>2]|0)==1102){c[q>>2]=12e3;break}else{c[q>>2]=16e3;break}}else c[(c[Pb>>2]|0)+8+20>>2]=8e3;while(0);q=(c[Pb>>2]|0)+8+16|0;if((c[(c[Pb>>2]|0)+14320>>2]|0)==1001)c[q>>2]=16e3;else c[q>>2]=8e3;do if((c[(c[Pb>>2]|0)+14320>>2]|0)==1e3){c[Ca>>2]=c[Ba>>2];c[(c[Pb>>2]|0)+8+12>>2]=16e3;if((c[Da>>2]|0)>50)c[Ca>>2]=(c[Ca>>2]<<1|0)/3|0;if((c[Ca>>2]|0)<13e3){c[(c[Pb>>2]|0)+8+12>>2]=12e3;if(12e3<(c[(c[Pb>>2]|0)+8+20>>2]|0))q=12e3;else q=c[(c[Pb>>2]|0)+8+20>>2]|0;c[(c[Pb>>2]|0)+8+20>>2]=q}if((c[Ca>>2]|0)>=9600)break;c[(c[Pb>>2]|0)+8+12>>2]=8e3;if(8e3<(c[(c[Pb>>2]|0)+8+20>>2]|0))q=8e3;else q=c[(c[Pb>>2]|0)+8+20>>2]|0;c[(c[Pb>>2]|0)+8+20>>2]=q}else c[(c[Pb>>2]|0)+8+12>>2]=16e3;while(0);c[(c[Pb>>2]|0)+8+48>>2]=((c[(c[Pb>>2]|0)+136>>2]|0)!=0^1)&1;if(1275<((c[Ib>>2]|0)-1-(c[Kb>>2]|0)|0))q=1275;else q=(c[Ib>>2]|0)-1-(c[Kb>>2]|0)|0;c[Ma>>2]=q;c[(c[Pb>>2]|0)+8+52>>2]=c[Ma>>2]<<3;if((c[(c[Pb>>2]|0)+14320>>2]|0)==1001)c[(c[Pb>>2]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;Ha=_(c[_a>>2]|0,c[(c[Pb>>2]|0)+100>>2]|0)|0;Ha=Ni(+g[n+(Ha+(c[Xa>>2]|0)<<2)>>2])|0;b[m+(c[Xa>>2]<<1)>>1]=Ha;c[Xa>>2]=(c[Xa>>2]|0)+1}c[Nb>>2]=Vd(c[Ga>>2]|0,(c[Pb>>2]|0)+8|0,m,c[Gb>>2]|0,Hb,Ma,0)|0;do if(c[Nb>>2]|0){c[Ob>>2]=-3;c[Mb>>2]=1}else{q=c[Pb>>2]|0;if(!(c[Ma>>2]|0)){c[q+18216>>2]=0;Xa=Hi(c[(c[Pb>>2]|0)+14320>>2]|0,(c[(c[Pb>>2]|0)+132>>2]|0)/(c[Gb>>2]|0)|0,c[ib>>2]|0,c[(c[Pb>>2]|0)+14288>>2]|0)|0;a[(c[Qb>>2]|0)+-1>>0]=Xa;c[Ob>>2]=1;c[Mb>>2]=1;break}do if((c[q+14320>>2]|0)==1e3){if((c[(c[Pb>>2]|0)+8+68>>2]|0)==8e3){c[ib>>2]=1101;break}if((c[(c[Pb>>2]|0)+8+68>>2]|0)==12e3){c[ib>>2]=1102;break}if((c[(c[Pb>>2]|0)+8+68>>2]|0)!=16e3)break;c[ib>>2]=1103}while(0);c[(c[Pb>>2]|0)+8+60>>2]=c[(c[Pb>>2]|0)+8+84>>2];if(c[(c[Pb>>2]|0)+8+60>>2]|0){c[Jb>>2]=1;c[hb>>2]=0;c[(c[Pb>>2]|0)+14340>>2]=1}c[Mb>>2]=0}while(0);na(c[Ia>>2]|0);if(!(c[Mb>>2]|0))Eb=335}else Eb=335;b:do if((Eb|0)==335){c[La>>2]=21;switch(c[ib>>2]|0){case 1101:{c[La>>2]=13;break}case 1103:case 1102:{c[La>>2]=17;break}case 1104:{c[La>>2]=19;break}case 1105:{c[La>>2]=21;break}default:{}}Xa=c[gb>>2]|0;c[Na>>2]=c[La>>2];lb(Xa,10012,Na)|0;Xa=c[gb>>2]|0;c[Oa>>2]=c[(c[Pb>>2]|0)+14288>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]|0);b[(c[Pb>>2]|0)+14292>>1]=c[(c[Pb>>2]|0)+8+80>>2]}while(0);do if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002){bb=(Oi(Hb)|0)+17|0;if((bb+(((c[(c[Pb>>2]|0)+14320>>2]|0)==1001&1)*20|0)|0)>((c[Ib>>2]|0)-1<<3|0)){Eb=393;break}do if((c[(c[Pb>>2]|0)+14320>>2]|0)==1001){if((c[Jb>>2]|0)==0?(bb=(Oi(Hb)|0)+37|0,(bb|0)>(c[pb>>2]<<3|0)):0)break;pc(Hb,c[Jb>>2]|0,12)}while(0);if(!(c[Jb>>2]|0))break;pc(Hb,c[hb>>2]|0,1);q=(c[Ib>>2]|0)-1|0;if((c[(c[Pb>>2]|0)+14320>>2]|0)==1001)c[cb>>2]=q-(c[pb>>2]|0);else c[cb>>2]=q-((Oi(Hb)|0)+7>>3);if((c[cb>>2]|0)<((c[(c[Pb>>2]|0)+148>>2]|0)/1600|0|0))q=c[cb>>2]|0;else q=(c[(c[Pb>>2]|0)+148>>2]|0)/1600|0;c[Kb>>2]=q;if(257<((2>(c[Kb>>2]|0)?2:c[Kb>>2]|0)|0))q=257;else q=2>(c[Kb>>2]|0)?2:c[Kb>>2]|0;c[Kb>>2]=q;if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1001)break;rc(Hb,(c[Kb>>2]|0)-2|0,256)}else Eb=393;while(0);if((Eb|0)==393)c[Jb>>2]=0;if(!(c[Jb>>2]|0)){c[(c[Pb>>2]|0)+14340>>2]=0;c[Kb>>2]=0}if((c[(c[Pb>>2]|0)+14320>>2]|0)!=1002)c[rb>>2]=17;if((c[(c[Pb>>2]|0)+14320>>2]|0)==1e3){c[Nb>>2]=(Oi(Hb)|0)+7>>3;wc(Hb);c[pb>>2]=c[Nb>>2]}else{if(((c[Ib>>2]|0)-1-(c[Kb>>2]|0)|0)<(c[pb>>2]|0))q=(c[Ib>>2]|0)-1-(c[Kb>>2]|0)|0;else q=c[pb>>2]|0;c[pb>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2]|0)+1>>0]=0;c[Nb>>2]=1;c[(c[Pb>>2]|0)+18216>>2]=0;break}else{if(!(((c[Jb>>2]|0?1:(c[(c[Pb>>2]|0)+14320>>2]|0)!=1e3)^1)&(c[Nb>>2]|0)>2))break;do{if(d[(c[Qb>>2]|0)+(c[Nb>>2]|0)>>0]|0)break c;c[Nb>>2]=(c[Nb>>2]|0)+-1}while((c[Nb>>2]|0)>2)}while(0);c[Nb>>2]=(c[Nb>>2]|0)+(1+(c[Kb>>2]|0));do if(!(c[(c[Pb>>2]|0)+136>>2]|0))if(Xi(c[Qb>>2]|0,c[Nb>>2]|0,c[Ib>>2]|0)|0){c[Ob>>2]=-3;c[Mb>>2]=1;break b}else{c[Nb>>2]=c[Ib>>2];break}while(0);c[Ob>>2]=c[Nb>>2];c[Mb>>2]=1}while(0);na(c[Fb>>2]|0);Qb=c[Ob>>2]|0;i=Rb;return Qb|0}while(0);c[B>>2]=c[(c[Pb>>2]|0)+14320>>2];if(!(c[(c[Pb>>2]|0)+14336>>2]|0))q=1101;else q=c[(c[Pb>>2]|0)+14336>>2]|0;c[z>>2]=q;if(!(c[B>>2]|0))c[B>>2]=1e3;if((c[Da>>2]|0)>100)c[B>>2]=1002;if((c[Da>>2]|0)<50)c[B>>2]=1e3;do if(!((c[B>>2]|0)==1e3&(c[z>>2]|0)>1103)){if((c[B>>2]|0)==1002&(c[z>>2]|0)==1102){c[z>>2]=1101;break}if((c[z>>2]|0)<=1104)c[z>>2]=1104}else c[z>>2]=1103;while(0);Pb=Hi(c[B>>2]|0,c[Da>>2]|0,c[z>>2]|0,c[(c[Pb>>2]|0)+14288>>2]|0)|0;a[c[Qb>>2]>>0]=Pb;c[Ob>>2]=1;Qb=c[Ob>>2]|0;i=Rb;return Qb|0}c[Ob>>2]=-1;Qb=c[Ob>>2]|0;i=Rb;return Qb|0}function Gi(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0;j=i;i=i+16|0;e=j+12|0;f=j+8|0;g=j+4|0;h=j;c[f>>2]=a;c[g>>2]=b;c[h>>2]=d;if(!(c[g>>2]|0))c[g>>2]=(c[(c[f>>2]|0)+132>>2]|0)/400|0;b=c[f>>2]|0;if((c[(c[f>>2]|0)+152>>2]|0)==-1e3){c[e>>2]=(((c[b+132>>2]|0)*60|0)/(c[g>>2]|0)|0)+(_(c[(c[f>>2]|0)+132>>2]|0,c[(c[f>>2]|0)+100>>2]|0)|0);h=c[e>>2]|0;i=j;return h|0}if((c[b+152>>2]|0)==-1){h=_(c[h>>2]<<3,c[(c[f>>2]|0)+132>>2]|0)|0;c[e>>2]=(h|0)/(c[g>>2]|0)|0;h=c[e>>2]|0;i=j;return h|0}else{c[e>>2]=c[(c[f>>2]|0)+152>>2];h=c[e>>2]|0;i=j;return h|0}return 0}function Hi(b,e,f,g){b=b|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;p=i;i=i+32|0;h=p+20|0;j=p+16|0;k=p+12|0;l=p+8|0;m=p+4|0;o=p+24|0;n=p;c[h>>2]=b;c[j>>2]=e;c[k>>2]=f;c[l>>2]=g;c[m>>2]=0;while(1){if((c[j>>2]|0)>=400)break;c[j>>2]=c[j>>2]<<1;c[m>>2]=(c[m>>2]|0)+1}do if((c[h>>2]|0)!=1e3)if((c[h>>2]|0)==1002){b=(c[k>>2]|0)-1102|0;c[n>>2]=b;c[n>>2]=(c[n>>2]|0)<0?0:b;a[o>>0]=-128;a[o>>0]=d[o>>0]|0|c[n>>2]<<5;a[o>>0]=d[o>>0]|0|c[m>>2]<<3;break}else{a[o>>0]=96;a[o>>0]=d[o>>0]|0|(c[k>>2]|0)-1104<<4;a[o>>0]=d[o>>0]|0|(c[m>>2]|0)-2<<3;break}else{a[o>>0]=(c[k>>2]|0)-1101<<5;a[o>>0]=d[o>>0]|0|(c[m>>2]|0)-2<<3}while(0);a[o>>0]=d[o>>0]|0|((c[l>>2]|0)==2&1)<<2;i=p;return a[o>>0]|0}function Ii(a,b,d,e,f,g,h){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;q=i;i=i+64|0;j=q+60|0;v=q+56|0;k=q+52|0;l=q+48|0;m=q+44|0;n=q+40|0;u=q+36|0;p=q+24|0;o=q+16|0;s=q+8|0;t=q+4|0;r=q;c[j>>2]=a;c[v>>2]=b;c[k>>2]=d;c[l>>2]=e;c[m>>2]=f;c[n>>2]=g;c[u>>2]=h;c[s>>2]=(((c[v>>2]&65535)<<16>>16)*2471|0)/((c[u>>2]|0)/1e3|0|0)|0;c[t>>2]=268435456-((c[s>>2]|0)*471|0);c[p>>2]=c[t>>2];c[p+4>>2]=0-(c[t>>2]|0)<<1;c[p+8>>2]=c[t>>2];c[r>>2]=c[t>>2]>>6;d=_(c[s>>2]>>16,(c[s>>2]&65535)<<16>>16)|0;d=d+((_(c[s>>2]&65535,(c[s>>2]&65535)<<16>>16)|0)>>16)|0;d=_(c[r>>2]>>16,(d+(_(c[s>>2]|0,(c[s>>2]>>15)+1>>1)|0)-8388608&65535)<<16>>16)|0;f=_(c[s>>2]>>16,(c[s>>2]&65535)<<16>>16)|0;f=f+((_(c[s>>2]&65535,(c[s>>2]&65535)<<16>>16)|0)>>16)|0;f=d+((_(c[r>>2]&65535,(f+(_(c[s>>2]|0,(c[s>>2]>>15)+1>>1)|0)-8388608&65535)<<16>>16)|0)>>16)|0;d=_(c[s>>2]>>16,(c[s>>2]&65535)<<16>>16)|0;d=d+((_(c[s>>2]&65535,(c[s>>2]&65535)<<16>>16)|0)>>16)|0;c[o>>2]=f+(_(c[r>>2]|0,(d+(_(c[s>>2]|0,(c[s>>2]>>15)+1>>1)|0)-8388608>>15)+1>>1)|0);d=_(c[r>>2]>>16,(c[r>>2]&65535)<<16>>16)|0;d=d+((_(c[r>>2]&65535,(c[r>>2]&65535)<<16>>16)|0)>>16)|0;c[o+4>>2]=d+(_(c[r>>2]|0,(c[r>>2]>>15)+1>>1)|0);Ji(c[j>>2]|0,p,o,c[l>>2]|0,c[k>>2]|0,c[m>>2]|0,c[n>>2]|0);if((c[n>>2]|0)!=2){i=q;return}Ji((c[j>>2]|0)+4|0,p,o,(c[l>>2]|0)+8|0,(c[k>>2]|0)+4|0,c[m>>2]|0,c[n>>2]|0);i=q;return}function Ji(a,b,d,e,f,h,j){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;u=i;i=i+64|0;k=u+60|0;v=u+56|0;w=u+52|0;l=u+48|0;m=u+44|0;n=u+40|0;o=u+36|0;s=u+32|0;t=u+28|0;r=u+24|0;p=u+16|0;q=u;c[k>>2]=a;c[v>>2]=b;c[w>>2]=d;c[l>>2]=e;c[m>>2]=f;c[n>>2]=h;c[o>>2]=j;g[p>>2]=+(c[c[w>>2]>>2]|0)*3.725290298461914e-09;g[p+4>>2]=+(c[(c[w>>2]|0)+4>>2]|0)*3.725290298461914e-09;g[q>>2]=+(c[c[v>>2]>>2]|0)*3.725290298461914e-09;g[q+4>>2]=+(c[(c[v>>2]|0)+4>>2]|0)*3.725290298461914e-09;g[q+8>>2]=+(c[(c[v>>2]|0)+8>>2]|0)*3.725290298461914e-09;c[s>>2]=0;while(1){if((c[s>>2]|0)>=(c[n>>2]|0))break;w=_(c[s>>2]|0,c[o>>2]|0)|0;g[r>>2]=+g[(c[k>>2]|0)+(w<<2)>>2];g[t>>2]=+g[c[l>>2]>>2]+ +g[q>>2]*+g[r>>2];g[c[l>>2]>>2]=+g[(c[l>>2]|0)+4>>2]-+g[t>>2]*+g[p>>2]+ +g[q+4>>2]*+g[r>>2];g[(c[l>>2]|0)+4>>2]=-+g[t>>2]*+g[p+4>>2]+ +g[q+8>>2]*+g[r>>2]+1.0000000031710769e-30;w=_(c[s>>2]|0,c[o>>2]|0)|0;g[(c[m>>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2)>>2]=+g[u>>2]*+g[(c[m>>2]|0)+(c[w>>2]<<2)>>2];c[w>>2]=(c[w>>2]|0)+1}else while(1){if((c[w>>2]|0)>=(c[y>>2]|0))break a;C=_(c[w>>2]|0,c[x>>2]|0)|0;D=_(c[w>>2]|0,c[x>>2]|0)|0;g[A>>2]=+g[(c[s>>2]|0)+(C<<2)>>2]*+g[(c[s>>2]|0)+(D<<2)>>2];g[v>>2]=+g[A>>2]*+g[p>>2]+(1.0-+g[A>>2])*+g[o>>2];g[(c[n>>2]|0)+(c[w>>2]<<1<<2)>>2]=+g[v>>2]*+g[(c[m>>2]|0)+(c[w>>2]<<1<<2)>>2];g[(c[n>>2]|0)+((c[w>>2]<<1)+1<<2)>>2]=+g[v>>2]*+g[(c[m>>2]|0)+((c[w>>2]<<1)+1<<2)>>2];c[w>>2]=(c[w>>2]|0)+1}while(0);c[t>>2]=0;do{c[w>>2]=c[y>>2];while(1){if((c[w>>2]|0)>=(c[q>>2]|0))break;C=_(c[w>>2]|0,c[r>>2]|0)|0;D=_(c[w>>2]|0,c[r>>2]|0)|0;g[(c[n>>2]|0)+(D+(c[t>>2]|0)<<2)>>2]=+g[p>>2]*+g[(c[m>>2]|0)+(C+(c[t>>2]|0)<<2)>>2];c[w>>2]=(c[w>>2]|0)+1}D=(c[t>>2]|0)+1|0;c[t>>2]=D}while((D|0)<(c[r>>2]|0));i=B;return}function Ni(a){a=+a;var b=0,c=0;c=i;i=i+16|0;b=c;g[b>>2]=a;g[b>>2]=+g[b>>2]*32768.0;g[b>>2]=+g[b>>2]>-32768.0?+g[b>>2]:-32768.0;g[b>>2]=+g[b>>2]<32767.0?+g[b>>2]:32767.0;b=(ij(+g[b>>2])|0)&65535;i=c;return b|0}function Oi(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;a=(c[(c[d>>2]|0)+20>>2]|0)-(32-(aa(c[(c[d>>2]|0)+28>>2]|0)|0))|0;i=b;return a|0}function Pi(a,b,d,e,f,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X=0,Y=0,Z=0,_=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ia=0;ha=i;i=i+352|0;ca=ha+48|0;ba=ha+40|0;aa=ha+32|0;$=ha+24|0;_=ha+16|0;Z=ha+8|0;Y=ha;fa=ha+336|0;ea=ha+332|0;ia=ha+328|0;ga=ha+324|0;h=ha+320|0;f=ha+304|0;m=ha+300|0;n=ha+296|0;y=ha+292|0;J=ha+288|0;da=ha+284|0;T=ha+280|0;U=ha+276|0;V=ha+272|0;W=ha+268|0;X=ha+264|0;o=ha+260|0;p=ha+256|0;q=ha+252|0;r=ha+248|0;s=ha+244|0;t=ha+240|0;u=ha+236|0;v=ha+232|0;w=ha+228|0;x=ha+224|0;z=ha+220|0;A=ha+216|0;B=ha+212|0;C=ha+208|0;D=ha+204|0;E=ha+200|0;F=ha+196|0;G=ha+192|0;H=ha+188|0;I=ha+184|0;K=ha+180|0;L=ha+176|0;M=ha+172|0;N=ha+168|0;O=ha+164|0;k=ha+160|0;j=ha+72|0;l=ha+68|0;P=ha+64|0;Q=ha+60|0;R=ha+56|0;S=ha+52|0;c[ea>>2]=a;c[ia>>2]=d;c[ga>>2]=0;c[f>>2]=e;c[h>>2]=(c[ea>>2]|0)+(c[c[ea>>2]>>2]|0);a:do switch(c[ia>>2]|0){case 4e3:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[m>>2]=ia;do if(!((c[m>>2]|0)!=2048&(c[m>>2]|0)!=2049&(c[m>>2]|0)!=2051)){if((c[(c[ea>>2]|0)+14344>>2]|0)==0?(c[(c[ea>>2]|0)+96>>2]|0)!=(c[m>>2]|0):0)break;c[(c[ea>>2]|0)+96>>2]=c[m>>2];f=99;break a}while(0);c[ga>>2]=-1;f=99;break}case 4001:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[n>>2]=ia;if(c[n>>2]|0){c[c[n>>2]>>2]=c[(c[ea>>2]|0)+96>>2];f=99}else f=100;break}case 4002:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[y>>2]=ia;do if((c[y>>2]|0)!=-1e3&(c[y>>2]|0)!=-1){if((c[y>>2]|0)<=0){f=100;break a}if((c[y>>2]|0)<=500){c[y>>2]=500;break}if((c[y>>2]|0)>((c[(c[ea>>2]|0)+100>>2]|0)*3e5|0))c[y>>2]=(c[(c[ea>>2]|0)+100>>2]|0)*3e5}while(0);c[(c[ea>>2]|0)+152>>2]=c[y>>2];f=99;break}case 4003:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[J>>2]=ia;if(c[J>>2]|0){f=Gi(c[ea>>2]|0,c[(c[ea>>2]|0)+14332>>2]|0,1276)|0;c[c[J>>2]>>2]=f;f=99}else f=100;break}case 4022:{e=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[e>>2]|0;c[f>>2]=e+4;c[da>>2]=ia;f=c[da>>2]|0;if((c[da>>2]|0)<1){if((f|0)!=-1e3){f=100;break a}}else if((c[da>>2]|0)!=-1e3?(f|0)>(c[(c[ea>>2]|0)+100>>2]|0):0){f=100;break a}c[(c[ea>>2]|0)+108>>2]=c[da>>2];f=99;break}case 4023:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[T>>2]=ia;if(c[T>>2]|0){c[c[T>>2]>>2]=c[(c[ea>>2]|0)+108>>2];f=99}else f=100;break}case 4004:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[U>>2]=ia;if(!((c[U>>2]|0)<1101|(c[U>>2]|0)>1105)){c[(c[ea>>2]|0)+120>>2]=c[U>>2];h=c[ea>>2]|0;if((c[(c[ea>>2]|0)+120>>2]|0)==1101){c[h+8+12>>2]=8e3;f=99;break a}f=(c[ea>>2]|0)+8+12|0;if((c[h+120>>2]|0)==1102){c[f>>2]=12e3;f=99;break a}else{c[f>>2]=16e3;f=99;break a}}else f=100;break}case 4005:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[V>>2]=ia;if(c[V>>2]|0){c[c[V>>2]>>2]=c[(c[ea>>2]|0)+120>>2];f=99}else f=100;break}case 4008:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[W>>2]=ia;if(!(((c[W>>2]|0)<1101|(c[W>>2]|0)>1105)&(c[W>>2]|0)!=-1e3)){c[(c[ea>>2]|0)+116>>2]=c[W>>2];h=c[ea>>2]|0;if((c[(c[ea>>2]|0)+116>>2]|0)==1101){c[h+8+12>>2]=8e3;f=99;break a}f=(c[ea>>2]|0)+8+12|0;if((c[h+116>>2]|0)==1102){c[f>>2]=12e3;f=99;break a}else{c[f>>2]=16e3;f=99;break a}}else f=100;break}case 4009:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[X>>2]=ia;if(c[X>>2]|0){c[c[X>>2]>>2]=c[(c[ea>>2]|0)+14336>>2];f=99}else f=100;break}case 4016:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[o>>2]=ia;if((c[o>>2]|0)<0|(c[o>>2]|0)>1)f=100;else{c[(c[ea>>2]|0)+8+44>>2]=c[o>>2];f=99}break}case 4017:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[p>>2]=ia;if(c[p>>2]|0){c[c[p>>2]>>2]=c[(c[ea>>2]|0)+8+44>>2];f=99}else f=100;break}case 4010:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[q>>2]=ia;if((c[q>>2]|0)<0|(c[q>>2]|0)>10)f=100;else{c[(c[ea>>2]|0)+8+36>>2]=c[q>>2];f=c[h>>2]|0;c[Y>>2]=c[q>>2];lb(f,4010,Y)|0;f=99}break}case 4011:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[r>>2]=ia;if(c[r>>2]|0){c[c[r>>2]>>2]=c[(c[ea>>2]|0)+8+36>>2];f=99}else f=100;break}case 4012:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[s>>2]=ia;if((c[s>>2]|0)<0|(c[s>>2]|0)>1)f=100;else{c[(c[ea>>2]|0)+8+40>>2]=c[s>>2];f=99}break}case 4013:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[t>>2]=ia;if(c[t>>2]|0){c[c[t>>2]>>2]=c[(c[ea>>2]|0)+8+40>>2];f=99}else f=100;break}case 4014:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[u>>2]=ia;if((c[u>>2]|0)<0|(c[u>>2]|0)>100)f=100;else{c[(c[ea>>2]|0)+8+32>>2]=c[u>>2];f=c[h>>2]|0;c[Z>>2]=c[u>>2];lb(f,4014,Z)|0;f=99}break}case 4015:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[v>>2]=ia;if(c[v>>2]|0){c[c[v>>2]>>2]=c[(c[ea>>2]|0)+8+32>>2];f=99}else f=100;break}case 4006:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[w>>2]=ia;if((c[w>>2]|0)<0|(c[w>>2]|0)>1)f=100;else{c[(c[ea>>2]|0)+136>>2]=c[w>>2];c[(c[ea>>2]|0)+8+48>>2]=1-(c[w>>2]|0);f=99}break}case 4007:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[x>>2]=ia;if(c[x>>2]|0){c[c[x>>2]>>2]=c[(c[ea>>2]|0)+136>>2];f=99}else f=100;break}case 11018:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[z>>2]=ia;if((c[z>>2]|0)<-1|(c[z>>2]|0)>100)f=100;else{c[(c[ea>>2]|0)+128>>2]=c[z>>2];f=99}break}case 11019:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[A>>2]=ia;if(c[A>>2]|0){c[c[A>>2]>>2]=c[(c[ea>>2]|0)+128>>2];f=99}else f=100;break}case 4020:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[B>>2]=ia;if((c[B>>2]|0)<0|(c[B>>2]|0)>1)f=100;else{c[(c[ea>>2]|0)+140>>2]=c[B>>2];f=99}break}case 4021:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[C>>2]=ia;if(c[C>>2]|0){c[c[C>>2]>>2]=c[(c[ea>>2]|0)+140>>2];f=99}else f=100;break}case 4024:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[D>>2]=ia;if((c[D>>2]|0)!=-1e3&(c[D>>2]|0)!=3001&(c[D>>2]|0)!=3002)f=100;else{c[(c[ea>>2]|0)+112>>2]=c[D>>2];f=99}break}case 4025:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[E>>2]=ia;if(c[E>>2]|0){c[c[E>>2]>>2]=c[(c[ea>>2]|0)+112>>2];f=99}else f=100;break}case 4027:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[F>>2]=ia;if(c[F>>2]|0){c[c[F>>2]>>2]=(c[(c[ea>>2]|0)+132>>2]|0)/400|0;if((c[(c[ea>>2]|0)+96>>2]|0)!=2051){f=c[F>>2]|0;c[f>>2]=(c[f>>2]|0)+(c[(c[ea>>2]|0)+104>>2]|0);f=99}else f=99}else f=100;break}case 4029:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[G>>2]=ia;if(c[G>>2]|0){c[c[G>>2]>>2]=c[(c[ea>>2]|0)+132>>2];f=99}else f=100;break}case 4031:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[H>>2]=ia;if(c[H>>2]|0){c[c[H>>2]>>2]=c[(c[ea>>2]|0)+18216>>2];f=99}else f=100;break}case 4036:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[I>>2]=ia;if((c[I>>2]|0)<8|(c[I>>2]|0)>24)f=100;else{c[(c[ea>>2]|0)+156>>2]=c[I>>2];f=99}break}case 4037:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[K>>2]=ia;if(c[K>>2]|0){c[c[K>>2]>>2]=c[(c[ea>>2]|0)+156>>2];f=99}else f=100;break}case 4040:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[L>>2]=ia;if((c[L>>2]|0)!=5e3&(c[L>>2]|0)!=5001&(c[L>>2]|0)!=5002&(c[L>>2]|0)!=5003&(c[L>>2]|0)!=5004&(c[L>>2]|0)!=5005&(c[L>>2]|0)!=5006&(c[L>>2]|0)!=5010)f=100;else{c[(c[ea>>2]|0)+144>>2]=c[L>>2];f=c[h>>2]|0;c[_>>2]=c[L>>2];lb(f,4040,_)|0;f=99}break}case 4041:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[M>>2]=ia;if(c[M>>2]|0){c[c[M>>2]>>2]=c[(c[ea>>2]|0)+144>>2];f=99}else f=100;break}case 4042:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[N>>2]=ia;if((c[N>>2]|0)>1|(c[N>>2]|0)<0)f=100;else{c[(c[ea>>2]|0)+8+64>>2]=c[N>>2];f=99}break}case 4043:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[O>>2]=ia;if(c[O>>2]|0){c[c[O>>2]>>2]=c[(c[ea>>2]|0)+8+64>>2];f=99}else f=100;break}case 4028:{c[k>>2]=(c[ea>>2]|0)+(c[(c[ea>>2]|0)+4>>2]|0);_i((c[ea>>2]|0)+172|0);c[l>>2]=(c[ea>>2]|0)+14288;oj(c[l>>2]|0,0,18220-((c[l>>2]|0)-(c[ea>>2]|0))|0)|0;lb(c[h>>2]|0,4028,$)|0;Td(c[k>>2]|0,c[(c[ea>>2]|0)+168>>2]|0,j)|0;c[(c[ea>>2]|0)+14288>>2]=c[(c[ea>>2]|0)+100>>2];b[(c[ea>>2]|0)+14292>>1]=16384;g[(c[ea>>2]|0)+14300>>2]=1.0;c[(c[ea>>2]|0)+14344>>2]=1;c[(c[ea>>2]|0)+14320>>2]=1001;c[(c[ea>>2]|0)+14336>>2]=1105;f=(Sf(60)|0)<<8;c[(c[ea>>2]|0)+14296>>2]=f;f=99;break}case 11002:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[P>>2]=ia;if(((c[P>>2]|0)<1e3|(c[P>>2]|0)>1002)&(c[P>>2]|0)!=-1e3)f=100;else{c[(c[ea>>2]|0)+124>>2]=c[P>>2];f=99}break}case 10024:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[Q>>2]=ia;c[(c[ea>>2]|0)+164>>2]=c[Q>>2];f=c[h>>2]|0;c[aa>>2]=c[Q>>2];c[ga>>2]=lb(f,10024,aa)|0;f=99;break}case 10026:{da=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[da>>2]|0;c[f>>2]=da+4;c[R>>2]=ia;c[(c[ea>>2]|0)+14348>>2]=c[R>>2];f=c[h>>2]|0;c[ba>>2]=(c[R>>2]|0)+((((c[R>>2]|0)-(c[R>>2]|0)|0)/4|0)<<2);c[ga>>2]=lb(f,10026,ba)|0;f=99;break}case 10015:{ea=(c[f>>2]|0)+(4-1)&~(4-1);ia=c[ea>>2]|0;c[f>>2]=ea+4;c[S>>2]=ia;if(c[S>>2]|0){f=c[h>>2]|0;c[ca>>2]=(c[S>>2]|0)+((((c[S>>2]|0)-(c[S>>2]|0)|0)/4|0)<<2);c[ga>>2]=lb(f,10015,ca)|0;f=99}else f=100;break}default:{c[ga>>2]=-5;f=99}}while(0);if((f|0)==99){c[fa>>2]=c[ga>>2];ia=c[fa>>2]|0;i=ha;return ia|0}else if((f|0)==100){c[fa>>2]=-1;ia=c[fa>>2]|0;i=ha;return ia|0}return 0}function Ti(a){a=a|0;var b=0,d=0;d=i;i=i+16|0;b=d;c[b>>2]=a;c[(c[b>>2]|0)+4>>2]=0;i=d;return c[b>>2]|0}function Ui(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0;e=i;i=i+16|0;h=e+8|0;g=e+4|0;f=e;c[h>>2]=a;c[g>>2]=b;c[f>>2]=d;a=Vi(c[h>>2]|0,c[g>>2]|0,c[f>>2]|0,0)|0;i=e;return a|0}function Vi(b,e,f,g){b=b|0;e=e|0;f=f|0;g=g|0;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;q=i;i=i+32|0;h=q+24|0;j=q+20|0;k=q+16|0;l=q+12|0;m=q+8|0;p=q+28|0;n=q+4|0;o=q;c[j>>2]=b;c[k>>2]=e;c[l>>2]=f;c[m>>2]=g;if((c[l>>2]|0)<1){c[h>>2]=-4;p=c[h>>2]|0;i=q;return p|0}if(c[(c[j>>2]|0)+4>>2]|0){if(((d[c[j>>2]>>0]|0)&252|0)!=((d[c[k>>2]>>0]|0)&252|0)){c[h>>2]=-4;p=c[h>>2]|0;i=q;return p|0}}else{a[c[j>>2]>>0]=a[c[k>>2]>>0]|0;g=Zh(c[k>>2]|0,8e3)|0;c[(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0)c[D>>2]=1+((b[(c[y>>2]|0)+((c[v>>2]|0)-1<<1)>>1]|0)>=252&1);else c[D>>2]=0;c[B>>2]=c[r>>2];do if((c[v>>2]|0)!=1){if((c[v>>2]|0)==2){m=b[c[y>>2]>>1]|0;if((b[(c[y>>2]|0)+2>>1]|0)==(b[c[y>>2]>>1]|0)){c[D>>2]=(c[D>>2]|0)+((m<<1)+1);if((c[D>>2]|0)<=(c[s>>2]|0)){e=(d[c[o>>2]>>0]&252|1)&255;k=c[B>>2]|0;c[B>>2]=k+1;a[k>>0]=e;break}c[q>>2]=-2;E=c[q>>2]|0;i=F;return E|0}else{c[D>>2]=(c[D>>2]|0)+(m+(b[(c[y>>2]|0)+2>>1]|0)+2+((b[c[y>>2]>>1]|0)>=252&1));if((c[D>>2]|0)<=(c[s>>2]|0)){e=(d[c[o>>2]>>0]&252|2)&255;k=c[B>>2]|0;c[B>>2]=k+1;a[k>>0]=e;k=Yh(b[c[y>>2]>>1]|0,c[B>>2]|0)|0;c[B>>2]=(c[B>>2]|0)+k;break}c[q>>2]=-2;E=c[q>>2]|0;i=F;return E|0}}}else{c[D>>2]=(c[D>>2]|0)+((b[c[y>>2]>>1]|0)+1);if((c[D>>2]|0)<=(c[s>>2]|0)){e=d[c[o>>2]>>0]&252;k=c[B>>2]|0;c[B>>2]=k+1;a[k>>0]=e;break}c[q>>2]=-2;E=c[q>>2]|0;i=F;return E|0}while(0);if((c[v>>2]|0)<=2){if(c[u>>2]|0?(c[D>>2]|0)<(c[s>>2]|0):0)p=23}else p=23;a:do if((p|0)==23){c[A>>2]=0;c[B>>2]=c[r>>2];if(c[t>>2]|0)c[D>>2]=1+((b[(c[y>>2]|0)+((c[v>>2]|0)-1<<1)>>1]|0)>=252&1);else c[D>>2]=0;c[E>>2]=0;c[x>>2]=1;while(1){if((c[x>>2]|0)>=(c[v>>2]|0))break;if((b[(c[y>>2]|0)+(c[x>>2]<<1)>>1]|0)!=(b[c[y>>2]>>1]|0)){p=29;break}c[x>>2]=(c[x>>2]|0)+1}if((p|0)==29)c[E>>2]=1;do if(c[E>>2]|0){c[D>>2]=(c[D>>2]|0)+2;c[x>>2]=0;while(1){if((c[x>>2]|0)>=((c[v>>2]|0)-1|0))break;c[D>>2]=(c[D>>2]|0)+(1+((b[(c[y>>2]|0)+(c[x>>2]<<1)>>1]|0)>=252&1)+(b[(c[y>>2]|0)+(c[x>>2]<<1)>>1]|0));c[x>>2]=(c[x>>2]|0)+1}c[D>>2]=(c[D>>2]|0)+(b[(c[y>>2]|0)+((c[v>>2]|0)-1<<1)>>1]|0);if((c[D>>2]|0)<=(c[s>>2]|0)){p=(d[c[o>>2]>>0]&252|3)&255;o=c[B>>2]|0;c[B>>2]=o+1;a[o>>0]=p;o=(c[v>>2]|128)&255;p=c[B>>2]|0;c[B>>2]=p+1;a[p>>0]=o;break}c[q>>2]=-2;E=c[q>>2]|0;i=F;return E|0}else{p=(_(c[v>>2]|0,b[c[y>>2]>>1]|0)|0)+2|0;c[D>>2]=(c[D>>2]|0)+p;if((c[D>>2]|0)<=(c[s>>2]|0)){p=(d[c[o>>2]>>0]&252|3)&255;o=c[B>>2]|0;c[B>>2]=o+1;a[o>>0]=p;o=c[v>>2]&255;p=c[B>>2]|0;c[B>>2]=p+1;a[p>>0]=o;break}c[q>>2]=-2;E=c[q>>2]|0;i=F;return E|0}while(0);if(c[u>>2]|0)m=(c[s>>2]|0)-(c[D>>2]|0)|0;else m=0;c[A>>2]=m;if(c[A>>2]|0){p=(c[r>>2]|0)+1|0;a[p>>0]=d[p>>0]|64;c[z>>2]=((c[A>>2]|0)-1|0)/255|0;c[x>>2]=0;while(1){if((c[x>>2]|0)>=(c[z>>2]|0))break;p=c[B>>2]|0;c[B>>2]=p+1;a[p>>0]=-1;c[x>>2]=(c[x>>2]|0)+1}p=(c[A>>2]|0)-((c[z>>2]|0)*255|0)-1&255;z=c[B>>2]|0;c[B>>2]=z+1;a[z>>0]=p;c[D>>2]=(c[D>>2]|0)+(c[A>>2]|0)}if(c[E>>2]|0){c[x>>2]=0;while(1){if((c[x>>2]|0)>=((c[v>>2]|0)-1|0))break a;E=Yh(b[(c[y>>2]|0)+(c[x>>2]<<1)>>1]|0,c[B>>2]|0)|0;c[B>>2]=(c[B>>2]|0)+E;c[x>>2]=(c[x>>2]|0)+1}}}while(0);if(c[t>>2]|0){c[C>>2]=Yh(b[(c[y>>2]|0)+((c[v>>2]|0)-1<<1)>>1]|0,c[B>>2]|0)|0;c[B>>2]=(c[B>>2]|0)+(c[C>>2]|0)}c[x>>2]=0;while(1){if((c[x>>2]|0)>=(c[v>>2]|0))break;qj(c[B>>2]|0,c[(c[w>>2]|0)+(c[x>>2]<<2)>>2]|0,(b[(c[y>>2]|0)+(c[x>>2]<<1)>>1]|0)+0|0)|0;c[B>>2]=(c[B>>2]|0)+(b[(c[y>>2]|0)+(c[x>>2]<<1)>>1]|0);c[x>>2]=(c[x>>2]|0)+1}b:do if(c[u>>2]|0)while(1){if((c[B>>2]|0)>>>0>=((c[r>>2]|0)+(c[s>>2]|0)|0)>>>0)break b;E=c[B>>2]|0;c[B>>2]=E+1;a[E>>0]=0}while(0);c[q>>2]=c[D>>2];E=c[q>>2]|0;i=F;return E|0}c[q>>2]=-1;E=c[q>>2]|0;i=F;return E|0}function Xi(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0;l=i;i=i+320|0;e=l+316|0;f=l+312|0;g=l+308|0;h=l+304|0;k=l+4|0;j=l;c[f>>2]=a;c[g>>2]=b;c[h>>2]=d;if((c[g>>2]|0)<1){c[e>>2]=-1;k=c[e>>2]|0;i=l;return k|0}if((c[g>>2]|0)==(c[h>>2]|0)){c[e>>2]=0;k=c[e>>2]|0;i=l;return k|0}if((c[g>>2]|0)>(c[h>>2]|0)){c[e>>2]=-1;k=c[e>>2]|0;i=l;return k|0}Ti(k)|0;qj((c[f>>2]|0)+(c[h>>2]|0)+(0-(c[g>>2]|0))|0,c[f>>2]|0,(c[g>>2]|0)+0|0)|0;Ui(k,(c[f>>2]|0)+(c[h>>2]|0)+(0-(c[g>>2]|0))|0,c[g>>2]|0)|0;c[j>>2]=Wi(k,0,c[k+4>>2]|0,c[f>>2]|0,c[h>>2]|0,0,1)|0;if((c[j>>2]|0)>0){c[e>>2]=0;k=c[e>>2]|0;i=l;return k|0}else{c[e>>2]=c[j>>2];k=c[e>>2]|0;i=l;return k|0}return 0}function Yi(a){a=a|0;var b=0,d=0;b=i;i=i+16|0;d=b;c[d>>2]=a;a=Zi()|0;c[c[d>>2]>>2]=a;_i(c[d>>2]|0);i=b;return}function Zi(){return 0}function _i(a){a=a|0;var b=0,d=0,e=0;b=i;i=i+16|0;d=b+4|0;e=b;c[d>>2]=a;c[e>>2]=(c[d>>2]|0)+4;oj(c[e>>2]|0,0,14116-((c[e>>2]|0)-(c[d>>2]|0))|0)|0;i=b;return}function $i(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0;n=i;i=i+32|0;h=n+24|0;j=n+20|0;e=n+16|0;f=n+12|0;k=n+8|0;m=n+4|0;l=n;c[h>>2]=a;c[j>>2]=b;c[e>>2]=d;c[f>>2]=c[(c[h>>2]|0)+8508>>2];c[k>>2]=(c[(c[h>>2]|0)+8504>>2]|0)-(c[(c[h>>2]|0)+8508>>2]|0);if((c[k>>2]|0)<0)c[k>>2]=(c[k>>2]|0)+200;if((c[e>>2]|0)>480?(c[f>>2]|0)!=(c[(c[h>>2]|0)+8504>>2]|0):0){a=(c[f>>2]|0)+1|0;c[f>>2]=a;c[f>>2]=(c[f>>2]|0)==200?0:a}if((c[f>>2]|0)==(c[(c[h>>2]|0)+8504>>2]|0))c[f>>2]=(c[f>>2]|0)+-1;if((c[f>>2]|0)<0)c[f>>2]=199;pj(c[j>>2]|0,(c[h>>2]|0)+8516+((c[f>>2]|0)*28|0)|0,28|0)|0;a=(c[h>>2]|0)+8512|0;c[a>>2]=(c[a>>2]|0)+((c[e>>2]|0)/120|0);while(1){e=c[h>>2]|0;if((c[(c[h>>2]|0)+8512>>2]|0)<4)break;a=e+8512|0;c[a>>2]=(c[a>>2]|0)-4;a=(c[h>>2]|0)+8508|0;c[a>>2]=(c[a>>2]|0)+1}if((c[e+8508>>2]|0)>=200){a=(c[h>>2]|0)+8508|0;c[a>>2]=(c[a>>2]|0)-200}c[k>>2]=((c[k>>2]|0)-10|0)>0?(c[k>>2]|0)-10|0:0;g[m>>2]=0.0;c[l>>2]=0;while(1){if((c[l>>2]|0)>=(200-(c[k>>2]|0)|0))break;g[m>>2]=+g[m>>2]+ +g[(c[h>>2]|0)+7688+(c[l>>2]<<2)>>2];c[l>>2]=(c[l>>2]|0)+1}while(1){if((c[l>>2]|0)>=200)break;g[m>>2]=+g[m>>2]+ +g[(c[h>>2]|0)+6888+(c[l>>2]<<2)>>2];c[l>>2]=(c[l>>2]|0)+1}g[m>>2]=+g[m>>2]*+g[(c[h>>2]|0)+8492>>2]+(1.0-+g[m>>2])*+g[(c[h>>2]|0)+8488>>2];g[(c[j>>2]|0)+20>>2]=+g[m>>2];i=n;return}function aj(a,b,d,e,f,g,h,j,k,l,m,n){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;k=k|0;l=l|0;m=m|0;n=n|0;var o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0;C=i;i=i+64|0;p=C+52|0;q=C+48|0;t=C+44|0;u=C+40|0;v=C+36|0;w=C+32|0;x=C+28|0;y=C+24|0;o=C+20|0;z=C+16|0;r=C+12|0;s=C+8|0;A=C+4|0;B=C;c[p>>2]=a;c[q>>2]=b;c[t>>2]=d;c[u>>2]=e;c[v>>2]=f;c[w>>2]=g;c[x>>2]=h;c[y>>2]=j;c[o>>2]=k;c[z>>2]=l;c[r>>2]=m;c[s>>2]=n;if(!(c[t>>2]|0)){z=c[s>>2]|0;c[z>>2]=0;z=c[p>>2]|0;A=c[s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15);n=+O(+(+g[W>>2]+1.000000013351432e-10));g[ta>>2]=+g[ta>>2]+n;n=+Y(+(+g[W>>2]+1.000000013351432e-10));g[ua+(c[sa>>2]<<2)>>2]=n;k=c[sa>>2]|0;if(+g[ua+(c[sa>>2]<<2)>>2]<+g[(c[Sa>>2]|0)+6420+(c[sa>>2]<<2)>>2]+.009999999776482582)n=+g[ua+(k<<2)>>2];else n=+g[(c[Sa>>2]|0)+6420+(k<<2)>>2]+.009999999776482582;g[(c[Sa>>2]|0)+6420+(c[sa>>2]<<2)>>2]=n;k=c[sa>>2]|0;if(+g[ua+(c[sa>>2]<<2)>>2]>+g[(c[Sa>>2]|0)+6492+(c[sa>>2]<<2)>>2]-.10000000149011612)n=+g[ua+(k<<2)>>2];else n=+g[(c[Sa>>2]|0)+6492+(k<<2)>>2]-.10000000149011612;g[(c[Sa>>2]|0)+6492+(c[sa>>2]<<2)>>2]=n;if(+g[(c[Sa>>2]|0)+6492+(c[sa>>2]<<2)>>2]<+g[(c[Sa>>2]|0)+6420+(c[sa>>2]<<2)>>2]+1.0){U=(c[Sa>>2]|0)+6492+(c[sa>>2]<<2)|0;g[U>>2]=+g[U>>2]+.5;U=(c[Sa>>2]|0)+6420+(c[sa>>2]<<2)|0;g[U>>2]=+g[U>>2]-.5}g[wa>>2]=+g[wa>>2]+(+g[ua+(c[sa>>2]<<2)>>2]-+g[(c[Sa>>2]|0)+6420+(c[sa>>2]<<2)>>2])/(+g[(c[Sa>>2]|0)+6492+(c[sa>>2]<<2)>>2]+1.0000000036274937e-15-+g[(c[Sa>>2]|0)+6420+(c[sa>>2]<<2)>>2]);g[Z>>2]=0.0;g[X>>2]=0.0;c[Fa>>2]=0;while(1){if((c[Fa>>2]|0)>=8)break;n=+O(+(+g[(c[Sa>>2]|0)+5844+((c[Fa>>2]|0)*72|0)+(c[sa>>2]<<2)>>2]));g[X>>2]=+g[X>>2]+n;g[Z>>2]=+g[Z>>2]+ +g[(c[Sa>>2]|0)+5844+((c[Fa>>2]|0)*72|0)+(c[sa>>2]<<2)>>2];c[Fa>>2]=(c[Fa>>2]|0)+1}if(.9900000095367432<+g[X>>2]/+O(+(+g[Z>>2]*8.0+1.0e-15)))n=.9900000095367432;else n=+g[X>>2]/+O(+(+g[Z>>2]*8.0+1.0e-15));g[ca>>2]=n;g[ca>>2]=+g[ca>>2]*+g[ca>>2];g[ca>>2]=+g[ca>>2]*+g[ca>>2];g[Ba>>2]=+g[Ba>>2]+ +g[ca>>2];if(+g[da>>2]/(+g[W>>2]+1.0000000036274937e-15)>+g[ca>>2]*+g[(c[Sa>>2]|0)+5768+(c[sa>>2]<<2)>>2])n=+g[da>>2]/(+g[W>>2]+1.0000000036274937e-15);else n=+g[ca>>2]*+g[(c[Sa>>2]|0)+5768+(c[sa>>2]<<2)>>2];g[_+(c[sa>>2]<<2)>>2]=n;g[Ca>>2]=+g[Ca>>2]+ +g[_+(c[sa>>2]<<2)>>2];if((c[sa>>2]|0)>=9)g[Ca>>2]=+g[Ca>>2]-+g[_+((c[sa>>2]|0)-18+9<<2)>>2];if(+g[va>>2]>(+((c[sa>>2]|0)-18|0)*.029999999329447746+1.0)*+g[Ca>>2])n=+g[va>>2];else n=(+((c[sa>>2]|0)-18|0)*.029999999329447746+1.0)*+g[Ca>>2];g[va>>2]=n;g[Da>>2]=+g[Da>>2]+ +g[_+(c[sa>>2]<<2)>>2]*+((c[sa>>2]|0)-8|0);g[(c[Sa>>2]|0)+5768+(c[sa>>2]<<2)>>2]=+g[_+(c[sa>>2]<<2)>>2];c[sa>>2]=(c[sa>>2]|0)+1}if((fa|0)==37){c[c[Wa>>2]>>2]=0;i=Xa;return}g[la>>2]=0.0;c[Ua>>2]=0;g[na>>2]=0.0;g[oa>>2]=5.699999746866524e-04/+(1<<(0>((c[V>>2]|0)-8|0)?0:(c[V>>2]|0)-8|0)|0);g[oa>>2]=+g[oa>>2]*+g[oa>>2];c[sa>>2]=0;while(1){if((c[sa>>2]|0)>=21)break;g[ga>>2]=0.0;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>2]=20;g[ta>>2]=+hj(+g[ta>>2])*20.0;if(+g[(c[Sa>>2]|0)+6848>>2]-.029999999329447746>+g[ta>>2])n=+g[(c[Sa>>2]|0)+6848>>2]-.029999999329447746;else n=+g[ta>>2];g[(c[Sa>>2]|0)+6848>>2]=n;pa=(c[Sa>>2]|0)+6852|0;g[pa>>2]=+g[pa>>2]*(1.0-+g[ra>>2]);if(+g[ta>>2]<+g[(c[Sa>>2]|0)+6848>>2]-30.0){ta=(c[Sa>>2]|0)+6852|0;g[ta>>2]=+g[ta>>2]+ +g[ra>>2]}c[Fa>>2]=0;while(1){if((c[Fa>>2]|0)>=8)break;g[xa>>2]=0.0;c[sa>>2]=0;while(1){if((c[sa>>2]|0)>=16)break;g[xa>>2]=+g[xa>>2]+ +g[19300+((c[Fa>>2]<<4)+(c[sa>>2]|0)<<2)>>2]*+g[ua+(c[sa>>2]<<2)>>2];c[sa>>2]=(c[sa>>2]|0)+1}g[ya+(c[Fa>>2]<<2)>>2]=+g[xa>>2];c[Fa>>2]=(c[Fa>>2]|0)+1}g[Ba>>2]=+g[Ba>>2]/18.0;n=+g[wa>>2]/18.0;g[wa>>2]=n;g[wa>>2]=(c[(c[Sa>>2]|0)+6868>>2]|0)<10?.5:n;g[Va>>2]=+g[Va>>2]/18.0;g[(c[Wa>>2]|0)+16>>2]=+g[Va>>2]+(1.0-+g[Va>>2])*+g[wa>>2];g[Ca>>2]=+g[va>>2]/9.0;if(+g[Ca>>2]>+g[(c[Sa>>2]|0)+5840>>2]*.800000011920929)n=+g[Ca>>2];else n=+g[(c[Sa>>2]|0)+5840>>2]*.800000011920929;g[Ca>>2]=n;g[(c[Sa>>2]|0)+5840>>2]=+g[Ca>>2];g[Da>>2]=+g[Da>>2]/64.0;g[(c[Wa>>2]|0)+8>>2]=+g[Da>>2];c[(c[Sa>>2]|0)+6856>>2]=((c[(c[Sa>>2]|0)+6856>>2]|0)+1|0)%8|0;Da=(c[Sa>>2]|0)+6868|0;c[Da>>2]=(c[Da>>2]|0)+1;g[(c[Wa>>2]|0)+4>>2]=+g[Ca>>2];c[Fa>>2]=0;while(1){if((c[Fa>>2]|0)>=4)break;g[Aa+(c[Fa>>2]<<2)>>2]=(+g[ya+(c[Fa>>2]<<2)>>2]+ +g[(c[Sa>>2]|0)+6648+((c[Fa>>2]|0)+24<<2)>>2])*-.12298999726772308+(+g[(c[Sa>>2]|0)+6648+(c[Fa>>2]<<2)>>2]+ +g[(c[Sa>>2]|0)+6648+((c[Fa>>2]|0)+16<<2)>>2])*.49195000529289246+ +g[(c[Sa>>2]|0)+6648+((c[Fa>>2]|0)+8<<2)>>2]*.6969299912452698-+g[(c[Sa>>2]|0)+6776+(c[Fa>>2]<<2)>>2]*1.4349000453948975;c[Fa>>2]=(c[Fa>>2]|0)+1}c[Fa>>2]=0;while(1){if((c[Fa>>2]|0)>=4)break;g[(c[Sa>>2]|0)+6776+(c[Fa>>2]<<2)>>2]=(1.0-+g[za>>2])*+g[(c[Sa>>2]|0)+6776+(c[Fa>>2]<<2)>>2]+ +g[za>>2]*+g[ya+(c[Fa>>2]<<2)>>2];c[Fa>>2]=(c[Fa>>2]|0)+1}c[Fa>>2]=0;while(1){if((c[Fa>>2]|0)>=4)break;g[Aa+(4+(c[Fa>>2]|0)<<2)>>2]=(+g[ya+(c[Fa>>2]<<2)>>2]-+g[(c[Sa>>2]|0)+6648+((c[Fa>>2]|0)+24<<2)>>2])*.6324599981307983+(+g[(c[Sa>>2]|0)+6648+(c[Fa>>2]<<2)>>2]-+g[(c[Sa>>2]|0)+6648+((c[Fa>>2]|0)+16<<2)>>2])*.31622999906539917;c[Fa>>2]=(c[Fa>>2]|0)+1}c[Fa>>2]=0;while(1){if((c[Fa>>2]|0)>=3)break;g[Aa+(8+(c[Fa>>2]|0)<<2)>>2]=(+g[ya+(c[Fa>>2]<<2)>>2]+ +g[(c[Sa>>2]|0)+6648+((c[Fa>>2]|0)+24<<2)>>2])*.5345199704170227-(+g[(c[Sa>>2]|0)+6648+(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[(c[Wa>>2]|0)+8>>2];g[Aa+96>>2]=+g[(c[Sa>>2]|0)+6852>>2];dj(20616,Aa,Ra);g[Ra>>2]=(+g[Ra>>2]+1.0)*.5;g[Ra>>2]=+g[Ra>>2]*1.2100000381469727*+g[Ra>>2]+.009999999776482582-+P(+(+g[Ra>>2]),10.0)*.23000000417232513;g[Ra+4>>2]=+g[Ra+4>>2]*.5+.5;g[Ra>>2]=+g[Ra+4>>2]*+g[Ra>>2]+(1.0-+g[Ra+4>>2])*.5;g[Pa>>2]=+g[Ra+4>>2]*4.999999873689376e-05;g[Ea>>2]=.05000000074505806;if(.05000000074505806>(.949999988079071<+g[Ra>>2]?.949999988079071:+g[Ra>>2]))n=.05000000074505806;else n=.949999988079071<+g[Ra>>2]?.949999988079071:+g[Ra>>2];g[Ia>>2]=n;if(.949999988079071<+g[(c[Sa>>2]|0)+6844>>2])n=.949999988079071;else n=+g[(c[Sa>>2]|0)+6844>>2];if(!(.05000000074505806>n))if(.949999988079071<+g[(c[Sa>>2]|0)+6844>>2])n=.949999988079071;else n=+g[(c[Sa>>2]|0)+6844>>2];else n=.05000000074505806;g[Ma>>2]=n;n=+N(+(+g[Ia>>2]-+g[Ma>>2]))*.05000000074505806;g[Ea>>2]=n/(+g[Ia>>2]*(1.0-+g[Ma>>2])+ +g[Ma>>2]*(1.0-+g[Ia>>2]))+.009999999776482582;g[Ja>>2]=(1.0-+g[(c[Sa>>2]|0)+6844>>2])*(1.0-+g[Pa>>2])+ +g[(c[Sa>>2]|0)+6844>>2]*+g[Pa>>2];g[Ka>>2]=+g[(c[Sa>>2]|0)+6844>>2]*(1.0-+g[Pa>>2])+(1.0-+g[(c[Sa>>2]|0)+6844>>2])*+g[Pa>>2];n=+P(+(1.0-+g[Ra>>2]),+(+g[Ea>>2]));g[Ja>>2]=+g[Ja>>2]*n;n=+P(+(+g[Ra>>2]),+(+g[Ea>>2]));g[Ka>>2]=+g[Ka>>2]*n;g[(c[Sa>>2]|0)+6844>>2]=+g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=1.0/+g[La>>2];c[Fa>>2]=0;while(1){if((c[Fa>>2]|0)>=200)break;Pa=(c[Sa>>2]|0)+6888+(c[Fa>>2]<<2)|0;g[Pa>>2]=+g[Pa>>2]*+g[La>>2];Pa=(c[Sa>>2]|0)+7688+(c[Fa>>2]<<2)|0;g[Pa>>2]=+g[Pa>>2]*+g[La>>2];c[Fa>>2]=(c[Fa>>2]|0)+1}g[La>>2]=+g[(c[Sa>>2]|0)+7688>>2];c[Fa>>2]=1;while(1){if((c[Fa>>2]|0)>=200)break;g[La>>2]=+g[La>>2]+ +g[(c[Sa>>2]|0)+6888+(c[Fa>>2]<<2)>>2];c[Fa>>2]=(c[Fa>>2]|0)+1}k=c[Sa>>2]|0;do if(+g[Ra+4>>2]>.75){if(+g[k+6844>>2]>.9){Oa=(c[Sa>>2]|0)+8500|0;Pa=(c[Oa>>2]|0)+1|0;c[Oa>>2]=Pa;g[Qa>>2]=1.0/+(Pa|0);if((c[(c[Sa>>2]|0)+8500>>2]|0)<500)k=c[(c[Sa>>2]|0)+8500>>2]|0;else k=500;c[(c[Sa>>2]|0)+8500>>2]=k;if(-.20000000298023224>+g[Ra>>2]-+g[(c[Sa>>2]|0)+8492>>2])n=-.20000000298023224;else n=+g[Ra>>2]-+g[(c[Sa>>2]|0)+8492>>2];Pa=(c[Sa>>2]|0)+8492|0;g[Pa>>2]=+g[Pa>>2]+ +g[Qa>>2]*n}if(!(+g[(c[Sa>>2]|0)+6844>>2]<.1))break;Pa=(c[Sa>>2]|0)+8496|0;Qa=(c[Pa>>2]|0)+1|0;c[Pa>>2]=Qa;g[Ta>>2]=1.0/+(Qa|0);if((c[(c[Sa>>2]|0)+8496>>2]|0)<500)k=c[(c[Sa>>2]|0)+8496>>2]|0;else k=500;c[(c[Sa>>2]|0)+8496>>2]=k;if(.20000000298023224<+g[Ra>>2]-+g[(c[Sa>>2]|0)+8488>>2])n=.20000000298023224;else n=+g[Ra>>2]-+g[(c[Sa>>2]|0)+8488>>2];Ra=(c[Sa>>2]|0)+8488|0;g[Ra>>2]=+g[Ra>>2]+ +g[Ta>>2]*n}else{if(!(c[k+8500>>2]|0))g[(c[Sa>>2]|0)+8492>>2]=.8999999761581421;if(c[(c[Sa>>2]|0)+8496>>2]|0)break;g[(c[Sa>>2]|0)+8488>>2]=.10000000149011612}while(0);if((c[(c[Sa>>2]|0)+6860>>2]|0)!=(+g[(c[Sa>>2]|0)+6844>>2]>.5|0))c[(c[Sa>>2]|0)+6864>>2]=0;c[(c[Sa>>2]|0)+6860>>2]=+g[(c[Sa>>2]|0)+6844>>2]>.5&1;c[(c[Wa>>2]|0)+24>>2]=c[Ua>>2];g[(c[Wa>>2]|0)+12>>2]=+g[Va>>2];c[c[Wa>>2]>>2]=1;i=Xa;return}function cj(a,b){a=+a;b=+b;var c=0,d=0,e=0,f=0,h=0,j=0,k=0,l=0;l=i;i=i+32|0;c=l+24|0;d=l+20|0;e=l+16|0;j=l+12|0;k=l+8|0;f=l+4|0;h=l;g[d>>2]=a;g[e>>2]=b;a=+N(+(+g[e>>2]));if(a+ +N(+(+g[d>>2]))<9.999999717180685e-10){g[e>>2]=+g[e>>2]*999999995904.0;g[d>>2]=+g[d>>2]*999999995904.0}g[j>>2]=+g[e>>2]*+g[e>>2];g[k>>2]=+g[d>>2]*+g[d>>2];if(+g[j>>2]<+g[k>>2]){g[f>>2]=(+g[k>>2]+ +g[j>>2]*.6784840226173401)*(+g[k>>2]+ +g[j>>2]*.0859554186463356);if(+g[f>>2]!=0.0){g[c>>2]=-+g[e>>2]*+g[d>>2]*(+g[k>>2]+ +g[j>>2]*.43157973885536194)/+g[f>>2]+(+g[d>>2]<0.0?-1.5707963705062866:1.5707963705062866);a=+g[c>>2];i=l;return +a}else{g[c>>2]=+g[d>>2]<0.0?-1.5707963705062866:1.5707963705062866;a=+g[c>>2];i=l;return +a}}else{g[h>>2]=(+g[j>>2]+ +g[k>>2]*.6784840226173401)*(+g[j>>2]+ +g[k>>2]*.0859554186463356);if(+g[h>>2]!=0.0){g[c>>2]=+g[e>>2]*+g[d>>2]*(+g[j>>2]+ +g[k>>2]*.43157973885536194)/+g[h>>2]+(+g[d>>2]<0.0?-1.5707963705062866:1.5707963705062866)-(+g[e>>2]*+g[d>>2]<0.0?-1.5707963705062866:1.5707963705062866);a=+g[c>>2];i=l;return +a}else{g[c>>2]=(+g[d>>2]<0.0?-1.5707963705062866:1.5707963705062866)-(+g[e>>2]*+g[d>>2]<0.0?-1.5707963705062866:1.5707963705062866);a=+g[c>>2];i=l;return +a}}return 0.0}function dj(a,b,d){a=a|0;b=b|0;d=d|0;var e=0.0,f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0.0;r=i;i=i+448|0;k=r+436|0;f=r+432|0;l=r+428|0;o=r+424|0;n=r+24|0;m=r+16|0;h=r+12|0;j=r+8|0;p=r+4|0;q=r;c[k>>2]=a;c[f>>2]=b;c[l>>2]=d;c[m>>2]=c[(c[k>>2]|0)+8>>2];c[o>>2]=0;while(1){if((c[o>>2]|0)>=(c[(c[(c[k>>2]|0)+4>>2]|0)+4>>2]|0))break;d=c[m>>2]|0;c[m>>2]=d+4;g[j>>2]=+g[d>>2];c[h>>2]=0;while(1){e=+g[j>>2];if((c[h>>2]|0)>=(c[c[(c[k>>2]|0)+4>>2]>>2]|0))break;s=+g[(c[f>>2]|0)+(c[h>>2]<<2)>>2];d=c[m>>2]|0;c[m>>2]=d+4;g[j>>2]=e+s*+g[d>>2];c[h>>2]=(c[h>>2]|0)+1}s=+ej(e);g[n+(c[o>>2]<<2)>>2]=s;c[o>>2]=(c[o>>2]|0)+1}c[o>>2]=0;while(1){if((c[o>>2]|0)>=(c[(c[(c[k>>2]|0)+4>>2]|0)+8>>2]|0))break;j=c[m>>2]|0;c[m>>2]=j+4;g[q>>2]=+g[j>>2];c[p>>2]=0;while(1){e=+g[q>>2];if((c[p>>2]|0)>=(c[(c[(c[k>>2]|0)+4>>2]|0)+4>>2]|0))break;s=+g[n+(c[p>>2]<<2)>>2];j=c[m>>2]|0;c[m>>2]=j+4;g[q>>2]=e+s*+g[j>>2];c[p>>2]=(c[p>>2]|0)+1}s=+ej(e);g[(c[l>>2]|0)+(c[o>>2]<<2)>>2]=s;c[o>>2]=(c[o>>2]|0)+1}i=r;return}function ej(a){a=+a;var b=0,d=0,e=0,f=0,h=0,j=0,k=0;k=i;i=i+32|0;b=k+20|0;d=k+16|0;f=k+12|0;j=k+8|0;e=k+4|0;h=k;g[d>>2]=a;g[h>>2]=1.0;if(!(+g[d>>2]<8.0)){g[b>>2]=1.0;a=+g[b>>2];i=k;return +a}if(!(+g[d>>2]>-8.0)){g[b>>2]=-1.0;a=+g[b>>2];i=k;return +a}if(+g[d>>2]!=+g[d>>2]){g[b>>2]=0.0;a=+g[b>>2];i=k;return +a}if(+g[d>>2]<0.0){g[d>>2]=-+g[d>>2];g[h>>2]=-1.0}c[f>>2]=~~+M(+(+g[d>>2]*25.0+.5));g[d>>2]=+g[d>>2]-+(c[f>>2]|0)*.03999999910593033;g[j>>2]=+g[19812+(c[f>>2]<<2)>>2];g[e>>2]=1.0-+g[j>>2]*+g[j>>2];g[j>>2]=+g[j>>2]+ +g[d>>2]*+g[e>>2]*(1.0-+g[j>>2]*+g[d>>2]);g[b>>2]=+g[h>>2]*+g[j>>2];a=+g[b>>2];i=k;return +a}function fj(){var a=0;if(!(c[7632]|0))a=30572;else a=c[(fa()|0)+64>>2]|0;return a|0}function gj(a){a=+a;var b=0;b=(g[k>>2]=a,c[k>>2]|0);if((b&2130706432)>>>0<=1249902592){b=(b|0)<0;a=b?a+-8388608.0+8388608.0:a+8388608.0+-8388608.0;if(a==0.0)a=b?-0.0:0.0}return +a}function hj(a){a=+a;var b=0,d=0,e=0,f=0,g=0.0,i=0.0,j=0.0,l=0.0,m=0.0;h[k>>3]=a;d=c[k>>2]|0;b=c[k+4>>2]|0;e=(b|0)<0;do if(e|b>>>0<1048576){g=+N(+a);h[k>>3]=g;if((c[k>>2]|0)==0&(c[k+4>>2]|0)==0){a=-1.0/(a*a);break}if(e){a=(a-a)/0.0;break}else{h[k>>3]=a*18014398509481984.0;b=c[k+4>>2]|0;e=c[k>>2]|0;d=-1077;f=9;break}}else if(b>>>0<=2146435071)if((d|0)==0&0==0&(b|0)==1072693248)a=0.0;else{e=d;d=-1023;f=9}while(0);if((f|0)==9){f=b+614242|0;c[k>>2]=e;c[k+4>>2]=(f&1048575)+1072079006;j=+h[k>>3]+-1.0;i=j*(j*.5);l=j/(j+2.0);m=l*l;a=m*m;h[k>>3]=j-i;e=c[k+4>>2]|0;c[k>>2]=0;c[k+4>>2]=e;g=+h[k>>3];a=j-g-i+l*(i+(a*(a*(a*.15313837699209373+.22222198432149784)+.3999999999940942)+m*(a*(a*(a*.14798198605116586+.1818357216161805)+.2857142874366239)+.6666666666666735)));m=g*.4342944818781689;i=+(d+(f>>>20)|0);l=i*.30102999566361177;j=l+m;a=j+(m+(l-j)+(a*.4342944818781689+(i*3.694239077158931e-13+(g+a)*2.5082946711645275e-11)))}return +a}function ij(a){a=+a;return ~~+gj(a)|0}function jj(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0;do if(a>>>0<245){o=a>>>0<11?16:a+11&-8;a=o>>>3;j=c[7644]|0;b=j>>>a;if(b&3|0){b=(b&1^1)+a|0;d=30616+(b<<1<<2)|0;e=d+8|0;f=c[e>>2]|0;g=f+8|0;h=c[g>>2]|0;do if((d|0)!=(h|0)){if(h>>>0<(c[7648]|0)>>>0)ga();a=h+12|0;if((c[a>>2]|0)==(f|0)){c[a>>2]=d;c[e>>2]=h;break}else ga()}else c[7644]=j&~(1<>2]=L|3;L=f+L+4|0;c[L>>2]=c[L>>2]|1;L=g;return L|0}h=c[7646]|0;if(o>>>0>h>>>0){if(b|0){d=2<>>12&16;d=d>>>i;f=d>>>5&8;d=d>>>f;g=d>>>2&4;d=d>>>g;e=d>>>1&2;d=d>>>e;b=d>>>1&1;b=(f|i|g|e|b)+(d>>>b)|0;d=30616+(b<<1<<2)|0;e=d+8|0;g=c[e>>2]|0;i=g+8|0;f=c[i>>2]|0;do if((d|0)!=(f|0)){if(f>>>0<(c[7648]|0)>>>0)ga();a=f+12|0;if((c[a>>2]|0)==(g|0)){c[a>>2]=d;c[e>>2]=f;k=c[7646]|0;break}else ga()}else{c[7644]=j&~(1<>2]=o|3;e=g+o|0;c[e+4>>2]=h|1;c[e+h>>2]=h;if(k|0){f=c[7649]|0;b=k>>>3;d=30616+(b<<1<<2)|0;a=c[7644]|0;b=1<>2]|0;if(b>>>0<(c[7648]|0)>>>0)ga();else{l=a;m=b}}else{c[7644]=a|b;l=d+8|0;m=d}c[l>>2]=f;c[m+12>>2]=f;c[f+8>>2]=m;c[f+12>>2]=d}c[7646]=h;c[7649]=e;L=i;return L|0}a=c[7645]|0;if(a){d=(a&0-a)+-1|0;K=d>>>12&16;d=d>>>K;J=d>>>5&8;d=d>>>J;L=d>>>2&4;d=d>>>L;b=d>>>1&2;d=d>>>b;e=d>>>1&1;e=c[30880+((J|K|L|b|e)+(d>>>e)<<2)>>2]|0;d=(c[e+4>>2]&-8)-o|0;b=e;while(1){a=c[b+16>>2]|0;if(!a){a=c[b+20>>2]|0;if(!a){j=e;break}}b=(c[a+4>>2]&-8)-o|0;L=b>>>0>>0;d=L?b:d;b=a;e=L?a:e}g=c[7648]|0;if(j>>>0>>0)ga();i=j+o|0;if(j>>>0>=i>>>0)ga();h=c[j+24>>2]|0;e=c[j+12>>2]|0;do if((e|0)==(j|0)){b=j+20|0;a=c[b>>2]|0;if(!a){b=j+16|0;a=c[b>>2]|0;if(!a){n=0;break}}while(1){e=a+20|0;f=c[e>>2]|0;if(f|0){a=f;b=e;continue}e=a+16|0;f=c[e>>2]|0;if(!f)break;else{a=f;b=e}}if(b>>>0>>0)ga();else{c[b>>2]=0;n=a;break}}else{f=c[j+8>>2]|0;if(f>>>0>>0)ga();a=f+12|0;if((c[a>>2]|0)!=(j|0))ga();b=e+8|0;if((c[b>>2]|0)==(j|0)){c[a>>2]=e;c[b>>2]=f;n=e;break}else ga()}while(0);do if(h|0){a=c[j+28>>2]|0;b=30880+(a<<2)|0;if((j|0)==(c[b>>2]|0)){c[b>>2]=n;if(!n){c[7645]=c[7645]&~(1<>>0<(c[7648]|0)>>>0)ga();a=h+16|0;if((c[a>>2]|0)==(j|0))c[a>>2]=n;else c[h+20>>2]=n;if(!n)break}b=c[7648]|0;if(n>>>0>>0)ga();c[n+24>>2]=h;a=c[j+16>>2]|0;do if(a|0)if(a>>>0>>0)ga();else{c[n+16>>2]=a;c[a+24>>2]=n;break}while(0);a=c[j+20>>2]|0;if(a|0)if(a>>>0<(c[7648]|0)>>>0)ga();else{c[n+20>>2]=a;c[a+24>>2]=n;break}}while(0);if(d>>>0<16){L=d+o|0;c[j+4>>2]=L|3;L=j+L+4|0;c[L>>2]=c[L>>2]|1}else{c[j+4>>2]=o|3;c[i+4>>2]=d|1;c[i+d>>2]=d;a=c[7646]|0;if(a|0){f=c[7649]|0;b=a>>>3;e=30616+(b<<1<<2)|0;a=c[7644]|0;b=1<>2]|0;if(b>>>0<(c[7648]|0)>>>0)ga();else{p=a;q=b}}else{c[7644]=a|b;p=e+8|0;q=e}c[p>>2]=f;c[q+12>>2]=f;c[f+8>>2]=q;c[f+12>>2]=e}c[7646]=d;c[7649]=i}L=j+8|0;return L|0}}}else if(a>>>0<=4294967231){a=a+11|0;o=a&-8;j=c[7645]|0;if(j){d=0-o|0;a=a>>>8;if(a)if(o>>>0>16777215)i=31;else{q=(a+1048320|0)>>>16&8;E=a<>>16&4;E=E<>>16&2;i=14-(p|q|i)+(E<>>15)|0;i=o>>>(i+7|0)&1|i<<1}else i=0;b=c[30880+(i<<2)>>2]|0;a:do if(!b){a=0;b=0;E=86}else{f=d;a=0;g=o<<((i|0)==31?0:25-(i>>>1)|0);h=b;b=0;while(1){e=c[h+4>>2]&-8;d=e-o|0;if(d>>>0>>0)if((e|0)==(o|0)){a=h;b=h;E=90;break a}else b=h;else d=f;e=c[h+20>>2]|0;h=c[h+16+(g>>>31<<2)>>2]|0;a=(e|0)==0|(e|0)==(h|0)?a:e;e=(h|0)==0;if(e){E=86;break}else{f=d;g=g<<(e&1^1)}}}while(0);if((E|0)==86){if((a|0)==0&(b|0)==0){a=2<>>12&16;q=q>>>m;l=q>>>5&8;q=q>>>l;n=q>>>2&4;q=q>>>n;p=q>>>1&2;q=q>>>p;a=q>>>1&1;a=c[30880+((l|m|n|p|a)+(q>>>a)<<2)>>2]|0}if(!a){i=d;j=b}else E=90}if((E|0)==90)while(1){E=0;q=(c[a+4>>2]&-8)-o|0;e=q>>>0>>0;d=e?q:d;b=e?a:b;e=c[a+16>>2]|0;if(e|0){a=e;E=90;continue}a=c[a+20>>2]|0;if(!a){i=d;j=b;break}else E=90}if((j|0)!=0?i>>>0<((c[7646]|0)-o|0)>>>0:0){f=c[7648]|0;if(j>>>0>>0)ga();h=j+o|0;if(j>>>0>=h>>>0)ga();g=c[j+24>>2]|0;d=c[j+12>>2]|0;do if((d|0)==(j|0)){b=j+20|0;a=c[b>>2]|0;if(!a){b=j+16|0;a=c[b>>2]|0;if(!a){s=0;break}}while(1){d=a+20|0;e=c[d>>2]|0;if(e|0){a=e;b=d;continue}d=a+16|0;e=c[d>>2]|0;if(!e)break;else{a=e;b=d}}if(b>>>0>>0)ga();else{c[b>>2]=0;s=a;break}}else{e=c[j+8>>2]|0;if(e>>>0>>0)ga();a=e+12|0;if((c[a>>2]|0)!=(j|0))ga();b=d+8|0;if((c[b>>2]|0)==(j|0)){c[a>>2]=d;c[b>>2]=e;s=d;break}else ga()}while(0);do if(g|0){a=c[j+28>>2]|0;b=30880+(a<<2)|0;if((j|0)==(c[b>>2]|0)){c[b>>2]=s;if(!s){c[7645]=c[7645]&~(1<>>0<(c[7648]|0)>>>0)ga();a=g+16|0;if((c[a>>2]|0)==(j|0))c[a>>2]=s;else c[g+20>>2]=s;if(!s)break}b=c[7648]|0;if(s>>>0>>0)ga();c[s+24>>2]=g;a=c[j+16>>2]|0;do if(a|0)if(a>>>0>>0)ga();else{c[s+16>>2]=a;c[a+24>>2]=s;break}while(0);a=c[j+20>>2]|0;if(a|0)if(a>>>0<(c[7648]|0)>>>0)ga();else{c[s+20>>2]=a;c[a+24>>2]=s;break}}while(0);do if(i>>>0>=16){c[j+4>>2]=o|3;c[h+4>>2]=i|1;c[h+i>>2]=i;a=i>>>3;if(i>>>0<256){d=30616+(a<<1<<2)|0;b=c[7644]|0;a=1<>2]|0;if(b>>>0<(c[7648]|0)>>>0)ga();else{u=a;v=b}}else{c[7644]=b|a;u=d+8|0;v=d}c[u>>2]=h;c[v+12>>2]=h;c[h+8>>2]=v;c[h+12>>2]=d;break}a=i>>>8;if(a)if(i>>>0>16777215)d=31;else{K=(a+1048320|0)>>>16&8;L=a<>>16&4;L=L<>>16&2;d=14-(J|K|d)+(L<>>15)|0;d=i>>>(d+7|0)&1|d<<1}else d=0;e=30880+(d<<2)|0;c[h+28>>2]=d;a=h+16|0;c[a+4>>2]=0;c[a>>2]=0;a=c[7645]|0;b=1<>2]=h;c[h+24>>2]=e;c[h+12>>2]=h;c[h+8>>2]=h;break}f=i<<((d|0)==31?0:25-(d>>>1)|0);a=c[e>>2]|0;while(1){if((c[a+4>>2]&-8|0)==(i|0)){d=a;E=148;break}b=a+16+(f>>>31<<2)|0;d=c[b>>2]|0;if(!d){E=145;break}else{f=f<<1;a=d}}if((E|0)==145)if(b>>>0<(c[7648]|0)>>>0)ga();else{c[b>>2]=h;c[h+24>>2]=a;c[h+12>>2]=h;c[h+8>>2]=h;break}else if((E|0)==148){a=d+8|0;b=c[a>>2]|0;L=c[7648]|0;if(b>>>0>=L>>>0&d>>>0>=L>>>0){c[b+12>>2]=h;c[a>>2]=h;c[h+8>>2]=b;c[h+12>>2]=d;c[h+24>>2]=0;break}else ga()}}else{L=i+o|0;c[j+4>>2]=L|3;L=j+L+4|0;c[L>>2]=c[L>>2]|1}while(0);L=j+8|0;return L|0}}}else o=-1;while(0);d=c[7646]|0;if(d>>>0>=o>>>0){a=d-o|0;b=c[7649]|0;if(a>>>0>15){L=b+o|0;c[7649]=L;c[7646]=a;c[L+4>>2]=a|1;c[L+a>>2]=a;c[b+4>>2]=o|3}else{c[7646]=0;c[7649]=0;c[b+4>>2]=d|3;L=b+d+4|0;c[L>>2]=c[L>>2]|1}L=b+8|0;return L|0}a=c[7647]|0;if(a>>>0>o>>>0){J=a-o|0;c[7647]=J;L=c[7650]|0;K=L+o|0;c[7650]=K;c[K+4>>2]=J|1;c[L+4>>2]=o|3;L=L+8|0;return L|0}do if(!(c[7762]|0)){a=oa(30)|0;if(!(a+-1&a)){c[7764]=a;c[7763]=a;c[7765]=-1;c[7766]=-1;c[7767]=0;c[7755]=0;c[7762]=(ka(0)|0)&-16^1431655768;break}else ga()}while(0);h=o+48|0;g=c[7764]|0;i=o+47|0;f=g+i|0;g=0-g|0;j=f&g;if(j>>>0<=o>>>0){L=0;return L|0}a=c[7754]|0;if(a|0?(u=c[7752]|0,v=u+j|0,v>>>0<=u>>>0|v>>>0>a>>>0):0){L=0;return L|0}b:do if(!(c[7755]&4)){a=c[7650]|0;c:do if(a){d=31024;while(1){b=c[d>>2]|0;if(b>>>0<=a>>>0?(r=d+4|0,(b+(c[r>>2]|0)|0)>>>0>a>>>0):0){e=d;d=r;break}d=c[d+8>>2]|0;if(!d){E=173;break c}}a=f-(c[7647]|0)&g;if(a>>>0<2147483647){b=ja(a|0)|0;if((b|0)==((c[e>>2]|0)+(c[d>>2]|0)|0)){if((b|0)!=(-1|0)){h=b;f=a;E=193;break b}}else E=183}}else E=173;while(0);do if((E|0)==173?(t=ja(0)|0,(t|0)!=(-1|0)):0){a=t;b=c[7763]|0;d=b+-1|0;if(!(d&a))a=j;else a=j-a+(d+a&0-b)|0;b=c[7752]|0;d=b+a|0;if(a>>>0>o>>>0&a>>>0<2147483647){v=c[7754]|0;if(v|0?d>>>0<=b>>>0|d>>>0>v>>>0:0)break;b=ja(a|0)|0;if((b|0)==(t|0)){h=t;f=a;E=193;break b}else E=183}}while(0);d:do if((E|0)==183){d=0-a|0;do if(h>>>0>a>>>0&(a>>>0<2147483647&(b|0)!=(-1|0))?(w=c[7764]|0,w=i-a+w&0-w,w>>>0<2147483647):0)if((ja(w|0)|0)==(-1|0)){ja(d|0)|0;break d}else{a=w+a|0;break}while(0);if((b|0)!=(-1|0)){h=b;f=a;E=193;break b}}while(0);c[7755]=c[7755]|4;E=190}else E=190;while(0);if((((E|0)==190?j>>>0<2147483647:0)?(x=ja(j|0)|0,y=ja(0)|0,x>>>0>>0&((x|0)!=(-1|0)&(y|0)!=(-1|0))):0)?(z=y-x|0,z>>>0>(o+40|0)>>>0):0){h=x;f=z;E=193}if((E|0)==193){a=(c[7752]|0)+f|0;c[7752]=a;if(a>>>0>(c[7753]|0)>>>0)c[7753]=a;i=c[7650]|0;do if(i){e=31024;do{a=c[e>>2]|0;b=e+4|0;d=c[b>>2]|0;if((h|0)==(a+d|0)){A=a;B=b;C=d;D=e;E=203;break}e=c[e+8>>2]|0}while((e|0)!=0);if(((E|0)==203?(c[D+12>>2]&8|0)==0:0)?i>>>0>>0&i>>>0>=A>>>0:0){c[B>>2]=C+f;L=i+8|0;L=(L&7|0)==0?0:0-L&7;K=i+L|0;L=f-L+(c[7647]|0)|0;c[7650]=K;c[7647]=L;c[K+4>>2]=L|1;c[K+L+4>>2]=40;c[7651]=c[7766];break}a=c[7648]|0;if(h>>>0>>0){c[7648]=h;j=h}else j=a;d=h+f|0;a=31024;while(1){if((c[a>>2]|0)==(d|0)){b=a;E=211;break}a=c[a+8>>2]|0;if(!a){b=31024;break}}if((E|0)==211)if(!(c[a+12>>2]&8)){c[b>>2]=h;l=a+4|0;c[l>>2]=(c[l>>2]|0)+f;l=h+8|0;l=h+((l&7|0)==0?0:0-l&7)|0;a=d+8|0;a=d+((a&7|0)==0?0:0-a&7)|0;k=l+o|0;g=a-l-o|0;c[l+4>>2]=o|3;do if((a|0)!=(i|0)){if((a|0)==(c[7649]|0)){L=(c[7646]|0)+g|0;c[7646]=L;c[7649]=k;c[k+4>>2]=L|1;c[k+L>>2]=L;break}b=c[a+4>>2]|0;if((b&3|0)==1){i=b&-8;f=b>>>3;e:do if(b>>>0>=256){h=c[a+24>>2]|0;e=c[a+12>>2]|0;do if((e|0)==(a|0)){d=a+16|0;e=d+4|0;b=c[e>>2]|0;if(!b){b=c[d>>2]|0;if(!b){J=0;break}}else d=e;while(1){e=b+20|0;f=c[e>>2]|0;if(f|0){b=f;d=e;continue}e=b+16|0;f=c[e>>2]|0;if(!f)break;else{b=f;d=e}}if(d>>>0>>0)ga();else{c[d>>2]=0;J=b;break}}else{f=c[a+8>>2]|0;if(f>>>0>>0)ga();b=f+12|0;if((c[b>>2]|0)!=(a|0))ga();d=e+8|0;if((c[d>>2]|0)==(a|0)){c[b>>2]=e;c[d>>2]=f;J=e;break}else ga()}while(0);if(!h)break;b=c[a+28>>2]|0;d=30880+(b<<2)|0;do if((a|0)!=(c[d>>2]|0)){if(h>>>0<(c[7648]|0)>>>0)ga();b=h+16|0;if((c[b>>2]|0)==(a|0))c[b>>2]=J;else c[h+20>>2]=J;if(!J)break e}else{c[d>>2]=J;if(J|0)break;c[7645]=c[7645]&~(1<>>0>>0)ga();c[J+24>>2]=h;b=a+16|0;d=c[b>>2]|0;do if(d|0)if(d>>>0>>0)ga();else{c[J+16>>2]=d;c[d+24>>2]=J;break}while(0);b=c[b+4>>2]|0;if(!b)break;if(b>>>0<(c[7648]|0)>>>0)ga();else{c[J+20>>2]=b;c[b+24>>2]=J;break}}else{d=c[a+8>>2]|0;e=c[a+12>>2]|0;b=30616+(f<<1<<2)|0;do if((d|0)!=(b|0)){if(d>>>0>>0)ga();if((c[d+12>>2]|0)==(a|0))break;ga()}while(0);if((e|0)==(d|0)){c[7644]=c[7644]&~(1<>>0>>0)ga();b=e+8|0;if((c[b>>2]|0)==(a|0)){G=b;break}ga()}while(0);c[d+12>>2]=e;c[G>>2]=d}while(0);a=a+i|0;g=i+g|0}a=a+4|0;c[a>>2]=c[a>>2]&-2;c[k+4>>2]=g|1;c[k+g>>2]=g;a=g>>>3;if(g>>>0<256){d=30616+(a<<1<<2)|0;b=c[7644]|0;a=1<>2]|0;if(b>>>0>=(c[7648]|0)>>>0){K=a;L=b;break}ga()}while(0);c[K>>2]=k;c[L+12>>2]=k;c[k+8>>2]=L;c[k+12>>2]=d;break}a=g>>>8;do if(!a)d=0;else{if(g>>>0>16777215){d=31;break}K=(a+1048320|0)>>>16&8;L=a<>>16&4;L=L<>>16&2;d=14-(J|K|d)+(L<>>15)|0;d=g>>>(d+7|0)&1|d<<1}while(0);e=30880+(d<<2)|0;c[k+28>>2]=d;a=k+16|0;c[a+4>>2]=0;c[a>>2]=0;a=c[7645]|0;b=1<>2]=k;c[k+24>>2]=e;c[k+12>>2]=k;c[k+8>>2]=k;break}f=g<<((d|0)==31?0:25-(d>>>1)|0);a=c[e>>2]|0;while(1){if((c[a+4>>2]&-8|0)==(g|0)){d=a;E=281;break}b=a+16+(f>>>31<<2)|0;d=c[b>>2]|0;if(!d){E=278;break}else{f=f<<1;a=d}}if((E|0)==278)if(b>>>0<(c[7648]|0)>>>0)ga();else{c[b>>2]=k;c[k+24>>2]=a;c[k+12>>2]=k;c[k+8>>2]=k;break}else if((E|0)==281){a=d+8|0;b=c[a>>2]|0;L=c[7648]|0;if(b>>>0>=L>>>0&d>>>0>=L>>>0){c[b+12>>2]=k;c[a>>2]=k;c[k+8>>2]=b;c[k+12>>2]=d;c[k+24>>2]=0;break}else ga()}}else{L=(c[7647]|0)+g|0;c[7647]=L;c[7650]=k;c[k+4>>2]=L|1}while(0);L=l+8|0;return L|0}else b=31024;while(1){a=c[b>>2]|0;if(a>>>0<=i>>>0?(F=a+(c[b+4>>2]|0)|0,F>>>0>i>>>0):0){b=F;break}b=c[b+8>>2]|0}g=b+-47|0;d=g+8|0;d=g+((d&7|0)==0?0:0-d&7)|0;g=i+16|0;d=d>>>0>>0?i:d;a=d+8|0;e=h+8|0;e=(e&7|0)==0?0:0-e&7;L=h+e|0;e=f+-40-e|0;c[7650]=L;c[7647]=e;c[L+4>>2]=e|1;c[L+e+4>>2]=40;c[7651]=c[7766];e=d+4|0;c[e>>2]=27;c[a>>2]=c[7756];c[a+4>>2]=c[7757];c[a+8>>2]=c[7758];c[a+12>>2]=c[7759];c[7756]=h;c[7757]=f;c[7759]=0;c[7758]=a;a=d+24|0;do{a=a+4|0;c[a>>2]=7}while((a+4|0)>>>0>>0);if((d|0)!=(i|0)){h=d-i|0;c[e>>2]=c[e>>2]&-2;c[i+4>>2]=h|1;c[d>>2]=h;a=h>>>3;if(h>>>0<256){d=30616+(a<<1<<2)|0;b=c[7644]|0;a=1<>2]|0;if(b>>>0<(c[7648]|0)>>>0)ga();else{H=a;I=b}}else{c[7644]=b|a;H=d+8|0;I=d}c[H>>2]=i;c[I+12>>2]=i;c[i+8>>2]=I;c[i+12>>2]=d;break}a=h>>>8;if(a)if(h>>>0>16777215)d=31;else{K=(a+1048320|0)>>>16&8;L=a<>>16&4;L=L<>>16&2;d=14-(J|K|d)+(L<>>15)|0;d=h>>>(d+7|0)&1|d<<1}else d=0;f=30880+(d<<2)|0;c[i+28>>2]=d;c[i+20>>2]=0;c[g>>2]=0;a=c[7645]|0;b=1<>2]=i;c[i+24>>2]=f;c[i+12>>2]=i;c[i+8>>2]=i;break}e=h<<((d|0)==31?0:25-(d>>>1)|0);a=c[f>>2]|0;while(1){if((c[a+4>>2]&-8|0)==(h|0)){d=a;E=307;break}b=a+16+(e>>>31<<2)|0;d=c[b>>2]|0;if(!d){E=304;break}else{e=e<<1;a=d}}if((E|0)==304)if(b>>>0<(c[7648]|0)>>>0)ga();else{c[b>>2]=i;c[i+24>>2]=a;c[i+12>>2]=i;c[i+8>>2]=i;break}else if((E|0)==307){a=d+8|0;b=c[a>>2]|0;L=c[7648]|0;if(b>>>0>=L>>>0&d>>>0>=L>>>0){c[b+12>>2]=i;c[a>>2]=i;c[i+8>>2]=b;c[i+12>>2]=d;c[i+24>>2]=0;break}else ga()}}}else{L=c[7648]|0;if((L|0)==0|h>>>0>>0)c[7648]=h;c[7756]=h;c[7757]=f;c[7759]=0;c[7653]=c[7762];c[7652]=-1;a=0;do{L=30616+(a<<1<<2)|0;c[L+12>>2]=L;c[L+8>>2]=L;a=a+1|0}while((a|0)!=32);L=h+8|0;L=(L&7|0)==0?0:0-L&7;K=h+L|0;L=f+-40-L|0;c[7650]=K;c[7647]=L;c[K+4>>2]=L|1;c[K+L+4>>2]=40;c[7651]=c[7766]}while(0);a=c[7647]|0;if(a>>>0>o>>>0){J=a-o|0;c[7647]=J;L=c[7650]|0;K=L+o|0;c[7650]=K;c[K+4>>2]=J|1;c[L+4>>2]=o|3;L=L+8|0;return L|0}}c[(fj()|0)>>2]=12;L=0;return L|0}function kj(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;if(!a)return;d=a+-8|0;h=c[7648]|0;if(d>>>0>>0)ga();a=c[a+-4>>2]|0;b=a&3;if((b|0)==1)ga();e=a&-8;m=d+e|0;do if(!(a&1)){a=c[d>>2]|0;if(!b)return;k=d+(0-a)|0;j=a+e|0;if(k>>>0>>0)ga();if((k|0)==(c[7649]|0)){a=m+4|0;b=c[a>>2]|0;if((b&3|0)!=3){q=k;g=j;break}c[7646]=j;c[a>>2]=b&-2;c[k+4>>2]=j|1;c[k+j>>2]=j;return}e=a>>>3;if(a>>>0<256){b=c[k+8>>2]|0;d=c[k+12>>2]|0;a=30616+(e<<1<<2)|0;if((b|0)!=(a|0)){if(b>>>0>>0)ga();if((c[b+12>>2]|0)!=(k|0))ga()}if((d|0)==(b|0)){c[7644]=c[7644]&~(1<>>0>>0)ga();a=d+8|0;if((c[a>>2]|0)==(k|0))f=a;else ga()}else f=d+8|0;c[b+12>>2]=d;c[f>>2]=b;q=k;g=j;break}f=c[k+24>>2]|0;d=c[k+12>>2]|0;do if((d|0)==(k|0)){b=k+16|0;d=b+4|0;a=c[d>>2]|0;if(!a){a=c[b>>2]|0;if(!a){i=0;break}}else b=d;while(1){d=a+20|0;e=c[d>>2]|0;if(e|0){a=e;b=d;continue}d=a+16|0;e=c[d>>2]|0;if(!e)break;else{a=e;b=d}}if(b>>>0>>0)ga();else{c[b>>2]=0;i=a;break}}else{e=c[k+8>>2]|0;if(e>>>0>>0)ga();a=e+12|0;if((c[a>>2]|0)!=(k|0))ga();b=d+8|0;if((c[b>>2]|0)==(k|0)){c[a>>2]=d;c[b>>2]=e;i=d;break}else ga()}while(0);if(f){a=c[k+28>>2]|0;b=30880+(a<<2)|0;if((k|0)==(c[b>>2]|0)){c[b>>2]=i;if(!i){c[7645]=c[7645]&~(1<>>0<(c[7648]|0)>>>0)ga();a=f+16|0;if((c[a>>2]|0)==(k|0))c[a>>2]=i;else c[f+20>>2]=i;if(!i){q=k;g=j;break}}d=c[7648]|0;if(i>>>0>>0)ga();c[i+24>>2]=f;a=k+16|0;b=c[a>>2]|0;do if(b|0)if(b>>>0>>0)ga();else{c[i+16>>2]=b;c[b+24>>2]=i;break}while(0);a=c[a+4>>2]|0;if(a)if(a>>>0<(c[7648]|0)>>>0)ga();else{c[i+20>>2]=a;c[a+24>>2]=i;q=k;g=j;break}else{q=k;g=j}}else{q=k;g=j}}else{q=d;g=e}while(0);if(q>>>0>=m>>>0)ga();a=m+4|0;b=c[a>>2]|0;if(!(b&1))ga();if(!(b&2)){if((m|0)==(c[7650]|0)){p=(c[7647]|0)+g|0;c[7647]=p;c[7650]=q;c[q+4>>2]=p|1;if((q|0)!=(c[7649]|0))return;c[7649]=0;c[7646]=0;return}if((m|0)==(c[7649]|0)){p=(c[7646]|0)+g|0;c[7646]=p;c[7649]=q;c[q+4>>2]=p|1;c[q+p>>2]=p;return}g=(b&-8)+g|0;e=b>>>3;do if(b>>>0>=256){f=c[m+24>>2]|0;a=c[m+12>>2]|0;do if((a|0)==(m|0)){b=m+16|0;d=b+4|0;a=c[d>>2]|0;if(!a){a=c[b>>2]|0;if(!a){n=0;break}}else b=d;while(1){d=a+20|0;e=c[d>>2]|0;if(e|0){a=e;b=d;continue}d=a+16|0;e=c[d>>2]|0;if(!e)break;else{a=e;b=d}}if(b>>>0<(c[7648]|0)>>>0)ga();else{c[b>>2]=0;n=a;break}}else{b=c[m+8>>2]|0;if(b>>>0<(c[7648]|0)>>>0)ga();d=b+12|0;if((c[d>>2]|0)!=(m|0))ga();e=a+8|0;if((c[e>>2]|0)==(m|0)){c[d>>2]=a;c[e>>2]=b;n=a;break}else ga()}while(0);if(f|0){a=c[m+28>>2]|0;b=30880+(a<<2)|0;if((m|0)==(c[b>>2]|0)){c[b>>2]=n;if(!n){c[7645]=c[7645]&~(1<>>0<(c[7648]|0)>>>0)ga();a=f+16|0;if((c[a>>2]|0)==(m|0))c[a>>2]=n;else c[f+20>>2]=n;if(!n)break}d=c[7648]|0;if(n>>>0>>0)ga();c[n+24>>2]=f;a=m+16|0;b=c[a>>2]|0;do if(b|0)if(b>>>0>>0)ga();else{c[n+16>>2]=b;c[b+24>>2]=n;break}while(0);a=c[a+4>>2]|0;if(a|0)if(a>>>0<(c[7648]|0)>>>0)ga();else{c[n+20>>2]=a;c[a+24>>2]=n;break}}}else{b=c[m+8>>2]|0;d=c[m+12>>2]|0;a=30616+(e<<1<<2)|0;if((b|0)!=(a|0)){if(b>>>0<(c[7648]|0)>>>0)ga();if((c[b+12>>2]|0)!=(m|0))ga()}if((d|0)==(b|0)){c[7644]=c[7644]&~(1<>>0<(c[7648]|0)>>>0)ga();a=d+8|0;if((c[a>>2]|0)==(m|0))l=a;else ga()}else l=d+8|0;c[b+12>>2]=d;c[l>>2]=b}while(0);c[q+4>>2]=g|1;c[q+g>>2]=g;if((q|0)==(c[7649]|0)){c[7646]=g;return}}else{c[a>>2]=b&-2;c[q+4>>2]=g|1;c[q+g>>2]=g}a=g>>>3;if(g>>>0<256){d=30616+(a<<1<<2)|0;b=c[7644]|0;a=1<>2]|0;if(b>>>0<(c[7648]|0)>>>0)ga();else{o=a;p=b}}else{c[7644]=b|a;o=d+8|0;p=d}c[o>>2]=q;c[p+12>>2]=q;c[q+8>>2]=p;c[q+12>>2]=d;return}a=g>>>8;if(a)if(g>>>0>16777215)d=31;else{o=(a+1048320|0)>>>16&8;p=a<>>16&4;p=p<>>16&2;d=14-(n|o|d)+(p<>>15)|0;d=g>>>(d+7|0)&1|d<<1}else d=0;e=30880+(d<<2)|0;c[q+28>>2]=d;c[q+20>>2]=0;c[q+16>>2]=0;a=c[7645]|0;b=1<>>1)|0);a=c[e>>2]|0;while(1){if((c[a+4>>2]&-8|0)==(g|0)){d=a;e=130;break}b=a+16+(f>>>31<<2)|0;d=c[b>>2]|0;if(!d){e=127;break}else{f=f<<1;a=d}}if((e|0)==127)if(b>>>0<(c[7648]|0)>>>0)ga();else{c[b>>2]=q;c[q+24>>2]=a;c[q+12>>2]=q;c[q+8>>2]=q;break}else if((e|0)==130){a=d+8|0;b=c[a>>2]|0;p=c[7648]|0;if(b>>>0>=p>>>0&d>>>0>=p>>>0){c[b+12>>2]=q;c[a>>2]=q;c[q+8>>2]=b;c[q+12>>2]=d;c[q+24>>2]=0;break}else ga()}}else{c[7645]=a|b;c[e>>2]=q;c[q+24>>2]=e;c[q+12>>2]=q;c[q+8>>2]=q}while(0);q=(c[7652]|0)+-1|0;c[7652]=q;if(!q)a=31032;else return;while(1){a=c[a>>2]|0;if(!a)break;else a=a+8|0}c[7652]=-1;return}function lj(){}function mj(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;c=a+c>>>0;return (C=b+d+(c>>>0>>0|0)>>>0,c|0)|0}function nj(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){C=b>>c;return a>>>c|(b&(1<>c-32|0}function oj(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0;f=b+e|0;if((e|0)>=20){d=d&255;h=b&3;i=d|d<<8|d<<16|d<<24;g=f&~3;if(h){h=b+4-h|0;while((b|0)<(h|0)){a[b>>0]=d;b=b+1|0}}while((b|0)<(g|0)){c[b>>2]=i;b=b+4|0}}while((b|0)<(f|0)){a[b>>0]=d;b=b+1|0}return b-e|0}function pj(b,d,e){b=b|0;d=d|0;e=e|0;var f=0;if((e|0)>=4096)return ma(b|0,d|0,e|0)|0;f=b|0;if((b&3)==(d&3)){while(b&3){if(!e)return f|0;a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}while((e|0)>=4){c[b>>2]=c[d>>2];b=b+4|0;d=d+4|0;e=e-4|0}}while((e|0)>0){a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}return f|0}function qj(b,c,d){b=b|0;c=c|0;d=d|0;var e=0;if((c|0)<(b|0)&(b|0)<(c+d|0)){e=b;c=c+d|0;b=b+d|0;while((d|0)>0){b=b-1|0;c=c-1|0;d=d-1|0;a[b>>0]=a[c>>0]|0}b=e}else pj(b,c,d)|0;return b|0}function rj(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;d=b-d-(c>>>0>a>>>0|0)>>>0;return (C=d,a-c>>>0|0)|0}function sj(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){C=b<>>32-c;return a<>>c;return a>>>c|(b&(1<>>c-32|0}function uj(b){b=b|0;var c=0;c=a[m+(b&255)>>0]|0;if((c|0)<8)return c|0;c=a[m+(b>>8&255)>>0]|0;if((c|0)<8)return c+8|0;c=a[m+(b>>16&255)>>0]|0;if((c|0)<8)return c+16|0;return (a[m+(b>>>24)>>0]|0)+24|0}function vj(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0;f=a&65535;e=b&65535;c=_(e,f)|0;d=a>>>16;a=(c>>>16)+(_(e,d)|0)|0;e=b>>>16;b=_(e,f)|0;return (C=(a>>>16)+(_(e,d)|0)+(((a&65535)+b|0)>>>16)|0,a+b<<16|c&65535|0)|0}function wj(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0;j=b>>31|((b|0)<0?-1:0)<<1;i=((b|0)<0?-1:0)>>31|((b|0)<0?-1:0)<<1;f=d>>31|((d|0)<0?-1:0)<<1;e=((d|0)<0?-1:0)>>31|((d|0)<0?-1:0)<<1;h=rj(j^a|0,i^b|0,j|0,i|0)|0;g=C;a=f^j;b=e^i;return rj((Bj(h,g,rj(f^c|0,e^d|0,f|0,e|0)|0,C,0)|0)^a|0,C^b|0,a|0,b|0)|0}function xj(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0;f=i;i=i+16|0;j=f|0;h=b>>31|((b|0)<0?-1:0)<<1;g=((b|0)<0?-1:0)>>31|((b|0)<0?-1:0)<<1;l=e>>31|((e|0)<0?-1:0)<<1;k=((e|0)<0?-1:0)>>31|((e|0)<0?-1:0)<<1;a=rj(h^a|0,g^b|0,h|0,g|0)|0;b=C;Bj(a,b,rj(l^d|0,k^e|0,l|0,k|0)|0,C,j)|0;e=rj(c[j>>2]^h|0,c[j+4>>2]^g|0,h|0,g|0)|0;d=C;i=f;return (C=d,e)|0}function yj(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0;e=a;f=c;c=vj(e,f)|0;a=C;return (C=(_(b,f)|0)+(_(d,e)|0)+a|a&0,c|0|0)|0}function zj(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;return Bj(a,b,c,d,0)|0}function Aj(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0;g=i;i=i+16|0;f=g|0;Bj(a,b,d,e,f)|0;i=g;return (C=c[f+4>>2]|0,c[f>>2]|0)|0}function Bj(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;l=a;j=b;k=j;h=d;n=e;i=n;if(!k){g=(f|0)!=0;if(!i){if(g){c[f>>2]=(l>>>0)%(h>>>0);c[f+4>>2]=0}n=0;f=(l>>>0)/(h>>>0)>>>0;return (C=n,f)|0}else{if(!g){n=0;f=0;return (C=n,f)|0}c[f>>2]=a|0;c[f+4>>2]=b&0;n=0;f=0;return (C=n,f)|0}}g=(i|0)==0;do if(h){if(!g){g=(aa(i|0)|0)-(aa(k|0)|0)|0;if(g>>>0<=31){m=g+1|0;i=31-g|0;b=g-31>>31;h=m;a=l>>>(m>>>0)&b|k<>>(m>>>0)&b;g=0;i=l<>2]=a|0;c[f+4>>2]=j|b&0;n=0;f=0;return (C=n,f)|0}g=h-1|0;if(g&h|0){i=(aa(h|0)|0)+33-(aa(k|0)|0)|0;p=64-i|0;m=32-i|0;j=m>>31;o=i-32|0;b=o>>31;h=i;a=m-1>>31&k>>>(o>>>0)|(k<>>(i>>>0))&b;b=b&k>>>(i>>>0);g=l<>>(o>>>0))&j|l<>31;break}if(f|0){c[f>>2]=g&l;c[f+4>>2]=0}if((h|0)==1){o=j|b&0;p=a|0|0;return (C=o,p)|0}else{p=uj(h|0)|0;o=k>>>(p>>>0)|0;p=k<<32-p|l>>>(p>>>0)|0;return (C=o,p)|0}}else{if(g){if(f|0){c[f>>2]=(k>>>0)%(h>>>0);c[f+4>>2]=0}o=0;p=(k>>>0)/(h>>>0)>>>0;return (C=o,p)|0}if(!l){if(f|0){c[f>>2]=0;c[f+4>>2]=(k>>>0)%(i>>>0)}o=0;p=(k>>>0)/(i>>>0)>>>0;return (C=o,p)|0}g=i-1|0;if(!(g&i)){if(f|0){c[f>>2]=a|0;c[f+4>>2]=g&k|b&0}o=0;p=k>>>((uj(i|0)|0)>>>0);return (C=o,p)|0}g=(aa(i|0)|0)-(aa(k|0)|0)|0;if(g>>>0<=30){b=g+1|0;i=31-g|0;h=b;a=k<>>(b>>>0);b=k>>>(b>>>0);g=0;i=l<>2]=a|0;c[f+4>>2]=j|b&0;o=0;p=0;return (C=o,p)|0}while(0);if(!h){k=i;j=0;i=0}else{m=d|0|0;l=n|e&0;k=mj(m|0,l|0,-1,-1)|0;d=C;j=i;i=0;do{e=j;j=g>>>31|j<<1;g=i|g<<1;e=a<<1|e>>>31|0;n=a>>>31|b<<1|0;rj(k|0,d|0,e|0,n|0)|0;p=C;o=p>>31|((p|0)<0?-1:0)<<1;i=o&1;a=rj(e|0,n|0,o&m|0,(((p|0)<0?-1:0)>>31|((p|0)<0?-1:0)<<1)&l|0)|0;b=C;h=h-1|0}while((h|0)!=0);k=j;j=0}h=0;if(f|0){c[f>>2]=a;c[f+4>>2]=b}o=(g|0)>>>31|(k|h)<<1|(h<<1|g>>>31)&0|j;p=(g<<1|0>>>31)&-2|i;return (C=o,p)|0}function Cj(a,b,c,d,e,f,g,h){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;qa[a&3](b|0,c|0,d|0,e|0,f|0,g|0,h|0)}function Dj(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;ba(0)} + + // EMSCRIPTEN_END_FUNCS + var qa=[Dj,yi,xi,Dj];return{_opus_decoder_get_size:ai,_opus_get_version_string:gb,_free:kj,_opus_encode_float:Ri,_opus_strerror:fb,_i64Add:mj,_memmove:qj,_opus_decoder_init:ci,_bitshift64Ashr:nj,_opus_encoder_get_size:ti,_memset:oj,_malloc:jj,_opus_decoder_ctl:si,_opus_encode:Qi,_opus_encoder_init:vi,_opus_decode:mi,_opus_packet_get_nb_samples:oi,_memcpy:pj,_opus_encoder_ctl:Si,_opus_decode_float:ri,runPostSets:lj,stackAlloc:ra,stackSave:sa,stackRestore:ta,establishStackSpace:ua,setThrew:va,setTempRet0:ya,getTempRet0:za,dynCall_viiiiiii:Cj}}) + + + // EMSCRIPTEN_END_ASM + (b.s,b.t,buffer);b._opus_decoder_get_size=Z._opus_decoder_get_size;b._opus_get_version_string=Z._opus_get_version_string;var va=b._free=Z._free; + b._opus_encode_float=Z._opus_encode_float;b._opus_strerror=Z._opus_strerror;var Pa=b._i64Add=Z._i64Add,Ua=b._memmove=Z._memmove;b._opus_decoder_init=Z._opus_decoder_init;var Qa=b._bitshift64Ashr=Z._bitshift64Ashr;b._opus_encoder_get_size=Z._opus_encoder_get_size;var Ra=b._memset=Z._memset,Q=b._malloc=Z._malloc;b._opus_packet_get_nb_samples=Z._opus_packet_get_nb_samples;b._opus_encode=Z._opus_encode;b._opus_encoder_init=Z._opus_encoder_init;b._opus_decode=Z._opus_decode;b._opus_decoder_ctl=Z._opus_decoder_ctl; + var Sa=b._memcpy=Z._memcpy;b._opus_encoder_ctl=Z._opus_encoder_ctl;b._opus_decode_float=Z._opus_decode_float;b.runPostSets=Z.runPostSets;b.dynCall_viiiiiii=Z.dynCall_viiiiiii;y.f=Z.stackAlloc;y.g=Z.stackSave;y.c=Z.stackRestore;y.I=Z.establishStackSpace;y.B=Z.setTempRet0;y.w=Z.getTempRet0;function w(a){this.name="ExitStatus";this.message="Program terminated with exit("+a+")";this.status=a}w.prototype=Error();w.prototype.constructor=w;var Wa=null,X=function Xa(){b.calledRun||Ya();b.calledRun||(X=Xa)}; + b.callMain=b.G=function(a){function c(){for(var a=0;3>a;a++)e.push(0)}a=a||[];T||(T=!0,V(Ea));var d=a.length+1,e=[O(Ka(b.thisProgram),"i8",0)];c();for(var g=0;g>2]+(Mn<<5)|0)>>2],Qn=q[a+60>>2]+w(Xn,24)|0,Mn=(lo=q[Qn+8>>2])+-1|0,yo=(ro=q[Qn+4>>2])+-1|0,zo=vo=(Xn=q[q[a+152>>2]+(Xn<<2)>>2])+(lo<<3)|0,Ao=wo=Xn+((uo=w(ro,mo=lo+1|0))<<3)|0,Bo=xo=Xn+(lo+uo<<3)|0,Jo=q[Qn+12>>2],so=x(0|ro),to=x(0|lo),a=0;Wn=u[4+(Qn=(po=a<<3)+Nn|0)>>2],Sn=x(Wn*so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),x(0),x(0),x(0),x(0),x(0),(rn=q[16+(q[a+308>>2]+(rn<<5)|0)>>2])<<2),zn=function(a){var Cl,Fl,Dl,El,Bl=x(0);L=Dl=L-16|0,j(a);a:if((Cl=2147483647&(El=b[0]))>>>0<=1061752794)Bl=x(1),Cl>>>0<964689920||(Bl=ba(+a));else if(Cl>>>0<=1081824209)Fl=+a,Bl=1075235812<=Cl>>>0?x(-ba(((0|El)<0?3.141592653589793:-3.141592653589793)+Fl)):aa((0|El)<=-1?1.5707963267948966+Fl:1.5707963267948966-Fl);else if(Cl>>>0<=1088565717)Bl=1085271520<=Cl>>>0?ba(+a+((0|El)<0?6.283185307179586:-6.283185307179586)):aa((0|El)<=-1?-4.71238898038469-+a:+a-4.71238898038469);else if(Bl=x(a-a),!(2139095040<=Cl>>>0))if((Cl=3&Da(a,8+Dl|0))>>>0<=2){switch(Cl-1|0){default:Bl=ba(v[8+Dl>>3]);break a;case 0:Bl=aa(-v[8+Dl>>3]);break a;case 1:}Bl=x(-ba(v[8+Dl>>3]))}else Bl=aa(v[8+Dl>>3]);return L=16+Dl|0,Bl}(yn=x(x(x(u[4+(q[a+168>>2]+w(rn,12)|0)>>2]+u[xn+q[a+284>>2]>>2])*x(3.1415927410125732))/x(180))),An=u[xn+q[a+272>>2]>>2],En=q[xn+q[a+292>>2]>>2],yn=function(a){var Tk,yl,Al,zl=0;L=yl=L-16|0,j(a);a:if((Tk=2147483647&(Al=b[0]))>>>0<=1061752794)Tk>>>0<964689920||(a=aa(+a));else if(Tk>>>0<=1081824209)zl=+a,a=Tk>>>0<=1075235811?(0|Al)<=-1?x(-ba(zl+1.5707963267948966)):ba(zl+-1.5707963267948966):aa(-(((0|Al)<0?3.141592653589793:-3.141592653589793)+zl));else if(Tk>>>0<=1088565717)zl=+a,a=Tk>>>0<=1085271519?(0|Al)<=-1?ba(zl+4.71238898038469):x(-ba(zl+-4.71238898038469)):aa(((0|Al)<0?6.283185307179586:-6.283185307179586)+zl);else if(2139095040<=Tk>>>0)a=x(a-a);else if((Tk=3&Da(a,8+yl|0))>>>0<=2){switch(Tk-1|0){default:a=aa(v[8+yl>>3]);break a;case 0:a=ba(v[8+yl>>3]);break a;case 1:}a=aa(-v[8+yl>>3])}else a=x(-ba(v[8+yl>>3]));return L=16+yl|0,a}(yn);if((rn=0)<(0|wn))for(zn=x(An*zn),Cn=x(En?-1:1),Fn=x(zn*Cn),Bn=q[xn+q[a+288>>2]>>2]?x(-1):x(1),Gn=x(x(An*yn)*Bn),zn=x(zn*Bn),An=x(x(An*x(-yn))*Cn),yn=u[xn+q[a+280>>2]>>2],Cn=u[xn+q[a+276>>2]>>2];xn=(a=rn<<3)+vn|0,Bn=u[(a=a+sn|0)>>2],Dn=u[a+4>>2],u[xn+4>>2]=yn+x(x(Gn*Bn)+x(Fn*Dn)),u[xn>>2]=Cn+x(x(zn*Bn)+x(An*Dn)),(0|wn)!=(0|(rn=rn+1|0)););},n[4]=function(a,jh){a|=0,jh|=0;var vh,wh,xh,yh,zh,kh,lh=0,mh=0,nh=0,oh=x(0),ph=0,qh=0,rh=x(0),sh=0,th=0,uh=0;if(x(0),x(0),x(0),x(0),L=kh=L+-64|0,sh=q[a+320>>2],th=q[a+316>>2],mh=q[a+308>>2],-1==(0|(ph=q[8+(nh=mh+(jh<<5)|0)>>2])))lh=q[nh+16>>2]<<2,q[(mh=jh<<2)+th>>2]=q[lh+q[a+268>>2]>>2],q[mh+sh>>2]=q[lh+q[a+272>>2]>>2];else{lh=q[nh+16>>2]<<2,uh=q[lh+q[a+276>>2]>>2],q[24+kh>>2]=uh,lh=q[lh+q[a+280>>2]>>2],q[28+kh>>2]=lh,q[16+kh>>2]=0,wh=1==q[12+(qh=mh+(ph<<5)|0)>>2]?x(-10):x(-.10000000149011612),u[20+kh>>2]=wh,q[60+kh>>2]=lh,q[56+kh>>2]=uh,n[q[qh+24>>2]](a,ph,56+kh|0,48+kh|0,1),oh=x(1),mh=9;b:{for(;;){if(lh=mh,rh=x(oh*x(0)),u[32+kh>>2]=rh+u[56+kh>>2],vh=x(wh*oh),u[36+kh>>2]=vh+u[60+kh>>2],n[q[qh+24>>2]](a,ph,32+kh|0,40+kh|0,1),xh=x(u[44+kh>>2]-u[52+kh>>2]),u[44+kh>>2]=xh,yh=x(u[40+kh>>2]-u[48+kh>>2]),u[40+kh>>2]=yh,xh!=x(0)||yh!=x(0)){mh=q[44+kh>>2],q[8+kh>>2]=q[40+kh>>2],q[12+kh>>2]=mh;break b}if(u[32+kh>>2]=u[56+kh>>2]-rh,u[36+kh>>2]=u[60+kh>>2]-vh,n[q[qh+24>>2]](a,ph,32+kh|0,40+kh|0,1),rh=x(u[40+kh>>2]-u[48+kh>>2]),u[40+kh>>2]=rh,vh=x(u[44+kh>>2]-u[52+kh>>2]),(u[44+kh>>2]=vh)!=x(0)||rh!=x(0)){u[12+kh>>2]=-vh,u[8+kh>>2]=-rh;break b}if(mh=lh+-1|0,oh=x(oh*x(.10000000149011612)),!lh)break}Y(3,1311,0)}oh=function(a,Sh){var Th=x(0);if((Th=x(Ba(u[4+a>>2],u[a>>2])-Ba(u[4+Sh>>2],u[Sh>>2])))x(3.1415927410125732))for(;(Th=x(Th+x(-6.2831854820251465)))>x(3.1415927410125732););return Th}(16+kh|0,8+kh|0),n[q[qh+24>>2]](a,q[nh+8>>2],24+kh|0,24+kh|0,1),mh=q[nh+16>>2]<<2,q[mh+q[a+276>>2]>>2]=q[24+kh>>2],q[mh+q[a+280>>2]>>2]=q[28+kh>>2],lh=mh+q[a+284>>2]|0,u[lh>>2]=u[lh>>2]+x(x(oh*x(-180))/x(3.1415927410125732)),nh=q[nh+8>>2]<<2,u[(lh=jh<<2)+th>>2]=u[mh+q[a+268>>2]>>2]*u[nh+th>>2],mh=mh+q[a+272>>2]|0,oh=x(u[mh>>2]*u[nh+sh>>2]),u[lh+sh>>2]=oh,u[mh>>2]=oh}4<=r[q[a>>2]+4|0]&&(lh=jh<<2,nh=q[a+308>>2]+(jh<<5)|0,ph=q[nh+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+1|0)););if(!((0|(zj=zj+1|0))<(0|Ij)))break}if(Ej=q[Cj+Nj>>2]+Ej|0,!((0|(yj=yj+1|0))<(0|Hj)))break}},n[9]=function(a){var Je,Ke,Le,Fe=0,Ge=0,He=0,Ie=0;if(!(q[(a|=0)+648>>2]||(0|(Fe=q[a+332>>2]))<1))for(Ke=(Ge=q[a+336>>2])+w(Fe,20)|0,Fe=q[a+424>>2],Ie=q[a+444>>2];;){if(q[Fe>>2]&&!((0|(He=q[Ge+16>>2]))<(a=1)))for(He<<=1,Le=q[Ie>>2];u[(Je=(a<<2)+Le|0)>>2]=-u[Je>>2],(0|(a=a+2|0))<(0|He););if(Ie=Ie+4|0,Fe=Fe+4|0,!((Ge=Ge+20|0)>>>0>>0))break}},n[10]=function(a,rn,sn){var un;return $(un=q[20+(a|=0)>>2],rn|=0,rn=(sn|=0)>>>0<(rn=q[a+16>>2]-un|0)>>>0?sn:rn),q[a+20>>2]=rn+q[a+20>>2],0|sn},n[11]=function(a,Gl,Pm,Qm,Rm,Sm){a|=0,Gl=+Gl,Pm|=0,Qm|=0,Rm|=0,Sm|=0;var dn,on,Xm,hn,Tm=0,Um=0,Vm=0,Wm=0,Ym=0,Zm=0,_m=0,$m=0,an=0,bn=0,cn=0,en=0,fn=0,gn=0,kn=0;if(q[44+(L=Xm=L-560|0)>>2]=0,h(+Gl),Tm=0|b[1],on=4294967295>>0?0:1,hn=(0|Tm)<-1||(0|Tm)<=-1&&on?(h(Gl=-Gl),Tm=0|b[1],b[0],gn=1,3872):2048&Rm?(gn=1,3875):(gn=1&Rm)?3878:3873,2146435072==(2146435072&Tm))_(a,32,Pm,Zm=gn+3|0,-65537&Rm),Z(a,hn,gn),Qm=Sm>>>5&1,Z(a,Gl!=Gl?Qm?3899:3903:Qm?3891:3895,3);else if(Gl=function Ja(a,ic){var kc,lc,jc=0;if(h(+a),jc=0|b[1],kc=0|b[0],2047!=(0|(jc=(lc=jc)>>>20&2047))){if(!jc)return jc=ic,ic=0==a?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m+1|0,(0|_m)<1&&!Ym||Z(a,3907,1);if(Z(a,$m=Tm,(0|(Tm=bn-Tm|0))<(0|_m)?Tm:_m),_m=_m-Tm|0,Sm>>>0<=(Vm=Vm+4|0)>>>0)break q;if(!(-1<(0|_m)))break}_(a,48,_m+18|0,18,0),Z(a,fn,dn-fn|0)}}return _(a,32,Pm,Zm,8192^Rm),L=560+Xm|0,0|((0|Zm)<(0|Pm)?Pm:Zm)},n[12]=function(a,Gl){a|=0;var Cm=Gl|=0;Gl=q[Gl>>2]+15&-16,q[Cm>>2]=Gl+16,Cm=a,a=function(a,Gl,Hl,Zl){var dm,am,_l=0,$l=0,bm=0,cm=0;return L=am=L-32|0,_l=(cm=_l=2147483647&Zl)-1006698496|0,$l=_l=(dm=$l=bm=Hl)>>>0<0?_l+1|0:_l,_l=cm-1140785152|0,(0|(_l=bm>>>0<0?_l+1|0:_l))==(0|$l)&dm>>>0>>0|$l>>>0<_l>>>0?(_l=Zl<<4|Hl>>>28,Hl=Hl<<4|Gl>>>28,134217728==(0|(bm=Gl&=268435455))&1<=a>>>0|134217728>>0?(_l=_l+1073741824|0,(a=Hl+1|0)>>>0<1&&(_l=_l+1|0),$l=a):(_l=_l-((($l=Hl)>>>0<0)+-1073741824|0)|0,a|134217728^bm||((a=$l+(1&$l)|0)>>>0<$l>>>0&&(_l=_l+1|0),$l=a))):(!bm&2147418112==(0|cm)?!(a|Gl):2147418112==(0|cm)&bm>>>0<0|cm>>>0<2147418112)?(_l=2146435072,1140785151==(($l=0)|cm)&4294967295>>0|1140785151>>0||(bm=cm>>>16)>>>(_l=0)<15249||(function(a,Gl,Hl,Cm,Dm,Em){var Hm,Im,Fm=0,Gm=0;64&Em?(Gl=31&(Hl=Em-64|0),Gl=32<=(63&Hl)>>>0?(Hl=0,Dm>>>Gl):(Hl=Dm>>>Gl,((1<>>Gl),Dm=Cm=0):Em&&(Gm=Dm,Fm=31&(Im=64-Em|0),Im=32<=(63&Im)>>>0?(Gm=Cm<>>32-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=0;for(L=Em=L-32|0,Dm=q[28+(a|=0)>>2],q[16+Em>>2]=Dm,Km=q[a+20>>2],q[28+Em>>2]=Cm,q[24+Em>>2]=Gl,Km=(q[20+Em>>2]=Gl=Km-Dm|0)+Cm|0,Lm=2,Gl=16+Em|0;;){a:{if((Jm=(Dm=0)|K(q[a+60>>2],0|Gl,0|Lm,12+Em|0))&&(q[2094]=Jm,Dm=-1),(0|(Dm=Dm?q[12+Em>>2]=-1:q[12+Em>>2]))==(0|Km))Gl=q[a+44>>2],q[a+28>>2]=Gl,q[a+20>>2]=Gl,q[a+16>>2]=Gl+q[a+48>>2],a=Cm;else{if(-1<(0|Dm))break a;q[a+28>>2]=0,q[a+16>>2]=0,q[a+20>>2]=0,q[a>>2]=32|q[a>>2],2!=((a=0)|Lm)&&(a=Cm-q[Gl+4>>2]|0)}return L=32+Em|0,0|a}Jm=q[Gl+4>>2],q[(Gl=(Mm=Jm>>>0>>0)?Gl+8|0:Gl)>>2]=(Jm=Dm-(Mm?Jm:0)|0)+q[Gl>>2],q[Gl+4>>2]=q[Gl+4>>2]-Jm,Km=Km-Dm|0,Lm=Lm-Mm|0}},n[15]=function(a,Gl,Cm,Dm){return M=0},{d:function(){},e:function(){return q[1813]},f:function(){return 83951616},g:function(){return 5},h:function(a,tj){return tj|=0,L=tj=L-16|0,a=(a|=0)?sa(a)?(Y(4,2150,0),0):r[a+4|0]:(q[tj+4>>2]=1444,q[tj>>2]=2267,Y(4,1294,tj),0),L=tj+16|0,0|a},i:function(a,tj){var uj;return tj|=0,L=uj=L-48|0,a=(a|=0)?(a+63&-64)!=(0|a)?(q[36+uj>>2]=1522,q[32+uj>>2]=2284,Y(4,1294,32+uj|0),0):(tj+63&-64)==(0|tj)&&tj?function(a,Tk){var nl,Uk=0,Vk=0,Wk=0,Xk=0,Yk=0,Zk=0,_k=0,$k=0,al=0,bl=0,cl=0,dl=0,el=0,fl=0,gl=0,hl=0,il=0,jl=0,kl=0,ll=0,ml=0;L=Yk=(n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324>>2])>>>0>>0|Vk>>>0<$k>>>0|$k>>>0>>0)break c;if(($k=Wk+$k|0)>>>0>>0|Vk>>>0<$k>>>0)break c;if((Uk=q[Yk+328>>2])>>>0>>0|Vk>>>0>>0|Uk>>>0<$k>>>0)break c;if(($k=Uk+Wk|0)>>>0>>0|Vk>>>0<$k>>>0)break c;if((Uk=q[Yk+332>>2])>>>0>>0|Vk>>>0>>0|Uk>>>0<$k>>>0)break c;if(($k=Uk+Wk|0)>>>0>>0|Vk>>>0<$k>>>0)break c;if((Uk=q[Yk+152>>2])>>>0>>0|Vk>>>0>>0|Uk>>>0<$k>>>0)break c;if((cl=Uk+cl|0)>>>0>>0|Vk>>>0>>0)break c;if((Uk=q[Yk+184>>2])>>>0>>0|Vk>>>0>>0|Uk>>>0>>0)break c;if((cl=Uk+dl|0)>>>0>>0|Vk>>>0>>0)break c;if((Uk=q[Yk+224>>2])>>>0>>0|Vk>>>0>>0|Uk>>>0>>0)break c;if((Uk=Uk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((0|(cl=q[Tk+92>>2]))<0)break c;if((Xk=q[Yk+648>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((cl=(Uk=cl<<2)+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+652>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((cl=Uk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+656>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=Uk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((0|(cl=q[Tk+96>>2]))<0)break c;if((Xk=q[Yk+660>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((cl=(Uk=cl<<2)+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+664>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((cl=Uk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+668>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=Uk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+304>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+316>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+320>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Wk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((0|(Uk=q[Tk+100>>2]))<0)break c;if((Xk=q[Yk+436>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=(Wk=Uk<<2)+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+440>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+444>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Wk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((0|(Uk=q[Tk+104>>2]))<0)break c;if((Xk=q[Yk+448>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=(Wk=Xk)+(Xk=Uk<<2)|0)>>>0>>0|Vk>>>0>>0)break c;if((Wk=q[Yk+452>>2])>>>0>>0|Vk>>>0>>0|Wk>>>0>>0)break c;if((Uk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Wk=q[Yk+456>>2])>>>0>>0|Vk>>>0>>0|Wk>>>0>>0)break c;if((Uk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Wk=q[Yk+460>>2])>>>0>>0|Vk>>>0>>0|Wk>>>0>>0)break c;if((Uk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Wk=q[Yk+464>>2])>>>0>>0|Vk>>>0>>0|Wk>>>0>>0)break c;if((Wk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((0|(Uk=q[Tk+108>>2]))<0)break c;if((Xk=q[Yk+480>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=(Wk=Uk<<2)+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+484>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+488>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Wk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((0|(Uk=q[Tk+112>>2]))<0)break c;if((Xk=q[Yk+504>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=(Wk=Uk<<2)+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+508>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+512>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Wk=Wk+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((0|(Uk=q[Tk+116>>2]))<0)break c;if((Xk=q[Yk+528>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Wk=Xk+(Uk<<2)|0)>>>0>>0|Vk>>>0>>0)break c;if((0|(Uk=q[Tk+120>>2]))<0)break c;if((Xk=q[Yk+532>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk=(Wk=Uk<<2)+Xk|0)>>>0>>0|Vk>>>0>>0)break c;if((Xk=q[Yk+536>>2])>>>0>>0|Vk>>>0>>0|Xk>>>0>>0)break c;if((Uk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]){if((0|Wk)<0|(0|Xk)<(0|Wk))break f;if((0|(_k=q[_k+bl>>2]))<0|(0|Xk)<=(0|_k))break f;if((Wk=Wk+_k|0)>>>31|(0|Xk)<(0|Wk))break f}if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Xk=q[Yk+92>>2];;){if(1>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Xk=q[Yk+96>>2];;){if(1>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Xk=q[Yk+100>>2];;){if((0|(Wk=q[Xk+(Vk<<2)>>2]))<-1|(0|a)<=(0|Wk))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}}else el=Tk+24|0}else el=Tk+24|0,Uk=Tk+48|0;if((a=0)<(0|(Vk=q[Tk+4>>2]))){for(Xk=q[Yk+108>>2];;){if(63>>0)break f;if((0|Vk)==(0|(a=a+1|0)))break}if(Zk=(Xk=q[Tk+48>>2])+-1|0,!(((Vk=0)|(a=q[Tk+4>>2]))<=0)){for(Wk=q[Yk+112>>2];;){if((0|(_k=q[Wk+(Vk<<2)>>2]))<0|(0|Xk)<=(0|_k))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Xk=q[Yk+116>>2];;){if(1>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Xk=q[Yk+120>>2];;){if(1>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Xk=q[Tk>>2],Vk=0,Wk=q[Yk+124>>2];;){if((0|(_k=q[Wk+(Vk<<2)>>2]))<-1|(0|Xk)<=(0|_k))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Xk=q[Yk+128>>2];;){if((0|(Wk=q[Xk+(Vk<<2)>>2]))<-1|(0|a)<=(0|Wk))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Xk=q[Yk+132>>2];;){if(1>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Wk=Tk+8|0,_k=Tk+12|0,bl=q[Yk+136>>2],Vk=0;;){if(1<(dl=q[(cl=Vk<<2)+Xk>>2])>>>0)break f;if((0|(cl=q[bl+cl>>2]))<0|(0|cl)>=q[(dl-1|0?Wk:_k)>>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}}}else Zk=q[Uk>>2]+-1|0;if((a=0)<(0|(Vk=q[Tk+8>>2]))){for(Xk=q[Yk+140>>2];;){if((0|(Wk=q[Xk+(a<<2)>>2]))<0|(0|Zk)<(0|Wk))break f;if((0|Vk)==(0|(a=a+1|0)))break}for(jl=Tk+28|0,Xk=q[Tk+28>>2],bl=q[Yk+148>>2],cl=q[Yk+144>>2],a=0;;){if(Wk=q[(_k=a<<2)+bl>>2]){if((0|Wk)<0|(0|Xk)<(0|Wk))break f;if((0|(_k=q[_k+cl>>2]))<0|(0|Xk)<=(0|_k))break f;if((Wk=Wk+_k|0)>>>31|(0|Xk)<(0|Wk))break f}if((0|Vk)==(0|(a=a+1|0)))break}for(a=0,Wk=q[Yk+156>>2],_k=q[Yk+164>>2],bl=q[Yk+160>>2];;){if((0|(cl=q[(Xk=a<<2)+bl>>2]))<1)break f;if((0|(dl=q[Xk+_k>>2]))<1)break f;if((0|(Xk=q[Wk+Xk>>2]))<1|(0|Xk)!=(0|w(dl+1|0,cl+1|0)))break f;if((0|Vk)==(0|(a=a+1|0)))break}}else jl=Tk+28|0;if((a=0)<(0|(Wk=q[Tk+12>>2]))){for(Vk=q[Yk+172>>2];;){if((0|(Xk=q[Vk+(a<<2)>>2]))<0|(0|Zk)<(0|Xk))break f;if((0|Wk)==(0|(a=a+1|0)))break}for($k=Tk+32|0,Vk=q[Tk+32>>2],Zk=q[Yk+180>>2],bl=q[Yk+176>>2],a=0;;){if(Xk=q[(_k=a<<2)+Zk>>2]){if((0|Xk)<0|(0|Vk)<(0|Xk))break f;if((0|(_k=q[_k+bl>>2]))<0|(0|Vk)<=(0|_k))break f;if((Xk=Xk+_k|0)>>>31|(0|Vk)<(0|Xk))break f}if((0|Wk)==(0|(a=a+1|0)))break}}else $k=Tk+32|0;Xk=Tk+16|0;m:{n:{if(!(((a=0)|(Vk=q[Tk+16>>2]))<=0)){for(Wk=q[Yk+208>>2];;){if(63>>0)break f;if((0|Vk)==(0|(a=a+1|0)))break}if(!(((Vk=0)|(a=q[Xk>>2]))<=0)){for(Wk=q[Uk>>2],_k=q[Yk+212>>2];;){if((0|(Zk=q[_k+(Vk<<2)>>2]))<0|(0|Wk)<=(0|Zk))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(ll=Tk+36|0,Wk=q[Tk+36>>2],bl=q[Yk+220>>2],cl=q[Yk+216>>2],Vk=0;;){if(_k=q[(Zk=Vk<<2)+bl>>2]){if((0|_k)<0|(0|Wk)<(0|_k))break f;if((0|(Zk=q[Zk+cl>>2]))<0|(0|Wk)<=(0|Zk))break f;if((_k=_k+Zk|0)>>>31|(0|Wk)<(0|_k))break f}if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Wk=q[Yk+228>>2];;){if(1>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Wk=q[Yk+232>>2];;){if(1>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Wk=q[Tk>>2],Vk=0,_k=q[Yk+236>>2];;){if((0|(Zk=q[_k+(Vk<<2)>>2]))<-1|(0|Wk)<=(0|Zk))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Wk=q[Tk+4>>2],Vk=0,_k=q[Yk+240>>2];;){if((0|(Zk=q[_k+(Vk<<2)>>2]))<-1|(0|Wk)<=(0|Zk))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Wk=q[Yk+244>>2],Vk=0;;){if(q[Wk+(Vk<<2)>>2]<0)break f;if((0|a)==(0|(Vk=Vk+1|0)))break}break n}}_k=Tk+68|0,ll=Tk+36|0;break m}for(Wk=q[Yk+252>>2],Vk=0;;){if(q[Wk+(Vk<<2)>>2]<0)break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(_k=q[Tk+60>>2],Vk=0,Zk=q[Yk+256>>2];;){if((bl=q[(bl=Vk<<2)+Zk>>2]+(q[Wk+bl>>2]<<1)|0)>>>31|(0|_k)<(0|bl))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Wk=q[Tk+64>>2],bl=q[Yk+264>>2],cl=q[Yk+260>>2],Vk=0;;){if(_k=q[(Zk=Vk<<2)+bl>>2]){if((0|_k)<0|(0|Wk)<(0|_k))break f;if((0|(Zk=q[Zk+cl>>2]))<0|(0|Wk)<=(0|Zk))break f;if((_k=_k+Zk|0)>>>31|(0|Wk)<(0|_k))break f}if((0|a)==(0|(Vk=Vk+1|0)))break}for(_k=Tk+68|0,Wk=q[Tk+68>>2],cl=q[Yk+272>>2],dl=q[Yk+268>>2],Vk=0;;){if(Zk=q[(bl=Vk<<2)+cl>>2]){if((0|Zk)<0|(0|Wk)<(0|Zk))break f;if((0|(bl=q[bl+dl>>2]))<0|(0|Wk)<=(0|bl))break f;if((Zk=Zk+bl|0)>>>31|(0|Wk)<(0|Zk))break f}if((0|a)==(0|(Vk=Vk+1|0)))break}}p:{q:{if(!(((a=0)|(Vk=q[Tk+20>>2]))<=0)){for(Wk=q[Yk+280>>2];;){if(63>>0)break f;if((0|Vk)==(0|(a=a+1|0)))break}if(!(((a=0)|(Vk=q[Tk+20>>2]))<=0)){for(Wk=q[Yk+296>>2];;){if(1>2])break f;if((0|Vk)==(0|(a=a+1|0)))break}for(Wk=q[Yk+300>>2],a=0;;){if(q[Wk+(a<<2)>>2]<0)break f;if((0|Vk)==(0|(a=a+1|0)))break}break q}}a=q[Tk+52>>2];break p}for(a=q[Tk+52>>2],cl=q[Yk+312>>2],dl=q[Yk+308>>2],Zk=0;;){if(Wk=q[(bl=Zk<<2)+cl>>2]){if((0|Wk)<0|(0|a)<(0|Wk))break f;if((0|(bl=q[bl+dl>>2]))<0|(0|a)<=(0|bl))break f;if((Wk=Wk+bl|0)>>>31|(0|a)<(0|Wk))break f}if((0|Vk)==(0|(Zk=Zk+1|0)))break}}if(Wk=q[Tk+40>>2],(Vk=0)<(0|(Zk=q[Tk+8>>2])))for(bl=q[Yk+344>>2],cl=q[Yk+156>>2];;){if((dl=q[(dl=Vk<<2)+bl>>2]+(q[cl+dl>>2]<<1)|0)>>>31|(0|Wk)<(0|dl))break f;if((0|Zk)==(0|(Vk=Vk+1|0)))break}if((Vk=0)<(0|(Zk=q[$k>>2]))){for(bl=q[Yk+376>>2];;){if(1>2])break f;if((0|Zk)==(0|(Vk=Vk+1|0)))break}for(Vk=0,bl=q[Yk+380>>2];;){if(1>2])break f;if((0|Zk)==(0|(Vk=Vk+1|0)))break}}if((Vk=0)<(0|(Zk=q[Xk>>2])))for(bl=q[Yk+400>>2],cl=q[Yk+252>>2];;){if((dl=q[(dl=Vk<<2)+bl>>2]+(q[cl+dl>>2]<<1)|0)>>>31|(0|Wk)<(0|dl))break f;if((0|Zk)==(0|(Vk=Vk+1|0)))break}if((Vk=0)<(0|(Wk=q[Tk+44>>2])))for(bl=q[Yk+424>>2];;){if((0|(cl=q[bl+(Vk<<2)>>2]))<0|(0|a)<=(0|cl))break f;if((0|Wk)==(0|(Vk=Vk+1|0)))break}if(1<=(0|(cl=q[Uk>>2])))for(Vk=0,dl=q[Yk+432>>2],al=q[Yk+428>>2];;){if(Uk=q[(bl=Vk<<2)+dl>>2]){if((0|Uk)<0|(0|Wk)<(0|Uk))break f;if((0|(bl=q[al+bl>>2]))<0|(0|Wk)<=(0|bl))break f;if((Uk=Uk+bl|0)>>>31|(0|Wk)<(0|Uk))break f}if((0|cl)==(0|(Vk=Vk+1|0)))break}if(1<=(0|a))for(Wk=q[Tk+56>>2],Vk=0,cl=q[Yk+420>>2],dl=q[Yk+416>>2];;){if(Uk=q[(bl=Vk<<2)+cl>>2]){if((0|Uk)<0|(0|Wk)<(0|Uk))break f;if((0|(bl=q[bl+dl>>2]))<0|(0|Wk)<=(0|bl))break f;if((Uk=Uk+bl|0)>>>31|(0|Wk)<(0|Uk))break f}if((0|(Vk=Vk+1|0))==(0|a))break}if((a=0)<(0|(Vk=q[_k>>2])))for(Wk=q[Yk+564>>2];;){if((0|(_k=q[Wk+(a<<2)>>2]))<-1|(0|Zk)<=(0|_k))break f;if((0|Vk)==(0|(a=a+1|0)))break}if(a=q[Tk+76>>2],1<=(0|(_k=q[Tk+72>>2])))for(Vk=0,Zk=q[Yk+572>>2],bl=q[Yk+568>>2];;){if(Wk=q[(Uk=Vk<<2)+Zk>>2]){if((0|Wk)<0|(0|a)<(0|Wk))break f;if((0|(Uk=q[Uk+bl>>2]))<0|(0|a)<=(0|Uk))break f;if((Wk=Uk+Wk|0)>>>31|(0|a)<(0|Wk))break f}if((0|_k)==(0|(Vk=Vk+1|0)))break}if((Vk=0)<(0|a)){for(Wk=q[Yk+588>>2];;){if(1>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Uk=q[Yk+592>>2],Vk=0;;){if(1<(bl=q[(Zk=Vk<<2)+Wk>>2])>>>0)break f;if((0|(Zk=q[Uk+Zk>>2]))<0|(0|Zk)>=q[(bl-1|0?Xk:Tk)>>2])break f;if((0|a)==(0|(Vk=Vk+1|0)))break}for(Vk=0,Wk=q[Yk+596>>2];;){if((0|(Uk=q[Wk+(Vk<<2)>>2]))<-1|(0|_k)<=(0|Uk))break f;if((0|a)==(0|(Vk=Vk+1|0)))break}}s:{if(!(((a=0)|(Zk=q[Tk+80>>2]))<=0)){for(Vk=q[Yk+604>>2];;){if(63>>0)break f;if((0|Zk)==(0|(a=a+1|0)))break}if(!(((a=0)|(Zk=q[Tk+80>>2]))<=0)){for(Vk=q[Tk+48>>2],Wk=q[Yk+608>>2];;){if((0|(_k=q[Wk+(a<<2)>>2]))<0|(0|Vk)<=(0|_k))break f;if((0|Zk)==(0|(a=a+1|0)))break}for(cl=q[Tk+88>>2],_k=q[Yk+616>>2],Uk=q[Yk+612>>2],a=0;;){if(Vk=q[(Wk=a<<2)+_k>>2]){if((0|Vk)<0|(0|cl)<(0|Vk))break f;if((0|(Wk=q[Uk+Wk>>2]))<0|(0|cl)<=(0|Wk))break f;if((Vk=Vk+Wk|0)>>>31|(0|cl)<(0|Vk))break f}if((0|Zk)==(0|(a=a+1|0)))break}for(Xk=q[Xk>>2],_k=q[Yk+620>>2],a=0;;){if((0|(Vk=q[_k+(a<<2)>>2]))<0|(0|Xk)<=(0|Vk))break f;if((0|Zk)==(0|(a=a+1|0)))break}for(Uk=q[Yk+624>>2],a=0;;){if((0|(Vk=q[Uk+(a<<2)>>2]))<0|(0|Xk)<=(0|Vk))break f;if((0|Zk)==(0|(a=a+1|0)))break}for(Vk=q[Tk+84>>2],bl=q[Yk+632>>2],dl=q[Yk+628>>2],a=0;;){if(Wk=q[(al=a<<2)+bl>>2]){if((0|Wk)<0|(0|Vk)<(0|Wk))break f;if((0|(al=q[al+dl>>2]))<0|(0|Vk)<=(0|al))break f;if((Wk=Wk+al|0)>>>31|(0|Vk)<(0|Wk))break f}if((0|Zk)==(0|(a=a+1|0)))break}for(fl=q[Yk+640>>2],Vk=q[Yk+252>>2],Wk=0;;){if(0<(0|(hl=q[(a=Wk<<2)+bl>>2])))for(al=fl+(q[a+dl>>2]<<1)|0,ml=q[Vk+(q[a+Uk>>2]<<2)>>2],il=q[Vk+(q[a+_k>>2]<<2)>>2],a=0;;){if((0|ml)<=s[al+(2|(kl=a<<1))>>1]|(0|il)<=s[al+kl>>1])break f;if(!((0|(a=a+2|0))<(0|hl)))break}if((0|Zk)==(0|(Wk=Wk+1|0)))break}break s}}Xk=q[Tk+16>>2],cl=q[Tk+88>>2]}if(!((255&gl)>>>0<2)){if((a=0)<(0|(bl=q[Tk+8>>2])))for(Vk=q[Yk+168>>2];;){if(1>2])break f;if((0|bl)==(0|(a=a+1|0)))break}if(!((255&gl)>>>0<4)){if(_k=q[Tk+56>>2],1<=(0|(dl=q[Tk+20>>2])))for(Uk=q[Yk+332>>2],al=q[Yk+328>>2],a=0;;){if(Vk=q[(Wk=a<<2)+Uk>>2]){if((0|Vk)<0|(0|_k)<(0|Vk))break f;if((0|(Wk=q[Wk+al>>2]))<0|(0|_k)<=(0|Wk))break f;if((Vk=Vk+Wk|0)>>>31|(0|_k)<(0|Vk))break f}if((0|dl)==(0|(a=a+1|0)))break}if((0|(a=q[Tk+92>>2]))!=q[Tk+96>>2])break f;if(1<=(0|bl))for(al=q[Yk+152>>2],Vk=0,fl=q[Yk+148>>2];;){if(Wk=q[(Uk=Vk<<2)+fl>>2]){if((0|Wk)<0|(0|a)<(0|Wk))break f;if((0|(Uk=q[Uk+al>>2]))<0|(0|a)<=(0|Uk))break f;if((Wk=Uk+Wk|0)>>>31|(0|a)<(0|Wk))break f}if((0|bl)==(0|(Vk=Vk+1|0)))break}if(1<=(0|(ml=q[Tk+12>>2])))for(al=q[Yk+184>>2],Vk=0,fl=q[Yk+180>>2];;){if(Wk=q[(Uk=Vk<<2)+fl>>2]){if((0|Wk)<0|(0|a)<(0|Wk))break f;if((0|(Uk=q[Uk+al>>2]))<0|(0|a)<=(0|Uk))break f;if((Wk=Uk+Wk|0)>>>31|(0|a)<(0|Wk))break f}if((0|ml)==(0|(Vk=Vk+1|0)))break}if(1<=(0|Xk))for(al=q[Yk+224>>2],Vk=0,fl=q[Yk+220>>2];;){if(Wk=q[(Uk=Vk<<2)+fl>>2]){if((0|Wk)<0|(0|a)<(0|Wk))break f;if((0|(Uk=q[Uk+al>>2]))<0|(0|a)<=(0|Uk))break f;if((Wk=Uk+Wk|0)>>>31|(0|a)<(0|Wk))break f}if((0|Xk)==(0|(Vk=Vk+1|0)))break}if((Vk=0)<(0|dl)){for(Wk=q[Yk+304>>2];;){if(1>2])break f;if((0|dl)==(0|(Vk=Vk+1|0)))break}for(Wk=q[Tk+100>>2],fl=q[Yk+320>>2],hl=q[Yk+316>>2],Vk=0;;){if(Uk=q[(al=Vk<<2)+fl>>2]){if((0|Uk)<0|(0|Wk)<(0|Uk))break f;if((0|(al=q[al+hl>>2]))<0|(0|Wk)<=(0|al))break f;if((Uk=Uk+al|0)>>>31|(0|Wk)<(0|Uk))break f}if((0|dl)==(0|(Vk=Vk+1|0)))break}}else Wk=q[Tk+100>>2];if(1<=(0|Wk)){for(al=q[Yk+440>>2],Vk=0,hl=q[Yk+436>>2];;){if(Uk=q[(fl=Vk<<2)+al>>2]){if((0|Uk)<0|(0|_k)<(0|Uk))break f;if((0|(fl=q[fl+hl>>2]))<0|(0|_k)<=(0|fl))break f;if((Uk=Uk+fl|0)>>>31|(0|_k)<(0|Uk))break f}if((0|Wk)==(0|(Vk=Vk+1|0)))break}for(_k=q[Yk+444>>2],Vk=0;;){if((0|(fl=q[(Uk=Vk<<2)+_k>>2]))<0|(0|fl)>=q[Uk+al>>2])break f;if((0|Wk)==(0|(Vk=Vk+1|0)))break}}if((_k=0)<(0|(Vk=q[Tk+104>>2]))){for(Uk=q[Yk+448>>2];;){if((0|(al=q[Uk+(_k<<2)>>2]))<0|(0|Wk)<=(0|al))break f;if((0|Vk)==(0|(_k=_k+1|0)))break}for(Uk=q[Tk+116>>2],fl=q[Yk+464>>2],hl=q[Yk+460>>2],Wk=0;;){if(_k=q[(al=Wk<<2)+fl>>2]){if((0|_k)<0|(0|Uk)<(0|_k))break f;if((0|(al=q[al+hl>>2]))<0|(0|Uk)<=(0|al))break f;if((_k=_k+al|0)>>>31|(0|Uk)<(0|_k))break f}if((0|Vk)==(0|(Wk=Wk+1|0)))break}}else Uk=q[Tk+116>>2];if((Wk=0)<(0|(al=q[Tk+108>>2]))){for(_k=q[Yk+480>>2];;){if((0|(fl=q[_k+(Wk<<2)>>2]))<0|(0|bl)<=(0|fl))break f;if((0|al)==(0|(Wk=Wk+1|0)))break}for(fl=q[Yk+488>>2],il=q[Yk+484>>2],Wk=0;;){if(_k=q[(bl=Wk<<2)+fl>>2]){if((0|_k)<0|(0|Vk)<(0|_k))break f;if((0|(bl=q[bl+il>>2]))<0|(0|Vk)<=(0|bl))break f;if((_k=_k+bl|0)>>>31|(0|Vk)<(0|_k))break f}if((0|al)==(0|(Wk=Wk+1|0)))break}for(fl=q[jl>>2],Wk=q[Yk+456>>2],bl=q[Yk+452>>2],_k=0;;){if(kl=q[il+(_k<<2)>>2]<<2,hl=q[kl+Wk>>2]){if((0|hl)<0|(0|fl)<(0|hl))break f;if((0|(kl=q[bl+kl>>2]))<0|(0|fl)<=(0|kl))break f;if((0|(hl=hl+kl|0))<0|(0|fl)<(0|hl))break f}if((0|al)==(0|(_k=_k+1|0)))break}}else Wk=q[Yk+456>>2],bl=q[Yk+452>>2];if((_k=0)<(0|(al=q[Tk+112>>2]))){for(fl=q[Yk+504>>2];;){if((0|(hl=q[fl+(_k<<2)>>2]))<0|(0|Xk)<=(0|hl))break f;if((0|al)==(0|(_k=_k+1|0)))break}for(il=q[Yk+512>>2],hl=q[Yk+508>>2],Xk=0;;){if(_k=q[(fl=Xk<<2)+il>>2]){if((0|_k)<0|(0|Vk)<(0|_k))break f;if((0|(fl=q[fl+hl>>2]))<0|(0|Vk)<=(0|fl))break f;if((_k=_k+fl|0)>>>31|(0|Vk)<(0|_k))break f}if((0|al)==(0|(Xk=Xk+1|0)))break}for(_k=q[ll>>2],Xk=0;;){if(il=q[hl+(Xk<<2)>>2]<<2,fl=q[il+Wk>>2]){if((0|fl)<0|(0|_k)<(0|fl))break f;if((0|(il=q[bl+il>>2]))<0|(0|_k)<=(0|il))break f;if((0|(fl=fl+il|0))<0|(0|_k)<(0|fl))break f}if((0|al)==(0|(Xk=Xk+1|0)))break}}if(_k=q[Tk+120>>2],(Xk=0)<(0|Uk))for(al=q[Yk+528>>2];;){if((0|(fl=q[al+(Xk<<2)>>2]))<0|(0|_k)<=(0|fl))break f;if((0|(Xk=Xk+1|0))==(0|Uk))break}if((Xk=0)<(0|_k)){for(Uk=q[Yk+532>>2];;){if((0|(al=q[Uk+(Xk<<2)>>2]))<-1|(0|dl)<=(0|al))break f;if((0|_k)==(0|(Xk=Xk+1|0)))break}for(Uk=q[Tk+124>>2],fl=q[Yk+540>>2],hl=q[Yk+536>>2],Xk=0;;){if(dl=q[(al=Xk<<2)+fl>>2]){if((0|dl)<0|(0|Uk)<(0|dl))break f;if((0|(al=q[al+hl>>2]))<0|(0|Uk)<=(0|al))break f;if((dl=al+dl|0)>>>31|(0|Uk)<(0|dl))break f}if((0|_k)==(0|(Xk=Xk+1|0)))break}}if(!((255&gl)>>>0<5)){if((Xk=0)<(0|(gl=q[jl>>2]))){for(_k=q[Yk+348>>2];;){if((0|(Uk=q[_k+(Xk<<2)>>2]))<0|(0|a)<(0|Uk))break f;if((0|gl)==(0|(Xk=Xk+1|0)))break}for(_k=q[Yk+352>>2],Xk=0;;){if((0|(Uk=q[_k+(Xk<<2)>>2]))<0|(0|a)<(0|Uk))break f;if((0|gl)==(0|(Xk=Xk+1|0)))break}}if((gl=0)<(0|(Xk=q[$k>>2]))){for(_k=q[Yk+384>>2];;){if((0|(Uk=q[_k+(gl<<2)>>2]))<0|(0|a)<(0|Uk))break f;if((0|Xk)==(0|(gl=gl+1|0)))break}for(_k=q[Yk+388>>2],gl=0;;){if((0|(Uk=q[_k+(gl<<2)>>2]))<0|(0|a)<(0|Uk))break f;if((0|Xk)==(0|(gl=gl+1|0)))break}}if((gl=0)<(0|(_k=q[ll>>2]))){for(Uk=q[Yk+404>>2];;){if((0|(dl=q[Uk+(gl<<2)>>2]))<0|(0|a)<(0|dl))break f;if((0|_k)==(0|(gl=gl+1|0)))break}for(Uk=q[Yk+408>>2],gl=0;;){if((0|(dl=q[Uk+(gl<<2)>>2]))<0|(0|a)<(0|dl))break f;if((0|_k)==(0|(gl=gl+1|0)))break}}if((a=0)<(0|(gl=q[Tk+128>>2]))){for(_k=q[Tk>>2],Uk=q[Yk+468>>2];;){if((0|(dl=q[Uk+(a<<2)>>2]))<0|(0|_k)<=(0|dl))break f;if((0|gl)==(0|(a=a+1|0)))break}for(jl=q[Yk+476>>2],dl=q[Yk+472>>2],a=0;;){if(_k=q[(Uk=a<<2)+jl>>2]){if((0|_k)<0|(0|Vk)<(0|_k))break f;if((0|(Uk=q[Uk+dl>>2]))<0|(0|Vk)<=(0|Uk))break f;if((_k=Uk+_k|0)>>>31|(0|Vk)<(0|_k))break f}if((0|gl)==(0|(a=a+1|0)))break}for(_k=q[el>>2],a=0;;){if(el=q[dl+(a<<2)>>2]<<2,Uk=q[el+Wk>>2]){if((0|Uk)<0|(0|_k)<(0|Uk))break f;if((0|(el=q[bl+el>>2]))<0|(0|_k)<=(0|el))break f;if((0|(Uk=Uk+el|0))<0|(0|_k)<(0|Uk))break f}if((0|gl)==(0|(a=a+1|0)))break}}if((a=0)<(0|(gl=q[Tk+132>>2]))){for(_k=q[Yk+492>>2];;){if((0|(Uk=q[_k+(a<<2)>>2]))<0|(0|ml)<=(0|Uk))break f;if((0|gl)==(0|(a=a+1|0)))break}for(el=q[Yk+500>>2],Uk=q[Yk+496>>2],a=0;;){if(_k=q[(dl=a<<2)+el>>2]){if((0|_k)<0|(0|Vk)<(0|_k))break f;if((0|(dl=q[Uk+dl>>2]))<0|(0|Vk)<=(0|dl))break f;if((_k=_k+dl|0)>>>31|(0|Vk)<(0|_k))break f}if((0|gl)==(0|(a=a+1|0)))break}for(a=0;;){if(dl=q[Uk+(a<<2)>>2]<<2,_k=q[dl+Wk>>2]){if((0|_k)<0|(0|Xk)<(0|_k))break f;if((0|(dl=q[bl+dl>>2]))<0|(0|Xk)<=(0|dl))break f;if((0|(_k=_k+dl|0))<0|(0|Xk)<(0|_k))break f}if((0|gl)==(0|(a=a+1|0)))break}}if(!(((a=0)|(Tk=q[Tk+136>>2]))<=0)){for(Xk=q[Yk+516>>2];;){if((0|(gl=q[Xk+(a<<2)>>2]))<0|(0|Zk)<=(0|gl))break f;if((0|Tk)==(0|(a=a+1|0)))break}for(_k=q[Yk+524>>2],Xk=q[Yk+520>>2],a=0;;){if(Yk=q[(gl=a<<2)+_k>>2]){if((0|Yk)<0|(0|Vk)<(0|Yk))break f;if((0|(gl=q[Xk+gl>>2]))<0|(0|Vk)<=(0|gl))break f;if((Yk=Yk+gl|0)>>>31|(0|Vk)<(0|Yk))break f}if((0|Tk)==(0|(a=a+1|0)))break}for(a=0;;){if(Yk=q[Xk+(a<<2)>>2]<<2,Vk=q[Yk+Wk>>2]){if((0|Vk)<0|(0|cl)<(0|Vk))break f;if((0|(Yk=q[Yk+bl>>2]))<0|(0|cl)<=(0|Yk))break f;if((0|(Vk=Vk+Yk|0))<0|(0|cl)<(0|Vk))break f}if((0|Tk)==(0|(a=a+1|0)))break}}}}}return L=nl,1}return Y(4,1846,0),L=nl,0}q[Yk+52>>2]=Vk,q[Yk+48>>2]=5,Y(4,1640,Yk+48|0)}else q[Yk+32>>2]=Vk,Y(4,1554,Yk+32|0);return L=nl,0}(a,tj):(q[20+uj>>2]=1621,q[16+uj>>2]=2284,Y(4,1294,16+uj|0),0):(q[4+uj>>2]=1444,q[uj>>2]=2284,Y(4,1294,uj),0),L=48+uj|0,0|a},j:function(a){q[1813]=a|=0},k:function(a,cj){var dj;return cj|=0,L=dj=L-48|0,a=(a|=0)?(a+63&-64)!=(0|a)?(q[36+dj>>2]=1522,q[32+dj>>2]=2305,Y(4,1294,32+dj|0),0):(cj+63&-64)==(0|cj)&&cj?function(a){var Ok,Rk,Sk,Rh,Ik=0,Jk=0,Kk=0,Lk=0,Mk=0,Nk=0,Pk=0,Qk=0;q[24+(L=Ok=L-32|0)>>2]=0,q[16+Ok>>2]=5,q[20+Ok>>2]=1,Ka(16+(L=Rh=L-272|0)|0,2227,q[12+Rh>>2]=16+Ok|0),function(a){var Dc;q[(L=Dc=L-16|0)>>2]=a,function(a,Gl){var Hl;q[12+(L=Hl=L-16|0)>>2]=Gl,Ia(a,1432,Gl,0,0),L=16+Hl|0}(q[978],Dc),L=16+Dc|0}(16+Rh|0),L=272+Rh|0;a:{if(sa(a))Y(4,1932,0);else{if(!(6<=(Kk=r[a+4|0])>>>0)){if(1!=(0|!r[a+5|0])?(da(a+4|0,1),X(a- -64|0,4,160),na(a,a+704|(o[a+5|0]=0)),ya(a)):na(a,a+704|0),r[7256]||(q[1815]=6,o[7256]=1,q[1816]=7,q[1817]=8,q[1818]=9),Jk=q[a+704>>2],1<=(0|(Kk=q[Jk+16>>2]))){for(Qk=(Lk=q[a+912>>2])+(Kk<<2)|0,Mk=q[a+908>>2];;){Pk=q[a+1204>>2]+(q[Mk>>2]<<2)|0;d:if(!(((Jk=0)|(Ik=(Kk=q[Lk>>2])+-1|0))<1))e:for(;;){for(;;){if(q[(Nk=Pk+(Jk<<2)|0)>>2]<=-1){if(function(a,Tk,ol){var pl=0,ql=0;a:if((0|a)!=(0|Tk)){if(!(a>>>0>>0&&Tk>>>0<(ql=a+ol|0)>>>0))return $(a,Tk,ol);if(pl=3&(a^Tk),a>>>0>>0){if(!pl){if(3&a)for(;;){if(!ol)break a;if(o[0|a]=r[0|Tk],Tk=Tk+1|0,ol=ol+-1|0,!(3&(a=a+1|0)))break}if(!(ol>>>0<=3)){for(pl=ol;q[a>>2]=q[Tk>>2],Tk=Tk+4|0,a=a+4|0,3<(pl=pl+-4|0)>>>0;);ol&=3}}if(ol)for(;o[0|a]=r[0|Tk],a=a+1|0,Tk=Tk+1|0,ol=ol+-1|0;);}else{if(!pl){if(3&ql)for(;;){if(!ol)break a;if(o[0|(pl=(ol=ol+-1|0)+a|0)]=r[Tk+ol|0],!(3&pl))break}if(!(ol>>>0<=3))for(;q[(ol=ol+-4|0)+a>>2]=q[Tk+ol>>2],3
      >>0;);}if(ol)for(;o[(ol=ol+-1|0)+a|0]=r[Tk+ol|0],ol;);}}}(Nk,Nk+4|0,(-1^Jk)+Kk<<2),(0|Jk)<(0|(Ik=(Kk=Ik)+-1|0)))continue e;break d}if(!((0|(Jk=Jk+1|0))<(0|Ik)))break}break}if(Jk=Lk,0<(0|Kk)&&(Kk=q[Pk+(Ik<<2)>>2]<0?Ik:Kk),q[Jk>>2]=Kk,Mk=Mk+4|0,!((Lk=Lk+4|0)>>>0>>0))break}Jk=q[a+704>>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(0|(Nk=q[(Jk=Ik<<2)+Kk>>2])))for(Nk=(Jk=Pk+(q[Jk+Mk>>2]<<2)|0)+(Nk<<3)|0,Jk=Jk+4|0;u[Jk>>2]=x(1)-u[Jk>>2],(Jk=Jk+8|0)>>>0>>0;);if((0|Lk)==(0|(Ik=Ik+1|0)))break}break a}q[4+Ok>>2]=Kk,q[Ok>>2]=5,Y(4,2023,Ok)}a=0}return L=32+Ok|0,a}(a):(q[20+dj>>2]=1621,q[16+dj>>2]=2305,Y(4,1294,16+dj|0),0):(q[4+dj>>2]=1444,q[dj>>2]=2305,Y(4,1294,dj),0),L=48+dj|0,0|a},l:function(a,cj,dj,ej){var fj;cj|=0,dj|=0,ej|=0,L=fj=L+-64|0,(a|=0)?cj?dj?ej?(a=q[q[a>>2]+708>>2],q[cj>>2]=q[a+12>>2],q[cj+4>>2]=q[a+16>>2],q[dj>>2]=q[a+4>>2],q[dj+4>>2]=q[a+8>>2],q[ej>>2]=q[a>>2]):(q[52+fj>>2]=1995,q[48+fj>>2]=2325,Y(4,1294,48+fj|0)):(q[36+fj>>2]=1903,q[32+fj>>2]=2325,Y(4,1294,32+fj|0)):(q[20+fj>>2]=1819,q[16+fj>>2]=2325,Y(4,1294,16+fj|0)):(q[4+fj>>2]=1740,q[fj>>2]=2325,Y(4,1294,fj)),L=64+fj|0},m:xa,n:wa,o:function(a){var bj;L=bj=L-16|0,(a|=0)?ua(a):(q[4+bj>>2]=1740,q[bj>>2]=2387,Y(4,1294,bj)),L=16+bj|0},p:function(a){var aj;return L=aj=L-16|0,a=(a|=0)?q[a+540>>2]:(q[4+aj>>2]=1740,q[aj>>2]=2402,Y(4,1294,aj),-1),L=16+aj|0,0|a},q:function(a){var $i;return L=$i=L-16|0,a=(a|=0)?q[q[a>>2]+916>>2]:(q[4+$i>>2]=1740,q[$i>>2]=2423,Y(4,1294,$i),0),L=16+$i|0,0|a},r:function(a){var _i;return L=_i=L-16|0,a=(a|=0)?q[a+548>>2]:(q[4+_i>>2]=1740,q[_i>>2]=2442,Y(4,1294,_i),0),L=16+_i|0,0|a},s:function(a){var Zi;return L=Zi=L-16|0,a=(a|=0)?q[q[a>>2]+928>>2]:(q[4+Zi>>2]=1740,q[Zi>>2]=2463,Y(4,1294,Zi),0),L=16+Zi|0,0|a},t:function(a){var Yi;return L=Yi=L-16|0,a=(a|=0)?q[q[a>>2]+924>>2]:(q[4+Yi>>2]=1740,q[Yi>>2]=2492,Y(4,1294,Yi),0),L=16+Yi|0,0|a},u:function(a){var Xi;return L=Xi=L-16|0,a=(a|=0)?q[q[a>>2]+932>>2]:(q[4+Xi>>2]=1740,q[Xi>>2]=2521,Y(4,1294,Xi),0),L=16+Xi|0,0|a},v:function(a){var Wi;return L=Wi=L-16|0,a=(a|=0)?q[a+552>>2]:(q[4+Wi>>2]=1740,q[Wi>>2]=2550,Y(4,1294,Wi),0),L=16+Wi|0,0|a},w:function(a){var Vi;return L=Vi=L-16|0,a=(a|=0)?q[q[a>>2]+936>>2]:(q[4+Vi>>2]=1740,q[Vi>>2]=2572,Y(4,1294,Vi),0),L=16+Vi|0,0|a},x:function(a){var Ui;return L=Ui=L-16|0,a=(a|=0)?q[a+4>>2]:(q[4+Ui>>2]=1740,q[Ui>>2]=2595,Y(4,1294,Ui),-1),L=16+Ui|0,0|a},y:function(a){var Ti;return L=Ti=L-16|0,a=(a|=0)?q[q[a>>2]+712>>2]:(q[4+Ti>>2]=1740,q[Ti>>2]=2611,Y(4,1294,Ti),0),L=16+Ti|0,0|a},z:function(a){var Si;return L=Si=L-16|0,a=(a|=0)?q[a+52>>2]:(q[4+Si>>2]=1740,q[Si>>2]=2625,Y(4,1294,Si),0),L=16+Si|0,0|a},A:function(a){var Ri;return L=Ri=L-16|0,a=(a|=0)?q[q[a>>2]+740>>2]:(q[4+Ri>>2]=1740,q[Ri>>2]=2645,Y(4,1294,Ri),0),L=16+Ri|0,0|a},B:function(a){var Qi;return L=Qi=L-16|0,a=(a|=0)?q[a+332>>2]:(q[4+Qi>>2]=1740,q[Qi>>2]=2673,Y(4,1294,Qi),-1),L=16+Qi|0,0|a},C:function(a){var Pi;return L=Pi=L-16|0,a=(a|=0)?q[q[a>>2]+832>>2]:(q[4+Pi>>2]=1740,q[Pi>>2]=2693,Y(4,1294,Pi),0),L=16+Pi|0,0|a},D:function(a){var Oi;return L=Oi=L-16|0,a=(a|=0)?q[q[a>>2]+888>>2]:(q[4+Oi>>2]=1740,q[Oi>>2]=2711,Y(4,1294,Oi),0),L=16+Oi|0,0|a},E:function(a){var Ni;return L=Ni=L-16|0,a=(a|=0)?q[a+432>>2]:(q[4+Ni>>2]=1740,q[Ni>>2]=2739,Y(4,1294,Ni),0),L=16+Ni|0,0|a},F:function(a){var Mi;return L=Mi=L-16|0,a=(a|=0)?q[q[a>>2]+884>>2]:(q[4+Mi>>2]=1740,q[Mi>>2]=2766,Y(4,1294,Mi),0),L=16+Mi|0,0|a},G:function(a){var Li;return L=Li=L-16|0,a=(a|=0)?q[a+440>>2]:(q[4+Li>>2]=1740,q[Li>>2]=2795,Y(4,1294,Li),0),L=16+Li|0,0|a},H:function(a){var Ki;return L=Ki=L-16|0,a=(a|=0)?q[a+436>>2]:(q[4+Ki>>2]=1740,q[Ki>>2]=2820,Y(4,1294,Ki),0),L=16+Ki|0,0|a},I:function(a){var Ji;return L=Ji=L-16|0,a=(a|=0)?q[a+448>>2]:(q[4+Ji>>2]=1740,q[Ji>>2]=2847,Y(4,1294,Ji),0),L=16+Ji|0,0|a},J:function(a){var Ii;return L=Ii=L-16|0,a=(a|=0)?q[q[a>>2]+912>>2]:(q[4+Ii>>2]=1740,q[Ii>>2]=2871,Y(4,1294,Ii),0),L=16+Ii|0,0|a},K:function(a){var Hi;return L=Hi=L-16|0,a=(a|=0)?q[q[a>>2]+844>>2]:(q[4+Hi>>2]=1740,q[Hi>>2]=2896,Y(4,1294,Hi),0),L=16+Hi|0,0|a},L:function(a){var Gi;return L=Gi=L-16|0,a=(a|=0)?q[q[a>>2]+892>>2]:(q[4+Gi>>2]=1740,q[Gi>>2]=2916,Y(4,1294,Gi),0),L=16+Gi|0,0|a},M:function(a){var qi;return L=qi=L-16|0,a=(a|=0)?q[a+444>>2]:(q[4+qi>>2]=1740,q[qi>>2]=2943,Y(4,1294,qi),0),L=16+qi|0,0|a},N:function(a){var pi;return L=pi=L-16|0,a=(a|=0)?q[q[a>>2]+836>>2]:(q[4+pi>>2]=1740,q[pi>>2]=2973,Y(4,1294,pi),0),L=16+pi|0,0|a},O:function(a){var oi;return L=oi=L-16|0,a=(a|=0)?q[q[a>>2]+904>>2]:(q[4+oi>>2]=1740,q[oi>>2]=2997,Y(4,1294,oi),0),L=16+oi|0,0|a},P:function(a){var ni;return L=ni=L-16|0,a=(a|=0)?q[q[a>>2]+840>>2]:(q[4+ni>>2]=1740,q[ni>>2]=3023,Y(4,1294,ni),0),L=16+ni|0,0|a},Q:function(a){var mi;return L=mi=L-16|0,a=(a|=0)?q[a+452>>2]:(q[4+mi>>2]=1740,q[mi>>2]=3045,Y(4,1294,mi),0),L=16+mi|0,0|a},R:function(a){var li;return L=li=L-16|0,a=(a|=0)?q[a+456>>2]:(q[4+li>>2]=1740,q[li>>2]=3074,Y(4,1294,li),0),L=16+li|0,0|a},S:function(a){var ki;return L=ki=L-16|0,a=(a|=0)?q[q[a>>2]+876>>2]:(q[4+ki>>2]=1740,q[ki>>2]=3101,Y(4,1294,ki),0),L=16+ki|0,0|a},T:function(a){var ji;L=ji=L-16|0,(a|=0)?q[a+428>>2]=1:(q[4+ji>>2]=1740,q[ji>>2]=3133,Y(4,1294,ji)),L=16+ji|0},U:function(a){var ii;return L=ii=L-16|0,a=(a|=0)?q[a+640>>2]:(q[4+ii>>2]=1740,q[ii>>2]=3162,Y(4,1294,ii),0),L=16+ii|0,0|a},V:function(a){var hi;return L=hi=L-16|0,a=(a|=0)?q[a+636>>2]:(q[4+hi>>2]=1740,q[hi>>2]=3187,Y(4,1294,hi),0),L=16+hi|0,0|a},W:function(a){var Cc;return oa(12+(L=Cc=L-16|0)|0,64,a|=0),L=16+Cc|0,q[12+Cc>>2]},X:function(a){var Ln,Jn,Kn=0;return L=Jn=L-16|0,!(a|=0)||oa(12+Jn|0,16,Ln=xa(a))||(Kn=wa(a,q[12+Jn>>2],Ln))||(pa(q[12+Jn>>2]),Kn=0),L=16+Jn|0,0|Kn},Y:function(a){return 0|qa(a|=0)},Z:function(a){pa(a|=0)},_:function(a){var rn;oa(12+(L=rn=L-16|0)|0,64,a|=0),pa(q[12+rn>>2]),L=16+rn|0},$:function(){return 0|L},aa:function(a){return 0|(L=L-(0|a)&-16)},ba:function(a){L=0|a},ca:function(a){return 0|(a=0|(a|=0),(P=0|N())<(a=P+(a|=0)|0)&&a<65536&&(a=new ArrayBuffer(w(a,65536)),(S=new global.Int8Array(a)).set(o),o=S,o=new global.Int8Array(a),p=new global.Int16Array(a),q=new global.Int32Array(a),r=new global.Uint8Array(a),s=new global.Uint16Array(a),t=new global.Uint32Array(a),u=new global.Float32Array(a),v=new global.Float64Array(a),buffer=a,m.buffer=a),P);var S,P},da:function(a,Tk){n[a|=0](Tk|=0)}};function X(a,b,c){var e,f,d=0;if(c)for(;;){if(c=c+-1|0,a>>>0<(d=(e=a+b|0)-1|0)>>>0)for(;f=r[0|a],o[0|a]=r[0|d],o[0|d]=f,(a=a+1|0)>>>0<(d=d+-1|0)>>>0;);if(a=e,!c)break}}function Y(a,b,c){var g;L=g=L-272|0,t[1812]>a>>>0||(a=q[1813])&&(Ka(16+g|0,b,q[12+g>>2]=c),n[a](16+g|0)),L=272+g|0}function Z(a,b,c){32&r[0|a]||!function(a,Gl,Pm){var Qm=0,Rm=0,Sm=0;a:{if(!(Qm=q[Pm+16>>2])){if(function(a){var Pm;return Pm=r[a+74|0],o[a+74|0]=Pm+-1|Pm,8&(Pm=q[a>>2])?(q[a>>2]=32|Pm,1):(q[a+4>>2]=0,q[a+8>>2]=0,Pm=q[a+44>>2],q[a+28>>2]=Pm,q[a+20>>2]=Pm,q[a+16>>2]=Pm+q[a+48>>2],0)}(Pm))break a;Qm=q[Pm+16>>2]}if(Qm-(Sm=q[Pm+20>>2])>>>0>>0)return n[q[Pm+36>>2]](Pm,a,Gl);b:if(!(o[Pm+75|0]<0)){for(Qm=Gl;;){if(!(Rm=Qm))break b;if(10==r[(Qm=Rm+-1|0)+a|0])break}if(n[q[Pm+36>>2]](Pm,a,Rm)>>>0>>0)break a;Gl=Gl-Rm|0,a=a+Rm|0,Sm=q[Pm+20>>2]}$(Sm,a,Gl),q[Pm+20>>2]=q[Pm+20>>2]+Gl}}(b,c,a)}function _(a,b,c,h,i){var k,l,j;if(L=j=L-256|0,!(73728&i|(0|c)<=(0|h))){if(ca(j,b,(k=(i=c-h|0)>>>0<256)?i:256),b=a,l=j,!k){for(c=c-h|0;Z(a,j,256),255<(i=i+-256|0)>>>0;);i=255&c}Z(b,l,i)}L=256+j|0}function $(a,b,c){var h,i=0;if(8192<=c>>>0)I(0|a,0|b,0|c);else{if(h=a+c|0,3&(a^b))if(h>>>0<4)c=a;else if((i=h-4|0)>>>0>>0)c=a;else for(c=a;o[0|c]=r[0|b],o[c+1|0]=r[b+1|0],o[c+2|0]=r[b+2|0],o[c+3|0]=r[b+3|0],b=b+4|0,(c=c+4|0)>>>0<=i>>>0;);else{b:if((0|c)<1)c=a;else if(3&a)for(c=a;;){if(o[0|c]=r[0|b],b=b+1|0,h>>>0<=(c=c+1|0)>>>0)break b;if(!(3&c))break}else c=a;if(!((a=-4&h)>>>0<64||(i=a+-64|0)>>>0>>0))for(;q[c>>2]=q[b>>2],q[c+4>>2]=q[b+4>>2],q[c+8>>2]=q[b+8>>2],q[c+12>>2]=q[b+12>>2],q[c+16>>2]=q[b+16>>2],q[c+20>>2]=q[b+20>>2],q[c+24>>2]=q[b+24>>2],q[c+28>>2]=q[b+28>>2],q[c+32>>2]=q[b+32>>2],q[c+36>>2]=q[b+36>>2],q[c+40>>2]=q[b+40>>2],q[c+44>>2]=q[b+44>>2],q[c+48>>2]=q[b+48>>2],q[c+52>>2]=q[b+52>>2],q[c+56>>2]=q[b+56>>2],q[c+60>>2]=q[b+60>>2],b=b- -64|0,(c=c- -64|0)>>>0<=i>>>0;);if(!(a>>>0<=c>>>0))for(;q[c>>2]=q[b>>2],b=b+4|0,(c=c+4|0)>>>0>>0;);}if(c>>>0>>0)for(;o[0|c]=r[0|b],b=b+1|0,(0|h)!=(0|(c=c+1|0)););}}function aa(a){var b,c;return x((b=a*a)*b*(c=b*a)*(2718311493989822e-21*b-.00019839334836096632)+(c*(.008333329385889463*b-.16666666641626524)+a))}function ba(a){var m;return x(-.499999997251031*(a*=a)+1+.04166662332373906*(m=a*a)+a*m*(2439044879627741e-20*a-.001388676377460993))}function ca(a,n,p){var r,s,t,u;if(p&&(o[(r=a+p|0)-1|0]=n,o[0|a]=n,!(p>>>0<3||(o[r-2|0]=n,o[a+1|0]=n,o[r-3|0]=n,o[a+2|0]=n,p>>>0<7)||(o[r-4|0]=n,o[a+3|0]=n,p>>>0<9)||(s=(r=0-a&3)+a|0,n=w(255&n,16843009),q[s>>2]=n,q[(r=(p=p-r&-4)+s|0)-4>>2]=n,p>>>0<9)||(q[8+s>>2]=n,q[4+s>>2]=n,q[r-8>>2]=n,q[r-12>>2]=n,p>>>0<25)||(q[24+s>>2]=n,q[20+s>>2]=n,q[16+s>>2]=n,q[12+s>>2]=n,q[r-16>>2]=n,q[r-20>>2]=n,q[r-24>>2]=n,q[r-28>>2]=n,(p=p-(u=4&s|24)|0)>>>0<32))))for(t=r=n,n=s+u|0;q[n+24>>2]=t,q[n+28>>2]=r,q[n+16>>2]=t,q[n+20>>2]=r,q[n+8>>2]=t,q[n+12>>2]=r,q[n>>2]=t,q[n+4>>2]=r,n=n+32|0,31<(p=p+-32|0)>>>0;);return a}function da(a,n){var p;if(a>>>0<(n=(a+n|0)-1|0)>>>0)for(;p=r[0|a],o[0|a]=r[0|n],o[0|n]=p,(a=a+1|0)>>>0<(n=n+-1|0)>>>0;);}function ea(a){var n,o=N();return(a=(n=q[2224])+a|0)>>>0<=o<<16>>>0||J(0|a)?(q[2224]=a,n):(q[2094]=48,-1)}function fa(a,v,y,z,B,C,D){var H,I,K,N,Q,R,S,O,P,J,E=0,F=x(0),G=x(0),M=x(0);if(x(0),x(0),x(0),x(0),L=J=L-16|0,1<=(0|a))for(R=w(a,12)+v|0;;){if(1<=(0|(I=q[v+4>>2])))for(S=(a=q[v+8>>2])+w(I,48)|0,I=(H=q[v>>2]<<4)+D|0,K=(8|H)+D|0,H=(4|H)+D|0;(E=q[a+8>>2])&&((O=E+-1|0)>>>0<=1?(P=(q[a+4>>2]<<2)+y|0,E=q[P+(q[a+12>>2]<<2)>>2]<<2,F=u[E+C>>2],Q=u[B+E>>2],G=u[z+E>>2],O-1?(M=G,G=u[a+20>>2],u[I>>2]=u[I>>2]+x(u[a+44>>2]*x(M*G)),u[H>>2]=u[H>>2]+x(x(Q*G)*u[a+44>>2]),u[K>>2]=u[K>>2]+x(x(F*G)*u[a+44>>2])):(E=q[(q[a+16>>2]<<2)+P>>2]<<2,O=u[E+C>>2],P=u[B+E>>2],M=G,G=u[a+20>>2],N=u[a+24>>2],u[I>>2]=u[I>>2]+x(u[a+44>>2]*x(x(M*G)+x(u[z+E>>2]*N))),u[H>>2]=u[H>>2]+x(x(x(Q*G)+x(P*N))*u[a+44>>2]),u[K>>2]=u[K>>2]+x(x(x(F*G)+x(O*N))*u[a+44>>2]))):(q[J>>2]=E,Y(4,1024,J))),(a=a+48|0)>>>0>>0;);if(a=(q[v>>2]<<4)+D|0,F=u[a>>2],u[a>>2]=F>2],u[a+4>>2]=F>2],u[a+8>>2]=F>>0>>0))break}L=16+J|0}function ga(a,q,v){var y,z,x=0;if(1==(0|q)&a>>>0<0|q>>>0<1)x=a;else for(;y=cd(x=dd(a,q,10),z=M,10),o[0|(v=v+-1|0)]=a-y|48,y=9==(0|q)&4294967295>>0|9>>0,a=x,q=z,y;);if(x)for(;o[0|(v=v+-1|0)]=x-w(a=(x>>>0)/10|0,10)|48,q=9>>0,x=a,q;);return v}function ha(a){return a+-48>>>0<10}function ia(a){var q;return(q=La(a,64))?q-a|0:64}function ja(a,v){var w=0;return 1024<=(0|v)?(a*=898846567431158e293,v=(0|(w=v+-1023|0))<1024?w:(a*=898846567431158e293,((0|v)<3069?v:3069)+-2046|0)):-1023<(0|v)||(a*=22250738585072014e-324,v=-1023<(0|(w=v+1022|0))?w:(a*=22250738585072014e-324,(-3066<(0|v)?v:-3066)+2044|0)),f(0,0),f(1,v+1023<<20),a*+g()}function ka(a,v){var A=0,C=a,B=v>>>0<=31?(A=q[a+4>>2],q[a>>2]):(A=q[a>>2],q[a+4>>2]=A,v=v+-32|(q[a>>2]=0),0);q[C>>2]=B<>2]=A<>>32-v}function la(a,v,D,V,W){var X,Y=0,Z=0,_=0;L=X=L-240|0,Y=q[v>>2],q[232+X>>2]=Y,v=q[v+4>>2],q[X>>2]=a,Z=1;a:{b:{c:{if(((q[236+X>>2]=v)||1!=(0|Y))&&(Y=a-q[(D<<2)+W>>2]|0,!((0|n[5](Y,a))<1))){for(_=!V;;){e:{if(v=Y,!(!_|(0|D)<2)){if(V=q[((D<<2)+W|0)-8>>2],-1<(0|n[5](Y=a+-4|0,v)))break e;if(-1<(0|n[5](Y-V|0,v)))break e}if(q[(Z<<2)+X>>2]=v,Z=Z+1|0,ma(232+X|0,a=Oa(232+X|0)),D=a+D|0,!q[236+X>>2]&&1==q[232+X>>2])break b;if(_=1,Y=(a=v)-q[(D<<2)+W>>2]|(V=0),0<(0|n[5](Y,q[X>>2])))continue;break c}break}v=a;break b}v=a}if(V)break a}Na(X,Z),ta(v,D,W)}L=240+X|0}function ma(a,v){var D=0,V=a,L=v>>>0<=31?(D=q[a>>2],q[a+4>>2]):(D=q[a+4>>2],q[a+4>>2]=0,q[a>>2]=D,v=v+-32|0,0);q[V+4>>2]=L>>>v,q[a>>2]=L<<32-v|D>>>v}function na(a,v){var W=r[a+4|0];q[v>>2]=q[a+64>>2]+a,q[v+4>>2]=q[a+68>>2]+a,q[v+8>>2]=q[a+72>>2]+a,q[v+12>>2]=q[a+76>>2]+a,q[v+16>>2]=q[a+80>>2]+a,q[v+20>>2]=q[a+84>>2]+a,q[v+24>>2]=q[a+88>>2]+a,q[v+28>>2]=q[a+92>>2]+a,q[v+32>>2]=q[a+96>>2]+a,q[v+36>>2]=q[a+100>>2]+a,q[v+40>>2]=q[a+104>>2]+a,q[v+44>>2]=q[a+108>>2]+a,q[v+48>>2]=q[a+112>>2]+a,q[v+52>>2]=q[a+116>>2]+a,q[v+56>>2]=q[a+120>>2]+a,q[v+60>>2]=q[a+124>>2]+a,q[v- -64>>2]=q[a+128>>2]+a,q[v+68>>2]=q[a+132>>2]+a,q[v+72>>2]=q[a+136>>2]+a,q[v+76>>2]=q[a+140>>2]+a,q[v+80>>2]=q[a+144>>2]+a,q[v+84>>2]=q[a+148>>2]+a,q[v+92>>2]=q[a+152>>2]+a,q[v+96>>2]=q[a+156>>2]+a,q[v+100>>2]=q[a+160>>2]+a,q[v+108>>2]=q[a+164>>2]+a,q[v+112>>2]=q[a+168>>2]+a,q[v+116>>2]=q[a+172>>2]+a,q[v+124>>2]=q[a+176>>2]+a,q[v+128>>2]=q[a+180>>2]+a,q[v+132>>2]=q[a+184>>2]+a,q[v+136>>2]=q[a+188>>2]+a,q[v+140>>2]=q[a+192>>2]+a,q[v+144>>2]=q[a+196>>2]+a,q[v+148>>2]=q[a+200>>2]+a,q[v+152>>2]=q[a+204>>2]+a,q[v+156>>2]=q[a+208>>2]+a,q[v+164>>2]=q[a+212>>2]+a,q[v+168>>2]=q[a+216>>2]+a,q[v+172>>2]=q[a+220>>2]+a,q[v+176>>2]=q[a+224>>2]+a,q[v+180>>2]=q[a+228>>2]+a,q[v+184>>2]=q[a+232>>2]+a,q[v+188>>2]=q[a+236>>2]+a,q[v+192>>2]=q[a+240>>2]+a,q[v+196>>2]=q[a+244>>2]+a,q[v+200>>2]=q[a+248>>2]+a,q[v+204>>2]=q[a+252>>2]+a,q[v+208>>2]=q[a+256>>2]+a,q[v+212>>2]=q[a+260>>2]+a,q[v+216>>2]=q[a+264>>2]+a,q[v+220>>2]=q[a+268>>2]+a,q[v+224>>2]=q[a+272>>2]+a,q[v+228>>2]=q[a+276>>2]+a,q[v+232>>2]=q[a+280>>2]+a,q[v+236>>2]=q[a+284>>2]+a,q[v+244>>2]=q[a+288>>2]+a,q[v+248>>2]=q[a+292>>2]+a,q[v+272>>2]=q[a+296>>2]+a,q[v+276>>2]=q[a+300>>2]+a,q[v+280>>2]=q[a+304>>2]+a,q[v+292>>2]=q[a+308>>2]+a,q[v+296>>2]=q[a+312>>2]+a,q[v+300>>2]=q[a+316>>2]+a,q[v+304>>2]=q[a+320>>2]+a,q[v+308>>2]=q[a+324>>2]+a,q[v+312>>2]=q[a+328>>2]+a,q[v+316>>2]=q[a+332>>2]+a,q[v+328>>2]=q[a+336>>2]+a,q[v+332>>2]=q[a+340>>2]+a,q[v+336>>2]=q[a+344>>2]+a,q[v+348>>2]=q[a+348>>2]+a,q[v+360>>2]=q[a+352>>2]+a,q[v+364>>2]=q[a+356>>2]+a,q[v+368>>2]=q[a+360>>2]+a,q[v+352>>2]=q[a+364>>2]+a,q[v+356>>2]=q[a+368>>2]+a,q[v+488>>2]=q[a+372>>2]+a,q[v+492>>2]=q[a+376>>2]+a,q[v+496>>2]=q[a+380>>2]+a,q[v+500>>2]=q[a+384>>2]+a,q[v+504>>2]=q[a+388>>2]+a,q[v+508>>2]=q[a+392>>2]+a,q[v+512>>2]=q[a+396>>2]+a,q[v+516>>2]=q[a+400>>2]+a,q[v+520>>2]=q[a+404>>2]+a,q[v+524>>2]=q[a+408>>2]+a,q[v+528>>2]=q[a+412>>2]+a,q[v+532>>2]=q[a+416>>2]+a,q[v+536>>2]=q[a+420>>2]+a,q[v+540>>2]=q[a+424>>2]+a,q[v+544>>2]=q[a+428>>2]+a,q[v+548>>2]=q[a+432>>2]+a,q[v+552>>2]=q[a+436>>2]+a,q[v+556>>2]=q[a+440>>2]+a,q[v+560>>2]=q[a+444>>2]+a,q[v+564>>2]=q[a+448>>2]+a,q[v+568>>2]=q[a+452>>2]+a,q[v+572>>2]=q[a+456>>2]+a,q[v+576>>2]=q[a+460>>2]+a,q[v+580>>2]=q[a+464>>2]+a,W>>>0<2||(q[v+104>>2]=q[a+468>>2]+a,W>>>0<4)||(q[v+260>>2]=q[a+472>>2]+a,q[v+264>>2]=q[a+476>>2]+a,q[v+268>>2]=q[a+480>>2]+a,q[v+88>>2]=q[a+484>>2]+a,q[v+120>>2]=q[a+488>>2]+a,q[v+160>>2]=q[a+492>>2]+a,q[v+584>>2]=q[a+496>>2]+a,q[v+588>>2]=q[a+500>>2]+a,q[v+592>>2]=q[a+504>>2]+a,q[v+596>>2]=q[a+508>>2]+a,q[v+600>>2]=q[a+512>>2]+a,q[v+604>>2]=q[a+516>>2]+a,q[v+240>>2]=q[a+520>>2]+a,q[v+252>>2]=q[a+524>>2]+a,q[v+256>>2]=q[a+528>>2]+a,q[v+372>>2]=q[a+532>>2]+a,q[v+376>>2]=q[a+536>>2]+a,q[v+380>>2]=q[a+540>>2]+a,q[v+384>>2]=q[a+544>>2]+a,q[v+388>>2]=q[a+548>>2]+a,q[v+392>>2]=q[a+552>>2]+a,q[v+396>>2]=q[a+556>>2]+a,q[v+400>>2]=q[a+560>>2]+a,q[v+416>>2]=q[a+564>>2]+a,q[v+420>>2]=q[a+568>>2]+a,q[v+424>>2]=q[a+572>>2]+a,q[v+440>>2]=q[a+576>>2]+a,q[v+444>>2]=q[a+580>>2]+a,q[v+448>>2]=q[a+584>>2]+a,q[v+464>>2]=q[a+588>>2]+a,q[v+468>>2]=q[a+592>>2]+a,q[v+472>>2]=q[a+596>>2]+a,q[v+476>>2]=q[a+600>>2]+a,q[v+480>>2]=q[a+604>>2]+a,q[v+484>>2]=q[a+608>>2]+a,4!=(0|W)&&(q[v+284>>2]=q[a+612>>2]+a,q[v+288>>2]=q[a+616>>2]+a,q[v+320>>2]=q[a+620>>2]+a,q[v+324>>2]=q[a+624>>2]+a,q[v+340>>2]=q[a+628>>2]+a,q[v+344>>2]=q[a+632>>2]+a,q[v+404>>2]=q[a+636>>2]+a,q[v+408>>2]=q[a+640>>2]+a,q[v+412>>2]=q[a+644>>2]+a,q[v+428>>2]=q[a+648>>2]+a,q[v+432>>2]=q[a+652>>2]+a,q[v+436>>2]=q[a+656>>2]+a,q[v+452>>2]=q[a+660>>2]+a,q[v+456>>2]=q[a+664>>2]+a,q[v+460>>2]=q[a+668>>2]+a))}function oa(a,v,$){var aa=0;a:{if(8==(0|v))v=qa($);else{if(aa=28,3&v|1!=(0|function(a){for(var ap=0,bp=0;bp=ap,a;)a&=a-1,ap=ap+1|0;return bp}(v>>>2)))break a;if(aa=48,-64-v>>>0<$>>>0)break a;v=function(a,Tk){var tl,ul,ol=0,rl=0,sl=0;if((rl=a>>>0>(ol=16)?a:16)+-1&rl)for(;ol=(a=ol)<<1,a>>>0>>0;);else a=rl;return-64-a>>>0<=Tk>>>0?(q[2094]=48,0):(ol=qa(12+((rl=Tk>>>0<11?16:Tk+11&-8)+a|0)|0))?(Tk=ol+-8|0,ol&a+-1?(sl=(-8&(ul=q[(tl=ol+-4|0)>>2]))-(ol=(a=15<(ol=((a+ol|0)-1&0-a)-8|0)-Tk>>>0?ol:a+ol|0)-Tk|0)|0,3&ul?(q[a+4>>2]=sl|1&q[a+4>>2]|2,q[4+(sl=a+sl|0)>>2]=1|q[4+sl>>2],q[tl>>2]=ol|1&q[tl>>2]|2,q[a+4>>2]=1|q[a+4>>2],za(Tk,ol)):(Tk=q[Tk>>2],q[a+4>>2]=sl,q[a>>2]=Tk+ol)):a=Tk,3&(Tk=q[a+4>>2])&&((ol=-8&Tk)>>>0<=rl+16>>>0||(q[a+4>>2]=rl|1&Tk|2,q[(Tk=a+rl|0)+4>>2]=3|(rl=ol-rl|0),q[4+(ol=a+ol|0)>>2]=1|q[ol+4>>2],za(Tk,rl))),a+8|0):0}(16>>0?v:16,$)}if(!v)return 1;q[a>>2]=v,aa=0}return aa}function pa(a){var da,v=0,$=0,ba=0,ca=0,ea=0,fa=0,ha=0;a:if(a){da=(ba=a+-8|0)+(a=-8&($=q[a+-4>>2]))|0;b:if(!(1&$)){if(!(3&$))break a;if((ba=ba-($=q[ba>>2])|0)>>>0>>0<=255)ca=q[ba+8>>2],$>>>=3,(0|(v=q[ba+12>>2]))==(0|ca)?(ha=q[2095]&fd($),q[2095]=ha):(q[ca+12>>2]=v,q[v+8>>2]=ca);else{if(fa=q[ba+24>>2],(0|ba)!=(0|($=q[ba+12>>2])))v=q[ba+8>>2],q[v+12>>2]=$,q[$+8>>2]=v;else if(v=(v=q[(ca=ba+20|0)>>2])||q[(ca=ba+16|0)>>2]){for(;ea=ca,(v=q[(ca=($=v)+20|0)>>2])||(ca=$+16|0,v=q[$+16>>2]););q[ea>>2]=0}else $=0;if(fa){ca=q[ba+28>>2];e:{if(q[(v=8684+(ca<<2)|0)>>2]==(0|ba)){if(q[v>>2]=$)break e;ha=q[2096]&fd(ca),q[2096]=ha;break b}if(!(q[fa+(q[fa+16>>2]==(0|ba)?16:20)>>2]=$))break b}q[$+24>>2]=fa,(v=q[ba+16>>2])&&(q[$+16>>2]=v,q[v+24>>2]=$),(v=q[ba+20>>2])&&(q[$+20>>2]=v,q[v+24>>2]=$)}}else if(3==(3&($=q[4+da>>2])))return q[2097]=a,q[4+da>>2]=-2&$,q[ba+4>>2]=1|a,q[a+ba>>2]=a}if(!(da>>>0<=ba>>>0)&&1&($=q[4+da>>2])){f:{if(!(2&$)){if(q[2101]==(0|da)){if(q[2101]=ba,a=q[2098]+a|0,q[2098]=a,q[ba+4>>2]=1|a,q[2100]!=(0|ba))break a;return q[2097]=0,q[2100]=0}if(q[2100]==(0|da))return q[2100]=ba,a=q[2097]+a|0,q[2097]=a,q[ba+4>>2]=1|a,q[a+ba>>2]=a;a=(-8&$)+a|0;g:if($>>>0<=255)$>>>=3,(0|(v=q[8+da>>2]))==(0|(ca=q[12+da>>2]))?(ha=q[2095]&fd($),q[2095]=ha):(q[v+12>>2]=ca,q[ca+8>>2]=v);else{if(fa=q[24+da>>2],(0|da)!=(0|($=q[12+da>>2])))v=q[8+da>>2],q[v+12>>2]=$,q[$+8>>2]=v;else if(v=(v=q[(ca=20+da|0)>>2])||q[(ca=16+da|0)>>2]){for(;ea=ca,(v=q[(ca=($=v)+20|0)>>2])||(ca=$+16|0,v=q[$+16>>2]););q[ea>>2]=0}else $=0;if(fa){ca=q[28+da>>2];j:{if(q[(v=8684+(ca<<2)|0)>>2]==(0|da)){if(q[v>>2]=$)break j;ha=q[2096]&fd(ca),q[2096]=ha;break g}if(!(q[fa+(q[fa+16>>2]==(0|da)?16:20)>>2]=$))break g}q[$+24>>2]=fa,(v=q[16+da>>2])&&(q[$+16>>2]=v,q[v+24>>2]=$),(v=q[20+da>>2])&&(q[$+20>>2]=v,q[v+24>>2]=$)}}if(q[ba+4>>2]=1|a,q[a+ba>>2]=a,q[2100]!=(0|ba))break f;return q[2097]=a}q[4+da>>2]=-2&$,q[ba+4>>2]=1|a,q[a+ba>>2]=a}if(a>>>0<=255)return $=8420+((a>>>=3)<<3)|0,a=(v=q[2095])&(a=1<>2]:(q[2095]=a|v,$),q[$+8>>2]=ba,q[a+12>>2]=ba,q[ba+12>>2]=$,q[ba+8>>2]=a;q[ba+16>>2]=0,v=q[ba+20>>2]=0,(ca=a>>>8)&&(v=31,16777215>>0||(v=ca,v=28+((v=((v=(v<<=ca=ca+1048320>>>16&8)<<(fa=v+520192>>>16&4))<<(ea=v+245760>>>16&2)>>>15)-(ea|ca|fa)|0)<<1|a>>>v+21&1)|0)),ea=8684+((q[($=ba)+28>>2]=v)<<2)|0;m:if((ca=q[2096])&($=1<>>1)|0),$=q[ea>>2];n:{for(;;){if((-8&q[(v=$)+4>>2])==(0|a))break n;if($=ca>>>29,ca<<=1,!($=q[16+(ea=v+(4&$)|0)>>2]))break}q[ea+16>>2]=ba,q[ba+12>>2]=ba,q[ba+24>>2]=v,q[ba+8>>2]=ba;break m}a=q[v+8>>2],q[a+12>>2]=ba,q[v+8>>2]=ba,q[ba+24>>2]=0,q[ba+12>>2]=v,q[ba+8>>2]=a}else q[2096]=$|ca,q[ea>>2]=ba,q[ba+12>>2]=ba,q[ba+24>>2]=ea,q[ba+8>>2]=ba;if(a=q[2103]+-1|0,!(q[2103]=a)){for(ba=8836;ba=(a=q[ba>>2])+8|0,a;);q[2103]=-1}}}}function qa(a){var sa,ia=0,ja=0,ka=0,la=0,ma=0,na=0,oa=0,pa=0,qa=0,ra=0,ua=0;L=sa=L-16|0;a:{b:{c:{d:{e:{f:{g:{h:{i:{j:{k:{if(a>>>0<=244){if(3&(ia=(ma=q[2095])>>>(a=(na=a>>>0<11?16:a+11&-8)>>>3))){a=(ia=q[8428+(la=(ja=a+(1&(-1^ia))|0)<<3)>>2])+8|0,(0|(ka=q[ia+8>>2]))==(0|(la=la+8420|0))?(ua=fd(ja)&ma,q[2095]=ua):(q[ka+12>>2]=la,q[la+8>>2]=ka),q[ia+4>>2]=3|(ja<<=3),q[4+(ia=ia+ja|0)>>2]=1|q[ia+4>>2];break a}if(na>>>0<=(pa=q[2097])>>>0)break k;if(ia){ja=ia=(a=(0-(a=(0-(ja=2<>>12&16,ia=q[8428+(ka=(ja=((ja=(ja|=ia=(a>>>=ia)>>>5&8)|(ia=(a>>>=ia)>>>2&4)|(ia=(a>>>=ia)>>>1&2))|(ia=(a>>>=ia)>>>1&1))+(a>>>ia)|0)<<3)>>2],(0|(a=q[ia+8>>2]))==(0|(ka=ka+8420|0))?(ma=fd(ja)&ma,q[2095]=ma):(q[a+12>>2]=ka,q[ka+8>>2]=a),a=ia+8|0,q[ia+4>>2]=3|na,q[4+(oa=ia+na|0)>>2]=1|(la=(ja<<=3)-na|0),q[ia+ja>>2]=la,pa&&(ia=8420+((ja=pa>>>3)<<3)|0,ka=q[2100],ja=(ja=1<>2]:(q[2095]=ja|ma,ia),q[ia+8>>2]=ka,q[ja+12>>2]=ka,q[ka+12>>2]=ia,q[ka+8>>2]=ja),q[2100]=oa,q[2097]=la;break a}if(!(ra=q[2096]))break k;for(ja=ia=(a=(ra&0-ra)-1|0)>>>12&16,ia=q[8684+(((ja=(ja|=ia=(a>>>=ia)>>>5&8)|(ia=(a>>>=ia)>>>2&4)|(ia=(a>>>=ia)>>>1&2))|(ia=(a>>>=ia)>>>1&1))+(a>>>ia)<<2)>>2],ka=(-8&q[ia+4>>2])-na|0,ja=ia;a=(a=q[ja+16>>2])||q[ja+20>>2];)ka=(ja=(la=(-8&q[a+4>>2])-na|0)>>>0>>0)?la:ka,ia=ja?a:ia,ja=a;if(qa=q[ia+24>>2],(0|(la=q[ia+12>>2]))!=(0|ia)){a=q[ia+8>>2],q[a+12>>2]=la,q[la+8>>2]=a;break b}if(!(a=q[(ja=ia+20|0)>>2])){if(!(a=q[ia+16>>2]))break j;ja=ia+16|0}for(;oa=ja,(a=q[(ja=(la=a)+20|0)>>2])||(ja=la+16|0,a=q[la+16>>2]););q[oa>>2]=0;break b}if(na=-1,!(4294967231>>0)&&(na=-8&(ia=a+11|0),pa=q[2096])){ja=0-na|0,ma=0,(ia>>>=8)&&(ma=31,16777215>>0||(ma=28+((a=((ma=(ia<<=ka=ia+1048320>>>16&8)<<(a=ia+520192>>>16&4))<<(ia=ma+245760>>>16&2)>>>15)-(ia|a|ka)|0)<<1|na>>>a+21&1)|0));q:{r:{if(ka=q[8684+(ma<<2)>>2])for(ia=na<<(31==(0|ma)?0:25-(ma>>>1)|0),a=0;;){if(!(ja>>>0<=(oa=(-8&q[ka+4>>2])-na|0)>>>0||(la=ka,ja=oa))){ja=0,a=ka;break r}if(oa=q[ka+20>>2],ka=q[16+((ia>>>29&4)+ka|0)>>2],a=oa&&(0|oa)!=(0|ka)?oa:a,ia<<=0!=(0|ka),!ka)break}else a=0;if(!(a|la)){if(!(a=(0-(a=2<>>12&16,a=q[8684+(((ka=(ka|=ia=(a>>>=ia)>>>5&8)|(ia=(a>>>=ia)>>>2&4)|(ia=(a>>>=ia)>>>1&2))|(ia=(a>>>=ia)>>>1&1))+(a>>>ia)<<2)>>2]}if(!a)break q}for(;ja=(ia=(ka=(-8&q[a+4>>2])-na|0)>>>0>>0)?ka:ja,la=ia?a:la,a=(ia=q[a+16>>2])||q[a+20>>2];);}if(!(!la|ja>>>0>=q[2097]-na>>>0)){if(oa=q[la+24>>2],(0|la)!=(0|(ia=q[la+12>>2]))){a=q[la+8>>2],q[a+12>>2]=ia,q[ia+8>>2]=a;break c}if(!(a=q[(ka=la+20|0)>>2])){if(!(a=q[la+16>>2]))break i;ka=la+16|0}for(;ma=ka,(a=q[(ka=(ia=a)+20|0)>>2])||(ka=ia+16|0,a=q[ia+16>>2]););q[ma>>2]=0;break c}}}if(na>>>0<=(ia=q[2097])>>>0){a=q[2100],16<=(ja=ia-na|0)>>>0?(q[2097]=ja,q[2100]=ka=a+na|0,q[ka+4>>2]=1|ja,q[a+ia>>2]=ja,q[a+4>>2]=3|na):(q[2100]=0,q[2097]=0,q[a+4>>2]=3|ia,q[4+(ia=a+ia|0)>>2]=1|q[ia+4>>2]),a=a+8|0;break a}if(na>>>0<(ka=q[2098])>>>0){q[2098]=ia=ka-na|0,a=q[2101],q[2101]=ja=a+na|0,q[ja+4>>2]=1|ia,q[a+4>>2]=3|na,a=a+8|0;break a}if((ja=(ma=(ja=la=na+47|(a=0))+(ia=q[2213]?q[2215]:(q[2216]=-1,q[2217]=-1,q[2214]=4096,q[2215]=4096,q[2213]=12+sa&-16^1431655768,q[2218]=0,q[2206]=0,4096))|0)&(oa=0-ia|0))>>>0<=na>>>0)break a;if((ia=q[2205])&&(qa=(pa=q[2203])+ja|0)>>>0<=pa>>>0|ia>>>0>>0)break a;if(4&r[8824])break f;v:{w:{if(ia=q[2101])for(a=8828;;){if((pa=q[a>>2])+q[a+4>>2]>>>0>ia>>>0&&pa>>>0<=ia>>>0)break w;if(!(a=q[a+8>>2]))break}if(-1==(0|(ia=ea(0))))break g;if(ma=ja,(ma=(ka=(a=q[2214])+-1|0)&ia?(ja-ia|0)+(ia+ka&0-a)|0:ma)>>>0<=na>>>0|2147483646>>0)break g;if((a=q[2205])&&(oa=(ka=q[2203])+ma|0)>>>0<=ka>>>0|a>>>0>>0)break g;if((0|ia)!=(0|(a=ea(ma))))break v;break e}if(2147483646<(ma=oa&ma-ka)>>>0)break g;if((0|(ia=ea(ma)))==(q[a>>2]+q[a+4>>2]|0))break h;a=ia}if(!(na+48>>>0<=ma>>>0|2147483646>>0|-1==(0|(ia=a)))){if(2147483646<(a=(a=q[2215])+(la-ma|0)&0-a)>>>0)break e;if(-1!=(0|ea(a))){ma=a+ma|0;break e}ea(0-ma|0);break g}if(-1!=(0|ia))break e;break g}la=0;break b}ia=0;break c}if(-1!=(0|ia))break e}q[2206]=4|q[2206]}if(2147483646>>0)break d;if(ia=ea(ja),(a=ea(0))>>>0<=ia>>>0|-1==(0|ia)|-1==(0|a))break d;if((ma=a-ia|0)>>>0<=na+40>>>0)break d}a=q[2203]+ma|0,(q[2203]=a)>>>0>t[2204]&&(q[2204]=a);x:{y:{z:{if(ja=q[2101]){for(a=8828;;){if(((ka=q[a>>2])+(la=q[a+4>>2])|0)==(0|ia))break z;if(!(a=q[a+8>>2]))break}break y}for((a=q[2099])>>>0<=ia>>>0&&a||(q[2099]=ia),a=0,q[2208]=ma,q[2207]=ia,q[2103]=-1,q[2104]=q[2213],q[2210]=0;q[8428+(ja=a<<3)>>2]=ka=ja+8420|0,q[ja+8432>>2]=ka,32!=(0|(a=a+1|0)););q[2098]=ka=(a=ma+-40|0)-(ja=ia+8&7?-8-ia&7:0)|0,q[2101]=ja=ia+ja|0,q[ja+4>>2]=1|ka,q[4+(a+ia|0)>>2]=40,q[2102]=q[2217];break x}if(!(8&r[a+12|0]|ia>>>0<=ja>>>0|ja>>>0>>0)){q[a+4>>2]=la+ma,q[2101]=ia=(a=ja+8&7?-8-ja&7:0)+ja|0,ka=q[2098]+ma|0,q[2098]=a=ka-a|0,q[ia+4>>2]=1|a,q[4+(ja+ka|0)>>2]=40,q[2102]=q[2217];break x}}ia>>>0<(la=q[2099])>>>0&&(q[2099]=ia,la=0),ka=ia+ma|0,a=8828;A:{B:{C:{D:{E:{F:{for(;(0|ka)!=q[a>>2];)if(!(a=q[a+8>>2]))break F;if(!(8&r[a+12|0]))break E}for(a=8828;;){if((ka=q[a>>2])>>>0<=ja>>>0&&ja>>>0<(la=ka+q[a+4>>2]|0)>>>0)break D;a=q[a+8>>2]}}if(q[a>>2]=ia,q[a+4>>2]=q[a+4>>2]+ma,q[4+(qa=(ia+8&7?-8-ia&7:0)+ia|0)>>2]=3|na,a=((ia=ka+(ka+8&7?-8-ka&7:0)|0)-qa|0)-na|0,oa=na+qa|0,(0|ia)==(0|ja)){q[2101]=oa,a=q[2098]+a|0,q[2098]=a,q[oa+4>>2]=1|a;break B}if(q[2100]==(0|ia)){q[2100]=oa,a=q[2097]+a|0,q[2097]=a,q[oa+4>>2]=1|a,q[a+oa>>2]=a;break B}if(1==(3&(ja=q[ia+4>>2]))){ra=-8&ja;G:if(ja>>>0<=255)la=ja>>>3,ja=q[ia+8>>2],(0|(ka=q[ia+12>>2]))==(0|ja)?(ua=q[2095]&fd(la),q[2095]=ua):(q[ja+12>>2]=ka,q[ka+8>>2]=ja);else{if(pa=q[ia+24>>2],(0|(ma=q[ia+12>>2]))!=(0|ia))ja=q[ia+8>>2],q[ja+12>>2]=ma,q[ma+8>>2]=ja;else if(na=(na=q[(ka=ia+20|0)>>2])||q[(ka=ia+16|0)>>2]){for(;ja=ka,(na=q[(ka=(ma=na)+20|0)>>2])||(ka=ma+16|0,na=q[ma+16>>2]););q[ja>>2]=0}else ma=0;if(pa){ja=q[ia+28>>2];J:{if(q[(ka=8684+(ja<<2)|0)>>2]==(0|ia)){if(q[ka>>2]=ma)break J;ua=q[2096]&fd(ja),q[2096]=ua;break G}if(!(q[pa+(q[pa+16>>2]==(0|ia)?16:20)>>2]=ma))break G}q[ma+24>>2]=pa,(ja=q[ia+16>>2])&&(q[ma+16>>2]=ja,q[ja+24>>2]=ma),(ja=q[ia+20>>2])&&(q[ma+20>>2]=ja,q[ja+24>>2]=ma)}}ia=ia+ra|0,a=a+ra|0}if(q[ia+4>>2]=-2&q[ia+4>>2],q[oa+4>>2]=1|a,(q[a+oa>>2]=a)>>>0<=255){a=8420+((ia=a>>>3)<<3)|0,ia=(ja=q[2095])&(ia=1<>2]:(q[2095]=ia|ja,a),q[a+8>>2]=oa,q[ia+12>>2]=oa,q[oa+12>>2]=a,q[oa+8>>2]=ia;break B}if(ia=0,(ka=a>>>8)&&(ia=31,16777215>>0||(ia=28+((ia=((na=(ka<<=la=ka+1048320>>>16&8)<<(ia=ka+520192>>>16&4))<<(ka=na+245760>>>16&2)>>>15)-(ka|ia|la)|0)<<1|a>>>ia+21&1)|0)),q[(ja=oa)+28>>2]=ia,q[oa+16>>2]=0,ja=8684+(ia<<2)|(q[oa+20>>2]=0),(ka=q[2096])&(la=1<>>1)|0),ia=q[ja>>2];;){if((-8&q[(ja=ia)+4>>2])==(0|a))break C;if(ia=ka>>>29,ka<<=1,!(ia=q[16+(la=(4&ia)+ja|0)>>2]))break}q[la+16>>2]=oa}else q[2096]=ka|la,q[ja>>2]=oa;q[oa+24>>2]=ja,q[oa+12>>2]=oa,q[oa+8>>2]=oa;break B}for(q[2098]=oa=(a=ma+-40|0)-(ka=ia+8&7?-8-ia&7:0)|0,q[2101]=ka=ia+ka|0,q[ka+4>>2]=1|oa,q[4+(a+ia|0)>>2]=40,q[2102]=q[2217],q[(ka=(a=(la+(la+-39&7?39-la&7:0)|0)-47|0)>>>0>>0?ja:a)+4>>2]=27,a=q[2210],q[ka+16>>2]=q[2209],q[ka+20>>2]=a,a=q[2208],q[ka+8>>2]=q[2207],q[ka+12>>2]=a,q[2209]=ka+8,q[2208]=ma,q[2207]=ia,a=ka+24|(q[2210]=0);q[a+4>>2]=7,ia=a+8|0,a=a+4|0,ia>>>0>>0;);if((0|ja)==(0|ka))break x;if(q[ka+4>>2]=-2&q[ka+4>>2],q[ja+4>>2]=1|(la=ka-ja|0),(q[ka>>2]=la)>>>0<=255){a=8420+((ia=la>>>3)<<3)|0,ia=(ka=q[2095])&(ia=1<>2]:(q[2095]=ia|ka,a),q[a+8>>2]=ja,q[ia+12>>2]=ja,q[ja+12>>2]=a,q[ja+8>>2]=ia;break x}if(q[ja+16>>2]=0,a=q[ja+20>>2]=0,(ka=la>>>8)&&(a=31,16777215>>0||(a=28+((a=((oa=(ka<<=ma=ka+1048320>>>16&8)<<(a=ka+520192>>>16&4))<<(ka=oa+245760>>>16&2)>>>15)-(ka|a|ma)|0)<<1|la>>>a+21&1)|0)),ia=8684+((q[(ia=ja)+28>>2]=a)<<2)|0,(ka=q[2096])&(ma=1<>>1)|0),ia=q[ia>>2];;){if((0|la)==(-8&q[(ka=ia)+4>>2]))break A;if(ia=a>>>29,a<<=1,!(ia=q[16+(ma=ka+(4&ia)|0)>>2]))break}q[ma+16>>2]=ja,q[ja+24>>2]=ka}else q[2096]=ka|ma,q[ia>>2]=ja,q[ja+24>>2]=ia;q[ja+12>>2]=ja,q[ja+8>>2]=ja;break x}a=q[ja+8>>2],q[a+12>>2]=oa,q[ja+8>>2]=oa,q[oa+24>>2]=0,q[oa+12>>2]=ja,q[oa+8>>2]=a}a=qa+8|0;break a}a=q[ka+8>>2],q[a+12>>2]=ja,q[ka+8>>2]=ja,q[ja+24>>2]=0,q[ja+12>>2]=ka,q[ja+8>>2]=a}if(!((a=q[2098])>>>0<=na>>>0)){q[2098]=ia=a-na|0,a=q[2101],q[2101]=ja=a+na|0,q[ja+4>>2]=1|ia,q[a+4>>2]=3|na,a=a+8|0;break a}}q[2094]=48,a=0;break a}Q:if(oa){a=q[la+28>>2];R:{if(q[(ka=8684+(a<<2)|0)>>2]==(0|la)){if(q[ka>>2]=ia)break R;pa=fd(a)&pa,q[2096]=pa;break Q}if(!(q[oa+(q[oa+16>>2]==(0|la)?16:20)>>2]=ia))break Q}q[ia+24>>2]=oa,(a=q[la+16>>2])&&(q[ia+16>>2]=a,q[a+24>>2]=ia),(a=q[la+20>>2])&&(q[ia+20>>2]=a,q[a+24>>2]=ia)}S:if(ja>>>0<=15)q[la+4>>2]=3|(a=ja+na|0),q[4+(a=a+la|0)>>2]=1|q[a+4>>2];else if(q[la+4>>2]=3|na,q[4+(ka=la+na|0)>>2]=1|ja,(q[ja+ka>>2]=ja)>>>0<=255)a=8420+((ia=ja>>>3)<<3)|0,ia=(ja=q[2095])&(ia=1<>2]:(q[2095]=ia|ja,a),q[a+8>>2]=ka,q[ia+12>>2]=ka,q[ka+12>>2]=a,q[ka+8>>2]=ia;else{a=0,(na=ja>>>8)&&(a=31,16777215>>0||(a=28+((a=((oa=(na<<=ma=na+1048320>>>16&8)<<(a=na+520192>>>16&4))<<(na=oa+245760>>>16&2)>>>15)-(na|a|ma)|0)<<1|ja>>>a+21&1)|0)),q[(ia=ka)+28>>2]=a,q[ka+16>>2]=0,ia=8684+(a<<2)|(q[ka+20>>2]=0);V:{if((na=1<>>1)|0),na=q[ia>>2];;){if((-8&q[(ia=na)+4>>2])==(0|ja))break V;if(na=a>>>29,a<<=1,!(na=q[16+(ma=(4&na)+ia|0)>>2]))break}q[ma+16>>2]=ka}else q[2096]=na|pa,q[ia>>2]=ka;q[ka+24>>2]=ia,q[ka+12>>2]=ka,q[ka+8>>2]=ka;break S}a=q[ia+8>>2],q[a+12>>2]=ka,q[ia+8>>2]=ka,q[ka+24>>2]=0,q[ka+12>>2]=ia,q[ka+8>>2]=a}a=la+8|0;break a}X:if(qa){a=q[ia+28>>2];Y:{if(q[(ja=8684+(a<<2)|0)>>2]==(0|ia)){if(q[ja>>2]=la)break Y;ua=fd(a)&ra,q[2096]=ua;break X}if(!(q[qa+(q[qa+16>>2]==(0|ia)?16:20)>>2]=la))break X}q[la+24>>2]=qa,(a=q[ia+16>>2])&&(q[la+16>>2]=a,q[a+24>>2]=la),(a=q[ia+20>>2])&&(q[la+20>>2]=a,q[a+24>>2]=la)}ka>>>0<=15?(q[ia+4>>2]=3|(a=ka+na|0),q[4+(a=a+ia|0)>>2]=1|q[a+4>>2]):(q[ia+4>>2]=3|na,q[4+(na=ia+na|0)>>2]=1|ka,q[ka+na>>2]=ka,pa&&(a=8420+((ja=pa>>>3)<<3)|0,la=q[2100],ja=(ja=1<>2]:(q[2095]=ja|ma,a),q[a+8>>2]=la,q[ja+12>>2]=la,q[la+12>>2]=a,q[la+8>>2]=ja),q[2100]=na,q[2097]=ka),a=ia+8|0}return L=16+sa|0,a}function ra(a,va,wa,xa,ya,za,Aa){var Qa,Ta,Ba,Ca=0,Da=0,Fa=0,Ia=0,Ja=0,Ka=0,Ma=0,Na=0,Oa=0,Pa=0,Ra=0,Sa=0;q[76+(L=Ba=L-80|0)>>2]=va,Ta=55+Ba|0,Qa=56+Ba|0,va=0;a:{b:{c:for(;;){(0|Oa)<0||(Oa=(2147483647-Oa|0)<(0|va)?(q[2094]=61,-1):va+Oa|0);e:{f:{g:{h:{i:{j:{k:{l:{m:{n:{o:{p:{q:{if(Ia=q[76+Ba>>2],Fa=r[0|(va=Ia)]){for(;;){r:{s:{t:if(Ca=255&Fa){if(37!=(0|Ca))break s;for(Fa=va;;){if(37!=r[va+1|0])break t;if(q[76+Ba>>2]=Ca=va+2|0,Fa=Fa+1|0,Da=r[va+2|0],va=Ca,37!=(0|Da))break}}else Fa=va;if(va=Fa-Ia|0,a&&Z(a,Ia,va),va)continue c;Pa=-1,Ja=!ha(o[q[76+(Ca=Ba)>>2]+(Fa=1)|0]),va=q[76+Ba>>2],Ja|36!=r[va+2|0]||(Pa=o[va+1|0]+-48|0,Ra=1,Fa=3),q[Ca+76>>2]=va=Fa+va|0;u:if(31<(Da=(Ma=o[(Fa=0)|va])+-32|0)>>>0)Ca=va;else if(Ca=va,75913&(Da=1<>2]=Ca=va+1|0,Fa|=Da,31<(Da=(Ma=o[va+1|0])+-32|0)>>>0)break u;if(va=Ca,!(75913&(Da=1<>2],36==r[va+2|0]))q[((o[va+1|0]<<2)+ya|0)-192>>2]=10,Na=q[((o[va+1|0]<<3)+xa|0)-384>>2],Ra=1,va=va+3|0;else{if(Ra)break b;Na=Ra=0,a&&(va=q[wa>>2],q[wa>>2]=va+4,Na=q[va>>2]),va=q[76+Ba>>2]+1|0}q[Ja+76>>2]=va,-1<(0|Na)||(Na=0-Na|0,Fa|=8192)}else{if((0|(Na=Ha(76+Ba|0)))<0)break b;va=q[76+Ba>>2]}if(Da=-1,46==r[0|va])if(42==r[va+1|0])if(ha(o[va+2|0])&&(va=q[76+Ba>>2],36==r[va+3|0]))q[((o[va+2|0]<<2)+ya|0)-192>>2]=10,Da=q[((o[va+2|0]<<3)+xa|0)-384>>2],q[76+Ba>>2]=va=va+4|0;else{if(Ra)break b;Da=a?(va=q[wa>>2],q[wa>>2]=va+4,q[va>>2]):0,va=q[76+Ba>>2]+2|0,q[76+Ba>>2]=va}else q[76+Ba>>2]=va+1,Da=Ha(76+Ba|0),va=q[76+Ba>>2];for(Ca=0;;){if(Sa=Ca,Ka=-1,57>>0)break a;if(q[76+Ba>>2]=Ma=va+1|0,Ca=o[0|va],va=Ma,!((Ca=r[3327+(Ca+w(Sa,58)|0)|0])+-1>>>0<8))break}if(!Ca)break a;A:{B:{C:{if(19==(0|Ca)){if((0|Pa)<=-1)break C;break a}if((0|Pa)<0)break B;q[(Pa<<2)+ya>>2]=Ca,Ca=q[4+(va=(Pa<<3)+xa|0)>>2],q[64+Ba>>2]=q[va>>2],q[68+Ba>>2]=Ca}if(va=0,a)break A;continue c}if(!a)break e;Ga(64+Ba|0,Ca,wa,Aa),Ma=q[76+Ba>>2]}if(Ja=-65537&Fa,Fa=8192&Fa?Ja:Fa,Pa=3360,Ca=Qa,va=o[Ma+-1|(Ka=0)],(Ma=(va=Sa&&3==(15&va)?-33&va:va)+-88|0)>>>0<=32)break r;D:{E:{F:{G:{if(6<(Ja=va+-65|0)>>>0){if(83!=(0|va))break f;if(!Da)break G;Ca=q[64+Ba>>2];break E}switch(Ja-1|0){case 1:break F;case 0:case 2:break f;default:break q}}_(a,32,Na,va=0,Fa);break D}q[12+Ba>>2]=0,q[8+Ba>>2]=q[64+Ba>>2],q[64+Ba>>2]=8+Ba,Da=-1,Ca=8+Ba|0}va=0;H:{for(;;){if(!(Ia=q[Ca>>2]))break H;if((Ja=(0|(Ia=Ea(4+Ba|0,Ia)))<0)|Da-va>>>0>>0)break;if(Ca=Ca+4|0,!((va=va+Ia|0)>>>0>>0))break H}if(Ka=-1,Ja)break a}if(_(a,32,Na,va,Fa),va)for(Da=0,Ca=q[64+Ba>>2];;){if(!(Ia=q[Ca>>2]))break D;if((0|va)<(0|(Da=(Ia=Ea(4+Ba|0,Ia))+Da|0)))break D;if(Z(a,4+Ba|0,Ia),Ca=Ca+4|0,!(Da>>>0>>0))break}else va=0}_(a,32,Na,va,8192^Fa),va=(0|va)<(0|Na)?Na:va;continue c}q[76+Ba>>2]=Ca=va+1|0,Fa=r[va+1|0],va=Ca;continue}break}switch(Ma-1|0){case 28:break i;case 21:break j;case 23:break l;case 22:break m;case 11:case 16:break n;case 10:break o;case 26:break p;case 8:case 12:case 13:case 14:break q;case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 9:case 15:case 17:case 18:case 19:case 20:case 24:case 25:case 27:case 29:case 30:break f;default:break k}}if(Ka=Oa,a)break a;if(!Ra)break e;for(va=1;;){if(a=q[(va<<2)+ya>>2]){if(Ga((va<<3)+xa|0,a,wa,Aa),10!=(0|(va=va+(Ka=1)|0)))continue;break a}break}if(Ka=1,9>>0)break a;if(Ka=-1,q[(va<<2)+ya>>2])break a;for(;!q[((va=va+1|0)<<2)+ya>>2]&&10!=(0|va););Ka=va>>>0<10?-1:1;break a}va=0|n[za](a,v[64+Ba>>3],Na,Da,Fa,va);continue}Ca=(va=La(Ia=(va=q[64+Ba>>2])||3370,Da))||Da+Ia|0,Fa=Ja,Da=va?va-Ia|0:Da;break f}o[55+Ba|0]=q[64+Ba>>2],Da=1,Ia=Ta,Fa=Ja;break f}if(va=Ja=q[68+Ba>>2],Ia=q[64+Ba>>2],(0|va)<-1||(0|va)<=-1&&!(4294967295>>0)){va=0-(va+(0>>0)|0)|0,q[64+Ba>>2]=Ia=0-Ia|0,q[68+Ba>>2]=va,Ka=1,Pa=3360;break h}if(2048&Fa){Ka=1,Pa=3361;break h}Pa=(Ka=1&Fa)?3362:3360;break h}if(Ia=function(a,Gl,Pm){if(a|Gl)for(;o[0|(Pm=Pm+-1|0)]=7&a|48,(a=(7&Gl)<<29|a>>>3)|(Gl>>>=3););return Pm}(q[64+Ba>>2],q[68+Ba>>2],Qa),!(8&Fa))break g;Da=(0|(va=Qa-Ia|0))<(0|Da)?Da:va+1|0;break g}Da=8>>0?Da:8,Fa|=8,va=120}if(Ia=function(a,Gl,Pm,Qm){if(a|Gl)for(;o[0|(Pm=Pm+-1|0)]=r[3856+(15&a)|0]|Qm,(a=(15&Gl)<<28|a>>>4)|(Gl>>>=4););return Pm}(q[64+Ba>>2],q[68+Ba>>2],Qa,32&va),!(8&Fa)|!(q[64+Ba>>2]|q[68+Ba>>2]))break g;Pa=3360+(va>>>4)|0,Ka=2;break g}if(7<(Ca=255&Sa)>>>(va=0))continue;switch(Ca-1|0){default:case 0:q[q[64+Ba>>2]>>2]=Oa;continue;case 1:Ca=q[64+Ba>>2],q[Ca>>2]=Oa,q[Ca+4>>2]=Oa>>31;continue;case 2:p[q[64+Ba>>2]>>1]=Oa;continue;case 3:o[q[64+Ba>>2]]=Oa;continue;case 5:q[q[64+Ba>>2]>>2]=Oa;continue;case 4:continue;case 6:}Ca=q[64+Ba>>2],q[Ca>>2]=Oa,q[Ca+4>>2]=Oa>>31;continue}Ia=q[64+Ba>>2],va=q[68+Ba>>2],Pa=3360}Ia=ga(Ia,va,Qa)}Fa=-1<(0|Da)?-65537&Fa:Fa,Da=!!((Ja=va=q[68+Ba>>2])|(Ma=q[64+Ba>>2]))|Da?(0|(va=!(Ja|Ma)+(Qa-Ia|0)|0))<(0|Da)?Da:va:(Ia=Qa,0)}_(a,32,va=(0|Na)<(0|(Ca=(Da=(0|Da)<(0|(Ja=Ca-Ia|0))?Ja:Da)+Ka|0))?Ca:Na,Ca,Fa),Z(a,Pa,Ka),_(a,48,va,Ca,65536^Fa),_(a,48,Da,Ja,0),Z(a,Ia,Ja),_(a,32,va,Ca,8192^Fa);continue}break}Ka=0;break a}Ka=-1}return L=80+Ba|0,Ka}function sa(a){var ya,va=0,wa=0,xa=0,za=0,xa=4,wa=1439;a:if(va=r[0|a]){for(;!((0|(ya=r[0|wa]))!=(0|va)||!(xa=xa+-1|0)|!ya);)if(wa=wa+1|0,va=r[a+1|0],a=a+1|0,!va)break a;za=va}return(255&za)-r[0|wa]|0}function ta(a,Aa,Ea){var La,Ga,Ha=0,Ua=0,Va=0;q[(L=Ga=L-240|0)>>2]=a,Ua=1;a:if(!((0|Aa)<2))for(Ha=a;;){if(Ha=(La=Ha+-4|0)-q[((Va=Aa+-2|0)<<2)+Ea>>2]|0,0<=(0|n[5](a,Ha))&&-1<(0|n[5](a,La)))break a;if(a=(Ua<<2)+Ga|0,0<=(0|n[5](Ha,La))?(q[a>>2]=Ha,Va=Aa+-1|0):Ha=q[a>>2]=La,Ua=Ua+1|0,(0|Va)<2)break a;a=q[Ga>>2],Aa=Va}Na(Ga,Ua),L=240+Ga|0}function ua(a){var Ea,_a,Aa=0;if(x(0),function(a){var Hg,Ig;q[a+428>>2]&&(Ig=q[a+332>>2],$(q[a+460>>2],q[a+436>>2],Hg=Ig<<2),$(q[a+464>>2],q[a+440>>2],Hg),$(q[a+468>>2],q[a+448>>2],Hg),r[q[a>>2]+4|0]<4||($(q[a+472>>2],q[a+452>>2],Hg=Ig<<4),$(q[a+476>>2],q[a+456>>2],Hg)))}(a),function(a){var he,ie,je,ce=0,de=x(0),ee=x(0),fe=0,ge=x(0);x(0),x(0);if(1<=(0|(fe=q[a>>2])))for(je=(ce=q[a+4>>2])+w(fe,52)|0,a=q[a+12>>2];de=u[a>>2],u[ce+44>>2]!=(de=(he=q[ce+16>>2])?(ee=de,de=u[ce+4>>2],ge=u[ce+12>>2],ee=x(x(ee-de)/ge),ie=x(C(ee)),fe=x(y(ie))>2],ee=u[ce+8>>2],de>2]=de,q[ce+48>>2]=1):q[ce+48>>2]=0,he||(u[a>>2]=de),a=a+4|0,(ce=ce+52|0)>>>0>>0;);}(a+540|0),function(a){var Td,Ud,Zd,$d,ae,be,Od=0,Pd=0,Qd=x(0),Rd=0,Sd=x(0),Vd=(x(0),x(0),0),Wd=x(0),Xd=0,Yd=0,_d=0;x(0);if(1<=(0|(Rd=q[a+540>>2])))for(ae=(Vd=q[a+544>>2])+w(Rd,52)|0,be=q[a+644>>2];;){a:if(!(q[Vd>>2]||(0|(Rd=q[Vd+32>>2]))<1))if(Zd=(a=q[Vd+28>>2])+w(Rd,28)|0,$d=u[Vd+24>>2],Ud=u[Vd+20>>2],Td=u[Vd+44>>2],be)for(;;){Wd=x(Yd=0);h:{i:{j:{if((0|(Pd=q[a>>2]))<1)Od=Rd=0;else if(Xd=q[a+4>>2],Sd=u[Xd>>2],Qd=x(Sd-Ud),1==(0|Pd))Rd=Td>2],!(Td>2],Td>2])break h;break i}Od=Pd+-1|0,Rd=1}Xd=(Pd=(Sd=u[a+12>>2])!=Wd)&(Wd==x(0)|Sd==x(0))|q[a+8>>2]!=(0|Od),Yd=Rd}if(q[a+20>>2]=Xd,q[a+24>>2]=Pd,u[a+12>>2]=Wd,q[a+16>>2]=Yd,q[a+8>>2]=Od,!((a=a+28|0)>>>0>>0))break}else{if(!q[Vd+48>>2])for(;;)if(q[a+20>>2]=0,!((a=a+28|(q[a+24>>2]=0))>>>0>>0))break a;for(;;){Wd=x(Yd=0);b:{c:{d:{e:if(!(((Pd=0)|(Od=q[(Xd=a)>>2]))<1)){if(Rd=q[a+4>>2],Sd=u[Rd>>2],Qd=x(Sd-Ud),1!=(0|Od)){if(!(Td>2],!(Td>2],Td>2]))break b}Yd=Rd,_d=(Pd=(Sd=u[a+12>>2])!=Wd)&(Wd==x(0)|Sd==x(0))|q[a+8>>2]!=(0|Od)}if(q[Xd+20>>2]=_d,q[a+24>>2]=Pd,u[a+12>>2]=Wd,q[a+16>>2]=Yd,q[a+8>>2]=Od,!((a=a+28|0)>>>0>>0))break}}if(!((Vd=Vd+52|0)>>>0>>0))break}}(a),function(a){var od,pd,qd,rd,sd,hd=0,id=x(0),jd=0,kd=0,ld=x(0),md=0,nd=x(0);x(0);if(!(r[q[a>>2]+4|0]<4||(0|(hd=q[a+540>>2]))<1))for(rd=(md=q[a+544>>2])+w(hd,52)|0,sd=q[a+644>>2];;){b:if(1==q[md>>2]&&!((0|(hd=q[md+40>>2]))<1))if(pd=(a=q[md+36>>2])+w(hd,28)|0,od=u[md+44>>2],sd)for(;;){nd=x(hd=0);d:if(!((0|(kd=q[a>>2]))<2||(jd=q[a+4>>2],od<=(id=u[jd>>2])))){hd=1;e:if(!(od<(ld=u[jd+4>>2]))){for(;id=ld,(0|kd)!=(0|(hd=hd+1|0));)if(od<(ld=u[jd+(hd<<2)>>2]))break e;hd=kd+-1|0;break d}nd=x(x(od-id)/x(ld-id)),hd=hd+-1|0}if(id=u[a+16>>2],u[a+16>>2]=nd,kd=q[a+12>>2],q[a+12>>2]=hd,q[a+24>>2]=jd=id!=nd,q[a+20>>2]=jd&(nd==x(0)|id==x(0))|(0|hd)!=(0|kd),!((a=a+28|0)>>>0>>0))break}else{if(!q[md+48>>2])for(;;)if(q[a+20>>2]=0,!((a=a+28|(q[a+24>>2]=0))>>>0>>0))break b;for(;;){nd=x(kd=0);c:if(!((0|(qd=q[a>>2]))<2||(jd=q[a+4>>2],od<=(id=u[jd>>2])))){if(hd=1,!(od<(ld=u[jd+4>>2])))for(kd=qd+-1|0;;){if(id=ld,(0|hd)==(0|kd))break c;if(od<(ld=u[jd+((hd=hd+1|0)<<2)>>2]))break}nd=x(x(od-id)/x(ld-id)),kd=hd+-1|0}if(id=u[a+16>>2],u[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=1}else for(;q[(Dd=vd+(a<<2)|0)>>2]=Ed+q[Dd>>2],(0|Bd)!=(0|(a=a+1|0)););if(td=w(q[wd>>2],td),(0|Gd)==(0|(yd=yd+1|0)))break}else for(;;){if(wd=q[(yd<<2)+Ld>>2],zd=w(q[wd+8>>2],td),(Ad=u[wd+12>>2])!=x(a=0))q[vd>>2]=zd+q[vd>>2],u[ud>>2]=x(x(1)-Ad)*u[ud>>2];else for(;q[(Ed=vd+(a<<2)|0)>>2]=zd+q[Ed>>2],(0|Bd)!=(0|(a=a+1|0)););if(td=w(q[wd>>2],td),(0|Gd)==(0|(yd=yd+1|0)))break}td=0}}}if(q[xd+32>>2]=td,q[xd+24>>2]=Id,q[xd+28>>2]=Hd,!((xd=xd+36|0)>>>0>>0))break}}(a),function(a){var dd,ed,fd,gd,Tc=x(0),Uc=0,Vc=0,Wc=0,Xc=0,Yc=0,Zc=x(0),_c=x(0),$c=x(0),ad=0,bd=0,cd=0;if(!(r[q[a>>2]+4|0]<4||(0|(Uc=q[a+588>>2]))<1))for(gd=(Wc=q[a+592>>2])+w(Uc,48)|0,dd=q[a+644>>2];;){if(a=q[Wc>>2],(bd=dd?1:q[a+20>>2])|(cd=dd?1:q[a+24>>2])){c:{d:{Yc=Wc,Xc=q[a+8>>2],Uc=q[a+12>>2],Tc=u[a+16>>2],a=(0|Xc)!=(0|Uc);e:{if(Tc!=x(0)){if(a=Uc+1|0,(0|Uc)==(0|Xc)){q[Wc+8>>2]=bd=1,Tc=x(x(1)-Tc),cd=1;break e}a=(0|a)==(0|Xc)?1:2}if(q[Yc+8>>2]=a,!cd)break d;a=Uc}u[Wc+24>>2]=Tc,u[Wc+20>>2]=x(1)-Tc;break c}cd=0,a=Uc}bd?(q[Wc+12>>2]=a,q[Wc+16>>2]=a+1):bd=0}else bd=cd=0;g:if((0|(ed=q[Wc+36>>2]))<1)$c=x(1);else{if(fd=q[Wc+40>>2],a=0,$c=x(1),!dd)for(;;){h:{i:{if(Uc=q[(a<<2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c=Wc+48|0)>>>0>>0))break}}(a),1<=(0|(Ea=q[a+4>>2])))for(Ea=(Aa=q[a+52>>2])+(Ea<<2)|0;_a=u[Aa>>2],u[Aa>>2]=_a>>0>>0;);!function(a){var Ce,De,Ee,Ae=0,Be=0;if(1<=(0|(Be=q[a+4>>2])))for(Ee=(Ae=q[a+8>>2])+w(Be,12)|0,a=Ce=q[a+40>>2];Be=0,q[Ae+8>>2]&&(De=q[Ae+4>>2],!q[(De<<2)+Ce>>2]&&-1!=(0|De)||(Be=!q[q[Ae>>2]+32>>2])),q[a>>2]=Be,a=a+4|0,(Ae=Ae+12|0)>>>0>>0;);}(a),function(a){var og,sg,tg,ug,vg,wg,xg,mg=0,ng=0,pg=0,qg=0,rg=0;if(1<=(0|(sg=q[a+4>>2])))for(ug=q[a+8>>2],tg=q[a>>2],vg=q[tg+724>>2];;){if(og=q[w(qg,12)+ug>>2],(q[og+28>>2]||q[og+24>>2])&&(q[(mg=qg<<2)+q[a+28>>2]>>2]=q[og+12>>2],q[og+24>>2])&&!((0|(pg=q[og+12>>2]))<1))for(pg=(ng=q[og+16>>2])+(pg<<2)|0,wg=q[mg+vg>>2],mg=q[a+36>>2]+(rg<<2)|0,xg=q[tg+976>>2];q[mg>>2]=q[(q[ng>>2]+wg<<2)+xg>>2],mg=mg+4|0,(ng=ng+4|0)>>>0>>0;);if(q[og+28>>2]&&!((0|(mg=q[og+12>>2]))<1))for(pg=(ng=q[og+20>>2])+(mg<<2)|0,mg=q[a+32>>2]+(rg<<2)|0;q[mg>>2]=q[ng>>2],mg=mg+4|0,(ng=ng+4|0)>>>0>>0;);if(rg=q[og+8>>2]+rg|0,(0|sg)==(0|(qg=qg+1|0)))break}}(a),n[q[1816]](a+12|0,q[a+36>>2],q[a+44>>2],q[a+40>>2]),function(a){var ue,ve,we,xe,ye,ze,re=0,se=0,te=0;if(1<=(0|(te=q[a+304>>2])))for(we=(re=q[a+308>>2])+(te<<5)|0,xe=q[a+264>>2],ye=q[a+144>>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wf+1304>>2],Mf=q[wf+1300>>2],Nf=q[wf+1296>>2],Of=q[wf+1292>>2],Pf=q[wf+1288>>2];vf=Jf+q[yf>>2]<<2,q[Df>>2]=q[vf+Pf>>2],q[Ef>>2]=q[vf+Of>>2],q[Ff>>2]=q[vf+Nf>>2],q[Gf>>2]=q[vf+Mf>>2],q[uf>>2]=q[vf+Lf>>2],q[Bf>>2]=q[vf+Kf>>2],Bf=Bf+4|0,uf=uf+4|0,Gf=Gf+4|0,Ff=Ff+4|0,Ef=Ef+4|0,Df=Df+4|0,(yf=yf+4|0)>>>0>>0;);if(xf=q[zf+8>>2]+xf|0,(0|Cf)==(0|(Af=Af+1|0)))break}}(a),function(a){var wk,ok=0,pk=0,qk=0,rk=0,sk=0,tk=0,uk=0,vk=0,ok=a- -64|0;if(n[q[1815]](ok,q[a+88>>2],q[a+148>>2],q[a+144>>2]),n[q[1817]](ok,q[a+92>>2],q[a+152>>2],q[q[a>>2]+796>>2],2,q[a+144>>2]),!(r[q[a>>2]+4|0]<4||(n[q[1815]](ok,q[a+96>>2],q[a+120>>2],q[a+144>>2]),n[q[1815]](ok,q[a+100>>2],q[a+124>>2],q[a+144>>2]),n[q[1815]](ok,q[a+104>>2],q[a+128>>2],q[a+144>>2]),n[q[1815]](ok,q[a+108>>2],q[a+132>>2],q[a+144>>2]),n[q[1815]](ok,q[a+112>>2],q[a+136>>2],q[a+144>>2]),n[q[1815]](ok,q[a+116>>2],q[a+140>>2],q[a+144>>2]),(0|(tk=q[a+56>>2]))<1))){for(uk=q[a+128>>2],vk=q[a+124>>2],wk=q[a+120>>2],pk=q[a+156>>2],ok=0;q[(qk=rk<<2)+pk>>2]=q[(sk=ok<<2)+wk>>2],q[pk+(4|qk)>>2]=q[sk+vk>>2],q[pk+(8|qk)>>2]=q[sk+uk>>2],rk=rk+4|0,(0|tk)!=(0|(ok=ok+1|0)););for(pk=q[a+160>>2],sk=q[a+140>>2],uk=q[a+136>>2],vk=q[a+132>>2],ok=a=0;q[(rk=a<<2)+pk>>2]=q[(qk=ok<<2)+vk>>2],q[pk+(4|rk)>>2]=q[qk+uk>>2],q[pk+(8|rk)>>2]=q[qk+sk>>2],a=a+4|0,(0|tk)!=(0|(ok=ok+1|0)););}}(a),function(a){var nk,fk=0,gk=0,hk=0,ik=0,jk=0,kk=0,lk=0,mk=0,fk=a+172|0;if(n[q[1815]](fk,q[a+196>>2],q[a+268>>2],q[a+264>>2]),n[q[1815]](fk,q[a+200>>2],q[a+284>>2],q[a+264>>2]),n[q[1815]](fk,q[a+204>>2],q[a+276>>2],q[a+264>>2]),n[q[1815]](fk,q[a+208>>2],q[a+280>>2],q[a+264>>2]),n[q[1815]](fk,q[a+212>>2],q[a+272>>2],q[a+264>>2]),!(r[q[a>>2]+4|0]<4||(n[q[1815]](fk,q[a+216>>2],q[a+240>>2],q[a+264>>2]),n[q[1815]](fk,q[a+220>>2],q[a+244>>2],q[a+264>>2]),n[q[1815]](fk,q[a+224>>2],q[a+248>>2],q[a+264>>2]),n[q[1815]](fk,q[a+228>>2],q[a+252>>2],q[a+264>>2]),n[q[1815]](fk,q[a+232>>2],q[a+256>>2],q[a+264>>2]),n[q[1815]](fk,q[a+236>>2],q[a+260>>2],q[a+264>>2]),(0|(kk=q[a+164>>2]))<1))){for(lk=q[a+248>>2],mk=q[a+244>>2],nk=q[a+240>>2],gk=q[a+296>>2],fk=0;q[(hk=ik<<2)+gk>>2]=q[(jk=fk<<2)+nk>>2],q[gk+(4|hk)>>2]=q[jk+mk>>2],q[gk+(8|hk)>>2]=q[jk+lk>>2],ik=ik+4|0,(0|kk)!=(0|(fk=fk+1|0)););for(gk=q[a+300>>2],jk=q[a+260>>2],lk=q[a+256>>2],mk=q[a+252>>2],fk=a=0;q[(ik=a<<2)+gk>>2]=q[(hk=fk<<2)+mk>>2],q[gk+(4|ik)>>2]=q[hk+lk>>2],q[gk+(8|ik)>>2]=q[hk+jk>>2],a=a+4|0,(0|kk)!=(0|(fk=fk+1|0)););}}(a),function(a){var oe,pe,qe,le=0,me=0,ne=0;if(1<=(0|(me=q[a+332>>2])))for(oe=(le=q[a+336>>2])+w(me,20)|0,pe=q[a+312>>2],qe=q[a+40>>2],a=q[a+424>>2];me=0,q[le+12>>2]&&(ne=q[le+4>>2],q[(ne<<2)+qe>>2]||-1==(0|ne))&&(ne=q[le+8>>2],q[(ne<<2)+pe>>2]||-1==(0|ne))&&(me=!q[q[le>>2]+32>>2]),q[a>>2]=me,a=a+4|0,(le=le+20|0)>>>0>>0;);}(a),function(a){var mf,nf,of,pf,qf,rf,sf,tf,Ye=0,Ze=0,_e=0,$e=0,af=0,bf=0,cf=0,df=0,ef=0,ff=0,gf=0,hf=0,jf=0,kf=0,lf=0,$e=q[a>>2];if(1<=(0|(ff=q[a+332>>2]))){for(gf=q[a+336>>2],hf=q[$e+1052>>2],jf=q[$e+856>>2];;){if(Ye=q[gf+w(cf,20)>>2],(q[Ye+28>>2]||q[Ye+24>>2])&&(q[(Ze=cf<<2)+q[a+356>>2]>>2]=q[Ye+12>>2],q[Ye+24>>2])&&!((0|(af=q[Ye+12>>2]))<1))for(kf=(_e=q[Ye+16>>2])+(af<<2)|0,lf=q[Ze+jf>>2],Ze=(bf=df<<2)+q[a+372>>2]|0,af=bf+q[a+364>>2]|0,bf=bf+q[a+368>>2]|0;ef=lf+q[_e>>2]<<2,q[Ze>>2]=hf+(q[ef+q[$e+1040>>2]>>2]<<2),q[af>>2]=q[ef+q[$e+1032>>2]>>2],q[bf>>2]=q[ef+q[$e+1036>>2]>>2],bf=bf+4|0,af=af+4|0,Ze=Ze+4|0,(_e=_e+4|0)>>>0>>0;);if(q[Ye+28>>2]&&!((0|(Ze=q[Ye+12>>2]))<1))for(af=(_e=q[Ye+20>>2])+(Ze<<2)|0,Ze=q[a+360>>2]+(df<<2)|0;q[Ze>>2]=q[_e>>2],Ze=Ze+4|0,(_e=_e+4|0)>>>0>>0;);if(df=q[Ye+8>>2]+df|0,(0|ff)==(0|(cf=cf+1|0)))break}$e=q[a>>2]}if(!(r[$e+4|0]<4||(0|(jf=q[a+332>>2]))<1))for(kf=q[$e+864>>2],lf=q[a+336>>2],_e=df=0;;){if(cf=q[lf+w(_e,20)>>2],q[cf+24>>2]&&!((0|(Ye=q[cf+12>>2]))<1))for(mf=(Ze=q[cf+16>>2])+(Ye<<2)|0,nf=q[kf+(_e<<2)>>2],af=(Ye=df<<2)+q[a+376>>2]|0,bf=Ye+q[a+380>>2]|0,ef=Ye+q[a+384>>2]|0,ff=Ye+q[a+388>>2]|0,gf=Ye+q[a+392>>2]|0,hf=Ye+q[a+396>>2]|0,of=q[$e+1308>>2],pf=q[$e+1304>>2],qf=q[$e+1300>>2],rf=q[$e+1296>>2],sf=q[$e+1292>>2],tf=q[$e+1288>>2];Ye=q[Ze>>2]+nf<<2,q[af>>2]=q[Ye+tf>>2],q[bf>>2]=q[Ye+sf>>2],q[ef>>2]=q[Ye+rf>>2],q[ff>>2]=q[Ye+qf>>2],q[gf>>2]=q[Ye+pf>>2],q[hf>>2]=q[Ye+of>>2],hf=hf+4|0,gf=gf+4|0,ff=ff+4|0,ef=ef+4|0,bf=bf+4|0,af=af+4|0,(Ze=Ze+4|0)>>>0>>0;);if(df=q[cf+8>>2]+df|0,(0|jf)==(0|(_e=_e+1|0)))break}}(a),function(a){var ek,tj=0,vj=0,wj=0,$j=0,ak=0,bk=0,ck=0,dk=0,tj=a+340|0;if(n[q[1815]](tj,q[a+364>>2],q[a+448>>2],q[a+424>>2]),n[q[1816]](tj,q[a+368>>2],q[a+440>>2],q[a+424>>2]),n[q[1817]](tj,q[a+372>>2],q[a+444>>2],q[q[a>>2]+892>>2],2,q[a+424>>2]),!(r[q[a>>2]+4|0]<4||(n[q[1815]](tj,q[a+376>>2],q[a+400>>2],q[a+424>>2]),n[q[1815]](tj,q[a+380>>2],q[a+404>>2],q[a+424>>2]),n[q[1815]](tj,q[a+384>>2],q[a+408>>2],q[a+424>>2]),n[q[1815]](tj,q[a+388>>2],q[a+412>>2],q[a+424>>2]),n[q[1815]](tj,q[a+392>>2],q[a+416>>2],q[a+424>>2]),n[q[1815]](tj,q[a+396>>2],q[a+420>>2],q[a+424>>2]),(0|(bk=q[a+332>>2]))<1))){for(ck=q[a+408>>2],dk=q[a+404>>2],ek=q[a+400>>2],vj=q[a+452>>2],tj=0;q[(wj=$j<<2)+vj>>2]=q[(ak=tj<<2)+ek>>2],q[vj+(4|wj)>>2]=q[ak+dk>>2],q[vj+(8|wj)>>2]=q[ak+ck>>2],$j=$j+4|0,(0|bk)!=(0|(tj=tj+1|0)););for(vj=q[a+456>>2],ak=q[a+420>>2],ck=q[a+416>>2],dk=q[a+412>>2],tj=a=0;q[($j=a<<2)+vj>>2]=q[(wj=tj<<2)+dk>>2],q[vj+(4|$j)>>2]=q[wj+ck>>2],q[vj+(8|$j)>>2]=q[wj+ak>>2],a=a+4|0,(0|bk)!=(0|(tj=tj+1|0)););}}(a),function(a){var Oe,Se,Te,Ue,Ve,We,Xe,Me=0,Ne=0,Pe=0,Qe=0,Re=0;if(1<=(0|(Se=q[a+500>>2])))for(Ue=q[a+504>>2],Te=q[a>>2],Ve=q[Te+1252>>2];;){if(Oe=q[w(Qe,24)+Ue>>2],(q[Oe+28>>2]||q[Oe+24>>2])&&(q[(Me=Qe<<2)+q[a+524>>2]>>2]=q[Oe+12>>2],q[Oe+24>>2])&&!((0|(Pe=q[Oe+12>>2]))<1))for(Pe=(Ne=q[Oe+16>>2])+(Pe<<2)|0,We=q[Me+Ve>>2],Me=q[a+532>>2]+(Re<<2)|0,Xe=q[Te+1284>>2];q[Me>>2]=q[(q[Ne>>2]+We<<2)+Xe>>2],Me=Me+4|0,(Ne=Ne+4|0)>>>0>>0;);if(q[Oe+28>>2]&&!((0|(Me=q[Oe+12>>2]))<1))for(Pe=(Ne=q[Oe+20>>2])+(Me<<2)|0,Me=q[a+528>>2]+(Re<<2)|0;q[Me>>2]=q[Ne>>2],Me=Me+4|0,(Ne=Ne+4|0)>>>0>>0;);if(Re=q[Oe+8>>2]+Re|0,(0|Se)==(0|(Qe=Qe+1|0)))break}}(a),n[q[1815]](a+508|0,q[a+532>>2],q[a+536>>2],0),function(a){var Ck,Dk,Ek,Fk,Gk,Hk,xk=x(0),yk=0,zk=0,Ak=0,Bk=0;x(0);if(L=Ck=L-16|0,Ak=q[a>>2],!(r[Ak+4|0]<5||(0|(Bk=q[a+596>>2]))<1))for(Fk=(zk=q[a+600>>2])+w(Bk,12)|0,Gk=q[a+44>>2],Bk=q[Ak+976>>2];;){if(Ak=(q[zk>>2]<<2)+Gk|0,xk=x(q[Ak>>2]),1<=(0|(yk=q[zk+4>>2])))for(Hk=(a=q[zk+8>>2])+w(yk,48)|0;(yk=q[a+8>>2])&&((Dk=yk+-1|0)>>>0<=1?(yk=q[a+4>>2],Ek=u[Bk+(yk+q[a+12>>2]<<2)>>2],xk=x(Dk-1?xk+x(u[a+44>>2]*x(Ek*u[a+20>>2])):xk+x(u[a+44>>2]*x(x(Ek*u[a+20>>2])+x(u[Bk+(yk+q[a+16>>2]<<2)>>2]*u[a+24>>2]))))):(q[Ck>>2]=yk,Y(4,1024,Ck))),(a=a+48|0)>>>0>>0;);if(xk=(xk=x(xk+x(.0010000000474974513)))>2]=a,!((zk=zk+12|0)>>>0>>0))break}L=16+Ck|0}(a),function(a){var kj,lj,mj,nj,oj,pj,qj,rj,sj,cj=0,ej=0,gj=0,hj=0,ij=0,jj=x(0);if(L=kj=L-16|0,cj=q[a>>2],!(r[cj+4|0]<4||(va(a,q[a+604>>2],q[a+608>>2],q[cj+984>>2],q[a+152>>2],q[cj+796>>2]),ej=q[a>>2],r[ej+4|0]<5))){if(gj=q[a+608>>2],oj=q[ej+992>>2],pj=q[ej+988>>2],1<=(0|(cj=q[a+604>>2]))){for(qj=w(cj,12)+gj|0,rj=q[a+148>>2],lj=q[ej+980>>2];;){if(mj=(q[gj>>2]<<2)+rj|0,ij=q[mj>>2],1<=(0|(hj=q[gj+4>>2])))for(sj=(cj=q[gj+8>>2])+w(hj,48)|0;(hj=q[cj+8>>2])&&((nj=hj+-1|0)>>>0<=1?(hj=q[cj+4>>2],jj=u[(hj+q[cj+12>>2]<<2)+lj>>2],j(x(nj-1?x(u[cj+44>>2]*x(jj*u[cj+20>>2]))+(f(0,ij),k()):x(u[cj+44>>2]*x(x(jj*u[cj+20>>2])+x(u[(hj+q[cj+16>>2]<<2)+lj>>2]*u[cj+24>>2])))+(f(0,ij),k()))),ij=b[0]):(q[kj>>2]=hj,Y(4,1024,kj))),(cj=cj+48|0)>>>0>>0;);if(f(0,ij),jj=k(),u[mj>>2]=jj>>0>>0))break}gj=q[a+608>>2],cj=q[a+604>>2]}fa(cj,gj,pj,q[ej+1288>>2],q[ej+1292>>2],q[ej+1296>>2],q[a+156>>2]),fa(q[a+604>>2],q[a+608>>2],oj,q[ej+1300>>2],q[ej+1304>>2],q[ej+1308>>2],q[a+160>>2])}L=16+kj|0}(a),function(a){var yi,ri=0,si=0,ti=0,ui=0,vi=0,wi=x(0),xi=0,zi=0,Ai=0,Bi=0,Ci=0,Di=0,Ei=0,Fi=0;if(L=yi=L-80|0,vi=q[a>>2],!(r[vi+4|0]<5)){if(Di=q[vi+1028>>2],Ei=q[vi+1024>>2],ti=si=q[a+616>>2],!((0|(ri=q[a+612>>2]))<1)){for(zi=w(ri,12)+si|0,Ai=q[a+276>>2],xi=q[vi+1004>>2];;){if(Bi=Ai+(q[si>>2]<<2)|0,ti=q[Bi>>2],1<=(0|(ui=q[si+4>>2])))for(Fi=(ri=q[si+8>>2])+w(ui,48)|0;(ui=q[ri+8>>2])&&((Ci=ui+-1|0)>>>0<=1?(ui=q[ri+4>>2],wi=u[xi+(ui+q[ri+12>>2]<<2)>>2],j(x(Ci-1?x(u[ri+44>>2]*x(wi*u[ri+20>>2]))+(f(0,ti),k()):x(u[ri+44>>2]*x(x(wi*u[ri+20>>2])+x(u[xi+(ui+q[ri+16>>2]<<2)>>2]*u[ri+24>>2])))+(f(0,ti),k()))),ti=b[0]):(q[64+yi>>2]=ui,Y(4,1024,64+yi|0))),(ri=ri+48|0)>>>0>>0;);if(q[Bi>>2]=ti,!((si=si+12|0)>>>0>>0))break}if(ti=si=q[a+616>>2],!((0|(ri=q[a+612>>2]))<1)){for(zi=w(ri,12)+si|0,Ai=q[a+280>>2],xi=q[q[a>>2]+1008>>2];;){if(Bi=Ai+(q[si>>2]<<2)|0,ti=q[Bi>>2],1<=(0|(ui=q[si+4>>2])))for(Fi=(ri=q[si+8>>2])+w(ui,48)|0;(ui=q[ri+8>>2])&&((Ci=ui+-1|0)>>>0<=1?(ui=q[ri+4>>2],wi=u[xi+(ui+q[ri+12>>2]<<2)>>2],j(x(Ci-1?x(u[ri+44>>2]*x(wi*u[ri+20>>2]))+(f(0,ti),k()):x(u[ri+44>>2]*x(x(wi*u[ri+20>>2])+x(u[xi+(ui+q[ri+16>>2]<<2)>>2]*u[ri+24>>2])))+(f(0,ti),k()))),ti=b[0]):(q[48+yi>>2]=ui,Y(4,1024,48+yi|0))),(ri=ri+48|0)>>>0>>0;);if(q[Bi>>2]=ti,!((si=si+12|0)>>>0>>0))break}if(ti=si=q[a+616>>2],!((0|(ri=q[a+612>>2]))<1)){for(zi=w(ri,12)+si|0,Ai=q[a+268>>2],xi=q[q[a>>2]+996>>2];;){if(Bi=Ai+(q[si>>2]<<2)|0,ti=q[Bi>>2],1<=(0|(ui=q[si+4>>2])))for(Fi=(ri=q[si+8>>2])+w(ui,48)|0;(ui=q[ri+8>>2])&&((Ci=ui+-1|0)>>>0<=1?(ui=q[ri+4>>2],wi=u[xi+(ui+q[ri+12>>2]<<2)>>2],j(x(Ci-1?x(u[ri+44>>2]*x(wi*u[ri+20>>2]))+(f(0,ti),k()):x(u[ri+44>>2]*x(x(wi*u[ri+20>>2])+x(u[xi+(ui+q[ri+16>>2]<<2)>>2]*u[ri+24>>2])))+(f(0,ti),k()))),ti=b[0]):(q[32+yi>>2]=ui,Y(4,1024,32+yi|0))),(ri=ri+48|0)>>>0>>0;);if(f(0,ti),wi=k(),u[Bi>>2]=wi>>0>>0))break}ri=q[a+612>>2],ti=q[a+616>>2]}}}if(fa(ri,ti,Ei,q[vi+1288>>2],q[vi+1292>>2],q[vi+1296>>2],q[a+296>>2]),fa(q[a+612>>2],q[a+616>>2],Di,q[vi+1300>>2],q[vi+1304>>2],q[vi+1308>>2],q[a+300>>2]),!((0|(ri=q[a+612>>2]))<1)){for(ui=(si=q[a+616>>2])+w(ri,12)|0,Di=q[a+284>>2],vi=q[q[a>>2]+1e3>>2];;){if(Ei=Di+(q[si>>2]<<2)|0,ti=q[Ei>>2],1<=(0|(xi=q[si+4>>2])))for(zi=(ri=q[si+8>>2])+w(xi,48)|0;(xi=q[ri+8>>2])&&((Ai=xi+-1|0)>>>0<=1?(xi=q[ri+4>>2],wi=u[vi+(xi+q[ri+12>>2]<<2)>>2],j(x(Ai-1?x(u[ri+44>>2]*x(wi*u[ri+20>>2]))+(f(0,ti),k()):x(u[ri+44>>2]*x(x(wi*u[ri+20>>2])+x(u[vi+(xi+q[ri+16>>2]<<2)>>2]*u[ri+24>>2])))+(f(0,ti),k()))),ti=b[0]):(q[16+yi>>2]=xi,Y(4,1024,16+yi|0))),(ri=ri+48|0)>>>0>>0;);if(f(0,ti),wi=k(),u[Ei>>2]=wi>>0>>0))break}if(!((0|(ri=q[a+612>>2]))<1))for(xi=(si=q[a+616>>2])+w(ri,12)|0,ui=q[a+272>>2],a=q[q[a>>2]+1012>>2];;){if(Di=ui+(q[si>>2]<<2)|0,ti=q[Di>>2],1<=(0|(vi=q[si+4>>2])))for(Ei=(ri=q[si+8>>2])+w(vi,48)|0;(vi=q[ri+8>>2])&&((zi=vi+-1|0)>>>0<=1?(vi=q[ri+4>>2],wi=u[a+(vi+q[ri+12>>2]<<2)>>2],j(x(zi-1?x(u[ri+44>>2]*x(wi*u[ri+20>>2]))+(f(0,ti),k()):x(u[ri+44>>2]*x(x(wi*u[ri+20>>2])+x(u[a+(vi+q[ri+16>>2]<<2)>>2]*u[ri+24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var fb,gb,hb,jb,kb,cb,db,ab=0,bb=0,eb=0,ib=0;if(L=cb=L-32|0,1<=(0|Wa))for(kb=w(Wa,12)+Xa|0;;){if(!((0|(ab=q[Xa+4>>2]))<1))if(fb=(Wa=q[Xa+8>>2])+w(ab,48)|0,ab=q[Xa>>2]<<2,1<=(0|(db=q[ab+$a>>2])))for(db<<=1,gb=q[q[a>>2]+1052>>2],hb=q[Za+ab>>2];;){b:if(ab=q[Wa+8>>2]){c:{if((bb=ab+-1|0)>>>0<=1){if(ab=(q[Wa+4>>2]<<2)+Ya|0,ib=(q[ab+(q[Wa+12>>2]<<2)>>2]<<2)+gb|0,bb-1)break c;for(eb=(q[ab+(q[Wa+16>>2]<<2)>>2]<<2)+gb|0,ab=0;u[(jb=(bb=ab<<2)+hb|0)>>2]=u[jb>>2]+x(u[Wa+44>>2]*x(x(u[bb+ib>>2]*u[Wa+20>>2])+x(u[bb+eb>>2]*u[Wa+24>>2]))),(0|db)!=(0|(ab=ab+1|0)););break b}q[cb>>2]=ab,Y(4,1024,cb);break b}for(ab=0;u[(eb=(bb=ab<<2)+hb|0)>>2]=u[eb>>2]+x(u[Wa+44>>2]*x(u[bb+ib>>2]*u[Wa+20>>2])),(0|db)!=(0|(ab=ab+1|0)););}if(!((Wa=Wa+48|0)>>>0>>0))break}else for(;3<=(ab=q[Wa+8>>2])>>>0&&(q[16+cb>>2]=ab,Y(4,1024,16+cb|0)),(Wa=Wa+48|0)>>>0>>0;);if(!((Xa=Xa+12|0)>>>0>>0))break}L=32+cb|0}function wa(a,Wa,Xa){var Ya;Wa|=0,Xa|=0,L=Ya=L+-64|0;a:{if(a|=0)if(Wa)if((Wa+15&-16)!=(0|Wa))q[52+Ya>>2]=1522,q[48+Ya>>2]=2361,Y(4,1294,48+Ya|0);else{if(Wa=function(a,Gl,Hl){var lm,Zl=0,fm=0,gm=0,mm=0,nm=0,om=0,pm=0,qm=0,rm=0,sm=0,tm=0,um=0,vm=0,wm=x(0),xm=0,ym=0,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fm+q[132+lm>>2],q[Zl+96>>2]=fm+q[136+lm>>2],q[Zl+100>>2]=fm+q[140+lm>>2],q[Zl+104>>2]=fm+q[144+lm>>2],q[Zl+108>>2]=fm+q[148+lm>>2],q[Zl+112>>2]=fm+q[152+lm>>2],q[Zl+116>>2]=fm+q[156+lm>>2],q[Zl+120>>2]=fm+q[160+lm>>2],q[Zl+124>>2]=fm+q[164+lm>>2],q[Zl+128>>2]=fm+q[168+lm>>2],q[Zl+132>>2]=fm+q[172+lm>>2],q[Zl+136>>2]=fm+q[176+lm>>2],q[Zl+140>>2]=fm+q[180+lm>>2],q[Zl+168>>2]=fm+q[184+lm>>2],q[Zl+264>>2]=fm+q[188+lm>>2],q[Zl+268>>2]=fm+q[192+lm>>2],q[Zl+272>>2]=fm+q[196+lm>>2],q[Zl+276>>2]=fm+q[200+lm>>2],q[Zl+280>>2]=fm+q[204+lm>>2],q[Zl+284>>2]=fm+q[208+lm>>2],q[Zl+288>>2]=fm+q[212+lm>>2],q[Zl+292>>2]=fm+q[216+lm>>2],q[Zl+296>>2]=fm+q[220+lm>>2],q[Zl+300>>2]=fm+q[224+lm>>2],q[Zl+176>>2]=fm+q[228+lm>>2],q[Zl+184>>2]=fm+q[232+lm>>2],q[Zl+188>>2]=fm+q[236+lm>>2],q[Zl+192>>2]=fm+q[240+lm>>2],q[Zl+196>>2]=fm+q[244+lm>>2],q[Zl+200>>2]=fm+q[248+lm>>2],q[Zl+204>>2]=fm+q[252+lm>>2],q[Zl+208>>2]=fm+q[256+lm>>2],q[Zl+212>>2]=fm+q[260+lm>>2],q[Zl+216>>2]=fm+q[264+lm>>2],q[Zl+220>>2]=fm+q[268+lm>>2],q[Zl+224>>2]=fm+q[272+lm>>2],q[Zl+228>>2]=fm+q[276+lm>>2],q[Zl+232>>2]=fm+q[280+lm>>2],q[Zl+236>>2]=fm+q[284+lm>>2],q[Zl+240>>2]=fm+q[288+lm>>2],q[Zl+244>>2]=fm+q[292+lm>>2],q[Zl+248>>2]=fm+q[296+lm>>2],q[Zl+252>>2]=fm+q[300+lm>>2],q[Zl+256>>2]=fm+q[304+lm>>2],q[Zl+260>>2]=fm+q[308+lm>>2],Gl=q[a+704>>2],q[Zl+336>>2]=fm+q[312+lm>>2],q[Zl+424>>2]=fm+q[316+lm>>2],q[Zl+432>>2]=fm+q[320+lm>>2],q[Zl+436>>2]=fm+q[324+lm>>2],q[Zl+440>>2]=fm+q[328+lm>>2],Hl=fm+q[332+lm>>2]|0,q[Zl+444>>2]=Hl,!((0|(mm=q[Gl+16>>2]))<1)&&(gm=fm+q[336+lm>>2]|0,q[Hl>>2]=gm,(Hl=1)!=(0|mm)))for(Gl=0;gm=(15+(q[q[a+892>>2]+(Gl<<2)>>2]<<3)&-16)+gm|0,q[q[Zl+444>>2]+(Hl<<2)>>2]=gm,(0|mm)!=(0|(Hl=(Gl=Hl)+1|0)););if(q[Zl+448>>2]=fm+q[340+lm>>2],q[Zl+452>>2]=fm+q[344+lm>>2],q[Zl+456>>2]=fm+q[348+lm>>2],q[Zl+460>>2]=fm+q[352+lm>>2],q[Zl+464>>2]=fm+q[356+lm>>2],q[Zl+468>>2]=fm+q[360+lm>>2],q[Zl+472>>2]=fm+q[364+lm>>2],q[Zl+476>>2]=fm+q[368+lm>>2],q[Zl+344>>2]=fm+q[372+lm>>2],q[Zl+352>>2]=fm+q[376+lm>>2],q[Zl+356>>2]=fm+q[380+lm>>2],q[Zl+360>>2]=fm+q[384+lm>>2],q[Zl+364>>2]=fm+q[388+lm>>2],q[Zl+368>>2]=fm+q[392+lm>>2],q[Zl+372>>2]=fm+q[396+lm>>2],q[Zl+376>>2]=fm+q[400+lm>>2],q[Zl+380>>2]=fm+q[404+lm>>2],q[Zl+384>>2]=fm+q[408+lm>>2],q[Zl+388>>2]=fm+q[412+lm>>2],q[Zl+392>>2]=fm+q[416+lm>>2],q[Zl+396>>2]=fm+q[420+lm>>2],q[Zl+400>>2]=fm+q[424+lm>>2],q[Zl+404>>2]=fm+q[428+lm>>2],q[Zl+408>>2]=fm+q[432+lm>>2],q[Zl+412>>2]=fm+q[436+lm>>2],q[Zl+416>>2]=fm+q[440+lm>>2],q[Zl+420>>2]=fm+q[444+lm>>2],Gl=q[448+lm>>2],Hl=q[452+lm>>2],q[Zl+552>>2]=fm+q[456+lm>>2],q[Zl+548>>2]=Hl+fm,q[Zl+544>>2]=Gl+fm,q[Zl+560>>2]=fm+q[460+lm>>2],Gl=q[a+704>>2],pm=fm+q[464+lm>>2]|0,q[Zl+568>>2]=pm,1<=(0|(om=q[Gl+48>>2])))for(gm=fm+q[468+lm>>2]|0,Gl=fm+q[472+lm>>2]|0,nm=fm+q[476+lm>>2]|0,qm=q[a+1072>>2],Hl=0;mm=pm+w(Hl,36)|0,q[mm+20>>2]=nm,q[mm+16>>2]=Gl,q[mm>>2]=gm,gm=((mm=q[qm+(Hl<<2)>>2])<<2)+gm|0,nm=(mm=1<>2],mm=fm+q[516+lm>>2]|0,q[Zl+484>>2]=mm,1<=(0|(Gl=q[Gl+72>>2])))for(gm=fm+q[520+lm>>2]|0,nm=q[a+1212>>2],Hl=0;q[12+(mm+w(Hl,28)|0)>>2]=gm,gm=(q[nm+(Hl<<2)>>2]<<4)+gm|0,(0|Gl)!=(0|(Hl=Hl+1|0)););q[Zl+488>>2]=fm+q[524+lm>>2],q[Zl+492>>2]=fm+q[528+lm>>2],q[Zl+496>>2]=fm+q[532+lm>>2],q[Zl+504>>2]=fm+q[536+lm>>2],q[Zl+536>>2]=fm+q[540+lm>>2],q[Zl+512>>2]=fm+q[544+lm>>2],q[Zl+520>>2]=fm+q[548+lm>>2],q[Zl+524>>2]=fm+q[552+lm>>2],q[Zl+528>>2]=fm+q[556+lm>>2],q[Zl+532>>2]=fm+q[560+lm>>2];c:{if(4<=(om=r[a+4|0])>>>0){if(q[Zl+576>>2]=fm+q[480+lm>>2],q[Zl+584>>2]=fm+q[484+lm>>2],Gl=q[a+704>>2],Hl=q[492+lm>>2],mm=fm+q[488+lm>>2]|0,q[Zl+592>>2]=mm,1<=(0|(Gl=q[Gl+104>>2])))for(gm=Hl+fm|0,nm=q[a+1104>>2],Hl=0;q[40+(mm+w(Hl,48)|0)>>2]=gm,gm=(q[nm+(Hl<<2)>>2]<<2)+gm|0,(0|Gl)!=(0|(Hl=Hl+1|0)););q[Zl+608>>2]=fm+q[500+lm>>2],q[Zl+624>>2]=fm+q[508+lm>>2]}else{if(Gl=q[572+lm>>2],Hl=q[568+lm>>2],q[Zl+636>>2]=fm+q[564+lm>>2],q[Zl+640>>2]=Hl+fm,q[q[a+704>>2]+20>>2]<1)break c;for(mm=Gl+fm|0,pm=0;;){e:{if((0|(gm=q[(Gl=pm<<2)+q[a+952>>2]>>2]))<=0)Gl=Gl+q[Zl+636>>2]|0;else{for(nm=gm+(Hl=q[Gl+q[a+948>>2]>>2])|0,qm=q[a+1060>>2],gm=0;gm=q[qm+(Hl<<2)>>2]+gm|0,(0|(Hl=Hl+1|0))<(0|nm););if(Gl=Gl+q[Zl+636>>2]|0,Hl=mm,gm)break e}Hl=gm=0}if(q[Gl>>2]=Hl,mm=(gm<<2)+mm|0,!((0|(pm=pm+1|0))>2]+20>>2]))break}}om>>>0<5||(q[Zl+600>>2]=fm+q[496+lm>>2],q[Zl+616>>2]=fm+q[504+lm>>2],q[Zl+632>>2]=fm+q[512+lm>>2])}q[Zl+644>>2]=1,q[Zl>>2]=a,q[Zl+648>>2]=1&o[q[a+708>>2]+20|0],fm=q[a+704>>2],pm=q[fm+20>>2];g:if(!((0|(q[Zl+540>>2]=pm))<1)){if(Gl=pm+-1|0,qm=q[a+952>>2],rm=q[a+940>>2],sm=q[a+932>>2],tm=q[a+936>>2],um=q[a+924>>2],vm=q[a+928>>2],xm=q[Zl+552>>2],zm=q[Zl+544>>2],om>>>0<4)for(;;)if(Hl=zm+w(Gl,52)|0,gm=(mm=Gl<<2)+vm|(q[Hl>>2]=0),q[Hl+4>>2]=q[gm>>2],q[Hl+8>>2]=q[(nm=mm+um|0)>>2],u[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=1065353216,q[rm+4>>2]=1065353216,q[gm+om>>2]=0,q[gm+qm>>2]=1065353216,q[(Hl=Hl+gm|0)>>2]=0,q[Hl+4>>2]=0,Hl=Gl,0<(0|(nm=nm+-1|0)););}else q[Zl+340>>2]=nm,q[Zl+348>>2]=0;if(nm=q[fm+72>>2],1<=(0|(q[Zl+480>>2]=nm)))for(qm=q[mm+1208>>2],rm=q[mm+1224>>2],sm=q[mm+1220>>2],tm=q[mm+1216>>2],um=q[mm+1212>>2],vm=q[Zl+484>>2],gm=0;;){if(Gl=vm+w(gm,28)|0,pm=q[(Hl=gm<<2)+um>>2],q[Gl+4>>2]=pm,q[Gl>>2]=q[Hl+tm>>2],om=q[Hl+sm>>2],q[Gl+16>>2]=om,xm=q[Hl+rm>>2],q[Gl+20>>2]=xm,q[Gl+8>>2]=0,q[Gl+24>>2]=1+(om-xm|0),1<=(0|pm))for(xm=q[Hl+qm>>2],zm=q[Gl+12>>2],ym=q[mm+1236>>2],Bm=q[mm+1228>>2],Am=q[mm+1232>>2],Hl=0;q[4+(Gl=zm+(Hl<<4)|0)>>2]=q[(om=Hl+xm<<2)+Am>>2],q[Gl>>2]=q[om+Bm>>2],om=q[om+ym>>2],q[Gl+12>>2]=0,q[Gl+8>>2]=om,(0|pm)!=(0|(Hl=Hl+1|0)););if((0|nm)==(0|(gm=gm+1|0)))break}if(Hl=q[fm+80>>2],(0|(q[Zl+500>>2]=Hl))<1)gm=0;else{for(om=q[mm+1280>>2],qm=q[mm+1268>>2],rm=q[mm+1276>>2],sm=q[mm+1272>>2],tm=q[mm+1264>>2],um=q[mm+1260>>2],nm=q[mm+1248>>2],pm=q[Zl+568>>2],vm=q[Zl+504>>2];Gl=vm+w(Hl=Hl+-1|0,24)|0,q[Gl>>2]=pm+w(q[(gm=Hl<<2)+nm>>2],36),q[Gl+4>>2]=q[gm+um>>2],q[Gl+8>>2]=q[gm+tm>>2],q[Gl+12>>2]=q[gm+sm>>2],gm=q[gm+qm>>2],q[Gl+20>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2),(0|Gl)!=(0|(Hl=Hl+1|0)););}}}else if(!(q[fm+20>>2]<1))for(fm=0;;){if(gm=q[(pm=fm<<2)+q[Zl+636>>2]>>2],1<=((Gl=0)|(Hl=q[pm+q[mm+952>>2]>>2])))for(rm=Hl+(om=q[pm+q[mm+948>>2]>>2])|0,sm=q[mm+1060>>2],tm=q[mm+1056>>2];;){if(1<=(0|(qm=q[(Hl=om<<2)+sm>>2])))for(um=qm+(nm=q[Hl+tm>>2])|0,vm=q[mm+1192>>2];;){qm=gm+(Gl<<2)|0,wm=u[vm+(nm<<2)>>2],Hl=gm;q:{if(0<(0|Gl))for(;;){if(u[Hl>>2]==wm)break q;if(!((Hl=Hl+4|0)>>>0>>0))break}u[qm>>2]=wm,Gl=Gl+1|0}if(!((0|(nm=nm+1|0))<(0|um)))break}if(!((0|(om=om+1|0))<(0|rm)))break}if(function(a,rn){var sn,In,vn=0,wn=0,Hn=0;q[8+(L=sn=L-208|0)>>2]=1,q[12+sn>>2]=0;a:if(In=rn<<2){for(q[16+sn>>2]=4,Hn=rn=q[20+sn>>2]=4,vn=2;rn=(Hn+4|0)+(wn=rn)|0,q[(16+sn|0)+(vn<<2)>>2]=rn,vn=vn+1|0,Hn=wn,rn>>>0>>0;);if((wn=(a+In|0)-4|0)>>>0<=a>>>0)rn=vn=1;else for(rn=vn=1;rn=3==(3&vn)?(ta(a,rn,16+sn|0),ma(8+sn|0,2),rn+2|0):(t[(16+sn|0)+((Hn=rn+-1|0)<<2)>>2]>=wn-a>>>0?la(a,8+sn|0,rn,0,16+sn|0):ta(a,rn,16+sn|0),1==(0|rn)?(ka(8+sn|0,1),0):(ka(8+sn|0,Hn),1)),vn=1|q[8+sn>>2],q[8+sn>>2]=vn,(a=a+4|0)>>>0>>0;);for(la(a,8+sn|0,rn,0,16+sn|0);;){e:{f:{g:{if(!(1!=(0|rn)|1!=(0|vn))){if(q[12+sn>>2])break g;break a}if(1<(0|rn))break f}ma(8+sn|0,wn=Oa(8+sn|0)),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return L=576+lm|0,Zl}(a,Wa,Xa))break a;q[36+Ya>>2]=2209,q[32+Ya>>2]=2361,Y(4,1294,32+Ya|0)}else q[20+Ya>>2]=1444,q[16+Ya>>2]=2361,Y(4,1294,16+Ya|0);else q[4+Ya>>2]=2132,q[Ya>>2]=2361,Y(4,1294,Ya);Wa=0}return L=64+Ya|0,0|Wa}function xa(a){var Wa;return L=Wa=L-16|0,a=(a|=0)?function(a){var Gl;return ca(16+(L=Gl=L-576|0)|0,0,560),Fa(a,16+Gl|0,12+Gl|0),L=576+Gl|0,q[12+Gl>>2]}(a):(q[4+Wa>>2]=2132,q[Wa>>2]=2343,Y(4,1294,Wa),0),L=16+Wa|0,0|a}function ya(a){var Xa=r[a+4|0];X(q[a+704>>2],4,64),da(q[a+708>>2],4),da(q[a+708>>2]+4|0,4),da(q[a+708>>2]+8|0,4),da(q[a+708>>2]+12|0,4),da(q[a+708>>2]+16|0,4),da(q[a+708>>2]+20|0,1),X(q[a+720>>2],4,q[q[a+704>>2]>>2]),X(q[a+724>>2],4,q[q[a+704>>2]>>2]),X(q[a+728>>2],4,q[q[a+704>>2]>>2]),X(q[a+732>>2],4,q[q[a+704>>2]>>2]),X(q[a+736>>2],4,q[q[a+704>>2]>>2]),X(q[a+740>>2],4,q[q[a+704>>2]>>2]),X(q[a+752>>2],4,q[q[a+704>>2]+4>>2]),X(q[a+756>>2],4,q[q[a+704>>2]+4>>2]),X(q[a+760>>2],4,q[q[a+704>>2]+4>>2]),X(q[a+764>>2],4,q[q[a+704>>2]+4>>2]),X(q[a+768>>2],4,q[q[a+704>>2]+4>>2]),X(q[a+772>>2],4,q[q[a+704>>2]+4>>2]),X(q[a+776>>2],4,q[q[a+704>>2]+4>>2]),X(q[a+780>>2],4,q[q[a+704>>2]+8>>2]),X(q[a+784>>2],4,q[q[a+704>>2]+8>>2]),X(q[a+788>>2],4,q[q[a+704>>2]+8>>2]),X(q[a+796>>2],4,q[q[a+704>>2]+8>>2]),X(q[a+800>>2],4,q[q[a+704>>2]+8>>2]),X(q[a+804>>2],4,q[q[a+704>>2]+8>>2]),X(q[a+812>>2],4,q[q[a+704>>2]+12>>2]),X(q[a+816>>2],4,q[q[a+704>>2]+12>>2]),X(q[a+820>>2],4,q[q[a+704>>2]+12>>2]),X(q[a+828>>2],4,q[q[a+704>>2]+12>>2]),X(q[a+852>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+856>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+860>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+868>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+872>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+876>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+880>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+884>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+888>>2],1,q[q[a+704>>2]+16>>2]),X(q[a+892>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+896>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+900>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+904>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+908>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+912>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+924>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+928>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+932>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+936>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+940>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+948>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+952>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+976>>2],4,q[q[a+704>>2]+24>>2]),X(q[a+980>>2],4,q[q[a+704>>2]+28>>2]),X(q[a+984>>2],4,q[q[a+704>>2]+28>>2]),X(q[a+996>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1e3>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1004>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1008>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1012>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1016>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1020>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1032>>2],4,q[q[a+704>>2]+36>>2]),X(q[a+1036>>2],4,q[q[a+704>>2]+36>>2]),X(q[a+1040>>2],4,q[q[a+704>>2]+36>>2]),X(q[a+1052>>2],4,q[q[a+704>>2]+40>>2]),X(q[a+1064>>2],4,q[q[a+704>>2]+44>>2]),X(q[a+1068>>2],4,q[q[a+704>>2]+48>>2]),X(q[a+1072>>2],4,q[q[a+704>>2]+48>>2]),X(q[a+1056>>2],4,q[q[a+704>>2]+52>>2]),X(q[a+1060>>2],4,q[q[a+704>>2]+52>>2]),X(q[a+1192>>2],4,q[q[a+704>>2]+56>>2]),X(q[a+1196>>2],4,q[q[a+704>>2]+60>>2]),X(q[a+1200>>2],2,q[q[a+704>>2]+64>>2]),X(q[a+1204>>2],4,q[q[a+704>>2]+68>>2]),X(q[a+1208>>2],4,q[q[a+704>>2]+72>>2]),X(q[a+1212>>2],4,q[q[a+704>>2]+72>>2]),X(q[a+1216>>2],4,q[q[a+704>>2]+72>>2]),X(q[a+1220>>2],4,q[q[a+704>>2]+72>>2]),X(q[a+1224>>2],4,q[q[a+704>>2]+72>>2]),X(q[a+1228>>2],4,q[q[a+704>>2]+76>>2]),X(q[a+1232>>2],4,q[q[a+704>>2]+76>>2]),X(q[a+1236>>2],4,q[q[a+704>>2]+76>>2]),X(q[a+1248>>2],4,q[q[a+704>>2]+80>>2]),X(q[a+1252>>2],4,q[q[a+704>>2]+80>>2]),X(q[a+1256>>2],4,q[q[a+704>>2]+80>>2]),X(q[a+1260>>2],4,q[q[a+704>>2]+80>>2]),X(q[a+1264>>2],4,q[q[a+704>>2]+80>>2]),X(q[a+1268>>2],4,q[q[a+704>>2]+80>>2]),X(q[a+1272>>2],4,q[q[a+704>>2]+80>>2]),X(q[a+1276>>2],4,q[q[a+704>>2]+84>>2]),X(q[a+1280>>2],2,q[q[a+704>>2]+84>>2]),X(q[a+1284>>2],4,q[q[a+704>>2]+88>>2]),Xa>>>0<2||(X(q[a+808>>2],4,q[q[a+704>>2]+8>>2]),Xa>>>0<4)||(X(q[a+968>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+972>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+792>>2],4,q[q[a+704>>2]+8>>2]),X(q[a+824>>2],4,q[q[a+704>>2]+12>>2]),X(q[a+864>>2],4,q[q[a+704>>2]+16>>2]),X(q[a+1288>>2],4,q[q[a+704>>2]+92>>2]),X(q[a+1292>>2],4,q[q[a+704>>2]+92>>2]),X(q[a+1296>>2],4,q[q[a+704>>2]+92>>2]),X(q[a+1300>>2],4,q[q[a+704>>2]+96>>2]),X(q[a+1304>>2],4,q[q[a+704>>2]+96>>2]),X(q[a+1308>>2],4,q[q[a+704>>2]+96>>2]),X(q[a+944>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+956>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+960>>2],4,q[q[a+704>>2]+20>>2]),X(q[a+1076>>2],4,q[q[a+704>>2]+100>>2]),X(q[a+1080>>2],4,q[q[a+704>>2]+100>>2]),X(q[a+1084>>2],4,q[q[a+704>>2]+100>>2]),X(q[a+1088>>2],4,q[q[a+704>>2]+104>>2]),X(q[a+1092>>2],4,q[q[a+704>>2]+104>>2]),X(q[a+1096>>2],4,q[q[a+704>>2]+104>>2]),X(q[a+1100>>2],4,q[q[a+704>>2]+104>>2]),X(q[a+1104>>2],4,q[q[a+704>>2]+104>>2]),X(q[a+1120>>2],4,q[q[a+704>>2]+108>>2]),X(q[a+1124>>2],4,q[q[a+704>>2]+108>>2]),X(q[a+1128>>2],4,q[q[a+704>>2]+108>>2]),X(q[a+1144>>2],4,q[q[a+704>>2]+112>>2]),X(q[a+1148>>2],4,q[q[a+704>>2]+112>>2]),X(q[a+1152>>2],4,q[q[a+704>>2]+112>>2]),X(q[a+1168>>2],4,q[q[a+704>>2]+116>>2]),X(q[a+1172>>2],4,q[q[a+704>>2]+120>>2]),X(q[a+1176>>2],4,q[q[a+704>>2]+120>>2]),X(q[a+1180>>2],4,q[q[a+704>>2]+120>>2]),X(q[a+1184>>2],4,q[q[a+704>>2]+124>>2]),X(q[a+1188>>2],4,q[q[a+704>>2]+124>>2]),4!=(0|Xa)&&(X(q[a+988>>2],4,q[q[a+704>>2]+28>>2]),X(q[a+992>>2],4,q[q[a+704>>2]+28>>2]),X(q[a+1024>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1028>>2],4,q[q[a+704>>2]+32>>2]),X(q[a+1044>>2],4,q[q[a+704>>2]+36>>2]),X(q[a+1048>>2],4,q[q[a+704>>2]+36>>2]),X(q[a+1108>>2],4,q[q[a+704>>2]+128>>2]),X(q[a+1112>>2],4,q[q[a+704>>2]+128>>2]),X(q[a+1116>>2],4,q[q[a+704>>2]+128>>2]),X(q[a+1132>>2],4,q[q[a+704>>2]+132>>2]),X(q[a+1136>>2],4,q[q[a+704>>2]+132>>2]),X(q[a+1140>>2],4,q[q[a+704>>2]+132>>2]),X(q[a+1156>>2],4,q[q[a+704>>2]+136>>2]),X(q[a+1160>>2],4,q[q[a+704>>2]+136>>2]),X(q[a+1164>>2],4,q[q[a+704>>2]+136>>2])))}function za(a,Za){var $a=0,lb=0,mb=0,ob=0,pb=0,rb=0,nb=a+Za|0;a:{b:if(!(1&($a=q[a+4>>2]))){if(!(3&$a))break a;if(Za=($a=q[a>>2])+Za|0,(0|(a=a-$a|0))!=q[2100])if($a>>>0<=255)mb=$a>>>3,$a=q[a+8>>2],(0|(lb=q[a+12>>2]))==(0|$a)?(rb=q[2095]&fd(mb),q[2095]=rb):(q[$a+12>>2]=lb,q[lb+8>>2]=$a);else{if(pb=q[a+24>>2],(0|($a=q[a+12>>2]))!=(0|a))lb=q[a+8>>2],q[lb+12>>2]=$a,q[$a+8>>2]=lb;else if(mb=(mb=q[(lb=a+20|0)>>2])||q[(lb=a+16|0)>>2]){for(;ob=lb,(mb=q[(lb=($a=mb)+20|0)>>2])||(lb=$a+16|0,mb=q[$a+16>>2]););q[ob>>2]=0}else $a=0;if(pb){lb=q[a+28>>2];e:{if(q[(mb=8684+(lb<<2)|0)>>2]==(0|a)){if(q[mb>>2]=$a)break e;rb=q[2096]&fd(lb),q[2096]=rb;break b}if(!(q[pb+(q[pb+16>>2]==(0|a)?16:20)>>2]=$a))break b}q[$a+24>>2]=pb,(lb=q[a+16>>2])&&(q[$a+16>>2]=lb,q[lb+24>>2]=$a),(lb=q[a+20>>2])&&(q[$a+20>>2]=lb,q[lb+24>>2]=$a)}}else if(3==(3&($a=q[4+nb>>2])))return q[2097]=Za,q[4+nb>>2]=-2&$a,q[a+4>>2]=1|Za,q[nb>>2]=Za}f:{if(!(2&($a=q[4+nb>>2]))){if(q[2101]==(0|nb)){if(q[2101]=a,Za=q[2098]+Za|0,q[2098]=Za,q[a+4>>2]=1|Za,q[2100]!=(0|a))break a;return q[2097]=0,q[2100]=0}if(q[2100]==(0|nb))return q[2100]=a,Za=q[2097]+Za|0,q[2097]=Za,q[a+4>>2]=1|Za,q[a+Za>>2]=Za;Za=(-8&$a)+Za|0;g:if($a>>>0<=255)mb=$a>>>3,$a=q[8+nb>>2],(0|(lb=q[12+nb>>2]))==(0|$a)?(rb=q[2095]&fd(mb),q[2095]=rb):(q[$a+12>>2]=lb,q[lb+8>>2]=$a);else{if(pb=q[24+nb>>2],(0|nb)!=(0|($a=q[12+nb>>2])))lb=q[8+nb>>2],q[lb+12>>2]=$a,q[$a+8>>2]=lb;else if(mb=(mb=q[(lb=20+nb|0)>>2])||q[(lb=16+nb|0)>>2]){for(;ob=lb,(mb=q[(lb=($a=mb)+20|0)>>2])||(lb=$a+16|0,mb=q[$a+16>>2]););q[ob>>2]=0}else $a=0;if(pb){lb=q[28+nb>>2];j:{if(q[(mb=8684+(lb<<2)|0)>>2]==(0|nb)){if(q[mb>>2]=$a)break j;rb=q[2096]&fd(lb),q[2096]=rb;break g}if(!(q[pb+(q[pb+16>>2]==(0|nb)?16:20)>>2]=$a))break g}q[$a+24>>2]=pb,(lb=q[16+nb>>2])&&(q[$a+16>>2]=lb,q[lb+24>>2]=$a),(lb=q[20+nb>>2])&&(q[$a+20>>2]=lb,q[lb+24>>2]=$a)}}if(q[a+4>>2]=1|Za,q[a+Za>>2]=Za,q[2100]!=(0|a))break f;return q[2097]=Za}q[4+nb>>2]=-2&$a,q[a+4>>2]=1|Za,q[a+Za>>2]=Za}if(Za>>>0<=255)return Za=8420+(($a=Za>>>3)<<3)|0,$a=(lb=q[2095])&($a=1<<$a)?q[Za+8>>2]:(q[2095]=$a|lb,Za),q[Za+8>>2]=a,q[$a+12>>2]=a,q[a+12>>2]=Za,q[a+8>>2]=$a;q[a+16>>2]=0,$a=q[a+20>>2]=0,(mb=Za>>>8)&&($a=31,16777215>>0||($a=28+(($a=((nb=(mb<<=ob=mb+1048320>>>16&8)<<($a=mb+520192>>>16&4))<<(mb=245760+nb>>>16&2)>>>15)-(mb|$a|ob)|0)<<1|Za>>>$a+21&1)|0)),mb=8684+((q[(lb=a)+28>>2]=$a)<<2)|0;m:{if((lb=q[2096])&(ob=1<<$a)){for(lb=Za<<(31==(0|$a)?0:25-($a>>>1)|0),$a=q[mb>>2];;){if((-8&q[(mb=$a)+4>>2])==(0|Za))break m;if($a=lb>>>29,lb<<=1,!($a=q[16+(ob=mb+(4&$a)|0)>>2]))break}q[ob+16>>2]=a}else q[2096]=lb|ob,q[mb>>2]=a;return q[a+24>>2]=mb,q[a+12>>2]=a,q[a+8>>2]=a}Za=q[mb+8>>2],q[Za+12>>2]=a,q[mb+8>>2]=a,q[a+24>>2]=0,q[a+12>>2]=mb,q[a+8>>2]=Za}}function Aa(a){var vb,xb,yb,Ab,Bb,Cb,sb,wb,Za=x(0),tb=(x(0),0),ub=0,zb=(x(0),x(0),x(0),x(0),0);x(0),x(0);a:{b:{if(j(a),ub=2147483647&(tb=b[0])){if(!(ub>>>0<2139095041))return x(x(.10000000149011612)+a);if(1065353216==(0|ub))return x(-1<(0|tb)?.10000000149011612:10);if(2139095040==(0|ub))return x(-1<(0|tb)?0:-a);if(1073741824==(0|tb))return x(.010000000707805157);if(1056964608==(0|tb))return x(.3162277638912201);if(1291845633<=ub>>>0)return x((0|tb)<0?H:0);if(vb=u[1709],wb=x(x(1.600000023841858)-vb),xb=x(x(1)/x(vb+x(1.600000023841858))),f(0,-4096&(j(sb=x(wb*xb)),b[0])),Za=k(),yb=x(Za*Za),Bb=u[1713],vb=x(xb*x(x(wb-x((Ab=Za)*x(3.099609375)))-x(Za*x(x(1.600000023841858)-x(x(3.099609375)-vb))))),xb=x(x(sb+Za)*vb),Za=x(sb*sb),wb=x(xb+x(x(Za*Za)*x(x(Za*x(x(Za*x(x(Za*x(x(Za*x(x(Za*x(.20697501301765442))+x(.23066075146198273)))+x(.2727281153202057)))+x(.3333333432674408)))+x(.4285714328289032)))+x(.6000000238418579)))),f(0,-4096&(j(x(x(yb+x(3))+wb)),b[0])),Za=k(),xb=x(Ab*Za),sb=x(x(vb*Za)+x(sb*x(wb-x(x(Za+x(-3))-yb)))),f(0,-4096&(j(x(xb+sb)),b[0])),Za=k(),vb=x(Za*x(.9619140625)),yb=x(u[1711]+x(x(x(sb-x(Za-xb))*x(.9617967009544373))+x(Za*x(-.00011736857413779944)))),f(0,-4096&(j(x(x(Bb+x(vb+yb))+x(-4))),b[0])),sb=k(),f(0,-4096&tb),wb=k(),Za=x(sb*wb),a=x(x(x(yb-x(x(x(sb-x(-4))-Bb)-vb))*a)+x(x(a-wb)*sb)),j(sb=x(Za+a)),1124073473<=(0|(tb=b[0])))break b;d:{if((ub=1124073472)==(0|tb)){if(x(a+x(4.299566569443414e-8))>x(sb-Za))break b}else{if(ub=2147483647&tb,!(a<=x(sb-Za)^1|-1021968384!=(0|tb))|1125515265<=ub>>>0)break a;if(ub>>>0<1056964609)break d}zb=(8388607&(ub=(8388608>>>(ub>>>23)-126)+tb|0)|8388608)>>>150-(Cb=ub>>>23&255),zb=(0|tb)<0?0-zb|0:zb,Za=x(Za-(f(0,ub&-8388608>>Cb-127),k())),j(x(a+Za)),tb=b[0]}f(0,-32768&tb),sb=k(),vb=x(sb*x(.693145751953125)),sb=x(x(sb*x(14286065379565116e-22))+x(x(a-x(sb-Za))*x(.6931471824645996))),a=x(vb+sb),Za=x(a*a),Za=x(a-x(Za*x(x(Za*x(x(Za*x(x(Za*x(x(Za*x(4.138136944220605e-8))+x(-16533901998627698e-22)))+x(661375597701408e-19)))+x(-.0027777778450399637)))+x(.1666666716337204)))),Ab=x(x(a*Za)/x(Za+x(-2))),Za=x(sb-x(a-vb)),a=(0|(tb=0|(j(a=x(x(a-x(Ab-x(Za+x(a*Za))))+x(1))),b[0]+(zb<<23))))<=8388607?function(a,Tk){var vl=0;return 128<=(0|Tk)?(a=x(a*x(17014118346046923e22)),Tk=(0|(vl=Tk+-127|0))<128?vl:(a=x(a*x(17014118346046923e22)),((0|Tk)<381?Tk:381)+-254|0)):-127<(0|Tk)||(a=x(a*x(11754943508222875e-54)),Tk=-127<(0|(vl=Tk+126|0))?vl:(a=x(a*x(11754943508222875e-54)),(-378<(0|Tk)?Tk:-378)+252|0)),x(a*(f(0,1065353216+(Tk<<23)|0),k()))}(a,zb):(f(0,tb),k()),a=x(x(1)*a)}else a=x(1);return a}return x(H)}return x(0)}function Ba(a,Db){var Jb,Eb,Gb,Fb=0,Hb=0,Ib=x(0);if(j(Db),!((Gb=2147483647&(Eb=b[0]))>>>0<=2139095040&&(j(a),(Fb=2147483647&(Hb=b[0]))>>>0<2139095041)))return x(a+Db);if(1065353216==(0|Eb))return Ca(a);Eb=(Jb=Eb>>>30&2)|Hb>>>31;b:{c:{d:{e:{if(!Fb){switch(Eb-2|0){case 0:break e;case 1:break;default:break d}return x(-3.1415927410125732)}if(2139095040!=(0|Gb)){if(!Gb|!(Fb>>>0<=218103808+Gb>>>0&&2139095040!=(0|Fb)))break b;if(a=Ib=Fb+218103808>>>0>>0&&(Ib=x(0),Jb)?Ib:Ca(x(y(x(a/Db)))),Eb>>>0<=2){switch(Eb-1|0){case 0:return x(-a);case 1:break;default:break d}return x(x(3.1415927410125732)-x(a+x(8.742277657347586e-8)))}return x(x(a+x(8.742277657347586e-8))+x(-3.1415927410125732))}if(2139095040==(0|Fb))break c;return u[6816+(Eb<<2)>>2]}a=x(3.1415927410125732)}return a}return u[6800+(Eb<<2)>>2]}return x((0|Hb)<0?-1.5707963705062866:1.5707963705062866)}function Ca(a){x(0);var Kb,Nb,Ob,Db,Mb,Lb=0;x(0),x(0),j(a);a:{if(1283457024<=(Db=2147483647&(Mb=b[0]))>>>0){if(2139095040>>0)break a;return x((0|Mb)<0?-1.570796251296997:1.570796251296997)}b:{if(Db>>>0<=1054867455){if(Lb=-1,964689920<=Db>>>0)break b;break a}a=x(y(a)),Lb=Db>>>0<=1066926079?Db>>>0<=1060110335?(a=x(x(x(a+a)+x(-1))/x(a+x(2))),0):(a=x(x(a+x(-1))/x(a+x(1))),1):Db>>>0<=1075576831?(a=x(x(a+x(-1.5))/x(x(a*x(1.5))+x(1))),2):(a=x(x(-1)/a),3)}if(Db=Lb,Nb=x(a*a),Kb=x(Nb*Nb),Ob=x(Kb*x(x(Kb*x(-.106480173766613))+x(-.19999158382415771))),Kb=x(Nb*x(x(Kb*x(x(Kb*x(.06168760731816292))+x(.14253635704517365)))+x(.333333283662796))),(0|Db)<=-1)return x(a-x(a*x(Ob+Kb)));a=x(u[6768+(Db<<=2)>>2]-x(x(x(a*x(Ob+Kb))-u[6784+Db>>2])-a)),a=(0|Mb)<0?x(-a):a}return a}function Da(a,Pb){var Ub,Sb,Tb,Qb=0,Rb=0;return L=Sb=L-16|0,j(a),(Qb=2147483647&(Tb=b[0]))>>>0<=1305022426?(v[Pb>>3]=(Ub=+a)+-1.5707963109016418*(Rb=.6366197723675814*Ub+6755399441055744-6755399441055744)+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l+1|0):(Hl=y(Il)<2147483648?~~Il:-2147483648,Pl=Nl),q[(480+Ll|0)+(Jl<<2)>>2]=Hl}if(Il=ja(1,Pl),!((0|Jl)<=-1)){for(Hl=Jl;v[(Hl<<3)+Ll>>3]=Il*+q[(480+Ll|0)+(Hl<<2)>>2],Il*=5.960464477539063e-8,a=0<(0|Hl),Hl=Hl+-1|0,a;);if(!((0|Jl)<=-1))for(Hl=Jl;;){for(Nl=Jl-(a=Hl)|0,Hl=Il=0;Il+=v[6704+(Hl<<3)>>3]*v[(a+Hl<<3)+Ll>>3],!((0|Ql)<=(0|Hl))&&(Pl=Hl>>>0>>0,Hl=Hl+1|0,Pl););if(v[(160+Ll|0)+(Nl<<3)>>3]=Il,Hl=a+-1|0,!(0<(0|a)))break}}if(0<=(Jl|(Il=0)))for(;Il+=v[(160+Ll|0)+(Jl<<3)>>3],a=0<(0|Jl),Jl=Jl+-1|0,a;);return v[Gl>>3]=Ml?-Il:Il,L=560+Ll|0,7&Ol}(8+Sb|0,Sb,Qb),Rb=v[Sb>>3],(0|Tb)<=-1?(v[Pb>>3]=-Rb,Qb=0-Qb|0):v[Pb>>3]=Rb),L=16+Sb|0,Qb}function Ea(a,Pb){return a?function(a,Gl){a:{if(a){if(Gl>>>0<=127)break a;if(q[q[1797]>>2]){if(Gl>>>0<=2047)return o[a+1|0]=63&Gl|128,o[0|a]=Gl>>>6|192,2;if(!(57344!=(-8192&Gl)&&55296<=Gl>>>0))return o[a+2|0]=63&Gl|128,o[0|a]=Gl>>>12|224,o[a+1|0]=Gl>>>6&63|128,3;if(Gl+-65536>>>0<=1048575)return o[a+3|0]=63&Gl|128,o[0|a]=Gl>>>18|240,o[a+2|0]=Gl>>>6&63|128,o[a+1|0]=Gl>>>12&63|128,4}else if(57216==(-128&Gl))break a;q[2094]=25,a=-1}else a=1;return a}return o[0|a]=Gl,1}(a,Pb):0}function Fa(a,Pb,Wb){var fc,gc,Xb=0,Yb=0,Zb=0,_b=0,$b=0,ac=0,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1<=((Xb=ac=0)|(bc=q[$b+104>>2]))){for(a=q[a+1104>>2],_b=0;_b=q[a+(Xb<<2)>>2]+_b|0,(0|bc)!=(0|(Xb=Xb+1|0)););a=_b<<2}else a=0;q[Zb+476>>2]=a,q[Pb+472>>2]=w(bc,48),q[Pb+484>>2]=w(q[$b+108>>2],12),a=q[$b+112>>2],q[Pb+552>>2]=0,q[Pb+492>>2]=w(a,12),a=0}else{if((0|(ac=q[$b+20>>2]))<1)_b=0;else for(bc=q[a+1060>>2],dc=q[a+952>>2],a=q[a+948>>2],Zb=_b=0;;){if(1<=(0|(cc=q[(Xb=Zb<<2)+dc>>2])))for(cc=(Xb=bc+(q[a+Xb>>2]<<2)|0)+(cc<<2)|0;_b=q[Xb>>2]+_b|0,(Xb=Xb+4|0)>>>0>>0;);if((0|ac)==(0|(Zb=Zb+1|0)))break}q[Pb+552>>2]=ac<<2,ac=q[$b+20>>2]<<2,a=_b<<2}for(q[Yb+556>>2]=a,q[Pb+548>>2]=ac,4>>0&&(q[Pb+480>>2]=w(q[$b+128>>2],12),q[Pb+488>>2]=w(q[$b+132>>2],12),q[Pb+496>>2]=w(q[$b+136>>2],12)),Xb=_b=0;Xb=((Yb=q[(a=(_b<<2)+Pb|0)>>2])+15&-16)+(q[a>>2]=Xb)|0,140!=(0|(_b=_b+1|0)););q[Wb>>2]=Xb}function Ga(a,Pb,Wb,hc){a:{if(!(20>>0||9<(Pb=Pb+-9|0)>>>0)){switch(Pb-1|0){default:return Pb=q[Wb>>2],q[Wb>>2]=Pb+4,q[a>>2]=q[Pb>>2];case 0:return Pb=q[Wb>>2],q[Wb>>2]=Pb+4,Pb=q[Pb>>2],q[a>>2]=Pb,q[a+4>>2]=Pb>>31;case 1:return Pb=q[Wb>>2],q[Wb>>2]=Pb+4,q[a>>2]=q[Pb>>2],q[a+4>>2]=0;case 3:return Pb=q[Wb>>2],q[Wb>>2]=Pb+4,Pb=p[Pb>>1],q[a>>2]=Pb,q[a+4>>2]=Pb>>31;case 4:return Pb=q[Wb>>2],q[Wb>>2]=Pb+4,q[a>>2]=s[Pb>>1],q[a+4>>2]=0;case 5:return Pb=q[Wb>>2],q[Wb>>2]=Pb+4,Pb=o[0|Pb],q[a>>2]=Pb,q[a+4>>2]=Pb>>31;case 6:return Pb=q[Wb>>2],q[Wb>>2]=Pb+4,q[a>>2]=r[0|Pb],q[a+4>>2]=0;case 2:case 7:break a;case 8:}n[hc](a,Wb)}return}Pb=q[Wb>>2]+7&-8,q[Wb>>2]=Pb+8,Wb=q[Pb+4>>2],q[a>>2]=q[Pb>>2],q[a+4>>2]=Wb}function Ha(a){var Pb,hc,Wb=0;if(ha(o[q[a>>2]]))for(;Pb=q[a>>2],hc=o[0|Pb],q[a>>2]=Pb+1,Wb=(w(Wb,10)+hc|0)-48|0,ha(o[Pb+1|0]););return Wb}function Ia(a,ic,jc,kc,lc){var oc,mc;q[204+(L=mc=L-208|0)>>2]=jc,ca(160+mc|(jc=0),0,40),q[200+mc>>2]=q[204+mc>>2],(0|ra(0,ic,200+mc|0,80+mc|0,160+mc|0,kc,lc))<0||(jc=0<=q[a+76>>2]?1:jc,jc=q[a>>2],o[a+74|0]<=0&&(q[a>>2]=-33&jc),oc=32&jc,q[a+48>>2]?ra(a,ic,200+mc|0,80+mc|0,160+mc|0,kc,lc):(q[a+48>>2]=80,q[a+16>>2]=80+mc,q[a+28>>2]=mc,q[a+20>>2]=mc,jc=q[a+44>>2],ra(a,ic,200+(q[a+44>>2]=mc)|0,80+mc|0,160+mc|0,kc,lc),jc&&(n[q[a+36>>2]](a,0,0),q[a+48>>2]=0,q[a+44>>2]=jc,q[a+28>>2]=0,q[a+16>>2]=0,q[a+20>>2]=0)),q[a>>2]=q[a>>2]|oc),L=208+mc|0}function Ka(a,ic,pc){var rc,qc;$(8+(L=qc=L-160|0)|0,3216,144),q[52+qc>>2]=a,q[28+qc>>2]=a,q[56+qc>>2]=rc=(rc=-2-a|0)>>>0<256?rc:256,q[36+qc>>2]=a=a+rc|0,q[24+qc>>2]=a,Ia(8+qc|0,ic,pc,11,12),rc&&(a=q[28+qc>>2],o[a-((0|a)==q[24+qc>>2])|0]=0),L=160+qc|0}function La(a,ic){var sc,tc,pc=0,pc=0!=(0|ic);a:{b:{c:{d:if(!(!ic|!(3&a)))for(;;){if(!r[0|a])break c;if(a=a+1|0,pc=0!=(0|(ic=ic+-1|0)),!ic)break d;if(!(3&a))break}if(!pc)break b}if(!r[0|a])break a;e:{if(4<=ic>>>0){for(pc=(pc=ic+-4|0)-(sc=-4&pc)|0,sc=4+(a+sc|0)|0;;){if((-1^(tc=q[a>>2]))&tc+-16843009&-2139062144)break e;if(a=a+4|0,!(3<(ic=ic+-4|0)>>>0))break}ic=pc,a=sc}if(!ic)break b}for(;;){if(!r[0|a])break a;if(a=a+1|0,!(ic=ic+-1|0))break}}return 0}return a}function Ma(a){var uc,ic=0;if(!a)return 32;if(!(1&a))for(;ic=ic+1|0,uc=2&a,a>>>=1,!uc;);return ic}function Na(a,vc){var zc,Ac,Bc,yc,wc=0,xc=0,xc=4;L=yc=L-256|0;a:if(!((0|vc)<2))for(wc=q[(Bc=(vc<<2)+a|0)>>2]=yc;;){for($(wc,q[a>>2],zc=xc>>>0<256?xc:256),wc=0;$(q[(Ac=(wc<<2)+a|0)>>2],q[((wc=wc+1|0)<<2)+a>>2],zc),q[Ac>>2]=q[Ac>>2]+zc,(0|vc)!=(0|wc););if(!(xc=xc-zc|0))break a;wc=q[Bc>>2]}L=256+yc|0}function Oa(a){return Ma(q[a>>2]+-1|0)||((a=Ma(q[a+4>>2]))?a+32|0:0)}function $c(a,ap){ap|=0,b[0]=a|=0,b[1]=ap}function cd(a,ap,bp){return function(a,ap,bp){var fp,dp,cp,ep,gp=w(dp=bp>>>16,cp=a>>>16);return a=(65535&(cp=((fp=w(ep=65535&bp,a&=65535))>>>16)+w(cp,ep)|0))+w(a,dp)|0,M=((gp+w(ap,bp)|0)+(cp>>>16)|0)+(a>>>16)|0,65535&fp|a<<16}(a,ap,bp)}function dd(a,ap,bp){return function(a,ap,bp){var op,np,hp=0,ip=0,jp=0,kp=0,lp=0,mp=0,pp=0;a:{b:{c:{d:{e:{if(!(ip=ap))return $c((ap=a)-w(a=(a>>>0)/(bp>>>0)|0,bp)|0,0),M=0,a;if(hp=bp){if(!((kp=hp+-1|0)&hp))break e;lp=0-(kp=(z(hp)+33|0)-z(ip)|0)|0;break c}if(!a)return $c(0,ip-w(a=(ip>>>0)/0|0,0)|0),M=0,a;if((hp=32-z(ip)|0)>>>0<31)break d;break b}if($c(a&kp,0),1==(0|hp))break a;return bp=31&(hp=hp?31-z(hp+-1^hp)|0:32),a=32<=(63&hp)>>>0?(ip=0,ap>>>bp):(ip=ap>>>bp,((1<>>bp),M=ip,a}kp=hp+1|0,lp=63-hp|0}if(hp=ap,jp=31&(ip=63&kp),jp=32<=ip>>>0?(ip=0,hp>>>jp):(ip=hp>>>jp,((1<>>jp),hp=31&(lp&=63),32<=lp>>>0?(ap=a<>>32-hp|ap<>>0<4294967295&&(hp=0);jp=(np=mp=jp<<1|ap>>>31)-(op=bp&(mp=hp-((ip=ip<<1|jp>>>31)+(lp>>>0>>0)|0)>>31))|0,ip=ip-(np>>>0>>0)|0,ap=ap<<1|a>>>31,a=pp|a<<1,pp=mp&=1,kp=kp+-1|0;);return $c(jp,ip),M=ap<<1|a>>>31,mp|a<<1}$c(a,ap),ap=a=0}return M=ap,a}(a,ap,bp)}function fd(a){var qp;return(-1>>>(qp=31&a)&-2)<>>a}function N(){return buffer.byteLength/65536|0}}(H,I,J)}}l=null,b.wasmBinary&&(F=b.wasmBinary);var WebAssembly={},F=[];"object"!=typeof WebAssembly&&E("no native wasm support detected");var I,J=new function(a){var c=Array(16);return c.grow=function(){17<=c.length&&B("Unable to grow wasm table. Use a higher value for RESERVED_FUNCTION_POINTERS or set ALLOW_TABLE_GROWTH."),c.push(null)},c.set=function(a,e){c[a]=e},c.get=function(a){return c[a]},c},K=!1;function assert(a,c){a||B("Assertion failed: "+c)}var buffer,M,L,N,ha="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function ia(a,c,d){var e=c+d;for(d=c;a[d]&&!(e<=d);)++d;if(16>10,56320|1023&f)))):e+=String.fromCharCode(f)}return e}function ja(a,c){return a?ia(L,a,c):""}function ka(a){return 0>>16)*e+d*(c>>>16)<<16)|0}),Math.fround||(ra=new Float32Array(1),Math.fround=function(a){return ra[0]=a,ra[0]}),Math.clz32||(Math.clz32=function(a){var c=32,d=a>>16;return d&&(c-=16,a=d),(d=a>>8)&&(c-=8,a=d),(d=a>>4)&&(c-=4,a=d),(d=a>>2)&&(c-=2,a=d),a>>1?c-2:c-a}),Math.trunc||(Math.trunc=function(a){return a<0?Math.ceil(a):Math.floor(a)}),0),Q=null,U=null;function B(a){throw b.onAbort&&b.onAbort(a),D(a),E(a),K=!0,"abort("+a+"). Build with -s ASSERTIONS=1 for more info."}b.preloadedImages={},b.preloadedAudios={};var V="data:application/octet-stream;base64,";function W(a){return String.prototype.startsWith?a.startsWith(V):0===a.indexOf(V)}var X="_em_module.wasm";function ta(){try{if(F)return new Uint8Array(F);var a=z(X);if(a)return a;if(w)return w(X);throw"both async and sync fetching of the wasm failed"}catch(c){B(c)}}W(X)||(t=X,X=b.locateFile?b.locateFile(t,u):u+t),na.push({fa:function(){va()}});var wa=[null,[],[]],xa=!1;function C(a){for(var c=[],d=0;d>4,f=(15&f)<<4|g>>2,h=(3&g)<<6|m}while(c+=String.fromCharCode(e),64!==g&&(c+=String.fromCharCode(f)),64!==m&&(c+=String.fromCharCode(h)),d>16),la(I.buffer);var d=1;break a}catch(e){}d=void 0}return!!d},c:function(a,c,d,e){try{for(var f=0,g=0;g>2],h=N[c+(8*g+4)>>2],A=0;A>2]=f,0}catch(T){return"undefined"!=typeof FS&&T instanceof FS.ga||B(T),T.ha}},memory:I,table:J},u=function(){function a(a){b.asm=a.exports,P--,b.monitorRunDependencies&&b.monitorRunDependencies(P),0==P&&(null!==Q&&(clearInterval(Q),Q=null),U)&&(a=U,U=null,a())}function c(c){a(c.instance)}function d(a){(F||!p&&!q||"function"!=typeof fetch?new Promise(function(a){a(ta())}):fetch(X,{credentials:"same-origin"}).then(function(a){if(a.ok)return a.arrayBuffer();throw"failed to load wasm binary file at '"+X+"'"}).catch(ta)).then(function(){return{then:function(a){a({instance:new da})}}}).then(a,function(a){E("failed to asynchronously prepare wasm: "+a),B(a)})}var e={env:H,wasi_unstable:H};if(P++,b.monitorRunDependencies&&b.monitorRunDependencies(P),b.instantiateWasm)try{return b.instantiateWasm(e,a)}catch(f){return E("Module.instantiateWasm callback failed with error: "+f),!1}return F||"function"!=typeof WebAssembly.instantiateStreaming||W(X)||"function"!=typeof fetch?d(c):fetch(X,{credentials:"same-origin"}).then(function(a){return WebAssembly.instantiateStreaming(a,e).then(c,function(a){E("wasm streaming compile failed: "+a),E("falling back to ArrayBuffer instantiation"),d(c)})}),{}}(),va=(b.asm=u,b.___wasm_call_ctors=function(){return b.asm.d.apply(null,arguments)}),Aa=(b._csmGetLogFunction=function(){return b.asm.e.apply(null,arguments)},b._csmGetVersion=function(){return b.asm.f.apply(null,arguments)},b._csmGetLatestMocVersion=function(){return b.asm.g.apply(null,arguments)},b._csmGetMocVersion=function(){return b.asm.h.apply(null,arguments)},b._csmHasMocConsistency=function(){return b.asm.i.apply(null,arguments)},b._csmSetLogFunction=function(){return b.asm.j.apply(null,arguments)},b._csmReviveMocInPlace=function(){return b.asm.k.apply(null,arguments)},b._csmReadCanvasInfo=function(){return b.asm.l.apply(null,arguments)},b._csmGetSizeofModel=function(){return b.asm.m.apply(null,arguments)},b._csmInitializeModelInPlace=function(){return b.asm.n.apply(null,arguments)},b._csmUpdateModel=function(){return b.asm.o.apply(null,arguments)},b._csmGetParameterCount=function(){return b.asm.p.apply(null,arguments)},b._csmGetParameterIds=function(){return b.asm.q.apply(null,arguments)},b._csmGetParameterTypes=function(){return b.asm.r.apply(null,arguments)},b._csmGetParameterMinimumValues=function(){return b.asm.s.apply(null,arguments)},b._csmGetParameterMaximumValues=function(){return b.asm.t.apply(null,arguments)},b._csmGetParameterDefaultValues=function(){return b.asm.u.apply(null,arguments)},b._csmGetParameterValues=function(){return b.asm.v.apply(null,arguments)},b._csmGetParameterRepeats=function(){return b.asm.w.apply(null,arguments)},b._csmGetPartCount=function(){return b.asm.x.apply(null,arguments)},b._csmGetPartIds=function(){return b.asm.y.apply(null,arguments)},b._csmGetPartOpacities=function(){return b.asm.z.apply(null,arguments)},b._csmGetPartParentPartIndices=function(){return b.asm.A.apply(null,arguments)},b._csmGetDrawableCount=function(){return b.asm.B.apply(null,arguments)},b._csmGetDrawableIds=function(){return b.asm.C.apply(null,arguments)},b._csmGetDrawableConstantFlags=function(){return b.asm.D.apply(null,arguments)},b._csmGetDrawableDynamicFlags=function(){return b.asm.E.apply(null,arguments)},b._csmGetDrawableTextureIndices=function(){return b.asm.F.apply(null,arguments)},b._csmGetDrawableDrawOrders=function(){return b.asm.G.apply(null,arguments)},b._csmGetDrawableRenderOrders=function(){return b.asm.H.apply(null,arguments)},b._csmGetDrawableOpacities=function(){return b.asm.I.apply(null,arguments)},b._csmGetDrawableMaskCounts=function(){return b.asm.J.apply(null,arguments)},b._csmGetDrawableMasks=function(){return b.asm.K.apply(null,arguments)},b._csmGetDrawableVertexCounts=function(){return b.asm.L.apply(null,arguments)},b._csmGetDrawableVertexPositions=function(){return b.asm.M.apply(null,arguments)},b._csmGetDrawableVertexUvs=function(){return b.asm.N.apply(null,arguments)},b._csmGetDrawableIndexCounts=function(){return b.asm.O.apply(null,arguments)},b._csmGetDrawableIndices=function(){return b.asm.P.apply(null,arguments)},b._csmGetDrawableMultiplyColors=function(){return b.asm.Q.apply(null,arguments)},b._csmGetDrawableScreenColors=function(){return b.asm.R.apply(null,arguments)},b._csmGetDrawableParentPartIndices=function(){return b.asm.S.apply(null,arguments)},b._csmResetDrawableDynamicFlags=function(){return b.asm.T.apply(null,arguments)},b._csmGetParameterKeyCounts=function(){return b.asm.U.apply(null,arguments)},b._csmGetParameterKeyValues=function(){return b.asm.V.apply(null,arguments)},b._csmMallocMoc=function(){return b.asm.W.apply(null,arguments)},b._csmMallocModelAndInitialize=function(){return b.asm.X.apply(null,arguments)},b._csmMalloc=function(){return b.asm.Y.apply(null,arguments)},b._csmFree=function(){return b.asm.Z.apply(null,arguments)},b._csmInitializeAmountOfMemory=function(){return b.asm._.apply(null,arguments)},b.stackSave=function(){return b.asm.$.apply(null,arguments)}),Ba=b.stackAlloc=function(){return b.asm.aa.apply(null,arguments)},Ca=b.stackRestore=function(){return b.asm.ba.apply(null,arguments)},ca=b.__growWasmMemory=function(){return b.asm.ca.apply(null,arguments)};function Z(){function a(){if(!Y&&(Y=!0,!K)){if(O(na),O(oa),b.onRuntimeInitialized&&b.onRuntimeInitialized(),b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var a=b.postRun.shift();pa.unshift(a)}O(pa)}}if(!(0>6}else{if(k<=65535){if(d<=e+2)break;f[e++]=224|k>>12}else{if(d<=e+3)break;f[e++]=240|k>>18,f[e++]=128|k>>12&63}f[e++]=128|k>>6&63}f[e++]=128|63&k}}f[e]=0}}return c},array:function(a){var c=Ba(a.length);return M.set(a,c),c}},g=function(a){var c=b["_"+a];return assert(c,"Cannot call unknown function "+a+", make sure it is exported"),c}(a),m=[];if(a=0,e)for(var h=0;h> 1) + i] = pcmData[i]; + } + + // 为输出分配内存 + const outPtr = mod._malloc(this.maxPacketSize); + + // 进行编码 + const encodedLen = mod._opus_encode( + this.encoderPtr, + pcmPtr, + this.frameSize, + outPtr, + this.maxPacketSize + ); + + if (encodedLen < 0) { + throw new Error(`Opus编码失败: ${encodedLen}`); + } + + // 复制编码后的数据 + const opusData = new Uint8Array(encodedLen); + for (let i = 0; i < encodedLen; i++) { + opusData[i] = mod.HEAPU8[outPtr + i]; + } + + // 释放内存 + mod._free(pcmPtr); + mod._free(outPtr); + + return opusData; + } catch (error) { + log(`Opus编码出错: ${error.message}`, 'error'); + return null; + } + }, + + // 销毁编码器 + destroy: function () { + if (this.encoderPtr) { + this.module._free(this.encoderPtr); + this.encoderPtr = null; + } + } + }; + + opusEncoder.init(); + return opusEncoder; + } catch (error) { + log(`创建Opus编码器失败: ${error.message}`, 'error'); + return false; + } +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/libs/pixi.js b/main/feedback-backend/admin-ui/libs/pixi.js new file mode 100644 index 000000000..f9d465daf --- /dev/null +++ b/main/feedback-backend/admin-ui/libs/pixi.js @@ -0,0 +1,43379 @@ +/*! + * pixi.js - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +var PIXI = (function (exports) { + 'use strict'; + + /** + * @this {Promise} + */ + function finallyConstructor(callback) { + var constructor = this.constructor; + return this.then( + function(value) { + // @ts-ignore + return constructor.resolve(callback()).then(function() { + return value; + }); + }, + function(reason) { + // @ts-ignore + return constructor.resolve(callback()).then(function() { + // @ts-ignore + return constructor.reject(reason); + }); + } + ); + } + + function allSettled(arr) { + var P = this; + return new P(function(resolve, reject) { + if (!(arr && typeof arr.length !== 'undefined')) { + return reject( + new TypeError( + typeof arr + + ' ' + + arr + + ' is not iterable(cannot read property Symbol(Symbol.iterator))' + ) + ); + } + var args = Array.prototype.slice.call(arr); + if (args.length === 0) { return resolve([]); } + var remaining = args.length; + + function res(i, val) { + if (val && (typeof val === 'object' || typeof val === 'function')) { + var then = val.then; + if (typeof then === 'function') { + then.call( + val, + function(val) { + res(i, val); + }, + function(e) { + args[i] = { status: 'rejected', reason: e }; + if (--remaining === 0) { + resolve(args); + } + } + ); + return; + } + } + args[i] = { status: 'fulfilled', value: val }; + if (--remaining === 0) { + resolve(args); + } + } + + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); + } + + // Store setTimeout reference so promise-polyfill will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var setTimeoutFunc = setTimeout; + + function isArray(x) { + return Boolean(x && typeof x.length !== 'undefined'); + } + + function noop() {} + + // Polyfill for Function.prototype.bind + function bind(fn, thisArg) { + return function() { + fn.apply(thisArg, arguments); + }; + } + + /** + * @constructor + * @param {Function} fn + */ + function Promise$1(fn) { + if (!(this instanceof Promise$1)) + { throw new TypeError('Promises must be constructed via new'); } + if (typeof fn !== 'function') { throw new TypeError('not a function'); } + /** @type {!number} */ + this._state = 0; + /** @type {!boolean} */ + this._handled = false; + /** @type {Promise|undefined} */ + this._value = undefined; + /** @type {!Array} */ + this._deferreds = []; + + doResolve(fn, this); + } + + function handle(self, deferred) { + while (self._state === 3) { + self = self._value; + } + if (self._state === 0) { + self._deferreds.push(deferred); + return; + } + self._handled = true; + Promise$1._immediateFn(function() { + var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; + if (cb === null) { + (self._state === 1 ? resolve$1 : reject)(deferred.promise, self._value); + return; + } + var ret; + try { + ret = cb(self._value); + } catch (e) { + reject(deferred.promise, e); + return; + } + resolve$1(deferred.promise, ret); + }); + } + + function resolve$1(self, newValue) { + try { + // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + if (newValue === self) + { throw new TypeError('A promise cannot be resolved with itself.'); } + if ( + newValue && + (typeof newValue === 'object' || typeof newValue === 'function') + ) { + var then = newValue.then; + if (newValue instanceof Promise$1) { + self._state = 3; + self._value = newValue; + finale(self); + return; + } else if (typeof then === 'function') { + doResolve(bind(then, newValue), self); + return; + } + } + self._state = 1; + self._value = newValue; + finale(self); + } catch (e) { + reject(self, e); + } + } + + function reject(self, newValue) { + self._state = 2; + self._value = newValue; + finale(self); + } + + function finale(self) { + if (self._state === 2 && self._deferreds.length === 0) { + Promise$1._immediateFn(function() { + if (!self._handled) { + Promise$1._unhandledRejectionFn(self._value); + } + }); + } + + for (var i = 0, len = self._deferreds.length; i < len; i++) { + handle(self, self._deferreds[i]); + } + self._deferreds = null; + } + + /** + * @constructor + */ + function Handler(onFulfilled, onRejected, promise) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.promise = promise; + } + + /** + * Take a potentially misbehaving resolver function and make sure + * onFulfilled and onRejected are only called once. + * + * Makes no guarantees about asynchrony. + */ + function doResolve(fn, self) { + var done = false; + try { + fn( + function(value) { + if (done) { return; } + done = true; + resolve$1(self, value); + }, + function(reason) { + if (done) { return; } + done = true; + reject(self, reason); + } + ); + } catch (ex) { + if (done) { return; } + done = true; + reject(self, ex); + } + } + + Promise$1.prototype['catch'] = function(onRejected) { + return this.then(null, onRejected); + }; + + Promise$1.prototype.then = function(onFulfilled, onRejected) { + // @ts-ignore + var prom = new this.constructor(noop); + + handle(this, new Handler(onFulfilled, onRejected, prom)); + return prom; + }; + + Promise$1.prototype['finally'] = finallyConstructor; + + Promise$1.all = function(arr) { + return new Promise$1(function(resolve, reject) { + if (!isArray(arr)) { + return reject(new TypeError('Promise.all accepts an array')); + } + + var args = Array.prototype.slice.call(arr); + if (args.length === 0) { return resolve([]); } + var remaining = args.length; + + function res(i, val) { + try { + if (val && (typeof val === 'object' || typeof val === 'function')) { + var then = val.then; + if (typeof then === 'function') { + then.call( + val, + function(val) { + res(i, val); + }, + reject + ); + return; + } + } + args[i] = val; + if (--remaining === 0) { + resolve(args); + } + } catch (ex) { + reject(ex); + } + } + + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); + }; + + Promise$1.allSettled = allSettled; + + Promise$1.resolve = function(value) { + if (value && typeof value === 'object' && value.constructor === Promise$1) { + return value; + } + + return new Promise$1(function(resolve) { + resolve(value); + }); + }; + + Promise$1.reject = function(value) { + return new Promise$1(function(resolve, reject) { + reject(value); + }); + }; + + Promise$1.race = function(arr) { + return new Promise$1(function(resolve, reject) { + if (!isArray(arr)) { + return reject(new TypeError('Promise.race accepts an array')); + } + + for (var i = 0, len = arr.length; i < len; i++) { + Promise$1.resolve(arr[i]).then(resolve, reject); + } + }); + }; + + // Use polyfill for setImmediate for performance gains + Promise$1._immediateFn = + // @ts-ignore + (typeof setImmediate === 'function' && + function(fn) { + // @ts-ignore + setImmediate(fn); + }) || + function(fn) { + setTimeoutFunc(fn, 0); + }; + + Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) { + if (typeof console !== 'undefined' && console) { + console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console + } + }; + + /* + object-assign + (c) Sindre Sorhus + @license MIT + */ + + 'use strict'; + /* eslint-disable no-unused-vars */ + var getOwnPropertySymbols = Object.getOwnPropertySymbols; + var hasOwnProperty$2 = Object.prototype.hasOwnProperty; + var propIsEnumerable = Object.prototype.propertyIsEnumerable; + + function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); + } + + function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } + } + + var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { + var arguments$1 = arguments; + + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments$1[s]); + + for (var key in from) { + if (hasOwnProperty$2.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; + }; + + /*! + * @pixi/polyfill - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/polyfill is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + if (typeof globalThis === 'undefined') { + if (typeof self !== 'undefined') { + // covers browsers + // @ts-expect-error not-writable ts(2540) error only on node + self.globalThis = self; + } + else if (typeof global !== 'undefined') { + // covers versions of Node < 12 + // @ts-expect-error not-writable ts(2540) error only on node + global.globalThis = global; + } + } + + // Support for IE 9 - 11 which does not include Promises + if (!globalThis.Promise) { + globalThis.Promise = Promise$1; + } + + // References: + if (!Object.assign) { + Object.assign = objectAssign; + } + + // References: + // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ + // https://gist.github.com/1579671 + // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision + // https://gist.github.com/timhall/4078614 + // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + // Expected to be used with Browserfiy + // Browserify automatically detects the use of `global` and passes the + // correct reference of `global`, `globalThis`, and finally `window` + var ONE_FRAME_TIME = 16; + // Date.now + if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; + } + // performance.now + if (!(globalThis.performance && globalThis.performance.now)) { + var startTime_1 = Date.now(); + if (!globalThis.performance) { + globalThis.performance = {}; + } + globalThis.performance.now = function () { return Date.now() - startTime_1; }; + } + // requestAnimationFrame + var lastTime = Date.now(); + var vendors = ['ms', 'moz', 'webkit', 'o']; + for (var x = 0; x < vendors.length && !globalThis.requestAnimationFrame; ++x) { + var p = vendors[x]; + globalThis.requestAnimationFrame = globalThis[p + "RequestAnimationFrame"]; + globalThis.cancelAnimationFrame = globalThis[p + "CancelAnimationFrame"] + || globalThis[p + "CancelRequestAnimationFrame"]; + } + if (!globalThis.requestAnimationFrame) { + globalThis.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + "is not a function"); + } + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + if (delay < 0) { + delay = 0; + } + lastTime = currentTime; + return globalThis.self.setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; + } + if (!globalThis.cancelAnimationFrame) { + globalThis.cancelAnimationFrame = function (id) { return clearTimeout(id); }; + } + + // References: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + if (x === 0 || isNaN(x)) { + return x; + } + return x > 0 ? 1 : -1; + }; + } + + // References: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger + if (!Number.isInteger) { + Number.isInteger = function numberIsInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; + } + + if (!globalThis.ArrayBuffer) { + globalThis.ArrayBuffer = Array; + } + if (!globalThis.Float32Array) { + globalThis.Float32Array = Array; + } + if (!globalThis.Uint32Array) { + globalThis.Uint32Array = Array; + } + if (!globalThis.Uint16Array) { + globalThis.Uint16Array = Array; + } + if (!globalThis.Uint8Array) { + globalThis.Uint8Array = Array; + } + if (!globalThis.Int32Array) { + globalThis.Int32Array = Array; + } + + /*! + * @pixi/settings - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/settings is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$5; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$5 || (ENV$5 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$5; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$5 || (RENDERER_TYPE$5 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$5; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$5 || (BUFFER_BITS$5 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$5; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$5 || (BLEND_MODES$5 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$5; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$5 || (DRAW_MODES$5 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$5; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$5 || (FORMATS$5 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$5; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$5 || (TARGETS$5 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$5; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$5 || (TYPES$5 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$5; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$5 || (SAMPLER_TYPES$5 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$5; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$5 || (SCALE_MODES$5 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$5; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$5 || (WRAP_MODES$5 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$5; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$5 || (MIPMAP_MODES$5 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$5; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$5 || (ALPHA_MODES$5 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$5; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$5 || (CLEAR_MODES$5 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$5; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$5 || (GC_MODES$5 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$5; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$5 || (PRECISION$5 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$5; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$5 || (MASK_TYPES$5 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$5; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$5 || (COLOR_MASK_BITS$5 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$5; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$5 || (MSAA_QUALITY$5 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$5; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$5 || (BUFFER_TYPE$5 = {})); + + var BrowserAdapter$1 = { + /** + * Creates a canvas element of the given size. + * This canvas is created using the browser's native canvas element. + * @param width - width of the canvas + * @param height - height of the canvas + */ + createCanvas: function (width, height) { + var canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + return canvas; + }, + getWebGLRenderingContext: function () { return WebGLRenderingContext; }, + getNavigator: function () { return navigator; }, + getBaseUrl: function () { var _a; return ((_a = document.baseURI) !== null && _a !== void 0 ? _a : window.location.href); }, + fetch: function (url, options) { return fetch(url, options); }, + }; + + var appleIphone$1 = /iPhone/i; + var appleIpod$1 = /iPod/i; + var appleTablet$1 = /iPad/i; + var appleUniversal$1 = /\biOS-universal(?:.+)Mac\b/i; + var androidPhone$1 = /\bAndroid(?:.+)Mobile\b/i; + var androidTablet$1 = /Android/i; + var amazonPhone$1 = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; + var amazonTablet$1 = /Silk/i; + var windowsPhone$1 = /Windows Phone/i; + var windowsTablet$1 = /\bWindows(?:.+)ARM\b/i; + var otherBlackBerry$1 = /BlackBerry/i; + var otherBlackBerry10$1 = /BB10/i; + var otherOpera$1 = /Opera Mini/i; + var otherChrome$1 = /\b(CriOS|Chrome)(?:.+)Mobile/i; + var otherFirefox$1 = /Mobile(?:.+)Firefox\b/i; + var isAppleTabletOnIos13$1 = function (navigator) { + return (typeof navigator !== 'undefined' && + navigator.platform === 'MacIntel' && + typeof navigator.maxTouchPoints === 'number' && + navigator.maxTouchPoints > 1 && + typeof MSStream === 'undefined'); + }; + function createMatch$1(userAgent) { + return function (regex) { return regex.test(userAgent); }; + } + function isMobile$1$1(param) { + var nav = { + userAgent: '', + platform: '', + maxTouchPoints: 0 + }; + if (!param && typeof navigator !== 'undefined') { + nav = { + userAgent: navigator.userAgent, + platform: navigator.platform, + maxTouchPoints: navigator.maxTouchPoints || 0 + }; + } + else if (typeof param === 'string') { + nav.userAgent = param; + } + else if (param && param.userAgent) { + nav = { + userAgent: param.userAgent, + platform: param.platform, + maxTouchPoints: param.maxTouchPoints || 0 + }; + } + var userAgent = nav.userAgent; + var tmp = userAgent.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + tmp = userAgent.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + var match = createMatch$1(userAgent); + var result = { + apple: { + phone: match(appleIphone$1) && !match(windowsPhone$1), + ipod: match(appleIpod$1), + tablet: !match(appleIphone$1) && + (match(appleTablet$1) || isAppleTabletOnIos13$1(nav)) && + !match(windowsPhone$1), + universal: match(appleUniversal$1), + device: (match(appleIphone$1) || + match(appleIpod$1) || + match(appleTablet$1) || + match(appleUniversal$1) || + isAppleTabletOnIos13$1(nav)) && + !match(windowsPhone$1) + }, + amazon: { + phone: match(amazonPhone$1), + tablet: !match(amazonPhone$1) && match(amazonTablet$1), + device: match(amazonPhone$1) || match(amazonTablet$1) + }, + android: { + phone: (!match(windowsPhone$1) && match(amazonPhone$1)) || + (!match(windowsPhone$1) && match(androidPhone$1)), + tablet: !match(windowsPhone$1) && + !match(amazonPhone$1) && + !match(androidPhone$1) && + (match(amazonTablet$1) || match(androidTablet$1)), + device: (!match(windowsPhone$1) && + (match(amazonPhone$1) || + match(amazonTablet$1) || + match(androidPhone$1) || + match(androidTablet$1))) || + match(/\bokhttp\b/i) + }, + windows: { + phone: match(windowsPhone$1), + tablet: match(windowsTablet$1), + device: match(windowsPhone$1) || match(windowsTablet$1) + }, + other: { + blackberry: match(otherBlackBerry$1), + blackberry10: match(otherBlackBerry10$1), + opera: match(otherOpera$1), + firefox: match(otherFirefox$1), + chrome: match(otherChrome$1), + device: match(otherBlackBerry$1) || + match(otherBlackBerry10$1) || + match(otherOpera$1) || + match(otherFirefox$1) || + match(otherChrome$1) + }, + any: false, + phone: false, + tablet: false + }; + result.any = + result.apple.device || + result.android.device || + result.windows.device || + result.other.device; + result.phone = + result.apple.phone || result.android.phone || result.windows.phone; + result.tablet = + result.apple.tablet || result.android.tablet || result.windows.tablet; + return result; + } + + var isMobile$2 = isMobile$1$1(globalThis.navigator); + + /** + * Uploading the same buffer multiple times in a single frame can cause performance issues. + * Apparent on iOS so only check for that at the moment + * This check may become more complex if this issue pops up elsewhere. + * @private + * @returns {boolean} `true` if the same buffer may be uploaded more than once. + */ + function canUploadSameBuffer$1() { + return !isMobile$2.apple.device; + } + + /** + * The maximum recommended texture units to use. + * In theory the bigger the better, and for desktop we'll use as many as we can. + * But some mobile devices slow down if there is to many branches in the shader. + * So in practice there seems to be a sweet spot size that varies depending on the device. + * + * In v4, all mobile devices were limited to 4 texture units because for this. + * In v5, we allow all texture units to be used on modern Apple or Android devices. + * @private + * @param {number} max + * @returns {number} The maximum recommended texture units to use. + */ + function maxRecommendedTextures$1(max) { + var allowMax = true; + if (isMobile$2.tablet || isMobile$2.phone) { + if (isMobile$2.apple.device) { + var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below iOS 11, which will be older hardware + if (majorVersion < 11) { + allowMax = false; + } + } + } + if (isMobile$2.android.device) { + var match = (navigator.userAgent).match(/Android\s([0-9.]*)/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below Android 7 (Nougat), which will be older hardware + if (majorVersion < 7) { + allowMax = false; + } + } + } + } + return allowMax ? max : 4; + } + + /** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float precision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio; + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ + var settings$1 = { + /** + * This adapter is used to call methods that are platform dependent. + * For example `document.createElement` only runs on the web but fails in node environments. + * This allows us to support more platforms by abstracting away specific implementations per platform. + * + * By default the adapter is set to work in the browser. However you can create your own + * by implementing the `IAdapter` interface. See `IAdapter` for more information. + * @name ADAPTER + * @memberof PIXI.settings + * @type {PIXI.IAdapter} + * @default PIXI.BrowserAdapter + */ + ADAPTER: BrowserAdapter$1, + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * @static + * @name MIPMAP_TEXTURES + * @memberof PIXI.settings + * @type {PIXI.MIPMAP_MODES} + * @default PIXI.MIPMAP_MODES.POW2 + */ + MIPMAP_TEXTURES: MIPMAP_MODES$5.POW2, + /** + * Default anisotropic filtering level of textures. + * Usually from 0 to 16 + * @static + * @name ANISOTROPIC_LEVEL + * @memberof PIXI.settings + * @type {number} + * @default 0 + */ + ANISOTROPIC_LEVEL: 0, + /** + * Default resolution / device pixel ratio of the renderer. + * @static + * @name RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + /** + * Default filter resolution. + * @static + * @name FILTER_RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + /** + * Default filter samples. + * @static + * @name FILTER_MULTISAMPLE + * @memberof PIXI.settings + * @type {PIXI.MSAA_QUALITY} + * @default PIXI.MSAA_QUALITY.NONE + */ + FILTER_MULTISAMPLE: MSAA_QUALITY$5.NONE, + /** + * The maximum textures that this device supports. + * @static + * @name SPRITE_MAX_TEXTURES + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: maxRecommendedTextures$1(32), + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * @static + * @name SPRITE_BATCH_SIZE + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + /** + * The default render options if none are supplied to {@link PIXI.Renderer} + * or {@link PIXI.CanvasRenderer}. + * @static + * @name RENDER_OPTIONS + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} [view=null] - + * @property {boolean} [antialias=false] - + * @property {boolean} [autoDensity=false] - + * @property {boolean} [useContextAlpha=true] - + * @property {number} [backgroundColor=0x000000] - + * @property {number} [backgroundAlpha=1] - + * @property {boolean} [clearBeforeRender=true] - + * @property {boolean} [preserveDrawingBuffer=false] - + * @property {number} [width=800] - + * @property {number} [height=600] - + * @property {boolean} [legacy=false] - + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + autoDensity: false, + backgroundColor: 0x000000, + backgroundAlpha: 1, + useContextAlpha: true, + clearBeforeRender: true, + preserveDrawingBuffer: false, + width: 800, + height: 600, + legacy: false, + }, + /** + * Default Garbage Collection mode. + * @static + * @name GC_MODE + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: GC_MODES$5.AUTO, + /** + * Default Garbage Collection max idle. + * @static + * @name GC_MAX_IDLE + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + /** + * Default Garbage Collection maximum check count. + * @static + * @name GC_MAX_CHECK_COUNT + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + /** + * Default wrap modes that are supported by pixi. + * @static + * @name WRAP_MODE + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: WRAP_MODES$5.CLAMP, + /** + * Default scale mode for textures. + * @static + * @name SCALE_MODE + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: SCALE_MODES$5.LINEAR, + /** + * Default specify float precision in vertex shader. + * @static + * @name PRECISION_VERTEX + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: PRECISION$5.HIGH, + /** + * Default specify float precision in fragment shader. + * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 + * @static + * @name PRECISION_FRAGMENT + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: isMobile$2.apple.device ? PRECISION$5.HIGH : PRECISION$5.MEDIUM, + /** + * Can we upload the same buffer in a single frame? + * @static + * @name CAN_UPLOAD_SAME_BUFFER + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer$1(), + /** + * Enables bitmap creation before image load. This feature is experimental. + * @static + * @name CREATE_IMAGE_BITMAP + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + CREATE_IMAGE_BITMAP: false, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + ROUND_PIXELS: false, + }; + + var commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule$1(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire$1(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } + + function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; + } + + function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; + } + + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } + + function commonjsRequire$1 () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } + + var eventemitter3 = createCommonjsModule$1(function (module) { + 'use strict'; + + var has = Object.prototype.hasOwnProperty + , prefix = '~'; + + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) { prefix = false; } + } + + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; } + else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); } + else { emitter._events[evt] = [emitter._events[evt], listener]; } + + return emitter; + } + + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) { emitter._events = new Events(); } + else { delete emitter._events[evt]; } + } + + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) { return names; } + + for (name in (events = this._events)) { + if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); } + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; + }; + + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) { return []; } + if (handlers.fn) { return [handlers.fn]; } + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; + }; + + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) { return 0; } + if (listeners.fn) { return 1; } + return listeners.length; + }; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var arguments$1 = arguments; + + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) { return false; } + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); } + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments$1[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); } + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments$1[j]; + } } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; + }; + + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) { return this; } + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; } + else { clearEvent(this, evt); } + } + + return this; + }; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { clearEvent(this, evt); } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; + + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; + + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; + + // + // Expose the module. + // + if ('undefined' !== 'object') { + module.exports = EventEmitter; + } + }); + + 'use strict'; + + var earcut_1 = earcut; + var _default = earcut; + + function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) { return triangles; } + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) { outerNode = eliminateHoles(data, holeIndices, outerNode, dim); } + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) { minX = x; } + if (y < minY) { minY = y; } + if (x > maxX) { maxX = x; } + if (y > maxY) { maxY = y; } + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + + return triangles; + } + + // create a circular doubly linked list from polygon points in the specified winding order + function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) { last = insertNode(i, data[i], data[i + 1], last); } + } else { + for (i = end - dim; i >= start; i -= dim) { last = insertNode(i, data[i], data[i + 1], last); } + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; + } + + // eliminate colinear or duplicate points + function filterPoints(start, end) { + if (!start) { return start; } + if (!end) { end = start; } + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) { break; } + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; + } + + // main ear slicing loop which triangulates a polygon (given as a linked list) + function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) { return; } + + // interlink polygon nodes in z-order + if (!pass && invSize) { indexCurve(ear, minX, minY, invSize); } + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } + } + + // check whether a polygon node forms a valid ear with adjacent nodes + function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + var p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) { return false; } + p = p.next; + } + + return true; + } + + function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear + + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + // z-order range for the current triangle bbox; + var minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; } + p = p.prevZ; + + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; } + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; } + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; } + n = n.nextZ; + } + + return true; + } + + // go through all polygon nodes and cure small local self-intersections + function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return filterPoints(p); + } + + // try splitting polygon into two and triangulate them independently + function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); + } + + // link every hole into the outer loop, producing a single-ring polygon without holes + function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) { list.steiner = true; } + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + + return outerNode; + } + + function compareX(a, b) { + return a.x - b.x; + } + + // find a bridge between vertices that connects hole with an outer ring and and link it + function eliminateHole(hole, outerNode) { + var bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + var bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); + } + + // David Eberly's algorithm for finding a bridge between hole and outer polygon + function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) { return m; } // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) { return null; } + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m; + + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } while (p !== stop); + + return m; + } + + // whether sector in vertex m contains sector in vertex p in the same coordinates + function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; + } + + // interlink polygon nodes in z-order + function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === 0) { p.z = zOrder(p.x, p.y, minX, minY, invSize); } + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); + } + + // Simon Tatham's linked list merge sort algorithm + // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) { break; } + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) { tail.nextZ = e; } + else { list = e; } + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; + } + + // z-order of a point given coords and inverse of the longer side of data bbox + function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); + } + + // find the leftmost node of a polygon ring + function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) { leftmost = p; } + p = p.next; + } while (p !== start); + + return leftmost; + } + + // check if a point lies within a convex triangle + function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); + } + + // check if a diagonal between two polygon nodes is valid (lies in polygon interior) + function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case + } + + // signed area of a triangle + function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + } + + // check if two points are equal + function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } + + // check if two segments intersect + function intersects(p1, q1, p2, q2) { + var o1 = sign$1(area(p1, q1, p2)); + var o2 = sign$1(area(p1, q1, q2)); + var o3 = sign$1(area(p2, q2, p1)); + var o4 = sign$1(area(p2, q2, q1)); + + if (o1 !== o2 && o3 !== o4) { return true; } // general case + + if (o1 === 0 && onSegment(p1, p2, q1)) { return true; } // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) { return true; } // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) { return true; } // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) { return true; } // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; + } + + // for collinear points p, q, r, check if point q lies on segment pr + function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); + } + + function sign$1(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + + // check if a polygon diagonal intersects any polygon segments + function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) { return true; } + p = p.next; + } while (p !== a); + + return false; + } + + // check if a polygon diagonal is locally inside the polygon + function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; + } + + // check if the middle point of a polygon diagonal is inside the polygon + function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + { inside = !inside; } + p = p.next; + } while (p !== a); + + return inside; + } + + // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; + // if one belongs to the outer ring and another to a hole, it merges it into a single ring + function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; + } + + // create a node and optionally link it with previous one (in a circular doubly linked list) + function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; + } + + function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) { p.prevZ.nextZ = p.nextZ; } + if (p.nextZ) { p.nextZ.prevZ = p.prevZ; } + } + + function Node(i, x, y) { + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = 0; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; + } + + // return a percentage difference between the polygon area and its triangulation area; + // used to verify correctness of triangulation + earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); + }; + + function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; + } + + // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts + earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) { result.vertices.push(data[i][j][d]); } + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; + }; + earcut_1.default = _default; + + var punycode = createCommonjsModule$1(function (module, exports) { + /*! https://mths.be/punycode v1.3.2 by @mathias */ + ;(function(root) { + + /** Detect free variables */ + var freeExports = 'object' == 'object' && exports && + !exports.nodeType && exports; + var freeModule = 'object' == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal$1 == 'object' && commonjsGlobal$1; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof undefined == 'function' && + typeof undefined.amd == 'object' && + undefined.amd + ) { + undefined('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + + }(commonjsGlobal$1)); + }); + + 'use strict'; + + var util = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } + }; + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty$1(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var decode$1 = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty$1(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }; + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var stringifyPrimitive$1 = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + }; + + var encode$1 = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive$1(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive$1(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive$1(obj[k])); + } + }).join(sep); + + } + + if (!name) { return ''; } + return encodeURIComponent(stringifyPrimitive$1(name)) + eq + + encodeURIComponent(stringifyPrimitive$1(obj)); + }; + + var querystring = createCommonjsModule$1(function (module, exports) { + 'use strict'; + + exports.decode = exports.parse = decode$1; + exports.encode = exports.stringify = encode$1; + }); + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + + + + var parse = urlParse; + var resolve = urlResolve; + var resolveObject = urlResolveObject; + var format = urlFormat; + + var Url_1 = Url; + + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) { return url; } + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; + }; + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); + } + + Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + { result[rkey] = relative[rkey]; } + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())){ ; } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } + else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } + else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } + }; + + var url$1 = { + parse: parse, + resolve: resolve, + resolveObject: resolveObject, + format: format, + Url: Url_1 + }; + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + exports.ENV = void 0; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(exports.ENV || (exports.ENV = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + exports.RENDERER_TYPE = void 0; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + exports.BUFFER_BITS = void 0; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(exports.BUFFER_BITS || (exports.BUFFER_BITS = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + exports.BLEND_MODES = void 0; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(exports.BLEND_MODES || (exports.BLEND_MODES = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + exports.DRAW_MODES = void 0; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(exports.DRAW_MODES || (exports.DRAW_MODES = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + exports.FORMATS = void 0; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(exports.FORMATS || (exports.FORMATS = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + exports.TARGETS = void 0; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(exports.TARGETS || (exports.TARGETS = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + exports.TYPES = void 0; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(exports.TYPES || (exports.TYPES = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + exports.SAMPLER_TYPES = void 0; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(exports.SAMPLER_TYPES || (exports.SAMPLER_TYPES = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + exports.SCALE_MODES = void 0; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(exports.SCALE_MODES || (exports.SCALE_MODES = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + exports.WRAP_MODES = void 0; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(exports.WRAP_MODES || (exports.WRAP_MODES = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + exports.MIPMAP_MODES = void 0; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(exports.MIPMAP_MODES || (exports.MIPMAP_MODES = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + exports.ALPHA_MODES = void 0; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(exports.ALPHA_MODES || (exports.ALPHA_MODES = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + exports.CLEAR_MODES = void 0; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(exports.CLEAR_MODES || (exports.CLEAR_MODES = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + exports.GC_MODES = void 0; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(exports.GC_MODES || (exports.GC_MODES = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + exports.PRECISION = void 0; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(exports.PRECISION || (exports.PRECISION = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + exports.MASK_TYPES = void 0; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(exports.MASK_TYPES || (exports.MASK_TYPES = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + exports.COLOR_MASK_BITS = void 0; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(exports.COLOR_MASK_BITS || (exports.COLOR_MASK_BITS = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + exports.MSAA_QUALITY = void 0; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(exports.MSAA_QUALITY || (exports.MSAA_QUALITY = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + exports.BUFFER_TYPE = void 0; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(exports.BUFFER_TYPE || (exports.BUFFER_TYPE = {})); + + /*! + * @pixi/utils - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/utils is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * This file contains redeclared types for Node `url` and `querystring` modules. These modules + * don't provide their own typings but instead are a part of the full Node typings. The purpose of + * this file is to redeclare the required types to avoid having the whole Node types as a + * dependency. + */ + var url = { + parse: parse, + format: format, + resolve: resolve, + }; + + function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError("Path must be a string. Received " + JSON.stringify(path)); + } + } + function removeUrlParams(url) { + var re = url.split('?')[0]; + return re.split('#')[0]; + } + function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string + } + function replaceAll(str, find, replace) { + return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); + } + // Resolves . and .. elements in a path with directory names + function normalizeStringPosix(path, allowAboveRoot) { + var res = ''; + var lastSegmentLength = 0; + var lastSlash = -1; + var dots = 0; + var code; + for (var i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (code === 47) { + break; + } + else { + code = 47; + } + if (code === 47) { + if (lastSlash === i - 1 || dots === 1) { ; } + else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 + || lastSegmentLength !== 2 + || res.charCodeAt(res.length - 1) !== 46 + || res.charCodeAt(res.length - 2) !== 46) { + if (res.length > 2) { + var lastSlashIndex = res.lastIndexOf('/'); + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf('/'); + } + lastSlash = i; + dots = 0; + continue; + } + } + else if (res.length === 2 || res.length === 1) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) { + res += '/..'; + } + else { + res = '..'; + } + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += "/" + path.slice(lastSlash + 1, i); + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === 46 && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; + } + var path = { + /** + * Converts a path to posix format. + * @param path - The path to convert to posix + */ + toPosix: function (path) { return replaceAll(path, '\\', '/'); }, + /** + * Checks if the path is a URL + * @param path - The path to check + */ + isUrl: function (path) { return (/^https?:/).test(this.toPosix(path)); }, + /** + * Checks if the path is a data URL + * @param path - The path to check + */ + isDataUrl: function (path) { + // eslint-disable-next-line max-len + return (/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i) + .test(path); + }, + /** + * Checks if the path has a protocol e.g. http:// + * This will return true for windows file paths + * @param path - The path to check + */ + hasProtocol: function (path) { return (/^[^/:]+:\//).test(this.toPosix(path)); }, + /** + * Returns the protocol of the path e.g. http://, C:/, file:/// + * @param path - The path to get the protocol from + */ + getProtocol: function (path) { + assertPath(path); + path = this.toPosix(path); + var protocol = ''; + var isFile = (/^file:\/\/\//).exec(path); + var isHttp = (/^[^/:]+:\/\//).exec(path); + var isWindows = (/^[^/:]+:\//).exec(path); + if (isFile || isHttp || isWindows) { + var arr = (isFile === null || isFile === void 0 ? void 0 : isFile[0]) || (isHttp === null || isHttp === void 0 ? void 0 : isHttp[0]) || (isWindows === null || isWindows === void 0 ? void 0 : isWindows[0]); + protocol = arr; + path = path.slice(arr.length); + } + return protocol; + }, + /** + * Converts URL to an absolute path. + * When loading from a Web Worker, we must use absolute paths. + * If the URL is already absolute we return it as is + * If it's not, we convert it + * @param url - The URL to test + * @param customBaseUrl - The base URL to use + * @param customRootUrl - The root URL to use + */ + toAbsolute: function (url, customBaseUrl, customRootUrl) { + if (this.isDataUrl(url)) + { return url; } + var baseUrl = removeUrlParams(this.toPosix(customBaseUrl !== null && customBaseUrl !== void 0 ? customBaseUrl : settings$1.ADAPTER.getBaseUrl())); + var rootUrl = removeUrlParams(this.toPosix(customRootUrl !== null && customRootUrl !== void 0 ? customRootUrl : this.rootname(baseUrl))); + assertPath(url); + url = this.toPosix(url); + // root relative url + if (url.startsWith('/')) { + return path.join(rootUrl, url.slice(1)); + } + var absolutePath = this.isAbsolute(url) ? url : this.join(baseUrl, url); + return absolutePath; + }, + /** + * Normalizes the given path, resolving '..' and '.' segments + * @param path - The path to normalize + */ + normalize: function (path) { + path = this.toPosix(path); + assertPath(path); + if (path.length === 0) + { return '.'; } + var protocol = ''; + var isAbsolute = path.startsWith('/'); + if (this.hasProtocol(path)) { + protocol = this.rootname(path); + path = path.slice(protocol.length); + } + var trailingSeparator = path.endsWith('/'); + // Normalize the path + path = normalizeStringPosix(path, false); + if (path.length > 0 && trailingSeparator) + { path += '/'; } + if (isAbsolute) + { return "/" + path; } + return protocol + path; + }, + /** + * Determines if path is an absolute path. + * Absolute paths can be urls, data urls, or paths on disk + * @param path - The path to test + */ + isAbsolute: function (path) { + assertPath(path); + path = this.toPosix(path); + if (this.hasProtocol(path)) + { return true; } + return path.startsWith('/'); + }, + /** + * Joins all given path segments together using the platform-specific separator as a delimiter, + * then normalizes the resulting path + * @param segments - The segments of the path to join + */ + join: function () { + var arguments$1 = arguments; + + var _a; + var segments = []; + for (var _i = 0; _i < arguments.length; _i++) { + segments[_i] = arguments$1[_i]; + } + if (segments.length === 0) { + return '.'; + } + var joined; + for (var i = 0; i < segments.length; ++i) { + var arg = segments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) + { joined = arg; } + else { + var prevArg = (_a = segments[i - 1]) !== null && _a !== void 0 ? _a : ''; + if (this.extname(prevArg)) { + joined += "/../" + arg; + } + else { + joined += "/" + arg; + } + } + } + } + if (joined === undefined) { + return '.'; + } + return this.normalize(joined); + }, + /** + * Returns the directory name of a path + * @param path - The path to parse + */ + dirname: function (path) { + assertPath(path); + if (path.length === 0) + { return '.'; } + path = this.toPosix(path); + var code = path.charCodeAt(0); + var hasRoot = code === 47; + var end = -1; + var matchedSlash = true; + var proto = this.getProtocol(path); + var origpath = path; + path = path.slice(proto.length); + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47) { + if (!matchedSlash) { + end = i; + break; + } + } + else { + // We saw the first non-path separator + matchedSlash = false; + } + } + // if end is -1 and its a url then we need to add the path back + // eslint-disable-next-line no-nested-ternary + if (end === -1) + { return hasRoot ? '/' : this.isUrl(origpath) ? proto + path : proto; } + if (hasRoot && end === 1) + { return '//'; } + return proto + path.slice(0, end); + }, + /** + * Returns the root of the path e.g. /, C:/, file:///, http://domain.com/ + * @param path - The path to parse + */ + rootname: function (path) { + assertPath(path); + path = this.toPosix(path); + var root = ''; + if (path.startsWith('/')) + { root = '/'; } + else { + root = this.getProtocol(path); + } + if (this.isUrl(path)) { + // need to find the first path separator + var index = path.indexOf('/', root.length); + if (index !== -1) { + root = path.slice(0, index); + } + else + { root = path; } + if (!root.endsWith('/')) + { root += '/'; } + } + return root; + }, + /** + * Returns the last portion of a path + * @param path - The path to test + * @param ext - Optional extension to remove + */ + basename: function (path, ext) { + assertPath(path); + if (ext) + { assertPath(ext); } + path = this.toPosix(path); + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) + { return ''; } + var extIdx = ext.length - 1; + var firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } + else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + if (start === end) + { end = firstNonSlashEnd; } + else if (end === -1) + { end = path.length; } + return path.slice(start, end); + } + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + if (end === -1) + { return ''; } + return path.slice(start, end); + }, + /** + * Returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last + * portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than + * the first character of the basename of path, an empty string is returned. + * @param path - The path to parse + */ + extname: function (path) { + assertPath(path); + path = this.toPosix(path); + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + { startDot = i; } + else if (preDotState !== 1) + { preDotState = 1; } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 + // We saw a non-dot character immediately before the dot + || preDotState === 0 + // The (right-most) trimmed path component is exactly '..' + // eslint-disable-next-line no-mixed-operators + || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); + }, + /** + * Parses a path into an object containing the 'root', `dir`, `base`, `ext`, and `name` properties. + * @param path - The path to parse + */ + parse: function (path) { + assertPath(path); + var ret = { root: '', dir: '', base: '', ext: '', name: '' }; + if (path.length === 0) + { return ret; } + path = this.toPosix(path); + var code = path.charCodeAt(0); + var isAbsolute = this.isAbsolute(path); + var start; + ret.root = this.rootname(path); + if (isAbsolute || this.hasProtocol(path)) { + start = 1; + } + else { + start = 0; + } + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + var i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + // Get non-dir info + for (; i >= start; --i) { + code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + { startDot = i; } + else if (preDotState !== 1) + { preDotState = 1; } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 + // We saw a non-dot character immediately before the dot + || preDotState === 0 + // The (right-most) trimmed path component is exactly '..' + // eslint-disable-next-line no-mixed-operators + || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) + { ret.base = ret.name = path.slice(1, end); } + else + { ret.base = ret.name = path.slice(startPart, end); } + } + } + else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } + else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + ret.dir = this.dirname(path); + return ret; + }, + sep: '/', + delimiter: ':' + }; + + /** + * The prefix that denotes a URL is for a retina asset. + * @static + * @name RETINA_PREFIX + * @memberof PIXI.settings + * @type {RegExp} + * @default /@([0-9\.]+)x/ + * @example `@2x` + */ + settings$1.RETINA_PREFIX = /@([0-9\.]+)x/; + /** + * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. + * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when + * using WebGL. + * + * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible. + * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the + * browser. + * + * If your application requires high performance rendering, you may wish to set this to false. + * We recommend one of two options if you decide to set this flag to false: + * + * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is + * not supported. + * + * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS + * renderer, and show an error message to the user if the function returns false, explaining that their device & browser + * combination does not support high performance WebGL. + * This is a much better strategy than trying to create a PixiJS renderer and finding it then fails. + * @static + * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings$1.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false; + + var saidHello = false; + var VERSION$1 = '6.5.3'; + /** + * Skips the hello message of renderers that are created after this is run. + * @function skipHello + * @memberof PIXI.utils + */ + function skipHello() { + saidHello = true; + } + /** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever make you a jerk face. + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ + function sayHello(type) { + var _a; + if (saidHello) { + return; + } + if (settings$1.ADAPTER.getNavigator().userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = [ + "\n %c %c %c PixiJS " + VERSION$1 + " - \u2730 " + type + " \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n", + 'background: #ff66a5; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff66a5; background: #030307; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'background: #ffc3dc; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;' ]; + (_a = globalThis.console).log.apply(_a, args); + } + else if (globalThis.console) { + globalThis.console.log("PixiJS " + VERSION$1 + " - " + type + " - http://www.pixijs.com/"); + } + saidHello = true; + } + + var supported; + /** + * Helper for checking for WebGL support. + * @memberof PIXI.utils + * @function isWebGLSupported + * @returns {boolean} Is WebGL supported. + */ + function isWebGLSupported() { + if (typeof supported === 'undefined') { + supported = (function supported() { + var contextOptions = { + stencil: true, + failIfMajorPerformanceCaveat: settings$1.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT, + }; + try { + if (!settings$1.ADAPTER.getWebGLRenderingContext()) { + return false; + } + var canvas = settings$1.ADAPTER.createCanvas(); + var gl = (canvas.getContext('webgl', contextOptions) + || canvas.getContext('experimental-webgl', contextOptions)); + var success = !!(gl && gl.getContextAttributes().stencil); + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + if (loseContext) { + loseContext.loseContext(); + } + } + gl = null; + return success; + } + catch (e) { + return false; + } + })(); + } + return supported; + } + + var aliceblue = "#f0f8ff"; + var antiquewhite = "#faebd7"; + var aqua = "#00ffff"; + var aquamarine = "#7fffd4"; + var azure = "#f0ffff"; + var beige = "#f5f5dc"; + var bisque = "#ffe4c4"; + var black = "#000000"; + var blanchedalmond = "#ffebcd"; + var blue = "#0000ff"; + var blueviolet = "#8a2be2"; + var brown = "#a52a2a"; + var burlywood = "#deb887"; + var cadetblue = "#5f9ea0"; + var chartreuse = "#7fff00"; + var chocolate = "#d2691e"; + var coral = "#ff7f50"; + var cornflowerblue = "#6495ed"; + var cornsilk = "#fff8dc"; + var crimson = "#dc143c"; + var cyan = "#00ffff"; + var darkblue = "#00008b"; + var darkcyan = "#008b8b"; + var darkgoldenrod = "#b8860b"; + var darkgray = "#a9a9a9"; + var darkgreen = "#006400"; + var darkgrey = "#a9a9a9"; + var darkkhaki = "#bdb76b"; + var darkmagenta = "#8b008b"; + var darkolivegreen = "#556b2f"; + var darkorange = "#ff8c00"; + var darkorchid = "#9932cc"; + var darkred = "#8b0000"; + var darksalmon = "#e9967a"; + var darkseagreen = "#8fbc8f"; + var darkslateblue = "#483d8b"; + var darkslategray = "#2f4f4f"; + var darkslategrey = "#2f4f4f"; + var darkturquoise = "#00ced1"; + var darkviolet = "#9400d3"; + var deeppink = "#ff1493"; + var deepskyblue = "#00bfff"; + var dimgray = "#696969"; + var dimgrey = "#696969"; + var dodgerblue = "#1e90ff"; + var firebrick = "#b22222"; + var floralwhite = "#fffaf0"; + var forestgreen = "#228b22"; + var fuchsia = "#ff00ff"; + var gainsboro = "#dcdcdc"; + var ghostwhite = "#f8f8ff"; + var goldenrod = "#daa520"; + var gold = "#ffd700"; + var gray = "#808080"; + var green = "#008000"; + var greenyellow = "#adff2f"; + var grey = "#808080"; + var honeydew = "#f0fff0"; + var hotpink = "#ff69b4"; + var indianred = "#cd5c5c"; + var indigo = "#4b0082"; + var ivory = "#fffff0"; + var khaki = "#f0e68c"; + var lavenderblush = "#fff0f5"; + var lavender = "#e6e6fa"; + var lawngreen = "#7cfc00"; + var lemonchiffon = "#fffacd"; + var lightblue = "#add8e6"; + var lightcoral = "#f08080"; + var lightcyan = "#e0ffff"; + var lightgoldenrodyellow = "#fafad2"; + var lightgray = "#d3d3d3"; + var lightgreen = "#90ee90"; + var lightgrey = "#d3d3d3"; + var lightpink = "#ffb6c1"; + var lightsalmon = "#ffa07a"; + var lightseagreen = "#20b2aa"; + var lightskyblue = "#87cefa"; + var lightslategray = "#778899"; + var lightslategrey = "#778899"; + var lightsteelblue = "#b0c4de"; + var lightyellow = "#ffffe0"; + var lime = "#00ff00"; + var limegreen = "#32cd32"; + var linen = "#faf0e6"; + var magenta = "#ff00ff"; + var maroon = "#800000"; + var mediumaquamarine = "#66cdaa"; + var mediumblue = "#0000cd"; + var mediumorchid = "#ba55d3"; + var mediumpurple = "#9370db"; + var mediumseagreen = "#3cb371"; + var mediumslateblue = "#7b68ee"; + var mediumspringgreen = "#00fa9a"; + var mediumturquoise = "#48d1cc"; + var mediumvioletred = "#c71585"; + var midnightblue = "#191970"; + var mintcream = "#f5fffa"; + var mistyrose = "#ffe4e1"; + var moccasin = "#ffe4b5"; + var navajowhite = "#ffdead"; + var navy = "#000080"; + var oldlace = "#fdf5e6"; + var olive = "#808000"; + var olivedrab = "#6b8e23"; + var orange = "#ffa500"; + var orangered = "#ff4500"; + var orchid = "#da70d6"; + var palegoldenrod = "#eee8aa"; + var palegreen = "#98fb98"; + var paleturquoise = "#afeeee"; + var palevioletred = "#db7093"; + var papayawhip = "#ffefd5"; + var peachpuff = "#ffdab9"; + var peru = "#cd853f"; + var pink = "#ffc0cb"; + var plum = "#dda0dd"; + var powderblue = "#b0e0e6"; + var purple = "#800080"; + var rebeccapurple = "#663399"; + var red = "#ff0000"; + var rosybrown = "#bc8f8f"; + var royalblue = "#4169e1"; + var saddlebrown = "#8b4513"; + var salmon = "#fa8072"; + var sandybrown = "#f4a460"; + var seagreen = "#2e8b57"; + var seashell = "#fff5ee"; + var sienna = "#a0522d"; + var silver = "#c0c0c0"; + var skyblue = "#87ceeb"; + var slateblue = "#6a5acd"; + var slategray = "#708090"; + var slategrey = "#708090"; + var snow = "#fffafa"; + var springgreen = "#00ff7f"; + var steelblue = "#4682b4"; + var tan = "#d2b48c"; + var teal = "#008080"; + var thistle = "#d8bfd8"; + var tomato = "#ff6347"; + var turquoise = "#40e0d0"; + var violet = "#ee82ee"; + var wheat = "#f5deb3"; + var white = "#ffffff"; + var whitesmoke = "#f5f5f5"; + var yellow = "#ffff00"; + var yellowgreen = "#9acd32"; + var cssColorNames = { + aliceblue: aliceblue, + antiquewhite: antiquewhite, + aqua: aqua, + aquamarine: aquamarine, + azure: azure, + beige: beige, + bisque: bisque, + black: black, + blanchedalmond: blanchedalmond, + blue: blue, + blueviolet: blueviolet, + brown: brown, + burlywood: burlywood, + cadetblue: cadetblue, + chartreuse: chartreuse, + chocolate: chocolate, + coral: coral, + cornflowerblue: cornflowerblue, + cornsilk: cornsilk, + crimson: crimson, + cyan: cyan, + darkblue: darkblue, + darkcyan: darkcyan, + darkgoldenrod: darkgoldenrod, + darkgray: darkgray, + darkgreen: darkgreen, + darkgrey: darkgrey, + darkkhaki: darkkhaki, + darkmagenta: darkmagenta, + darkolivegreen: darkolivegreen, + darkorange: darkorange, + darkorchid: darkorchid, + darkred: darkred, + darksalmon: darksalmon, + darkseagreen: darkseagreen, + darkslateblue: darkslateblue, + darkslategray: darkslategray, + darkslategrey: darkslategrey, + darkturquoise: darkturquoise, + darkviolet: darkviolet, + deeppink: deeppink, + deepskyblue: deepskyblue, + dimgray: dimgray, + dimgrey: dimgrey, + dodgerblue: dodgerblue, + firebrick: firebrick, + floralwhite: floralwhite, + forestgreen: forestgreen, + fuchsia: fuchsia, + gainsboro: gainsboro, + ghostwhite: ghostwhite, + goldenrod: goldenrod, + gold: gold, + gray: gray, + green: green, + greenyellow: greenyellow, + grey: grey, + honeydew: honeydew, + hotpink: hotpink, + indianred: indianred, + indigo: indigo, + ivory: ivory, + khaki: khaki, + lavenderblush: lavenderblush, + lavender: lavender, + lawngreen: lawngreen, + lemonchiffon: lemonchiffon, + lightblue: lightblue, + lightcoral: lightcoral, + lightcyan: lightcyan, + lightgoldenrodyellow: lightgoldenrodyellow, + lightgray: lightgray, + lightgreen: lightgreen, + lightgrey: lightgrey, + lightpink: lightpink, + lightsalmon: lightsalmon, + lightseagreen: lightseagreen, + lightskyblue: lightskyblue, + lightslategray: lightslategray, + lightslategrey: lightslategrey, + lightsteelblue: lightsteelblue, + lightyellow: lightyellow, + lime: lime, + limegreen: limegreen, + linen: linen, + magenta: magenta, + maroon: maroon, + mediumaquamarine: mediumaquamarine, + mediumblue: mediumblue, + mediumorchid: mediumorchid, + mediumpurple: mediumpurple, + mediumseagreen: mediumseagreen, + mediumslateblue: mediumslateblue, + mediumspringgreen: mediumspringgreen, + mediumturquoise: mediumturquoise, + mediumvioletred: mediumvioletred, + midnightblue: midnightblue, + mintcream: mintcream, + mistyrose: mistyrose, + moccasin: moccasin, + navajowhite: navajowhite, + navy: navy, + oldlace: oldlace, + olive: olive, + olivedrab: olivedrab, + orange: orange, + orangered: orangered, + orchid: orchid, + palegoldenrod: palegoldenrod, + palegreen: palegreen, + paleturquoise: paleturquoise, + palevioletred: palevioletred, + papayawhip: papayawhip, + peachpuff: peachpuff, + peru: peru, + pink: pink, + plum: plum, + powderblue: powderblue, + purple: purple, + rebeccapurple: rebeccapurple, + red: red, + rosybrown: rosybrown, + royalblue: royalblue, + saddlebrown: saddlebrown, + salmon: salmon, + sandybrown: sandybrown, + seagreen: seagreen, + seashell: seashell, + sienna: sienna, + silver: silver, + skyblue: skyblue, + slateblue: slateblue, + slategray: slategray, + slategrey: slategrey, + snow: snow, + springgreen: springgreen, + steelblue: steelblue, + tan: tan, + teal: teal, + thistle: thistle, + tomato: tomato, + turquoise: turquoise, + violet: violet, + wheat: wheat, + white: white, + whitesmoke: whitesmoke, + yellow: yellow, + yellowgreen: yellowgreen + }; + + /** + * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0). + * @example + * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1] + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The hexadecimal number to convert + * @param {number[]} [out=[]] - If supplied, this array will be used rather than returning a new one + * @returns {number[]} An array representing the [R, G, B] of the color where all values are floats. + */ + function hex2rgb(hex, out) { + if (out === void 0) { out = []; } + out[0] = ((hex >> 16) & 0xFF) / 255; + out[1] = ((hex >> 8) & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + return out; + } + /** + * Converts a hexadecimal color number to a string. + * @example + * PIXI.utils.hex2string(0xffffff); // returns "#ffffff" + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex (e.g., `0xffffff`) + * @returns {string} The string color (e.g., `"#ffffff"`). + */ + function hex2string(hex) { + var hexString = hex.toString(16); + hexString = '000000'.substring(0, 6 - hexString.length) + hexString; + return "#" + hexString; + } + /** + * Converts a string to a hexadecimal color number. + * It can handle: + * hex strings starting with #: "#ffffff" + * hex strings starting with 0x: "0xffffff" + * hex strings without prefix: "ffffff" + * css colors: "black" + * @example + * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff + * @memberof PIXI.utils + * @function string2hex + * @param {string} string - The string color (e.g., `"#ffffff"`) + * @returns {number} Number in hexadecimal. + */ + function string2hex(string) { + if (typeof string === 'string') { + string = cssColorNames[string.toLowerCase()] || string; + if (string[0] === '#') { + string = string.slice(1); + } + } + return parseInt(string, 16); + } + /** + * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. + * @example + * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. + * @returns {number} Number in hexadecimal. + */ + function rgb2hex(rgb) { + return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0)); + } + + /** + * Corrects PixiJS blend, takes premultiplied alpha into account + * @memberof PIXI.utils + * @function mapPremultipliedBlendModes + * @private + * @returns {Array} Mapped modes. + */ + function mapPremultipliedBlendModes$1() { + var pm = []; + var npm = []; + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + pm[exports.BLEND_MODES.NORMAL_NPM] = exports.BLEND_MODES.NORMAL; + pm[exports.BLEND_MODES.ADD_NPM] = exports.BLEND_MODES.ADD; + pm[exports.BLEND_MODES.SCREEN_NPM] = exports.BLEND_MODES.SCREEN; + npm[exports.BLEND_MODES.NORMAL] = exports.BLEND_MODES.NORMAL_NPM; + npm[exports.BLEND_MODES.ADD] = exports.BLEND_MODES.ADD_NPM; + npm[exports.BLEND_MODES.SCREEN] = exports.BLEND_MODES.SCREEN_NPM; + var array = []; + array.push(npm); + array.push(pm); + return array; + } + /** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @constant premultiplyBlendMode + * @type {Array} + */ + var premultiplyBlendMode = mapPremultipliedBlendModes$1(); + /** + * changes blendMode according to texture format + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode - supposed blend mode + * @param {boolean} premultiplied - whether source is premultiplied + * @returns {number} true blend mode for this texture + */ + function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; + } + /** + * combines rgb and alpha to out array + * @memberof PIXI.utils + * @function premultiplyRgba + * @param {Float32Array|number[]} rgb - input rgb + * @param {number} alpha - alpha param + * @param {Float32Array} [out] - output + * @param {boolean} [premultiply=true] - do premultiply it + * @returns {Float32Array} vec4 rgba + */ + function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } + else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + return out; + } + /** + * premultiplies tint + * @memberof PIXI.utils + * @function premultiplyTint + * @param {number} tint - integer RGB + * @param {number} alpha - floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ + function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = ((tint >> 16) & 0xFF); + var G = ((tint >> 8) & 0xFF); + var B = (tint & 0xFF); + R = ((R * alpha) + 0.5) | 0; + G = ((G * alpha) + 0.5) | 0; + B = ((B * alpha) + 0.5) | 0; + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; + } + /** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * @memberof PIXI.utils + * @function premultiplyTintToRgba + * @param {number} tint - input tint + * @param {number} alpha - alpha param + * @param {Float32Array} [out] - output + * @param {boolean} [premultiply=true] - do premultiply it + * @returns {Float32Array} vec4 rgba + */ + function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = ((tint >> 16) & 0xFF) / 255.0; + out[1] = ((tint >> 8) & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + return out; + } + + /** + * Generic Mask Stack data structure + * @memberof PIXI.utils + * @function createIndicesForQuads + * @param {number} size - Number of quads + * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size` + * @returns {Uint16Array|Uint32Array} - Resulting index buffer + */ + function createIndicesForQuads(size, outBuffer) { + if (outBuffer === void 0) { outBuffer = null; } + // the total number of indices in our array, there are 6 points per quad. + var totalIndices = size * 6; + outBuffer = outBuffer || new Uint16Array(totalIndices); + if (outBuffer.length !== totalIndices) { + throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices); + } + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + outBuffer[i + 0] = j + 0; + outBuffer[i + 1] = j + 1; + outBuffer[i + 2] = j + 2; + outBuffer[i + 3] = j + 0; + outBuffer[i + 4] = j + 2; + outBuffer[i + 5] = j + 3; + } + return outBuffer; + } + + function getBufferType(array) { + if (array.BYTES_PER_ELEMENT === 4) { + if (array instanceof Float32Array) { + return 'Float32Array'; + } + else if (array instanceof Uint32Array) { + return 'Uint32Array'; + } + return 'Int32Array'; + } + else if (array.BYTES_PER_ELEMENT === 2) { + if (array instanceof Uint16Array) { + return 'Uint16Array'; + } + } + else if (array.BYTES_PER_ELEMENT === 1) { + if (array instanceof Uint8Array) { + return 'Uint8Array'; + } + } + // TODO map out the rest of the array elements! + return null; + } + + /* eslint-disable object-shorthand */ + var map$2 = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array }; + function interleaveTypedArrays$1(arrays, sizes) { + var outSize = 0; + var stride = 0; + var views = {}; + for (var i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + var buffer = new ArrayBuffer(outSize * 4); + var out = null; + var littleOffset = 0; + for (var i = 0; i < arrays.length; i++) { + var size = sizes[i]; + var array = arrays[i]; + /* + @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way + or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed? + */ + var type = getBufferType(array); + if (!views[type]) { + views[type] = new map$2[type](buffer); + } + out = views[type]; + for (var j = 0; j < array.length; j++) { + var indexStart = ((j / size | 0) * stride) + littleOffset; + var index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); + } + + // Taken from the bit-twiddle package + /** + * Rounds to next power of two. + * @function nextPow2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {number} - next rounded power of two + */ + function nextPow2(v) { + v += v === 0 ? 1 : 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; + } + /** + * Checks if a number is a power of two. + * @function isPow2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {boolean} `true` if value is power of two + */ + function isPow2(v) { + return !(v & (v - 1)) && (!!v); + } + /** + * Computes ceil of log base 2 + * @function log2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {number} logarithm base 2 + */ + function log2(v) { + var r = (v > 0xFFFF ? 1 : 0) << 4; + v >>>= r; + var shift = (v > 0xFF ? 1 : 0) << 3; + v >>>= shift; + r |= shift; + shift = (v > 0xF ? 1 : 0) << 2; + v >>>= shift; + r |= shift; + shift = (v > 0x3 ? 1 : 0) << 1; + v >>>= shift; + r |= shift; + return r | (v >> 1); + } + + /** + * Remove items from a javascript array without generating garbage + * @function removeItems + * @memberof PIXI.utils + * @param {Array} arr - Array to remove elements from + * @param {number} startIdx - starting index + * @param {number} removeCount - how many to remove + */ + function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + var i; + if (startIdx >= length || removeCount === 0) { + return; + } + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); + var len = length - removeCount; + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + arr.length = len; + } + + /** + * Returns sign of number + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ + function sign(n) { + if (n === 0) + { return 0; } + return n < 0 ? -1 : 1; + } + + var nextUid = 0; + /** + * Gets the next unique identifier + * @memberof PIXI.utils + * @function uid + * @returns {number} The next unique identifier to use. + */ + function uid() { + return ++nextUid; + } + + // A map of warning messages already fired + var warnings$1 = {}; + /** + * Helper for warning developers about deprecated features & settings. + * A stack track for warnings is given; useful for tracking-down where + * deprecated methods/properties/classes are being used within the code. + * @memberof PIXI.utils + * @function deprecation + * @param {string} version - The version where the feature became deprecated + * @param {string} message - Message should include what is deprecated, where, and the new solution + * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack + * this is mostly to ignore internal deprecation calls. + */ + function deprecation$1(version, message, ignoreDepth) { + if (ignoreDepth === void 0) { ignoreDepth = 3; } + // Ignore duplicat + if (warnings$1[message]) { + return; + } + /* eslint-disable no-console */ + var stack = new Error().stack; + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + } + else { + // chop off the stack trace which includes PixiJS internal calls + stack = stack.split('\n').splice(ignoreDepth).join('\n'); + if (console.groupCollapsed) { + console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); + console.warn(stack); + console.groupEnd(); + } + else { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + console.warn(stack); + } + } + /* eslint-enable no-console */ + warnings$1[message] = true; + } + + /** + * @todo Describe property usage + * @static + * @name ProgramCache + * @memberof PIXI.utils + * @type {object} + */ + var ProgramCache = {}; + /** + * @todo Describe property usage + * @static + * @name TextureCache + * @memberof PIXI.utils + * @type {object} + */ + var TextureCache = Object.create(null); + /** + * @todo Describe property usage + * @static + * @name BaseTextureCache + * @memberof PIXI.utils + * @type {object} + */ + var BaseTextureCache = Object.create(null); + /** + * Destroys all texture in the cache + * @memberof PIXI.utils + * @function destroyTextureCache + */ + function destroyTextureCache() { + var key; + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } + } + /** + * Removes all textures from cache, but does not destroy them + * @memberof PIXI.utils + * @function clearTextureCache + */ + function clearTextureCache() { + var key; + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } + } + + /** + * Creates a Canvas element of the given size to be used as a target for rendering to. + * @class + * @memberof PIXI.utils + */ + var CanvasRenderTarget = /** @class */ (function () { + /** + * @param width - the width for the newly created canvas + * @param height - the height for the newly created canvas + * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + this.canvas = settings$1.ADAPTER.createCanvas(); + this.context = this.canvas.getContext('2d'); + this.resolution = resolution || settings$1.RESOLUTION; + this.resize(width, height); + } + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * @private + */ + CanvasRenderTarget.prototype.clear = function () { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + /** + * Resizes the canvas to the specified width and height. + * @param desiredWidth - the desired width of the canvas + * @param desiredHeight - the desired height of the canvas + */ + CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) { + this.canvas.width = Math.round(desiredWidth * this.resolution); + this.canvas.height = Math.round(desiredHeight * this.resolution); + }; + /** Destroys this canvas. */ + CanvasRenderTarget.prototype.destroy = function () { + this.context = null; + this.canvas = null; + }; + Object.defineProperty(CanvasRenderTarget.prototype, "width", { + /** + * The width of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.width; + }, + set: function (val) { + this.canvas.width = Math.round(val); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CanvasRenderTarget.prototype, "height", { + /** + * The height of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.height; + }, + set: function (val) { + this.canvas.height = Math.round(val); + }, + enumerable: false, + configurable: true + }); + return CanvasRenderTarget; + }()); + + /** + * Trim transparent borders from a canvas + * @memberof PIXI.utils + * @function trimCanvas + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ + function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + var width = canvas.width; + var height = canvas.height; + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + var bound = { + top: null, + left: null, + right: null, + bottom: null, + }; + var data = null; + var i; + var x; + var y; + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = (i / 4) % width; + y = ~~((i / 4) / width); + if (bound.top === null) { + bound.top = y; + } + if (bound.left === null) { + bound.left = x; + } + else if (x < bound.left) { + bound.left = x; + } + if (bound.right === null) { + bound.right = x + 1; + } + else if (bound.right < x) { + bound.right = x + 1; + } + if (bound.bottom === null) { + bound.bottom = y; + } + else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + if (bound.top !== null) { + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + data = context.getImageData(bound.left, bound.top, width, height); + } + return { + height: height, + width: width, + data: data, + }; + } + + /** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * @static + * @constant {RegExp|string} DATA_URI + * @memberof PIXI + * @example data:image/png;base64 + */ + var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; + + /** + * @memberof PIXI.utils + * @interface DecomposedDataUri + */ + /** + * type, eg. `image` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} mediaType + */ + /** + * Sub type, eg. `png` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} subType + */ + /** + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} charset + */ + /** + * Data encoding, eg. `base64` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} encoding + */ + /** + * The actual data + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} data + */ + /** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @returns {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined + */ + function decomposeDataUri(dataUri) { + var dataUriMatch = DATA_URI.exec(dataUri); + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, + data: dataUriMatch[5], + }; + } + return undefined; + } + + var tempAnchor$1; + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @returns {string} The crossOrigin value to use (or empty string for none). + */ + function determineCrossOrigin(url$1, loc) { + if (loc === void 0) { loc = globalThis.location; } + // data: and javascript: urls are considered same-origin + if (url$1.indexOf('data:') === 0) { + return ''; + } + // default is window.location + loc = loc || globalThis.location; + if (!tempAnchor$1) { + tempAnchor$1 = document.createElement('a'); + } + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor$1.href = url$1; + var parsedUrl = url.parse(tempAnchor$1.href); + var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); + // if cross origin + if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) { + return 'anonymous'; + } + return ''; + } + + /** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @returns {number} resolution / device pixel ratio of an asset + */ + function getResolutionOfUrl(url, defaultValue) { + var resolution = settings$1.RETINA_PREFIX.exec(url); + if (resolution) { + return parseFloat(resolution[1]); + } + return defaultValue !== undefined ? defaultValue : 1; + } + + var utils = { + __proto__: null, + BaseTextureCache: BaseTextureCache, + CanvasRenderTarget: CanvasRenderTarget, + DATA_URI: DATA_URI, + ProgramCache: ProgramCache, + TextureCache: TextureCache, + clearTextureCache: clearTextureCache, + correctBlendMode: correctBlendMode, + createIndicesForQuads: createIndicesForQuads, + decomposeDataUri: decomposeDataUri, + deprecation: deprecation$1, + destroyTextureCache: destroyTextureCache, + determineCrossOrigin: determineCrossOrigin, + getBufferType: getBufferType, + getResolutionOfUrl: getResolutionOfUrl, + hex2rgb: hex2rgb, + hex2string: hex2string, + interleaveTypedArrays: interleaveTypedArrays$1, + isPow2: isPow2, + isWebGLSupported: isWebGLSupported, + log2: log2, + nextPow2: nextPow2, + path: path, + premultiplyBlendMode: premultiplyBlendMode, + premultiplyRgba: premultiplyRgba, + premultiplyTint: premultiplyTint, + premultiplyTintToRgba: premultiplyTintToRgba, + removeItems: removeItems, + rgb2hex: rgb2hex, + sayHello: sayHello, + sign: sign, + skipHello: skipHello, + string2hex: string2hex, + trimCanvas: trimCanvas, + uid: uid, + url: url, + isMobile: isMobile$2, + EventEmitter: eventemitter3, + earcut: earcut_1 + }; + + /*! + * @pixi/math - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/math is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Two Pi. + * @static + * @member {number} + * @memberof PIXI + */ + var PI_2 = Math.PI * 2; + /** + * Conversion factor for converting radians to degrees. + * @static + * @member {number} RAD_TO_DEG + * @memberof PIXI + */ + var RAD_TO_DEG = 180 / Math.PI; + /** + * Conversion factor for converting degrees to radians. + * @static + * @member {number} + * @memberof PIXI + */ + var DEG_TO_RAD = Math.PI / 180; + /** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * @static + * @memberof PIXI + * @enum {number} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ + exports.SHAPES = void 0; + (function (SHAPES) { + SHAPES[SHAPES["POLY"] = 0] = "POLY"; + SHAPES[SHAPES["RECT"] = 1] = "RECT"; + SHAPES[SHAPES["CIRC"] = 2] = "CIRC"; + SHAPES[SHAPES["ELIP"] = 3] = "ELIP"; + SHAPES[SHAPES["RREC"] = 4] = "RREC"; + })(exports.SHAPES || (exports.SHAPES = {})); + + /** + * The Point object represents a location in a two-dimensional coordinate system, where `x` represents + * the position on the horizontal axis and `y` represents the position on the vertical axis + * @class + * @memberof PIXI + * @implements {IPoint} + */ + var Point = /** @class */ (function () { + /** + * Creates a new `Point` + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point(x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + /** Position of the point on the x axis */ + this.x = 0; + /** Position of the point on the y axis */ + this.y = 0; + this.x = x; + this.y = y; + } + /** + * Creates a clone of this point + * @returns A clone of this point + */ + Point.prototype.clone = function () { + return new Point(this.x, this.y); + }; + /** + * Copies `x` and `y` from the given point into this point + * @param p - The point to copy from + * @returns The point instance itself + */ + Point.prototype.copyFrom = function (p) { + this.set(p.x, p.y); + return this; + }; + /** + * Copies this point's x and y into the given point (`p`). + * @param p - The point to copy to. Can be any of type that is or extends `IPointData` + * @returns The point (`p`) with values updated + */ + Point.prototype.copyTo = function (p) { + p.set(this.x, this.y); + return p; + }; + /** + * Accepts another point (`p`) and returns `true` if the given point is equal to this point + * @param p - The point to check + * @returns Returns `true` if both `x` and `y` are equal + */ + Point.prototype.equals = function (p) { + return (p.x === this.x) && (p.y === this.y); + }; + /** + * Sets the point to a new `x` and `y` position. + * If `y` is omitted, both `x` and `y` will be set to `x`. + * @param {number} [x=0] - position of the point on the `x` axis + * @param {number} [y=x] - position of the point on the `y` axis + * @returns The point instance itself + */ + Point.prototype.set = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = x; } + this.x = x; + this.y = y; + return this; + }; + Point.prototype.toString = function () { + return "[@pixi/math:Point x=" + this.x + " y=" + this.y + "]"; + }; + return Point; + }()); + + var tempPoints$1 = [new Point(), new Point(), new Point(), new Point()]; + /** + * Size object, contains width and height + * @memberof PIXI + * @typedef {object} ISize + * @property {number} width - Width component + * @property {number} height - Height component + */ + /** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * @memberof PIXI + */ + var Rectangle = /** @class */ (function () { + /** + * @param x - The X coordinate of the upper-left corner of the rectangle + * @param y - The Y coordinate of the upper-left corner of the rectangle + * @param width - The overall width of the rectangle + * @param height - The overall height of the rectangle + */ + function Rectangle(x, y, width, height) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + this.x = Number(x); + this.y = Number(y); + this.width = Number(width); + this.height = Number(height); + this.type = exports.SHAPES.RECT; + } + Object.defineProperty(Rectangle.prototype, "left", { + /** Returns the left edge of the rectangle. */ + get: function () { + return this.x; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "right", { + /** Returns the right edge of the rectangle. */ + get: function () { + return this.x + this.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "top", { + /** Returns the top edge of the rectangle. */ + get: function () { + return this.y; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottom", { + /** Returns the bottom edge of the rectangle. */ + get: function () { + return this.y + this.height; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle, "EMPTY", { + /** A constant empty rectangle. */ + get: function () { + return new Rectangle(0, 0, 0, 0); + }, + enumerable: false, + configurable: true + }); + /** + * Creates a clone of this Rectangle + * @returns a copy of the rectangle + */ + Rectangle.prototype.clone = function () { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + /** + * Copies another rectangle to this one. + * @param rectangle - The rectangle to copy from. + * @returns Returns itself. + */ + Rectangle.prototype.copyFrom = function (rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + return this; + }; + /** + * Copies this rectangle to another one. + * @param rectangle - The rectangle to copy to. + * @returns Returns given parameter. + */ + Rectangle.prototype.copyTo = function (rectangle) { + rectangle.x = this.x; + rectangle.y = this.y; + rectangle.width = this.width; + rectangle.height = this.height; + return rectangle; + }; + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coordinates are within this Rectangle + */ + Rectangle.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + return false; + }; + /** + * Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object. + * Returns true only if the area of the intersection is >0, this means that Rectangles + * sharing a side are not overlapping. Another side effect is that an arealess rectangle + * (width or height equal to zero) can't intersect any other rectangle. + * @param {Rectangle} other - The Rectangle to intersect with `this`. + * @param {Matrix} transform - The transformation matrix of `other`. + * @returns {boolean} A value of `true` if the transformed `other` Rectangle intersects with `this`; otherwise `false`. + */ + Rectangle.prototype.intersects = function (other, transform) { + if (!transform) { + var x0_1 = this.x < other.x ? other.x : this.x; + var x1_1 = this.right > other.right ? other.right : this.right; + if (x1_1 <= x0_1) { + return false; + } + var y0_1 = this.y < other.y ? other.y : this.y; + var y1_1 = this.bottom > other.bottom ? other.bottom : this.bottom; + return y1_1 > y0_1; + } + var x0 = this.left; + var x1 = this.right; + var y0 = this.top; + var y1 = this.bottom; + if (x1 <= x0 || y1 <= y0) { + return false; + } + var lt = tempPoints$1[0].set(other.left, other.top); + var lb = tempPoints$1[1].set(other.left, other.bottom); + var rt = tempPoints$1[2].set(other.right, other.top); + var rb = tempPoints$1[3].set(other.right, other.bottom); + if (rt.x <= lt.x || lb.y <= lt.y) { + return false; + } + var s = Math.sign((transform.a * transform.d) - (transform.b * transform.c)); + if (s === 0) { + return false; + } + transform.apply(lt, lt); + transform.apply(lb, lb); + transform.apply(rt, rt); + transform.apply(rb, rb); + if (Math.max(lt.x, lb.x, rt.x, rb.x) <= x0 + || Math.min(lt.x, lb.x, rt.x, rb.x) >= x1 + || Math.max(lt.y, lb.y, rt.y, rb.y) <= y0 + || Math.min(lt.y, lb.y, rt.y, rb.y) >= y1) { + return false; + } + var nx = s * (lb.y - lt.y); + var ny = s * (lt.x - lb.x); + var n00 = (nx * x0) + (ny * y0); + var n10 = (nx * x1) + (ny * y0); + var n01 = (nx * x0) + (ny * y1); + var n11 = (nx * x1) + (ny * y1); + if (Math.max(n00, n10, n01, n11) <= (nx * lt.x) + (ny * lt.y) + || Math.min(n00, n10, n01, n11) >= (nx * rb.x) + (ny * rb.y)) { + return false; + } + var mx = s * (lt.y - rt.y); + var my = s * (rt.x - lt.x); + var m00 = (mx * x0) + (my * y0); + var m10 = (mx * x1) + (my * y0); + var m01 = (mx * x0) + (my * y1); + var m11 = (mx * x1) + (my * y1); + if (Math.max(m00, m10, m01, m11) <= (mx * lt.x) + (my * lt.y) + || Math.min(m00, m10, m01, m11) >= (mx * rb.x) + (my * rb.y)) { + return false; + } + return true; + }; + /** + * Pads the rectangle making it grow in all directions. + * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. + * @param paddingX - The horizontal padding amount. + * @param paddingY - The vertical padding amount. + * @returns Returns itself. + */ + Rectangle.prototype.pad = function (paddingX, paddingY) { + if (paddingX === void 0) { paddingX = 0; } + if (paddingY === void 0) { paddingY = paddingX; } + this.x -= paddingX; + this.y -= paddingY; + this.width += paddingX * 2; + this.height += paddingY * 2; + return this; + }; + /** + * Fits this rectangle around the passed one. + * @param rectangle - The rectangle to fit. + * @returns Returns itself. + */ + Rectangle.prototype.fit = function (rectangle) { + var x1 = Math.max(this.x, rectangle.x); + var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.max(this.y, rectangle.y); + var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = Math.max(x2 - x1, 0); + this.y = y1; + this.height = Math.max(y2 - y1, 0); + return this; + }; + /** + * Enlarges rectangle that way its corners lie on grid + * @param resolution - resolution + * @param eps - precision + * @returns Returns itself. + */ + Rectangle.prototype.ceil = function (resolution, eps) { + if (resolution === void 0) { resolution = 1; } + if (eps === void 0) { eps = 0.001; } + var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; + var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; + this.x = Math.floor((this.x + eps) * resolution) / resolution; + this.y = Math.floor((this.y + eps) * resolution) / resolution; + this.width = x2 - this.x; + this.height = y2 - this.y; + return this; + }; + /** + * Enlarges this rectangle to include the passed rectangle. + * @param rectangle - The rectangle to include. + * @returns Returns itself. + */ + Rectangle.prototype.enlarge = function (rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + return this; + }; + Rectangle.prototype.toString = function () { + return "[@pixi/math:Rectangle x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]"; + }; + return Rectangle; + }()); + + /** + * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects. + * @memberof PIXI + */ + var Circle = /** @class */ (function () { + /** + * @param x - The X coordinate of the center of this circle + * @param y - The Y coordinate of the center of this circle + * @param radius - The radius of the circle + */ + function Circle(x, y, radius) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (radius === void 0) { radius = 0; } + this.x = x; + this.y = y; + this.radius = radius; + this.type = exports.SHAPES.CIRC; + } + /** + * Creates a clone of this Circle instance + * @returns A copy of the Circle + */ + Circle.prototype.clone = function () { + return new Circle(this.x, this.y, this.radius); + }; + /** + * Checks whether the x and y coordinates given are contained within this circle + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coordinates are within this Circle + */ + Circle.prototype.contains = function (x, y) { + if (this.radius <= 0) { + return false; + } + var r2 = this.radius * this.radius; + var dx = (this.x - x); + var dy = (this.y - y); + dx *= dx; + dy *= dy; + return (dx + dy <= r2); + }; + /** + * Returns the framing rectangle of the circle as a Rectangle object + * @returns The framing rectangle + */ + Circle.prototype.getBounds = function () { + return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + Circle.prototype.toString = function () { + return "[@pixi/math:Circle x=" + this.x + " y=" + this.y + " radius=" + this.radius + "]"; + }; + return Circle; + }()); + + /** + * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects. + * @memberof PIXI + */ + var Ellipse = /** @class */ (function () { + /** + * @param x - The X coordinate of the center of this ellipse + * @param y - The Y coordinate of the center of this ellipse + * @param halfWidth - The half width of this ellipse + * @param halfHeight - The half height of this ellipse + */ + function Ellipse(x, y, halfWidth, halfHeight) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (halfWidth === void 0) { halfWidth = 0; } + if (halfHeight === void 0) { halfHeight = 0; } + this.x = x; + this.y = y; + this.width = halfWidth; + this.height = halfHeight; + this.type = exports.SHAPES.ELIP; + } + /** + * Creates a clone of this Ellipse instance + * @returns {PIXI.Ellipse} A copy of the ellipse + */ + Ellipse.prototype.clone = function () { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coords are within this ellipse + */ + Ellipse.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + // normalize the coords to an ellipse with center 0,0 + var normx = ((x - this.x) / this.width); + var normy = ((y - this.y) / this.height); + normx *= normx; + normy *= normy; + return (normx + normy <= 1); + }; + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * @returns The framing rectangle + */ + Ellipse.prototype.getBounds = function () { + return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + }; + Ellipse.prototype.toString = function () { + return "[@pixi/math:Ellipse x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]"; + }; + return Ellipse; + }()); + + /** + * A class to define a shape via user defined coordinates. + * @memberof PIXI + */ + var Polygon = /** @class */ (function () { + /** + * @param {PIXI.IPointData[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + var arguments$1 = arguments; + + var points = []; + for (var _i = 0; _i < arguments.length; _i++) { + points[_i] = arguments$1[_i]; + } + var flat = Array.isArray(points[0]) ? points[0] : points; + // if this is an array of points, convert it to a flat array of numbers + if (typeof flat[0] !== 'number') { + var p = []; + for (var i = 0, il = flat.length; i < il; i++) { + p.push(flat[i].x, flat[i].y); + } + flat = p; + } + this.points = flat; + this.type = exports.SHAPES.POLY; + this.closeStroke = true; + } + /** + * Creates a clone of this polygon. + * @returns - A copy of the polygon. + */ + Polygon.prototype.clone = function () { + var points = this.points.slice(); + var polygon = new Polygon(points); + polygon.closeStroke = this.closeStroke; + return polygon; + }; + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon. + * @param x - The X coordinate of the point to test. + * @param y - The Y coordinate of the point to test. + * @returns - Whether the x/y coordinates are within this polygon. + */ + Polygon.prototype.contains = function (x, y) { + var inside = false; + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[(i * 2) + 1]; + var xj = this.points[j * 2]; + var yj = this.points[(j * 2) + 1]; + var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi); + if (intersect) { + inside = !inside; + } + } + return inside; + }; + Polygon.prototype.toString = function () { + return "[@pixi/math:Polygon" + + ("closeStroke=" + this.closeStroke) + + ("points=" + this.points.reduce(function (pointsDesc, currentPoint) { return pointsDesc + ", " + currentPoint; }, '') + "]"); + }; + return Polygon; + }()); + + /** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * @memberof PIXI + */ + var RoundedRectangle = /** @class */ (function () { + /** + * @param x - The X coordinate of the upper-left corner of the rounded rectangle + * @param y - The Y coordinate of the upper-left corner of the rounded rectangle + * @param width - The overall width of this rounded rectangle + * @param height - The overall height of this rounded rectangle + * @param radius - Controls the radius of the rounded corners + */ + function RoundedRectangle(x, y, width, height, radius) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + if (radius === void 0) { radius = 20; } + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.radius = radius; + this.type = exports.SHAPES.RREC; + } + /** + * Creates a clone of this Rounded Rectangle. + * @returns - A copy of the rounded rectangle. + */ + RoundedRectangle.prototype.clone = function () { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * @param x - The X coordinate of the point to test. + * @param y - The Y coordinate of the point to test. + * @returns - Whether the x/y coordinates are within this Rounded Rectangle. + */ + RoundedRectangle.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + var radius = Math.max(0, Math.min(this.radius, Math.min(this.width, this.height) / 2)); + if ((y >= this.y + radius && y <= this.y + this.height - radius) + || (x >= this.x + radius && x <= this.x + this.width - radius)) { + return true; + } + var dx = x - (this.x + radius); + var dy = y - (this.y + radius); + var radius2 = radius * radius; + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dx = x - (this.x + this.width - radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dy = y - (this.y + this.height - radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dx = x - (this.x + radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + } + } + return false; + }; + RoundedRectangle.prototype.toString = function () { + return "[@pixi/math:RoundedRectangle x=" + this.x + " y=" + this.y + + ("width=" + this.width + " height=" + this.height + " radius=" + this.radius + "]"); + }; + return RoundedRectangle; + }()); + + /** + * The ObservablePoint object represents a location in a two-dimensional coordinate system, where `x` represents + * the position on the horizontal axis and `y` represents the position on the vertical axis. + * + * An `ObservablePoint` is a point that triggers a callback when the point's position is changed. + * @memberof PIXI + */ + var ObservablePoint = /** @class */ (function () { + /** + * Creates a new `ObservablePoint` + * @param cb - callback function triggered when `x` and/or `y` are changed + * @param scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope, x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + this._x = x; + this._y = y; + this.cb = cb; + this.scope = scope; + } + /** + * Creates a clone of this point. + * The callback and scope params can be overridden otherwise they will default + * to the clone object's values. + * @override + * @param cb - The callback function triggered when `x` and/or `y` are changed + * @param scope - The owner of the callback + * @returns a copy of this observable point + */ + ObservablePoint.prototype.clone = function (cb, scope) { + if (cb === void 0) { cb = this.cb; } + if (scope === void 0) { scope = this.scope; } + return new ObservablePoint(cb, scope, this._x, this._y); + }; + /** + * Sets the point to a new `x` and `y` position. + * If `y` is omitted, both `x` and `y` will be set to `x`. + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=x] - position of the point on the y axis + * @returns The observable point instance itself + */ + ObservablePoint.prototype.set = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = x; } + if (this._x !== x || this._y !== y) { + this._x = x; + this._y = y; + this.cb.call(this.scope); + } + return this; + }; + /** + * Copies x and y from the given point (`p`) + * @param p - The point to copy from. Can be any of type that is or extends `IPointData` + * @returns The observable point instance itself + */ + ObservablePoint.prototype.copyFrom = function (p) { + if (this._x !== p.x || this._y !== p.y) { + this._x = p.x; + this._y = p.y; + this.cb.call(this.scope); + } + return this; + }; + /** + * Copies this point's x and y into that of the given point (`p`) + * @param p - The point to copy to. Can be any of type that is or extends `IPointData` + * @returns The point (`p`) with values updated + */ + ObservablePoint.prototype.copyTo = function (p) { + p.set(this._x, this._y); + return p; + }; + /** + * Accepts another point (`p`) and returns `true` if the given point is equal to this point + * @param p - The point to check + * @returns Returns `true` if both `x` and `y` are equal + */ + ObservablePoint.prototype.equals = function (p) { + return (p.x === this._x) && (p.y === this._y); + }; + ObservablePoint.prototype.toString = function () { + return "[@pixi/math:ObservablePoint x=" + 0 + " y=" + 0 + " scope=" + this.scope + "]"; + }; + Object.defineProperty(ObservablePoint.prototype, "x", { + /** Position of the observable point on the x axis. */ + get: function () { + return this._x; + }, + set: function (value) { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObservablePoint.prototype, "y", { + /** Position of the observable point on the y axis. */ + get: function () { + return this._y; + }, + set: function (value) { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + }, + enumerable: false, + configurable: true + }); + return ObservablePoint; + }()); + + /** + * The PixiJS Matrix as a class makes it a lot faster. + * + * Here is a representation of it: + * ```js + * | a | c | tx| + * | b | d | ty| + * | 0 | 0 | 1 | + * ``` + * @memberof PIXI + */ + var Matrix = /** @class */ (function () { + /** + * @param a - x scale + * @param b - y skew + * @param c - x skew + * @param d - y scale + * @param tx - x translation + * @param ty - y translation + */ + function Matrix(a, b, c, d, tx, ty) { + if (a === void 0) { a = 1; } + if (b === void 0) { b = 0; } + if (c === void 0) { c = 0; } + if (d === void 0) { d = 1; } + if (tx === void 0) { tx = 0; } + if (ty === void 0) { ty = 0; } + this.array = null; + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + } + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * @param array - The array that the matrix will be populated from. + */ + Matrix.prototype.fromArray = function (array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + /** + * Sets the matrix properties. + * @param a - Matrix component + * @param b - Matrix component + * @param c - Matrix component + * @param d - Matrix component + * @param tx - Matrix component + * @param ty - Matrix component + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.set = function (a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + return this; + }; + /** + * Creates an array from the current Matrix object. + * @param transpose - Whether we need to transpose the matrix or not + * @param [out=new Float32Array(9)] - If provided the array will be assigned to out + * @returns The newly created array which contains the matrix + */ + Matrix.prototype.toArray = function (transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + var array = out || this.array; + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + return array; + }; + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * @param pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @returns {PIXI.Point} The new point, transformed through this matrix + */ + Matrix.prototype.apply = function (pos, newPos) { + newPos = (newPos || new Point()); + var x = pos.x; + var y = pos.y; + newPos.x = (this.a * x) + (this.c * y) + this.tx; + newPos.y = (this.b * x) + (this.d * y) + this.ty; + return newPos; + }; + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * @param pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @returns {PIXI.Point} The new point, inverse-transformed through this matrix + */ + Matrix.prototype.applyInverse = function (pos, newPos) { + newPos = (newPos || new Point()); + var id = 1 / ((this.a * this.d) + (this.c * -this.b)); + var x = pos.x; + var y = pos.y; + newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id); + newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id); + return newPos; + }; + /** + * Translates the matrix on the x and y. + * @param x - How much to translate x by + * @param y - How much to translate y by + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.translate = function (x, y) { + this.tx += x; + this.ty += y; + return this; + }; + /** + * Applies a scale transformation to the matrix. + * @param x - The amount to scale horizontally + * @param y - The amount to scale vertically + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.scale = function (x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + return this; + }; + /** + * Applies a rotation transformation to the matrix. + * @param angle - The angle in radians. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.rotate = function (angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + this.a = (a1 * cos) - (this.b * sin); + this.b = (a1 * sin) + (this.b * cos); + this.c = (c1 * cos) - (this.d * sin); + this.d = (c1 * sin) + (this.d * cos); + this.tx = (tx1 * cos) - (this.ty * sin); + this.ty = (tx1 * sin) + (this.ty * cos); + return this; + }; + /** + * Appends the given Matrix to this Matrix. + * @param matrix - The matrix to append. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.append = function (matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + this.a = (matrix.a * a1) + (matrix.b * c1); + this.b = (matrix.a * b1) + (matrix.b * d1); + this.c = (matrix.c * a1) + (matrix.d * c1); + this.d = (matrix.c * b1) + (matrix.d * d1); + this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx; + this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty; + return this; + }; + /** + * Sets the matrix based on all the available properties + * @param x - Position on the x axis + * @param y - Position on the y axis + * @param pivotX - Pivot on the x axis + * @param pivotY - Pivot on the y axis + * @param scaleX - Scale on the x axis + * @param scaleY - Scale on the y axis + * @param rotation - Rotation in radians + * @param skewX - Skew on the x axis + * @param skewY - Skew on the y axis + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + this.tx = x - ((pivotX * this.a) + (pivotY * this.c)); + this.ty = y - ((pivotX * this.b) + (pivotY * this.d)); + return this; + }; + /** + * Prepends the given Matrix to this Matrix. + * @param matrix - The matrix to prepend + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.prepend = function (matrix) { + var tx1 = this.tx; + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + this.a = (a1 * matrix.a) + (this.b * matrix.c); + this.b = (a1 * matrix.b) + (this.b * matrix.d); + this.c = (c1 * matrix.a) + (this.d * matrix.c); + this.d = (c1 * matrix.b) + (this.d * matrix.d); + } + this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx; + this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty; + return this; + }; + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * @param transform - The transform to apply the properties to. + * @returns The transform with the newly applied properties + */ + Matrix.prototype.decompose = function (transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + var pivot = transform.pivot; + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + var delta = Math.abs(skewX + skewY); + if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) { + transform.rotation = skewY; + transform.skew.x = transform.skew.y = 0; + } + else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; + } + // next set scale + transform.scale.x = Math.sqrt((a * a) + (b * b)); + transform.scale.y = Math.sqrt((c * c) + (d * d)); + // next set position + transform.position.x = this.tx + ((pivot.x * a) + (pivot.y * c)); + transform.position.y = this.ty + ((pivot.x * b) + (pivot.y * d)); + return transform; + }; + /** + * Inverts this matrix + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.invert = function () { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = (a1 * d1) - (b1 * c1); + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = ((c1 * this.ty) - (d1 * tx1)) / n; + this.ty = -((a1 * this.ty) - (b1 * tx1)) / n; + return this; + }; + /** + * Resets this Matrix to an identity (default) matrix. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.identity = function () { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + return this; + }; + /** + * Creates a new Matrix object with the same values as this one. + * @returns A copy of this matrix. Good for chaining method calls. + */ + Matrix.prototype.clone = function () { + var matrix = new Matrix(); + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; + }; + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * @param matrix - The matrix to copy to. + * @returns The matrix given in parameter with its values updated. + */ + Matrix.prototype.copyTo = function (matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; + }; + /** + * Changes the values of the matrix to be the same as the ones in given matrix + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @returns {PIXI.Matrix} this + */ + Matrix.prototype.copyFrom = function (matrix) { + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + return this; + }; + Matrix.prototype.toString = function () { + return "[@pixi/math:Matrix a=" + this.a + " b=" + this.b + " c=" + this.c + " d=" + this.d + " tx=" + this.tx + " ty=" + this.ty + "]"; + }; + Object.defineProperty(Matrix, "IDENTITY", { + /** + * A default (identity) matrix + * @readonly + */ + get: function () { + return new Matrix(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Matrix, "TEMP_MATRIX", { + /** + * A temp matrix + * @readonly + */ + get: function () { + return new Matrix(); + }, + enumerable: false, + configurable: true + }); + return Matrix; + }()); + + // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group + /* + * Transform matrix for operation n is: + * | ux | vx | + * | uy | vy | + */ + var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; + var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; + var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; + var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; + /** + * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table} + * for the composition of each rotation in the dihederal group D8. + * @type {number[][]} + * @private + */ + var rotationCayley = []; + /** + * Matrices for each `GD8Symmetry` rotation. + * @type {PIXI.Matrix[]} + * @private + */ + var rotationMatrices = []; + /* + * Alias for {@code Math.sign}. + */ + var signum = Math.sign; + /* + * Initializes `rotationCayley` and `rotationMatrices`. It is called + * only once below. + */ + function init() { + for (var i = 0; i < 16; i++) { + var row = []; + rotationCayley.push(row); + for (var j = 0; j < 16; j++) { + /* Multiplies rotation matrices i and j. */ + var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j])); + var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j])); + var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j])); + var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j])); + /* Finds rotation matrix matching the product and pushes it. */ + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy + && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + for (var i = 0; i < 16; i++) { + var mat = new Matrix(); + mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); + rotationMatrices.push(mat); + } + } + init(); + /** + * @memberof PIXI + * @typedef {number} GD8Symmetry + * @see PIXI.groupD8 + */ + /** + * Implements the dihedral group D8, which is similar to + * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}; + * D8 is the same but with diagonals, and it is used for texture + * rotations. + * + * The directions the U- and V- axes after rotation + * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))` + * and `(vX(a), vY(a))`. These aren't necessarily unit vectors. + * + * **Origin:**
      + * This is the small part of gameofbombs.com portal system. It works. + * @see PIXI.groupD8.E + * @see PIXI.groupD8.SE + * @see PIXI.groupD8.S + * @see PIXI.groupD8.SW + * @see PIXI.groupD8.W + * @see PIXI.groupD8.NW + * @see PIXI.groupD8.N + * @see PIXI.groupD8.NE + * @author Ivan @ivanpopelyshev + * @namespace PIXI.groupD8 + * @memberof PIXI + */ + var groupD8 = { + /** + * | Rotation | Direction | + * |----------|-----------| + * | 0° | East | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + E: 0, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 45°↻ | Southeast | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + SE: 1, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 90°↻ | South | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + S: 2, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 135°↻ | Southwest | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + SW: 3, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 180° | West | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + W: 4, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -135°/225°↻ | Northwest | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + NW: 5, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -90°/270°↻ | North | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + N: 6, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -45°/315°↻ | Northeast | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + NE: 7, + /** + * Reflection about Y-axis. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MIRROR_VERTICAL: 8, + /** + * Reflection about the main diagonal. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MAIN_DIAGONAL: 10, + /** + * Reflection about X-axis. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MIRROR_HORIZONTAL: 12, + /** + * Reflection about reverse diagonal. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + REVERSE_DIAGONAL: 14, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The X-component of the U-axis + * after rotating the axes. + */ + uX: function (ind) { return ux[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The Y-component of the U-axis + * after rotating the axes. + */ + uY: function (ind) { return uy[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The X-component of the V-axis + * after rotating the axes. + */ + vX: function (ind) { return vx[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The Y-component of the V-axis + * after rotating the axes. + */ + vY: function (ind) { return vy[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite + * is needed. Only rotations have opposite symmetries while + * reflections don't. + * @returns {PIXI.GD8Symmetry} The opposite symmetry of `rotation` + */ + inv: function (rotation) { + if (rotation & 8) // true only if between 8 & 15 (reflections) + { + return rotation & 15; // or rotation % 16 + } + return (-rotation) & 7; // or (8 - rotation) % 8 + }, + /** + * Composes the two D8 operations. + * + * Taking `^` as reflection: + * + * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 | + * |-------|-----|-----|-----|-----|------|-------|-------|-------| + * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ | + * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ | + * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ | + * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ | + * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S | + * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W | + * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N | + * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E | + * + * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table} + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which + * is the row in the above cayley table. + * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which + * is the column in the above cayley table. + * @returns {PIXI.GD8Symmetry} Composed operation + */ + add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); }, + /** + * Reverse of `add`. + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotationSecond - Second operation + * @param {PIXI.GD8Symmetry} rotationFirst - First operation + * @returns {PIXI.GD8Symmetry} Result + */ + sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); }, + /** + * Adds 180 degrees to rotation, which is a commutative + * operation. + * @memberof PIXI.groupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} Rotated number + */ + rotate180: function (rotation) { return rotation ^ 4; }, + /** + * Checks if the rotation angle is vertical, i.e. south + * or north. It doesn't work for reflections. + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function (rotation) { return (rotation & 3) === 2; }, + /** + * Approximates the vector `V(dx,dy)` into one of the + * eight directions provided by `groupD8`. + * @memberof PIXI.groupD8 + * @param {number} dx - X-component of the vector + * @param {number} dy - Y-component of the vector + * @returns {PIXI.GD8Symmetry} Approximation of the vector into + * one of the eight symmetries. + */ + byDirection: function (dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return groupD8.S; + } + return groupD8.N; + } + else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return groupD8.E; + } + return groupD8.W; + } + else if (dy > 0) { + if (dx > 0) { + return groupD8.SE; + } + return groupD8.SW; + } + else if (dx > 0) { + return groupD8.NE; + } + return groupD8.NW; + }, + /** + * Helps sprite to compensate texture packer rotation. + * @memberof PIXI.groupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function (matrix, rotation, tx, ty) { + if (tx === void 0) { tx = 0; } + if (ty === void 0) { ty = 0; } + // Packer used "rotation", we use "inv(rotation)" + var mat = rotationMatrices[groupD8.inv(rotation)]; + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + }, + }; + + /** + * Transform that takes care about its versions. + * @memberof PIXI + */ + var Transform = /** @class */ (function () { + function Transform() { + this.worldTransform = new Matrix(); + this.localTransform = new Matrix(); + this.position = new ObservablePoint(this.onChange, this, 0, 0); + this.scale = new ObservablePoint(this.onChange, this, 1, 1); + this.pivot = new ObservablePoint(this.onChange, this, 0, 0); + this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); + this._rotation = 0; + this._cx = 1; + this._sx = 0; + this._cy = 0; + this._sy = 1; + this._localID = 0; + this._currentLocalID = 0; + this._worldID = 0; + this._parentID = 0; + } + /** Called when a value changes. */ + Transform.prototype.onChange = function () { + this._localID++; + }; + /** Called when the skew or the rotation changes. */ + Transform.prototype.updateSkew = function () { + this._cx = Math.cos(this._rotation + this.skew.y); + this._sx = Math.sin(this._rotation + this.skew.y); + this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2 + this._localID++; + }; + Transform.prototype.toString = function () { + return "[@pixi/math:Transform " + + ("position=(" + this.position.x + ", " + this.position.y + ") ") + + ("rotation=" + this.rotation + " ") + + ("scale=(" + this.scale.x + ", " + this.scale.y + ") ") + + ("skew=(" + this.skew.x + ", " + this.skew.y + ") ") + + "]"; + }; + /** Updates the local transformation matrix. */ + Transform.prototype.updateLocalTransform = function () { + var lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); + lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); + this._currentLocalID = this._localID; + // force an update.. + this._parentID = -1; + } + }; + /** + * Updates the local and the world transformation matrices. + * @param parentTransform - The parent transform + */ + Transform.prototype.updateTransform = function (parentTransform) { + var lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); + lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); + this._currentLocalID = this._localID; + // force an update.. + this._parentID = -1; + } + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + wt.a = (lt.a * pt.a) + (lt.b * pt.c); + wt.b = (lt.a * pt.b) + (lt.b * pt.d); + wt.c = (lt.c * pt.a) + (lt.d * pt.c); + wt.d = (lt.c * pt.b) + (lt.d * pt.d); + wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx; + wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty; + this._parentID = parentTransform._worldID; + // update the id of the transform.. + this._worldID++; + } + }; + /** + * Decomposes a matrix and sets the transforms properties based on it. + * @param matrix - The matrix to decompose + */ + Transform.prototype.setFromMatrix = function (matrix) { + matrix.decompose(this); + this._localID++; + }; + Object.defineProperty(Transform.prototype, "rotation", { + /** The rotation of the object in radians. */ + get: function () { + return this._rotation; + }, + set: function (value) { + if (this._rotation !== value) { + this._rotation = value; + this.updateSkew(); + } + }, + enumerable: false, + configurable: true + }); + /** A default (identity) transform. */ + Transform.IDENTITY = new Transform(); + return Transform; + }()); + + /*! + * @pixi/display - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/display is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Sets the default value for the container property 'sortableChildren'. + * If set to true, the container will sort its children by zIndex value + * when updateTransform() is called, or manually if sortChildren() is called. + * + * This actually changes the order of elements in the array, so should be treated + * as a basic solution that is not performant compared to other solutions, + * such as @link https://github.com/pixijs/pixi-display + * + * Also be aware of that this may not work nicely with the addChildAt() function, + * as the zIndex sorting may cause the child to automatically sorted to another position. + * @static + * @constant + * @name SORTABLE_CHILDREN + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings$1.SORTABLE_CHILDREN = false; + + /** + * 'Builder' pattern for bounds rectangles. + * + * This could be called an Axis-Aligned Bounding Box. + * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems. + * @memberof PIXI + */ + var Bounds = /** @class */ (function () { + function Bounds() { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + this.rect = null; + this.updateID = -1; + } + /** + * Checks if bounds are empty. + * @returns - True if empty. + */ + Bounds.prototype.isEmpty = function () { + return this.minX > this.maxX || this.minY > this.maxY; + }; + /** Clears the bounds and resets. */ + Bounds.prototype.clear = function () { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * @param rect - Temporary object will be used if AABB is not empty + * @returns - A rectangle of the bounds + */ + Bounds.prototype.getRectangle = function (rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return Rectangle.EMPTY; + } + rect = rect || new Rectangle(0, 0, 1, 1); + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + return rect; + }; + /** + * This function should be inlined when its possible. + * @param point - The point to add. + */ + Bounds.prototype.addPoint = function (point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + /** + * Adds a point, after transformed. This should be inlined when its possible. + * @param matrix + * @param point + */ + Bounds.prototype.addPointMatrix = function (matrix, point) { + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty; + var x = (a * point.x) + (c * point.y) + tx; + var y = (b * point.x) + (d * point.y) + ty; + this.minX = Math.min(this.minX, x); + this.maxX = Math.max(this.maxX, x); + this.minY = Math.min(this.minY, y); + this.maxY = Math.max(this.maxY, y); + }; + /** + * Adds a quad, not transformed + * @param vertices - The verts to add. + */ + Bounds.prototype.addQuad = function (vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + var x = vertices[0]; + var y = vertices[1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds sprite frame, transformed. + * @param transform - transform to apply + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + */ + Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) { + this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); + }; + /** + * Adds sprite frame, multiplied by matrix + * @param matrix - matrix to apply + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + */ + Bounds.prototype.addFrameMatrix = function (matrix, x0, y0, x1, y1) { + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + var x = (a * x0) + (c * y0) + tx; + var y = (b * x0) + (d * y0) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x1) + (c * y0) + tx; + y = (b * x1) + (d * y0) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x0) + (c * y1) + tx; + y = (b * x0) + (d * y1) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x1) + (c * y1) + tx; + y = (b * x1) + (d * y1) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds screen vertices from array + * @param vertexData - calculated vertices + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + */ + Bounds.prototype.addVertexData = function (vertexData, beginOffset, endOffset) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + for (var i = beginOffset; i < endOffset; i += 2) { + var x = vertexData[i]; + var y = vertexData[i + 1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Add an array of mesh vertices + * @param transform - mesh transform + * @param vertices - mesh coordinates in array + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + */ + Bounds.prototype.addVertices = function (transform, vertices, beginOffset, endOffset) { + this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); + }; + /** + * Add an array of mesh vertices. + * @param matrix - mesh matrix + * @param vertices - mesh coordinates in array + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + * @param padX - x padding + * @param padY - y padding + */ + Bounds.prototype.addVerticesMatrix = function (matrix, vertices, beginOffset, endOffset, padX, padY) { + if (padX === void 0) { padX = 0; } + if (padY === void 0) { padY = padX; } + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + minX = Math.min(minX, x - padX); + maxX = Math.max(maxX, x + padX); + minY = Math.min(minY, y - padY); + maxY = Math.max(maxY, y + padY); + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds other {@link Bounds}. + * @param bounds - The Bounds to be added + */ + Bounds.prototype.addBounds = function (bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + /** + * Adds other Bounds, masked with Bounds. + * @param bounds - The Bounds to be added. + * @param mask - TODO + */ + Bounds.prototype.addBoundsMask = function (bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + /** + * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty. + * @param bounds - other bounds + * @param matrix - multiplicator + */ + Bounds.prototype.addBoundsMatrix = function (bounds, matrix) { + this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); + }; + /** + * Adds other Bounds, masked with Rectangle. + * @param bounds - TODO + * @param area - TODO + */ + Bounds.prototype.addBoundsArea = function (bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width); + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height); + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + /** + * Pads bounds object, making it grow in all directions. + * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. + * @param paddingX - The horizontal padding amount. + * @param paddingY - The vertical padding amount. + */ + Bounds.prototype.pad = function (paddingX, paddingY) { + if (paddingX === void 0) { paddingX = 0; } + if (paddingY === void 0) { paddingY = paddingX; } + if (!this.isEmpty()) { + this.minX -= paddingX; + this.maxX += paddingX; + this.minY -= paddingY; + this.maxY += paddingY; + } + }; + /** + * Adds padded frame. (x0, y0) should be strictly less than (x1, y1) + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + * @param padX - padding X + * @param padY - padding Y + */ + Bounds.prototype.addFramePad = function (x0, y0, x1, y1, padX, padY) { + x0 -= padX; + y0 -= padY; + x1 += padX; + y1 += padY; + this.minX = this.minX < x0 ? this.minX : x0; + this.maxX = this.maxX > x1 ? this.maxX : x1; + this.minY = this.minY < y0 ? this.minY : y0; + this.maxY = this.maxY > y1 ? this.maxY : y1; + }; + return Bounds; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$j = function(d, b) { + extendStatics$j = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$j(d, b); + }; + + function __extends$j(d, b) { + extendStatics$j(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * The base class for all objects that are rendered on the screen. + * + * This is an abstract class and can not be used on its own; rather it should be extended. + * + * ## Display objects implemented in PixiJS + * + * | Display Object | Description | + * | ------------------------------- | --------------------------------------------------------------------- | + * | {@link PIXI.Container} | Adds support for `children` to DisplayObject | + * | {@link PIXI.Graphics} | Shape-drawing display object similar to the Canvas API | + * | {@link PIXI.Sprite} | Draws textures (i.e. images) | + * | {@link PIXI.Text} | Draws text using the Canvas API internally | + * | {@link PIXI.BitmapText} | More scaleable solution for text rendering, reusing glyph textures | + * | {@link PIXI.TilingSprite} | Draws textures/images in a tiled fashion | + * | {@link PIXI.AnimatedSprite} | Draws an animation of multiple images | + * | {@link PIXI.Mesh} | Provides a lower-level API for drawing meshes with custom data | + * | {@link PIXI.NineSlicePlane} | Mesh-related | + * | {@link PIXI.SimpleMesh} | v4-compatible mesh | + * | {@link PIXI.SimplePlane} | Mesh-related | + * | {@link PIXI.SimpleRope} | Mesh-related | + * + * ## Transforms + * + * The [transform]{@link DisplayObject#transform} of a display object describes the projection from its + * local coordinate space to its parent's local coordinate space. The following properties are derived + * from the transform: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
      PropertyDescription
      [pivot]{@link PIXI.DisplayObject#pivot} + * Invariant under rotation, scaling, and skewing. The projection of into the parent's space of the pivot + * is equal to position, regardless of the other three transformations. In other words, It is the center of + * rotation, scaling, and skewing. + *
      [position]{@link PIXI.DisplayObject#position} + * Translation. This is the position of the [pivot]{@link PIXI.DisplayObject#pivot} in the parent's local + * space. The default value of the pivot is the origin (0,0). If the top-left corner of your display object + * is (0,0) in its local space, then the position will be its top-left corner in the parent's local space. + *
      [scale]{@link PIXI.DisplayObject#scale} + * Scaling. This will stretch (or compress) the display object's projection. The scale factors are along the + * local coordinate axes. In other words, the display object is scaled before rotated or skewed. The center + * of scaling is the [pivot]{@link PIXI.DisplayObject#pivot}. + *
      [rotation]{@link PIXI.DisplayObject#rotation} + * Rotation. This will rotate the display object's projection by this angle (in radians). + *
      [skew]{@link PIXI.DisplayObject#skew} + *

      Skewing. This can be used to deform a rectangular display object into a parallelogram.

      + *

      + * In PixiJS, skew has a slightly different behaviour than the conventional meaning. It can be + * thought of the net rotation applied to the coordinate axes (separately). For example, if "skew.x" is + * ⍺ and "skew.y" is β, then the line x = 0 will be rotated by ⍺ (y = -x*cot⍺) and the line y = 0 will be + * rotated by β (y = x*tanβ). A line y = x*tanϴ (i.e. a line at angle ϴ to the x-axis in local-space) will + * be rotated by an angle between ⍺ and β. + *

      + *

      + * It can be observed that if skew is applied equally to both axes, then it will be equivalent to applying + * a rotation. Indeed, if "skew.x" = -ϴ and "skew.y" = ϴ, it will produce an equivalent of "rotation" = ϴ. + *

      + *

      + * Another quite interesting observation is that "skew.x", "skew.y", rotation are communtative operations. Indeed, + * because rotation is essentially a careful combination of the two. + *

      + *
      angleRotation. This is an alias for [rotation]{@link PIXI.DisplayObject#rotation}, but in degrees.
      xTranslation. This is an alias for position.x!
      yTranslation. This is an alias for position.y!
      width + * Implemented in [Container]{@link PIXI.Container}. Scaling. The width property calculates scale.x by dividing + * the "requested" width by the local bounding box width. It is indirectly an abstraction over scale.x, and there + * is no concept of user-defined width. + *
      height + * Implemented in [Container]{@link PIXI.Container}. Scaling. The height property calculates scale.y by dividing + * the "requested" height by the local bounding box height. It is indirectly an abstraction over scale.y, and there + * is no concept of user-defined height. + *
      + * + * ## Bounds + * + * The bounds of a display object is defined by the minimum axis-aligned rectangle in world space that can fit + * around it. The abstract `calculateBounds` method is responsible for providing it (and it should use the + * `worldTransform` to calculate in world space). + * + * There are a few additional types of bounding boxes: + * + * | Bounds | Description | + * | --------------------- | ---------------------------------------------------------------------------------------- | + * | World Bounds | This is synonymous is the regular bounds described above. See `getBounds()`. | + * | Local Bounds | This the axis-aligned bounding box in the parent's local space. See `getLocalBounds()`. | + * | Render Bounds | The bounds, but including extra rendering effects like filter padding. | + * | Projected Bounds | The bounds of the projected display object onto the screen. Usually equals world bounds. | + * | Relative Bounds | The bounds of a display object when projected onto a ancestor's (or parent's) space. | + * | Natural Bounds | The bounds of an object in its own local space (not parent's space, like in local bounds)| + * | Content Bounds | The natural bounds when excluding all children of a `Container`. | + * + * ### calculateBounds + * + * [Container]{@link Container} already implements `calculateBounds` in a manner that includes children. + * + * But for a non-Container display object, the `calculateBounds` method must be overridden in order for `getBounds` and + * `getLocalBounds` to work. This method must write the bounds into `this._bounds`. + * + * Generally, the following technique works for most simple cases: take the list of points + * forming the "hull" of the object (i.e. outline of the object's shape), and then add them + * using {@link PIXI.Bounds#addPointMatrix}. + * + * ```js + * calculateBounds(): void + * { + * const points = [...]; + * + * for (let i = 0, j = points.length; i < j; i++) + * { + * this._bounds.addPointMatrix(this.worldTransform, points[i]); + * } + * } + * ``` + * + * You can optimize this for a large number of points by using {@link PIXI.Bounds#addVerticesMatrix} to pass them + * in one array together. + * + * ## Alpha + * + * This alpha sets a display object's **relative opacity** w.r.t its parent. For example, if the alpha of a display + * object is 0.5 and its parent's alpha is 0.5, then it will be rendered with 25% opacity (assuming alpha is not + * applied on any ancestor further up the chain). + * + * The alpha with which the display object will be rendered is called the [worldAlpha]{@link PIXI.DisplayObject#worldAlpha}. + * + * ## Renderable vs Visible + * + * The `renderable` and `visible` properties can be used to prevent a display object from being rendered to the + * screen. However, there is a subtle difference between the two. When using `renderable`, the transforms of the display + * object (and its children subtree) will continue to be calculated. When using `visible`, the transforms will not + * be calculated. + * + * It is recommended that applications use the `renderable` property for culling. See + * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} or + * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull} for more details. + * + * Otherwise, to prevent an object from rendering in the general-purpose sense - `visible` is the property to use. This + * one is also better in terms of performance. + * @memberof PIXI + */ + var DisplayObject = /** @class */ (function (_super) { + __extends$j(DisplayObject, _super); + function DisplayObject() { + var _this = _super.call(this) || this; + _this.tempDisplayObjectParent = null; + // TODO: need to create Transform from factory + _this.transform = new Transform(); + _this.alpha = 1; + _this.visible = true; + _this.renderable = true; + _this.cullable = false; + _this.cullArea = null; + _this.parent = null; + _this.worldAlpha = 1; + _this._lastSortedIndex = 0; + _this._zIndex = 0; + _this.filterArea = null; + _this.filters = null; + _this._enabledFilters = null; + _this._bounds = new Bounds(); + _this._localBounds = null; + _this._boundsID = 0; + _this._boundsRect = null; + _this._localBoundsRect = null; + _this._mask = null; + _this._maskRefCount = 0; + _this._destroyed = false; + _this.isSprite = false; + _this.isMask = false; + return _this; + } + /** + * Mixes all enumerable properties and methods from a source object to DisplayObject. + * @param source - The source of properties and methods to mix in. + */ + DisplayObject.mixin = function (source) { + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(DisplayObject.prototype, Object.getOwnPropertyDescriptors(source)); + // get all the enumerable property keys + var keys = Object.keys(source); + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } + }; + Object.defineProperty(DisplayObject.prototype, "destroyed", { + /** + * Fired when this DisplayObject is added to a Container. + * @instance + * @event added + * @param {PIXI.Container} container - The container added to. + */ + /** + * Fired when this DisplayObject is removed from a Container. + * @instance + * @event removed + * @param {PIXI.Container} container - The container removed from. + */ + /** + * Fired when this DisplayObject is destroyed. This event is emitted once + * destroy is finished. + * @instance + * @event destroyed + */ + /** Readonly flag for destroyed display objects. */ + get: function () { + return this._destroyed; + }, + enumerable: false, + configurable: true + }); + /** Recursively updates transform of all objects from the root to this one internal function for toLocal() */ + DisplayObject.prototype._recursivePostUpdateTransform = function () { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } + else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + /** Updates the object transform for rendering. TODO - Optimization pass! */ + DisplayObject.prototype.updateTransform = function () { + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + }; + /** + * Calculates and returns the (world) bounds of the display object as a [Rectangle]{@link PIXI.Rectangle}. + * + * This method is expensive on containers with a large subtree (like the stage). This is because the bounds + * of a container depend on its children's bounds, which recursively causes all bounds in the subtree to + * be recalculated. The upside, however, is that calling `getBounds` once on a container will indeed update + * the bounds of all children (the whole subtree, in fact). This side effect should be exploited by using + * `displayObject._bounds.getRectangle()` when traversing through all the bounds in a scene graph. Otherwise, + * calling `getBounds` on each object in a subtree will cause the total cost to increase quadratically as + * its height increases. + * + * The transforms of all objects in a container's **subtree** and of all **ancestors** are updated. + * The world bounds of all display objects in a container's **subtree** will also be recalculated. + * + * The `_bounds` object stores the last calculation of the bounds. You can use to entirely skip bounds + * calculation if needed. + * + * ```js + * const lastCalculatedBounds = displayObject._bounds.getRectangle(optionalRect); + * ``` + * + * Do know that usage of `getLocalBounds` can corrupt the `_bounds` of children (the whole subtree, actually). This + * is a known issue that has not been solved. See [getLocalBounds]{@link PIXI.DisplayObject#getLocalBounds} for more + * details. + * + * `getBounds` should be called with `skipUpdate` equal to `true` in a render() call. This is because the transforms + * are guaranteed to be update-to-date. In fact, recalculating inside a render() call may cause corruption in certain + * cases. + * @param skipUpdate - Setting to `true` will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @returns - The minimum axis-aligned rectangle in world space that fits around this object. + */ + DisplayObject.prototype.getBounds = function (skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } + else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + if (this._bounds.updateID !== this._boundsID) { + this.calculateBounds(); + this._bounds.updateID = this._boundsID; + } + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new Rectangle(); + } + rect = this._boundsRect; + } + return this._bounds.getRectangle(rect); + }; + /** + * Retrieves the local bounds of the displayObject as a rectangle object. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @returns - The rectangular bounding area. + */ + DisplayObject.prototype.getLocalBounds = function (rect) { + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + var transformRef = this.transform; + var parentRef = this.parent; + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + var worldBounds = this._bounds; + var worldBoundsID = this._boundsID; + this._bounds = this._localBounds; + var bounds = this.getBounds(false, rect); + this.parent = parentRef; + this.transform = transformRef; + this._bounds = worldBounds; + this._bounds.updateID += this._boundsID - worldBoundsID; // reflect side-effects + return bounds; + }; + /** + * Calculates the global position of the display object. + * @param position - The world origin to calculate from. + * @param point - A Point object in which to store the value, optional + * (otherwise will create a new Point). + * @param skipUpdate - Should we skip the update transform. + * @returns - A point object representing the position of this object. + */ + DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) { + if (skipUpdate === void 0) { skipUpdate = false; } + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else { + this.displayObjectUpdateTransform(); + } + } + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + /** + * Calculates the local position of the display object relative to another point. + * @param position - The world origin to calculate from. + * @param from - The DisplayObject to calculate the global position from. + * @param point - A Point object in which to store the value, optional + * (otherwise will create a new Point). + * @param skipUpdate - Should we skip the update transform + * @returns - A point object representing the position of this object + */ + DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else { + this.displayObjectUpdateTransform(); + } + } + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + /** + * Set the parent Container of this DisplayObject. + * @param container - The Container to add this DisplayObject to. + * @returns - The Container that this DisplayObject was added to. + */ + DisplayObject.prototype.setParent = function (container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + container.addChild(this); + return container; + }; + /** + * Convenience function to set the position, scale, skew and pivot at once. + * @param x - The X position + * @param y - The Y position + * @param scaleX - The X scale value + * @param scaleY - The Y scale value + * @param rotation - The rotation + * @param skewX - The X skew value + * @param skewY - The Y skew value + * @param pivotX - The X pivot value + * @param pivotY - The Y pivot value + * @returns - The DisplayObject instance + */ + DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (scaleX === void 0) { scaleX = 1; } + if (scaleY === void 0) { scaleY = 1; } + if (rotation === void 0) { rotation = 0; } + if (skewX === void 0) { skewX = 0; } + if (skewY === void 0) { skewY = 0; } + if (pivotX === void 0) { pivotX = 0; } + if (pivotY === void 0) { pivotY = 0; } + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + return this; + }; + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy()`. + * @param _options + */ + DisplayObject.prototype.destroy = function (_options) { + if (this.parent) { + this.parent.removeChild(this); + } + this._destroyed = true; + this.transform = null; + this.parent = null; + this._bounds = null; + this.mask = null; + this.cullArea = null; + this.filters = null; + this.filterArea = null; + this.hitArea = null; + this.interactive = false; + this.interactiveChildren = false; + this.emit('destroyed'); + this.removeAllListeners(); + }; + Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", { + /** + * @protected + * @member {PIXI.Container} + */ + get: function () { + if (this.tempDisplayObjectParent === null) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.tempDisplayObjectParent = new TemporaryDisplayObject(); + } + return this.tempDisplayObjectParent; + }, + enumerable: false, + configurable: true + }); + /** + * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root + * + * ``` + * const cacheParent = elem.enableTempParent(); + * elem.updateTransform(); + * elem.disableTempParent(cacheParent); + * ``` + * @returns - current parent + */ + DisplayObject.prototype.enableTempParent = function () { + var myParent = this.parent; + this.parent = this._tempDisplayObjectParent; + return myParent; + }; + /** + * Pair method for `enableTempParent` + * @param cacheParent - Actual parent of element + */ + DisplayObject.prototype.disableTempParent = function (cacheParent) { + this.parent = cacheParent; + }; + Object.defineProperty(DisplayObject.prototype, "x", { + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + */ + get: function () { + return this.position.x; + }, + set: function (value) { + this.transform.position.x = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "y", { + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + */ + get: function () { + return this.position.y; + }, + set: function (value) { + this.transform.position.y = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "worldTransform", { + /** + * Current transform of the object based on world (parent) factors. + * @readonly + */ + get: function () { + return this.transform.worldTransform; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "localTransform", { + /** + * Current transform of the object based on local factors: position, scale, other stuff. + * @readonly + */ + get: function () { + return this.transform.localTransform; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "position", { + /** + * The coordinate of the object relative to the local coordinates of the parent. + * @since 4.0.0 + */ + get: function () { + return this.transform.position; + }, + set: function (value) { + this.transform.position.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "scale", { + /** + * The scale factors of this object along the local coordinate axes. + * + * The default scale is (1, 1). + * @since 4.0.0 + */ + get: function () { + return this.transform.scale; + }, + set: function (value) { + this.transform.scale.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "pivot", { + /** + * The center of rotation, scaling, and skewing for this display object in its local space. The `position` + * is the projection of `pivot` in the parent's local space. + * + * By default, the pivot is the origin (0, 0). + * @since 4.0.0 + */ + get: function () { + return this.transform.pivot; + }, + set: function (value) { + this.transform.pivot.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "skew", { + /** + * The skew factor for the object in radians. + * @since 4.0.0 + */ + get: function () { + return this.transform.skew; + }, + set: function (value) { + this.transform.skew.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "rotation", { + /** + * The rotation of the object in radians. + * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + */ + get: function () { + return this.transform.rotation; + }, + set: function (value) { + this.transform.rotation = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "angle", { + /** + * The angle of the object in degrees. + * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + */ + get: function () { + return this.transform.rotation * RAD_TO_DEG; + }, + set: function (value) { + this.transform.rotation = value * DEG_TO_RAD; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "zIndex", { + /** + * The zIndex of the displayObject. + * + * If a container has the sortableChildren property set to true, children will be automatically + * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, + * and thus rendered on top of other display objects within the same container. + * @see PIXI.Container#sortableChildren + */ + get: function () { + return this._zIndex; + }, + set: function (value) { + this._zIndex = value; + if (this.parent) { + this.parent.sortDirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "worldVisible", { + /** + * Indicates if the object is globally visible. + * @readonly + */ + get: function () { + var item = this; + do { + if (!item.visible) { + return false; + } + item = item.parent; + } while (item); + return true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "mask", { + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PixiJS a regular mask must be a + * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it + * utilities shape clipping. Furthermore, a mask of an object must be in the subtree of its parent. + * Otherwise, `getLocalBounds` may calculate incorrect bounds, which makes the container's width and height wrong. + * To remove a mask, set this property to `null`. + * + * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask. + * @example + * const graphics = new PIXI.Graphics(); + * graphics.beginFill(0xFF3300); + * graphics.drawRect(50, 250, 100, 100); + * graphics.endFill(); + * + * const sprite = new PIXI.Sprite(texture); + * sprite.mask = graphics; + * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + */ + get: function () { + return this._mask; + }, + set: function (value) { + if (this._mask === value) { + return; + } + if (this._mask) { + var maskObject = (this._mask.isMaskData + ? this._mask.maskObject : this._mask); + if (maskObject) { + maskObject._maskRefCount--; + if (maskObject._maskRefCount === 0) { + maskObject.renderable = true; + maskObject.isMask = false; + } + } + } + this._mask = value; + if (this._mask) { + var maskObject = (this._mask.isMaskData + ? this._mask.maskObject : this._mask); + if (maskObject) { + if (maskObject._maskRefCount === 0) { + maskObject.renderable = false; + maskObject.isMask = true; + } + maskObject._maskRefCount++; + } + } + }, + enumerable: false, + configurable: true + }); + return DisplayObject; + }(eventemitter3)); + /** + * @private + */ + var TemporaryDisplayObject = /** @class */ (function (_super) { + __extends$j(TemporaryDisplayObject, _super); + function TemporaryDisplayObject() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.sortDirty = null; + return _this; + } + return TemporaryDisplayObject; + }(DisplayObject)); + /** + * DisplayObject default updateTransform, does not update children of container. + * Will crash if there's no parent element. + * @memberof PIXI.DisplayObject# + * @method displayObjectUpdateTransform + */ + DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$4; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$4 || (ENV$4 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$4; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$4 || (RENDERER_TYPE$4 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$4; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$4 || (BUFFER_BITS$4 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$4; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$4 || (BLEND_MODES$4 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$4; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$4 || (DRAW_MODES$4 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$4; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$4 || (FORMATS$4 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$4; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$4 || (TARGETS$4 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$4; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$4 || (TYPES$4 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$4; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$4 || (SAMPLER_TYPES$4 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$4; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$4 || (SCALE_MODES$4 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$4; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$4 || (WRAP_MODES$4 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$4; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$4 || (MIPMAP_MODES$4 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$4; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$4 || (ALPHA_MODES$4 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$4; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$4 || (CLEAR_MODES$4 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$4; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$4 || (GC_MODES$4 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$4; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$4 || (PRECISION$4 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$4; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$4 || (MASK_TYPES$4 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$4; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$4 || (COLOR_MASK_BITS$4 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$4; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$4 || (MSAA_QUALITY$4 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$4; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$4 || (BUFFER_TYPE$4 = {})); + + function sortChildren(a, b) { + if (a.zIndex === b.zIndex) { + return a._lastSortedIndex - b._lastSortedIndex; + } + return a.zIndex - b.zIndex; + } + /** + * Container is a general-purpose display object that holds children. It also adds built-in support for advanced + * rendering features like masking and filtering. + * + * It is the base class of all display objects that act as a container for other objects, including Graphics + * and Sprite. + * + * ```js + * import { BlurFilter } from '@pixi/filter-blur'; + * import { Container } from '@pixi/display'; + * import { Graphics } from '@pixi/graphics'; + * import { Sprite } from '@pixi/sprite'; + * + * let container = new Container(); + * let sprite = Sprite.from("https://s3-us-west-2.amazonaws.com/s.cdpn.io/693612/IaUrttj.png"); + * + * sprite.width = 512; + * sprite.height = 512; + * + * // Adds a sprite as a child to this container. As a result, the sprite will be rendered whenever the container + * // is rendered. + * container.addChild(sprite); + * + * // Blurs whatever is rendered by the container + * container.filters = [new BlurFilter()]; + * + * // Only the contents within a circle at the center should be rendered onto the screen. + * container.mask = new Graphics() + * .beginFill(0xffffff) + * .drawCircle(sprite.width / 2, sprite.height / 2, Math.min(sprite.width, sprite.height) / 2) + * .endFill(); + * ``` + * @memberof PIXI + */ + var Container = /** @class */ (function (_super) { + __extends$j(Container, _super); + function Container() { + var _this = _super.call(this) || this; + _this.children = []; + _this.sortableChildren = settings$1.SORTABLE_CHILDREN; + _this.sortDirty = false; + return _this; + /** + * Fired when a DisplayObject is added to this Container. + * @event PIXI.Container#childAdded + * @param {PIXI.DisplayObject} child - The child added to the Container. + * @param {PIXI.Container} container - The container that added the child. + * @param {number} index - The children's index of the added child. + */ + /** + * Fired when a DisplayObject is removed from this Container. + * @event PIXI.DisplayObject#childRemoved + * @param {PIXI.DisplayObject} child - The child removed from the Container. + * @param {PIXI.Container} container - The container that removed the child. + * @param {number} index - The former children's index of the removed child + */ + } + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified. + * @param _length + */ + Container.prototype.onChildrenChange = function (_length) { + /* empty */ + }; + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to add to the container + * @returns {PIXI.DisplayObject} - The first child that was added. + */ + Container.prototype.addChild = function () { + var arguments$1 = arguments; + + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments$1[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the array and add all children + for (var i = 0; i < children.length; i++) { + // eslint-disable-next-line prefer-rest-params + this.addChild(children[i]); + } + } + else { + var child = children[0]; + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.push(child); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + this.emit('childAdded', child, this, this.children.length - 1); + child.emit('added', this); + } + return children[0]; + }; + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @returns {PIXI.DisplayObject} The child that was added. + */ + Container.prototype.addChildAt = function (child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + "addChildAt: The index " + index + " supplied is out of bounds " + this.children.length); + } + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.splice(index, 0, child); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + this.emit('childAdded', child, this, index); + return child; + }; + /** + * Swaps the position of 2 Display Objects within this container. + * @param child - First display object to swap + * @param child2 - Second display object to swap + */ + Container.prototype.swapChildren = function (child, child2) { + if (child === child2) { + return; + } + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + /** + * Returns the index position of a child DisplayObject instance + * @param child - The DisplayObject instance to identify + * @returns - The index position of the child display object to identify + */ + Container.prototype.getChildIndex = function (child) { + var index = this.children.indexOf(child); + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + return index; + }; + /** + * Changes the position of an existing child in the display object container + * @param child - The child DisplayObject instance for which you want to change the index number + * @param index - The resulting index number for the child display object + */ + Container.prototype.setChildIndex = function (child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error("The index " + index + " supplied is out of bounds " + this.children.length); + } + var currentIndex = this.getChildIndex(child); + removeItems(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + this.onChildrenChange(index); + }; + /** + * Returns the child at the specified index + * @param index - The index to get the child at + * @returns - The child at the given index, if any. + */ + Container.prototype.getChildAt = function (index) { + if (index < 0 || index >= this.children.length) { + throw new Error("getChildAt: Index (" + index + ") does not exist."); + } + return this.children[index]; + }; + /** + * Removes one or more children from the container. + * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove + * @returns {PIXI.DisplayObject} The first child that was removed. + */ + Container.prototype.removeChild = function () { + var arguments$1 = arguments; + + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments$1[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the arguments property and remove all children + for (var i = 0; i < children.length; i++) { + this.removeChild(children[i]); + } + } + else { + var child = children[0]; + var index = this.children.indexOf(child); + if (index === -1) + { return null; } + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + removeItems(this.children, index, 1); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + } + return children[0]; + }; + /** + * Removes a child from the specified index position. + * @param index - The index to get the child from + * @returns The child that was removed. + */ + Container.prototype.removeChildAt = function (index) { + var child = this.getChildAt(index); + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + removeItems(this.children, index, 1); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + return child; + }; + /** + * Removes all children from this container that are within the begin and end indexes. + * @param beginIndex - The beginning position. + * @param endIndex - The ending position. Default value is size of the container. + * @returns - List of removed children + */ + Container.prototype.removeChildren = function (beginIndex, endIndex) { + if (beginIndex === void 0) { beginIndex = 0; } + if (endIndex === void 0) { endIndex = this.children.length; } + var begin = beginIndex; + var end = endIndex; + var range = end - begin; + var removed; + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + this._boundsID++; + this.onChildrenChange(beginIndex); + for (var i = 0; i < removed.length; ++i) { + removed[i].emit('removed', this); + this.emit('childRemoved', removed[i], this, i); + } + return removed; + } + else if (range === 0 && this.children.length === 0) { + return []; + } + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + /** Sorts children by zIndex. Previous order is maintained for 2 children with the same zIndex. */ + Container.prototype.sortChildren = function () { + var sortRequired = false; + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + child._lastSortedIndex = i; + if (!sortRequired && child.zIndex !== 0) { + sortRequired = true; + } + } + if (sortRequired && this.children.length > 1) { + this.children.sort(sortChildren); + } + this.sortDirty = false; + }; + /** Updates the transform on all children of this container for rendering. */ + Container.prototype.updateTransform = function () { + if (this.sortableChildren && this.sortDirty) { + this.sortChildren(); + } + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + }; + /** + * Recalculates the bounds of the container. + * + * This implementation will automatically fit the children's bounds into the calculation. Each child's bounds + * is limited to its mask's bounds or filterArea, if any is applied. + */ + Container.prototype.calculateBounds = function () { + this._bounds.clear(); + this._calculateBounds(); + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + if (!child.visible || !child.renderable) { + continue; + } + child.calculateBounds(); + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + var maskObject = (child._mask.isMaskData + ? child._mask.maskObject : child._mask); + if (maskObject) { + maskObject.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, maskObject._bounds); + } + else { + this._bounds.addBounds(child._bounds); + } + } + else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } + else { + this._bounds.addBounds(child._bounds); + } + } + this._bounds.updateID = this._boundsID; + }; + /** + * Retrieves the local bounds of the displayObject as a rectangle object. + * + * Calling `getLocalBounds` may invalidate the `_bounds` of the whole subtree below. If using it inside a render() + * call, it is advised to call `getBounds()` immediately after to recalculate the world bounds of the subtree. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @param skipChildrenUpdate - Setting to `true` will stop re-calculation of children transforms, + * it was default behaviour of pixi 4.0-5.2 and caused many problems to users. + * @returns - The rectangular bounding area. + */ + Container.prototype.getLocalBounds = function (rect, skipChildrenUpdate) { + if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; } + var result = _super.prototype.getLocalBounds.call(this, rect); + if (!skipChildrenUpdate) { + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + } + return result; + }; + /** + * Recalculates the content bounds of this object. This should be overriden to + * calculate the bounds of this specific object (not including children). + * @protected + */ + Container.prototype._calculateBounds = function () { + // FILL IN// + }; + /** + * Renders this object and its children with culling. + * @protected + * @param {PIXI.Renderer} renderer - The renderer + */ + Container.prototype._renderWithCulling = function (renderer) { + var sourceFrame = renderer.renderTexture.sourceFrame; + // If the source frame is empty, stop rendering. + if (!(sourceFrame.width > 0 && sourceFrame.height > 0)) { + return; + } + // Render the content of the container only if its bounds intersect with the source frame. + // All filters are on the stack at this point, and the filter source frame is bound: + // therefore, even if the bounds to non intersect the filter frame, the filter + // is still applied and any filter padding that is in the frame is rendered correctly. + var bounds; + var transform; + // If cullArea is set, we use this rectangle instead of the bounds of the object. The cullArea + // rectangle must completely contain the container and its children including filter padding. + if (this.cullArea) { + bounds = this.cullArea; + transform = this.worldTransform; + } + // If the container doesn't override _render, we can skip the bounds calculation and intersection test. + else if (this._render !== Container.prototype._render) { + bounds = this.getBounds(true); + } + // Render the container if the source frame intersects the bounds. + if (bounds && sourceFrame.intersects(bounds, transform)) { + this._render(renderer); + } + // If the bounds are defined by cullArea and do not intersect with the source frame, stop rendering. + else if (this.cullArea) { + return; + } + // Unless cullArea is set, we cannot skip the children if the bounds of the container do not intersect + // the source frame, because the children might have filters with nonzero padding, which may intersect + // with the source frame while the bounds do not: filter padding is not included in the bounds. + // If cullArea is not set, render the children with culling temporarily enabled so that they are not rendered + // if they are out of frame; otherwise, render the children normally. + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + var childCullable = child.cullable; + child.cullable = childCullable || !this.cullArea; + child.render(renderer); + child.cullable = childCullable; + } + }; + /** + * Renders the object using the WebGL renderer. + * + * The [_render]{@link PIXI.Container#_render} method is be overriden for rendering the contents of the + * container itself. This `render` method will invoke it, and also invoke the `render` methods of all + * children afterward. + * + * If `renderable` or `visible` is false or if `worldAlpha` is not positive or if `cullable` is true and + * the bounds of this object are out of frame, this implementation will entirely skip rendering. + * See {@link PIXI.DisplayObject} for choosing between `renderable` or `visible`. Generally, + * setting alpha to zero is not recommended for purely skipping rendering. + * + * When your scene becomes large (especially when it is larger than can be viewed in a single screen), it is + * advised to employ **culling** to automatically skip rendering objects outside of the current screen. + * See [cullable]{@link PIXI.DisplayObject#cullable} and [cullArea]{@link PIXI.DisplayObject#cullArea}. + * Other culling methods might be better suited for a large number static objects; see + * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} and + * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull}. + * + * The [renderAdvanced]{@link PIXI.Container#renderAdvanced} method is internally used when when masking or + * filtering is applied on a container. This does, however, break batching and can affect performance when + * masking and filtering is applied extensively throughout the scene graph. + * @param renderer - The renderer + */ + Container.prototype.render = function (renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + // do a quick check to see if this element has a mask or a filter. + if (this._mask || (this.filters && this.filters.length)) { + this.renderAdvanced(renderer); + } + else if (this.cullable) { + this._renderWithCulling(renderer); + } + else { + this._render(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } + } + }; + /** + * Render the object using the WebGL renderer and advanced features. + * @param renderer - The renderer + */ + Container.prototype.renderAdvanced = function (renderer) { + var filters = this.filters; + var mask = this._mask; + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + this._enabledFilters.length = 0; + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + } + var flush = (filters && this._enabledFilters && this._enabledFilters.length) + || (mask && (!mask.isMaskData + || (mask.enabled && (mask.autoDetect || mask.type !== MASK_TYPES$4.NONE)))); + if (flush) { + renderer.batch.flush(); + } + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filter.push(this, this._enabledFilters); + } + if (mask) { + renderer.mask.push(this, this._mask); + } + if (this.cullable) { + this._renderWithCulling(renderer); + } + else { + this._render(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } + } + if (flush) { + renderer.batch.flush(); + } + if (mask) { + renderer.mask.pop(this); + } + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filter.pop(); + } + }; + /** + * To be overridden by the subclasses. + * @param _renderer - The renderer + */ + Container.prototype._render = function (_renderer) { + // this is where content itself gets rendered... + }; + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Container.prototype.destroy = function (options) { + _super.prototype.destroy.call(this); + this.sortDirty = false; + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + var oldChildren = this.removeChildren(0, this.children.length); + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + Object.defineProperty(Container.prototype, "width", { + /** The width of the Container, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this.scale.x * this.getLocalBounds().width; + }, + set: function (value) { + var width = this.getLocalBounds().width; + if (width !== 0) { + this.scale.x = value / width; + } + else { + this.scale.x = 1; + } + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Container.prototype, "height", { + /** The height of the Container, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this.scale.y * this.getLocalBounds().height; + }, + set: function (value) { + var height = this.getLocalBounds().height; + if (height !== 0) { + this.scale.y = value / height; + } + else { + this.scale.y = 1; + } + this._height = value; + }, + enumerable: false, + configurable: true + }); + return Container; + }(DisplayObject)); + /** + * Container default updateTransform, does update children of container. + * Will crash if there's no parent element. + * @memberof PIXI.Container# + * @method containerUpdateTransform + */ + Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + + /*! + * @pixi/extensions - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/extensions is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + + var __assign$1 = function() { + __assign$1 = Object.assign || function __assign(t) { + var arguments$1 = arguments; + + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments$1[i]; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + + /** + * Collection of valid extension types. + * @memberof PIXI + * @property {string} Application - Application plugins + * @property {string} RendererPlugin - Plugins for Renderer + * @property {string} CanvasRendererPlugin - Plugins for CanvasRenderer + * @property {string} Loader - Plugins to use with Loader + * @property {string} LoadParser - Parsers for Assets loader. + * @property {string} ResolveParser - Parsers for Assets resolvers. + * @property {string} CacheParser - Parsers for Assets cache. + */ + exports.ExtensionType = void 0; + (function (ExtensionType) { + ExtensionType["Application"] = "application"; + ExtensionType["RendererPlugin"] = "renderer-webgl-plugin"; + ExtensionType["CanvasRendererPlugin"] = "renderer-canvas-plugin"; + ExtensionType["Loader"] = "loader"; + ExtensionType["LoadParser"] = "load-parser"; + ExtensionType["ResolveParser"] = "resolve-parser"; + ExtensionType["CacheParser"] = "cache-parser"; + ExtensionType["DetectionParser"] = "detection-parser"; + })(exports.ExtensionType || (exports.ExtensionType = {})); + /** + * Convert input into extension format data. + * @ignore + */ + var normalizeExtension = function (ext) { + // Class/Object submission, use extension object + if (typeof ext === 'function' || (typeof ext === 'object' && ext.extension)) { + if (!ext.extension) { + throw new Error('Extension class must have an extension object'); + } + var metadata = (typeof ext.extension !== 'object') + ? { type: ext.extension } + : ext.extension; + ext = __assign$1(__assign$1({}, metadata), { ref: ext }); + } + if (typeof ext === 'object') { + ext = __assign$1({}, ext); + } + else { + throw new Error('Invalid extension type'); + } + if (typeof ext.type === 'string') { + ext.type = [ext.type]; + } + return ext; + }; + /** + * Global registration of all PixiJS extensions. One-stop-shop for extensibility. + * @memberof PIXI + * @namespace extensions + */ + var extensions = { + /** @ignore */ + _addHandlers: null, + /** @ignore */ + _removeHandlers: null, + /** @ignore */ + _queue: {}, + /** + * Remove extensions from PixiJS. + * @param extensions - Extensions to be removed. + * @returns {PIXI.extensions} For chaining. + */ + remove: function () { + var arguments$1 = arguments; + + var _this = this; + var extensions = []; + for (var _i = 0; _i < arguments.length; _i++) { + extensions[_i] = arguments$1[_i]; + } + extensions.map(normalizeExtension).forEach(function (ext) { + ext.type.forEach(function (type) { var _a, _b; return (_b = (_a = _this._removeHandlers)[type]) === null || _b === void 0 ? void 0 : _b.call(_a, ext); }); + }); + return this; + }, + /** + * Register new extensions with PixiJS. + * @param extensions - The spread of extensions to add to PixiJS. + * @returns {PIXI.extensions} For chaining. + */ + add: function () { + var arguments$1 = arguments; + + var _this = this; + var extensions = []; + for (var _i = 0; _i < arguments.length; _i++) { + extensions[_i] = arguments$1[_i]; + } + // Handle any extensions either passed as class w/ data or as data + extensions.map(normalizeExtension).forEach(function (ext) { + ext.type.forEach(function (type) { + var handlers = _this._addHandlers; + var queue = _this._queue; + if (!handlers[type]) { + queue[type] = queue[type] || []; + queue[type].push(ext); + } + else { + handlers[type](ext); + } + }); + }); + return this; + }, + /** + * Internal method to handle extensions by name. + * @param type - The extension type. + * @param onAdd - Function for handling when extensions are added/registered passes {@link PIXI.ExtensionFormat}. + * @param onRemove - Function for handling when extensions are removed/unregistered passes {@link PIXI.ExtensionFormat}. + * @returns {PIXI.extensions} For chaining. + */ + handle: function (type, onAdd, onRemove) { + var addHandlers = this._addHandlers = this._addHandlers || {}; + var removeHandlers = this._removeHandlers = this._removeHandlers || {}; + if (addHandlers[type] || removeHandlers[type]) { + throw new Error("Extension type " + type + " already has a handler"); + } + addHandlers[type] = onAdd; + removeHandlers[type] = onRemove; + // Process the queue + var queue = this._queue; + // Process any plugins that have been registered before the handler + if (queue[type]) { + queue[type].forEach(function (ext) { return onAdd(ext); }); + delete queue[type]; + } + return this; + }, + /** + * Handle a type, but using a map by `name` property. + * @param type - Type of extension to handle. + * @param map - The object map of named extensions. + * @returns {PIXI.extensions} For chaining. + */ + handleByMap: function (type, map) { + return this.handle(type, function (extension) { + map[extension.name] = extension.ref; + }, function (extension) { + delete map[extension.name]; + }); + }, + /** + * Handle a type, but using a list of extensions. + * @param type - Type of extension to handle. + * @param list - The list of extensions. + * @returns {PIXI.extensions} For chaining. + */ + handleByList: function (type, list) { + return this.handle(type, function (extension) { + var _a, _b; + list.push(extension.ref); + // TODO: remove me later, only added for @pixi/loaders + if (type === exports.ExtensionType.Loader) { + (_b = (_a = extension.ref).add) === null || _b === void 0 ? void 0 : _b.call(_a); + } + }, function (extension) { + var index = list.indexOf(extension.ref); + if (index !== -1) { + list.splice(index, 1); + } + }); + }, + }; + + /*! + * @pixi/runner - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/runner is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * A Runner is a highly performant and simple alternative to signals. Best used in situations + * where events are dispatched to many objects at high frequency (say every frame!) + * + * + * like a signal.. + * ``` + * import { Runner } from '@pixi/runner'; + * + * const myObject = { + * loaded: new Runner('loaded') + * } + * + * const listener = { + * loaded: function(){ + * // thin + * } + * } + * + * myObject.loaded.add(listener); + * + * myObject.loaded.emit(); + * ``` + * + * Or for handling calling the same function on many items + * ``` + * import { Runner } from '@pixi/runner'; + * + * const myGame = { + * update: new Runner('update') + * } + * + * const gameObject = { + * update: function(time){ + * // update my gamey state + * } + * } + * + * myGame.update.add(gameObject); + * + * myGame.update.emit(time); + * ``` + * @memberof PIXI + */ + var Runner = /** @class */ (function () { + /** + * @param name - The function name that will be executed on the listeners added to this Runner. + */ + function Runner(name) { + this.items = []; + this._name = name; + this._aliasCount = 0; + } + /* eslint-disable jsdoc/require-param, jsdoc/check-param-names */ + /** + * Dispatch/Broadcast Runner to all listeners added to the queue. + * @param {...any} params - (optional) parameters to pass to each listener + */ + /* eslint-enable jsdoc/require-param, jsdoc/check-param-names */ + Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) { + if (arguments.length > 8) { + throw new Error('max arguments reached'); + } + var _a = this, name = _a.name, items = _a.items; + this._aliasCount++; + for (var i = 0, len = items.length; i < len; i++) { + items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); + } + if (items === this.items) { + this._aliasCount--; + } + return this; + }; + Runner.prototype.ensureNonAliasedItems = function () { + if (this._aliasCount > 0 && this.items.length > 1) { + this._aliasCount = 0; + this.items = this.items.slice(0); + } + }; + /** + * Add a listener to the Runner + * + * Runners do not need to have scope or functions passed to them. + * All that is required is to pass the listening object and ensure that it has contains a function that has the same name + * as the name provided to the Runner when it was created. + * + * Eg A listener passed to this Runner will require a 'complete' function. + * + * ``` + * import { Runner } from '@pixi/runner'; + * + * const complete = new Runner('complete'); + * ``` + * + * The scope used will be the object itself. + * @param {any} item - The object that will be listening. + */ + Runner.prototype.add = function (item) { + if (item[this._name]) { + this.ensureNonAliasedItems(); + this.remove(item); + this.items.push(item); + } + return this; + }; + /** + * Remove a single listener from the dispatch queue. + * @param {any} item - The listener that you would like to remove. + */ + Runner.prototype.remove = function (item) { + var index = this.items.indexOf(item); + if (index !== -1) { + this.ensureNonAliasedItems(); + this.items.splice(index, 1); + } + return this; + }; + /** + * Check to see if the listener is already in the Runner + * @param {any} item - The listener that you would like to check. + */ + Runner.prototype.contains = function (item) { + return this.items.indexOf(item) !== -1; + }; + /** Remove all listeners from the Runner */ + Runner.prototype.removeAll = function () { + this.ensureNonAliasedItems(); + this.items.length = 0; + return this; + }; + /** Remove all references, don't use after this. */ + Runner.prototype.destroy = function () { + this.removeAll(); + this.items = null; + this._name = null; + }; + Object.defineProperty(Runner.prototype, "empty", { + /** + * `true` if there are no this Runner contains no listeners + * @readonly + */ + get: function () { + return this.items.length === 0; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Runner.prototype, "name", { + /** + * The name of the runner. + * @readonly + */ + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + return Runner; + }()); + Object.defineProperties(Runner.prototype, { + /** + * Alias for `emit` + * @memberof PIXI.Runner# + * @method dispatch + * @see PIXI.Runner#emit + */ + dispatch: { value: Runner.prototype.emit }, + /** + * Alias for `emit` + * @memberof PIXI.Runner# + * @method run + * @see PIXI.Runner#emit + */ + run: { value: Runner.prototype.emit }, + }); + + /*! + * @pixi/ticker - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/ticker is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Target frames per millisecond. + * @static + * @name TARGET_FPMS + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + settings$1.TARGET_FPMS = 0.06; + + /** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @enum {number} + * @property {number} [INTERACTION=50] Highest priority, used for {@link PIXI.InteractionManager} + * @property {number} [HIGH=25] High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite} + * @property {number} [NORMAL=0] Default priority for ticker events, see {@link PIXI.Ticker#add}. + * @property {number} [LOW=-25] Low priority used for {@link PIXI.Application} rendering. + * @property {number} [UTILITY=-50] Lowest priority used for {@link PIXI.BasePrepare} utility. + */ + exports.UPDATE_PRIORITY = void 0; + (function (UPDATE_PRIORITY) { + UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION"; + UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH"; + UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL"; + UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW"; + UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY"; + })(exports.UPDATE_PRIORITY || (exports.UPDATE_PRIORITY = {})); + + /** + * Internal class for handling the priority sorting of ticker handlers. + * @private + * @class + * @memberof PIXI + */ + var TickerListener = /** @class */ (function () { + /** + * Constructor + * @private + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @param priority - The priority for emitting + * @param once - If the handler should fire once + */ + function TickerListener(fn, context, priority, once) { + if (context === void 0) { context = null; } + if (priority === void 0) { priority = 0; } + if (once === void 0) { once = false; } + /** The next item in chain. */ + this.next = null; + /** The previous item in chain. */ + this.previous = null; + /** `true` if this listener has been destroyed already. */ + this._destroyed = false; + this.fn = fn; + this.context = context; + this.priority = priority; + this.once = once; + } + /** + * Simple compare function to figure out if a function and context match. + * @private + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @returns `true` if the listener match the arguments + */ + TickerListener.prototype.match = function (fn, context) { + if (context === void 0) { context = null; } + return this.fn === fn && this.context === context; + }; + /** + * Emit by calling the current function. + * @private + * @param deltaTime - time since the last emit. + * @returns Next ticker + */ + TickerListener.prototype.emit = function (deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } + else { + this.fn(deltaTime); + } + } + var redirect = this.next; + if (this.once) { + this.destroy(true); + } + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + return redirect; + }; + /** + * Connect to the list. + * @private + * @param previous - Input node, previous listener + */ + TickerListener.prototype.connect = function (previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + /** + * Destroy and don't use after this. + * @private + * @param hard - `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @returns The listener to redirect while emitting or removing. + */ + TickerListener.prototype.destroy = function (hard) { + if (hard === void 0) { hard = false; } + this._destroyed = true; + this.fn = null; + this.context = null; + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + if (this.next) { + this.next.previous = this.previous; + } + // Redirect to the next item + var redirect = this.next; + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + return redirect; + }; + return TickerListener; + }()); + + /** + * A Ticker class that runs an update loop that other objects listen to. + * + * This class is composed around listeners meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners. + * @class + * @memberof PIXI + */ + var Ticker = /** @class */ (function () { + function Ticker() { + var _this = this; + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.Ticker#start} automatically + * when a listener is added. + */ + this.autoStart = false; + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.Ticker#minFPS} + * and is scaled with {@link PIXI.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + */ + this.deltaTime = 1; + /** + * The last time {@link PIXI.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + */ + this.lastTime = -1; + /** + * Factor of current {@link PIXI.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + */ + this.speed = 1; + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.Ticker#start} has been called. + * `false` if {@link PIXI.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.Ticker#autoStart} being `true` + * and a listener is added. + */ + this.started = false; + /** Internal current frame request ID */ + this._requestId = null; + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + */ + this._maxElapsedMS = 100; + /** + * Internal value managed by minFPS property setter and getter. + * This is the minimum allowed milliseconds between updates. + */ + this._minElapsedMS = 0; + /** If enabled, deleting is disabled.*/ + this._protected = false; + /** The last time keyframe was executed. Maintains a relatively fixed interval with the previous value. */ + this._lastFrame = -1; + this._head = new TickerListener(null, null, Infinity); + this.deltaMS = 1 / settings$1.TARGET_FPMS; + this.elapsedMS = 1 / settings$1.TARGET_FPMS; + this._tick = function (time) { + _this._requestId = null; + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * @private + */ + Ticker.prototype._requestIfNeeded = function () { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._lastFrame = this.lastTime; + this._requestId = requestAnimationFrame(this._tick); + } + }; + /** + * Conditionally cancels a pending animation frame. + * @private + */ + Ticker.prototype._cancelIfNeeded = function () { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * @private + */ + Ticker.prototype._startIfPossible = function () { + if (this.started) { + this._requestIfNeeded(); + } + else if (this.autoStart) { + this.start(); + } + }; + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * @param fn - The listener function to be added for updates + * @param context - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns This instance of a ticker + */ + Ticker.prototype.add = function (fn, context, priority) { + if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } + return this._addListener(new TickerListener(fn, context, priority)); + }; + /** + * Add a handler for the tick event which is only execute once. + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns This instance of a ticker + */ + Ticker.prototype.addOnce = function (fn, context, priority) { + if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } + return this._addListener(new TickerListener(fn, context, priority, true)); + }; + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * @private + * @param listener - Current listener being added. + * @returns This instance of a ticker + */ + Ticker.prototype._addListener = function (listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + // Add the first item + if (!current) { + listener.connect(previous); + } + else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + this._startIfPossible(); + return this; + }; + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * @param fn - The listener function to be removed + * @param context - The listener context to be removed + * @returns This instance of a ticker + */ + Ticker.prototype.remove = function (fn, context) { + var listener = this._head.next; + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } + else { + listener = listener.next; + } + } + if (!this._head.next) { + this._cancelIfNeeded(); + } + return this; + }; + Object.defineProperty(Ticker.prototype, "count", { + /** + * The number of listeners on this ticker, calculated by walking through linked list + * @readonly + * @member {number} + */ + get: function () { + if (!this._head) { + return 0; + } + var count = 0; + var current = this._head; + while ((current = current.next)) { + count++; + } + return count; + }, + enumerable: false, + configurable: true + }); + /** Starts the ticker. If the ticker has listeners a new animation frame is requested at this point. */ + Ticker.prototype.start = function () { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + /** Stops the ticker. If the ticker has requested an animation frame it is canceled at this point. */ + Ticker.prototype.stop = function () { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + /** Destroy the ticker and don't use after this. Calling this method removes all references to internal events. */ + Ticker.prototype.destroy = function () { + if (!this._protected) { + this.stop(); + var listener = this._head.next; + while (listener) { + listener = listener.destroy(true); + } + this._head.destroy(); + this._head = null; + } + }; + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.Ticker#elapsedMS}, + * the current {@link PIXI.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + Ticker.prototype.update = function (currentTime) { + if (currentTime === void 0) { currentTime = performance.now(); } + var elapsedMS; + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + elapsedMS *= this.speed; + // If not enough time has passed, exit the function. + // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS + // adjustment to ensure a relatively stable interval. + if (this._minElapsedMS) { + var delta = currentTime - this._lastFrame | 0; + if (delta < this._minElapsedMS) { + return; + } + this._lastFrame = currentTime - (delta % this._minElapsedMS); + } + this.deltaMS = elapsedMS; + this.deltaTime = this.deltaMS * settings$1.TARGET_FPMS; + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + // Invoke listeners added to internal emitter + var listener = head.next; + while (listener) { + listener = listener.emit(this.deltaTime); + } + if (!head.next) { + this._cancelIfNeeded(); + } + } + else { + this.deltaTime = this.deltaMS = this.elapsedMS = 0; + } + this.lastTime = currentTime; + }; + Object.defineProperty(Ticker.prototype, "FPS", { + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.Ticker#speed}, which is specific + * to scaling {@link PIXI.Ticker#deltaTime}. + * @member {number} + * @readonly + */ + get: function () { + return 1000 / this.elapsedMS; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker.prototype, "minFPS", { + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.Ticker#update}. + * This value is used to cap {@link PIXI.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * @member {number} + * @default 10 + */ + get: function () { + return 1000 / this._maxElapsedMS; + }, + set: function (fps) { + // Minimum must be below the maxFPS + var minFPS = Math.min(this.maxFPS, fps); + // Must be at least 0, but below 1 / settings.TARGET_FPMS + var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings$1.TARGET_FPMS); + this._maxElapsedMS = 1 / minFPMS; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker.prototype, "maxFPS", { + /** + * Manages the minimum amount of milliseconds required to + * elapse between invoking {@link PIXI.Ticker#update}. + * This will effect the measured value of {@link PIXI.Ticker#FPS}. + * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can. + * Otherwise it will be at least `minFPS` + * @member {number} + * @default 0 + */ + get: function () { + if (this._minElapsedMS) { + return Math.round(1000 / this._minElapsedMS); + } + return 0; + }, + set: function (fps) { + if (fps === 0) { + this._minElapsedMS = 0; + } + else { + // Max must be at least the minFPS + var maxFPS = Math.max(this.minFPS, fps); + this._minElapsedMS = 1 / (maxFPS / 1000); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker, "shared", { + /** + * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by + * {@link PIXI.VideoResource} to update animation frames / video textures. + * + * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true. + * + * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. + * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker. + * @example + * let ticker = PIXI.Ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.Ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(); + * let stage = new PIXI.Container(); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * @member {PIXI.Ticker} + * @static + */ + get: function () { + if (!Ticker._shared) { + var shared = Ticker._shared = new Ticker(); + shared.autoStart = true; + shared._protected = true; + } + return Ticker._shared; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker, "system", { + /** + * The system ticker instance used by {@link PIXI.InteractionManager} and by + * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused, + * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused. + * + * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. + * @member {PIXI.Ticker} + * @static + */ + get: function () { + if (!Ticker._system) { + var system = Ticker._system = new Ticker(); + system.autoStart = true; + system._protected = true; + } + return Ticker._system; + }, + enumerable: false, + configurable: true + }); + return Ticker; + }()); + + /** + * Middleware for for Application Ticker. + * @example + * import {TickerPlugin} from '@pixi/ticker'; + * import {Application} from '@pixi/app'; + * import {extensions} from '@pixi/extensions'; + * extensions.add(TickerPlugin); + * @class + * @memberof PIXI + */ + var TickerPlugin = /** @class */ (function () { + function TickerPlugin() { + } + /** + * Initialize the plugin with scope of application instance + * @static + * @private + * @param {object} [options] - See application options + */ + TickerPlugin.init = function (options) { + var _this = this; + // Set default + options = Object.assign({ + autoStart: true, + sharedTicker: false, + }, options); + // Create ticker setter + Object.defineProperty(this, 'ticker', { + set: function (ticker) { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, exports.UPDATE_PRIORITY.LOW); + } + }, + get: function () { + return this._ticker; + }, + }); + /** + * Convenience method for stopping the render. + * @method + * @memberof PIXI.Application + * @instance + */ + this.stop = function () { + _this._ticker.stop(); + }; + /** + * Convenience method for starting the render. + * @method + * @memberof PIXI.Application + * @instance + */ + this.start = function () { + _this._ticker.start(); + }; + /** + * Internal reference to the ticker. + * @type {PIXI.Ticker} + * @name _ticker + * @memberof PIXI.Application# + * @private + */ + this._ticker = null; + /** + * Ticker for doing render updates. + * @type {PIXI.Ticker} + * @name ticker + * @memberof PIXI.Application# + * @default PIXI.Ticker.shared + */ + this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); + // Start the rendering + if (options.autoStart) { + this.start(); + } + }; + /** + * Clean up the ticker, scoped to application. + * @static + * @private + */ + TickerPlugin.destroy = function () { + if (this._ticker) { + var oldTicker = this._ticker; + this.ticker = null; + oldTicker.destroy(); + } + }; + /** @ignore */ + TickerPlugin.extension = exports.ExtensionType.Application; + return TickerPlugin; + }()); + + /*! + * @pixi/core - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/core is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * The maximum support for using WebGL. If a device does not + * support WebGL version, for instance WebGL 2, it will still + * attempt to fallback support to WebGL 1. If you want to + * explicitly remove feature support to target a more stable + * baseline, prefer a lower environment. + * + * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium} + * we disable webgl2 by default for all non-apple mobile devices. + * @static + * @name PREFER_ENV + * @memberof PIXI.settings + * @type {number} + * @default PIXI.ENV.WEBGL2 + */ + settings$1.PREFER_ENV = isMobile$2.any ? exports.ENV.WEBGL : exports.ENV.WEBGL2; + /** + * If set to `true`, *only* Textures and BaseTexture objects stored + * in the caches ({@link PIXI.utils.TextureCache TextureCache} and + * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can be + * used when calling {@link PIXI.Texture.from Texture.from} or + * {@link PIXI.BaseTexture.from BaseTexture.from}. + * Otherwise, these `from` calls throw an exception. Using this property + * can be useful if you want to enforce preloading all assets with + * {@link PIXI.Loader Loader}. + * @static + * @name STRICT_TEXTURE_CACHE + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings$1.STRICT_TEXTURE_CACHE = false; + + /** + * Collection of installed resource types, class must extend {@link PIXI.Resource}. + * @example + * class CustomResource extends PIXI.Resource { + * // MUST have source, options constructor signature + * // for auto-detected resources to be created. + * constructor(source, options) { + * super(); + * } + * upload(renderer, baseTexture, glTexture) { + * // upload with GL + * return true; + * } + * // used to auto-detect resource + * static test(source, extension) { + * return extension === 'xyz'|| source instanceof SomeClass; + * } + * } + * // Install the new resource type + * PIXI.INSTALLED.push(CustomResource); + * @memberof PIXI + * @type {Array} + * @static + * @readonly + */ + var INSTALLED = []; + /** + * Create a resource element from a single source element. This + * auto-detects which type of resource to create. All resources that + * are auto-detectable must have a static `test` method and a constructor + * with the arguments `(source, options?)`. Currently, the supported + * resources for auto-detection include: + * - {@link PIXI.ImageResource} + * - {@link PIXI.CanvasResource} + * - {@link PIXI.VideoResource} + * - {@link PIXI.SVGResource} + * - {@link PIXI.BufferResource} + * @static + * @memberof PIXI + * @function autoDetectResource + * @param {string|*} source - Resource source, this can be the URL to the resource, + * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri + * or any other resource that can be auto-detected. If not resource is + * detected, it's assumed to be an ImageResource. + * @param {object} [options] - Pass-through options to use for Resource + * @param {number} [options.width] - Width of BufferResource or SVG rasterization + * @param {number} [options.height] - Height of BufferResource or SVG rasterization + * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading + * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height + * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object + * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin + * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately + * @param {number} [options.updateFPS=0] - Video option to update how many times a second the + * texture should be updated from the video. Leave at 0 to update at every render + * @returns {PIXI.Resource} The created resource. + */ + function autoDetectResource(source, options) { + if (!source) { + return null; + } + var extension = ''; + if (typeof source === 'string') { + // search for file extension: period, 3-4 chars, then ?, # or EOL + var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source); + if (result) { + extension = result[1].toLowerCase(); + } + } + for (var i = INSTALLED.length - 1; i >= 0; --i) { + var ResourcePlugin = INSTALLED[i]; + if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) { + return new ResourcePlugin(source, options); + } + } + throw new Error('Unrecognized source type to auto-detect Resource'); + } + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$i = function(d, b) { + extendStatics$i = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$i(d, b); + }; + + function __extends$i(d, b) { + extendStatics$i(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var __assign = function() { + __assign = Object.assign || function __assign(t) { + var arguments$1 = arguments; + + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments$1[i]; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } + } + return t; + }; + return __assign.apply(this, arguments); + }; + + function __rest(s, e) { + var t = {}; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + { t[p] = s[p]; } } + if (s != null && typeof Object.getOwnPropertySymbols === "function") + { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + { t[p[i]] = s[p[i]]; } + } } + return t; + } + + /** + * Base resource class for textures that manages validation and uploading, depending on its type. + * + * Uploading of a base texture to the GPU is required. + * @memberof PIXI + */ + var Resource = /** @class */ (function () { + /** + * @param width - Width of the resource + * @param height - Height of the resource + */ + function Resource(width, height) { + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + this._width = width; + this._height = height; + this.destroyed = false; + this.internal = false; + this.onResize = new Runner('setRealSize'); + this.onUpdate = new Runner('update'); + this.onError = new Runner('onError'); + } + /** + * Bind to a parent BaseTexture + * @param baseTexture - Parent texture + */ + Resource.prototype.bind = function (baseTexture) { + this.onResize.add(baseTexture); + this.onUpdate.add(baseTexture); + this.onError.add(baseTexture); + // Call a resize immediate if we already + // have the width and height of the resource + if (this._width || this._height) { + this.onResize.emit(this._width, this._height); + } + }; + /** + * Unbind to a parent BaseTexture + * @param baseTexture - Parent texture + */ + Resource.prototype.unbind = function (baseTexture) { + this.onResize.remove(baseTexture); + this.onUpdate.remove(baseTexture); + this.onError.remove(baseTexture); + }; + /** + * Trigger a resize event + * @param width - X dimension + * @param height - Y dimension + */ + Resource.prototype.resize = function (width, height) { + if (width !== this._width || height !== this._height) { + this._width = width; + this._height = height; + this.onResize.emit(width, height); + } + }; + Object.defineProperty(Resource.prototype, "valid", { + /** + * Has been validated + * @readonly + */ + get: function () { + return !!this._width && !!this._height; + }, + enumerable: false, + configurable: true + }); + /** Has been updated trigger event. */ + Resource.prototype.update = function () { + if (!this.destroyed) { + this.onUpdate.emit(); + } + }; + /** + * This can be overridden to start preloading a resource + * or do any other prepare step. + * @protected + * @returns Handle the validate event + */ + Resource.prototype.load = function () { + return Promise.resolve(this); + }; + Object.defineProperty(Resource.prototype, "width", { + /** + * The width of the resource. + * @readonly + */ + get: function () { + return this._width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Resource.prototype, "height", { + /** + * The height of the resource. + * @readonly + */ + get: function () { + return this._height; + }, + enumerable: false, + configurable: true + }); + /** + * Set the style, optional to override + * @param _renderer - yeah, renderer! + * @param _baseTexture - the texture + * @param _glTexture - texture instance for this webgl context + * @returns - `true` is success + */ + Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) { + return false; + }; + /** Clean up anything, this happens when destroying is ready. */ + Resource.prototype.dispose = function () { + // override + }; + /** + * Call when destroying resource, unbind any BaseTexture object + * before calling this method, as reference counts are maintained + * internally. + */ + Resource.prototype.destroy = function () { + if (!this.destroyed) { + this.destroyed = true; + this.dispose(); + this.onError.removeAll(); + this.onError = null; + this.onResize.removeAll(); + this.onResize = null; + this.onUpdate.removeAll(); + this.onUpdate = null; + } + }; + /** + * Abstract, used to auto-detect resource type. + * @param {*} _source - The source object + * @param {string} _extension - The extension of source, if set + */ + Resource.test = function (_source, _extension) { + return false; + }; + return Resource; + }()); + + /** + * @interface SharedArrayBuffer + */ + /** + * Buffer resource with data of typed array. + * @memberof PIXI + */ + var BufferResource = /** @class */ (function (_super) { + __extends$i(BufferResource, _super); + /** + * @param source - Source buffer + * @param options - Options + * @param {number} options.width - Width of the texture + * @param {number} options.height - Height of the texture + */ + function BufferResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + if (!width || !height) { + throw new Error('BufferResource width or height invalid'); + } + _this = _super.call(this, width, height) || this; + _this.data = source; + return _this; + } + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture - glTexture + * @returns - true is success + */ + BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) { + var gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + if (glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + }; + /** Destroy and don't use after this. */ + BufferResource.prototype.dispose = function () { + this.data = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if + */ + BufferResource.test = function (source) { + return source instanceof Float32Array + || source instanceof Uint8Array + || source instanceof Uint32Array; + }; + return BufferResource; + }(Resource)); + + var defaultBufferOptions = { + scaleMode: exports.SCALE_MODES.NEAREST, + format: exports.FORMATS.RGBA, + alphaMode: exports.ALPHA_MODES.NPM, + }; + /** + * A Texture stores the information that represents an image. + * All textures have a base texture, which contains information about the source. + * Therefore you can have many textures all using a single BaseTexture + * @memberof PIXI + * @typeParam R - The BaseTexture's Resource type. + * @typeParam RO - The options for constructing resource. + */ + var BaseTexture = /** @class */ (function (_super) { + __extends$i(BaseTexture, _super); + /** + * @param {PIXI.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] - + * The current resource to use, for things that aren't Resource objects, will be converted + * into a Resource. + * @param options - Collection of options + * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture + * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture + * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest + * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type + * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type + * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha + * @param {number} [options.width=0] - Width of the texture + * @param {number} [options.height=0] - Height of the texture + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - Resolution of the base texture + * @param {object} [options.resourceOptions] - Optional resource options, + * see {@link PIXI.autoDetectResource autoDetectResource} + */ + function BaseTexture(resource, options) { + if (resource === void 0) { resource = null; } + if (options === void 0) { options = null; } + var _this = _super.call(this) || this; + options = options || {}; + var alphaMode = options.alphaMode, mipmap = options.mipmap, anisotropicLevel = options.anisotropicLevel, scaleMode = options.scaleMode, width = options.width, height = options.height, wrapMode = options.wrapMode, format = options.format, type = options.type, target = options.target, resolution = options.resolution, resourceOptions = options.resourceOptions; + // Convert the resource to a Resource object + if (resource && !(resource instanceof Resource)) { + resource = autoDetectResource(resource, resourceOptions); + resource.internal = true; + } + _this.resolution = resolution || settings$1.RESOLUTION; + _this.width = Math.round((width || 0) * _this.resolution) / _this.resolution; + _this.height = Math.round((height || 0) * _this.resolution) / _this.resolution; + _this._mipmap = mipmap !== undefined ? mipmap : settings$1.MIPMAP_TEXTURES; + _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings$1.ANISOTROPIC_LEVEL; + _this._wrapMode = wrapMode || settings$1.WRAP_MODE; + _this._scaleMode = scaleMode !== undefined ? scaleMode : settings$1.SCALE_MODE; + _this.format = format || exports.FORMATS.RGBA; + _this.type = type || exports.TYPES.UNSIGNED_BYTE; + _this.target = target || exports.TARGETS.TEXTURE_2D; + _this.alphaMode = alphaMode !== undefined ? alphaMode : exports.ALPHA_MODES.UNPACK; + _this.uid = uid(); + _this.touched = 0; + _this.isPowerOfTwo = false; + _this._refreshPOT(); + _this._glTextures = {}; + _this.dirtyId = 0; + _this.dirtyStyleId = 0; + _this.cacheId = null; + _this.valid = width > 0 && height > 0; + _this.textureCacheIds = []; + _this.destroyed = false; + _this.resource = null; + _this._batchEnabled = 0; + _this._batchLocation = 0; + _this.parentTextureArray = null; + /** + * Fired when a not-immediately-available source finishes loading. + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + /** + * Fired when a not-immediately-available source fails to load. + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + * @param {ErrorEvent} event - Load error event. + */ + /** + * Fired when BaseTexture is updated. + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + /** + * Fired when BaseTexture is updated. + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + /** + * Fired when BaseTexture is destroyed. + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + // Set the resource + _this.setResource(resource); + return _this; + } + Object.defineProperty(BaseTexture.prototype, "realWidth", { + /** + * Pixel width of the source of this texture + * @readonly + */ + get: function () { + return Math.round(this.width * this.resolution); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "realHeight", { + /** + * Pixel height of the source of this texture + * @readonly + */ + get: function () { + return Math.round(this.height * this.resolution); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "mipmap", { + /** + * Mipmap mode of the texture, affects downscaled images + * @default PIXI.settings.MIPMAP_TEXTURES + */ + get: function () { + return this._mipmap; + }, + set: function (value) { + if (this._mipmap !== value) { + this._mipmap = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "scaleMode", { + /** + * The scale mode to apply when scaling this texture + * @default PIXI.settings.SCALE_MODE + */ + get: function () { + return this._scaleMode; + }, + set: function (value) { + if (this._scaleMode !== value) { + this._scaleMode = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "wrapMode", { + /** + * How the texture wraps + * @default PIXI.settings.WRAP_MODE + */ + get: function () { + return this._wrapMode; + }, + set: function (value) { + if (this._wrapMode !== value) { + this._wrapMode = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + /** + * Changes style options of BaseTexture + * @param scaleMode - Pixi scalemode + * @param mipmap - enable mipmaps + * @returns - this + */ + BaseTexture.prototype.setStyle = function (scaleMode, mipmap) { + var dirty; + if (scaleMode !== undefined && scaleMode !== this.scaleMode) { + this.scaleMode = scaleMode; + dirty = true; + } + if (mipmap !== undefined && mipmap !== this.mipmap) { + this.mipmap = mipmap; + dirty = true; + } + if (dirty) { + this.dirtyStyleId++; + } + return this; + }; + /** + * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero. + * @param desiredWidth - Desired visual width + * @param desiredHeight - Desired visual height + * @param resolution - Optionally set resolution + * @returns - this + */ + BaseTexture.prototype.setSize = function (desiredWidth, desiredHeight, resolution) { + resolution = resolution || this.resolution; + return this.setRealSize(desiredWidth * resolution, desiredHeight * resolution, resolution); + }; + /** + * Sets real size of baseTexture, preserves current resolution. + * @param realWidth - Full rendered width + * @param realHeight - Full rendered height + * @param resolution - Optionally set resolution + * @returns - this + */ + BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) { + this.resolution = resolution || this.resolution; + this.width = Math.round(realWidth) / this.resolution; + this.height = Math.round(realHeight) / this.resolution; + this._refreshPOT(); + this.update(); + return this; + }; + /** + * Refresh check for isPowerOfTwo texture based on size + * @private + */ + BaseTexture.prototype._refreshPOT = function () { + this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight); + }; + /** + * Changes resolution + * @param resolution - res + * @returns - this + */ + BaseTexture.prototype.setResolution = function (resolution) { + var oldResolution = this.resolution; + if (oldResolution === resolution) { + return this; + } + this.resolution = resolution; + if (this.valid) { + this.width = Math.round(this.width * oldResolution) / resolution; + this.height = Math.round(this.height * oldResolution) / resolution; + this.emit('update', this); + } + this._refreshPOT(); + return this; + }; + /** + * Sets the resource if it wasn't set. Throws error if resource already present + * @param resource - that is managing this BaseTexture + * @returns - this + */ + BaseTexture.prototype.setResource = function (resource) { + if (this.resource === resource) { + return this; + } + if (this.resource) { + throw new Error('Resource can be set only once'); + } + resource.bind(this); + this.resource = resource; + return this; + }; + /** Invalidates the object. Texture becomes valid if width and height are greater than zero. */ + BaseTexture.prototype.update = function () { + if (!this.valid) { + if (this.width > 0 && this.height > 0) { + this.valid = true; + this.emit('loaded', this); + this.emit('update', this); + } + } + else { + this.dirtyId++; + this.dirtyStyleId++; + this.emit('update', this); + } + }; + /** + * Handle errors with resources. + * @private + * @param event - Error event emitted. + */ + BaseTexture.prototype.onError = function (event) { + this.emit('error', this, event); + }; + /** + * Destroys this base texture. + * The method stops if resource doesn't want this texture to be destroyed. + * Removes texture from all caches. + */ + BaseTexture.prototype.destroy = function () { + // remove and destroy the resource + if (this.resource) { + this.resource.unbind(this); + // only destroy resourced created internally + if (this.resource.internal) { + this.resource.destroy(); + } + this.resource = null; + } + if (this.cacheId) { + delete BaseTextureCache[this.cacheId]; + delete TextureCache[this.cacheId]; + this.cacheId = null; + } + // finally let the WebGL renderer know.. + this.dispose(); + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + this.destroyed = true; + }; + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * @fires PIXI.BaseTexture#dispose + */ + BaseTexture.prototype.dispose = function () { + this.emit('dispose', this); + }; + /** Utility function for BaseTexture|Texture cast. */ + BaseTexture.prototype.castToBaseTexture = function () { + return this; + }; + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * @static + * @param {string|string[]|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The + * source to create base texture from. + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id + * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. + * @returns {PIXI.BaseTexture} The new base texture. + */ + BaseTexture.from = function (source, options, strict) { + if (strict === void 0) { strict = settings$1.STRICT_TEXTURE_CACHE; } + var isFrame = typeof source === 'string'; + var cacheId = null; + if (isFrame) { + cacheId = source; + } + else { + if (!source._pixiId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source._pixiId = prefix + "_" + uid(); + } + cacheId = source._pixiId; + } + var baseTexture = BaseTextureCache[cacheId]; + // Strict-mode rejects invalid cacheIds + if (isFrame && strict && !baseTexture) { + throw new Error("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache."); + } + if (!baseTexture) { + baseTexture = new BaseTexture(source, options); + baseTexture.cacheId = cacheId; + BaseTexture.addToCache(baseTexture, cacheId); + } + return baseTexture; + }; + /** + * Create a new BaseTexture with a BufferResource from a Float32Array. + * RGBA values are floats from 0 to 1. + * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data + * is provided, a new Float32Array is created. + * @param width - Width of the resource + * @param height - Height of the resource + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * Default properties are different from the constructor's defaults. + * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.NPM] - Image alpha, not premultiplied by default + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.SCALE_MODES.NEAREST] - Scale mode, pixelating by default + * @returns - The resulting new BaseTexture + */ + BaseTexture.fromBuffer = function (buffer, width, height, options) { + buffer = buffer || new Float32Array(width * height * 4); + var resource = new BufferResource(buffer, { width: width, height: height }); + var type = buffer instanceof Float32Array ? exports.TYPES.FLOAT : exports.TYPES.UNSIGNED_BYTE; + return new BaseTexture(resource, Object.assign(defaultBufferOptions, options || { width: width, height: height, type: type })); + }; + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + BaseTexture.addToCache = function (baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + if (BaseTextureCache[id]) { + // eslint-disable-next-line no-console + console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry"); + } + BaseTextureCache[id] = baseTexture; + } + }; + /** + * Remove a BaseTexture from the global BaseTextureCache. + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @returns {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + BaseTexture.removeFromCache = function (baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = BaseTextureCache[baseTexture]; + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + delete BaseTextureCache[baseTexture]; + return baseTextureFromCache; + } + } + else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + baseTexture.textureCacheIds.length = 0; + return baseTexture; + } + return null; + }; + /** Global number of the texture batch, used by multi-texture renderers. */ + BaseTexture._globalBatch = 0; + return BaseTexture; + }(eventemitter3)); + + /** + * Resource that can manage several resource (items) inside. + * All resources need to have the same pixel size. + * Parent class for CubeResource and ArrayResource + * @memberof PIXI + */ + var AbstractMultiResource = /** @class */ (function (_super) { + __extends$i(AbstractMultiResource, _super); + /** + * @param length + * @param options - Options to for Resource constructor + * @param {number} [options.width] - Width of the resource + * @param {number} [options.height] - Height of the resource + */ + function AbstractMultiResource(length, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + _this = _super.call(this, width, height) || this; + _this.items = []; + _this.itemDirtyIds = []; + for (var i = 0; i < length; i++) { + var partTexture = new BaseTexture(); + _this.items.push(partTexture); + // -2 - first run of texture array upload + // -1 - texture item was allocated + // >=0 - texture item uploaded , in sync with items[i].dirtyId + _this.itemDirtyIds.push(-2); + } + _this.length = length; + _this._load = null; + _this.baseTexture = null; + return _this; + } + /** + * Used from ArrayResource and CubeResource constructors. + * @param resources - Can be resources, image elements, canvas, etc. , + * length should be same as constructor length + * @param options - Detect options for resources + */ + AbstractMultiResource.prototype.initFromArray = function (resources, options) { + for (var i = 0; i < this.length; i++) { + if (!resources[i]) { + continue; + } + if (resources[i].castToBaseTexture) { + this.addBaseTextureAt(resources[i].castToBaseTexture(), i); + } + else if (resources[i] instanceof Resource) { + this.addResourceAt(resources[i], i); + } + else { + this.addResourceAt(autoDetectResource(resources[i], options), i); + } + } + }; + /** Destroy this BaseImageResource. */ + AbstractMultiResource.prototype.dispose = function () { + for (var i = 0, len = this.length; i < len; i++) { + this.items[i].destroy(); + } + this.items = null; + this.itemDirtyIds = null; + this._load = null; + }; + /** + * Set a resource by ID + * @param resource + * @param index - Zero-based index of resource to set + * @returns - Instance for chaining + */ + AbstractMultiResource.prototype.addResourceAt = function (resource, index) { + if (!this.items[index]) { + throw new Error("Index " + index + " is out of bounds"); + } + // Inherit the first resource dimensions + if (resource.valid && !this.valid) { + this.resize(resource.width, resource.height); + } + this.items[index].setResource(resource); + return this; + }; + /** + * Set the parent base texture. + * @param baseTexture + */ + AbstractMultiResource.prototype.bind = function (baseTexture) { + if (this.baseTexture !== null) { + throw new Error('Only one base texture per TextureArray is allowed'); + } + _super.prototype.bind.call(this, baseTexture); + for (var i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = baseTexture; + this.items[i].on('update', baseTexture.update, baseTexture); + } + }; + /** + * Unset the parent base texture. + * @param baseTexture + */ + AbstractMultiResource.prototype.unbind = function (baseTexture) { + _super.prototype.unbind.call(this, baseTexture); + for (var i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = null; + this.items[i].off('update', baseTexture.update, baseTexture); + } + }; + /** + * Load all the resources simultaneously + * @returns - When load is resolved + */ + AbstractMultiResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + var resources = this.items.map(function (item) { return item.resource; }).filter(function (item) { return item; }); + // TODO: also implement load part-by-part strategy + var promises = resources.map(function (item) { return item.load(); }); + this._load = Promise.all(promises) + .then(function () { + var _a = _this.items[0], realWidth = _a.realWidth, realHeight = _a.realHeight; + _this.resize(realWidth, realHeight); + return Promise.resolve(_this); + }); + return this._load; + }; + return AbstractMultiResource; + }(Resource)); + + /** + * A resource that contains a number of sources. + * @memberof PIXI + */ + var ArrayResource = /** @class */ (function (_super) { + __extends$i(ArrayResource, _super); + /** + * @param source - Number of items in array or the collection + * of image URLs to use. Can also be resources, image elements, canvas, etc. + * @param options - Options to apply to {@link PIXI.autoDetectResource} + * @param {number} [options.width] - Width of the resource + * @param {number} [options.height] - Height of the resource + */ + function ArrayResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + var urls; + var length; + if (Array.isArray(source)) { + urls = source; + length = source.length; + } + else { + length = source; + } + _this = _super.call(this, length, { width: width, height: height }) || this; + if (urls) { + _this.initFromArray(urls, options); + } + return _this; + } + /** + * Set a baseTexture by ID, + * ArrayResource just takes resource from it, nothing more + * @param baseTexture + * @param index - Zero-based index of resource to set + * @returns - Instance for chaining + */ + ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) { + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } + else { + throw new Error('ArrayResource does not support RenderTexture'); + } + return this; + }; + /** + * Add binding + * @param baseTexture + */ + ArrayResource.prototype.bind = function (baseTexture) { + _super.prototype.bind.call(this, baseTexture); + baseTexture.target = exports.TARGETS.TEXTURE_2D_ARRAY; + }; + /** + * Upload the resources to the GPU. + * @param renderer + * @param texture + * @param glTexture + * @returns - whether texture was uploaded + */ + ArrayResource.prototype.upload = function (renderer, texture, glTexture) { + var _a = this, length = _a.length, itemDirtyIds = _a.itemDirtyIds, items = _a.items; + var gl = renderer.gl; + if (glTexture.dirtyId < 0) { + gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, glTexture.internalFormat, this._width, this._height, length, 0, texture.format, glTexture.type, null); + } + for (var i = 0; i < length; i++) { + var item = items[i]; + if (itemDirtyIds[i] < item.dirtyId) { + itemDirtyIds[i] = item.dirtyId; + if (item.valid) { + gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset + 0, // yoffset + i, // zoffset + item.resource.width, item.resource.height, 1, texture.format, glTexture.type, item.resource.source); + } + } + } + return true; + }; + return ArrayResource; + }(AbstractMultiResource)); + + /** + * Base for all the image/canvas resources. + * @memberof PIXI + */ + var BaseImageResource = /** @class */ (function (_super) { + __extends$i(BaseImageResource, _super); + /** + * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source + */ + function BaseImageResource(source) { + var _this = this; + var sourceAny = source; + var width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width; + var height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height; + _this = _super.call(this, width, height) || this; + _this.source = source; + _this.noSubImage = false; + return _this; + } + /** + * Set cross origin based detecting the url and the crossorigin + * @param element - Element to apply crossOrigin + * @param url - URL to check + * @param crossorigin - Cross origin value to use + */ + BaseImageResource.crossOrigin = function (element, url, crossorigin) { + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + element.crossOrigin = determineCrossOrigin(url); + } + else if (crossorigin !== false) { + element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + }; + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture + * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] - (optional) + * @returns - true is success + */ + BaseImageResource.prototype.upload = function (renderer, baseTexture, glTexture, source) { + var gl = renderer.gl; + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + source = source || this.source; + if (source instanceof HTMLImageElement) { + if (!source.complete || source.naturalWidth === 0) { + return false; + } + } + else if (source instanceof HTMLVideoElement) { + if (source.readyState <= 1) { + return false; + } + } + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + if (!this.noSubImage + && baseTexture.target === gl.TEXTURE_2D + && glTexture.width === width + && glTexture.height === height) { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, glTexture.type, source); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.type, source); + } + return true; + }; + /** + * Checks if source width/height was changed, resize can cause extra baseTexture update. + * Triggers one update in any case. + */ + BaseImageResource.prototype.update = function () { + if (this.destroyed) { + return; + } + var source = this.source; + var width = source.naturalWidth || source.videoWidth || source.width; + var height = source.naturalHeight || source.videoHeight || source.height; + this.resize(width, height); + _super.prototype.update.call(this); + }; + /** Destroy this {@link BaseImageResource} */ + BaseImageResource.prototype.dispose = function () { + this.source = null; + }; + return BaseImageResource; + }(Resource)); + + /** + * @interface OffscreenCanvas + */ + /** + * Resource type for HTMLCanvasElement. + * @memberof PIXI + */ + var CanvasResource = /** @class */ (function (_super) { + __extends$i(CanvasResource, _super); + /** + * @param source - Canvas element to use + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function CanvasResource(source) { + return _super.call(this, source) || this; + } + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas + */ + CanvasResource.test = function (source) { + var OffscreenCanvas = globalThis.OffscreenCanvas; + // Check for browsers that don't yet support OffscreenCanvas + if (OffscreenCanvas && source instanceof OffscreenCanvas) { + return true; + } + return globalThis.HTMLCanvasElement && source instanceof HTMLCanvasElement; + }; + return CanvasResource; + }(BaseImageResource)); + + /** + * Resource for a CubeTexture which contains six resources. + * @memberof PIXI + */ + var CubeResource = /** @class */ (function (_super) { + __extends$i(CubeResource, _super); + /** + * @param {Array} [source] - Collection of URLs or resources + * to use as the sides of the cube. + * @param options - ImageResource options + * @param {number} [options.width] - Width of resource + * @param {number} [options.height] - Height of resource + * @param {number} [options.autoLoad=true] - Whether to auto-load resources + * @param {number} [options.linkBaseTexture=true] - In case BaseTextures are supplied, + * whether to copy them or use + */ + function CubeResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height, autoLoad = _a.autoLoad, linkBaseTexture = _a.linkBaseTexture; + if (source && source.length !== CubeResource.SIDES) { + throw new Error("Invalid length. Got " + source.length + ", expected 6"); + } + _this = _super.call(this, 6, { width: width, height: height }) || this; + for (var i = 0; i < CubeResource.SIDES; i++) { + _this.items[i].target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; + } + _this.linkBaseTexture = linkBaseTexture !== false; + if (source) { + _this.initFromArray(source, options); + } + if (autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Add binding. + * @param baseTexture - parent base texture + */ + CubeResource.prototype.bind = function (baseTexture) { + _super.prototype.bind.call(this, baseTexture); + baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP; + }; + CubeResource.prototype.addBaseTextureAt = function (baseTexture, index, linkBaseTexture) { + if (!this.items[index]) { + throw new Error("Index " + index + " is out of bounds"); + } + if (!this.linkBaseTexture + || baseTexture.parentTextureArray + || Object.keys(baseTexture._glTextures).length > 0) { + // copy mode + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } + else { + throw new Error("CubeResource does not support copying of renderTexture."); + } + } + else { + // link mode, the difficult one! + baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index; + baseTexture.parentTextureArray = this.baseTexture; + this.items[index] = baseTexture; + } + if (baseTexture.valid && !this.valid) { + this.resize(baseTexture.realWidth, baseTexture.realHeight); + } + this.items[index] = baseTexture; + return this; + }; + /** + * Upload the resource + * @param renderer + * @param _baseTexture + * @param glTexture + * @returns {boolean} true is success + */ + CubeResource.prototype.upload = function (renderer, _baseTexture, glTexture) { + var dirty = this.itemDirtyIds; + for (var i = 0; i < CubeResource.SIDES; i++) { + var side = this.items[i]; + if (dirty[i] < side.dirtyId || glTexture.dirtyId < _baseTexture.dirtyId) { + if (side.valid && side.resource) { + side.resource.upload(renderer, side, glTexture); + dirty[i] = side.dirtyId; + } + else if (dirty[i] < -1) { + // either item is not valid yet, either its a renderTexture + // allocate the memory + renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null); + dirty[i] = -1; + } + } + } + return true; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is an array of 6 elements + */ + CubeResource.test = function (source) { + return Array.isArray(source) && source.length === CubeResource.SIDES; + }; + /** Number of texture sides to store for CubeResources. */ + CubeResource.SIDES = 6; + return CubeResource; + }(AbstractMultiResource)); + + /** + * Resource type for HTMLImageElement. + * @memberof PIXI + */ + var ImageResource = /** @class */ (function (_super) { + __extends$i(ImageResource, _super); + /** + * @param source - image source or URL + * @param options + * @param {boolean} [options.autoLoad=true] - start loading process + * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create + * a bitmap before upload + * @param {boolean} [options.crossorigin=true] - Load image using cross origin + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap + */ + function ImageResource(source, options) { + var _this = this; + options = options || {}; + if (!(source instanceof HTMLImageElement)) { + var imageElement = new Image(); + BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); + imageElement.src = source; + source = imageElement; + } + _this = _super.call(this, source) || this; + // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height + // to non-zero values before its loading completes if images are in a cache. + // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images. + // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968). + if (!source.complete && !!_this._width && !!_this._height) { + _this._width = 0; + _this._height = 0; + } + _this.url = source.src; + _this._process = null; + _this.preserveBitmap = false; + _this.createBitmap = (options.createBitmap !== undefined + ? options.createBitmap : settings$1.CREATE_IMAGE_BITMAP) && !!globalThis.createImageBitmap; + _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null; + _this.bitmap = null; + _this._load = null; + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Returns a promise when image will be loaded and processed. + * @param createBitmap - whether process image into bitmap + */ + ImageResource.prototype.load = function (createBitmap) { + var _this = this; + if (this._load) { + return this._load; + } + if (createBitmap !== undefined) { + this.createBitmap = createBitmap; + } + this._load = new Promise(function (resolve, reject) { + var source = _this.source; + _this.url = source.src; + var completed = function () { + if (_this.destroyed) { + return; + } + source.onload = null; + source.onerror = null; + _this.resize(source.width, source.height); + _this._load = null; + if (_this.createBitmap) { + resolve(_this.process()); + } + else { + resolve(_this); + } + }; + if (source.complete && source.src) { + completed(); + } + else { + source.onload = completed; + source.onerror = function (event) { + // Avoids Promise freezing when resource broken + reject(event); + _this.onError.emit(event); + }; + } + }); + return this._load; + }; + /** + * Called when we need to convert image into BitmapImage. + * Can be called multiple times, real promise is cached inside. + * @returns - Cached promise to fill that bitmap + */ + ImageResource.prototype.process = function () { + var _this = this; + var source = this.source; + if (this._process !== null) { + return this._process; + } + if (this.bitmap !== null || !globalThis.createImageBitmap) { + return Promise.resolve(this); + } + var createImageBitmap = globalThis.createImageBitmap; + var cors = !source.crossOrigin || source.crossOrigin === 'anonymous'; + this._process = fetch(source.src, { + mode: cors ? 'cors' : 'no-cors' + }) + .then(function (r) { return r.blob(); }) + .then(function (blob) { return createImageBitmap(blob, 0, 0, source.width, source.height, { + premultiplyAlpha: _this.alphaMode === exports.ALPHA_MODES.UNPACK ? 'premultiply' : 'none', + }); }) + .then(function (bitmap) { + if (_this.destroyed) { + return Promise.reject(); + } + _this.bitmap = bitmap; + _this.update(); + _this._process = null; + return Promise.resolve(_this); + }); + return this._process; + }; + /** + * Upload the image resource to GPU. + * @param renderer - Renderer to upload to + * @param baseTexture - BaseTexture for this resource + * @param glTexture - GLTexture to use + * @returns {boolean} true is success + */ + ImageResource.prototype.upload = function (renderer, baseTexture, glTexture) { + if (typeof this.alphaMode === 'number') { + // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it + baseTexture.alphaMode = this.alphaMode; + } + if (!this.createBitmap) { + return _super.prototype.upload.call(this, renderer, baseTexture, glTexture); + } + if (!this.bitmap) { + // yeah, ignore the output + this.process(); + if (!this.bitmap) { + return false; + } + } + _super.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap); + if (!this.preserveBitmap) { + // checks if there are other renderers that possibly need this bitmap + var flag = true; + var glTextures = baseTexture._glTextures; + for (var key in glTextures) { + var otherTex = glTextures[key]; + if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) { + flag = false; + break; + } + } + if (flag) { + if (this.bitmap.close) { + this.bitmap.close(); + } + this.bitmap = null; + } + } + return true; + }; + /** Destroys this resource. */ + ImageResource.prototype.dispose = function () { + this.source.onload = null; + this.source.onerror = null; + _super.prototype.dispose.call(this); + if (this.bitmap) { + this.bitmap.close(); + this.bitmap = null; + } + this._process = null; + this._load = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is string or HTMLImageElement + */ + ImageResource.test = function (source) { + return typeof source === 'string' || source instanceof HTMLImageElement; + }; + return ImageResource; + }(BaseImageResource)); + + /** + * Resource type for SVG elements and graphics. + * @memberof PIXI + */ + var SVGResource = /** @class */ (function (_super) { + __extends$i(SVGResource, _super); + /** + * @param sourceBase64 - Base64 encoded SVG element or URL for SVG file. + * @param {object} [options] - Options to use + * @param {number} [options.scale=1] - Scale to apply to SVG. Overridden by... + * @param {number} [options.width] - Rasterize SVG this wide. Aspect ratio preserved if height not specified. + * @param {number} [options.height] - Rasterize SVG this high. Aspect ratio preserved if width not specified. + * @param {boolean} [options.autoLoad=true] - Start loading right away. + */ + function SVGResource(sourceBase64, options) { + var _this = this; + options = options || {}; + _this = _super.call(this, settings$1.ADAPTER.createCanvas()) || this; + _this._width = 0; + _this._height = 0; + _this.svg = sourceBase64; + _this.scale = options.scale || 1; + _this._overrideWidth = options.width; + _this._overrideHeight = options.height; + _this._resolve = null; + _this._crossorigin = options.crossorigin; + _this._load = null; + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + SVGResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + this._load = new Promise(function (resolve) { + // Save this until after load is finished + _this._resolve = function () { + _this.resize(_this.source.width, _this.source.height); + resolve(_this); + }; + // Convert SVG inline string to data-uri + if (SVGResource.SVG_XML.test(_this.svg.trim())) { + if (!btoa) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + _this.svg = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(_this.svg))); + } + _this._loadSvg(); + }); + return this._load; + }; + /** Loads an SVG image from `imageUrl` or `data URL`. */ + SVGResource.prototype._loadSvg = function () { + var _this = this; + var tempImage = new Image(); + BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin); + tempImage.src = this.svg; + tempImage.onerror = function (event) { + if (!_this._resolve) { + return; + } + tempImage.onerror = null; + _this.onError.emit(event); + }; + tempImage.onload = function () { + if (!_this._resolve) { + return; + } + var svgWidth = tempImage.width; + var svgHeight = tempImage.height; + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + // Set render size + var width = svgWidth * _this.scale; + var height = svgHeight * _this.scale; + if (_this._overrideWidth || _this._overrideHeight) { + width = _this._overrideWidth || _this._overrideHeight / svgHeight * svgWidth; + height = _this._overrideHeight || _this._overrideWidth / svgWidth * svgHeight; + } + width = Math.round(width); + height = Math.round(height); + // Create a canvas element + var canvas = _this.source; + canvas.width = width; + canvas.height = height; + canvas._pixiId = "canvas_" + uid(); + // Draw the Svg to the canvas + canvas + .getContext('2d') + .drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height); + _this._resolve(); + _this._resolve = null; + }; + }; + /** + * Get size from an svg string using a regular expression. + * @param svgString - a serialized svg element + * @returns - image extension + */ + SVGResource.getSize = function (svgString) { + var sizeMatch = SVGResource.SVG_SIZE.exec(svgString); + var size = {}; + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + return size; + }; + /** Destroys this texture. */ + SVGResource.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this._resolve = null; + this._crossorigin = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @param {string} extension - The extension of source, if set + * @returns {boolean} - If the source is a SVG source or data file + */ + SVGResource.test = function (source, extension) { + // url file extension is SVG + return extension === 'svg' + // source is SVG data-uri + || (typeof source === 'string' && (/^data:image\/svg\+xml(;(charset=utf8|utf8))?;base64/).test(source)) + // source is SVG inline + || (typeof source === 'string' && SVGResource.SVG_XML.test(source)); + }; + /** + * Regular expression for SVG XML document. + * @example <?xml version="1.0" encoding="utf-8" ?><!-- image/svg --><svg + * @readonly + */ + SVGResource.SVG_XML = /^(<\?xml[^?]+\?>)?\s*()]*-->)?\s*\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + return SVGResource; + }(BaseImageResource)); + + /** + * Resource type for {@code HTMLVideoElement}. + * @memberof PIXI + */ + var VideoResource = /** @class */ (function (_super) { + __extends$i(VideoResource, _super); + /** + * @param {HTMLVideoElement|object|string|Array} source - Video element to use. + * @param {object} [options] - Options to use + * @param {boolean} [options.autoLoad=true] - Start loading the video immediately + * @param {boolean} [options.autoPlay=true] - Start playing video immediately + * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video. + * Leave at 0 to update at every render. + * @param {boolean} [options.crossorigin=true] - Load image using cross origin + */ + function VideoResource(source, options) { + var _this = this; + options = options || {}; + if (!(source instanceof HTMLVideoElement)) { + var videoElement = document.createElement('video'); + // workaround for https://github.com/pixijs/pixi.js/issues/5996 + videoElement.setAttribute('preload', 'auto'); + videoElement.setAttribute('webkit-playsinline', ''); + videoElement.setAttribute('playsinline', ''); + if (typeof source === 'string') { + source = [source]; + } + var firstSrc = source[0].src || source[0]; + BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin); + // array of objects or strings + for (var i = 0; i < source.length; ++i) { + var sourceElement = document.createElement('source'); + var _a = source[i], src = _a.src, mime = _a.mime; + src = src || source[i]; + var baseSrc = src.split('?').shift().toLowerCase(); + var ext = baseSrc.slice(baseSrc.lastIndexOf('.') + 1); + mime = mime || VideoResource.MIME_TYPES[ext] || "video/" + ext; + sourceElement.src = src; + sourceElement.type = mime; + videoElement.appendChild(sourceElement); + } + // Override the source + source = videoElement; + } + _this = _super.call(this, source) || this; + _this.noSubImage = true; + _this._autoUpdate = true; + _this._isConnectedToTicker = false; + _this._updateFPS = options.updateFPS || 0; + _this._msToNextUpdate = 0; + _this.autoPlay = options.autoPlay !== false; + _this._load = null; + _this._resolve = null; + // Bind for listeners + _this._onCanPlay = _this._onCanPlay.bind(_this); + _this._onError = _this._onError.bind(_this); + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Trigger updating of the texture. + * @param _deltaTime - time delta since last tick + */ + VideoResource.prototype.update = function (_deltaTime) { + if (!this.destroyed) { + // account for if video has had its playbackRate changed + var elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate; + this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); + if (!this._updateFPS || this._msToNextUpdate <= 0) { + _super.prototype.update.call(this); + this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0; + } + } + }; + /** + * Start preloading the video resource. + * @returns {Promise} Handle the validate event + */ + VideoResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + var source = this.source; + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) + && source.width && source.height) { + source.complete = true; + } + source.addEventListener('play', this._onPlayStart.bind(this)); + source.addEventListener('pause', this._onPlayStop.bind(this)); + if (!this._isSourceReady()) { + source.addEventListener('canplay', this._onCanPlay); + source.addEventListener('canplaythrough', this._onCanPlay); + source.addEventListener('error', this._onError, true); + } + else { + this._onCanPlay(); + } + this._load = new Promise(function (resolve) { + if (_this.valid) { + resolve(_this); + } + else { + _this._resolve = resolve; + source.load(); + } + }); + return this._load; + }; + /** + * Handle video error events. + * @param event + */ + VideoResource.prototype._onError = function (event) { + this.source.removeEventListener('error', this._onError, true); + this.onError.emit(event); + }; + /** + * Returns true if the underlying source is playing. + * @returns - True if playing. + */ + VideoResource.prototype._isSourcePlaying = function () { + var source = this.source; + return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2); + }; + /** + * Returns true if the underlying source is ready for playing. + * @returns - True if ready. + */ + VideoResource.prototype._isSourceReady = function () { + var source = this.source; + return source.readyState === 3 || source.readyState === 4; + }; + /** Runs the update loop when the video is ready to play. */ + VideoResource.prototype._onPlayStart = function () { + // Just in case the video has not received its can play even yet.. + if (!this.valid) { + this._onCanPlay(); + } + if (this.autoUpdate && !this._isConnectedToTicker) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + }; + /** Fired when a pause event is triggered, stops the update loop. */ + VideoResource.prototype._onPlayStop = function () { + if (this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + }; + /** Fired when the video is loaded and ready to play. */ + VideoResource.prototype._onCanPlay = function () { + var source = this.source; + source.removeEventListener('canplay', this._onCanPlay); + source.removeEventListener('canplaythrough', this._onCanPlay); + var valid = this.valid; + this.resize(source.videoWidth, source.videoHeight); + // prevent multiple loaded dispatches.. + if (!valid && this._resolve) { + this._resolve(this); + this._resolve = null; + } + if (this._isSourcePlaying()) { + this._onPlayStart(); + } + else if (this.autoPlay) { + source.play(); + } + }; + /** Destroys this texture. */ + VideoResource.prototype.dispose = function () { + if (this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + var source = this.source; + if (source) { + source.removeEventListener('error', this._onError, true); + source.pause(); + source.src = ''; + source.load(); + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(VideoResource.prototype, "autoUpdate", { + /** Should the base texture automatically update itself, set to true by default. */ + get: function () { + return this._autoUpdate; + }, + set: function (value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(VideoResource.prototype, "updateFPS", { + /** + * How many times a second to update the texture from the video. Leave at 0 to update at every render. + * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient. + */ + get: function () { + return this._updateFPS; + }, + set: function (value) { + if (value !== this._updateFPS) { + this._updateFPS = value; + } + }, + enumerable: false, + configurable: true + }); + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @param {string} extension - The extension of source, if set + * @returns {boolean} `true` if video source + */ + VideoResource.test = function (source, extension) { + return (globalThis.HTMLVideoElement && source instanceof HTMLVideoElement) + || VideoResource.TYPES.indexOf(extension) > -1; + }; + /** + * List of common video file extensions supported by VideoResource. + * @readonly + */ + VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov']; + /** + * Map of video MIME types that can't be directly derived from file extensions. + * @readonly + */ + VideoResource.MIME_TYPES = { + ogv: 'video/ogg', + mov: 'video/quicktime', + m4v: 'video/mp4', + }; + return VideoResource; + }(BaseImageResource)); + + /** + * Resource type for ImageBitmap. + * @memberof PIXI + */ + var ImageBitmapResource = /** @class */ (function (_super) { + __extends$i(ImageBitmapResource, _super); + /** + * @param source - Image element to use + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function ImageBitmapResource(source) { + return _super.call(this, source) || this; + } + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is an ImageBitmap + */ + ImageBitmapResource.test = function (source) { + return !!globalThis.createImageBitmap && typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap; + }; + return ImageBitmapResource; + }(BaseImageResource)); + + INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource); + + var _resources = { + __proto__: null, + Resource: Resource, + BaseImageResource: BaseImageResource, + INSTALLED: INSTALLED, + autoDetectResource: autoDetectResource, + AbstractMultiResource: AbstractMultiResource, + ArrayResource: ArrayResource, + BufferResource: BufferResource, + CanvasResource: CanvasResource, + CubeResource: CubeResource, + ImageResource: ImageResource, + SVGResource: SVGResource, + VideoResource: VideoResource, + ImageBitmapResource: ImageBitmapResource + }; + + /** + * Resource type for DepthTexture. + * @memberof PIXI + */ + var DepthResource = /** @class */ (function (_super) { + __extends$i(DepthResource, _super); + function DepthResource() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture - glTexture + * @returns - true is success + */ + DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) { + var gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + if (glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + }; + return DepthResource; + }(BufferResource)); + + /** + * A framebuffer can be used to render contents off of the screen. {@link PIXI.BaseRenderTexture} uses + * one internally to render into itself. You can attach a depth or stencil buffer to a framebuffer. + * + * On WebGL 2 machines, shaders can output to multiple textures simultaneously with GLSL 300 ES. + * @memberof PIXI + */ + var Framebuffer = /** @class */ (function () { + /** + * @param width - Width of the frame buffer + * @param height - Height of the frame buffer + */ + function Framebuffer(width, height) { + this.width = Math.round(width || 100); + this.height = Math.round(height || 100); + this.stencil = false; + this.depth = false; + this.dirtyId = 0; + this.dirtyFormat = 0; + this.dirtySize = 0; + this.depthTexture = null; + this.colorTextures = []; + this.glFramebuffers = {}; + this.disposeRunner = new Runner('disposeFramebuffer'); + this.multisample = exports.MSAA_QUALITY.NONE; + } + Object.defineProperty(Framebuffer.prototype, "colorTexture", { + /** + * Reference to the colorTexture. + * @readonly + */ + get: function () { + return this.colorTextures[0]; + }, + enumerable: false, + configurable: true + }); + /** + * Add texture to the colorTexture array. + * @param index - Index of the array to add the texture to + * @param texture - Texture to add to the array + */ + Framebuffer.prototype.addColorTexture = function (index, texture) { + if (index === void 0) { index = 0; } + // TODO add some validation to the texture - same width / height etc? + this.colorTextures[index] = texture || new BaseTexture(null, { + scaleMode: exports.SCALE_MODES.NEAREST, + resolution: 1, + mipmap: exports.MIPMAP_MODES.OFF, + width: this.width, + height: this.height, + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Add a depth texture to the frame buffer. + * @param texture - Texture to add. + */ + Framebuffer.prototype.addDepthTexture = function (texture) { + /* eslint-disable max-len */ + this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { + scaleMode: exports.SCALE_MODES.NEAREST, + resolution: 1, + width: this.width, + height: this.height, + mipmap: exports.MIPMAP_MODES.OFF, + format: exports.FORMATS.DEPTH_COMPONENT, + type: exports.TYPES.UNSIGNED_SHORT, + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** Enable depth on the frame buffer. */ + Framebuffer.prototype.enableDepth = function () { + this.depth = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** Enable stencil on the frame buffer. */ + Framebuffer.prototype.enableStencil = function () { + this.stencil = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Resize the frame buffer + * @param width - Width of the frame buffer to resize to + * @param height - Height of the frame buffer to resize to + */ + Framebuffer.prototype.resize = function (width, height) { + width = Math.round(width); + height = Math.round(height); + if (width === this.width && height === this.height) + { return; } + this.width = width; + this.height = height; + this.dirtyId++; + this.dirtySize++; + for (var i = 0; i < this.colorTextures.length; i++) { + var texture = this.colorTextures[i]; + var resolution = texture.resolution; + // take into account the fact the texture may have a different resolution.. + texture.setSize(width / resolution, height / resolution); + } + if (this.depthTexture) { + var resolution = this.depthTexture.resolution; + this.depthTexture.setSize(width / resolution, height / resolution); + } + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Framebuffer.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys and removes the depth texture added to this framebuffer. */ + Framebuffer.prototype.destroyDepthTexture = function () { + if (this.depthTexture) { + this.depthTexture.destroy(); + this.depthTexture = null; + ++this.dirtyId; + ++this.dirtyFormat; + } + }; + return Framebuffer; + }()); + + /** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(); + * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 }); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * let sprite = PIXI.Sprite.from("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, {renderTexture}); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 }); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture + * ``` + * @memberof PIXI + */ + var BaseRenderTexture = /** @class */ (function (_super) { + __extends$i(BaseRenderTexture, _super); + /** + * @param options + * @param {number} [options.width=100] - The width of the base render texture. + * @param {number} [options.height=100] - The height of the base render texture. + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} + * for possible values. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio + * of the texture being generated. + * @param {PIXI.MSAA_QUALITY} [options.multisample=PIXI.MSAA_QUALITY.NONE] - The number of samples of the frame buffer. + */ + function BaseRenderTexture(options) { + if (options === void 0) { options = {}; } + var _this = this; + if (typeof options === 'number') { + /* eslint-disable prefer-rest-params */ + // Backward compatibility of signature + var width = arguments[0]; + var height = arguments[1]; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + options = { width: width, height: height, scaleMode: scaleMode, resolution: resolution }; + /* eslint-enable prefer-rest-params */ + } + options.width = options.width || 100; + options.height = options.height || 100; + options.multisample = options.multisample !== undefined ? options.multisample : exports.MSAA_QUALITY.NONE; + _this = _super.call(this, null, options) || this; + // Set defaults + _this.mipmap = exports.MIPMAP_MODES.OFF; + _this.valid = true; + _this.clearColor = [0, 0, 0, 0]; + _this.framebuffer = new Framebuffer(_this.realWidth, _this.realHeight) + .addColorTexture(0, _this); + _this.framebuffer.multisample = options.multisample; + // TODO - could this be added the systems? + _this.maskStack = []; + _this.filterStack = [{}]; + return _this; + } + /** + * Resizes the BaseRenderTexture. + * @param desiredWidth - The desired width to resize to. + * @param desiredHeight - The desired height to resize to. + */ + BaseRenderTexture.prototype.resize = function (desiredWidth, desiredHeight) { + this.framebuffer.resize(desiredWidth * this.resolution, desiredHeight * this.resolution); + this.setRealSize(this.framebuffer.width, this.framebuffer.height); + }; + /** + * Frees the texture and framebuffer from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * @fires PIXI.BaseTexture#dispose + */ + BaseRenderTexture.prototype.dispose = function () { + this.framebuffer.dispose(); + _super.prototype.dispose.call(this); + }; + /** Destroys this texture. */ + BaseRenderTexture.prototype.destroy = function () { + _super.prototype.destroy.call(this); + this.framebuffer.destroyDepthTexture(); + this.framebuffer = null; + }; + return BaseRenderTexture; + }(BaseTexture)); + + /** + * Stores a texture's frame in UV coordinates, in + * which everything lies in the rectangle `[(0,0), (1,0), + * (1,1), (0,1)]`. + * + * | Corner | Coordinates | + * |--------------|-------------| + * | Top-Left | `(x0,y0)` | + * | Top-Right | `(x1,y1)` | + * | Bottom-Right | `(x2,y2)` | + * | Bottom-Left | `(x3,y3)` | + * @protected + * @memberof PIXI + */ + var TextureUvs = /** @class */ (function () { + function TextureUvs() { + this.x0 = 0; + this.y0 = 0; + this.x1 = 1; + this.y1 = 0; + this.x2 = 1; + this.y2 = 1; + this.x3 = 0; + this.y3 = 1; + this.uvsFloat32 = new Float32Array(8); + } + /** + * Sets the texture Uvs based on the given frame information. + * @protected + * @param frame - The frame of the texture + * @param baseFrame - The base frame of the texture + * @param rotate - Rotation of frame, see {@link PIXI.groupD8} + */ + TextureUvs.prototype.set = function (frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + // coordinates of center + var cX = (frame.x / tw) + w2; + var cY = (frame.y / th) + h2; + rotate = groupD8.add(rotate, groupD8.NW); // NW is top-left corner + this.x0 = cX + (w2 * groupD8.uX(rotate)); + this.y0 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + (w2 * groupD8.uX(rotate)); + this.y1 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); + this.x2 = cX + (w2 * groupD8.uX(rotate)); + this.y2 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); + this.x3 = cX + (w2 * groupD8.uX(rotate)); + this.y3 = cY + (h2 * groupD8.uY(rotate)); + } + else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + this.uvsFloat32[0] = this.x0; + this.uvsFloat32[1] = this.y0; + this.uvsFloat32[2] = this.x1; + this.uvsFloat32[3] = this.y1; + this.uvsFloat32[4] = this.x2; + this.uvsFloat32[5] = this.y2; + this.uvsFloat32[6] = this.x3; + this.uvsFloat32[7] = this.y3; + }; + TextureUvs.prototype.toString = function () { + return "[@pixi/core:TextureUvs " + + ("x0=" + this.x0 + " y0=" + this.y0 + " ") + + ("x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " ") + + ("y2=" + this.y2 + " x3=" + this.x3 + " y3=" + this.y3) + + "]"; + }; + return TextureUvs; + }()); + + var DEFAULT_UVS = new TextureUvs(); + /** + * Used to remove listeners from WHITE and EMPTY Textures + * @ignore + */ + function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() { }; + tex.on = function _emptyOn() { }; + tex.once = function _emptyOnce() { }; + tex.emit = function _emptyEmit() { }; + } + /** + * A texture stores the information that represents an image or part of an image. + * + * It cannot be added to the display list directly; instead use it as the texture for a Sprite. + * If no frame is provided for a texture, then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.from('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * If you didnt pass the texture frame to constructor, it enables `noFrame` mode: + * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture. + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.from('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * @memberof PIXI + * @typeParam R - The BaseTexture's Resource type. + */ + var Texture = /** @class */ (function (_super) { + __extends$i(Texture, _super); + /** + * @param baseTexture - The base texture source to create the texture from + * @param frame - The rectangle frame of the texture to show + * @param orig - The area of original texture + * @param trim - Trimmed rectangle of original texture + * @param rotate - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8} + * @param anchor - Default anchor point used for sprite placement / rotation + */ + function Texture(baseTexture, frame, orig, trim, rotate, anchor) { + var _this = _super.call(this) || this; + _this.noFrame = false; + if (!frame) { + _this.noFrame = true; + frame = new Rectangle(0, 0, 1, 1); + } + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + _this.baseTexture = baseTexture; + _this._frame = frame; + _this.trim = trim; + _this.valid = false; + _this._uvs = DEFAULT_UVS; + _this.uvMatrix = null; + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + _this._rotate = Number(rotate || 0); + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } + else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + _this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0); + _this._updateID = 0; + _this.textureCacheIds = []; + if (!baseTexture.valid) { + baseTexture.once('loaded', _this.onBaseTextureUpdated, _this); + } + else if (_this.noFrame) { + // if there is no frame we should monitor for any base texture changes.. + if (baseTexture.valid) { + _this.onBaseTextureUpdated(baseTexture); + } + } + else { + _this.frame = frame; + } + if (_this.noFrame) { + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + return _this; + } + /** + * Updates this texture on the gpu. + * + * Calls the TextureResource update. + * + * If you adjusted `frame` manually, please call `updateUvs()` instead. + */ + Texture.prototype.update = function () { + if (this.baseTexture.resource) { + this.baseTexture.resource.update(); + } + }; + /** + * Called when the base texture is updated + * @protected + * @param baseTexture - The base texture. + */ + Texture.prototype.onBaseTextureUpdated = function (baseTexture) { + if (this.noFrame) { + if (!this.baseTexture.valid) { + return; + } + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + this.valid = true; + this.updateUvs(); + } + else { + // TODO this code looks confusing.. boo to abusing getters and setters! + // if user gave us frame that has bigger size than resized texture it can be a problem + this.frame = this._frame; + } + this.emit('update', this); + }; + /** + * Destroys this texture + * @param [destroyBase=false] - Whether to destroy the base texture as well + */ + Texture.prototype.destroy = function (destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + var resource = this.baseTexture.resource; + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (resource && resource.url && TextureCache[resource.url]) { + Texture.removeFromCache(resource.url); + } + this.baseTexture.destroy(); + } + this.baseTexture.off('loaded', this.onBaseTextureUpdated, this); + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture = null; + } + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + this.valid = false; + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + /** + * Creates a new texture object that acts the same as this one. + * @returns - The new texture + */ + Texture.prototype.clone = function () { + var clonedFrame = this._frame.clone(); + var clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone(); + var clonedTexture = new Texture(this.baseTexture, !this.noFrame && clonedFrame, clonedOrig, this.trim && this.trim.clone(), this.rotate, this.defaultAnchor); + if (this.noFrame) { + clonedTexture._frame = clonedFrame; + } + return clonedTexture; + }; + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + * Call it after changing the frame + */ + Texture.prototype.updateUvs = function () { + if (this._uvs === DEFAULT_UVS) { + this._uvs = new TextureUvs(); + } + this._uvs.set(this._frame, this.baseTexture, this.rotate); + this._updateID++; + }; + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source - + * Source or array of sources to create texture from + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id + * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. + * @returns {PIXI.Texture} The newly created texture + */ + Texture.from = function (source, options, strict) { + if (options === void 0) { options = {}; } + if (strict === void 0) { strict = settings$1.STRICT_TEXTURE_CACHE; } + var isFrame = typeof source === 'string'; + var cacheId = null; + if (isFrame) { + cacheId = source; + } + else if (source instanceof BaseTexture) { + if (!source.cacheId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source.cacheId = prefix + "-" + uid(); + BaseTexture.addToCache(source, source.cacheId); + } + cacheId = source.cacheId; + } + else { + if (!source._pixiId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source._pixiId = prefix + "_" + uid(); + } + cacheId = source._pixiId; + } + var texture = TextureCache[cacheId]; + // Strict-mode rejects invalid cacheIds + if (isFrame && strict && !texture) { + throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache."); + } + if (!texture && !(source instanceof BaseTexture)) { + if (!options.resolution) { + options.resolution = getResolutionOfUrl(source); + } + texture = new Texture(new BaseTexture(source, options)); + texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); + Texture.addToCache(texture, cacheId); + } + else if (!texture && (source instanceof BaseTexture)) { + texture = new Texture(source); + Texture.addToCache(texture, cacheId); + } + // lets assume its a base texture! + return texture; + }; + /** + * Useful for loading textures via URLs. Use instead of `Texture.from` because + * it does a better job of handling failed URLs more effectively. This also ignores + * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images. + * @param url - The remote URL or array of URLs to load. + * @param options - Optional options to include + * @returns - A Promise that resolves to a Texture. + */ + Texture.fromURL = function (url, options) { + var resourceOptions = Object.assign({ autoLoad: false }, options === null || options === void 0 ? void 0 : options.resourceOptions); + var texture = Texture.from(url, Object.assign({ resourceOptions: resourceOptions }, options), false); + var resource = texture.baseTexture.resource; + // The texture was already loaded + if (texture.baseTexture.valid) { + return Promise.resolve(texture); + } + // Manually load the texture, this should allow users to handle load errors + return resource.load().then(function () { return Promise.resolve(texture); }); + }; + /** + * Create a new Texture with a BufferResource from a Float32Array. + * RGBA values are floats from 0 to 1. + * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data + * is provided, a new Float32Array is created. + * @param width - Width of the resource + * @param height - Height of the resource + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @returns - The resulting new BaseTexture + */ + Texture.fromBuffer = function (buffer, width, height, options) { + return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); + }; + /** + * Create a texture from a source and add to the cache. + * @param {HTMLImageElement|HTMLCanvasElement|string} source - The input source. + * @param imageUrl - File name of texture, for cache and resolving resolution. + * @param name - Human readable name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @param options + * @returns - Output texture + */ + Texture.fromLoader = function (source, imageUrl, name, options) { + var baseTexture = new BaseTexture(source, Object.assign({ + scaleMode: settings$1.SCALE_MODE, + resolution: getResolutionOfUrl(imageUrl), + }, options)); + var resource = baseTexture.resource; + if (resource instanceof ImageResource) { + resource.url = imageUrl; + } + var texture = new Texture(baseTexture); + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + // lets also add the frame to pixi's global cache for 'fromLoader' function + BaseTexture.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + // also add references by url if they are different. + if (name !== imageUrl) { + BaseTexture.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + // Generally images are valid right away + if (texture.baseTexture.valid) { + return Promise.resolve(texture); + } + // SVG assets need to be parsed async, let's wait + return new Promise(function (resolve) { + texture.baseTexture.once('loaded', function () { return resolve(texture); }); + }); + }; + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * @param texture - The Texture to add to the cache. + * @param id - The id that the Texture will be stored against. + */ + Texture.addToCache = function (texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + if (TextureCache[id]) { + // eslint-disable-next-line no-console + console.warn("Texture added to the cache with an id [" + id + "] that already had an entry"); + } + TextureCache[id] = texture; + } + }; + /** + * Remove a Texture from the global TextureCache. + * @param texture - id of a Texture to be removed, or a Texture instance itself + * @returns - The Texture that was removed + */ + Texture.removeFromCache = function (texture) { + if (typeof texture === 'string') { + var textureFromCache = TextureCache[texture]; + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + delete TextureCache[texture]; + return textureFromCache; + } + } + else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (TextureCache[texture.textureCacheIds[i]] === texture) { + delete TextureCache[texture.textureCacheIds[i]]; + } + } + texture.textureCacheIds.length = 0; + return texture; + } + return null; + }; + Object.defineProperty(Texture.prototype, "resolution", { + /** + * Returns resolution of baseTexture + * @readonly + */ + get: function () { + return this.baseTexture.resolution; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "frame", { + /** + * The frame specifies the region of the base texture that this texture uses. + * Please call `updateUvs()` after you change coordinates of `frame` manually. + */ + get: function () { + return this._frame; + }, + set: function (frame) { + this._frame = frame; + this.noFrame = false; + var x = frame.x, y = frame.y, width = frame.width, height = frame.height; + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width; + var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height; + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + + (errorX + " " + relationship + " " + errorY)); + } + this.valid = width && height && this.baseTexture.valid; + if (!this.trim && !this.rotate) { + this.orig = frame; + } + if (this.valid) { + this.updateUvs(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "rotate", { + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.groupD8} for explanation + */ + get: function () { + return this._rotate; + }, + set: function (rotate) { + this._rotate = rotate; + if (this.valid) { + this.updateUvs(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "width", { + /** The width of the Texture in pixels. */ + get: function () { + return this.orig.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "height", { + /** The height of the Texture in pixels. */ + get: function () { + return this.orig.height; + }, + enumerable: false, + configurable: true + }); + /** Utility function for BaseTexture|Texture cast. */ + Texture.prototype.castToBaseTexture = function () { + return this.baseTexture; + }; + Object.defineProperty(Texture, "EMPTY", { + /** An empty texture, used often to not have to create multiple empty textures. Can not be destroyed. */ + get: function () { + if (!Texture._EMPTY) { + Texture._EMPTY = new Texture(new BaseTexture()); + removeAllHandlers(Texture._EMPTY); + removeAllHandlers(Texture._EMPTY.baseTexture); + } + return Texture._EMPTY; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture, "WHITE", { + /** A white texture of 16x16 size, used for graphics and other things Can not be destroyed. */ + get: function () { + if (!Texture._WHITE) { + var canvas = settings$1.ADAPTER.createCanvas(16, 16); + var context = canvas.getContext('2d'); + canvas.width = 16; + canvas.height = 16; + context.fillStyle = 'white'; + context.fillRect(0, 0, 16, 16); + Texture._WHITE = new Texture(BaseTexture.from(canvas)); + removeAllHandlers(Texture._WHITE); + removeAllHandlers(Texture._WHITE.baseTexture); + } + return Texture._WHITE; + }, + enumerable: false, + configurable: true + }); + return Texture; + }(eventemitter3)); + + /** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * __Hint-2__: The actual memory allocation will happen on first render. + * You shouldn't create renderTextures each frame just to delete them after, try to reuse them. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(); + * let renderTexture = PIXI.RenderTexture.create({ width: 800, height: 600 }); + * let sprite = PIXI.Sprite.from("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, {renderTexture}); + * ``` + * Note that you should not create a new renderer, but reuse the same one as the rest of the application. + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create({ width: 100, height: 100 }); + * + * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture + * ``` + * @memberof PIXI + */ + var RenderTexture = /** @class */ (function (_super) { + __extends$i(RenderTexture, _super); + /** + * @param baseRenderTexture - The base texture object that this texture uses. + * @param frame - The rectangle frame of the texture to show. + */ + function RenderTexture(baseRenderTexture, frame) { + var _this = _super.call(this, baseRenderTexture, frame) || this; + _this.valid = true; + _this.filterFrame = null; + _this.filterPoolKey = null; + _this.updateUvs(); + return _this; + } + Object.defineProperty(RenderTexture.prototype, "framebuffer", { + /** + * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast. + * @readonly + */ + get: function () { + return this.baseTexture.framebuffer; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(RenderTexture.prototype, "multisample", { + /** + * Shortcut to `this.framebuffer.multisample`. + * @default PIXI.MSAA_QUALITY.NONE + */ + get: function () { + return this.framebuffer.multisample; + }, + set: function (value) { + this.framebuffer.multisample = value; + }, + enumerable: false, + configurable: true + }); + /** + * Resizes the RenderTexture. + * @param desiredWidth - The desired width to resize to. + * @param desiredHeight - The desired height to resize to. + * @param resizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + RenderTexture.prototype.resize = function (desiredWidth, desiredHeight, resizeBaseTexture) { + if (resizeBaseTexture === void 0) { resizeBaseTexture = true; } + var resolution = this.baseTexture.resolution; + var width = Math.round(desiredWidth * resolution) / resolution; + var height = Math.round(desiredHeight * resolution) / resolution; + // TODO - could be not required.. + this.valid = (width > 0 && height > 0); + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + if (resizeBaseTexture) { + this.baseTexture.resize(width, height); + } + this.updateUvs(); + }; + /** + * Changes the resolution of baseTexture, but does not change framebuffer size. + * @param resolution - The new resolution to apply to RenderTexture + */ + RenderTexture.prototype.setResolution = function (resolution) { + var baseTexture = this.baseTexture; + if (baseTexture.resolution === resolution) { + return; + } + baseTexture.setResolution(resolution); + this.resize(baseTexture.width, baseTexture.height, false); + }; + RenderTexture.create = function (options) { + var arguments$1 = arguments; + + var rest = []; + for (var _i = 1; _i < arguments.length; _i++) { + rest[_i - 1] = arguments$1[_i]; + } + // @deprecated fallback, old-style: create(width, height, scaleMode, resolution) + if (typeof options === 'number') { + deprecation$1('6.0.0', 'Arguments (width, height, scaleMode, resolution) have been deprecated.'); + /* eslint-disable prefer-rest-params */ + options = { + width: options, + height: rest[0], + scaleMode: rest[1], + resolution: rest[2], + }; + /* eslint-enable prefer-rest-params */ + } + return new RenderTexture(new BaseRenderTexture(options)); + }; + return RenderTexture; + }(Texture)); + + /** + * Texture pool, used by FilterSystem and plugins. + * + * Stores collection of temporary pow2 or screen-sized renderTextures + * + * If you use custom RenderTexturePool for your filters, you can use methods + * `getFilterTexture` and `returnFilterTexture` same as in + * @memberof PIXI + */ + var RenderTexturePool = /** @class */ (function () { + /** + * @param textureOptions - options that will be passed to BaseRenderTexture constructor + * @param {PIXI.SCALE_MODES} [textureOptions.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values. + */ + function RenderTexturePool(textureOptions) { + this.texturePool = {}; + this.textureOptions = textureOptions || {}; + this.enableFullScreen = false; + this._pixelsWidth = 0; + this._pixelsHeight = 0; + } + /** + * Creates texture with params that were specified in pool constructor. + * @param realWidth - Width of texture in pixels. + * @param realHeight - Height of texture in pixels. + * @param multisample - Number of samples of the framebuffer. + */ + RenderTexturePool.prototype.createTexture = function (realWidth, realHeight, multisample) { + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + var baseRenderTexture = new BaseRenderTexture(Object.assign({ + width: realWidth, + height: realHeight, + resolution: 1, + multisample: multisample, + }, this.textureOptions)); + return new RenderTexture(baseRenderTexture); + }; + /** + * Gets a Power-of-Two render texture or fullScreen texture + * @param minWidth - The minimum width of the render texture. + * @param minHeight - The minimum height of the render texture. + * @param resolution - The resolution of the render texture. + * @param multisample - Number of samples of the render texture. + * @returns The new render texture. + */ + RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution, multisample) { + if (resolution === void 0) { resolution = 1; } + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + var key; + minWidth = Math.ceil((minWidth * resolution) - 1e-6); + minHeight = Math.ceil((minHeight * resolution) - 1e-6); + if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) { + minWidth = nextPow2(minWidth); + minHeight = nextPow2(minHeight); + key = (((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF)) >>> 0; + if (multisample > 1) { + key += multisample * 0x100000000; + } + } + else { + key = multisample > 1 ? -multisample : -1; + } + if (!this.texturePool[key]) { + this.texturePool[key] = []; + } + var renderTexture = this.texturePool[key].pop(); + if (!renderTexture) { + renderTexture = this.createTexture(minWidth, minHeight, multisample); + } + renderTexture.filterPoolKey = key; + renderTexture.setResolution(resolution); + return renderTexture; + }; + /** + * Gets extra texture of the same size as input renderTexture + * + * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)` + * @param input - renderTexture from which size and resolution will be copied + * @param resolution - override resolution of the renderTexture + * It overrides, it does not multiply + * @param multisample - number of samples of the renderTexture + */ + RenderTexturePool.prototype.getFilterTexture = function (input, resolution, multisample) { + var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; + }; + /** + * Place a render texture back into the pool. + * @param renderTexture - The renderTexture to free + */ + RenderTexturePool.prototype.returnTexture = function (renderTexture) { + var key = renderTexture.filterPoolKey; + renderTexture.filterFrame = null; + this.texturePool[key].push(renderTexture); + }; + /** + * Alias for returnTexture, to be compliant with FilterSystem interface. + * @param renderTexture - The renderTexture to free + */ + RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) { + this.returnTexture(renderTexture); + }; + /** + * Clears the pool. + * @param destroyTextures - Destroy all stored textures. + */ + RenderTexturePool.prototype.clear = function (destroyTextures) { + destroyTextures = destroyTextures !== false; + if (destroyTextures) { + for (var i in this.texturePool) { + var textures = this.texturePool[i]; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + } + this.texturePool = {}; + }; + /** + * If screen size was changed, drops all screen-sized textures, + * sets new screen size, sets `enableFullScreen` to true + * + * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen` + * @param size - Initial size of screen. + */ + RenderTexturePool.prototype.setScreenSize = function (size) { + if (size.width === this._pixelsWidth + && size.height === this._pixelsHeight) { + return; + } + this.enableFullScreen = size.width > 0 && size.height > 0; + for (var i in this.texturePool) { + if (!(Number(i) < 0)) { + continue; + } + var textures = this.texturePool[i]; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + this.texturePool[i] = []; + } + this._pixelsWidth = size.width; + this._pixelsHeight = size.height; + }; + /** + * Key that is used to store fullscreen renderTextures in a pool + * @constant + */ + RenderTexturePool.SCREEN_KEY = -1; + return RenderTexturePool; + }()); + + /* eslint-disable max-len */ + /** + * Holds the information for a single attribute structure required to render geometry. + * + * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer} + * This can include anything from positions, uvs, normals, colors etc. + * @memberof PIXI + */ + var Attribute = /** @class */ (function () { + /** + * @param buffer - the id of the buffer that this attribute will look for + * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2. + * @param normalized - should the data be normalized. + * @param {PIXI.TYPES} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @param [start=0] - How far into the array to start reading values (used for interleaving data) + * @param [instance=false] - Whether the geometry is instanced. + */ + function Attribute(buffer, size, normalized, type, stride, start, instance) { + if (size === void 0) { size = 0; } + if (normalized === void 0) { normalized = false; } + if (type === void 0) { type = exports.TYPES.FLOAT; } + this.buffer = buffer; + this.size = size; + this.normalized = normalized; + this.type = type; + this.stride = stride; + this.start = start; + this.instance = instance; + } + /** Destroys the Attribute. */ + Attribute.prototype.destroy = function () { + this.buffer = null; + }; + /** + * Helper function that creates an Attribute based on the information provided + * @param buffer - the id of the buffer that this attribute will look for + * @param [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 + * @param [normalized=false] - should the data be normalized. + * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @returns - A new {@link PIXI.Attribute} based on the information provided + */ + Attribute.from = function (buffer, size, normalized, type, stride) { + return new Attribute(buffer, size, normalized, type, stride); + }; + return Attribute; + }()); + + var UID$4 = 0; + /** + * A wrapper for data so that it can be used and uploaded by WebGL + * @memberof PIXI + */ + var Buffer = /** @class */ (function () { + /** + * @param {PIXI.IArrayBuffer} data - the data to store in the buffer. + * @param _static - `true` for static buffer + * @param index - `true` for index buffer + */ + function Buffer(data, _static, index) { + if (_static === void 0) { _static = true; } + if (index === void 0) { index = false; } + this.data = (data || new Float32Array(1)); + this._glBuffers = {}; + this._updateID = 0; + this.index = index; + this.static = _static; + this.id = UID$4++; + this.disposeRunner = new Runner('disposeBuffer'); + } + // TODO could explore flagging only a partial upload? + /** + * Flags this buffer as requiring an upload to the GPU. + * @param {PIXI.IArrayBuffer|number[]} [data] - the data to update in the buffer. + */ + Buffer.prototype.update = function (data) { + if (data instanceof Array) { + data = new Float32Array(data); + } + this.data = data || this.data; + this._updateID++; + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Buffer.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys the buffer. */ + Buffer.prototype.destroy = function () { + this.dispose(); + this.data = null; + }; + Object.defineProperty(Buffer.prototype, "index", { + get: function () { + return this.type === exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + }, + /** + * Flags whether this is an index buffer. + * + * Index buffers are of type `ELEMENT_ARRAY_BUFFER`. Note that setting this property to false will make + * the buffer of type `ARRAY_BUFFER`. + * + * For backwards compatibility. + */ + set: function (value) { + this.type = value ? exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER : exports.BUFFER_TYPE.ARRAY_BUFFER; + }, + enumerable: false, + configurable: true + }); + /** + * Helper function that creates a buffer based on an array or TypedArray + * @param {ArrayBufferView | number[]} data - the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. + * @returns - A new Buffer based on the data provided. + */ + Buffer.from = function (data) { + if (data instanceof Array) { + data = new Float32Array(data); + } + return new Buffer(data); + }; + return Buffer; + }()); + + /* eslint-disable object-shorthand */ + var map$1 = { + Float32Array: Float32Array, + Uint32Array: Uint32Array, + Int32Array: Int32Array, + Uint8Array: Uint8Array, + }; + function interleaveTypedArrays(arrays, sizes) { + var outSize = 0; + var stride = 0; + var views = {}; + for (var i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + var buffer = new ArrayBuffer(outSize * 4); + var out = null; + var littleOffset = 0; + for (var i = 0; i < arrays.length; i++) { + var size = sizes[i]; + var array = arrays[i]; + var type = getBufferType(array); + if (!views[type]) { + views[type] = new map$1[type](buffer); + } + out = views[type]; + for (var j = 0; j < array.length; j++) { + var indexStart = ((j / size | 0) * stride) + littleOffset; + var index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); + } + + var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; + var UID$3 = 0; + /* eslint-disable object-shorthand */ + var map = { + Float32Array: Float32Array, + Uint32Array: Uint32Array, + Int32Array: Int32Array, + Uint8Array: Uint8Array, + Uint16Array: Uint16Array, + }; + /* eslint-disable max-len */ + /** + * The Geometry represents a model. It consists of two components: + * - GeometryStyle - The structure of the model such as the attributes layout + * - GeometryData - the data of the model - this consists of buffers. + * This can include anything from positions, uvs, normals, colors etc. + * + * Geometry can be defined without passing in a style or data if required (thats how I prefer!) + * + * ```js + * let geometry = new PIXI.Geometry(); + * + * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); + * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2) + * geometry.addIndex([0,1,2,1,3,2]) + * ``` + * @memberof PIXI + */ + var Geometry = /** @class */ (function () { + /** + * @param buffers - An array of buffers. optional. + * @param attributes - Of the geometry, optional structure of the attributes layout + */ + function Geometry(buffers, attributes) { + if (buffers === void 0) { buffers = []; } + if (attributes === void 0) { attributes = {}; } + this.buffers = buffers; + this.indexBuffer = null; + this.attributes = attributes; + this.glVertexArrayObjects = {}; + this.id = UID$3++; + this.instanced = false; + this.instanceCount = 1; + this.disposeRunner = new Runner('disposeGeometry'); + this.refCount = 0; + } + /** + * + * Adds an attribute to the geometry + * Note: `stride` and `start` should be `undefined` if you dont know them, not 0! + * @param id - the name of the attribute (matching up to a shader) + * @param {PIXI.Buffer|number[]} buffer - the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it. + * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 + * @param normalized - should the data be normalized. + * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @param [start=0] - How far into the array to start reading values (used for interleaving data) + * @param instance - Instancing flag + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.addAttribute = function (id, buffer, size, normalized, type, stride, start, instance) { + if (size === void 0) { size = 0; } + if (normalized === void 0) { normalized = false; } + if (instance === void 0) { instance = false; } + if (!buffer) { + throw new Error('You must pass a buffer when creating an attribute'); + } + // check if this is a buffer! + if (!(buffer instanceof Buffer)) { + // its an array! + if (buffer instanceof Array) { + buffer = new Float32Array(buffer); + } + buffer = new Buffer(buffer); + } + var ids = id.split('|'); + if (ids.length > 1) { + for (var i = 0; i < ids.length; i++) { + this.addAttribute(ids[i], buffer, size, normalized, type); + } + return this; + } + var bufferIndex = this.buffers.indexOf(buffer); + if (bufferIndex === -1) { + this.buffers.push(buffer); + bufferIndex = this.buffers.length - 1; + } + this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); + // assuming that if there is instanced data then this will be drawn with instancing! + this.instanced = this.instanced || instance; + return this; + }; + /** + * Returns the requested attribute. + * @param id - The name of the attribute required + * @returns - The attribute requested. + */ + Geometry.prototype.getAttribute = function (id) { + return this.attributes[id]; + }; + /** + * Returns the requested buffer. + * @param id - The name of the buffer required. + * @returns - The buffer requested. + */ + Geometry.prototype.getBuffer = function (id) { + return this.buffers[this.getAttribute(id).buffer]; + }; + /** + * + * Adds an index buffer to the geometry + * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer. + * @param {PIXI.Buffer|number[]} [buffer] - The buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.addIndex = function (buffer) { + if (!(buffer instanceof Buffer)) { + // its an array! + if (buffer instanceof Array) { + buffer = new Uint16Array(buffer); + } + buffer = new Buffer(buffer); + } + buffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + this.indexBuffer = buffer; + if (this.buffers.indexOf(buffer) === -1) { + this.buffers.push(buffer); + } + return this; + }; + /** + * Returns the index buffer + * @returns - The index buffer. + */ + Geometry.prototype.getIndex = function () { + return this.indexBuffer; + }; + /** + * This function modifies the structure so that all current attributes become interleaved into a single buffer + * This can be useful if your model remains static as it offers a little performance boost + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.interleave = function () { + // a simple check to see if buffers are already interleaved.. + if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) + { return this; } + // assume already that no buffers are interleaved + var arrays = []; + var sizes = []; + var interleavedBuffer = new Buffer(); + var i; + for (i in this.attributes) { + var attribute = this.attributes[i]; + var buffer = this.buffers[attribute.buffer]; + arrays.push(buffer.data); + sizes.push((attribute.size * byteSizeMap$1[attribute.type]) / 4); + attribute.buffer = 0; + } + interleavedBuffer.data = interleaveTypedArrays(arrays, sizes); + for (i = 0; i < this.buffers.length; i++) { + if (this.buffers[i] !== this.indexBuffer) { + this.buffers[i].destroy(); + } + } + this.buffers = [interleavedBuffer]; + if (this.indexBuffer) { + this.buffers.push(this.indexBuffer); + } + return this; + }; + /** Get the size of the geometries, in vertices. */ + Geometry.prototype.getSize = function () { + for (var i in this.attributes) { + var attribute = this.attributes[i]; + var buffer = this.buffers[attribute.buffer]; + return buffer.data.length / ((attribute.stride / 4) || attribute.size); + } + return 0; + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Geometry.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys the geometry. */ + Geometry.prototype.destroy = function () { + this.dispose(); + this.buffers = null; + this.indexBuffer = null; + this.attributes = null; + }; + /** + * Returns a clone of the geometry. + * @returns - A new clone of this geometry. + */ + Geometry.prototype.clone = function () { + var geometry = new Geometry(); + for (var i = 0; i < this.buffers.length; i++) { + geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0)); + } + for (var i in this.attributes) { + var attrib = this.attributes[i]; + geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance); + } + if (this.indexBuffer) { + geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; + geometry.indexBuffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + } + return geometry; + }; + /** + * Merges an array of geometries into a new single one. + * + * Geometry attribute styles must match for this operation to work. + * @param geometries - array of geometries to merge + * @returns - Shiny new geometry! + */ + Geometry.merge = function (geometries) { + // todo add a geometry check! + // also a size check.. cant be too big!] + var geometryOut = new Geometry(); + var arrays = []; + var sizes = []; + var offsets = []; + var geometry; + // pass one.. get sizes.. + for (var i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (var j = 0; j < geometry.buffers.length; j++) { + sizes[j] = sizes[j] || 0; + sizes[j] += geometry.buffers[j].data.length; + offsets[j] = 0; + } + } + // build the correct size arrays.. + for (var i = 0; i < geometry.buffers.length; i++) { + // TODO types! + arrays[i] = new map[getBufferType(geometry.buffers[i].data)](sizes[i]); + geometryOut.buffers[i] = new Buffer(arrays[i]); + } + // pass to set data.. + for (var i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (var j = 0; j < geometry.buffers.length; j++) { + arrays[j].set(geometry.buffers[j].data, offsets[j]); + offsets[j] += geometry.buffers[j].data.length; + } + } + geometryOut.attributes = geometry.attributes; + if (geometry.indexBuffer) { + geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; + geometryOut.indexBuffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + var offset = 0; + var stride = 0; + var offset2 = 0; + var bufferIndexToCount = 0; + // get a buffer + for (var i = 0; i < geometry.buffers.length; i++) { + if (geometry.buffers[i] !== geometry.indexBuffer) { + bufferIndexToCount = i; + break; + } + } + // figure out the stride of one buffer.. + for (var i in geometry.attributes) { + var attribute = geometry.attributes[i]; + if ((attribute.buffer | 0) === bufferIndexToCount) { + stride += ((attribute.size * byteSizeMap$1[attribute.type]) / 4); + } + } + // time to off set all indexes.. + for (var i = 0; i < geometries.length; i++) { + var indexBufferData = geometries[i].indexBuffer.data; + for (var j = 0; j < indexBufferData.length; j++) { + geometryOut.indexBuffer.data[j + offset2] += offset; + } + offset += geometries[i].buffers[bufferIndexToCount].data.length / (stride); + offset2 += indexBufferData.length; + } + } + return geometryOut; + }; + return Geometry; + }()); + + /** + * Helper class to create a quad + * @memberof PIXI + */ + var Quad = /** @class */ (function (_super) { + __extends$i(Quad, _super); + function Quad() { + var _this = _super.call(this) || this; + _this.addAttribute('aVertexPosition', new Float32Array([ + 0, 0, + 1, 0, + 1, 1, + 0, 1 ])) + .addIndex([0, 1, 3, 2]); + return _this; + } + return Quad; + }(Geometry)); + + /** + * Helper class to create a quad with uvs like in v4 + * @memberof PIXI + */ + var QuadUv = /** @class */ (function (_super) { + __extends$i(QuadUv, _super); + function QuadUv() { + var _this = _super.call(this) || this; + _this.vertices = new Float32Array([ + -1, -1, + 1, -1, + 1, 1, + -1, 1 ]); + _this.uvs = new Float32Array([ + 0, 0, + 1, 0, + 1, 1, + 0, 1 ]); + _this.vertexBuffer = new Buffer(_this.vertices); + _this.uvBuffer = new Buffer(_this.uvs); + _this.addAttribute('aVertexPosition', _this.vertexBuffer) + .addAttribute('aTextureCoord', _this.uvBuffer) + .addIndex([0, 1, 2, 0, 2, 3]); + return _this; + } + /** + * Maps two Rectangle to the quad. + * @param targetTextureFrame - The first rectangle + * @param destinationFrame - The second rectangle + * @returns - Returns itself. + */ + QuadUv.prototype.map = function (targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + this.uvs[0] = x; + this.uvs[1] = y; + this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width); + this.uvs[3] = y; + this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width); + this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height); + this.uvs[6] = x; + this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height); + x = destinationFrame.x; + y = destinationFrame.y; + this.vertices[0] = x; + this.vertices[1] = y; + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + this.invalidate(); + return this; + }; + /** + * Legacy upload method, just marks buffers dirty. + * @returns - Returns itself. + */ + QuadUv.prototype.invalidate = function () { + this.vertexBuffer._updateID++; + this.uvBuffer._updateID++; + return this; + }; + return QuadUv; + }(Geometry)); + + var UID$2 = 0; + /** + * Uniform group holds uniform map and some ID's for work + * + * `UniformGroup` has two modes: + * + * 1: Normal mode + * Normal mode will upload the uniforms with individual function calls as required + * + * 2: Uniform buffer mode + * This mode will treat the uniforms as a uniform buffer. You can pass in either a buffer that you manually handle, or + * or a generic object that PixiJS will automatically map to a buffer for you. + * For maximum benefits, make Ubo UniformGroups static, and only update them each frame. + * + * Rules of UBOs: + * - UBOs only work with WebGL2, so make sure you have a fallback! + * - Only floats are supported (including vec[2,3,4], mat[2,3,4]) + * - Samplers cannot be used in ubo's (a GPU limitation) + * - You must ensure that the object you pass in exactly matches in the shader ubo structure. + * Otherwise, weirdness will ensue! + * - The name of the ubo object added to the group must match exactly the name of the ubo in the shader. + * + * ``` + * // ubo in shader: + * uniform myCoolData { // declaring a ubo.. + * mat4 uCoolMatrix; + * float uFloatyMcFloatFace + * + * + * // a new uniform buffer object.. + * const myCoolData = new UniformBufferGroup({ + * uCoolMatrix: new Matrix(), + * uFloatyMcFloatFace: 23, + * }} + * + * // build a shader... + * const shader = Shader.from(srcVert, srcFrag, { + * myCoolData // name matches the ubo name in the shader. will be processed accordingly. + * }) + * + * ``` + * @memberof PIXI + */ + var UniformGroup = /** @class */ (function () { + /** + * @param {object | Buffer} [uniforms] - Custom uniforms to use to augment the built-in ones. Or a pixi buffer. + * @param isStatic - Uniforms wont be changed after creation. + * @param isUbo - If true, will treat this uniform group as a uniform buffer object. + */ + function UniformGroup(uniforms, isStatic, isUbo) { + this.group = true; + // lets generate this when the shader ? + this.syncUniforms = {}; + this.dirtyId = 0; + this.id = UID$2++; + this.static = !!isStatic; + this.ubo = !!isUbo; + if (uniforms instanceof Buffer) { + this.buffer = uniforms; + this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER; + this.autoManage = false; + this.ubo = true; + } + else { + this.uniforms = uniforms; + if (this.ubo) { + this.buffer = new Buffer(new Float32Array(1)); + this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER; + this.autoManage = true; + } + } + } + UniformGroup.prototype.update = function () { + this.dirtyId++; + if (!this.autoManage && this.buffer) { + this.buffer.update(); + } + }; + UniformGroup.prototype.add = function (name, uniforms, _static) { + if (!this.ubo) { + this.uniforms[name] = new UniformGroup(uniforms, _static); + } + else { + // eslint-disable-next-line max-len + throw new Error('[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them'); + } + }; + UniformGroup.from = function (uniforms, _static, _ubo) { + return new UniformGroup(uniforms, _static, _ubo); + }; + /** + * A short hand function for creating a static UBO UniformGroup. + * @param uniforms - the ubo item + * @param _static - should this be updated each time it is used? defaults to true here! + */ + UniformGroup.uboFrom = function (uniforms, _static) { + return new UniformGroup(uniforms, _static !== null && _static !== void 0 ? _static : true, true); + }; + return UniformGroup; + }()); + + /** + * System plugin to the renderer to manage filter states. + * @ignore + */ + var FilterState = /** @class */ (function () { + function FilterState() { + this.renderTexture = null; + this.target = null; + this.legacy = false; + this.resolution = 1; + this.multisample = exports.MSAA_QUALITY.NONE; + // next three fields are created only for root + // re-assigned for everything else + this.sourceFrame = new Rectangle(); + this.destinationFrame = new Rectangle(); + this.bindingSourceFrame = new Rectangle(); + this.bindingDestinationFrame = new Rectangle(); + this.filters = []; + this.transform = null; + } + /** Clears the state */ + FilterState.prototype.clear = function () { + this.target = null; + this.filters = null; + this.renderTexture = null; + }; + return FilterState; + }()); + + var tempPoints = [new Point(), new Point(), new Point(), new Point()]; + var tempMatrix$2 = new Matrix(); + /** + * System plugin to the renderer to manage filters. + * + * ## Pipeline + * + * The FilterSystem executes the filtering pipeline by rendering the display-object into a texture, applying its + * [filters]{@link PIXI.Filter} in series, and the last filter outputs into the final render-target. + * + * The filter-frame is the rectangle in world space being filtered, and those contents are mapped into + * `(0, 0, filterFrame.width, filterFrame.height)` into the filter render-texture. The filter-frame is also called + * the source-frame, as it is used to bind the filter render-textures. The last filter outputs to the `filterFrame` + * in the final render-target. + * + * ## Usage + * + * {@link PIXI.Container#renderAdvanced} is an example of how to use the filter system. It is a 3 step process: + * + * **push**: Use {@link PIXI.FilterSystem#push} to push the set of filters to be applied on a filter-target. + * **render**: Render the contents to be filtered using the renderer. The filter-system will only capture the contents + * inside the bounds of the filter-target. NOTE: Using {@link PIXI.Renderer#render} is + * illegal during an existing render cycle, and it may reset the filter system. + * **pop**: Use {@link PIXI.FilterSystem#pop} to pop & execute the filters you initially pushed. It will apply them + * serially and output to the bounds of the filter-target. + * @memberof PIXI + */ + var FilterSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function FilterSystem(renderer) { + this.renderer = renderer; + this.defaultFilterStack = [{}]; + this.texturePool = new RenderTexturePool(); + this.texturePool.setScreenSize(renderer.view); + this.statePool = []; + this.quad = new Quad(); + this.quadUv = new QuadUv(); + this.tempRect = new Rectangle(); + this.activeState = {}; + this.globalUniforms = new UniformGroup({ + outputFrame: new Rectangle(), + inputSize: new Float32Array(4), + inputPixel: new Float32Array(4), + inputClamp: new Float32Array(4), + resolution: 1, + // legacy variables + filterArea: new Float32Array(4), + filterClamp: new Float32Array(4), + }, true); + this.forceClear = false; + this.useMaxPadding = false; + } + /** + * Pushes a set of filters to be applied later to the system. This will redirect further rendering into an + * input render-texture for the rest of the filtering pipeline. + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param filters - The filters to apply. + */ + FilterSystem.prototype.push = function (target, filters) { + var _a, _b; + var renderer = this.renderer; + var filterStack = this.defaultFilterStack; + var state = this.statePool.pop() || new FilterState(); + var renderTextureSystem = this.renderer.renderTexture; + var resolution = filters[0].resolution; + var multisample = filters[0].multisample; + var padding = filters[0].padding; + var autoFit = filters[0].autoFit; + // We don't know whether it's a legacy filter until it was bound for the first time, + // therefore we have to assume that it is if legacy is undefined. + var legacy = (_a = filters[0].legacy) !== null && _a !== void 0 ? _a : true; + for (var i = 1; i < filters.length; i++) { + var filter = filters[i]; + // let's use the lowest resolution + resolution = Math.min(resolution, filter.resolution); + // let's use the lowest number of samples + multisample = Math.min(multisample, filter.multisample); + // figure out the padding required for filters + padding = this.useMaxPadding + // old behavior: use largest amount of padding! + ? Math.max(padding, filter.padding) + // new behavior: sum the padding + : padding + filter.padding; + // only auto fit if all filters are autofit + autoFit = autoFit && filter.autoFit; + legacy = legacy || ((_b = filter.legacy) !== null && _b !== void 0 ? _b : true); + } + if (filterStack.length === 1) { + this.defaultFilterStack[0].renderTexture = renderTextureSystem.current; + } + filterStack.push(state); + state.resolution = resolution; + state.multisample = multisample; + state.legacy = legacy; + state.target = target; + state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); + state.sourceFrame.pad(padding); + var sourceFrameProjected = this.tempRect.copyFrom(renderTextureSystem.sourceFrame); + // Project source frame into world space (if projection is applied) + if (renderer.projection.transform) { + this.transformAABB(tempMatrix$2.copyFrom(renderer.projection.transform).invert(), sourceFrameProjected); + } + if (autoFit) { + state.sourceFrame.fit(sourceFrameProjected); + if (state.sourceFrame.width <= 0 || state.sourceFrame.height <= 0) { + state.sourceFrame.width = 0; + state.sourceFrame.height = 0; + } + } + else if (!state.sourceFrame.intersects(sourceFrameProjected)) { + state.sourceFrame.width = 0; + state.sourceFrame.height = 0; + } + // Round sourceFrame in screen space based on render-texture. + this.roundFrame(state.sourceFrame, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); + state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution, multisample); + state.filters = filters; + state.destinationFrame.width = state.renderTexture.width; + state.destinationFrame.height = state.renderTexture.height; + var destinationFrame = this.tempRect; + destinationFrame.x = 0; + destinationFrame.y = 0; + destinationFrame.width = state.sourceFrame.width; + destinationFrame.height = state.sourceFrame.height; + state.renderTexture.filterFrame = state.sourceFrame; + state.bindingSourceFrame.copyFrom(renderTextureSystem.sourceFrame); + state.bindingDestinationFrame.copyFrom(renderTextureSystem.destinationFrame); + state.transform = renderer.projection.transform; + renderer.projection.transform = null; + renderTextureSystem.bind(state.renderTexture, state.sourceFrame, destinationFrame); + renderer.framebuffer.clear(0, 0, 0, 0); + }; + /** Pops off the filter and applies it. */ + FilterSystem.prototype.pop = function () { + var filterStack = this.defaultFilterStack; + var state = filterStack.pop(); + var filters = state.filters; + this.activeState = state; + var globalUniforms = this.globalUniforms.uniforms; + globalUniforms.outputFrame = state.sourceFrame; + globalUniforms.resolution = state.resolution; + var inputSize = globalUniforms.inputSize; + var inputPixel = globalUniforms.inputPixel; + var inputClamp = globalUniforms.inputClamp; + inputSize[0] = state.destinationFrame.width; + inputSize[1] = state.destinationFrame.height; + inputSize[2] = 1.0 / inputSize[0]; + inputSize[3] = 1.0 / inputSize[1]; + inputPixel[0] = Math.round(inputSize[0] * state.resolution); + inputPixel[1] = Math.round(inputSize[1] * state.resolution); + inputPixel[2] = 1.0 / inputPixel[0]; + inputPixel[3] = 1.0 / inputPixel[1]; + inputClamp[0] = 0.5 * inputPixel[2]; + inputClamp[1] = 0.5 * inputPixel[3]; + inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]); + inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]); + // only update the rect if its legacy.. + if (state.legacy) { + var filterArea = globalUniforms.filterArea; + filterArea[0] = state.destinationFrame.width; + filterArea[1] = state.destinationFrame.height; + filterArea[2] = state.sourceFrame.x; + filterArea[3] = state.sourceFrame.y; + globalUniforms.filterClamp = globalUniforms.inputClamp; + } + this.globalUniforms.update(); + var lastState = filterStack[filterStack.length - 1]; + this.renderer.framebuffer.blit(); + if (filters.length === 1) { + filters[0].apply(this, state.renderTexture, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); + this.returnFilterTexture(state.renderTexture); + } + else { + var flip = state.renderTexture; + var flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + var i = 0; + for (i = 0; i < filters.length - 1; ++i) { + if (i === 1 && state.multisample > 1) { + flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + } + filters[i].apply(this, flip, flop, exports.CLEAR_MODES.CLEAR, state); + var t = flip; + flip = flop; + flop = t; + } + filters[i].apply(this, flip, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); + if (i > 1 && state.multisample > 1) { + this.returnFilterTexture(state.renderTexture); + } + this.returnFilterTexture(flip); + this.returnFilterTexture(flop); + } + // lastState.renderTexture is blitted when lastState is popped + state.clear(); + this.statePool.push(state); + }; + /** + * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds. + * @param filterTexture - renderTexture to bind, should belong to filter pool or filter stack + * @param clearMode - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES} + */ + FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) { + if (clearMode === void 0) { clearMode = exports.CLEAR_MODES.CLEAR; } + var _a = this.renderer, renderTextureSystem = _a.renderTexture, stateSystem = _a.state; + if (filterTexture === this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { + // Restore projection transform if rendering into the output render-target. + this.renderer.projection.transform = this.activeState.transform; + } + else { + // Prevent projection within filtering pipeline. + this.renderer.projection.transform = null; + } + if (filterTexture && filterTexture.filterFrame) { + var destinationFrame = this.tempRect; + destinationFrame.x = 0; + destinationFrame.y = 0; + destinationFrame.width = filterTexture.filterFrame.width; + destinationFrame.height = filterTexture.filterFrame.height; + renderTextureSystem.bind(filterTexture, filterTexture.filterFrame, destinationFrame); + } + else if (filterTexture !== this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { + renderTextureSystem.bind(filterTexture); + } + else { + // Restore binding for output render-target. + this.renderer.renderTexture.bind(filterTexture, this.activeState.bindingSourceFrame, this.activeState.bindingDestinationFrame); + } + // Clear the texture in BLIT mode if blending is disabled or the forceClear flag is set. The blending + // is stored in the 0th bit of the state. + var autoClear = (stateSystem.stateId & 1) || this.forceClear; + if (clearMode === exports.CLEAR_MODES.CLEAR + || (clearMode === exports.CLEAR_MODES.BLIT && autoClear)) { + // Use framebuffer.clear because we want to clear the whole filter texture, not just the filtering + // area over which the shaders are run. This is because filters may sampling outside of it (e.g. blur) + // instead of clamping their arithmetic. + this.renderer.framebuffer.clear(0, 0, 0, 0); + } + }; + /** + * Draws a filter using the default rendering process. + * + * This should be called only by {@link Filter#apply}. + * @param filter - The filter to draw. + * @param input - The input render target. + * @param output - The target to output to. + * @param clearMode - Should the output be cleared before rendering to it + */ + FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) { + var renderer = this.renderer; + // Set state before binding, so bindAndClear gets the blend mode. + renderer.state.set(filter.state); + this.bindAndClear(output, clearMode); + // set the uniforms.. + filter.uniforms.uSampler = input; + filter.uniforms.filterGlobals = this.globalUniforms; + // TODO make it so that the order of this does not matter.. + // because it does at the moment cos of global uniforms. + // they need to get resynced + renderer.shader.bind(filter); + // check to see if the filter is a legacy one.. + filter.legacy = !!filter.program.attributeData.aTextureCoord; + if (filter.legacy) { + this.quadUv.map(input._frame, input.filterFrame); + renderer.geometry.bind(this.quadUv); + renderer.geometry.draw(exports.DRAW_MODES.TRIANGLES); + } + else { + renderer.geometry.bind(this.quad); + renderer.geometry.draw(exports.DRAW_MODES.TRIANGLE_STRIP); + } + }; + /** + * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_. + * + * Use `outputMatrix * vTextureCoord` in the shader. + * @param outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @returns The mapped matrix. + */ + FilterSystem.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) { + var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y); + var worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX); + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + return mappedMatrix; + }; + /** Destroys this Filter System. */ + FilterSystem.prototype.destroy = function () { + this.renderer = null; + // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem + this.texturePool.clear(false); + }; + /** + * Gets a Power-of-Two render texture or fullScreen texture + * @param minWidth - The minimum width of the render texture in real pixels. + * @param minHeight - The minimum height of the render texture in real pixels. + * @param resolution - The resolution of the render texture. + * @param multisample - Number of samples of the render texture. + * @returns - The new render texture. + */ + FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution, multisample) { + if (resolution === void 0) { resolution = 1; } + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution, multisample); + }; + /** + * Gets extra render texture to use inside current filter + * To be compliant with older filters, you can use params in any order + * @param input - renderTexture from which size and resolution will be copied + * @param resolution - override resolution of the renderTexture + * @param multisample - number of samples of the renderTexture + */ + FilterSystem.prototype.getFilterTexture = function (input, resolution, multisample) { + if (typeof input === 'number') { + var swap = input; + input = resolution; + resolution = swap; + } + input = input || this.activeState.renderTexture; + var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; + }; + /** + * Frees a render texture back into the pool. + * @param renderTexture - The renderTarget to free + */ + FilterSystem.prototype.returnFilterTexture = function (renderTexture) { + this.texturePool.returnTexture(renderTexture); + }; + /** Empties the texture pool. */ + FilterSystem.prototype.emptyPool = function () { + this.texturePool.clear(true); + }; + /** Calls `texturePool.resize()`, affects fullScreen renderTextures. */ + FilterSystem.prototype.resize = function () { + this.texturePool.setScreenSize(this.renderer.view); + }; + /** + * @param matrix - first param + * @param rect - second param + */ + FilterSystem.prototype.transformAABB = function (matrix, rect) { + var lt = tempPoints[0]; + var lb = tempPoints[1]; + var rt = tempPoints[2]; + var rb = tempPoints[3]; + lt.set(rect.left, rect.top); + lb.set(rect.left, rect.bottom); + rt.set(rect.right, rect.top); + rb.set(rect.right, rect.bottom); + matrix.apply(lt, lt); + matrix.apply(lb, lb); + matrix.apply(rt, rt); + matrix.apply(rb, rb); + var x0 = Math.min(lt.x, lb.x, rt.x, rb.x); + var y0 = Math.min(lt.y, lb.y, rt.y, rb.y); + var x1 = Math.max(lt.x, lb.x, rt.x, rb.x); + var y1 = Math.max(lt.y, lb.y, rt.y, rb.y); + rect.x = x0; + rect.y = y0; + rect.width = x1 - x0; + rect.height = y1 - y0; + }; + FilterSystem.prototype.roundFrame = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { + if (frame.width <= 0 || frame.height <= 0 || bindingSourceFrame.width <= 0 || bindingSourceFrame.height <= 0) { + return; + } + if (transform) { + var a = transform.a, b = transform.b, c = transform.c, d = transform.d; + // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation + // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0). + if ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) + && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)) { + return; + } + } + transform = transform ? tempMatrix$2.copyFrom(transform) : tempMatrix$2.identity(); + // Get forward transform from world space to screen space + transform + .translate(-bindingSourceFrame.x, -bindingSourceFrame.y) + .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height) + .translate(bindingDestinationFrame.x, bindingDestinationFrame.y); + // Convert frame to screen space + this.transformAABB(transform, frame); + // Round frame in screen space + frame.ceil(resolution); + // Project back into world space. + this.transformAABB(transform.invert(), frame); + }; + return FilterSystem; + }()); + + /** + * Base for a common object renderer that can be used as a + * system renderer plugin. + * @memberof PIXI + */ + var ObjectRenderer = /** @class */ (function () { + /** + * @param renderer - The renderer this manager works for. + */ + function ObjectRenderer(renderer) { + this.renderer = renderer; + } + /** Stub method that should be used to empty the current batch by rendering objects now. */ + ObjectRenderer.prototype.flush = function () { + // flush! + }; + /** Generic destruction method that frees all resources. This should be called by subclasses. */ + ObjectRenderer.prototype.destroy = function () { + this.renderer = null; + }; + /** + * Stub method that initializes any state required before + * rendering starts. It is different from the `prerender` + * signal, which occurs every frame, in that it is called + * whenever an object requests _this_ renderer specifically. + */ + ObjectRenderer.prototype.start = function () { + // set the shader.. + }; + /** Stops the renderer. It should free up any state and become dormant. */ + ObjectRenderer.prototype.stop = function () { + this.flush(); + }; + /** + * Keeps the object to render. It doesn't have to be + * rendered immediately. + * @param {PIXI.DisplayObject} _object - The object to render. + */ + ObjectRenderer.prototype.render = function (_object) { + // render the object + }; + return ObjectRenderer; + }()); + + /** + * System plugin to the renderer to manage batching. + * @memberof PIXI + */ + var BatchSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function BatchSystem(renderer) { + this.renderer = renderer; + this.emptyRenderer = new ObjectRenderer(renderer); + this.currentRenderer = this.emptyRenderer; + } + /** + * Changes the current renderer to the one given in parameter + * @param objectRenderer - The object renderer to use. + */ + BatchSystem.prototype.setObjectRenderer = function (objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + */ + BatchSystem.prototype.flush = function () { + this.setObjectRenderer(this.emptyRenderer); + }; + /** Reset the system to an empty renderer */ + BatchSystem.prototype.reset = function () { + this.setObjectRenderer(this.emptyRenderer); + }; + /** + * Handy function for batch renderers: copies bound textures in first maxTextures locations to array + * sets actual _batchLocation for them + * @param arr - arr copy destination + * @param maxTextures - number of copied elements + */ + BatchSystem.prototype.copyBoundTextures = function (arr, maxTextures) { + var boundTextures = this.renderer.texture.boundTextures; + for (var i = maxTextures - 1; i >= 0; --i) { + arr[i] = boundTextures[i] || null; + if (arr[i]) { + arr[i]._batchLocation = i; + } + } + }; + /** + * Assigns batch locations to textures in array based on boundTextures state. + * All textures in texArray should have `_batchEnabled = _batchId`, + * and their count should be less than `maxTextures`. + * @param texArray - textures to bound + * @param boundTextures - current state of bound textures + * @param batchId - marker for _batchEnabled param of textures in texArray + * @param maxTextures - number of texture locations to manipulate + */ + BatchSystem.prototype.boundArray = function (texArray, boundTextures, batchId, maxTextures) { + var elements = texArray.elements, ids = texArray.ids, count = texArray.count; + var j = 0; + for (var i = 0; i < count; i++) { + var tex = elements[i]; + var loc = tex._batchLocation; + if (loc >= 0 && loc < maxTextures + && boundTextures[loc] === tex) { + ids[i] = loc; + continue; + } + while (j < maxTextures) { + var bound = boundTextures[j]; + if (bound && bound._batchEnabled === batchId + && bound._batchLocation === j) { + j++; + continue; + } + ids[i] = j; + tex._batchLocation = j; + boundTextures[j] = tex; + break; + } + } + }; + /** + * @ignore + */ + BatchSystem.prototype.destroy = function () { + this.renderer = null; + }; + return BatchSystem; + }()); + + var CONTEXT_UID_COUNTER = 0; + /** + * System plugin to the renderer to manage the context. + * @memberof PIXI + */ + var ContextSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ContextSystem(renderer) { + this.renderer = renderer; + this.webGLVersion = 1; + this.extensions = {}; + this.supports = { + uint32Indices: false, + }; + // Bind functions + this.handleContextLost = this.handleContextLost.bind(this); + this.handleContextRestored = this.handleContextRestored.bind(this); + renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); + renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); + } + Object.defineProperty(ContextSystem.prototype, "isLost", { + /** + * `true` if the context is lost + * @readonly + */ + get: function () { + return (!this.gl || this.gl.isContextLost()); + }, + enumerable: false, + configurable: true + }); + /** + * Handles the context change event. + * @param {WebGLRenderingContext} gl - New WebGL context. + */ + ContextSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + }; + /** + * Initializes the context. + * @protected + * @param {WebGLRenderingContext} gl - WebGL context + */ + ContextSystem.prototype.initFromContext = function (gl) { + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + this.renderer.runners.contextChange.emit(gl); + }; + /** + * Initialize from context options + * @protected + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext + * @param {object} options - context attributes + */ + ContextSystem.prototype.initFromOptions = function (options) { + var gl = this.createContext(this.renderer.view, options); + this.initFromContext(gl); + }; + /** + * Helper class to create a WebGL Context + * @param canvas - the canvas element that we will get the context from + * @param options - An options object that gets passed in to the canvas element containing the + * context attributes + * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext + * @returns {WebGLRenderingContext} the WebGL context + */ + ContextSystem.prototype.createContext = function (canvas, options) { + var gl; + if (settings$1.PREFER_ENV >= exports.ENV.WEBGL2) { + gl = canvas.getContext('webgl2', options); + } + if (gl) { + this.webGLVersion = 2; + } + else { + this.webGLVersion = 1; + gl = canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options); + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support WebGL. Try using the canvas renderer'); + } + } + this.gl = gl; + this.getExtensions(); + return this.gl; + }; + /** Auto-populate the {@link PIXI.ContextSystem.extensions extensions}. */ + ContextSystem.prototype.getExtensions = function () { + // time to set up default extensions that Pixi uses. + var gl = this.gl; + var common = { + anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), + floatTextureLinear: gl.getExtension('OES_texture_float_linear'), + s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'), + s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'), + etc: gl.getExtension('WEBGL_compressed_texture_etc'), + etc1: gl.getExtension('WEBGL_compressed_texture_etc1'), + pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc') + || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'), + atc: gl.getExtension('WEBGL_compressed_texture_atc'), + astc: gl.getExtension('WEBGL_compressed_texture_astc') + }; + if (this.webGLVersion === 1) { + Object.assign(this.extensions, common, { + drawBuffers: gl.getExtension('WEBGL_draw_buffers'), + depthTexture: gl.getExtension('WEBGL_depth_texture'), + loseContext: gl.getExtension('WEBGL_lose_context'), + vertexArrayObject: gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'), + uint32ElementIndex: gl.getExtension('OES_element_index_uint'), + // Floats and half-floats + floatTexture: gl.getExtension('OES_texture_float'), + floatTextureLinear: gl.getExtension('OES_texture_float_linear'), + textureHalfFloat: gl.getExtension('OES_texture_half_float'), + textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'), + }); + } + else if (this.webGLVersion === 2) { + Object.assign(this.extensions, common, { + // Floats and half-floats + colorBufferFloat: gl.getExtension('EXT_color_buffer_float') + }); + } + }; + /** + * Handles a lost webgl context + * @param {WebGLContextEvent} event - The context lost event. + */ + ContextSystem.prototype.handleContextLost = function (event) { + event.preventDefault(); + }; + /** Handles a restored webgl context. */ + ContextSystem.prototype.handleContextRestored = function () { + this.renderer.runners.contextChange.emit(this.gl); + }; + ContextSystem.prototype.destroy = function () { + var view = this.renderer.view; + this.renderer = null; + // remove listeners + view.removeEventListener('webglcontextlost', this.handleContextLost); + view.removeEventListener('webglcontextrestored', this.handleContextRestored); + this.gl.useProgram(null); + if (this.extensions.loseContext) { + this.extensions.loseContext.loseContext(); + } + }; + /** Handle the post-render runner event. */ + ContextSystem.prototype.postrender = function () { + if (this.renderer.renderingToScreen) { + this.gl.flush(); + } + }; + /** + * Validate context. + * @param {WebGLRenderingContext} gl - Render context. + */ + ContextSystem.prototype.validateContext = function (gl) { + var attributes = gl.getContextAttributes(); + var isWebGl2 = 'WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext; + if (isWebGl2) { + this.webGLVersion = 2; + } + // this is going to be fairly simple for now.. but at least we have room to grow! + if (attributes && !attributes.stencil) { + /* eslint-disable max-len, no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable max-len, no-console */ + } + var hasuint32 = isWebGl2 || !!gl.getExtension('OES_element_index_uint'); + this.supports.uint32Indices = hasuint32; + if (!hasuint32) { + /* eslint-disable max-len, no-console */ + console.warn('Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly'); + /* eslint-enable max-len, no-console */ + } + }; + return ContextSystem; + }()); + + /** + * Internal framebuffer for WebGL context. + * @memberof PIXI + */ + var GLFramebuffer = /** @class */ (function () { + function GLFramebuffer(framebuffer) { + this.framebuffer = framebuffer; + this.stencil = null; + this.dirtyId = -1; + this.dirtyFormat = -1; + this.dirtySize = -1; + this.multisample = exports.MSAA_QUALITY.NONE; + this.msaaBuffer = null; + this.blitFramebuffer = null; + this.mipLevel = 0; + } + return GLFramebuffer; + }()); + + var tempRectangle = new Rectangle(); + /** + * System plugin to the renderer to manage framebuffers. + * @memberof PIXI + */ + var FramebufferSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function FramebufferSystem(renderer) { + this.renderer = renderer; + this.managedFramebuffers = []; + this.unknownFramebuffer = new Framebuffer(10, 10); + this.msaaSamples = null; + } + /** Sets up the renderer context and necessary buffers. */ + FramebufferSystem.prototype.contextChange = function () { + var gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.current = this.unknownFramebuffer; + this.viewport = new Rectangle(); + this.hasMRT = true; + this.writeDepthTexture = true; + this.disposeAll(true); + // webgl2 + if (this.renderer.context.webGLVersion === 1) { + // webgl 1! + var nativeDrawBuffersExtension_1 = this.renderer.context.extensions.drawBuffers; + var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; + if (settings$1.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + nativeDrawBuffersExtension_1 = null; + nativeDepthTextureExtension = null; + } + if (nativeDrawBuffersExtension_1) { + gl.drawBuffers = function (activeTextures) { + return nativeDrawBuffersExtension_1.drawBuffersWEBGL(activeTextures); + }; + } + else { + this.hasMRT = false; + gl.drawBuffers = function () { + // empty + }; + } + if (!nativeDepthTextureExtension) { + this.writeDepthTexture = false; + } + } + else { + // WebGL2 + // cache possible MSAA samples + this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES); + } + }; + /** + * Bind a framebuffer. + * @param framebuffer + * @param frame - frame, default is framebuffer size + * @param mipLevel - optional mip level to set on the framebuffer - defaults to 0 + */ + FramebufferSystem.prototype.bind = function (framebuffer, frame, mipLevel) { + if (mipLevel === void 0) { mipLevel = 0; } + var gl = this.gl; + if (framebuffer) { + // TODO caching layer! + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + if (this.current !== framebuffer) { + this.current = framebuffer; + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); + } + // make sure all textures are unbound.. + if (fbo.mipLevel !== mipLevel) { + framebuffer.dirtyId++; + framebuffer.dirtyFormat++; + fbo.mipLevel = mipLevel; + } + // now check for updates... + if (fbo.dirtyId !== framebuffer.dirtyId) { + fbo.dirtyId = framebuffer.dirtyId; + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { + fbo.dirtyFormat = framebuffer.dirtyFormat; + fbo.dirtySize = framebuffer.dirtySize; + this.updateFramebuffer(framebuffer, mipLevel); + } + else if (fbo.dirtySize !== framebuffer.dirtySize) { + fbo.dirtySize = framebuffer.dirtySize; + this.resizeFramebuffer(framebuffer); + } + } + for (var i = 0; i < framebuffer.colorTextures.length; i++) { + var tex = framebuffer.colorTextures[i]; + this.renderer.texture.unbind(tex.parentTextureArray || tex); + } + if (framebuffer.depthTexture) { + this.renderer.texture.unbind(framebuffer.depthTexture); + } + if (frame) { + var mipWidth = (frame.width >> mipLevel); + var mipHeight = (frame.height >> mipLevel); + var scale = mipWidth / frame.width; + this.setViewport(frame.x * scale, frame.y * scale, mipWidth, mipHeight); + } + else { + var mipWidth = (framebuffer.width >> mipLevel); + var mipHeight = (framebuffer.height >> mipLevel); + this.setViewport(0, 0, mipWidth, mipHeight); + } + } + else { + if (this.current) { + this.current = null; + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + if (frame) { + this.setViewport(frame.x, frame.y, frame.width, frame.height); + } + else { + this.setViewport(0, 0, this.renderer.width, this.renderer.height); + } + } + }; + /** + * Set the WebGLRenderingContext's viewport. + * @param x - X position of viewport + * @param y - Y position of viewport + * @param width - Width of viewport + * @param height - Height of viewport + */ + FramebufferSystem.prototype.setViewport = function (x, y, width, height) { + var v = this.viewport; + x = Math.round(x); + y = Math.round(y); + width = Math.round(width); + height = Math.round(height); + if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) { + v.x = x; + v.y = y; + v.width = width; + v.height = height; + this.gl.viewport(x, y, width, height); + } + }; + Object.defineProperty(FramebufferSystem.prototype, "size", { + /** + * Get the size of the current width and height. Returns object with `width` and `height` values. + * @readonly + */ + get: function () { + if (this.current) { + // TODO store temp + return { x: 0, y: 0, width: this.current.width, height: this.current.height }; + } + return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; + }, + enumerable: false, + configurable: true + }); + /** + * Clear the color of the context + * @param r - Red value from 0 to 1 + * @param g - Green value from 0 to 1 + * @param b - Blue value from 0 to 1 + * @param a - Alpha value from 0 to 1 + * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks + * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. + */ + FramebufferSystem.prototype.clear = function (r, g, b, a, mask) { + if (mask === void 0) { mask = exports.BUFFER_BITS.COLOR | exports.BUFFER_BITS.DEPTH; } + var gl = this.gl; + // TODO clear color can be set only one right? + gl.clearColor(r, g, b, a); + gl.clear(mask); + }; + /** + * Initialize framebuffer for this context + * @protected + * @param framebuffer + * @returns - created GLFramebuffer + */ + FramebufferSystem.prototype.initFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = new GLFramebuffer(gl.createFramebuffer()); + fbo.multisample = this.detectSamples(framebuffer.multisample); + framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; + this.managedFramebuffers.push(framebuffer); + framebuffer.disposeRunner.add(this); + return fbo; + }; + /** + * Resize the framebuffer + * @param framebuffer + * @protected + */ + FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (fbo.msaaBuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); + } + if (fbo.stencil) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + } + } + var colorTextures = framebuffer.colorTextures; + var count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); + } + for (var i = 0; i < count; i++) { + var texture = colorTextures[i]; + var parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + } + if (framebuffer.depthTexture && this.writeDepthTexture) { + this.renderer.texture.bind(framebuffer.depthTexture, 0); + } + }; + /** + * Update the framebuffer + * @param framebuffer + * @param mipLevel + * @protected + */ + FramebufferSystem.prototype.updateFramebuffer = function (framebuffer, mipLevel) { + var gl = this.gl; + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + // bind the color texture + var colorTextures = framebuffer.colorTextures; + var count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); + } + if (fbo.multisample > 1 && this.canMultisampleFramebuffer(framebuffer)) { + fbo.msaaBuffer = fbo.msaaBuffer || gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer); + } + else if (fbo.msaaBuffer) { + gl.deleteRenderbuffer(fbo.msaaBuffer); + fbo.msaaBuffer = null; + if (fbo.blitFramebuffer) { + fbo.blitFramebuffer.dispose(); + fbo.blitFramebuffer = null; + } + } + var activeTextures = []; + for (var i = 0; i < count; i++) { + var texture = colorTextures[i]; + var parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + if (i === 0 && fbo.msaaBuffer) { + continue; + } + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); + activeTextures.push(gl.COLOR_ATTACHMENT0 + i); + } + if (activeTextures.length > 1) { + gl.drawBuffers(activeTextures); + } + if (framebuffer.depthTexture) { + var writeDepthTexture = this.writeDepthTexture; + if (writeDepthTexture) { + var depthTexture = framebuffer.depthTexture; + this.renderer.texture.bind(depthTexture, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); + } + } + if ((framebuffer.stencil || framebuffer.depth) && !(framebuffer.depthTexture && this.writeDepthTexture)) { + fbo.stencil = fbo.stencil || gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + } + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); + } + else if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + fbo.stencil = null; + } + }; + /** + * Returns true if the frame buffer can be multisampled. + * @param framebuffer + */ + FramebufferSystem.prototype.canMultisampleFramebuffer = function (framebuffer) { + return this.renderer.context.webGLVersion !== 1 + && framebuffer.colorTextures.length <= 1 && !framebuffer.depthTexture; + }; + /** + * Detects number of samples that is not more than a param but as close to it as possible + * @param samples - number of samples + * @returns - recommended number of samples + */ + FramebufferSystem.prototype.detectSamples = function (samples) { + var msaaSamples = this.msaaSamples; + var res = exports.MSAA_QUALITY.NONE; + if (samples <= 1 || msaaSamples === null) { + return res; + } + for (var i = 0; i < msaaSamples.length; i++) { + if (msaaSamples[i] <= samples) { + res = msaaSamples[i]; + break; + } + } + if (res === 1) { + res = exports.MSAA_QUALITY.NONE; + } + return res; + }; + /** + * Only works with WebGL2 + * + * blits framebuffer to another of the same or bigger size + * after that target framebuffer is bound + * + * Fails with WebGL warning if blits multisample framebuffer to different size + * @param framebuffer - by default it blits "into itself", from renderBuffer to texture. + * @param sourcePixels - source rectangle in pixels + * @param destPixels - dest rectangle in pixels, assumed to be the same as sourcePixels + */ + FramebufferSystem.prototype.blit = function (framebuffer, sourcePixels, destPixels) { + var _a = this, current = _a.current, renderer = _a.renderer, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + if (renderer.context.webGLVersion !== 2) { + return; + } + if (!current) { + return; + } + var fbo = current.glFramebuffers[CONTEXT_UID]; + if (!fbo) { + return; + } + if (!framebuffer) { + if (!fbo.msaaBuffer) { + return; + } + var colorTexture = current.colorTextures[0]; + if (!colorTexture) { + return; + } + if (!fbo.blitFramebuffer) { + fbo.blitFramebuffer = new Framebuffer(current.width, current.height); + fbo.blitFramebuffer.addColorTexture(0, colorTexture); + } + framebuffer = fbo.blitFramebuffer; + if (framebuffer.colorTextures[0] !== colorTexture) { + framebuffer.colorTextures[0] = colorTexture; + framebuffer.dirtyId++; + framebuffer.dirtyFormat++; + } + if (framebuffer.width !== current.width || framebuffer.height !== current.height) { + framebuffer.width = current.width; + framebuffer.height = current.height; + framebuffer.dirtyId++; + framebuffer.dirtySize++; + } + } + if (!sourcePixels) { + sourcePixels = tempRectangle; + sourcePixels.width = current.width; + sourcePixels.height = current.height; + } + if (!destPixels) { + destPixels = sourcePixels; + } + var sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height; + this.bind(framebuffer); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer); + gl.blitFramebuffer(sourcePixels.left, sourcePixels.top, sourcePixels.right, sourcePixels.bottom, destPixels.left, destPixels.top, destPixels.right, destPixels.bottom, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR); + }; + /** + * Disposes framebuffer. + * @param framebuffer - framebuffer that has to be disposed of + * @param contextLost - If context was lost, we suppress all delete function calls + */ + FramebufferSystem.prototype.disposeFramebuffer = function (framebuffer, contextLost) { + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + var gl = this.gl; + if (!fbo) { + return; + } + delete framebuffer.glFramebuffers[this.CONTEXT_UID]; + var index = this.managedFramebuffers.indexOf(framebuffer); + if (index >= 0) { + this.managedFramebuffers.splice(index, 1); + } + framebuffer.disposeRunner.remove(this); + if (!contextLost) { + gl.deleteFramebuffer(fbo.framebuffer); + if (fbo.msaaBuffer) { + gl.deleteRenderbuffer(fbo.msaaBuffer); + } + if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + } + } + if (fbo.blitFramebuffer) { + fbo.blitFramebuffer.dispose(); + } + }; + /** + * Disposes all framebuffers, but not textures bound to them. + * @param [contextLost=false] - If context was lost, we suppress all delete function calls + */ + FramebufferSystem.prototype.disposeAll = function (contextLost) { + var list = this.managedFramebuffers; + this.managedFramebuffers = []; + for (var i = 0; i < list.length; i++) { + this.disposeFramebuffer(list[i], contextLost); + } + }; + /** + * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. + * Used by MaskSystem, when its time to use stencil mask for Graphics element. + * + * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. + * @private + */ + FramebufferSystem.prototype.forceStencil = function () { + var framebuffer = this.current; + if (!framebuffer) { + return; + } + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (!fbo || fbo.stencil) { + return; + } + framebuffer.stencil = true; + var w = framebuffer.width; + var h = framebuffer.height; + var gl = this.gl; + var stencil = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, w, h); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); + } + fbo.stencil = stencil; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); + }; + /** Resets framebuffer stored state, binds screen framebuffer. Should be called before renderTexture reset(). */ + FramebufferSystem.prototype.reset = function () { + this.current = this.unknownFramebuffer; + this.viewport = new Rectangle(); + }; + FramebufferSystem.prototype.destroy = function () { + this.renderer = null; + }; + return FramebufferSystem; + }()); + + var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; + /** + * System plugin to the renderer to manage geometry. + * @memberof PIXI + */ + var GeometrySystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function GeometrySystem(renderer) { + this.renderer = renderer; + this._activeGeometry = null; + this._activeVao = null; + this.hasVao = true; + this.hasInstance = true; + this.canUseUInt32ElementIndex = false; + this.managedGeometries = {}; + } + /** Sets up the renderer context and necessary buffers. */ + GeometrySystem.prototype.contextChange = function () { + this.disposeAll(true); + var gl = this.gl = this.renderer.gl; + var context = this.renderer.context; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + // webgl2 + if (context.webGLVersion !== 2) { + // webgl 1! + var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject; + if (settings$1.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + nativeVaoExtension_1 = null; + } + if (nativeVaoExtension_1) { + gl.createVertexArray = function () { + return nativeVaoExtension_1.createVertexArrayOES(); + }; + gl.bindVertexArray = function (vao) { + return nativeVaoExtension_1.bindVertexArrayOES(vao); + }; + gl.deleteVertexArray = function (vao) { + return nativeVaoExtension_1.deleteVertexArrayOES(vao); + }; + } + else { + this.hasVao = false; + gl.createVertexArray = function () { + return null; + }; + gl.bindVertexArray = function () { + return null; + }; + gl.deleteVertexArray = function () { + return null; + }; + } + } + if (context.webGLVersion !== 2) { + var instanceExt_1 = gl.getExtension('ANGLE_instanced_arrays'); + if (instanceExt_1) { + gl.vertexAttribDivisor = function (a, b) { + return instanceExt_1.vertexAttribDivisorANGLE(a, b); + }; + gl.drawElementsInstanced = function (a, b, c, d, e) { + return instanceExt_1.drawElementsInstancedANGLE(a, b, c, d, e); + }; + gl.drawArraysInstanced = function (a, b, c, d) { + return instanceExt_1.drawArraysInstancedANGLE(a, b, c, d); + }; + } + else { + this.hasInstance = false; + } + } + this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; + }; + /** + * Binds geometry so that is can be drawn. Creating a Vao if required + * @param geometry - Instance of geometry to bind. + * @param shader - Instance of shader to use vao for. + */ + GeometrySystem.prototype.bind = function (geometry, shader) { + shader = shader || this.renderer.shader.shader; + var gl = this.gl; + // not sure the best way to address this.. + // currently different shaders require different VAOs for the same geometry + // Still mulling over the best way to solve this one.. + // will likely need to modify the shader attribute locations at run time! + var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var incRefCount = false; + if (!vaos) { + this.managedGeometries[geometry.id] = geometry; + geometry.disposeRunner.add(this); + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; + incRefCount = true; + } + var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader, incRefCount); + this._activeGeometry = geometry; + if (this._activeVao !== vao) { + this._activeVao = vao; + if (this.hasVao) { + gl.bindVertexArray(vao); + } + else { + this.activateVao(geometry, shader.program); + } + } + // TODO - optimise later! + // don't need to loop through if nothing changed! + // maybe look to add an 'autoupdate' to geometry? + this.updateBuffers(); + }; + /** Reset and unbind any active VAO and geometry. */ + GeometrySystem.prototype.reset = function () { + this.unbind(); + }; + /** Update buffers of the currently bound geometry. */ + GeometrySystem.prototype.updateBuffers = function () { + var geometry = this._activeGeometry; + var bufferSystem = this.renderer.buffer; + for (var i = 0; i < geometry.buffers.length; i++) { + var buffer = geometry.buffers[i]; + bufferSystem.update(buffer); + } + }; + /** + * Check compatibility between a geometry and a program + * @param geometry - Geometry instance. + * @param program - Program instance. + */ + GeometrySystem.prototype.checkCompatibility = function (geometry, program) { + // geometry must have at least all the attributes that the shader requires. + var geometryAttributes = geometry.attributes; + var shaderAttributes = program.attributeData; + for (var j in shaderAttributes) { + if (!geometryAttributes[j]) { + throw new Error("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute"); + } + } + }; + /** + * Takes a geometry and program and generates a unique signature for them. + * @param geometry - To get signature from. + * @param program - To test geometry against. + * @returns - Unique signature of the geometry and program + */ + GeometrySystem.prototype.getSignature = function (geometry, program) { + var attribs = geometry.attributes; + var shaderAttributes = program.attributeData; + var strings = ['g', geometry.id]; + for (var i in attribs) { + if (shaderAttributes[i]) { + strings.push(i, shaderAttributes[i].location); + } + } + return strings.join('-'); + }; + /** + * Creates or gets Vao with the same structure as the geometry and stores it on the geometry. + * If vao is created, it is bound automatically. We use a shader to infer what and how to set up the + * attribute locations. + * @param geometry - Instance of geometry to to generate Vao for. + * @param shader - Instance of the shader. + * @param incRefCount - Increment refCount of all geometry buffers. + */ + GeometrySystem.prototype.initGeometryVao = function (geometry, shader, incRefCount) { + if (incRefCount === void 0) { incRefCount = true; } + var gl = this.gl; + var CONTEXT_UID = this.CONTEXT_UID; + var bufferSystem = this.renderer.buffer; + var program = shader.program; + if (!program.glPrograms[CONTEXT_UID]) { + this.renderer.shader.generateProgram(shader); + } + this.checkCompatibility(geometry, program); + var signature = this.getSignature(geometry, program); + var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var vao = vaoObjectHash[signature]; + if (vao) { + // this will give us easy access to the vao + vaoObjectHash[program.id] = vao; + return vao; + } + var buffers = geometry.buffers; + var attributes = geometry.attributes; + var tempStride = {}; + var tempStart = {}; + for (var j in buffers) { + tempStride[j] = 0; + tempStart[j] = 0; + } + for (var j in attributes) { + if (!attributes[j].size && program.attributeData[j]) { + attributes[j].size = program.attributeData[j].size; + } + else if (!attributes[j].size) { + console.warn("PIXI Geometry attribute '" + j + "' size cannot be determined (likely the bound shader does not have the attribute)"); // eslint-disable-line + } + tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap[attributes[j].type]; + } + for (var j in attributes) { + var attribute = attributes[j]; + var attribSize = attribute.size; + if (attribute.stride === undefined) { + if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) { + attribute.stride = 0; + } + else { + attribute.stride = tempStride[attribute.buffer]; + } + } + if (attribute.start === undefined) { + attribute.start = tempStart[attribute.buffer]; + tempStart[attribute.buffer] += attribSize * byteSizeMap[attribute.type]; + } + } + vao = gl.createVertexArray(); + gl.bindVertexArray(vao); + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (var i = 0; i < buffers.length; i++) { + var buffer = buffers[i]; + bufferSystem.bind(buffer); + if (incRefCount) { + buffer._glBuffers[CONTEXT_UID].refCount++; + } + } + // TODO - maybe make this a data object? + // lets wait to see if we need to first! + this.activateVao(geometry, program); + this._activeVao = vao; + // add it to the cache! + vaoObjectHash[program.id] = vao; + vaoObjectHash[signature] = vao; + return vao; + }; + /** + * Disposes geometry. + * @param geometry - Geometry with buffers. Only VAO will be disposed + * @param [contextLost=false] - If context was lost, we suppress deleteVertexArray + */ + GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) { + var _a; + if (!this.managedGeometries[geometry.id]) { + return; + } + delete this.managedGeometries[geometry.id]; + var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var gl = this.gl; + var buffers = geometry.buffers; + var bufferSystem = (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.buffer; + geometry.disposeRunner.remove(this); + if (!vaos) { + return; + } + // bufferSystem may have already been destroyed.. + // if this is the case, there is no need to destroy the geometry buffers... + // they already have been! + if (bufferSystem) { + for (var i = 0; i < buffers.length; i++) { + var buf = buffers[i]._glBuffers[this.CONTEXT_UID]; + // my be null as context may have changed right before the dispose is called + if (buf) { + buf.refCount--; + if (buf.refCount === 0 && !contextLost) { + bufferSystem.dispose(buffers[i], contextLost); + } + } + } + } + if (!contextLost) { + for (var vaoId in vaos) { + // delete only signatures, everything else are copies + if (vaoId[0] === 'g') { + var vao = vaos[vaoId]; + if (this._activeVao === vao) { + this.unbind(); + } + gl.deleteVertexArray(vao); + } + } + } + delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; + }; + /** + * Dispose all WebGL resources of all managed geometries. + * @param [contextLost=false] - If context was lost, we suppress `gl.delete` calls + */ + GeometrySystem.prototype.disposeAll = function (contextLost) { + var all = Object.keys(this.managedGeometries); + for (var i = 0; i < all.length; i++) { + this.disposeGeometry(this.managedGeometries[all[i]], contextLost); + } + }; + /** + * Activate vertex array object. + * @param geometry - Geometry instance. + * @param program - Shader program instance. + */ + GeometrySystem.prototype.activateVao = function (geometry, program) { + var gl = this.gl; + var CONTEXT_UID = this.CONTEXT_UID; + var bufferSystem = this.renderer.buffer; + var buffers = geometry.buffers; + var attributes = geometry.attributes; + if (geometry.indexBuffer) { + // first update the index buffer if we have one.. + bufferSystem.bind(geometry.indexBuffer); + } + var lastBuffer = null; + // add a new one! + for (var j in attributes) { + var attribute = attributes[j]; + var buffer = buffers[attribute.buffer]; + var glBuffer = buffer._glBuffers[CONTEXT_UID]; + if (program.attributeData[j]) { + if (lastBuffer !== glBuffer) { + bufferSystem.bind(buffer); + lastBuffer = glBuffer; + } + var location = program.attributeData[j].location; + // TODO introduce state again + // we can optimise this for older devices that have no VAOs + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start); + if (attribute.instance) { + // TODO calculate instance count based of this... + if (this.hasInstance) { + gl.vertexAttribDivisor(location, 1); + } + else { + throw new Error('geometry error, GPU Instancing is not supported on this device'); + } + } + } + } + }; + /** + * Draws the currently bound geometry. + * @param type - The type primitive to render. + * @param size - The number of elements to be rendered. If not specified, all vertices after the + * starting vertex will be drawn. + * @param start - The starting vertex in the geometry to start drawing from. If not specified, + * drawing will start from the first vertex. + * @param instanceCount - The number of instances of the set of elements to execute. If not specified, + * all instances will be drawn. + */ + GeometrySystem.prototype.draw = function (type, size, start, instanceCount) { + var gl = this.gl; + var geometry = this._activeGeometry; + // TODO.. this should not change so maybe cache the function? + if (geometry.indexBuffer) { + var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; + var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; + if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) { + if (geometry.instanced) { + /* eslint-disable max-len */ + gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); + /* eslint-enable max-len */ + } + else { + /* eslint-disable max-len */ + gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); + /* eslint-enable max-len */ + } + } + else { + console.warn('unsupported index buffer type: uint32'); + } + } + else if (geometry.instanced) { + // TODO need a better way to calculate size.. + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } + else { + gl.drawArrays(type, start, size || geometry.getSize()); + } + return this; + }; + /** Unbind/reset everything. */ + GeometrySystem.prototype.unbind = function () { + this.gl.bindVertexArray(null); + this._activeVao = null; + this._activeGeometry = null; + }; + GeometrySystem.prototype.destroy = function () { + this.renderer = null; + }; + return GeometrySystem; + }()); + + /** + * Component for masked elements. + * + * Holds mask mode and temporary data about current mask. + * @memberof PIXI + */ + var MaskData = /** @class */ (function () { + /** + * Create MaskData + * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask + */ + function MaskData(maskObject) { + if (maskObject === void 0) { maskObject = null; } + this.type = exports.MASK_TYPES.NONE; + this.autoDetect = true; + this.maskObject = maskObject || null; + this.pooled = false; + this.isMaskData = true; + this.resolution = null; + this.multisample = settings$1.FILTER_MULTISAMPLE; + this.enabled = true; + this.colorMask = 0xf; + this._filters = null; + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + this._scissorRectLocal = null; + this._colorMask = 0xf; + this._target = null; + } + Object.defineProperty(MaskData.prototype, "filter", { + /** + * The sprite mask filter. + * If set to `null`, the default sprite mask filter is used. + * @default null + */ + get: function () { + return this._filters ? this._filters[0] : null; + }, + set: function (value) { + if (value) { + if (this._filters) { + this._filters[0] = value; + } + else { + this._filters = [value]; + } + } + else { + this._filters = null; + } + }, + enumerable: false, + configurable: true + }); + /** Resets the mask data after popMask(). */ + MaskData.prototype.reset = function () { + if (this.pooled) { + this.maskObject = null; + this.type = exports.MASK_TYPES.NONE; + this.autoDetect = true; + } + this._target = null; + this._scissorRectLocal = null; + }; + /** + * Copies counters from maskData above, called from pushMask(). + * @param maskAbove + */ + MaskData.prototype.copyCountersOrReset = function (maskAbove) { + if (maskAbove) { + this._stencilCounter = maskAbove._stencilCounter; + this._scissorCounter = maskAbove._scissorCounter; + this._scissorRect = maskAbove._scissorRect; + } + else { + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + } + }; + return MaskData; + }()); + + /** + * @private + * @param {WebGLRenderingContext} gl - The current WebGL context {WebGLProgram} + * @param {number} type - the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param {string} src - The vertex shader source as an array of strings. + * @returns {WebGLShader} the shader + */ + function compileShader(gl, type, src) { + var shader = gl.createShader(type); + gl.shaderSource(shader, src); + gl.compileShader(shader); + return shader; + } + + /** + * will log a shader error highlighting the lines with the error + * also will add numbers along the side. + * @param gl - the WebGLContext + * @param shader - the shader to log errors for + */ + function logPrettyShaderError(gl, shader) { + var shaderSrc = gl.getShaderSource(shader) + .split('\n') + .map(function (line, index) { return index + ": " + line; }); + var shaderLog = gl.getShaderInfoLog(shader); + var splitShader = shaderLog.split('\n'); + var dedupe = {}; + var lineNumbers = splitShader.map(function (line) { return parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, '$1')); }) + .filter(function (n) { + if (n && !dedupe[n]) { + dedupe[n] = true; + return true; + } + return false; + }); + var logArgs = ['']; + lineNumbers.forEach(function (number) { + shaderSrc[number - 1] = "%c" + shaderSrc[number - 1] + "%c"; + logArgs.push('background: #FF0000; color:#FFFFFF; font-size: 10px', 'font-size: 10px'); + }); + var fragmentSourceToLog = shaderSrc + .join('\n'); + logArgs[0] = fragmentSourceToLog; + console.error(shaderLog); + // eslint-disable-next-line no-console + console.groupCollapsed('click to view full shader code'); + console.warn.apply(console, logArgs); + // eslint-disable-next-line no-console + console.groupEnd(); + } + /** + * + * logs out any program errors + * @param gl - The current WebGL context + * @param program - the WebGL program to display errors for + * @param vertexShader - the fragment WebGL shader program + * @param fragmentShader - the vertex WebGL shader program + */ + function logProgramError(gl, program, vertexShader, fragmentShader) { + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { + logPrettyShaderError(gl, vertexShader); + } + if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { + logPrettyShaderError(gl, fragmentShader); + } + console.error('PixiJS Error: Could not initialize shader.'); + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') { + console.warn('PixiJS Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + } + } + + function booleanArray(size) { + var array = new Array(size); + for (var i = 0; i < array.length; i++) { + array[i] = false; + } + return array; + } + /** + * @method defaultValue + * @memberof PIXI.glCore.shader + * @param {string} type - Type of value + * @param {number} size + * @private + */ + function defaultValue(type, size) { + switch (type) { + case 'float': + return 0; + case 'vec2': + return new Float32Array(2 * size); + case 'vec3': + return new Float32Array(3 * size); + case 'vec4': + return new Float32Array(4 * size); + case 'int': + case 'uint': + case 'sampler2D': + case 'sampler2DArray': + return 0; + case 'ivec2': + return new Int32Array(2 * size); + case 'ivec3': + return new Int32Array(3 * size); + case 'ivec4': + return new Int32Array(4 * size); + case 'uvec2': + return new Uint32Array(2 * size); + case 'uvec3': + return new Uint32Array(3 * size); + case 'uvec4': + return new Uint32Array(4 * size); + case 'bool': + return false; + case 'bvec2': + return booleanArray(2 * size); + case 'bvec3': + return booleanArray(3 * size); + case 'bvec4': + return booleanArray(4 * size); + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } + return null; + } + + var unknownContext = {}; + var context = unknownContext; + /** + * returns a little WebGL context to use for program inspection. + * @static + * @private + * @returns {WebGLRenderingContext} a gl context to test with + */ + function getTestContext() { + if (context === unknownContext || (context && context.isContextLost())) { + var canvas = settings$1.ADAPTER.createCanvas(); + var gl = void 0; + if (settings$1.PREFER_ENV >= exports.ENV.WEBGL2) { + gl = canvas.getContext('webgl2', {}); + } + if (!gl) { + gl = (canvas.getContext('webgl', {}) + || canvas.getContext('experimental-webgl', {})); + if (!gl) { + // fail, not able to get a context + gl = null; + } + else { + // for shader testing.. + gl.getExtension('WEBGL_draw_buffers'); + } + } + context = gl; + } + return context; + } + + var maxFragmentPrecision; + function getMaxFragmentPrecision() { + if (!maxFragmentPrecision) { + maxFragmentPrecision = exports.PRECISION.MEDIUM; + var gl = getTestContext(); + if (gl) { + if (gl.getShaderPrecisionFormat) { + var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); + maxFragmentPrecision = shaderFragment.precision ? exports.PRECISION.HIGH : exports.PRECISION.MEDIUM; + } + } + } + return maxFragmentPrecision; + } + + /** + * Sets the float precision on the shader, ensuring the device supports the request precision. + * If the precision is already present, it just ensures that the device is able to handle it. + * @private + * @param {string} src - The shader source + * @param {PIXI.PRECISION} requestedPrecision - The request float precision of the shader. + * @param {PIXI.PRECISION} maxSupportedPrecision - The maximum precision the shader supports. + * @returns {string} modified shader source + */ + function setPrecision(src, requestedPrecision, maxSupportedPrecision) { + if (src.substring(0, 9) !== 'precision') { + // no precision supplied, so PixiJS will add the requested level. + var precision = requestedPrecision; + // If highp is requested but not supported, downgrade precision to a level all devices support. + if (requestedPrecision === exports.PRECISION.HIGH && maxSupportedPrecision !== exports.PRECISION.HIGH) { + precision = exports.PRECISION.MEDIUM; + } + return "precision " + precision + " float;\n" + src; + } + else if (maxSupportedPrecision !== exports.PRECISION.HIGH && src.substring(0, 15) === 'precision highp') { + // precision was supplied, but at a level this device does not support, so downgrading to mediump. + return src.replace('precision highp', 'precision mediump'); + } + return src; + } + + var GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + uint: 1, + uvec2: 2, + uvec3: 3, + uvec4: 4, + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + mat2: 4, + mat3: 9, + mat4: 16, + sampler2D: 1, + }; + /** + * @private + * @method mapSize + * @memberof PIXI.glCore.shader + * @param {string} type + */ + function mapSize(type) { + return GLSL_TO_SIZE[type]; + } + + var GL_TABLE = null; + var GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + UNSIGNED_INT: 'uint', + UNSIGNED_INT_VEC2: 'uvec2', + UNSIGNED_INT_VEC3: 'uvec3', + UNSIGNED_INT_VEC4: 'uvec4', + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + SAMPLER_2D: 'sampler2D', + INT_SAMPLER_2D: 'sampler2D', + UNSIGNED_INT_SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + INT_SAMPLER_CUBE: 'samplerCube', + UNSIGNED_INT_SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', + INT_SAMPLER_2D_ARRAY: 'sampler2DArray', + UNSIGNED_INT_SAMPLER_2D_ARRAY: 'sampler2DArray', + }; + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + function mapType(gl, type) { + if (!GL_TABLE) { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + GL_TABLE = {}; + for (var i = 0; i < typeNames.length; ++i) { + var tn = typeNames[i]; + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; + } + } + return GL_TABLE[type]; + } + + /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ + // Parsers, each one of these will take a look at the type of shader property and uniform. + // if they pass the test function then the code function is called that returns a the shader upload code for that uniform. + // Shader upload code is automagically generated with these parsers. + // If no parser is valid then the default upload functions are used. + // exposing Parsers means that custom upload logic can be added to pixi's shaders. + // A good example would be a pixi rectangle can be directly set on a uniform. + // If the shader sees it it knows how to upload the rectangle structure as a vec4 + // format is as follows: + // + // { + // test: (data, uniform) => {} <--- test is this code should be used for this uniform + // code: (name, uniform) => {} <--- returns the string of the piece of code that uploads the uniform + // codeUbo: (name, uniform) => {} <--- returns the string of the piece of code that uploads the + // uniform to a uniform buffer + // } + var uniformParsers = [ + // a float cache layer + { + test: function (data) { + return data.type === 'float' && data.size === 1; + }, + code: function (name) { + return "\n if(uv[\"" + name + "\"] !== ud[\"" + name + "\"].value)\n {\n ud[\"" + name + "\"].value = uv[\"" + name + "\"]\n gl.uniform1f(ud[\"" + name + "\"].location, uv[\"" + name + "\"])\n }\n "; + }, + }, + // handling samplers + { + test: function (data, uniform) { + // eslint-disable-next-line max-len,no-eq-null,eqeqeq + return (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray && (uniform == null || uniform.castToBaseTexture !== undefined); + }, + code: function (name) { return "t = syncData.textureCount++;\n\n renderer.texture.bind(uv[\"" + name + "\"], t);\n\n if(ud[\"" + name + "\"].value !== t)\n {\n ud[\"" + name + "\"].value = t;\n gl.uniform1i(ud[\"" + name + "\"].location, t);\n; // eslint-disable-line max-len\n }"; }, + }, + // uploading pixi matrix object to mat3 + { + test: function (data, uniform) { + return data.type === 'mat3' && data.size === 1 && uniform.a !== undefined; + }, + code: function (name) { + // TODO and some smart caching dirty ids here! + return "\n gl.uniformMatrix3fv(ud[\"" + name + "\"].location, false, uv[\"" + name + "\"].toArray(true));\n "; + }, + codeUbo: function (name) { + return "\n var " + name + "_matrix = uv." + name + ".toArray(true);\n\n data[offset] = " + name + "_matrix[0];\n data[offset+1] = " + name + "_matrix[1];\n data[offset+2] = " + name + "_matrix[2];\n \n data[offset + 4] = " + name + "_matrix[3];\n data[offset + 5] = " + name + "_matrix[4];\n data[offset + 6] = " + name + "_matrix[5];\n \n data[offset + 8] = " + name + "_matrix[6];\n data[offset + 9] = " + name + "_matrix[7];\n data[offset + 10] = " + name + "_matrix[8];\n "; + }, + }, + // uploading a pixi point as a vec2 with caching layer + { + test: function (data, uniform) { + return data.type === 'vec2' && data.size === 1 && uniform.x !== undefined; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud[\"" + name + "\"].location, v.x, v.y);\n }"; + }, + codeUbo: function (name) { + return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n "; + } + }, + // caching layer for a vec2 + { + test: function (data) { + return data.type === 'vec2' && data.size === 1; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud[\"" + name + "\"].location, v[0], v[1]);\n }\n "; + }, + }, + // upload a pixi rectangle as a vec4 with caching layer + { + test: function (data, uniform) { + return data.type === 'vec4' && data.size === 1 && uniform.width !== undefined; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud[\"" + name + "\"].location, v.x, v.y, v.width, v.height)\n }"; + }, + codeUbo: function (name) { + return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n "; + } + }, + // a caching layer for vec4 uploading + { + test: function (data) { + return data.type === 'vec4' && data.size === 1; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud[\"" + name + "\"].location, v[0], v[1], v[2], v[3])\n }"; + }, + } ]; + + // cu = Cached value's uniform data field + // cv = Cached value + // v = value to upload + // ud = uniformData + // uv = uniformValue + // l = location + var GLSL_TO_SINGLE_SETTERS_CACHED = { + float: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }", + vec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }", + vec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }", + vec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }", + int: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + ivec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }", + ivec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }", + ivec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }", + uint: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }", + uvec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }", + uvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }", + uvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }", + bool: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }", + bvec2: "\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }", + bvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }", + bvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }", + mat2: 'gl.uniformMatrix2fv(location, false, v)', + mat3: 'gl.uniformMatrix3fv(location, false, v)', + mat4: 'gl.uniformMatrix4fv(location, false, v)', + sampler2D: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + samplerCube: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + sampler2DArray: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + }; + var GLSL_TO_ARRAY_SETTERS = { + float: "gl.uniform1fv(location, v)", + vec2: "gl.uniform2fv(location, v)", + vec3: "gl.uniform3fv(location, v)", + vec4: 'gl.uniform4fv(location, v)', + mat4: 'gl.uniformMatrix4fv(location, false, v)', + mat3: 'gl.uniformMatrix3fv(location, false, v)', + mat2: 'gl.uniformMatrix2fv(location, false, v)', + int: 'gl.uniform1iv(location, v)', + ivec2: 'gl.uniform2iv(location, v)', + ivec3: 'gl.uniform3iv(location, v)', + ivec4: 'gl.uniform4iv(location, v)', + uint: 'gl.uniform1uiv(location, v)', + uvec2: 'gl.uniform2uiv(location, v)', + uvec3: 'gl.uniform3uiv(location, v)', + uvec4: 'gl.uniform4uiv(location, v)', + bool: 'gl.uniform1iv(location, v)', + bvec2: 'gl.uniform2iv(location, v)', + bvec3: 'gl.uniform3iv(location, v)', + bvec4: 'gl.uniform4iv(location, v)', + sampler2D: 'gl.uniform1iv(location, v)', + samplerCube: 'gl.uniform1iv(location, v)', + sampler2DArray: 'gl.uniform1iv(location, v)', + }; + function generateUniformsSync(group, uniformData) { + var _a; + var funcFragments = ["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "]; + for (var i in group.uniforms) { + var data = uniformData[i]; + if (!data) { + if ((_a = group.uniforms[i]) === null || _a === void 0 ? void 0 : _a.group) { + if (group.uniforms[i].ubo) { + funcFragments.push("\n renderer.shader.syncUniformBufferGroup(uv." + i + ", '" + i + "');\n "); + } + else { + funcFragments.push("\n renderer.shader.syncUniformGroup(uv." + i + ", syncData);\n "); + } + } + continue; + } + var uniform = group.uniforms[i]; + var parsed = false; + for (var j = 0; j < uniformParsers.length; j++) { + if (uniformParsers[j].test(data, uniform)) { + funcFragments.push(uniformParsers[j].code(i, uniform)); + parsed = true; + break; + } + } + if (!parsed) { + var templateType = (data.size === 1) ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; + var template = templateType[data.type].replace('location', "ud[\"" + i + "\"].location"); + funcFragments.push("\n cu = ud[\"" + i + "\"];\n cv = cu.value;\n v = uv[\"" + i + "\"];\n " + template + ";"); + } + } + /* + * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly + * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used + * no matter which group is being used + * + */ + // eslint-disable-next-line no-new-func + return new Function('ud', 'uv', 'renderer', 'syncData', funcFragments.join('\n')); + } + + var fragTemplate$1 = [ + 'precision mediump float;', + 'void main(void){', + 'float test = 0.1;', + '%forloop%', + 'gl_FragColor = vec4(0.0);', + '}' ].join('\n'); + function generateIfTestSrc(maxIfs) { + var src = ''; + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + if (i < maxIfs - 1) { + src += "if(test == " + i + ".0){}"; + } + } + return src; + } + function checkMaxIfStatementsInShader(maxIfs, gl) { + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + var shader = gl.createShader(gl.FRAGMENT_SHADER); + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate$1.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = (maxIfs / 2) | 0; + } + else { + // valid! + break; + } + } + return maxIfs; + } + + // Cache the result to prevent running this over and over + var unsafeEval; + /** + * Not all platforms allow to generate function code (e.g., `new Function`). + * this provides the platform-level detection. + * @private + * @returns {boolean} `true` if `new Function` is supported. + */ + function unsafeEvalSupported() { + if (typeof unsafeEval === 'boolean') { + return unsafeEval; + } + try { + /* eslint-disable no-new-func */ + var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;'); + /* eslint-enable no-new-func */ + unsafeEval = func({ a: 'b' }, 'a', 'b') === true; + } + catch (e) { + unsafeEval = false; + } + return unsafeEval; + } + + var defaultFragment$2 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; + + var defaultVertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; + + var UID$1 = 0; + var nameCache = {}; + /** + * Helper class to create a shader program. + * @memberof PIXI + */ + var Program = /** @class */ (function () { + /** + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param name - Name for shader + */ + function Program(vertexSrc, fragmentSrc, name) { + if (name === void 0) { name = 'pixi-shader'; } + this.id = UID$1++; + this.vertexSrc = vertexSrc || Program.defaultVertexSrc; + this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc; + this.vertexSrc = this.vertexSrc.trim(); + this.fragmentSrc = this.fragmentSrc.trim(); + if (this.vertexSrc.substring(0, 8) !== '#version') { + name = name.replace(/\s+/g, '-'); + if (nameCache[name]) { + nameCache[name]++; + name += "-" + nameCache[name]; + } + else { + nameCache[name] = 1; + } + this.vertexSrc = "#define SHADER_NAME " + name + "\n" + this.vertexSrc; + this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + this.fragmentSrc; + this.vertexSrc = setPrecision(this.vertexSrc, settings$1.PRECISION_VERTEX, exports.PRECISION.HIGH); + this.fragmentSrc = setPrecision(this.fragmentSrc, settings$1.PRECISION_FRAGMENT, getMaxFragmentPrecision()); + } + // currently this does not extract structs only default types + // this is where we store shader references.. + this.glPrograms = {}; + this.syncUniforms = null; + } + Object.defineProperty(Program, "defaultVertexSrc", { + /** + * The default vertex shader source. + * @constant + */ + get: function () { + return defaultVertex$3; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Program, "defaultFragmentSrc", { + /** + * The default fragment shader source. + * @constant + */ + get: function () { + return defaultFragment$2; + }, + enumerable: false, + configurable: true + }); + /** + * A short hand function to create a program based of a vertex and fragment shader. + * + * This method will also check to see if there is a cached program. + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param name - Name for shader + * @returns A shiny new PixiJS shader program! + */ + Program.from = function (vertexSrc, fragmentSrc, name) { + var key = vertexSrc + fragmentSrc; + var program = ProgramCache[key]; + if (!program) { + ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name); + } + return program; + }; + return Program; + }()); + + /** + * A helper class for shaders. + * @memberof PIXI + */ + var Shader = /** @class */ (function () { + /** + * @param program - The program the shader will use. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + */ + function Shader(program, uniforms) { + /** + * Used internally to bind uniform buffer objects. + * @ignore + */ + this.uniformBindCount = 0; + this.program = program; + // lets see whats been passed in + // uniforms should be converted to a uniform group + if (uniforms) { + if (uniforms instanceof UniformGroup) { + this.uniformGroup = uniforms; + } + else { + this.uniformGroup = new UniformGroup(uniforms); + } + } + else { + this.uniformGroup = new UniformGroup({}); + } + } + // TODO move to shader system.. + Shader.prototype.checkUniformExists = function (name, group) { + if (group.uniforms[name]) { + return true; + } + for (var i in group.uniforms) { + var uniform = group.uniforms[i]; + if (uniform.group) { + if (this.checkUniformExists(name, uniform)) { + return true; + } + } + } + return false; + }; + Shader.prototype.destroy = function () { + // usage count on programs? + // remove if not used! + this.uniformGroup = null; + }; + Object.defineProperty(Shader.prototype, "uniforms", { + /** + * Shader uniform values, shortcut for `uniformGroup.uniforms`. + * @readonly + */ + get: function () { + return this.uniformGroup.uniforms; + }, + enumerable: false, + configurable: true + }); + /** + * A short hand function to create a shader based of a vertex and fragment shader. + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + * @returns A shiny new PixiJS shader! + */ + Shader.from = function (vertexSrc, fragmentSrc, uniforms) { + var program = Program.from(vertexSrc, fragmentSrc); + return new Shader(program, uniforms); + }; + return Shader; + }()); + + /* eslint-disable max-len */ + var BLEND$1 = 0; + var OFFSET$1 = 1; + var CULLING$1 = 2; + var DEPTH_TEST$1 = 3; + var WINDING$1 = 4; + var DEPTH_MASK$1 = 5; + /** + * This is a WebGL state, and is is passed to {@link PIXI.StateSystem}. + * + * Each mesh rendered may require WebGL to be in a different state. + * For example you may want different blend mode or to enable polygon offsets + * @memberof PIXI + */ + var State = /** @class */ (function () { + function State() { + this.data = 0; + this.blendMode = exports.BLEND_MODES.NORMAL; + this.polygonOffset = 0; + this.blend = true; + this.depthMask = true; + // this.depthTest = true; + } + Object.defineProperty(State.prototype, "blend", { + /** + * Activates blending of the computed fragment color values. + * @default true + */ + get: function () { + return !!(this.data & (1 << BLEND$1)); + }, + set: function (value) { + if (!!(this.data & (1 << BLEND$1)) !== value) { + this.data ^= (1 << BLEND$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "offsets", { + /** + * Activates adding an offset to depth values of polygon's fragments + * @default false + */ + get: function () { + return !!(this.data & (1 << OFFSET$1)); + }, + set: function (value) { + if (!!(this.data & (1 << OFFSET$1)) !== value) { + this.data ^= (1 << OFFSET$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "culling", { + /** + * Activates culling of polygons. + * @default false + */ + get: function () { + return !!(this.data & (1 << CULLING$1)); + }, + set: function (value) { + if (!!(this.data & (1 << CULLING$1)) !== value) { + this.data ^= (1 << CULLING$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "depthTest", { + /** + * Activates depth comparisons and updates to the depth buffer. + * @default false + */ + get: function () { + return !!(this.data & (1 << DEPTH_TEST$1)); + }, + set: function (value) { + if (!!(this.data & (1 << DEPTH_TEST$1)) !== value) { + this.data ^= (1 << DEPTH_TEST$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "depthMask", { + /** + * Enables or disables writing to the depth buffer. + * @default true + */ + get: function () { + return !!(this.data & (1 << DEPTH_MASK$1)); + }, + set: function (value) { + if (!!(this.data & (1 << DEPTH_MASK$1)) !== value) { + this.data ^= (1 << DEPTH_MASK$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "clockwiseFrontFace", { + /** + * Specifies whether or not front or back-facing polygons can be culled. + * @default false + */ + get: function () { + return !!(this.data & (1 << WINDING$1)); + }, + set: function (value) { + if (!!(this.data & (1 << WINDING$1)) !== value) { + this.data ^= (1 << WINDING$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "blendMode", { + /** + * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * Setting this mode to anything other than NO_BLEND will automatically switch blending on. + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this._blendMode; + }, + set: function (value) { + this.blend = (value !== exports.BLEND_MODES.NONE); + this._blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "polygonOffset", { + /** + * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill. + * @default 0 + */ + get: function () { + return this._polygonOffset; + }, + set: function (value) { + this.offsets = !!value; + this._polygonOffset = value; + }, + enumerable: false, + configurable: true + }); + State.prototype.toString = function () { + return "[@pixi/core:State " + + ("blendMode=" + this.blendMode + " ") + + ("clockwiseFrontFace=" + this.clockwiseFrontFace + " ") + + ("culling=" + this.culling + " ") + + ("depthMask=" + this.depthMask + " ") + + ("polygonOffset=" + this.polygonOffset) + + "]"; + }; + State.for2d = function () { + var state = new State(); + state.depthTest = false; + state.blend = true; + return state; + }; + return State; + }()); + + var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; + + var defaultVertex$2 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; + + /** + * A filter is a special shader that applies post-processing effects to an input texture and writes into an output + * render-target. + * + * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the + * {@link PIXI.filters.BlurFilter BlurFilter}. + * + * ### Usage + * Filters can be applied to any DisplayObject or Container. + * PixiJS' `FilterSystem` renders the container into temporary Framebuffer, + * then filter renders it to the screen. + * Multiple filters can be added to the `filters` array property and stacked on each other. + * + * ``` + * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 }); + * const container = new PIXI.Container(); + * container.filters = [filter]; + * ``` + * + * ### Previous Version Differences + * + * In PixiJS **v3**, a filter was always applied to _whole screen_. + * + * In PixiJS **v4**, a filter can be applied _only part of the screen_. + * Developers had to create a set of uniforms to deal with coordinates. + * + * In PixiJS **v5** combines _both approaches_. + * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, + * bringing those extra uniforms into account. + * + * Also be aware that we have changed default vertex shader, please consult + * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. + * + * ### Frames + * + * The following table summarizes the coordinate spaces used in the filtering pipeline: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
      Coordinate SpaceDescription
      Texture Coordinates + * The texture (or UV) coordinates in the input base-texture's space. These are normalized into the (0,1) range along + * both axes. + *
      World Space + * A point in the same space as the world bounds of any display-object (i.e. in the scene graph's space). + *
      Physical Pixels + * This is base-texture's space with the origin on the top-left. You can calculate these by multiplying the texture + * coordinates by the dimensions of the texture. + *
      + * + * ### Built-in Uniforms + * + * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`, + * and `projectionMatrix` uniform maps it to the gl viewport. + * + * **uSampler** + * + * The most important uniform is the input texture that container was rendered into. + * _Important note: as with all Framebuffers in PixiJS, both input and output are + * premultiplied by alpha._ + * + * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`. + * Use it to sample the input. + * + * ``` + * const fragment = ` + * varying vec2 vTextureCoord; + * uniform sampler2D uSampler; + * void main(void) + * { + * gl_FragColor = texture2D(uSampler, vTextureCoord); + * } + * `; + * + * const myFilter = new PIXI.Filter(null, fragment); + * ``` + * + * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}. + * + * **outputFrame** + * + * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates. + * It's the same as `renderer.screen` for a fullscreen filter. + * Only a part of `outputFrame.zw` size of temporary Framebuffer is used, + * `(0, 0, outputFrame.width, outputFrame.height)`, + * + * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute. + * To calculate vertex position in screen space using normalized (0-1) space: + * + * ``` + * vec4 filterVertexPosition( void ) + * { + * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; + * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + * } + * ``` + * + * **inputSize** + * + * Temporary framebuffer is different, it can be either the size of screen, either power-of-two. + * The `inputSize.xy` are size of temporary framebuffer that holds input. + * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader. + * + * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter. + * + * To calculate input normalized coordinate, you have to map it to filter normalized space. + * Multiply by `outputFrame.zw` to get input coordinate. + * Divide by `inputSize.xy` to get input normalized coordinate. + * + * ``` + * vec2 filterTextureCoord( void ) + * { + * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy + * } + * ``` + * **resolution** + * + * The `resolution` is the ratio of screen (CSS) pixels to real pixels. + * + * **inputPixel** + * + * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution` + * `inputPixel.zw` is inverted `inputPixel.xy`. + * + * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}. + * + * **inputClamp** + * + * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. + * For displacements, coordinates has to be clamped. + * + * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer + * `inputClamp.zw` is bottom-right pixel center. + * + * ``` + * vec4 color = texture2D(uSampler, clamp(modifiedTextureCoord, inputClamp.xy, inputClamp.zw)) + * ``` + * OR + * ``` + * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw)) + * ``` + * + * ### Additional Information + * + * Complete documentation on Filter usage is located in the + * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. + * + * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded + * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository. + * @memberof PIXI + */ + var Filter = /** @class */ (function (_super) { + __extends$i(Filter, _super); + /** + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + var _this = this; + var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc); + _this = _super.call(this, program, uniforms) || this; + _this.padding = 0; + _this.resolution = settings$1.FILTER_RESOLUTION; + _this.multisample = settings$1.FILTER_MULTISAMPLE; + _this.enabled = true; + _this.autoFit = true; + _this.state = new State(); + return _this; + } + /** + * Applies the filter + * @param {PIXI.FilterSystem} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTexture} input - The input render target. + * @param {PIXI.RenderTexture} output - The target to output to. + * @param {PIXI.CLEAR_MODES} [clearMode] - Should the output be cleared before rendering to it. + * @param {object} [_currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + Filter.prototype.apply = function (filterManager, input, output, clearMode, _currentState) { + // do as you please! + filterManager.applyFilter(this, input, output, clearMode); + // or just do a regular render.. + }; + Object.defineProperty(Filter.prototype, "blendMode", { + /** + * Sets the blend mode of the filter. + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this.state.blendMode; + }, + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter.prototype, "resolution", { + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._resolution = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter, "defaultVertexSrc", { + /** + * The default vertex shader source + * @constant + */ + get: function () { + return defaultVertex$2; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter, "defaultFragmentSrc", { + /** + * The default fragment shader source + * @constant + */ + get: function () { + return defaultFragment$1; + }, + enumerable: false, + configurable: true + }); + return Filter; + }(Shader)); + + var vertex$4 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; + + var fragment$7 = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; + + var tempMat$1 = new Matrix(); + /** + * Class controls uv mapping from Texture normal space to BaseTexture normal space. + * + * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite. + * + * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. + * + * Takes track of Texture changes through `_lastTextureID` private field. + * Use `update()` method call to track it from outside. + * @see PIXI.Texture + * @see PIXI.Mesh + * @see PIXI.TilingSprite + * @memberof PIXI + */ + var TextureMatrix = /** @class */ (function () { + /** + * @param texture - observed texture + * @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + */ + function TextureMatrix(texture, clampMargin) { + this._texture = texture; + this.mapCoord = new Matrix(); + this.uClampFrame = new Float32Array(4); + this.uClampOffset = new Float32Array(2); + this._textureID = -1; + this._updateID = 0; + this.clampOffset = 0; + this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin; + this.isSimple = false; + } + Object.defineProperty(TextureMatrix.prototype, "texture", { + /** Texture property. */ + get: function () { + return this._texture; + }, + set: function (value) { + this._texture = value; + this._textureID = -1; + }, + enumerable: false, + configurable: true + }); + /** + * Multiplies uvs array to transform + * @param uvs - mesh uvs + * @param [out=uvs] - output + * @returns - output + */ + TextureMatrix.prototype.multiplyUvs = function (uvs, out) { + if (out === undefined) { + out = uvs; + } + var mat = this.mapCoord; + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + out[i] = (x * mat.a) + (y * mat.c) + mat.tx; + out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty; + } + return out; + }; + /** + * Updates matrices if texture was changed. + * @param [forceUpdate=false] - if true, matrices will be updated any case + * @returns - Whether or not it was updated + */ + TextureMatrix.prototype.update = function (forceUpdate) { + var tex = this._texture; + if (!tex || !tex.valid) { + return false; + } + if (!forceUpdate + && this._textureID === tex._updateID) { + return false; + } + this._textureID = tex._updateID; + this._updateID++; + var uvs = tex._uvs; + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + var orig = tex.orig; + var trim = tex.trim; + if (trim) { + tempMat$1.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat$1); + } + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + this.isSimple = tex._frame.width === texBase.width + && tex._frame.height === texBase.height + && tex.rotate === 0; + return true; + }; + return TextureMatrix; + }()); + + /** + * This handles a Sprite acting as a mask, as opposed to a Graphic. + * + * WebGL only. + * @memberof PIXI + */ + var SpriteMaskFilter = /** @class */ (function (_super) { + __extends$i(SpriteMaskFilter, _super); + /** @ignore */ + function SpriteMaskFilter(vertexSrc, fragmentSrc, uniforms) { + var _this = this; + var sprite = null; + if (typeof vertexSrc !== 'string' && fragmentSrc === undefined && uniforms === undefined) { + sprite = vertexSrc; + vertexSrc = undefined; + fragmentSrc = undefined; + uniforms = undefined; + } + _this = _super.call(this, vertexSrc || vertex$4, fragmentSrc || fragment$7, uniforms) || this; + _this.maskSprite = sprite; + _this.maskMatrix = new Matrix(); + return _this; + } + Object.defineProperty(SpriteMaskFilter.prototype, "maskSprite", { + /** + * Sprite mask + * @type {PIXI.DisplayObject} + */ + get: function () { + return this._maskSprite; + }, + set: function (value) { + this._maskSprite = value; + if (this._maskSprite) { + this._maskSprite.renderable = false; + } + }, + enumerable: false, + configurable: true + }); + /** + * Applies the filter + * @param filterManager - The renderer to retrieve the filter from + * @param input - The input render target. + * @param output - The target to output to. + * @param clearMode - Should the output be cleared before rendering to it. + */ + SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) { + var maskSprite = this._maskSprite; + var tex = maskSprite._texture; + if (!tex.valid) { + return; + } + if (!tex.uvMatrix) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.uvMatrix = new TextureMatrix(tex, 0.0); + } + tex.uvMatrix.update(); + this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; + this.uniforms.mask = tex; + // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend` + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite) + .prepend(tex.uvMatrix.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; + filterManager.applyFilter(this, input, output, clearMode); + }; + return SpriteMaskFilter; + }(Filter)); + + /** + * System plugin to the renderer to manage masks. + * + * There are three built-in types of masking: + * **Scissor Masking**: Scissor masking discards pixels that are outside of a rectangle called the scissor box. It is + * the most performant as the scissor test is inexpensive. However, it can only be used when the mask is rectangular. + * **Stencil Masking**: Stencil masking discards pixels that don't overlap with the pixels rendered into the stencil + * buffer. It is the next fastest option as it does not require rendering into a separate framebuffer. However, it does + * cause the mask to be rendered **twice** for each masking operation; hence, minimize the rendering cost of your masks. + * **Sprite Mask Filtering**: Sprite mask filtering discards pixels based on the red channel of the sprite-mask's + * texture. (Generally, the masking texture is grayscale). Using advanced techniques, you might be able to embed this + * type of masking in a custom shader - and hence, bypassing the masking system fully for performance wins. + * + * The best type of masking is auto-detected when you `push` one. To use scissor masking, you must pass in a `Graphics` + * object with just a rectangle drawn. + * + * ## Mask Stacks + * + * In the scene graph, masks can be applied recursively, i.e. a mask can be applied during a masking operation. The mask + * stack stores the currently applied masks in order. Each {@link PIXI.BaseRenderTexture} holds its own mask stack, i.e. + * when you switch render-textures, the old masks only applied when you switch back to rendering to the old render-target. + * @memberof PIXI + */ + var MaskSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function MaskSystem(renderer) { + this.renderer = renderer; + this.enableScissor = true; + this.alphaMaskPool = []; + this.maskDataPool = []; + this.maskStack = []; + this.alphaMaskIndex = 0; + } + /** + * Changes the mask stack that is used by this System. + * @param maskStack - The mask stack + */ + MaskSystem.prototype.setMaskStack = function (maskStack) { + this.maskStack = maskStack; + this.renderer.scissor.setMaskStack(maskStack); + this.renderer.stencil.setMaskStack(maskStack); + }; + /** + * Enables the mask and appends it to the current mask stack. + * + * NOTE: The batch renderer should be flushed beforehand to prevent pending renders from being masked. + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskDataOrTarget - The masking data. + */ + MaskSystem.prototype.push = function (target, maskDataOrTarget) { + var maskData = maskDataOrTarget; + if (!maskData.isMaskData) { + var d = this.maskDataPool.pop() || new MaskData(); + d.pooled = true; + d.maskObject = maskDataOrTarget; + maskData = d; + } + var maskAbove = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; + maskData.copyCountersOrReset(maskAbove); + maskData._colorMask = maskAbove ? maskAbove._colorMask : 0xf; + if (maskData.autoDetect) { + this.detect(maskData); + } + maskData._target = target; + if (maskData.type !== exports.MASK_TYPES.SPRITE) { + this.maskStack.push(maskData); + } + if (maskData.enabled) { + switch (maskData.type) { + case exports.MASK_TYPES.SCISSOR: + this.renderer.scissor.push(maskData); + break; + case exports.MASK_TYPES.STENCIL: + this.renderer.stencil.push(maskData); + break; + case exports.MASK_TYPES.SPRITE: + maskData.copyCountersOrReset(null); + this.pushSpriteMask(maskData); + break; + case exports.MASK_TYPES.COLOR: + this.pushColorMask(maskData); + break; + } + } + if (maskData.type === exports.MASK_TYPES.SPRITE) { + this.maskStack.push(maskData); + } + }; + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * NOTE: The batch renderer should be flushed beforehand to render the masked contents before the mask is removed. + * @param {PIXI.IMaskTarget} target - Display Object to pop the mask from + */ + MaskSystem.prototype.pop = function (target) { + var maskData = this.maskStack.pop(); + if (!maskData || maskData._target !== target) { + // TODO: add an assert when we have it + return; + } + if (maskData.enabled) { + switch (maskData.type) { + case exports.MASK_TYPES.SCISSOR: + this.renderer.scissor.pop(maskData); + break; + case exports.MASK_TYPES.STENCIL: + this.renderer.stencil.pop(maskData.maskObject); + break; + case exports.MASK_TYPES.SPRITE: + this.popSpriteMask(maskData); + break; + case exports.MASK_TYPES.COLOR: + this.popColorMask(maskData); + break; + } + } + maskData.reset(); + if (maskData.pooled) { + this.maskDataPool.push(maskData); + } + if (this.maskStack.length !== 0) { + var maskCurrent = this.maskStack[this.maskStack.length - 1]; + if (maskCurrent.type === exports.MASK_TYPES.SPRITE && maskCurrent._filters) { + maskCurrent._filters[0].maskSprite = maskCurrent.maskObject; + } + } + }; + /** + * Sets type of MaskData based on its maskObject. + * @param maskData + */ + MaskSystem.prototype.detect = function (maskData) { + var maskObject = maskData.maskObject; + if (!maskObject) { + maskData.type = exports.MASK_TYPES.COLOR; + } + else if (maskObject.isSprite) { + maskData.type = exports.MASK_TYPES.SPRITE; + } + else if (this.enableScissor && this.renderer.scissor.testScissor(maskData)) { + maskData.type = exports.MASK_TYPES.SCISSOR; + } + else { + maskData.type = exports.MASK_TYPES.STENCIL; + } + }; + /** + * Applies the Mask and adds it to the current filter stack. + * @param maskData - Sprite to be used as the mask. + */ + MaskSystem.prototype.pushSpriteMask = function (maskData) { + var _a, _b; + var maskObject = maskData.maskObject; + var target = maskData._target; + var alphaMaskFilter = maskData._filters; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter()]; + } + } + var renderer = this.renderer; + var renderTextureSystem = renderer.renderTexture; + var resolution; + var multisample; + if (renderTextureSystem.current) { + var renderTexture = renderTextureSystem.current; + resolution = maskData.resolution || renderTexture.resolution; + multisample = (_a = maskData.multisample) !== null && _a !== void 0 ? _a : renderTexture.multisample; + } + else { + resolution = maskData.resolution || renderer.resolution; + multisample = (_b = maskData.multisample) !== null && _b !== void 0 ? _b : renderer.multisample; + } + alphaMaskFilter[0].resolution = resolution; + alphaMaskFilter[0].multisample = multisample; + alphaMaskFilter[0].maskSprite = maskObject; + var stashFilterArea = target.filterArea; + target.filterArea = maskObject.getBounds(true); + renderer.filter.push(target, alphaMaskFilter); + target.filterArea = stashFilterArea; + if (!maskData._filters) { + this.alphaMaskIndex++; + } + }; + /** + * Removes the last filter from the filter stack and doesn't return it. + * @param maskData - Sprite to be used as the mask. + */ + MaskSystem.prototype.popSpriteMask = function (maskData) { + this.renderer.filter.pop(); + if (maskData._filters) { + maskData._filters[0].maskSprite = null; + } + else { + this.alphaMaskIndex--; + this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite = null; + } + }; + /** + * Pushes the color mask. + * @param maskData - The mask data + */ + MaskSystem.prototype.pushColorMask = function (maskData) { + var currColorMask = maskData._colorMask; + var nextColorMask = maskData._colorMask = currColorMask & maskData.colorMask; + if (nextColorMask !== currColorMask) { + this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0); + } + }; + /** + * Pops the color mask. + * @param maskData - The mask data + */ + MaskSystem.prototype.popColorMask = function (maskData) { + var currColorMask = maskData._colorMask; + var nextColorMask = this.maskStack.length > 0 + ? this.maskStack[this.maskStack.length - 1]._colorMask : 0xf; + if (nextColorMask !== currColorMask) { + this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0); + } + }; + MaskSystem.prototype.destroy = function () { + this.renderer = null; + }; + return MaskSystem; + }()); + + /** + * System plugin to the renderer to manage specific types of masking operations. + * @memberof PIXI + */ + var AbstractMaskSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function AbstractMaskSystem(renderer) { + this.renderer = renderer; + this.maskStack = []; + this.glConst = 0; + } + /** Gets count of masks of certain type. */ + AbstractMaskSystem.prototype.getStackLength = function () { + return this.maskStack.length; + }; + /** + * Changes the mask stack that is used by this System. + * @param {PIXI.MaskData[]} maskStack - The mask stack + */ + AbstractMaskSystem.prototype.setMaskStack = function (maskStack) { + var gl = this.renderer.gl; + var curStackLen = this.getStackLength(); + this.maskStack = maskStack; + var newStackLen = this.getStackLength(); + if (newStackLen !== curStackLen) { + if (newStackLen === 0) { + gl.disable(this.glConst); + } + else { + gl.enable(this.glConst); + this._useCurrent(); + } + } + }; + /** + * Setup renderer to use the current mask data. + * @private + */ + AbstractMaskSystem.prototype._useCurrent = function () { + // OVERWRITE; + }; + /** Destroys the mask stack. */ + AbstractMaskSystem.prototype.destroy = function () { + this.renderer = null; + this.maskStack = null; + }; + return AbstractMaskSystem; + }()); + + var tempMatrix$1 = new Matrix(); + var rectPool = []; + /** + * System plugin to the renderer to manage scissor masking. + * + * Scissor masking discards pixels outside of a rectangle called the scissor box. The scissor box is in the framebuffer + * viewport's space; however, the mask's rectangle is projected from world-space to viewport space automatically + * by this system. + * @memberof PIXI + */ + var ScissorSystem = /** @class */ (function (_super) { + __extends$i(ScissorSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function ScissorSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.glConst = settings$1.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST; + return _this; + } + ScissorSystem.prototype.getStackLength = function () { + var maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._scissorCounter; + } + return 0; + }; + /** + * evaluates _boundsTransformed, _scissorRect for MaskData + * @param maskData + */ + ScissorSystem.prototype.calcScissorRect = function (maskData) { + var _a; + if (maskData._scissorRectLocal) { + return; + } + var prevData = maskData._scissorRect; + var maskObject = maskData.maskObject; + var renderer = this.renderer; + var renderTextureSystem = renderer.renderTexture; + var rect = maskObject.getBounds(true, (_a = rectPool.pop()) !== null && _a !== void 0 ? _a : new Rectangle()); + this.roundFrameToPixels(rect, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); + if (prevData) { + rect.fit(prevData); + } + maskData._scissorRectLocal = rect; + }; + ScissorSystem.isMatrixRotated = function (matrix) { + if (!matrix) { + return false; + } + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d; + // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation + // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0). + return ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) + && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)); + }; + /** + * Test, whether the object can be scissor mask with current renderer projection. + * Calls "calcScissorRect()" if its true. + * @param maskData - mask data + * @returns whether Whether the object can be scissor mask + */ + ScissorSystem.prototype.testScissor = function (maskData) { + var maskObject = maskData.maskObject; + if (!maskObject.isFastRect || !maskObject.isFastRect()) { + return false; + } + if (ScissorSystem.isMatrixRotated(maskObject.worldTransform)) { + return false; + } + if (ScissorSystem.isMatrixRotated(this.renderer.projection.transform)) { + return false; + } + this.calcScissorRect(maskData); + var rect = maskData._scissorRectLocal; + return rect.width > 0 && rect.height > 0; + }; + ScissorSystem.prototype.roundFrameToPixels = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { + if (ScissorSystem.isMatrixRotated(transform)) { + return; + } + transform = transform ? tempMatrix$1.copyFrom(transform) : tempMatrix$1.identity(); + // Get forward transform from world space to screen space + transform + .translate(-bindingSourceFrame.x, -bindingSourceFrame.y) + .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height) + .translate(bindingDestinationFrame.x, bindingDestinationFrame.y); + // Convert frame to screen space + this.renderer.filter.transformAABB(transform, frame); + frame.fit(bindingDestinationFrame); + frame.x = Math.round(frame.x * resolution); + frame.y = Math.round(frame.y * resolution); + frame.width = Math.round(frame.width * resolution); + frame.height = Math.round(frame.height * resolution); + }; + /** + * Applies the Mask and adds it to the current stencil stack. + * @author alvin + * @param maskData - The mask data. + */ + ScissorSystem.prototype.push = function (maskData) { + if (!maskData._scissorRectLocal) { + this.calcScissorRect(maskData); + } + var gl = this.renderer.gl; + if (!maskData._scissorRect) { + gl.enable(gl.SCISSOR_TEST); + } + maskData._scissorCounter++; + maskData._scissorRect = maskData._scissorRectLocal; + this._useCurrent(); + }; + /** + * This should be called after a mask is popped off the mask stack. It will rebind the scissor box to be latest with the + * last mask in the stack. + * + * This can also be called when you directly modify the scissor box and want to restore PixiJS state. + * @param maskData - The mask data. + */ + ScissorSystem.prototype.pop = function (maskData) { + var gl = this.renderer.gl; + if (maskData) { + rectPool.push(maskData._scissorRectLocal); + } + if (this.getStackLength() > 0) { + this._useCurrent(); + } + else { + gl.disable(gl.SCISSOR_TEST); + } + }; + /** + * Setup renderer to use the current scissor data. + * @private + */ + ScissorSystem.prototype._useCurrent = function () { + var rect = this.maskStack[this.maskStack.length - 1]._scissorRect; + var y; + if (this.renderer.renderTexture.current) { + y = rect.y; + } + else { + // flipY. In future we'll have it over renderTextures as an option + y = this.renderer.height - rect.height - rect.y; + } + this.renderer.gl.scissor(rect.x, y, rect.width, rect.height); + }; + return ScissorSystem; + }(AbstractMaskSystem)); + + /** + * System plugin to the renderer to manage stencils (used for masks). + * @memberof PIXI + */ + var StencilSystem = /** @class */ (function (_super) { + __extends$i(StencilSystem, _super); + /** + * @param renderer - The renderer this System works for. + */ + function StencilSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.glConst = settings$1.ADAPTER.getWebGLRenderingContext().STENCIL_TEST; + return _this; + } + StencilSystem.prototype.getStackLength = function () { + var maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._stencilCounter; + } + return 0; + }; + /** + * Applies the Mask and adds it to the current stencil stack. + * @param maskData - The mask data + */ + StencilSystem.prototype.push = function (maskData) { + var maskObject = maskData.maskObject; + var gl = this.renderer.gl; + var prevMaskCount = maskData._stencilCounter; + if (prevMaskCount === 0) { + // force use stencil texture in current framebuffer + this.renderer.framebuffer.forceStencil(); + gl.clearStencil(0); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.enable(gl.STENCIL_TEST); + } + maskData._stencilCounter++; + var colorMask = maskData._colorMask; + if (colorMask !== 0) { + maskData._colorMask = 0; + gl.colorMask(false, false, false, false); + } + // Increment the reference stencil value where the new mask overlaps with the old ones. + gl.stencilFunc(gl.EQUAL, prevMaskCount, 0xFFFFFFFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + if (colorMask !== 0) { + maskData._colorMask = colorMask; + gl.colorMask((colorMask & 1) !== 0, (colorMask & 2) !== 0, (colorMask & 4) !== 0, (colorMask & 8) !== 0); + } + this._useCurrent(); + }; + /** + * Pops stencil mask. MaskData is already removed from stack + * @param {PIXI.DisplayObject} maskObject - object of popped mask data + */ + StencilSystem.prototype.pop = function (maskObject) { + var gl = this.renderer.gl; + if (this.getStackLength() === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } + else { + var maskData = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; + var colorMask = maskData ? maskData._colorMask : 0xf; + if (colorMask !== 0) { + maskData._colorMask = 0; + gl.colorMask(false, false, false, false); + } + // Decrement the reference stencil value where the popped mask overlaps with the other ones + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + if (colorMask !== 0) { + maskData._colorMask = colorMask; + gl.colorMask((colorMask & 0x1) !== 0, (colorMask & 0x2) !== 0, (colorMask & 0x4) !== 0, (colorMask & 0x8) !== 0); + } + this._useCurrent(); + } + }; + /** + * Setup renderer to use the current stencil data. + * @private + */ + StencilSystem.prototype._useCurrent = function () { + var gl = this.renderer.gl; + gl.stencilFunc(gl.EQUAL, this.getStackLength(), 0xFFFFFFFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + return StencilSystem; + }(AbstractMaskSystem)); + + /** + * System plugin to the renderer to manage the projection matrix. + * + * The `projectionMatrix` is a global uniform provided to all shaders. It is used to transform points in world space to + * normalized device coordinates. + * @memberof PIXI + */ + var ProjectionSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ProjectionSystem(renderer) { + this.renderer = renderer; + this.destinationFrame = null; + this.sourceFrame = null; + this.defaultFrame = null; + this.projectionMatrix = new Matrix(); + this.transform = null; + } + /** + * Updates the projection-matrix based on the sourceFrame → destinationFrame mapping provided. + * + * NOTE: It is expected you call `renderer.framebuffer.setViewport(destinationFrame)` after this. This is because + * the framebuffer viewport converts shader vertex output in normalized device coordinates to window coordinates. + * + * NOTE-2: {@link RenderTextureSystem#bind} updates the projection-matrix when you bind a render-texture. It is expected + * that you dirty the current bindings when calling this manually. + * @param destinationFrame - The rectangle in the render-target to render the contents into. If rendering to the canvas, + * the origin is on the top-left; if rendering to a render-texture, the origin is on the bottom-left. + * @param sourceFrame - The rectangle in world space that contains the contents being rendered. + * @param resolution - The resolution of the render-target, which is the ratio of + * world-space (or CSS) pixels to physical pixels. + * @param root - Whether the render-target is the screen. This is required because rendering to textures + * is y-flipped (i.e. upside down relative to the screen). + */ + ProjectionSystem.prototype.update = function (destinationFrame, sourceFrame, resolution, root) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + // Calculate object-space to clip-space projection + this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + var renderer = this.renderer; + renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; + renderer.globalUniforms.update(); + // this will work for now + // but would be sweet to stick and even on the global uniforms.. + if (renderer.shader.shader) { + renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); + } + }; + /** + * Calculates the `projectionMatrix` to map points inside `sourceFrame` to inside `destinationFrame`. + * @param _destinationFrame - The destination frame in the render-target. + * @param sourceFrame - The source frame in world space. + * @param _resolution - The render-target's resolution, i.e. ratio of CSS to physical pixels. + * @param root - Whether rendering into the screen. Otherwise, if rendering to a framebuffer, the projection + * is y-flipped. + */ + ProjectionSystem.prototype.calculateProjection = function (_destinationFrame, sourceFrame, _resolution, root) { + var pm = this.projectionMatrix; + var sign = !root ? 1 : -1; + pm.identity(); + pm.a = (1 / sourceFrame.width * 2); + pm.d = sign * (1 / sourceFrame.height * 2); + pm.tx = -1 - (sourceFrame.x * pm.a); + pm.ty = -sign - (sourceFrame.y * pm.d); + }; + /** + * Sets the transform of the active render target to the given matrix. + * @param _matrix - The transformation matrix + */ + ProjectionSystem.prototype.setTransform = function (_matrix) { + // this._activeRenderTarget.transform = matrix; + }; + ProjectionSystem.prototype.destroy = function () { + this.renderer = null; + }; + return ProjectionSystem; + }()); + + // Temporary rectangle for assigned sourceFrame or destinationFrame + var tempRect = new Rectangle(); + // Temporary rectangle for renderTexture destinationFrame + var tempRect2 = new Rectangle(); + /* eslint-disable max-len */ + /** + * System plugin to the renderer to manage render textures. + * + * Should be added after FramebufferSystem + * + * ### Frames + * + * The `RenderTextureSystem` holds a sourceFrame → destinationFrame projection. The following table explains the different + * coordinate spaces used: + * + * | Frame | Description | Coordinate System | + * | ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------------- | + * | sourceFrame | The rectangle inside of which display-objects are being rendered | **World Space**: The origin on the top-left | + * | destinationFrame | The rectangle in the render-target (canvas or texture) into which contents should be rendered | If rendering to the canvas, this is in screen space and the origin is on the top-left. If rendering to a render-texture, this is in its base-texture's space with the origin on the bottom-left. | + * | viewportFrame | The framebuffer viewport corresponding to the destination-frame | **Window Coordinates**: The origin is always on the bottom-left. | + * @memberof PIXI + */ + var RenderTextureSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function RenderTextureSystem(renderer) { + this.renderer = renderer; + this.clearColor = renderer._backgroundColorRgba; + this.defaultMaskStack = []; + this.current = null; + this.sourceFrame = new Rectangle(); + this.destinationFrame = new Rectangle(); + this.viewportFrame = new Rectangle(); + } + /** + * Bind the current render texture. + * @param renderTexture - RenderTexture to bind, by default its `null` - the screen. + * @param sourceFrame - Part of world that is mapped to the renderTexture. + * @param destinationFrame - Part of renderTexture, by default it has the same size as sourceFrame. + */ + RenderTextureSystem.prototype.bind = function (renderTexture, sourceFrame, destinationFrame) { + if (renderTexture === void 0) { renderTexture = null; } + var renderer = this.renderer; + this.current = renderTexture; + var baseTexture; + var framebuffer; + var resolution; + if (renderTexture) { + baseTexture = renderTexture.baseTexture; + resolution = baseTexture.resolution; + if (!sourceFrame) { + tempRect.width = renderTexture.frame.width; + tempRect.height = renderTexture.frame.height; + sourceFrame = tempRect; + } + if (!destinationFrame) { + tempRect2.x = renderTexture.frame.x; + tempRect2.y = renderTexture.frame.y; + tempRect2.width = sourceFrame.width; + tempRect2.height = sourceFrame.height; + destinationFrame = tempRect2; + } + framebuffer = baseTexture.framebuffer; + } + else { + resolution = renderer.resolution; + if (!sourceFrame) { + tempRect.width = renderer.screen.width; + tempRect.height = renderer.screen.height; + sourceFrame = tempRect; + } + if (!destinationFrame) { + destinationFrame = tempRect; + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + } + } + var viewportFrame = this.viewportFrame; + viewportFrame.x = destinationFrame.x * resolution; + viewportFrame.y = destinationFrame.y * resolution; + viewportFrame.width = destinationFrame.width * resolution; + viewportFrame.height = destinationFrame.height * resolution; + if (!renderTexture) { + viewportFrame.y = renderer.view.height - (viewportFrame.y + viewportFrame.height); + } + viewportFrame.ceil(); + this.renderer.framebuffer.bind(framebuffer, viewportFrame); + this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer); + if (renderTexture) { + this.renderer.mask.setMaskStack(baseTexture.maskStack); + } + else { + this.renderer.mask.setMaskStack(this.defaultMaskStack); + } + this.sourceFrame.copyFrom(sourceFrame); + this.destinationFrame.copyFrom(destinationFrame); + }; + /** + * Erases the render texture and fills the drawing area with a colour. + * @param clearColor - The color as rgba, default to use the renderer backgroundColor + * @param [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks + * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. + */ + RenderTextureSystem.prototype.clear = function (clearColor, mask) { + if (this.current) { + clearColor = clearColor || this.current.baseTexture.clearColor; + } + else { + clearColor = clearColor || this.clearColor; + } + var destinationFrame = this.destinationFrame; + var baseFrame = this.current ? this.current.baseTexture : this.renderer.screen; + var clearMask = destinationFrame.width !== baseFrame.width || destinationFrame.height !== baseFrame.height; + if (clearMask) { + var _a = this.viewportFrame, x = _a.x, y = _a.y, width = _a.width, height = _a.height; + x = Math.round(x); + y = Math.round(y); + width = Math.round(width); + height = Math.round(height); + // TODO: ScissorSystem should cache whether the scissor test is enabled or not. + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + this.renderer.gl.scissor(x, y, width, height); + } + this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask); + if (clearMask) { + // Restore the scissor box + this.renderer.scissor.pop(); + } + }; + RenderTextureSystem.prototype.resize = function () { + // resize the root only! + this.bind(null); + }; + /** Resets render-texture state. */ + RenderTextureSystem.prototype.reset = function () { + this.bind(null); + }; + RenderTextureSystem.prototype.destroy = function () { + this.renderer = null; + }; + return RenderTextureSystem; + }()); + + function uboUpdate(_ud, _uv, _renderer, _syncData, buffer) { + _renderer.buffer.update(buffer); + } + // cv = CachedValue + // v = value + // ud = uniformData + // uv = uniformValue + // l = location + var UBO_TO_SINGLE_SETTERS = { + float: "\n data[offset] = v;\n ", + vec2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n ", + vec3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ", + vec4: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ", + mat2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ", + mat3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ", + mat4: "\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n " + }; + var GLSL_TO_STD40_SIZE = { + float: 4, + vec2: 8, + vec3: 12, + vec4: 16, + int: 4, + ivec2: 8, + ivec3: 12, + ivec4: 16, + uint: 4, + uvec2: 8, + uvec3: 12, + uvec4: 16, + bool: 4, + bvec2: 8, + bvec3: 12, + bvec4: 16, + mat2: 16 * 2, + mat3: 16 * 3, + mat4: 16 * 4, + }; + /** + * logic originally from here: https://github.com/sketchpunk/FunWithWebGL2/blob/master/lesson_022/Shaders.js + * rewrote it, but this was a great starting point to get a solid understanding of whats going on :) + * @ignore + * @param uniformData + */ + function createUBOElements(uniformData) { + var uboElements = uniformData.map(function (data) { + return ({ + data: data, + offset: 0, + dataLen: 0, + dirty: 0 + }); + }); + var size = 0; + var chunkSize = 0; + var offset = 0; + for (var i = 0; i < uboElements.length; i++) { + var uboElement = uboElements[i]; + size = GLSL_TO_STD40_SIZE[uboElement.data.type]; + if (uboElement.data.size > 1) { + size = Math.max(size, 16) * uboElement.data.size; + } + uboElement.dataLen = size; + // add some size offset.. + // must align to the nearest 16 bytes or internally nearest round size + if (chunkSize % size !== 0 && chunkSize < 16) { + // diff required to line up.. + var lineUpValue = (chunkSize % size) % 16; + chunkSize += lineUpValue; + offset += lineUpValue; + } + if ((chunkSize + size) > 16) { + offset = Math.ceil(offset / 16) * 16; + uboElement.offset = offset; + offset += size; + chunkSize = size; + } + else { + uboElement.offset = offset; + chunkSize += size; + offset += size; + } + } + offset = Math.ceil(offset / 16) * 16; + return { uboElements: uboElements, size: offset }; + } + function getUBOData(uniforms, uniformData) { + var usedUniformDatas = []; + // build.. + for (var i in uniforms) { + if (uniformData[i]) { + usedUniformDatas.push(uniformData[i]); + } + } + // sort them out by index! + usedUniformDatas.sort(function (a, b) { return a.index - b.index; }); + return usedUniformDatas; + } + function generateUniformBufferSync(group, uniformData) { + if (!group.autoManage) { + // if the group is nott automatically managed, we don't need to generate a special function for it... + return { size: 0, syncFunc: uboUpdate }; + } + var usedUniformDatas = getUBOData(group.uniforms, uniformData); + var _a = createUBOElements(usedUniformDatas), uboElements = _a.uboElements, size = _a.size; + var funcFragments = ["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "]; + for (var i = 0; i < uboElements.length; i++) { + var uboElement = uboElements[i]; + var uniform = group.uniforms[uboElement.data.name]; + var name = uboElement.data.name; + var parsed = false; + for (var j = 0; j < uniformParsers.length; j++) { + var uniformParser = uniformParsers[j]; + if (uniformParser.codeUbo && uniformParser.test(uboElement.data, uniform)) { + funcFragments.push("offset = " + uboElement.offset / 4 + ";", uniformParsers[j].codeUbo(uboElement.data.name, uniform)); + parsed = true; + break; + } + } + if (!parsed) { + if (uboElement.data.size > 1) { + var size_1 = mapSize(uboElement.data.type); + var rowSize = Math.max(GLSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1); + var elementSize = size_1 / rowSize; + var remainder = (4 - (elementSize % 4)) % 4; + funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n\n t = 0;\n\n for(var i=0; i < " + uboElement.data.size * rowSize + "; i++)\n {\n for(var j = 0; j < " + elementSize + "; j++)\n {\n data[offset++] = v[t++];\n }\n offset += " + remainder + ";\n }\n\n "); + } + else { + var template = UBO_TO_SINGLE_SETTERS[uboElement.data.type]; + funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n " + template + ";\n "); + } + } + } + funcFragments.push("\n renderer.buffer.update(buffer);\n "); + return { + size: size, + // eslint-disable-next-line no-new-func + syncFunc: new Function('ud', 'uv', 'renderer', 'syncData', 'buffer', funcFragments.join('\n')) + }; + } + + /** + * @private + */ + var IGLUniformData = /** @class */ (function () { + function IGLUniformData() { + } + return IGLUniformData; + }()); + /** + * Helper class to create a WebGL Program + * @memberof PIXI + */ + var GLProgram = /** @class */ (function () { + /** + * Makes a new Pixi program. + * @param program - webgl program + * @param uniformData - uniforms + */ + function GLProgram(program, uniformData) { + this.program = program; + this.uniformData = uniformData; + this.uniformGroups = {}; + this.uniformDirtyGroups = {}; + this.uniformBufferBindings = {}; + } + /** Destroys this program. */ + GLProgram.prototype.destroy = function () { + this.uniformData = null; + this.uniformGroups = null; + this.uniformDirtyGroups = null; + this.uniformBufferBindings = null; + this.program = null; + }; + return GLProgram; + }()); + + /** + * returns the attribute data from the program + * @private + * @param {WebGLProgram} [program] - the WebGL program + * @param {WebGLRenderingContext} [gl] - the WebGL context + * @returns {object} the attribute data for this program + */ + function getAttributeData(program, gl) { + var attributes = {}; + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (var i = 0; i < totalAttributes; i++) { + var attribData = gl.getActiveAttrib(program, i); + if (attribData.name.indexOf('gl_') === 0) { + continue; + } + var type = mapType(gl, attribData.type); + var data = { + type: type, + name: attribData.name, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + }; + attributes[attribData.name] = data; + } + return attributes; + } + + /** + * returns the uniform data from the program + * @private + * @param program - the webgl program + * @param gl - the WebGL context + * @returns {object} the uniform data for this program + */ + function getUniformData(program, gl) { + var uniforms = {}; + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (var i = 0; i < totalUniforms; i++) { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]$/, ''); + var isArray = !!(uniformData.name.match(/\[.*?\]$/)); + var type = mapType(gl, uniformData.type); + uniforms[name] = { + name: name, + index: i, + type: type, + size: uniformData.size, + isArray: isArray, + value: defaultValue(type, uniformData.size), + }; + } + return uniforms; + } + + /** + * generates a WebGL Program object from a high level Pixi Program. + * @param gl - a rendering context on which to generate the program + * @param program - the high level Pixi Program. + */ + function generateProgram(gl, program) { + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragmentSrc); + var webGLProgram = gl.createProgram(); + gl.attachShader(webGLProgram, glVertShader); + gl.attachShader(webGLProgram, glFragShader); + gl.linkProgram(webGLProgram); + if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) { + logProgramError(gl, webGLProgram, glVertShader, glFragShader); + } + program.attributeData = getAttributeData(webGLProgram, gl); + program.uniformData = getUniformData(webGLProgram, gl); + // GLSL 1.00: bind attributes sorted by name in ascending order + // GLSL 3.00: don't change the attribute locations that where chosen by the compiler + // or assigned by the layout specifier in the shader source code + if (!(/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m).test(program.vertexSrc)) { + var keys = Object.keys(program.attributeData); + keys.sort(function (a, b) { return (a > b) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow + for (var i = 0; i < keys.length; i++) { + program.attributeData[keys[i]].location = i; + gl.bindAttribLocation(webGLProgram, i, keys[i]); + } + gl.linkProgram(webGLProgram); + } + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + var uniformData = {}; + for (var i in program.uniformData) { + var data = program.uniformData[i]; + uniformData[i] = { + location: gl.getUniformLocation(webGLProgram, i), + value: defaultValue(data.type, data.size), + }; + } + var glProgram = new GLProgram(webGLProgram, uniformData); + return glProgram; + } + + var UID = 0; + // default sync data so we don't create a new one each time! + var defaultSyncData = { textureCount: 0, uboCount: 0 }; + /** + * System plugin to the renderer to manage shaders. + * @memberof PIXI + */ + var ShaderSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ShaderSystem(renderer) { + this.destroyed = false; + this.renderer = renderer; + // Validation check that this environment support `new Function` + this.systemCheck(); + this.gl = null; + this.shader = null; + this.program = null; + this.cache = {}; + this._uboCache = {}; + this.id = UID++; + } + /** + * Overrideable function by `@pixi/unsafe-eval` to silence + * throwing an error if platform doesn't support unsafe-evals. + * @private + */ + ShaderSystem.prototype.systemCheck = function () { + if (!unsafeEvalSupported()) { + throw new Error('Current environment does not allow unsafe-eval, ' + + 'please use @pixi/unsafe-eval module to enable support.'); + } + }; + ShaderSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.reset(); + }; + /** + * Changes the current shader to the one given in parameter. + * @param shader - the new shader + * @param dontSync - false if the shader should automatically sync its uniforms. + * @returns the glProgram that belongs to the shader. + */ + ShaderSystem.prototype.bind = function (shader, dontSync) { + shader.uniforms.globals = this.renderer.globalUniforms; + var program = shader.program; + var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateProgram(shader); + this.shader = shader; + // TODO - some current Pixi plugins bypass this.. so it not safe to use yet.. + if (this.program !== program) { + this.program = program; + this.gl.useProgram(glProgram.program); + } + if (!dontSync) { + defaultSyncData.textureCount = 0; + defaultSyncData.uboCount = 0; + this.syncUniformGroup(shader.uniformGroup, defaultSyncData); + } + return glProgram; + }; + /** + * Uploads the uniforms values to the currently bound shader. + * @param uniforms - the uniforms values that be applied to the current shader + */ + ShaderSystem.prototype.setUniforms = function (uniforms) { + var shader = this.shader.program; + var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; + shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); + }; + /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ + /** + * Syncs uniforms on the group + * @param group - the uniform group to sync + * @param syncData - this is data that is passed to the sync function and any nested sync functions + */ + ShaderSystem.prototype.syncUniformGroup = function (group, syncData) { + var glProgram = this.getGlProgram(); + if (!group.static || group.dirtyId !== glProgram.uniformDirtyGroups[group.id]) { + glProgram.uniformDirtyGroups[group.id] = group.dirtyId; + this.syncUniforms(group, glProgram, syncData); + } + }; + /** + * Overrideable by the @pixi/unsafe-eval package to use static syncUniforms instead. + * @param group + * @param glProgram + * @param syncData + */ + ShaderSystem.prototype.syncUniforms = function (group, glProgram, syncData) { + var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData); + }; + ShaderSystem.prototype.createSyncGroups = function (group) { + var id = this.getSignature(group, this.shader.program.uniformData, 'u'); + if (!this.cache[id]) { + this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); + } + group.syncUniforms[this.shader.program.id] = this.cache[id]; + return group.syncUniforms[this.shader.program.id]; + }; + /** + * Syncs uniform buffers + * @param group - the uniform buffer group to sync + * @param name - the name of the uniform buffer + */ + ShaderSystem.prototype.syncUniformBufferGroup = function (group, name) { + var glProgram = this.getGlProgram(); + if (!group.static || group.dirtyId !== 0 || !glProgram.uniformGroups[group.id]) { + group.dirtyId = 0; + var syncFunc = glProgram.uniformGroups[group.id] + || this.createSyncBufferGroup(group, glProgram, name); + // TODO wrap update in a cache?? + group.buffer.update(); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, defaultSyncData, group.buffer); + } + this.renderer.buffer.bindBufferBase(group.buffer, glProgram.uniformBufferBindings[name]); + }; + /** + * Will create a function that uploads a uniform buffer using the STD140 standard. + * The upload function will then be cached for future calls + * If a group is manually managed, then a simple upload function is generated + * @param group - the uniform buffer group to sync + * @param glProgram - the gl program to attach the uniform bindings to + * @param name - the name of the uniform buffer (must exist on the shader) + */ + ShaderSystem.prototype.createSyncBufferGroup = function (group, glProgram, name) { + var gl = this.renderer.gl; + this.renderer.buffer.bind(group.buffer); + // bind them... + var uniformBlockIndex = this.gl.getUniformBlockIndex(glProgram.program, name); + glProgram.uniformBufferBindings[name] = this.shader.uniformBindCount; + gl.uniformBlockBinding(glProgram.program, uniformBlockIndex, this.shader.uniformBindCount); + this.shader.uniformBindCount++; + var id = this.getSignature(group, this.shader.program.uniformData, 'ubo'); + var uboData = this._uboCache[id]; + if (!uboData) { + uboData = this._uboCache[id] = generateUniformBufferSync(group, this.shader.program.uniformData); + } + if (group.autoManage) { + var data = new Float32Array(uboData.size / 4); + group.buffer.update(data); + } + glProgram.uniformGroups[group.id] = uboData.syncFunc; + return glProgram.uniformGroups[group.id]; + }; + /** + * Takes a uniform group and data and generates a unique signature for them. + * @param group - The uniform group to get signature of + * @param group.uniforms + * @param uniformData - Uniform information generated by the shader + * @param preFix + * @returns Unique signature of the uniform group + */ + ShaderSystem.prototype.getSignature = function (group, uniformData, preFix) { + var uniforms = group.uniforms; + var strings = [preFix + "-"]; + for (var i in uniforms) { + strings.push(i); + if (uniformData[i]) { + strings.push(uniformData[i].type); + } + } + return strings.join('-'); + }; + /** + * Returns the underlying GLShade rof the currently bound shader. + * + * This can be handy for when you to have a little more control over the setting of your uniforms. + * @returns The glProgram for the currently bound Shader for this context + */ + ShaderSystem.prototype.getGlProgram = function () { + if (this.shader) { + return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; + } + return null; + }; + /** + * Generates a glProgram version of the Shader provided. + * @param shader - The shader that the glProgram will be based on. + * @returns A shiny new glProgram! + */ + ShaderSystem.prototype.generateProgram = function (shader) { + var gl = this.gl; + var program = shader.program; + var glProgram = generateProgram(gl, program); + program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; + return glProgram; + }; + /** Resets ShaderSystem state, does not affect WebGL state. */ + ShaderSystem.prototype.reset = function () { + this.program = null; + this.shader = null; + }; + /** Destroys this System and removes all its textures. */ + ShaderSystem.prototype.destroy = function () { + this.renderer = null; + // TODO implement destroy method for ShaderSystem + this.destroyed = true; + }; + return ShaderSystem; + }()); + + /** + * Maps gl blend combinations to WebGL. + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {number[][]} [array=[]] - The array to output into. + * @returns {number[][]} Mapped modes. + */ + function mapWebGLBlendModesToPixi(gl, array) { + if (array === void 0) { array = []; } + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[exports.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; + array[exports.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.NONE] = [0, 0]; + // not-premultiplied blend modes + array[exports.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; + array[exports.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + // composite operations + array[exports.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; + array[exports.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; + array[exports.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; + array[exports.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; + array[exports.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; + array[exports.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + // SUBTRACT from flash + array[exports.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; + return array; + } + + var BLEND = 0; + var OFFSET = 1; + var CULLING = 2; + var DEPTH_TEST = 3; + var WINDING = 4; + var DEPTH_MASK = 5; + /** + * System plugin to the renderer to manage WebGL state machines. + * @memberof PIXI + */ + var StateSystem = /** @class */ (function () { + function StateSystem() { + this.gl = null; + this.stateId = 0; + this.polygonOffset = 0; + this.blendMode = exports.BLEND_MODES.NONE; + this._blendEq = false; + // map functions for when we set state.. + this.map = []; + this.map[BLEND] = this.setBlend; + this.map[OFFSET] = this.setOffset; + this.map[CULLING] = this.setCullFace; + this.map[DEPTH_TEST] = this.setDepthTest; + this.map[WINDING] = this.setFrontFace; + this.map[DEPTH_MASK] = this.setDepthMask; + this.checks = []; + this.defaultState = new State(); + this.defaultState.blend = true; + } + StateSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.blendModes = mapWebGLBlendModesToPixi(gl); + this.set(this.defaultState); + this.reset(); + }; + /** + * Sets the current state + * @param {*} state - The state to set. + */ + StateSystem.prototype.set = function (state) { + state = state || this.defaultState; + // TODO maybe to an object check? ( this.state === state )? + if (this.stateId !== state.data) { + var diff = this.stateId ^ state.data; + var i = 0; + // order from least to most common + while (diff) { + if (diff & 1) { + // state change! + this.map[i].call(this, !!(state.data & (1 << i))); + } + diff = diff >> 1; + i++; + } + this.stateId = state.data; + } + // based on the above settings we check for specific modes.. + // for example if blend is active we check and set the blend modes + // or of polygon offset is active we check the poly depth. + for (var i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); + } + }; + /** + * Sets the state, when previous state is unknown. + * @param {*} state - The state to set + */ + StateSystem.prototype.forceState = function (state) { + state = state || this.defaultState; + for (var i = 0; i < this.map.length; i++) { + this.map[i].call(this, !!(state.data & (1 << i))); + } + for (var i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); + } + this.stateId = state.data; + }; + /** + * Sets whether to enable or disable blending. + * @param value - Turn on or off WebGl blending. + */ + StateSystem.prototype.setBlend = function (value) { + this.updateCheck(StateSystem.checkBlendMode, value); + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + /** + * Sets whether to enable or disable polygon offset fill. + * @param value - Turn on or off webgl polygon offset testing. + */ + StateSystem.prototype.setOffset = function (value) { + this.updateCheck(StateSystem.checkPolygonOffset, value); + this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL); + }; + /** + * Sets whether to enable or disable depth test. + * @param value - Turn on or off webgl depth testing. + */ + StateSystem.prototype.setDepthTest = function (value) { + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + /** + * Sets whether to enable or disable depth mask. + * @param value - Turn on or off webgl depth mask. + */ + StateSystem.prototype.setDepthMask = function (value) { + this.gl.depthMask(value); + }; + /** + * Sets whether to enable or disable cull face. + * @param {boolean} value - Turn on or off webgl cull face. + */ + StateSystem.prototype.setCullFace = function (value) { + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + /** + * Sets the gl front face. + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + StateSystem.prototype.setFrontFace = function (value) { + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + /** + * Sets the blend mode. + * @param {number} value - The blend mode to set to. + */ + StateSystem.prototype.setBlendMode = function (value) { + if (value === this.blendMode) { + return; + } + this.blendMode = value; + var mode = this.blendModes[value]; + var gl = this.gl; + if (mode.length === 2) { + gl.blendFunc(mode[0], mode[1]); + } + else { + gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + if (mode.length === 6) { + this._blendEq = true; + gl.blendEquationSeparate(mode[4], mode[5]); + } + else if (this._blendEq) { + this._blendEq = false; + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + } + }; + /** + * Sets the polygon offset. + * @param {number} value - the polygon offset + * @param {number} scale - the polygon offset scale + */ + StateSystem.prototype.setPolygonOffset = function (value, scale) { + this.gl.polygonOffset(value, scale); + }; + // used + /** Resets all the logic and disables the VAOs. */ + StateSystem.prototype.reset = function () { + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + this.forceState(this.defaultState); + this._blendEq = true; + this.blendMode = -1; + this.setBlendMode(0); + }; + /** + * Checks to see which updates should be checked based on which settings have been activated. + * + * For example, if blend is enabled then we should check the blend modes each time the state is changed + * or if polygon fill is activated then we need to check if the polygon offset changes. + * The idea is that we only check what we have too. + * @param func - the checking function to add or remove + * @param value - should the check function be added or removed. + */ + StateSystem.prototype.updateCheck = function (func, value) { + var index = this.checks.indexOf(func); + if (value && index === -1) { + this.checks.push(func); + } + else if (!value && index !== -1) { + this.checks.splice(index, 1); + } + }; + /** + * A private little wrapper function that we call to check the blend mode. + * @param system - the System to perform the state check on + * @param state - the state that the blendMode will pulled from + */ + StateSystem.checkBlendMode = function (system, state) { + system.setBlendMode(state.blendMode); + }; + /** + * A private little wrapper function that we call to check the polygon offset. + * @param system - the System to perform the state check on + * @param state - the state that the blendMode will pulled from + */ + StateSystem.checkPolygonOffset = function (system, state) { + system.setPolygonOffset(1, state.polygonOffset); + }; + /** + * @ignore + */ + StateSystem.prototype.destroy = function () { + this.gl = null; + }; + return StateSystem; + }()); + + /** + * System plugin to the renderer to manage texture garbage collection on the GPU, + * ensuring that it does not get clogged up with textures that are no longer being used. + * @memberof PIXI + */ + var TextureGCSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function TextureGCSystem(renderer) { + this.renderer = renderer; + this.count = 0; + this.checkCount = 0; + this.maxIdle = settings$1.GC_MAX_IDLE; + this.checkCountMax = settings$1.GC_MAX_CHECK_COUNT; + this.mode = settings$1.GC_MODE; + } + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + TextureGCSystem.prototype.postrender = function () { + if (!this.renderer.renderingToScreen) { + return; + } + this.count++; + if (this.mode === exports.GC_MODES.MANUAL) { + return; + } + this.checkCount++; + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + this.run(); + } + }; + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + TextureGCSystem.prototype.run = function () { + var tm = this.renderer.texture; + var managedTextures = tm.managedTextures; + var wasRemoved = false; + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + // only supports non generated textures at the moment! + if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + if (wasRemoved) { + var j = 0; + for (var i = 0; i < managedTextures.length; i++) { + if (managedTextures[i] !== null) { + managedTextures[j++] = managedTextures[i]; + } + } + managedTextures.length = j; + } + }; + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + TextureGCSystem.prototype.unload = function (displayObject) { + var tm = this.renderer.texture; + var texture = displayObject._texture; + // only destroy non generated textures + if (texture && !texture.framebuffer) { + tm.destroyTexture(texture); + } + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + TextureGCSystem.prototype.destroy = function () { + this.renderer = null; + }; + return TextureGCSystem; + }()); + + /** + * Returns a lookup table that maps each type-format pair to a compatible internal format. + * @memberof PIXI + * @function mapTypeAndFormatToInternalFormat + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @returns Lookup table. + */ + function mapTypeAndFormatToInternalFormat(gl) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; + var table; + if ('WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext) { + table = (_a = {}, + _a[exports.TYPES.UNSIGNED_BYTE] = (_b = {}, + _b[exports.FORMATS.RGBA] = gl.RGBA8, + _b[exports.FORMATS.RGB] = gl.RGB8, + _b[exports.FORMATS.RG] = gl.RG8, + _b[exports.FORMATS.RED] = gl.R8, + _b[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8UI, + _b[exports.FORMATS.RGB_INTEGER] = gl.RGB8UI, + _b[exports.FORMATS.RG_INTEGER] = gl.RG8UI, + _b[exports.FORMATS.RED_INTEGER] = gl.R8UI, + _b[exports.FORMATS.ALPHA] = gl.ALPHA, + _b[exports.FORMATS.LUMINANCE] = gl.LUMINANCE, + _b[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA, + _b), + _a[exports.TYPES.BYTE] = (_c = {}, + _c[exports.FORMATS.RGBA] = gl.RGBA8_SNORM, + _c[exports.FORMATS.RGB] = gl.RGB8_SNORM, + _c[exports.FORMATS.RG] = gl.RG8_SNORM, + _c[exports.FORMATS.RED] = gl.R8_SNORM, + _c[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8I, + _c[exports.FORMATS.RGB_INTEGER] = gl.RGB8I, + _c[exports.FORMATS.RG_INTEGER] = gl.RG8I, + _c[exports.FORMATS.RED_INTEGER] = gl.R8I, + _c), + _a[exports.TYPES.UNSIGNED_SHORT] = (_d = {}, + _d[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16UI, + _d[exports.FORMATS.RGB_INTEGER] = gl.RGB16UI, + _d[exports.FORMATS.RG_INTEGER] = gl.RG16UI, + _d[exports.FORMATS.RED_INTEGER] = gl.R16UI, + _d[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT16, + _d), + _a[exports.TYPES.SHORT] = (_e = {}, + _e[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16I, + _e[exports.FORMATS.RGB_INTEGER] = gl.RGB16I, + _e[exports.FORMATS.RG_INTEGER] = gl.RG16I, + _e[exports.FORMATS.RED_INTEGER] = gl.R16I, + _e), + _a[exports.TYPES.UNSIGNED_INT] = (_f = {}, + _f[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32UI, + _f[exports.FORMATS.RGB_INTEGER] = gl.RGB32UI, + _f[exports.FORMATS.RG_INTEGER] = gl.RG32UI, + _f[exports.FORMATS.RED_INTEGER] = gl.R32UI, + _f[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT24, + _f), + _a[exports.TYPES.INT] = (_g = {}, + _g[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32I, + _g[exports.FORMATS.RGB_INTEGER] = gl.RGB32I, + _g[exports.FORMATS.RG_INTEGER] = gl.RG32I, + _g[exports.FORMATS.RED_INTEGER] = gl.R32I, + _g), + _a[exports.TYPES.FLOAT] = (_h = {}, + _h[exports.FORMATS.RGBA] = gl.RGBA32F, + _h[exports.FORMATS.RGB] = gl.RGB32F, + _h[exports.FORMATS.RG] = gl.RG32F, + _h[exports.FORMATS.RED] = gl.R32F, + _h[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT32F, + _h), + _a[exports.TYPES.HALF_FLOAT] = (_j = {}, + _j[exports.FORMATS.RGBA] = gl.RGBA16F, + _j[exports.FORMATS.RGB] = gl.RGB16F, + _j[exports.FORMATS.RG] = gl.RG16F, + _j[exports.FORMATS.RED] = gl.R16F, + _j), + _a[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_k = {}, + _k[exports.FORMATS.RGB] = gl.RGB565, + _k), + _a[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_l = {}, + _l[exports.FORMATS.RGBA] = gl.RGBA4, + _l), + _a[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_m = {}, + _m[exports.FORMATS.RGBA] = gl.RGB5_A1, + _m), + _a[exports.TYPES.UNSIGNED_INT_2_10_10_10_REV] = (_o = {}, + _o[exports.FORMATS.RGBA] = gl.RGB10_A2, + _o[exports.FORMATS.RGBA_INTEGER] = gl.RGB10_A2UI, + _o), + _a[exports.TYPES.UNSIGNED_INT_10F_11F_11F_REV] = (_p = {}, + _p[exports.FORMATS.RGB] = gl.R11F_G11F_B10F, + _p), + _a[exports.TYPES.UNSIGNED_INT_5_9_9_9_REV] = (_q = {}, + _q[exports.FORMATS.RGB] = gl.RGB9_E5, + _q), + _a[exports.TYPES.UNSIGNED_INT_24_8] = (_r = {}, + _r[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH24_STENCIL8, + _r), + _a[exports.TYPES.FLOAT_32_UNSIGNED_INT_24_8_REV] = (_s = {}, + _s[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH32F_STENCIL8, + _s), + _a); + } + else { + table = (_t = {}, + _t[exports.TYPES.UNSIGNED_BYTE] = (_u = {}, + _u[exports.FORMATS.RGBA] = gl.RGBA, + _u[exports.FORMATS.RGB] = gl.RGB, + _u[exports.FORMATS.ALPHA] = gl.ALPHA, + _u[exports.FORMATS.LUMINANCE] = gl.LUMINANCE, + _u[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA, + _u), + _t[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_v = {}, + _v[exports.FORMATS.RGB] = gl.RGB, + _v), + _t[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_w = {}, + _w[exports.FORMATS.RGBA] = gl.RGBA, + _w), + _t[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_x = {}, + _x[exports.FORMATS.RGBA] = gl.RGBA, + _x), + _t); + } + return table; + } + + /** + * Internal texture for WebGL context. + * @memberof PIXI + */ + var GLTexture = /** @class */ (function () { + function GLTexture(texture) { + this.texture = texture; + this.width = -1; + this.height = -1; + this.dirtyId = -1; + this.dirtyStyleId = -1; + this.mipmap = false; + this.wrapMode = 33071; + this.type = exports.TYPES.UNSIGNED_BYTE; + this.internalFormat = exports.FORMATS.RGBA; + this.samplerType = 0; + } + return GLTexture; + }()); + + /** + * System plugin to the renderer to manage textures. + * @memberof PIXI + */ + var TextureSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this system works for. + */ + function TextureSystem(renderer) { + this.renderer = renderer; + // TODO set to max textures... + this.boundTextures = []; + this.currentLocation = -1; + this.managedTextures = []; + this._unknownBoundTextures = false; + this.unknownTexture = new BaseTexture(); + this.hasIntegerTextures = false; + } + /** Sets up the renderer context and necessary buffers. */ + TextureSystem.prototype.contextChange = function () { + var gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.webGLVersion = this.renderer.context.webGLVersion; + this.internalFormats = mapTypeAndFormatToInternalFormat(gl); + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.boundTextures.length = maxTextures; + for (var i = 0; i < maxTextures; i++) { + this.boundTextures[i] = null; + } + // TODO move this.. to a nice make empty textures class.. + this.emptyTextures = {}; + var emptyTexture2D = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; + this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); + for (var i = 0; i < 6; i++) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + } + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + for (var i = 0; i < this.boundTextures.length; i++) { + this.bind(null, i); + } + }; + /** + * Bind a texture to a specific location + * + * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)` + * @param texture - Texture to bind + * @param [location=0] - Location to bind at + */ + TextureSystem.prototype.bind = function (texture, location) { + if (location === void 0) { location = 0; } + var gl = this.gl; + texture = texture === null || texture === void 0 ? void 0 : texture.castToBaseTexture(); + // cannot bind partial texture + // TODO: report a warning + if (texture && texture.valid && !texture.parentTextureArray) { + texture.touched = this.renderer.textureGC.count; + var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + if (this.boundTextures[location] !== texture) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(texture.target, glTexture.texture); + } + if (glTexture.dirtyId !== texture.dirtyId) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + this.updateTexture(texture); + } + this.boundTextures[location] = texture; + } + else { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); + this.boundTextures[location] = null; + } + }; + /** Resets texture location and bound textures Actual `bind(null, i)` calls will be performed at next `unbind()` call */ + TextureSystem.prototype.reset = function () { + this._unknownBoundTextures = true; + this.hasIntegerTextures = false; + this.currentLocation = -1; + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.unknownTexture; + } + }; + /** + * Unbind a texture. + * @param texture - Texture to bind + */ + TextureSystem.prototype.unbind = function (texture) { + var _a = this, gl = _a.gl, boundTextures = _a.boundTextures; + if (this._unknownBoundTextures) { + this._unknownBoundTextures = false; + // someone changed webGL state, + // we have to be sure that our texture does not appear in multi-texture renderer samplers + for (var i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === this.unknownTexture) { + this.bind(null, i); + } + } + } + for (var i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === texture) { + if (this.currentLocation !== i) { + gl.activeTexture(gl.TEXTURE0 + i); + this.currentLocation = i; + } + gl.bindTexture(texture.target, this.emptyTextures[texture.target].texture); + boundTextures[i] = null; + } + } + }; + /** + * Ensures that current boundTextures all have FLOAT sampler type, + * see {@link PIXI.SAMPLER_TYPES} for explanation. + * @param maxTextures - number of locations to check + */ + TextureSystem.prototype.ensureSamplerType = function (maxTextures) { + var _a = this, boundTextures = _a.boundTextures, hasIntegerTextures = _a.hasIntegerTextures, CONTEXT_UID = _a.CONTEXT_UID; + if (!hasIntegerTextures) { + return; + } + for (var i = maxTextures - 1; i >= 0; --i) { + var tex = boundTextures[i]; + if (tex) { + var glTexture = tex._glTextures[CONTEXT_UID]; + if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) { + this.renderer.texture.unbind(tex); + } + } + } + }; + /** + * Initialize a texture + * @private + * @param texture - Texture to initialize + */ + TextureSystem.prototype.initTexture = function (texture) { + var glTexture = new GLTexture(this.gl.createTexture()); + // guarantee an update.. + glTexture.dirtyId = -1; + texture._glTextures[this.CONTEXT_UID] = glTexture; + this.managedTextures.push(texture); + texture.on('dispose', this.destroyTexture, this); + return glTexture; + }; + TextureSystem.prototype.initTextureType = function (texture, glTexture) { + var _a, _b; + glTexture.internalFormat = (_b = (_a = this.internalFormats[texture.type]) === null || _a === void 0 ? void 0 : _a[texture.format]) !== null && _b !== void 0 ? _b : texture.format; + if (this.webGLVersion === 2 && texture.type === exports.TYPES.HALF_FLOAT) { + // TYPES.HALF_FLOAT is WebGL1 HALF_FLOAT_OES + // we have to convert it to WebGL HALF_FLOAT + glTexture.type = this.gl.HALF_FLOAT; + } + else { + glTexture.type = texture.type; + } + }; + /** + * Update a texture + * @private + * @param {PIXI.BaseTexture} texture - Texture to initialize + */ + TextureSystem.prototype.updateTexture = function (texture) { + var glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + var renderer = this.renderer; + this.initTextureType(texture, glTexture); + if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) { + // texture is uploaded, dont do anything! + if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) { + this.hasIntegerTextures = true; + } + } + else { + // default, renderTexture-like logic + var width = texture.realWidth; + var height = texture.realHeight; + var gl = renderer.gl; + if (glTexture.width !== width + || glTexture.height !== height + || glTexture.dirtyId < 0) { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null); + } + } + // lets only update what changes.. + if (texture.dirtyStyleId !== glTexture.dirtyStyleId) { + this.updateTextureStyle(texture); + } + glTexture.dirtyId = texture.dirtyId; + }; + /** + * Deletes the texture from WebGL + * @private + * @param texture - the texture to destroy + * @param [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + TextureSystem.prototype.destroyTexture = function (texture, skipRemove) { + var gl = this.gl; + texture = texture.castToBaseTexture(); + if (texture._glTextures[this.CONTEXT_UID]) { + this.unbind(texture); + gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); + texture.off('dispose', this.destroyTexture, this); + delete texture._glTextures[this.CONTEXT_UID]; + if (!skipRemove) { + var i = this.managedTextures.indexOf(texture); + if (i !== -1) { + removeItems(this.managedTextures, i, 1); + } + } + } + }; + /** + * Update texture style such as mipmap flag + * @private + * @param {PIXI.BaseTexture} texture - Texture to update + */ + TextureSystem.prototype.updateTextureStyle = function (texture) { + var glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + if ((texture.mipmap === exports.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) { + glTexture.mipmap = false; + } + else { + glTexture.mipmap = texture.mipmap >= 1; + } + if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) { + glTexture.wrapMode = exports.WRAP_MODES.CLAMP; + } + else { + glTexture.wrapMode = texture.wrapMode; + } + if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) { ; } + else { + this.setStyle(texture, glTexture); + } + glTexture.dirtyStyleId = texture.dirtyStyleId; + }; + /** + * Set style for texture + * @private + * @param texture - Texture to update + * @param glTexture + */ + TextureSystem.prototype.setStyle = function (texture, glTexture) { + var gl = this.gl; + if (glTexture.mipmap && texture.mipmap !== exports.MIPMAP_MODES.ON_MANUAL) { + gl.generateMipmap(texture.target); + } + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); + if (glTexture.mipmap) { + /* eslint-disable max-len */ + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; + if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === exports.SCALE_MODES.LINEAR) { + var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); + gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); + } + } + else { + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + } + gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + }; + TextureSystem.prototype.destroy = function () { + this.renderer = null; + }; + return TextureSystem; + }()); + + var _systems = { + __proto__: null, + FilterSystem: FilterSystem, + BatchSystem: BatchSystem, + ContextSystem: ContextSystem, + FramebufferSystem: FramebufferSystem, + GeometrySystem: GeometrySystem, + MaskSystem: MaskSystem, + ScissorSystem: ScissorSystem, + StencilSystem: StencilSystem, + ProjectionSystem: ProjectionSystem, + RenderTextureSystem: RenderTextureSystem, + ShaderSystem: ShaderSystem, + StateSystem: StateSystem, + TextureGCSystem: TextureGCSystem, + TextureSystem: TextureSystem + }; + + var tempMatrix = new Matrix(); + /** + * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. + * @abstract + * @class + * @extends PIXI.utils.EventEmitter + * @memberof PIXI + */ + var AbstractRenderer = /** @class */ (function (_super) { + __extends$i(AbstractRenderer, _super); + /** + * @param type - The renderer type. + * @param [options] - The optional renderer parameters. + * @param {number} [options.width=800] - The width of the screen. + * @param {number} [options.height=600] - The height of the screen. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. + * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the WebGL context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). + */ + function AbstractRenderer(type, options) { + if (type === void 0) { type = exports.RENDERER_TYPE.UNKNOWN; } + var _this = _super.call(this) || this; + // Add the default render options + options = Object.assign({}, settings$1.RENDER_OPTIONS, options); + /** + * The supplied constructor options. + * @member {object} + * @readonly + */ + _this.options = options; + /** + * The type of the renderer. + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = type; + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight). + * + * Its safe to use as filterArea or hitArea for the whole stage. + * @member {PIXI.Rectangle} + */ + _this.screen = new Rectangle(0, 0, options.width, options.height); + /** + * The canvas element that everything is drawn to. + * @member {HTMLCanvasElement} + */ + _this.view = options.view || settings$1.ADAPTER.createCanvas(); + /** + * The resolution / device pixel ratio of the renderer. + * @member {number} + * @default PIXI.settings.RESOLUTION + */ + _this.resolution = options.resolution || settings$1.RESOLUTION; + /** + * Pass-thru setting for the canvas' context `alpha` property. This is typically + * not something you need to fiddle with. If you want transparency, use `backgroundAlpha`. + * @member {boolean} + */ + _this.useContextAlpha = options.useContextAlpha; + /** + * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. + * @member {boolean} + */ + _this.autoDensity = !!options.autoDensity; + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example, if + * your game has a canvas filling background image you often don't need this set. + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + /** + * The background color as a number. + * @member {number} + * @protected + */ + _this._backgroundColor = 0x000000; + /** + * The background color as an [R, G, B, A] array. + * @member {number[]} + * @protected + */ + _this._backgroundColorRgba = [0, 0, 0, 1]; + /** + * The background color as a string. + * @member {string} + * @protected + */ + _this._backgroundColorString = '#000000'; + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + _this.backgroundAlpha = options.backgroundAlpha; + // @deprecated + if (options.transparent !== undefined) { + deprecation$1('6.0.0', 'Option transparent is deprecated, please use backgroundAlpha instead.'); + _this.useContextAlpha = options.transparent; + _this.backgroundAlpha = options.transparent ? 0 : 1; + } + /** + * The last root object that the renderer tried to render. + * @member {PIXI.DisplayObject} + * @protected + */ + _this._lastObjectRendered = null; + /** + * Collection of plugins. + * @readonly + * @member {object} + */ + _this.plugins = {}; + return _this; + } + /** + * Initialize the plugins. + * @protected + * @param {object} staticMap - The dictionary of statically saved plugins. + */ + AbstractRenderer.prototype.initPlugins = function (staticMap) { + for (var o in staticMap) { + this.plugins[o] = new (staticMap[o])(this); + } + }; + Object.defineProperty(AbstractRenderer.prototype, "width", { + /** + * Same as view.width, actual number of pixels in the canvas by horizontal. + * @member {number} + * @readonly + * @default 800 + */ + get: function () { + return this.view.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbstractRenderer.prototype, "height", { + /** + * Same as view.height, actual number of pixels in the canvas by vertical. + * @member {number} + * @readonly + * @default 600 + */ + get: function () { + return this.view.height; + }, + enumerable: false, + configurable: true + }); + /** + * Resizes the screen and canvas as close as possible to the specified width and height. + * Canvas dimensions are multiplied by resolution and rounded to the nearest integers. + * The new canvas dimensions divided by the resolution become the new screen dimensions. + * @param desiredScreenWidth - The desired width of the screen. + * @param desiredScreenHeight - The desired height of the screen. + */ + AbstractRenderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) { + this.view.width = Math.round(desiredScreenWidth * this.resolution); + this.view.height = Math.round(desiredScreenHeight * this.resolution); + var screenWidth = this.view.width / this.resolution; + var screenHeight = this.view.height / this.resolution; + this.screen.width = screenWidth; + this.screen.height = screenHeight; + if (this.autoDensity) { + this.view.style.width = screenWidth + "px"; + this.view.style.height = screenHeight + "px"; + } + /** + * Fired after view has been resized. + * @event PIXI.Renderer#resize + * @param {number} screenWidth - The new width of the screen. + * @param {number} screenHeight - The new height of the screen. + */ + this.emit('resize', screenWidth, screenHeight); + }; + /** + * @ignore + */ + AbstractRenderer.prototype.generateTexture = function (displayObject, options, resolution, region) { + if (options === void 0) { options = {}; } + // @deprecated parameters spread, use options instead + if (typeof options === 'number') { + deprecation$1('6.1.0', 'generateTexture options (scaleMode, resolution, region) are now object options.'); + options = { scaleMode: options, resolution: resolution, region: region }; + } + var manualRegion = options.region, textureOptions = __rest(options, ["region"]); + region = manualRegion || displayObject.getLocalBounds(null, true); + // minimum texture size is 1x1, 0x0 will throw an error + if (region.width === 0) + { region.width = 1; } + if (region.height === 0) + { region.height = 1; } + var renderTexture = RenderTexture.create(__assign({ width: region.width, height: region.height }, textureOptions)); + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + this.render(displayObject, { + renderTexture: renderTexture, + clear: false, + transform: tempMatrix, + skipUpdateTransform: !!displayObject.parent + }); + return renderTexture; + }; + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * @param [removeView=false] - Removes the Canvas element from the DOM. + */ + AbstractRenderer.prototype.destroy = function (removeView) { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + var thisAny = this; + // null-ing all objects, that's a tradition! + thisAny.plugins = null; + thisAny.type = exports.RENDERER_TYPE.UNKNOWN; + thisAny.view = null; + thisAny.screen = null; + thisAny._tempDisplayObjectParent = null; + thisAny.options = null; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + this._lastObjectRendered = null; + }; + Object.defineProperty(AbstractRenderer.prototype, "backgroundColor", { + /** + * The background color to fill if not transparent + * @member {number} + */ + get: function () { + return this._backgroundColor; + }, + set: function (value) { + this._backgroundColor = value; + this._backgroundColorString = hex2string(value); + hex2rgb(value, this._backgroundColorRgba); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbstractRenderer.prototype, "backgroundAlpha", { + /** + * The background color alpha. Setting this to 0 will make the canvas transparent. + * @member {number} + */ + get: function () { + return this._backgroundColorRgba[3]; + }, + set: function (value) { + this._backgroundColorRgba[3] = value; + }, + enumerable: false, + configurable: true + }); + return AbstractRenderer; + }(eventemitter3)); + + var GLBuffer = /** @class */ (function () { + function GLBuffer(buffer) { + this.buffer = buffer || null; + this.updateID = -1; + this.byteLength = -1; + this.refCount = 0; + } + return GLBuffer; + }()); + + /** + * System plugin to the renderer to manage buffers. + * + * WebGL uses Buffers as a way to store objects to the GPU. + * This system makes working with them a lot easier. + * + * Buffers are used in three main places in WebGL + * - geometry information + * - Uniform information (via uniform buffer objects - a WebGL 2 only feature) + * - Transform feedback information. (WebGL 2 only feature) + * + * This system will handle the binding of buffers to the GPU as well as uploading + * them. With this system, you never need to work directly with GPU buffers, but instead work with + * the PIXI.Buffer class. + * @class + * @memberof PIXI + */ + var BufferSystem = /** @class */ (function () { + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function BufferSystem(renderer) { + this.renderer = renderer; + this.managedBuffers = {}; + this.boundBufferBases = {}; + } + /** + * @ignore + */ + BufferSystem.prototype.destroy = function () { + this.renderer = null; + }; + /** Sets up the renderer context and necessary buffers. */ + BufferSystem.prototype.contextChange = function () { + this.disposeAll(true); + this.gl = this.renderer.gl; + // TODO fill out... + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + }; + /** + * This binds specified buffer. On first run, it will create the webGL buffers for the context too + * @param buffer - the buffer to bind to the renderer + */ + BufferSystem.prototype.bind = function (buffer) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + gl.bindBuffer(buffer.type, glBuffer.buffer); + }; + /** + * Binds an uniform buffer to at the given index. + * + * A cache is used so a buffer will not be bound again if already bound. + * @param buffer - the buffer to bind + * @param index - the base index to bind it to. + */ + BufferSystem.prototype.bindBufferBase = function (buffer, index) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + if (this.boundBufferBases[index] !== buffer) { + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + this.boundBufferBases[index] = buffer; + gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer); + } + }; + /** + * Binds a buffer whilst also binding its range. + * This will make the buffer start from the offset supplied rather than 0 when it is read. + * @param buffer - the buffer to bind + * @param index - the base index to bind at, defaults to 0 + * @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc + */ + BufferSystem.prototype.bindBufferRange = function (buffer, index, offset) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + offset = offset || 0; + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, 256); + }; + /** + * Will ensure the data in the buffer is uploaded to the GPU. + * @param {PIXI.Buffer} buffer - the buffer to update + */ + BufferSystem.prototype.update = function (buffer) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + var glBuffer = buffer._glBuffers[CONTEXT_UID]; + if (buffer._updateID === glBuffer.updateID) { + return; + } + glBuffer.updateID = buffer._updateID; + gl.bindBuffer(buffer.type, glBuffer.buffer); + if (glBuffer.byteLength >= buffer.data.byteLength) { + // offset is always zero for now! + gl.bufferSubData(buffer.type, 0, buffer.data); + } + else { + var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; + glBuffer.byteLength = buffer.data.byteLength; + gl.bufferData(buffer.type, buffer.data, drawType); + } + }; + /** + * Disposes buffer + * @param {PIXI.Buffer} buffer - buffer with data + * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray + */ + BufferSystem.prototype.dispose = function (buffer, contextLost) { + if (!this.managedBuffers[buffer.id]) { + return; + } + delete this.managedBuffers[buffer.id]; + var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; + var gl = this.gl; + buffer.disposeRunner.remove(this); + if (!glBuffer) { + return; + } + if (!contextLost) { + gl.deleteBuffer(glBuffer.buffer); + } + delete buffer._glBuffers[this.CONTEXT_UID]; + }; + /** + * dispose all WebGL resources of all managed buffers + * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls + */ + BufferSystem.prototype.disposeAll = function (contextLost) { + var all = Object.keys(this.managedBuffers); + for (var i = 0; i < all.length; i++) { + this.dispose(this.managedBuffers[all[i]], contextLost); + } + }; + /** + * creates and attaches a GLBuffer object tied to the current context. + * @param buffer + * @protected + */ + BufferSystem.prototype.createGLBuffer = function (buffer) { + var _a = this, CONTEXT_UID = _a.CONTEXT_UID, gl = _a.gl; + buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); + this.managedBuffers[buffer.id] = buffer; + buffer.disposeRunner.add(this); + return buffer._glBuffers[CONTEXT_UID]; + }; + return BufferSystem; + }()); + + /** + * The Renderer draws the scene and all its content onto a WebGL enabled canvas. + * + * This renderer should be used for browsers that support WebGL. + * + * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything! + * + * Renderer is composed of systems that manage specific tasks. The following systems are added by default + * whenever you create a renderer: + * + * | System | Description | + * | ------------------------------------ | ----------------------------------------------------------------------------- | + * | {@link PIXI.BatchSystem} | This manages object renderers that defer rendering until a flush. | + * | {@link PIXI.ContextSystem} | This manages the WebGL context and extensions. | + * | {@link PIXI.EventSystem} | This manages UI events. | + * | {@link PIXI.FilterSystem} | This manages the filtering pipeline for post-processing effects. | + * | {@link PIXI.FramebufferSystem} | This manages framebuffers, which are used for offscreen rendering. | + * | {@link PIXI.GeometrySystem} | This manages geometries & buffers, which are used to draw object meshes. | + * | {@link PIXI.MaskSystem} | This manages masking operations. | + * | {@link PIXI.ProjectionSystem} | This manages the `projectionMatrix`, used by shaders to get NDC coordinates. | + * | {@link PIXI.RenderTextureSystem} | This manages render-textures, which are an abstraction over framebuffers. | + * | {@link PIXI.ScissorSystem} | This handles scissor masking, and is used internally by {@link MaskSystem} | + * | {@link PIXI.ShaderSystem} | This manages shaders, programs that run on the GPU to calculate 'em pixels. | + * | {@link PIXI.StateSystem} | This manages the WebGL state variables like blend mode, depth testing, etc. | + * | {@link PIXI.StencilSystem} | This handles stencil masking, and is used internally by {@link MaskSystem} | + * | {@link PIXI.TextureSystem} | This manages textures and their resources on the GPU. | + * | {@link PIXI.TextureGCSystem} | This will automatically remove textures from the GPU if they are not used. | + * + * The breadth of the API surface provided by the renderer is contained within these systems. + * @memberof PIXI + */ + var Renderer = /** @class */ (function (_super) { + __extends$i(Renderer, _super); + /** + * @param [options] - The optional renderer parameters. + * @param {number} [options.width=800] - The width of the screen. + * @param {number} [options.height=600] - The height of the screen. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. + * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias. If not available natively then FXAA + * antialiasing is used. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the WebGL context. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). + * @param {string} [options.powerPreference] - Parameter passed to WebGL context, set to "high-performance" + * for devices with dual graphics card. + * @param {object} [options.context] - If WebGL context already exists, all parameters must be taken from it. + */ + function Renderer(options) { + var _this = _super.call(this, exports.RENDERER_TYPE.WEBGL, options) || this; + // the options will have been modified here in the super constructor with pixi's default settings.. + options = _this.options; + _this.gl = null; + _this.CONTEXT_UID = 0; + _this.runners = { + destroy: new Runner('destroy'), + contextChange: new Runner('contextChange'), + reset: new Runner('reset'), + update: new Runner('update'), + postrender: new Runner('postrender'), + prerender: new Runner('prerender'), + resize: new Runner('resize'), + }; + _this.runners.contextChange.add(_this); + _this.globalUniforms = new UniformGroup({ + projectionMatrix: new Matrix(), + }, true); + _this.addSystem(MaskSystem, 'mask') + .addSystem(ContextSystem, 'context') + .addSystem(StateSystem, 'state') + .addSystem(ShaderSystem, 'shader') + .addSystem(TextureSystem, 'texture') + .addSystem(BufferSystem, 'buffer') + .addSystem(GeometrySystem, 'geometry') + .addSystem(FramebufferSystem, 'framebuffer') + .addSystem(ScissorSystem, 'scissor') + .addSystem(StencilSystem, 'stencil') + .addSystem(ProjectionSystem, 'projection') + .addSystem(TextureGCSystem, 'textureGC') + .addSystem(FilterSystem, 'filter') + .addSystem(RenderTextureSystem, 'renderTexture') + .addSystem(BatchSystem, 'batch'); + _this.initPlugins(Renderer.__plugins); + _this.multisample = undefined; + /* + * The options passed in to create a new WebGL context. + */ + if (options.context) { + _this.context.initFromContext(options.context); + } + else { + _this.context.initFromOptions({ + alpha: !!_this.useContextAlpha, + antialias: options.antialias, + premultipliedAlpha: _this.useContextAlpha && _this.useContextAlpha !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference, + }); + } + _this.renderingToScreen = true; + sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); + _this.resize(_this.options.width, _this.options.height); + return _this; + } + /** + * Create renderer if WebGL is available. Overrideable + * by the **@pixi/canvas-renderer** package to allow fallback. + * throws error if WebGL is not available. + * @param options + * @private + */ + Renderer.create = function (options) { + if (isWebGLSupported()) { + return new Renderer(options); + } + throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); + }; + Renderer.prototype.contextChange = function () { + var gl = this.gl; + var samples; + if (this.context.webGLVersion === 1) { + var framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + samples = gl.getParameter(gl.SAMPLES); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + } + else { + var framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + samples = gl.getParameter(gl.SAMPLES); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer); + } + if (samples >= exports.MSAA_QUALITY.HIGH) { + this.multisample = exports.MSAA_QUALITY.HIGH; + } + else if (samples >= exports.MSAA_QUALITY.MEDIUM) { + this.multisample = exports.MSAA_QUALITY.MEDIUM; + } + else if (samples >= exports.MSAA_QUALITY.LOW) { + this.multisample = exports.MSAA_QUALITY.LOW; + } + else { + this.multisample = exports.MSAA_QUALITY.NONE; + } + }; + /** + * Add a new system to the renderer. + * @param ClassRef - Class reference + * @param name - Property name for system, if not specified + * will use a static `name` property on the class itself. This + * name will be assigned as s property on the Renderer so make + * sure it doesn't collide with properties on Renderer. + * @returns Return instance of renderer + */ + Renderer.prototype.addSystem = function (ClassRef, name) { + var system = new ClassRef(this); + if (this[name]) { + throw new Error("Whoops! The name \"" + name + "\" is already in use"); + } + this[name] = system; + for (var i in this.runners) { + this.runners[i].add(system); + } + /** + * Fired after rendering finishes. + * @event PIXI.Renderer#postrender + */ + /** + * Fired before rendering starts. + * @event PIXI.Renderer#prerender + */ + /** + * Fired when the WebGL context is set. + * @event PIXI.Renderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return this; + }; + /** + * @ignore + */ + Renderer.prototype.render = function (displayObject, options) { + var renderTexture; + var clear; + var transform; + var skipUpdateTransform; + if (options) { + if (options instanceof RenderTexture) { + deprecation$1('6.0.0', 'Renderer#render arguments changed, use options instead.'); + /* eslint-disable prefer-rest-params */ + renderTexture = options; + clear = arguments[2]; + transform = arguments[3]; + skipUpdateTransform = arguments[4]; + /* eslint-enable prefer-rest-params */ + } + else { + renderTexture = options.renderTexture; + clear = options.clear; + transform = options.transform; + skipUpdateTransform = options.skipUpdateTransform; + } + } + // can be handy to know! + this.renderingToScreen = !renderTexture; + this.runners.prerender.emit(); + this.emit('prerender'); + // apply a transform at a GPU level + this.projection.transform = transform; + // no point rendering if our context has been blown up! + if (this.context.isLost) { + return; + } + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.enableTempParent(); + displayObject.updateTransform(); + displayObject.disableTempParent(cacheParent); + // displayObject.hitArea = //TODO add a temp hit area + } + this.renderTexture.bind(renderTexture); + this.batch.currentRenderer.start(); + if (clear !== undefined ? clear : this.clearBeforeRender) { + this.renderTexture.clear(); + } + displayObject.render(this); + // apply transform.. + this.batch.currentRenderer.flush(); + if (renderTexture) { + renderTexture.baseTexture.update(); + } + this.runners.postrender.emit(); + // reset transform after render + this.projection.transform = null; + this.emit('postrender'); + }; + /** + * @override + * @ignore + */ + Renderer.prototype.generateTexture = function (displayObject, options, resolution, region) { + if (options === void 0) { options = {}; } + var renderTexture = _super.prototype.generateTexture.call(this, displayObject, options, resolution, region); + this.framebuffer.blit(); + return renderTexture; + }; + /** + * Resizes the WebGL view to the specified width and height. + * @param desiredScreenWidth - The desired width of the screen. + * @param desiredScreenHeight - The desired height of the screen. + */ + Renderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) { + _super.prototype.resize.call(this, desiredScreenWidth, desiredScreenHeight); + this.runners.resize.emit(this.screen.height, this.screen.width); + }; + /** + * Resets the WebGL state so you can render things however you fancy! + * @returns Returns itself. + */ + Renderer.prototype.reset = function () { + this.runners.reset.emit(); + return this; + }; + /** Clear the frame buffer. */ + Renderer.prototype.clear = function () { + this.renderTexture.bind(); + this.renderTexture.clear(); + }; + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * @param [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + Renderer.prototype.destroy = function (removeView) { + this.runners.destroy.emit(); + for (var r in this.runners) { + this.runners[r].destroy(); + } + // call base destroy + _super.prototype.destroy.call(this, removeView); + // TODO nullify all the managers.. + this.gl = null; + }; + Object.defineProperty(Renderer.prototype, "extract", { + /** + * Please use `plugins.extract` instead. + * @member {PIXI.Extract} extract + * @deprecated since 6.0.0 + * @readonly + */ + get: function () { + deprecation$1('6.0.0', 'Renderer#extract has been deprecated, please use Renderer#plugins.extract instead.'); + return this.plugins.extract; + }, + enumerable: false, + configurable: true + }); + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @param pluginName - The name of the plugin. + * @param ctor - The constructor function or class for the plugin. + */ + Renderer.registerPlugin = function (pluginName, ctor) { + deprecation$1('6.5.0', 'Renderer.registerPlugin() has been deprecated, please use extensions.add() instead.'); + extensions.add({ + name: pluginName, + type: exports.ExtensionType.RendererPlugin, + ref: ctor, + }); + }; + /** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @readonly + * @property {PIXI.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.Extract} extract Extract image data from renderer. + * @property {PIXI.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.ParticleRenderer} particle Renderer for ParticleContainer objects. + * @property {PIXI.Prepare} prepare Pre-render display objects. + * @property {PIXI.BatchRenderer} batch Batching of Sprite, Graphics and Mesh objects. + * @property {PIXI.TilingSpriteRenderer} tilingSprite Renderer for TilingSprite objects. + */ + Renderer.__plugins = {}; + return Renderer; + }(AbstractRenderer)); + // Handle registration of extensions + extensions.handleByMap(exports.ExtensionType.RendererPlugin, Renderer.__plugins); + + /** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by + * the browser then this function will return a canvas renderer + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. + * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1 + * @param {boolean} [options.antialias=false] - sets antialias + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this + * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise + * it is ignored. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @returns {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ + function autoDetectRenderer(options) { + return Renderer.create(options); + } + + var $defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; + + var $defaultFilterVertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; + + /** + * Default vertex shader + * @memberof PIXI + * @member {string} defaultVertex + */ + /** + * Default filter vertex shader + * @memberof PIXI + * @member {string} defaultFilterVertex + */ + // NOTE: This black magic is so that @microsoft/api-extractor does not complain! This explicitly specifies the types + // of defaultVertex, defaultFilterVertex. + var defaultVertex$1 = $defaultVertex; + var defaultFilterVertex = $defaultFilterVertex; + + /** + * Use the ISystem interface instead. + * @deprecated since 6.1.0 + * @memberof PIXI + */ + var System = /** @class */ (function () { + /** + * @param renderer - Reference to Renderer + */ + function System(renderer) { + deprecation$1('6.1.0', 'System class is deprecated, implemement ISystem interface instead.'); + this.renderer = renderer; + } + /** Destroy and don't use after this. */ + System.prototype.destroy = function () { + this.renderer = null; + }; + return System; + }()); + + /** + * Used by the batcher to draw batches. + * Each one of these contains all information required to draw a bound geometry. + * @memberof PIXI + */ + var BatchDrawCall = /** @class */ (function () { + function BatchDrawCall() { + this.texArray = null; + this.blend = 0; + this.type = exports.DRAW_MODES.TRIANGLES; + this.start = 0; + this.size = 0; + this.data = null; + } + return BatchDrawCall; + }()); + + /** + * Used by the batcher to build texture batches. + * Holds list of textures and their respective locations. + * @memberof PIXI + */ + var BatchTextureArray = /** @class */ (function () { + function BatchTextureArray() { + this.elements = []; + this.ids = []; + this.count = 0; + } + BatchTextureArray.prototype.clear = function () { + for (var i = 0; i < this.count; i++) { + this.elements[i] = null; + } + this.count = 0; + }; + return BatchTextureArray; + }()); + + /** + * Flexible wrapper around `ArrayBuffer` that also provides typed array views on demand. + * @memberof PIXI + */ + var ViewableBuffer = /** @class */ (function () { + function ViewableBuffer(sizeOrBuffer) { + if (typeof sizeOrBuffer === 'number') { + this.rawBinaryData = new ArrayBuffer(sizeOrBuffer); + } + else if (sizeOrBuffer instanceof Uint8Array) { + this.rawBinaryData = sizeOrBuffer.buffer; + } + else { + this.rawBinaryData = sizeOrBuffer; + } + this.uint32View = new Uint32Array(this.rawBinaryData); + this.float32View = new Float32Array(this.rawBinaryData); + } + Object.defineProperty(ViewableBuffer.prototype, "int8View", { + /** View on the raw binary data as a `Int8Array`. */ + get: function () { + if (!this._int8View) { + this._int8View = new Int8Array(this.rawBinaryData); + } + return this._int8View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "uint8View", { + /** View on the raw binary data as a `Uint8Array`. */ + get: function () { + if (!this._uint8View) { + this._uint8View = new Uint8Array(this.rawBinaryData); + } + return this._uint8View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "int16View", { + /** View on the raw binary data as a `Int16Array`. */ + get: function () { + if (!this._int16View) { + this._int16View = new Int16Array(this.rawBinaryData); + } + return this._int16View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "uint16View", { + /** View on the raw binary data as a `Uint16Array`. */ + get: function () { + if (!this._uint16View) { + this._uint16View = new Uint16Array(this.rawBinaryData); + } + return this._uint16View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "int32View", { + /** View on the raw binary data as a `Int32Array`. */ + get: function () { + if (!this._int32View) { + this._int32View = new Int32Array(this.rawBinaryData); + } + return this._int32View; + }, + enumerable: false, + configurable: true + }); + /** + * Returns the view of the given type. + * @param type - One of `int8`, `uint8`, `int16`, + * `uint16`, `int32`, `uint32`, and `float32`. + * @returns - typed array of given type + */ + ViewableBuffer.prototype.view = function (type) { + return this[type + "View"]; + }; + /** Destroys all buffer references. Do not use after calling this. */ + ViewableBuffer.prototype.destroy = function () { + this.rawBinaryData = null; + this._int8View = null; + this._uint8View = null; + this._int16View = null; + this._uint16View = null; + this._int32View = null; + this.uint32View = null; + this.float32View = null; + }; + ViewableBuffer.sizeOf = function (type) { + switch (type) { + case 'int8': + case 'uint8': + return 1; + case 'int16': + case 'uint16': + return 2; + case 'int32': + case 'uint32': + case 'float32': + return 4; + default: + throw new Error(type + " isn't a valid view type"); + } + }; + return ViewableBuffer; + }()); + + /** + * Renderer dedicated to drawing and batching sprites. + * + * This is the default batch renderer. It buffers objects + * with texture-based geometries and renders them in + * batches. It uploads multiple textures to the GPU to + * reduce to the number of draw calls. + * @memberof PIXI + */ + var AbstractBatchRenderer = /** @class */ (function (_super) { + __extends$i(AbstractBatchRenderer, _super); + /** + * This will hook onto the renderer's `contextChange` + * and `prerender` signals. + * @param {PIXI.Renderer} renderer - The renderer this works for. + */ + function AbstractBatchRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + _this.shaderGenerator = null; + _this.geometryClass = null; + _this.vertexSize = null; + _this.state = State.for2d(); + _this.size = settings$1.SPRITE_BATCH_SIZE * 4; + _this._vertexCount = 0; + _this._indexCount = 0; + _this._bufferedElements = []; + _this._bufferedTextures = []; + _this._bufferSize = 0; + _this._shader = null; + _this._packedGeometries = []; + _this._packedGeometryPoolSize = 2; + _this._flushId = 0; + _this._aBuffers = {}; + _this._iBuffers = {}; + _this.MAX_TEXTURES = 1; + _this.renderer.on('prerender', _this.onPrerender, _this); + renderer.runners.contextChange.add(_this); + _this._dcIndex = 0; + _this._aIndex = 0; + _this._iIndex = 0; + _this._attributeBuffer = null; + _this._indexBuffer = null; + _this._tempBoundTextures = []; + return _this; + } + /** + * Handles the `contextChange` signal. + * + * It calculates `this.MAX_TEXTURES` and allocating the packed-geometry object pool. + */ + AbstractBatchRenderer.prototype.contextChange = function () { + var gl = this.renderer.gl; + if (settings$1.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + this.MAX_TEXTURES = 1; + } + else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings$1.SPRITE_MAX_TEXTURES); + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl); + } + this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES); + // we use the second shader as the first one depending on your browser + // may omit aTextureId as it is not used by the shader so is optimized out. + for (var i = 0; i < this._packedGeometryPoolSize; i++) { + /* eslint-disable max-len */ + this._packedGeometries[i] = new (this.geometryClass)(); + } + this.initFlushBuffers(); + }; + /** Makes sure that static and dynamic flush pooled objects have correct dimensions. */ + AbstractBatchRenderer.prototype.initFlushBuffers = function () { + var _drawCallPool = AbstractBatchRenderer._drawCallPool, _textureArrayPool = AbstractBatchRenderer._textureArrayPool; + // max draw calls + var MAX_SPRITES = this.size / 4; + // max texture arrays + var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1; + while (_drawCallPool.length < MAX_SPRITES) { + _drawCallPool.push(new BatchDrawCall()); + } + while (_textureArrayPool.length < MAX_TA) { + _textureArrayPool.push(new BatchTextureArray()); + } + for (var i = 0; i < this.MAX_TEXTURES; i++) { + this._tempBoundTextures[i] = null; + } + }; + /** Handles the `prerender` signal. It ensures that flushes start from the first geometry object again. */ + AbstractBatchRenderer.prototype.onPrerender = function () { + this._flushId = 0; + }; + /** + * Buffers the "batchable" object. It need not be rendered immediately. + * @param {PIXI.DisplayObject} element - the element to render when + * using this renderer + */ + AbstractBatchRenderer.prototype.render = function (element) { + if (!element._texture.valid) { + return; + } + if (this._vertexCount + (element.vertexData.length / 2) > this.size) { + this.flush(); + } + this._vertexCount += element.vertexData.length / 2; + this._indexCount += element.indices.length; + this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; + this._bufferedElements[this._bufferSize++] = element; + }; + AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function () { + var _a = this, textures = _a._bufferedTextures, MAX_TEXTURES = _a.MAX_TEXTURES; + var textureArrays = AbstractBatchRenderer._textureArrayPool; + var batch = this.renderer.batch; + var boundTextures = this._tempBoundTextures; + var touch = this.renderer.textureGC.count; + var TICK = ++BaseTexture._globalBatch; + var countTexArrays = 0; + var texArray = textureArrays[0]; + var start = 0; + batch.copyBoundTextures(boundTextures, MAX_TEXTURES); + for (var i = 0; i < this._bufferSize; ++i) { + var tex = textures[i]; + textures[i] = null; + if (tex._batchEnabled === TICK) { + continue; + } + if (texArray.count >= MAX_TEXTURES) { + batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); + this.buildDrawCalls(texArray, start, i); + start = i; + texArray = textureArrays[++countTexArrays]; + ++TICK; + } + tex._batchEnabled = TICK; + tex.touched = touch; + texArray.elements[texArray.count++] = tex; + } + if (texArray.count > 0) { + batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); + this.buildDrawCalls(texArray, start, this._bufferSize); + ++countTexArrays; + ++TICK; + } + // Clean-up + for (var i = 0; i < boundTextures.length; i++) { + boundTextures[i] = null; + } + BaseTexture._globalBatch = TICK; + }; + /** + * Populating drawcalls for rendering + * @param texArray + * @param start + * @param finish + */ + AbstractBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) { + var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize; + var drawCalls = AbstractBatchRenderer._drawCallPool; + var dcIndex = this._dcIndex; + var aIndex = this._aIndex; + var iIndex = this._iIndex; + var drawCall = drawCalls[dcIndex]; + drawCall.start = this._iIndex; + drawCall.texArray = texArray; + for (var i = start; i < finish; ++i) { + var sprite = elements[i]; + var tex = sprite._texture.baseTexture; + var spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode]; + elements[i] = null; + if (start < i && drawCall.blend !== spriteBlendMode) { + drawCall.size = iIndex - drawCall.start; + start = i; + drawCall = drawCalls[++dcIndex]; + drawCall.texArray = texArray; + drawCall.start = iIndex; + } + this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); + aIndex += sprite.vertexData.length / 2 * vertexSize; + iIndex += sprite.indices.length; + drawCall.blend = spriteBlendMode; + } + if (start < finish) { + drawCall.size = iIndex - drawCall.start; + ++dcIndex; + } + this._dcIndex = dcIndex; + this._aIndex = aIndex; + this._iIndex = iIndex; + }; + /** + * Bind textures for current rendering + * @param texArray + */ + AbstractBatchRenderer.prototype.bindAndClearTexArray = function (texArray) { + var textureSystem = this.renderer.texture; + for (var j = 0; j < texArray.count; j++) { + textureSystem.bind(texArray.elements[j], texArray.ids[j]); + texArray.elements[j] = null; + } + texArray.count = 0; + }; + AbstractBatchRenderer.prototype.updateGeometry = function () { + var _a = this, packedGeometries = _a._packedGeometries, attributeBuffer = _a._attributeBuffer, indexBuffer = _a._indexBuffer; + if (!settings$1.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't + like uploads to the same buffer in a single frame. */ + if (this._packedGeometryPoolSize <= this._flushId) { + this._packedGeometryPoolSize++; + packedGeometries[this._flushId] = new (this.geometryClass)(); + } + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.bind(packedGeometries[this._flushId]); + this.renderer.geometry.updateBuffers(); + this._flushId++; + } + else { + // lets use the faster option, always use buffer number 0 + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.updateBuffers(); + } + }; + AbstractBatchRenderer.prototype.drawBatches = function () { + var dcCount = this._dcIndex; + var _a = this.renderer, gl = _a.gl, stateSystem = _a.state; + var drawCalls = AbstractBatchRenderer._drawCallPool; + var curTexArray = null; + // Upload textures and do the draw calls + for (var i = 0; i < dcCount; i++) { + var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend; + if (curTexArray !== texArray) { + curTexArray = texArray; + this.bindAndClearTexArray(texArray); + } + this.state.blendMode = blend; + stateSystem.set(this.state); + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); + } + }; + /** Renders the content _now_ and empties the current batch. */ + AbstractBatchRenderer.prototype.flush = function () { + if (this._vertexCount === 0) { + return; + } + this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); + this._indexBuffer = this.getIndexBuffer(this._indexCount); + this._aIndex = 0; + this._iIndex = 0; + this._dcIndex = 0; + this.buildTexturesAndDrawCalls(); + this.updateGeometry(); + this.drawBatches(); + // reset elements buffer for the next flush + this._bufferSize = 0; + this._vertexCount = 0; + this._indexCount = 0; + }; + /** Starts a new sprite batch. */ + AbstractBatchRenderer.prototype.start = function () { + this.renderer.state.set(this.state); + this.renderer.texture.ensureSamplerType(this.MAX_TEXTURES); + this.renderer.shader.bind(this._shader); + if (settings$1.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.geometry.bind(this._packedGeometries[this._flushId]); + } + }; + /** Stops and flushes the current batch. */ + AbstractBatchRenderer.prototype.stop = function () { + this.flush(); + }; + /** Destroys this `AbstractBatchRenderer`. It cannot be used again. */ + AbstractBatchRenderer.prototype.destroy = function () { + for (var i = 0; i < this._packedGeometryPoolSize; i++) { + if (this._packedGeometries[i]) { + this._packedGeometries[i].destroy(); + } + } + this.renderer.off('prerender', this.onPrerender, this); + this._aBuffers = null; + this._iBuffers = null; + this._packedGeometries = null; + this._attributeBuffer = null; + this._indexBuffer = null; + if (this._shader) { + this._shader.destroy(); + this._shader = null; + } + _super.prototype.destroy.call(this); + }; + /** + * Fetches an attribute buffer from `this._aBuffers` that can hold atleast `size` floats. + * @param size - minimum capacity required + * @returns - buffer than can hold atleast `size` floats + */ + AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) { + // 8 vertices is enough for 2 quads + var roundedP2 = nextPow2(Math.ceil(size / 8)); + var roundedSizeIndex = log2(roundedP2); + var roundedSize = roundedP2 * 8; + if (this._aBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + var buffer = this._aBuffers[roundedSize]; + if (!buffer) { + this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); + } + return buffer; + }; + /** + * Fetches an index buffer from `this._iBuffers` that can + * have at least `size` capacity. + * @param size - minimum required capacity + * @returns - buffer that can fit `size` indices. + */ + AbstractBatchRenderer.prototype.getIndexBuffer = function (size) { + // 12 indices is enough for 2 quads + var roundedP2 = nextPow2(Math.ceil(size / 12)); + var roundedSizeIndex = log2(roundedP2); + var roundedSize = roundedP2 * 12; + if (this._iBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + var buffer = this._iBuffers[roundedSizeIndex]; + if (!buffer) { + this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); + } + return buffer; + }; + /** + * Takes the four batching parameters of `element`, interleaves + * and pushes them into the batching attribute/index buffers given. + * + * It uses these properties: `vertexData` `uvs`, `textureId` and + * `indicies`. It also uses the "tint" of the base-texture, if + * present. + * @param {PIXI.DisplayObject} element - element being rendered + * @param attributeBuffer - attribute buffer. + * @param indexBuffer - index buffer + * @param aIndex - number of floats already in the attribute buffer + * @param iIndex - number of indices already in `indexBuffer` + */ + AbstractBatchRenderer.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) { + var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View; + var packedVertices = aIndex / this.vertexSize; + var uvs = element.uvs; + var indicies = element.indices; + var vertexData = element.vertexData; + var textureId = element._texture.baseTexture._batchLocation; + var alpha = Math.min(element.worldAlpha, 1.0); + var argb = (alpha < 1.0 + && element._texture.baseTexture.alphaMode) + ? premultiplyTint(element._tintRGB, alpha) + : element._tintRGB + (alpha * 255 << 24); + // lets not worry about tint! for now.. + for (var i = 0; i < vertexData.length; i += 2) { + float32View[aIndex++] = vertexData[i]; + float32View[aIndex++] = vertexData[i + 1]; + float32View[aIndex++] = uvs[i]; + float32View[aIndex++] = uvs[i + 1]; + uint32View[aIndex++] = argb; + float32View[aIndex++] = textureId; + } + for (var i = 0; i < indicies.length; i++) { + indexBuffer[iIndex++] = packedVertices + indicies[i]; + } + }; + /** + * Pool of `BatchDrawCall` objects that `flush` used + * to create "batches" of the objects being rendered. + * + * These are never re-allocated again. + * Shared between all batch renderers because it can be only one "flush" working at the moment. + * @member {PIXI.BatchDrawCall[]} + */ + AbstractBatchRenderer._drawCallPool = []; + /** + * Pool of `BatchDrawCall` objects that `flush` used + * to create "batches" of the objects being rendered. + * + * These are never re-allocated again. + * Shared between all batch renderers because it can be only one "flush" working at the moment. + * @member {PIXI.BatchTextureArray[]} + */ + AbstractBatchRenderer._textureArrayPool = []; + return AbstractBatchRenderer; + }(ObjectRenderer)); + + /** + * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer + * @memberof PIXI + */ + var BatchShaderGenerator = /** @class */ (function () { + /** + * @param vertexSrc - Vertex shader + * @param fragTemplate - Fragment shader template + */ + function BatchShaderGenerator(vertexSrc, fragTemplate) { + this.vertexSrc = vertexSrc; + this.fragTemplate = fragTemplate; + this.programCache = {}; + this.defaultGroupCache = {}; + if (fragTemplate.indexOf('%count%') < 0) { + throw new Error('Fragment template must contain "%count%".'); + } + if (fragTemplate.indexOf('%forloop%') < 0) { + throw new Error('Fragment template must contain "%forloop%".'); + } + } + BatchShaderGenerator.prototype.generateShader = function (maxTextures) { + if (!this.programCache[maxTextures]) { + var sampleValues = new Int32Array(maxTextures); + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); + var fragmentSrc = this.fragTemplate; + fragmentSrc = fragmentSrc.replace(/%count%/gi, "" + maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); + this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); + } + var uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new Matrix(), + default: this.defaultGroupCache[maxTextures], + }; + return new Shader(this.programCache[maxTextures], uniforms); + }; + BatchShaderGenerator.prototype.generateSampleSrc = function (maxTextures) { + var src = ''; + src += '\n'; + src += '\n'; + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + if (i < maxTextures - 1) { + src += "if(vTextureId < " + i + ".5)"; + } + src += '\n{'; + src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; + src += '\n}'; + } + src += '\n'; + src += '\n'; + return src; + }; + return BatchShaderGenerator; + }()); + + /** + * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects). + * @memberof PIXI + */ + var BatchGeometry = /** @class */ (function (_super) { + __extends$i(BatchGeometry, _super); + /** + * @param {boolean} [_static=false] - Optimization flag, where `false` + * is updated every frame, `true` doesn't change frame-to-frame. + */ + function BatchGeometry(_static) { + if (_static === void 0) { _static = false; } + var _this = _super.call(this) || this; + _this._buffer = new Buffer(null, _static, false); + _this._indexBuffer = new Buffer(null, _static, true); + _this.addAttribute('aVertexPosition', _this._buffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aTextureCoord', _this._buffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aColor', _this._buffer, 4, true, exports.TYPES.UNSIGNED_BYTE) + .addAttribute('aTextureId', _this._buffer, 1, true, exports.TYPES.FLOAT) + .addIndex(_this._indexBuffer); + return _this; + } + return BatchGeometry; + }(Geometry)); + + var defaultVertex = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; + + var defaultFragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; + + /** @memberof PIXI */ + var BatchPluginFactory = /** @class */ (function () { + function BatchPluginFactory() { + } + /** + * Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way + * to extend BatchRenderer with all the necessary pieces. + * @example + * const fragment = ` + * varying vec2 vTextureCoord; + * varying vec4 vColor; + * varying float vTextureId; + * uniform sampler2D uSamplers[%count%]; + * + * void main(void){ + * vec4 color; + * %forloop% + * gl_FragColor = vColor * vec4(color.a - color.rgb, color.a); + * } + * `; + * const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment }); + * PIXI.extensions.add({ + * name: 'invert', + * ref: InvertBatchRenderer, + * type: PIXI.ExtensionType.RendererPlugin, + * }); + * const sprite = new PIXI.Sprite(); + * sprite.pluginName = 'invert'; + * @param {object} [options] + * @param {string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source + * @param {string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template + * @param {number} [options.vertexSize=6] - Vertex size + * @param {object} [options.geometryClass=PIXI.BatchGeometry] + * @returns {*} New batch renderer plugin + */ + BatchPluginFactory.create = function (options) { + var _a = Object.assign({ + vertex: defaultVertex, + fragment: defaultFragment, + geometryClass: BatchGeometry, + vertexSize: 6, + }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass; + return /** @class */ (function (_super) { + __extends$i(BatchPlugin, _super); + function BatchPlugin(renderer) { + var _this = _super.call(this, renderer) || this; + _this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); + _this.geometryClass = geometryClass; + _this.vertexSize = vertexSize; + return _this; + } + return BatchPlugin; + }(AbstractBatchRenderer)); + }; + Object.defineProperty(BatchPluginFactory, "defaultVertexSrc", { + /** + * The default vertex shader source + * @readonly + */ + get: function () { + return defaultVertex; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", { + /** + * The default fragment shader source + * @readonly + */ + get: function () { + return defaultFragment; + }, + enumerable: false, + configurable: true + }); + return BatchPluginFactory; + }()); + // Setup the default BatchRenderer plugin, this is what + // we'll actually export at the root level + var BatchRenderer = BatchPluginFactory.create(); + Object.assign(BatchRenderer, { + extension: { + name: 'batch', + type: exports.ExtensionType.RendererPlugin, + }, + }); + + /** + * @memberof PIXI + * @namespace resources + * @see PIXI + * @deprecated since 6.0.0 + */ + var resources = {}; + var _loop_1 = function (name) { + Object.defineProperty(resources, name, { + get: function () { + deprecation$1('6.0.0', "PIXI.systems." + name + " has moved to PIXI." + name); + return _resources[name]; + }, + }); + }; + for (var name in _resources) { + _loop_1(name); + } + /** + * @memberof PIXI + * @namespace systems + * @see PIXI + * @deprecated since 6.0.0 + */ + var systems = {}; + var _loop_2 = function (name) { + Object.defineProperty(systems, name, { + get: function () { + deprecation$1('6.0.0', "PIXI.resources." + name + " has moved to PIXI." + name); + return _systems[name]; + }, + }); + }; + for (var name in _systems) { + _loop_2(name); + } + + /** + * @namespace PIXI + */ + /** + * String of the current PIXI version. + * @memberof PIXI + */ + var VERSION = '6.5.3'; + + /*! + * @pixi/accessibility - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/accessibility is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Default property values of accessible objects + * used by {@link PIXI.AccessibilityManager}. + * @private + * @function accessibleTarget + * @memberof PIXI + * @type {object} + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibleTarget + * ); + */ + var accessibleTarget = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + accessible: false, + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * @member {?string} + * @memberof PIXI.DisplayObject# + */ + accessibleTitle: null, + /** + * Sets the aria-label attribute of the shadow div + * @member {string} + * @memberof PIXI.DisplayObject# + */ + accessibleHint: null, + /** + * @member {number} + * @memberof PIXI.DisplayObject# + * @private + * @todo Needs docs. + */ + tabIndex: 0, + /** + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @todo Needs docs. + */ + _accessibleActive: false, + /** + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @todo Needs docs. + */ + _accessibleDiv: null, + /** + * Specify the type of div the accessible layer is. Screen readers treat the element differently + * depending on this type. Defaults to button. + * @member {string} + * @memberof PIXI.DisplayObject# + * @default 'button' + */ + accessibleType: 'button', + /** + * Specify the pointer-events the accessible div will use + * Defaults to auto. + * @member {string} + * @memberof PIXI.DisplayObject# + * @default 'auto' + */ + accessiblePointerEvents: 'auto', + /** + * Setting to false will prevent any children inside this container to + * be accessible. Defaults to true. + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @default true + */ + accessibleChildren: true, + renderId: -1, + }; + + // add some extra variables to the container.. + DisplayObject.mixin(accessibleTarget); + var KEY_CODE_TAB = 9; + var DIV_TOUCH_SIZE = 100; + var DIV_TOUCH_POS_X = 0; + var DIV_TOUCH_POS_Y = 0; + var DIV_TOUCH_ZINDEX = 2; + var DIV_HOOK_SIZE = 1; + var DIV_HOOK_POS_X = -1000; + var DIV_HOOK_POS_Y = -1000; + var DIV_HOOK_ZINDEX = 2; + /** + * The Accessibility manager recreates the ability to tab and have content read by screen readers. + * This is very important as it can possibly help people with disabilities access PixiJS content. + * + * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` + * @class + * @memberof PIXI + */ + var AccessibilityManager = /** @class */ (function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + /** Setting this to true will visually show the divs. */ + this.debug = false; + /** Internal variable, see isActive getter. */ + this._isActive = false; + /** Internal variable, see isMobileAccessibility getter. */ + this._isMobileAccessibility = false; + /** A simple pool for storing divs. */ + this.pool = []; + /** This is a tick used to check if an object is no longer being rendered. */ + this.renderId = 0; + /** The array of currently active accessible items. */ + this.children = []; + /** Count to throttle div updates on android devices. */ + this.androidUpdateCount = 0; + /** The frequency to update the div elements. */ + this.androidUpdateFrequency = 500; // 2fps + this._hookDiv = null; + if (isMobile$2.tablet || isMobile$2.phone) { + this.createTouchHook(); + } + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + div.style.width = DIV_TOUCH_SIZE + "px"; + div.style.height = DIV_TOUCH_SIZE + "px"; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + "px"; + div.style.left = DIV_TOUCH_POS_Y + "px"; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + this.div = div; + this.renderer = renderer; + /** + * pre-bind the functions + * @type {Function} + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + /** + * pre-bind the functions + * @type {Function} + * @private + */ + this._onMouseMove = this._onMouseMove.bind(this); + // let listen for tab.. once pressed we can fire up and show the accessibility layer + globalThis.addEventListener('keydown', this._onKeyDown, false); + } + Object.defineProperty(AccessibilityManager.prototype, "isActive", { + /** + * Value of `true` if accessibility is currently active and accessibility layers are showing. + * @member {boolean} + * @readonly + */ + get: function () { + return this._isActive; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", { + /** + * Value of `true` if accessibility is enabled for touch devices. + * @member {boolean} + * @readonly + */ + get: function () { + return this._isMobileAccessibility; + }, + enumerable: false, + configurable: true + }); + /** + * Creates the touch hooks. + * @private + */ + AccessibilityManager.prototype.createTouchHook = function () { + var _this = this; + var hookDiv = document.createElement('button'); + hookDiv.style.width = DIV_HOOK_SIZE + "px"; + hookDiv.style.height = DIV_HOOK_SIZE + "px"; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + "px"; + hookDiv.style.left = DIV_HOOK_POS_Y + "px"; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(); + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'select to enable accessibility for this content'; + hookDiv.addEventListener('focus', function () { + _this._isMobileAccessibility = true; + _this.activate(); + _this.destroyTouchHook(); + }); + document.body.appendChild(hookDiv); + this._hookDiv = hookDiv; + }; + /** + * Destroys the touch hooks. + * @private + */ + AccessibilityManager.prototype.destroyTouchHook = function () { + if (!this._hookDiv) { + return; + } + document.body.removeChild(this._hookDiv); + this._hookDiv = null; + }; + /** + * Activating will cause the Accessibility layer to be shown. + * This is called when a user presses the tab key. + * @private + */ + AccessibilityManager.prototype.activate = function () { + var _a; + if (this._isActive) { + return; + } + this._isActive = true; + globalThis.document.addEventListener('mousemove', this._onMouseMove, true); + globalThis.removeEventListener('keydown', this._onKeyDown, false); + this.renderer.on('postrender', this.update, this); + (_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div); + }; + /** + * Deactivating will cause the Accessibility layer to be hidden. + * This is called when a user moves the mouse. + * @private + */ + AccessibilityManager.prototype.deactivate = function () { + var _a; + if (!this._isActive || this._isMobileAccessibility) { + return; + } + this._isActive = false; + globalThis.document.removeEventListener('mousemove', this._onMouseMove, true); + globalThis.addEventListener('keydown', this._onKeyDown, false); + this.renderer.off('postrender', this.update); + (_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div); + }; + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) { + if (!displayObject.visible || !displayObject.accessibleChildren) { + return; + } + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + displayObject.renderId = this.renderId; + } + var children = displayObject.children; + if (children) { + for (var i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + } + }; + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * @private + */ + AccessibilityManager.prototype.update = function () { + /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex, + * moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate, + * so I am just running update every half a second, seems to fix it. + */ + var now = performance.now(); + if (isMobile$2.android.device && now < this.androidUpdateCount) { + return; + } + this.androidUpdateCount = now + this.androidUpdateFrequency; + if (!this.renderer.renderingToScreen) { + return; + } + // update children... + if (this.renderer._lastObjectRendered) { + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + } + var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height; + var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution; + var sx = (width / viewWidth) * resolution; + var sy = (height / viewHeight) * resolution; + var div = this.div; + div.style.left = left + "px"; + div.style.top = top + "px"; + div.style.width = viewWidth + "px"; + div.style.height = viewHeight + "px"; + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + i--; + } + else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + if (child.hitArea) { + div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px"; + div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px"; + div.style.width = hitArea.width * wt.a * sx + "px"; + div.style.height = hitArea.height * wt.d * sy + "px"; + } + else { + hitArea = child.getBounds(); + this.capHitArea(hitArea); + div.style.left = hitArea.x * sx + "px"; + div.style.top = hitArea.y * sy + "px"; + div.style.width = hitArea.width * sx + "px"; + div.style.height = hitArea.height * sy + "px"; + // update button titles and hints if they exist and they've changed + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute('aria-label') !== child.accessibleHint + && child.accessibleHint !== null) { + div.setAttribute('aria-label', child.accessibleHint); + } + } + // the title or index may have changed, if so lets update it! + if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { + div.title = child.accessibleTitle; + div.tabIndex = child.tabIndex; + if (this.debug) + { this.updateDebugHTML(div); } + } + } + } + // increment the render id.. + this.renderId++; + }; + /** + * private function that will visually add the information to the + * accessability div + * @param {HTMLElement} div - + */ + AccessibilityManager.prototype.updateDebugHTML = function (div) { + div.innerHTML = "type: " + div.type + "
      title : " + div.title + "
      tabIndex: " + div.tabIndex; + }; + /** + * Adjust the hit area based on the bounds of a display object + * @param {PIXI.Rectangle} hitArea - Bounds of the child + */ + AccessibilityManager.prototype.capHitArea = function (hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height; + if (hitArea.x + hitArea.width > viewWidth) { + hitArea.width = viewWidth - hitArea.x; + } + if (hitArea.y + hitArea.height > viewHeight) { + hitArea.height = viewHeight - hitArea.y; + } + }; + /** + * Adds a DisplayObject to the accessibility manager + * @private + * @param {PIXI.DisplayObject} displayObject - The child to make accessible. + */ + AccessibilityManager.prototype.addChild = function (displayObject) { + // this.activate(); + var div = this.pool.pop(); + if (!div) { + div = document.createElement('button'); + div.style.width = DIV_TOUCH_SIZE + "px"; + div.style.height = DIV_TOUCH_SIZE + "px"; + div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + div.style.borderStyle = 'none'; + // ARIA attributes ensure that button title and hint updates are announced properly + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. + div.setAttribute('aria-live', 'off'); + } + else { + div.setAttribute('aria-live', 'polite'); + } + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + // FireFox needs this to announce only the new button name + div.setAttribute('aria-relevant', 'additions'); + } + else { + // required by IE, other browsers don't much care + div.setAttribute('aria-relevant', 'text'); + } + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + // set pointer events + div.style.pointerEvents = displayObject.accessiblePointerEvents; + // set the type, this defaults to button! + div.type = displayObject.accessibleType; + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } + else if (!displayObject.accessibleHint + || displayObject.accessibleHint === null) { + div.title = "displayObject " + displayObject.tabIndex; + } + if (displayObject.accessibleHint + && displayObject.accessibleHint !== null) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + if (this.debug) + { this.updateDebugHTML(div); } + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + /** + * Maps the div button press to pixi's InteractionManager (click) + * @private + * @param {MouseEvent} e - The click event. + */ + AccessibilityManager.prototype._onClick = function (e) { + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'click', eventData); + interactionManager.dispatchEvent(displayObject, 'pointertap', eventData); + interactionManager.dispatchEvent(displayObject, 'tap', eventData); + }; + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * @private + * @param {FocusEvent} e - The focus event. + */ + AccessibilityManager.prototype._onFocus = function (e) { + if (!e.target.getAttribute('aria-live')) { + e.target.setAttribute('aria-live', 'assertive'); + } + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'mouseover', eventData); + }; + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * @private + * @param {FocusEvent} e - The focusout event. + */ + AccessibilityManager.prototype._onFocusOut = function (e) { + if (!e.target.getAttribute('aria-live')) { + e.target.setAttribute('aria-live', 'polite'); + } + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'mouseout', eventData); + }; + /** + * Is called when a key is pressed + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + AccessibilityManager.prototype._onKeyDown = function (e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + this.activate(); + }; + /** + * Is called when the mouse moves across the renderer element + * @private + * @param {MouseEvent} e - The mouse event. + */ + AccessibilityManager.prototype._onMouseMove = function (e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + this.deactivate(); + }; + /** Destroys the accessibility manager */ + AccessibilityManager.prototype.destroy = function () { + this.destroyTouchHook(); + this.div = null; + globalThis.document.removeEventListener('mousemove', this._onMouseMove, true); + globalThis.removeEventListener('keydown', this._onKeyDown); + this.pool = null; + this.children = null; + this.renderer = null; + }; + /** @ignore */ + AccessibilityManager.extension = { + name: 'accessibility', + type: [ + exports.ExtensionType.RendererPlugin, + exports.ExtensionType.CanvasRendererPlugin ], + }; + return AccessibilityManager; + }()); + + /*! + * @pixi/interaction - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/interaction is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Holds all information related to an Interaction event + * @memberof PIXI + */ + var InteractionData = /** @class */ (function () { + function InteractionData() { + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + */ + this.pressure = 0; + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + */ + this.rotationAngle = 0; + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + */ + this.twist = 0; + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + */ + this.tangentialPressure = 0; + this.global = new Point(); + this.target = null; + this.originalEvent = null; + this.identifier = null; + this.isPrimary = false; + this.button = 0; + this.buttons = 0; + this.width = 0; + this.height = 0; + this.tiltX = 0; + this.tiltY = 0; + this.pointerType = null; + this.pressure = 0; + this.rotationAngle = 0; + this.twist = 0; + this.tangentialPressure = 0; + } + Object.defineProperty(InteractionData.prototype, "pointerId", { + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + get: function () { + return this.identifier; + }, + enumerable: false, + configurable: true + }); + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * @param displayObject - The DisplayObject that you would like the local + * coords off + * @param point - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param globalPos - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @returns - A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + /** + * Copies properties from normalized event data. + * @param {Touch|MouseEvent|PointerEvent} event - The normalized event data + */ + InteractionData.prototype.copyEvent = function (event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if ('isPrimary' in event && event.isPrimary) { + this.isPrimary = true; + } + this.button = 'button' in event && event.button; + // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard + // event.which property instead, which conveys the same information. + var buttons = 'buttons' in event && event.buttons; + this.buttons = Number.isInteger(buttons) ? buttons : 'which' in event && event.which; + this.width = 'width' in event && event.width; + this.height = 'height' in event && event.height; + this.tiltX = 'tiltX' in event && event.tiltX; + this.tiltY = 'tiltY' in event && event.tiltY; + this.pointerType = 'pointerType' in event && event.pointerType; + this.pressure = 'pressure' in event && event.pressure; + this.rotationAngle = 'rotationAngle' in event && event.rotationAngle; + this.twist = ('twist' in event && event.twist) || 0; + this.tangentialPressure = ('tangentialPressure' in event && event.tangentialPressure) || 0; + }; + /** Resets the data for pooling. */ + InteractionData.prototype.reset = function () { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + return InteractionData; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$h = function(d, b) { + extendStatics$h = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$h(d, b); + }; + + function __extends$h(d, b) { + extendStatics$h(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * Event class that mimics native DOM events. + * @memberof PIXI + */ + var InteractionEvent = /** @class */ (function () { + function InteractionEvent() { + this.stopped = false; + this.stopsPropagatingAt = null; + this.stopPropagationHint = false; + this.target = null; + this.currentTarget = null; + this.type = null; + this.data = null; + } + /** Prevents event from reaching any objects other than the current object. */ + InteractionEvent.prototype.stopPropagation = function () { + this.stopped = true; + this.stopPropagationHint = true; + this.stopsPropagatingAt = this.currentTarget; + }; + /** Resets the event. */ + InteractionEvent.prototype.reset = function () { + this.stopped = false; + this.stopsPropagatingAt = null; + this.stopPropagationHint = false; + this.currentTarget = null; + this.target = null; + }; + return InteractionEvent; + }()); + + /** + * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions + * @class + * @private + * @memberof PIXI + */ + var InteractionTrackingData = /** @class */ (function () { + /** + * @param {number} pointerId - Unique pointer id of the event + * @private + */ + function InteractionTrackingData(pointerId) { + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + InteractionTrackingData.prototype._doSet = function (flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } + else { + this._flags = this._flags & (~flag); + } + }; + Object.defineProperty(InteractionTrackingData.prototype, "pointerId", { + /** + * Unique pointer id of the event + * @readonly + * @private + * @member {number} + */ + get: function () { + return this._pointerId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "flags", { + /** + * State of the tracking data, expressed as bit flags + * @private + * @member {number} + */ + get: function () { + return this._flags; + }, + set: function (flags) { + this._flags = flags; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "none", { + /** + * Is the tracked event inactive (not over or down)? + * @private + * @member {number} + */ + get: function () { + return this._flags === InteractionTrackingData.FLAGS.NONE; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "over", { + /** + * Is the tracked event over the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.OVER) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.OVER, yn); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "rightDown", { + /** + * Did the right mouse button come down in the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.RIGHT_DOWN) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.RIGHT_DOWN, yn); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "leftDown", { + /** + * Did the left mouse button come down in the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.LEFT_DOWN) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.LEFT_DOWN, yn); + }, + enumerable: false, + configurable: true + }); + InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2, + }); + return InteractionTrackingData; + }()); + + /** + * Strategy how to search through stage tree for interactive objects + * @memberof PIXI + */ + var TreeSearch = /** @class */ (function () { + function TreeSearch() { + this._tempPoint = new Point(); + } + /** + * Recursive implementation for findHit + * @private + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - this indicates if the objects inside should be hit test against the point + * @param interactive - Whether the displayObject is interactive + * @returns - Returns true if the displayObject hit the point + */ + TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) { + var _a; + if (!displayObject || !displayObject.visible) { + return false; + } + var point = interactionEvent.data.global; + // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimization once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimization is that an object is not hit test directly if a child has already been hit. + interactive = displayObject.interactive || interactive; + var hit = false; + var interactiveParent = interactive; + // Flag here can set to false if the event is outside the parents hitArea or mask + var hitTestChildren = true; + // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea + // There is also no longer a need to hitTest children. + if (displayObject.hitArea) { + if (hitTest) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hitTest = false; + hitTestChildren = false; + } + else { + hit = true; + } + } + interactiveParent = false; + } + // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask. + // We still want to hitTestChildren, however, to ensure a mouseout can still be generated. + // https://github.com/pixijs/pixi.js/issues/5135 + else if (displayObject._mask) { + if (hitTest) { + var maskObject = (displayObject._mask.isMaskData + ? displayObject._mask.maskObject : displayObject._mask); + if (maskObject && !((_a = maskObject.containsPoint) === null || _a === void 0 ? void 0 : _a.call(maskObject, point))) { + hitTest = false; + } + } + } + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent); + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + // already tested against hitArea if it is defined + if (!displayObject.hitArea && displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + return hit; + }; + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * @private + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - this indicates if the objects inside should be hit test against the point + * @returns - Returns true if the displayObject hit the point + */ + TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) { + this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false); + }; + return TreeSearch; + }()); + + /** + * Interface for classes that represent a hit area. + * + * It is implemented by the following classes: + * - {@link PIXI.Circle} + * - {@link PIXI.Ellipse} + * - {@link PIXI.Polygon} + * - {@link PIXI.RoundedRectangle} + * @interface IHitArea + * @memberof PIXI + */ + /** + * Checks whether the x and y coordinates given are contained within this area + * @method + * @name contains + * @memberof PIXI.IHitArea# + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @returns {boolean} Whether the x/y coordinates are within this area + */ + /** + * Default property values of interactive objects + * Used by {@link PIXI.InteractionManager} to automatically give all DisplayObjects these properties + * @private + * @name interactiveTarget + * @type {object} + * @memberof PIXI + * @example + * function MyObject() {} + * + * Object.assign( + * DisplayObject.prototype, + * PIXI.interactiveTarget + * ); + */ + var interactiveTarget = { + interactive: false, + interactiveChildren: true, + hitArea: null, + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } + else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + /** + * Internal set of all active pointers, by identifier + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) + { this._trackedPointers = {}; } + return this._trackedPointers; + }, + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * @private + * @type {Map} + */ + _trackedPointers: undefined, + }; + + // Mix interactiveTarget into DisplayObject.prototype + DisplayObject.mixin(interactiveTarget); + var MOUSE_POINTER_ID = 1; + // helpers for hitTest() - only used inside hitTest() + var hitTestEvent = { + target: null, + data: { + global: null, + }, + }; + /** + * The interaction manager deals with mouse, touch and pointer events. + * + * Any DisplayObject can be interactive if its `interactive` property is set to true. + * + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction` + * @memberof PIXI + */ + var InteractionManager = /** @class */ (function (_super) { + __extends$h(InteractionManager, _super); + /** + * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer + * @param options - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Maximum frequency (ms) at pointer over/out states will be checked. + * @param {number} [options.useSystemTicker=true] - Whether to add {@link tickerUpdate} to {@link PIXI.Ticker.system}. + */ + function InteractionManager(renderer, options) { + var _this = _super.call(this) || this; + options = options || {}; + _this.renderer = renderer; + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + _this.interactionFrequency = options.interactionFrequency || 10; + _this.mouse = new InteractionData(); + _this.mouse.identifier = MOUSE_POINTER_ID; + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + _this.interactionDataPool = []; + _this.eventData = new InteractionEvent(); + _this.interactionDOMElement = null; + _this.moveWhenInside = false; + _this.eventsAdded = false; + _this.tickerAdded = false; + _this.mouseOverRenderer = !('PointerEvent' in globalThis); + _this.supportsTouchEvents = 'ontouchstart' in globalThis; + _this.supportsPointerEvents = !!globalThis.PointerEvent; + // this will make it so that you don't have to call bind all the time + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + _this.onPointerOver = _this.onPointerOver.bind(_this); + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer', + }; + _this.currentCursorMode = null; + _this.cursor = null; + _this.resolution = 1; + _this.delayedEvents = []; + _this.search = new TreeSearch(); + _this._tempDisplayObject = new TemporaryDisplayObject(); + _this._eventListenerOptions = { capture: true, passive: false }; + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * @event PIXI.InteractionManager#mousedown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * @event PIXI.InteractionManager#rightdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * @event PIXI.InteractionManager#mouseup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * @event PIXI.InteractionManager#rightup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * @event PIXI.InteractionManager#click + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * @event PIXI.InteractionManager#rightclick + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.InteractionManager#event:mousedown}. + * @event PIXI.InteractionManager#mouseupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.InteractionManager#event:rightdown}. + * @event PIXI.InteractionManager#rightupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * @event PIXI.InteractionManager#mousemove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * @event PIXI.InteractionManager#mouseover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * @event PIXI.InteractionManager#mouseout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed on the display object. + * @event PIXI.InteractionManager#pointerdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released over the display object. + * Not always fired when some buttons are held down while others are released. In those cases, + * use [mousedown]{@link PIXI.InteractionManager#event:mousedown} and + * [mouseup]{@link PIXI.InteractionManager#event:mouseup} instead. + * @event PIXI.InteractionManager#pointerup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a pointer event + * @event PIXI.InteractionManager#pointercancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed and released on the display object. + * @event PIXI.InteractionManager#pointertap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.InteractionManager#event:pointerdown}. + * @event PIXI.InteractionManager#pointerupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved while over the display object + * @event PIXI.InteractionManager#pointermove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved onto the display object + * @event PIXI.InteractionManager#pointerover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved off the display object + * @event PIXI.InteractionManager#pointerout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed on the display object. + * @event PIXI.InteractionManager#touchstart + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed from the display object. + * @event PIXI.InteractionManager#touchend + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a touch + * @event PIXI.InteractionManager#touchcancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed and removed from the display object. + * @event PIXI.InteractionManager#tap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.InteractionManager#event:touchstart}. + * @event PIXI.InteractionManager#touchendoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is moved along the display object. + * @event PIXI.InteractionManager#touchmove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#click + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchend + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#tap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + _this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true; + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + return _this; + } + Object.defineProperty(InteractionManager.prototype, "useSystemTicker", { + /** + * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}. + * @default true + */ + get: function () { + return this._useSystemTicker; + }, + set: function (useSystemTicker) { + this._useSystemTicker = useSystemTicker; + if (useSystemTicker) { + this.addTickerListener(); + } + else { + this.removeTickerListener(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionManager.prototype, "lastObjectRendered", { + /** + * Last rendered object or temp object. + * @readonly + * @protected + */ + get: function () { + return this.renderer._lastObjectRendered || this._tempDisplayObject; + }, + enumerable: false, + configurable: true + }); + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * @param globalPoint - A point to hit test with, in global space. + * @param root - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @returns - The hit display object, if any. + */ + InteractionManager.prototype.hitTest = function (globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + return hitTestEvent.target; + }; + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate + * another DOM element to receive those events. + * @param element - the DOM element which will receive mouse and touch events. + * @param resolution - The resolution / device pixel ratio of the new element (relative to the canvas). + */ + InteractionManager.prototype.setTargetElement = function (element, resolution) { + if (resolution === void 0) { resolution = 1; } + this.removeTickerListener(); + this.removeEvents(); + this.interactionDOMElement = element; + this.resolution = resolution; + this.addEvents(); + this.addTickerListener(); + }; + /** Adds the ticker listener. */ + InteractionManager.prototype.addTickerListener = function () { + if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) { + return; + } + Ticker.system.add(this.tickerUpdate, this, exports.UPDATE_PRIORITY.INTERACTION); + this.tickerAdded = true; + }; + /** Removes the ticker listener. */ + InteractionManager.prototype.removeTickerListener = function () { + if (!this.tickerAdded) { + return; + } + Ticker.system.remove(this.tickerUpdate, this); + this.tickerAdded = false; + }; + /** Registers all the DOM events. */ + InteractionManager.prototype.addEvents = function () { + if (this.eventsAdded || !this.interactionDOMElement) { + return; + } + var style = this.interactionDOMElement.style; + if (globalThis.navigator.msPointerEnabled) { + style.msContentZooming = 'none'; + style.msTouchAction = 'none'; + } + else if (this.supportsPointerEvents) { + style.touchAction = 'none'; + } + /* + * These events are added first, so that if pointer events are normalized, they are fired + * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + globalThis.document.addEventListener('pointermove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, this._eventListenerOptions); + globalThis.addEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions); + globalThis.addEventListener('pointerup', this.onPointerUp, this._eventListenerOptions); + } + else { + globalThis.document.addEventListener('mousemove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, this._eventListenerOptions); + globalThis.addEventListener('mouseup', this.onPointerUp, this._eventListenerOptions); + } + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, this._eventListenerOptions); + } + this.eventsAdded = true; + }; + /** Removes all the DOM events that were previously registered. */ + InteractionManager.prototype.removeEvents = function () { + if (!this.eventsAdded || !this.interactionDOMElement) { + return; + } + var style = this.interactionDOMElement.style; + if (globalThis.navigator.msPointerEnabled) { + style.msContentZooming = ''; + style.msTouchAction = ''; + } + else if (this.supportsPointerEvents) { + style.touchAction = ''; + } + if (this.supportsPointerEvents) { + globalThis.document.removeEventListener('pointermove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, this._eventListenerOptions); + globalThis.removeEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions); + globalThis.removeEventListener('pointerup', this.onPointerUp, this._eventListenerOptions); + } + else { + globalThis.document.removeEventListener('mousemove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, this._eventListenerOptions); + globalThis.removeEventListener('mouseup', this.onPointerUp, this._eventListenerOptions); + } + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, this._eventListenerOptions); + } + this.interactionDOMElement = null; + this.eventsAdded = false; + }; + /** + * Updates the state of interactive objects if at least {@link interactionFrequency} + * milliseconds have passed since the last invocation. + * + * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}. + * @param deltaTime - time delta since the last call + */ + InteractionManager.prototype.tickerUpdate = function (deltaTime) { + this._deltaTime += deltaTime; + if (this._deltaTime < this.interactionFrequency) { + return; + } + this._deltaTime = 0; + this.update(); + }; + /** Updates the state of interactive objects. */ + InteractionManager.prototype.update = function () { + if (!this.interactionDOMElement) { + return; + } + // if the user move the mouse this check has already been done using the mouse move! + if (this._didMove) { + this._didMove = false; + return; + } + this.cursor = null; + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, true); + } + } + } + this.setCursorMode(this.cursor); + }; + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * @param mode - cursor mode, a key from the cursorStyles dictionary + */ + InteractionManager.prototype.setCursorMode = function (mode) { + mode = mode || 'default'; + var applyStyles = true; + // offscreen canvas does not support setting styles, but cursor modes can be functions, + // in order to handle pixi rendered cursors, so we can't bail + if (globalThis.OffscreenCanvas && this.interactionDOMElement instanceof OffscreenCanvas) { + applyStyles = false; + } + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + // only do things if there is a cursor style for it + if (style) { + switch (typeof style) { + case 'string': + // string styles are handled as cursor CSS + if (applyStyles) { + this.interactionDOMElement.style.cursor = style; + } + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + if (applyStyles) { + Object.assign(this.interactionDOMElement.style, style); + } + break; + } + } + else if (applyStyles && typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + /** + * Dispatches an event on the display object that was interacted with. + * @param displayObject - the display object in question + * @param eventString - the name of the event (e.g, mousedown) + * @param eventData - the event data object + */ + InteractionManager.prototype.dispatchEvent = function (displayObject, eventString, eventData) { + // Even if the event was stopped, at least dispatch any remaining events + // for the same display object. + if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + displayObject.emit(eventString, eventData); + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + /** + * Puts a event on a queue to be dispatched later. This is used to guarantee correct + * ordering of over/out events. + * @param displayObject - the display object in question + * @param eventString - the name of the event (e.g, mousedown) + * @param eventData - the event data object + */ + InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) { + this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData }); + }; + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * @param point - the point that the result will be stored in + * @param x - the x coord of the position to map + * @param y - the y coord of the position to map + */ + InteractionManager.prototype.mapPositionToPoint = function (point, x, y) { + var rect; + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { + x: 0, + y: 0, + width: this.interactionDOMElement.width, + height: this.interactionDOMElement.height, + left: 0, + top: 0 + }; + } + else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + var resolutionMultiplier = 1.0 / this.resolution; + point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier; + point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier; + }; + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * @protected + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - indicates whether we want to calculate hits + * or just iterate through all interactive objects + */ + InteractionManager.prototype.processInteractive = function (interactionEvent, displayObject, func, hitTest) { + var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest); + var delayedEvents = this.delayedEvents; + if (!delayedEvents.length) { + return hit; + } + // Reset the propagation hint, because we start deeper in the tree again. + interactionEvent.stopPropagationHint = false; + var delayedLen = delayedEvents.length; + this.delayedEvents = []; + for (var i = 0; i < delayedLen; i++) { + var _a = delayedEvents[i], displayObject_1 = _a.displayObject, eventString = _a.eventString, eventData = _a.eventData; + // When we reach the object we wanted to stop propagating at, + // set the propagation hint. + if (eventData.stopsPropagatingAt === displayObject_1) { + eventData.stopPropagationHint = true; + } + this.dispatchEvent(displayObject_1, eventString, eventData); + } + return hit; + }; + /** + * Is called when the pointer button is pressed down on the renderer element + * @param originalEvent - The DOM event of a pointer button being pressed down + */ + InteractionManager.prototype.onPointerDown = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + /* + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + if (this.autoPreventDefault && events[0].isNormalized) { + var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent); + if (cancelable) { + originalEvent.preventDefault(); + } + } + var eventLen = events.length; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerDown, true); + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + /** + * Processes the result of the pointer down check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerDown = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new InteractionTrackingData(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } + else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } + else { + displayObject.trackedPointers[id].leftDown = true; + } + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + /** + * Is called when the pointer button is released on the renderer element + * @param originalEvent - The DOM event of a pointer button being released + * @param cancelled - true if the pointer is cancelled + * @param func - Function passed to {@link processInteractive} + */ + InteractionManager.prototype.onPointerComplete = function (originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + var eventLen = events.length; + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var target = originalEvent.target; + // if in shadow DOM use composedPath to access target + if (originalEvent.composedPath && originalEvent.composedPath().length > 0) { + target = originalEvent.composedPath()[0]; + } + var eventAppend = target !== this.interactionDOMElement ? 'outside' : ''; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.lastObjectRendered, func, cancelled || !eventAppend); + this.emit(cancelled ? 'pointercancel' : "pointerup" + eventAppend, interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + this.emit(isRightButton ? "rightup" + eventAppend : "mouseup" + eventAppend, interactionEvent); + } + else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : "touchend" + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId); + } + } + }; + /** + * Is called when the pointer button is cancelled + * @param event - The DOM event of a pointer button being released + */ + InteractionManager.prototype.onPointerCancel = function (event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') + { return; } + this.onPointerComplete(event, true, this.processPointerCancel); + }; + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + */ + InteractionManager.prototype.processPointerCancel = function (interactionEvent, displayObject) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + /** + * Is called when the pointer button is released on the renderer element + * @param event - The DOM event of a pointer button being released + */ + InteractionManager.prototype.onPointerUp = function (event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') + { return; } + this.onPointerComplete(event, false, this.processPointerUp); + }; + /** + * Processes the result of the pointer up check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerUp = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + var trackingData = displayObject.trackedPointers[id]; + var isTouch = data.pointerType === 'touch'; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + // need to track mouse down status in the mouse block so that we can emit + // event in a later block + var isMouseTap = false; + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + var flags = InteractionTrackingData.FLAGS; + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + var isDown = trackingData !== undefined && (trackingData.flags & test); + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap + isMouseTap = true; + } + } + else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } + else { + trackingData.leftDown = false; + } + } + } + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchend', interactionEvent); } + if (trackingData) { + // emit pointertap if not a mouse, or if the mouse block decided it was a tap + if (!isMouse || isMouseTap) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + } + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } + else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); } + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + /** + * Is called when the pointer moves across the renderer element + * @param originalEvent - The DOM event of a pointer moving + */ + InteractionManager.prototype.onPointerMove = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { + this._didMove = true; + this.cursor = null; + } + var eventLen = events.length; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerMove, true); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') + { this.emit('touchmove', interactionEvent); } + if (event.pointerType === 'mouse' || event.pointerType === 'pen') + { this.emit('mousemove', interactionEvent); } + } + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + // TODO BUG for parents interactive object (border order issue) + } + }; + /** + * Processes the result of the pointer move check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerMove = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var isTouch = data.pointerType === 'touch'; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); } + if (isMouse) + { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); } + } + }; + /** + * Is called when the pointer is moved out of the renderer element + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + InteractionManager.prototype.onPointerOut = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = event; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, false); + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } + else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + /** + * Processes the result of the pointer over/out check and dispatches the event if need be. + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerOverOut = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + var trackingData = displayObject.trackedPointers[id]; + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id); + } + if (trackingData === undefined) + { return; } + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } + else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + /** + * Is called when the pointer is moved into the renderer element. + * @param originalEvent - The DOM event of a pointer button being moved into the renderer view. + */ + InteractionManager.prototype.onPointerOver = function (originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = event; + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + /** + * Get InteractionData for a given pointerId. Store that data as well. + * @param event - Normalized pointer event, output from normalizeToPointerData. + * @returns - Interaction data for the given pointer identifier. + */ + InteractionManager.prototype.getInteractionDataForPointerId = function (event) { + var pointerId = event.pointerId; + var interactionData; + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } + else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } + else { + interactionData = this.interactionDataPool.pop() || new InteractionData(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData.copyEvent(event); + return interactionData; + }; + /** + * Return unused InteractionData to the pool, for a given pointerId + * @param pointerId - Identifier from a pointer event + */ + InteractionManager.prototype.releaseInteractionDataForPointerId = function (pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData.reset(); + this.interactionDataPool.push(interactionData); + } + }; + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * @param interactionEvent - The event to be configured + * @param pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @returns - the interaction event that was passed in + */ + InteractionManager.prototype.configureInteractionEventForDOMEvent = function (interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + interactionData.originalEvent = pointerEvent; + interactionEvent.reset(); + return interactionEvent; + }; + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @returns - An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + InteractionManager.prototype.normalizeToPointerData = function (event) { + var normalizedEvents = []; + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + if (typeof touch.button === 'undefined') + { touch.button = event.touches.length ? 1 : 0; } + if (typeof touch.buttons === 'undefined') + { touch.buttons = event.touches.length ? 1 : 0; } + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') + { touch.width = touch.radiusX || 1; } + if (typeof touch.height === 'undefined') + { touch.height = touch.radiusY || 1; } + if (typeof touch.tiltX === 'undefined') + { touch.tiltX = 0; } + if (typeof touch.tiltY === 'undefined') + { touch.tiltY = 0; } + if (typeof touch.pointerType === 'undefined') + { touch.pointerType = 'touch'; } + if (typeof touch.pointerId === 'undefined') + { touch.pointerId = touch.identifier || 0; } + if (typeof touch.pressure === 'undefined') + { touch.pressure = touch.force || 0.5; } + if (typeof touch.twist === 'undefined') + { touch.twist = 0; } + if (typeof touch.tangentialPressure === 'undefined') + { touch.tangentialPressure = 0; } + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') + { touch.layerX = touch.offsetX = touch.clientX; } + if (typeof touch.layerY === 'undefined') + { touch.layerY = touch.offsetY = touch.clientY; } + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (!globalThis.MouseEvent + || (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.PointerEvent)))) { + var tempEvent = event; + if (typeof tempEvent.isPrimary === 'undefined') + { tempEvent.isPrimary = true; } + if (typeof tempEvent.width === 'undefined') + { tempEvent.width = 1; } + if (typeof tempEvent.height === 'undefined') + { tempEvent.height = 1; } + if (typeof tempEvent.tiltX === 'undefined') + { tempEvent.tiltX = 0; } + if (typeof tempEvent.tiltY === 'undefined') + { tempEvent.tiltY = 0; } + if (typeof tempEvent.pointerType === 'undefined') + { tempEvent.pointerType = 'mouse'; } + if (typeof tempEvent.pointerId === 'undefined') + { tempEvent.pointerId = MOUSE_POINTER_ID; } + if (typeof tempEvent.pressure === 'undefined') + { tempEvent.pressure = 0.5; } + if (typeof tempEvent.twist === 'undefined') + { tempEvent.twist = 0; } + if (typeof tempEvent.tangentialPressure === 'undefined') + { tempEvent.tangentialPressure = 0; } + // mark the mouse event as normalized, just so that we know we did it + tempEvent.isNormalized = true; + normalizedEvents.push(tempEvent); + } + else { + normalizedEvents.push(event); + } + return normalizedEvents; + }; + /** Destroys the interaction manager. */ + InteractionManager.prototype.destroy = function () { + this.removeEvents(); + this.removeTickerListener(); + this.removeAllListeners(); + this.renderer = null; + this.mouse = null; + this.eventData = null; + this.interactionDOMElement = null; + this.onPointerDown = null; + this.processPointerDown = null; + this.onPointerUp = null; + this.processPointerUp = null; + this.onPointerCancel = null; + this.processPointerCancel = null; + this.onPointerMove = null; + this.processPointerMove = null; + this.onPointerOut = null; + this.processPointerOverOut = null; + this.onPointerOver = null; + this.search = null; + }; + /** @ignore */ + InteractionManager.extension = { + name: 'interaction', + type: [ + exports.ExtensionType.RendererPlugin, + exports.ExtensionType.CanvasRendererPlugin ], + }; + return InteractionManager; + }(eventemitter3)); + + /*! + * @pixi/extract - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/extract is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + var TEMP_RECT = new Rectangle(); + var BYTES_PER_PIXEL = 4; + /** + * This class provides renderer-specific plugins for exporting content from a renderer. + * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels). + * + * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. + * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. + * @example + * // Create a new app (will auto-add extract plugin to renderer) + * const app = new PIXI.Application(); + * + * // Draw a red circle + * const graphics = new PIXI.Graphics() + * .beginFill(0xFF0000) + * .drawCircle(0, 0, 50); + * + * // Render the graphics as an HTMLImageElement + * const image = app.renderer.plugins.extract.image(graphics); + * document.body.appendChild(image); + * @memberof PIXI + */ + var Extract = /** @class */ (function () { + /** + * @param renderer - A reference to the current renderer + */ + function Extract(renderer) { + this.renderer = renderer; + } + /** + * Will return a HTML Image of the target + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param format - Image format, e.g. "image/jpeg" or "image/webp". + * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92. + * @returns - HTML Image of the target + */ + Extract.prototype.image = function (target, format, quality) { + var image = new Image(); + image.src = this.base64(target, format, quality); + return image; + }; + /** + * Will return a base64 encoded string of this target. It works by calling + * `Extract.getCanvas` and then running toDataURL on that. + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param format - Image format, e.g. "image/jpeg" or "image/webp". + * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92. + * @returns - A base64 encoded string of the texture. + */ + Extract.prototype.base64 = function (target, format, quality) { + return this.canvas(target).toDataURL(format, quality); + }; + /** + * Creates a Canvas element, renders this target to it and then returns it. + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param frame - The frame the extraction is restricted to. + * @returns - A Canvas element with the texture rendered on. + */ + Extract.prototype.canvas = function (target, frame) { + var renderer = this.renderer; + var resolution; + var flipY = false; + var renderTexture; + var generated = false; + if (target) { + if (target instanceof RenderTexture) { + renderTexture = target; + } + else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + if (renderTexture) { + resolution = renderTexture.baseTexture.resolution; + frame = frame !== null && frame !== void 0 ? frame : renderTexture.frame; + flipY = false; + renderer.renderTexture.bind(renderTexture); + } + else { + resolution = renderer.resolution; + if (!frame) { + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + flipY = true; + renderer.renderTexture.bind(null); + } + var width = Math.round(frame.width * resolution); + var height = Math.round(frame.height * resolution); + var canvasBuffer = new CanvasRenderTarget(width, height, 1); + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + Extract.arrayPostDivide(webglPixels, canvasData.data); + canvasBuffer.context.putImageData(canvasData, 0, 0); + // pulling pixels + if (flipY) { + var target_1 = new CanvasRenderTarget(canvasBuffer.width, canvasBuffer.height, 1); + target_1.context.scale(1, -1); + // we can't render to itself because we should be empty before render. + target_1.context.drawImage(canvasBuffer.canvas, 0, -height); + canvasBuffer.destroy(); + canvasBuffer = target_1; + } + if (generated) { + renderTexture.destroy(true); + } + // send the canvas back.. + return canvasBuffer.canvas; + }; + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param frame - The frame the extraction is restricted to. + * @returns - One-dimensional array containing the pixel data of the entire texture + */ + Extract.prototype.pixels = function (target, frame) { + var renderer = this.renderer; + var resolution; + var renderTexture; + var generated = false; + if (target) { + if (target instanceof RenderTexture) { + renderTexture = target; + } + else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + if (renderTexture) { + resolution = renderTexture.baseTexture.resolution; + frame = frame !== null && frame !== void 0 ? frame : renderTexture.frame; + renderer.renderTexture.bind(renderTexture); + } + else { + resolution = renderer.resolution; + if (!frame) { + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + renderer.renderTexture.bind(null); + } + var width = Math.round(frame.width * resolution); + var height = Math.round(frame.height * resolution); + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + if (generated) { + renderTexture.destroy(true); + } + Extract.arrayPostDivide(webglPixels, webglPixels); + return webglPixels; + }; + /** Destroys the extract. */ + Extract.prototype.destroy = function () { + this.renderer = null; + }; + /** + * Takes premultiplied pixel data and produces regular pixel data + * @private + * @param pixels - array of pixel data + * @param out - output array + */ + Extract.arrayPostDivide = function (pixels, out) { + for (var i = 0; i < pixels.length; i += 4) { + var alpha = out[i + 3] = pixels[i + 3]; + if (alpha !== 0) { + out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0)); + out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0)); + out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0)); + } + else { + out[i] = pixels[i]; + out[i + 1] = pixels[i + 1]; + out[i + 2] = pixels[i + 2]; + } + } + }; + /** @ignore */ + Extract.extension = { + name: 'extract', + type: exports.ExtensionType.RendererPlugin, + }; + return Extract; + }()); + + /*! + * @pixi/loaders - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/loaders is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /* jshint -W097 */ + /** + * @memberof PIXI + */ + var SignalBinding = /** @class */ (function () { + /** + * SignalBinding constructor. + * @constructs SignalBinding + * @param {Function} fn - Event handler to be called. + * @param {boolean} [once=false] - Should this listener be removed after dispatch + * @param {object} [thisArg] - The context of the callback function. + * @api private + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + function SignalBinding(fn, once, thisArg) { + if (once === void 0) { once = false; } + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + SignalBinding.prototype.detach = function () { + if (this._owner === null) + { return false; } + this._owner.detach(this); + return true; + }; + return SignalBinding; + }()); + /** + * @param self + * @param node + * @private + */ + function _addSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } + else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + node._owner = self; + return node; + } + /** + * @memberof PIXI + */ + var Signal = /** @class */ (function () { + /** + * MiniSignal constructor. + * @example + * let mySignal = new Signal(); + * let binding = mySignal.add(onSignal); + * mySignal.dispatch('foo', 'bar'); + * mySignal.detach(binding); + */ + function Signal() { + this._head = this._tail = undefined; + } + /** + * Return an array of attached SignalBinding. + * @param {boolean} [exists=false] - We only need to know if there are handlers. + * @returns {PIXI.SignalBinding[] | boolean} Array of attached SignalBinding or Boolean if called with exists = true + * @api public + */ + Signal.prototype.handlers = function (exists) { + if (exists === void 0) { exists = false; } + var node = this._head; + if (exists) + { return !!node; } + var ee = []; + while (node) { + ee.push(node); + node = node._next; + } + return ee; + }; + /** + * Return true if node is a SignalBinding attached to this MiniSignal + * @param {PIXI.SignalBinding} node - Node to check. + * @returns {boolean} True if node is attache to mini-signal + */ + Signal.prototype.has = function (node) { + if (!(node instanceof SignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a SignalBinding object.'); + } + return node._owner === this; + }; + /** + * Dispaches a signal to all registered listeners. + * @param {...any} args + * @returns {boolean} Indication if we've emitted an event. + */ + Signal.prototype.dispatch = function () { + var arguments$1 = arguments; + + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + var node = this._head; + if (!node) + { return false; } + while (node) { + if (node._once) + { this.detach(node); } + node._fn.apply(node._thisArg, args); + node = node._next; + } + return true; + }; + /** + * Register a new listener. + * @param {Function} fn - Callback function. + * @param {object} [thisArg] - The context of the callback function. + * @returns {PIXI.SignalBinding} The SignalBinding node that was added. + */ + Signal.prototype.add = function (fn, thisArg) { + if (thisArg === void 0) { thisArg = null; } + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addSignalBinding(this, new SignalBinding(fn, false, thisArg)); + }; + /** + * Register a new listener that will be executed only once. + * @param {Function} fn - Callback function. + * @param {object} [thisArg] - The context of the callback function. + * @returns {PIXI.SignalBinding} The SignalBinding node that was added. + */ + Signal.prototype.once = function (fn, thisArg) { + if (thisArg === void 0) { thisArg = null; } + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addSignalBinding(this, new SignalBinding(fn, true, thisArg)); + }; + /** + * Remove binding object. + * @param {PIXI.SignalBinding} node - The binding node that will be removed. + * @returns {Signal} The instance on which this method was called. + @api public */ + Signal.prototype.detach = function (node) { + if (!(node instanceof SignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a SignalBinding object.'); + } + if (node._owner !== this) + { return this; } // todo: or error? + if (node._prev) + { node._prev._next = node._next; } + if (node._next) + { node._next._prev = node._prev; } + if (node === this._head) { // first node + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } + else if (node === this._tail) { // last node + this._tail = node._prev; + this._tail._next = null; + } + node._owner = null; + return this; + }; + /** + * Detach all listeners. + * @returns {Signal} The instance on which this method was called. + */ + Signal.prototype.detachAll = function () { + var node = this._head; + if (!node) + { return this; } + this._head = this._tail = null; + while (node) { + node._owner = null; + node = node._next; + } + return this; + }; + return Signal; + }()); + + /** + * function from npm package `parseUri`, converted to TS to avoid leftpad incident + * @param {string} str + * @param [opts] - options + * @param {boolean} [opts.strictMode] - type of parser + */ + function parseUri(str, opts) { + opts = opts || {}; + var o = { + // eslint-disable-next-line max-len + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + // eslint-disable-next-line max-len + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + // eslint-disable-next-line max-len + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + }; + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str); + var uri = {}; + var i = 14; + while (i--) + { uri[o.key[i]] = m[i] || ''; } + uri[o.q.name] = {}; + uri[o.key[12]].replace(o.q.parser, function (_t0, t1, t2) { + if (t1) + { uri[o.q.name][t1] = t2; } + }); + return uri; + } + + // tests if CORS is supported in XHR, if not we need to use XDR + var useXdr; + var tempAnchor = null; + // some status constants + var STATUS_NONE = 0; + var STATUS_OK = 200; + var STATUS_EMPTY = 204; + var STATUS_IE_BUG_EMPTY = 1223; + var STATUS_TYPE_OK = 2; + // noop + function _noop$1() { } + /** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * @ignore + * @param map - The map to set on. + * @param extname - The extension (or key) to set. + * @param val - The value to set. + */ + function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + if (!extname) { + return; + } + map[extname] = val; + } + /** + * Quick helper to get string xhr type. + * @ignore + * @param xhr - The request to check. + * @returns The type. + */ + function reqType(xhr) { + return xhr.toString().replace('object ', ''); + } + /** + * Manages the state and loading of a resource and all child resources. + * + * Can be extended in `GlobalMixins.LoaderResource`. + * @memberof PIXI + */ + exports.LoaderResource = /** @class */ (function () { + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes + * longer than this time it is cancelled and the load is considered a failure. If this value is + * set to `0` then there is no explicit timeout. + * @param {PIXI.LoaderResource.LOAD_TYPE} [options.loadType=LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} [options.xhrType=XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {PIXI.LoaderResource.IMetadata} [options.metadata] - Extra configuration for middleware + * and the Resource object. + */ + function LoaderResource(name, url, options) { + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * @private + * @member {Function} + */ + this._dequeue = _noop$1; + /** + * Used a storage place for the on load binding used privately by the loader. + * @private + * @member {Function} + */ + this._onLoadBinding = null; + /** + * The timer for element loads to check if they timeout. + * @private + */ + this._elementTimer = 0; + /** + * The `complete` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundComplete = null; + /** + * The `_onError` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnError = null; + /** + * The `_onProgress` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnProgress = null; + /** + * The `_onTimeout` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnTimeout = null; + this._boundXhrOnError = null; + this._boundXhrOnTimeout = null; + this._boundXhrOnAbort = null; + this._boundXhrOnLoad = null; + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + options = options || {}; + this._flags = 0; + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(LoaderResource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + this.name = name; + this.url = url; + this.extension = this._getExtension(); + this.data = null; + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + this.timeout = options.timeout || 0; + this.loadType = options.loadType || this._determineLoadType(); + // The type used to load the resource via XHR. If unset, determined automatically. + this.xhrType = options.xhrType; + // Extra info for middleware, and controlling specifics about how the resource loads. + // Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + // Meaning it will modify it as it sees fit. + this.metadata = options.metadata || {}; + // The error that occurred while loading (if any). + this.error = null; + // The XHR object that was used to load this resource. This is only set + // when `loadType` is `LoaderResource.LOAD_TYPE.XHR`. + this.xhr = null; + // The child resources this resource owns. + this.children = []; + // The resource type. + this.type = LoaderResource.TYPE.UNKNOWN; + // The progress chunk owned by this resource. + this.progressChunk = 0; + // The `dequeue` method that will be used a storage place for the async queue dequeue method + // used privately by the loader. + this._dequeue = _noop$1; + // Used a storage place for the on load binding used privately by the loader. + this._onLoadBinding = null; + // The timer for element loads to check if they timeout. + this._elementTimer = 0; + this._boundComplete = this.complete.bind(this); + this._boundOnError = this._onError.bind(this); + this._boundOnProgress = this._onProgress.bind(this); + this._boundOnTimeout = this._onTimeout.bind(this); + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + // Dispatched when the resource beings to load. + this.onStart = new Signal(); + // Dispatched each time progress of this resource load updates. + // Not all resources types and loader systems can support this event + // so sometimes it may not be available. If the resource + // is being loaded on a modern browser, using XHR, and the remote server + // properly sets Content-Length headers, then this will be available. + this.onProgress = new Signal(); + // Dispatched once this resource has loaded, if there was an error it will + // be in the `error` property. + this.onComplete = new Signal(); + // Dispatched after this resource has had all the *after* middleware run on it. + this.onAfterMiddleware = new Signal(); + } + /** + * Sets the load type to be used for a specific extension. + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {PIXI.LoaderResource.LOAD_TYPE} loadType - The load type to set it to. + */ + LoaderResource.setExtensionLoadType = function (extname, loadType) { + setExtMap(LoaderResource._loadTypeMap, extname, loadType); + }; + /** + * Sets the load type to be used for a specific extension. + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + LoaderResource.setExtensionXhrType = function (extname, xhrType) { + setExtMap(LoaderResource._xhrTypeMap, extname, xhrType); + }; + Object.defineProperty(LoaderResource.prototype, "isDataUrl", { + /** + * When the resource starts to load. + * @memberof PIXI.LoaderResource + * @callback OnStartSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + */ + /** + * When the resource reports loading progress. + * @memberof PIXI.LoaderResource + * @callback OnProgressSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + /** + * When the resource finishes loading. + * @memberof PIXI.LoaderResource + * @callback OnCompleteSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + */ + /** + * @memberof PIXI.LoaderResource + * @typedef {object} IMetadata + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @property {string|string[]} [mimeType] - The mime type to use for the source element + * of a video/audio elment. If the urls are an array, you can pass this as an array as well + * where each index is the mime type to use for the corresponding url index. + */ + /** + * Stores whether or not this url is a data url. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.DATA_URL); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(LoaderResource.prototype, "isComplete", { + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.COMPLETE); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(LoaderResource.prototype, "isLoading", { + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.LOADING); + }, + enumerable: false, + configurable: true + }); + /** Marks the resource as complete. */ + LoaderResource.prototype.complete = function () { + this._clearEvents(); + this._finish(); + }; + /** + * Aborts the loading of this resource, with an optional message. + * @param {string} message - The message to use for the error + */ + LoaderResource.prototype.abort = function (message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + // store error + this.error = new Error(message); + // clear events before calling aborts + this._clearEvents(); + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } + else if (this.xdr) { + this.xdr.abort(); + } + else if (this.data) { + // single source + if (this.data.src) { + this.data.src = LoaderResource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + // done now. + this._finish(); + }; + /** + * Kicks off loading of this resource. This method is asynchronous. + * @param {PIXI.LoaderResource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded. + */ + LoaderResource.prototype.load = function (cb) { + var _this = this; + if (this.isLoading) { + return; + } + if (this.isComplete) { + if (cb) { + setTimeout(function () { return cb(_this); }, 1); + } + return; + } + else if (cb) { + this.onComplete.once(cb); + } + this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, true); + this.onStart.dispatch(this); + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + switch (this.loadType) { + case LoaderResource.LOAD_TYPE.IMAGE: + this.type = LoaderResource.TYPE.IMAGE; + this._loadElement('image'); + break; + case LoaderResource.LOAD_TYPE.AUDIO: + this.type = LoaderResource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + case LoaderResource.LOAD_TYPE.VIDEO: + this.type = LoaderResource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + case LoaderResource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (typeof useXdr === 'undefined') { + useXdr = !!(globalThis.XDomainRequest && !('withCredentials' in (new XMLHttpRequest()))); + } + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } + else { + this._loadXhr(); + } + break; + } + }; + /** + * Checks if the flag is set. + * @param flag - The flag to check. + * @returns True if the flag is set. + */ + LoaderResource.prototype._hasFlag = function (flag) { + return (this._flags & flag) !== 0; + }; + /** + * (Un)Sets the flag. + * @param flag - The flag to (un)set. + * @param value - Whether to set or (un)set the flag. + */ + LoaderResource.prototype._setFlag = function (flag, value) { + this._flags = value ? (this._flags | flag) : (this._flags & ~flag); + }; + /** Clears all the events from the underlying loading source. */ + LoaderResource.prototype._clearEvents = function () { + clearTimeout(this._elementTimer); + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } + else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + }; + /** Finalizes the load. */ + LoaderResource.prototype._finish = function () { + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + this._setFlag(LoaderResource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, false); + this.onComplete.dispatch(this); + }; + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * @private + * @param type - The type of element to use. + */ + LoaderResource.prototype._loadElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'image' && typeof globalThis.Image !== 'undefined') { + this.data = new Image(); + } + else { + this.data = document.createElement(type); + } + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + }; + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * @param type - The type of element to use. + */ + LoaderResource.prototype._loadSourceElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'audio' && typeof globalThis.Audio !== 'undefined') { + this.data = new Audio(); + } + else { + this.data = document.createElement(type); + } + if (this.data === null) { + this.abort("Unsupported element: " + type); + return; + } + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } + else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } + else { + var mimeTypes = this.metadata.mimeType; + this.data.appendChild(this._createSource(type, this.url, Array.isArray(mimeTypes) ? mimeTypes[0] : mimeTypes)); + } + } + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + this.data.load(); + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + }; + /** Loads this resources using an XMLHttpRequest. */ + LoaderResource.prototype._loadXhr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + var xhr = this.xhr = new XMLHttpRequest(); + // send credentials when crossOrigin with credentials requested + if (this.crossOrigin === 'use-credentials') { + xhr.withCredentials = true; + } + // set the request type and url + xhr.open('GET', this.url, true); + xhr.timeout = this.timeout; + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON + || this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = LoaderResource.XHR_RESPONSE_TYPE.TEXT; + } + else { + xhr.responseType = this.xhrType; + } + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('timeout', this._boundXhrOnTimeout, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + xhr.send(); + }; + /** Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). */ + LoaderResource.prototype._loadXdr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + var xdr = this.xhr = new globalThis.XDomainRequest(); // eslint-disable-line no-undef + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9 + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXhrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + xdr.open('GET', this.url, true); + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { return xdr.send(); }, 1); + }; + /** + * Creates a source used in loading via an element. + * @param type - The element type (video or audio). + * @param url - The source URL to load from. + * @param [mime] - The mime type of the video + * @returns The source element. + */ + LoaderResource.prototype._createSource = function (type, url, mime) { + if (!mime) { + mime = type + "/" + this._getExtension(url); + } + var source = document.createElement('source'); + source.src = url; + source.type = mime; + return source; + }; + /** + * Called if a load errors out. + * @param event - The error event from the element that emits it. + */ + LoaderResource.prototype._onError = function (event) { + this.abort("Failed to load element using: " + event.target.nodeName); + }; + /** + * Called if a load progress event fires for an element or xhr/xdr. + * @param event - Progress event. + */ + LoaderResource.prototype._onProgress = function (event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + /** Called if a timeout event fires for an element. */ + LoaderResource.prototype._onTimeout = function () { + this.abort("Load timed out."); + }; + /** Called if an error event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnError = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\""); + }; + /** Called if an error event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnTimeout = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request timed out."); + }; + /** Called if an abort event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnAbort = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request was aborted by the user."); + }; + /** Called when data successfully loads from an xhr/xdr request. */ + LoaderResource.prototype._xhrOnLoad = function () { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === LoaderResource.XHR_RESPONSE_TYPE.BUFFER)) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + var statusType = (status / 100) | 0; + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = LoaderResource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = LoaderResource.TYPE.JSON; + } + catch (e) { + this.abort("Error trying to parse loaded json: " + e); + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (globalThis.DOMParser) { + var domparser = new DOMParser(); + this.data = domparser.parseFromString(text, 'text/xml'); + } + else { + var div = document.createElement('div'); + div.innerHTML = text; + this.data = div; + } + this.type = LoaderResource.TYPE.XML; + } + catch (e$1) { + this.abort("Error trying to parse loaded xml: " + e$1); + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } + else { + this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL); + return; + } + this.complete(); + }; + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * @private + * @param url - The url to test. + * @param [loc=globalThis.location] - The location object to test against. + * @returns The crossOrigin value to use (or empty string for none). + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + LoaderResource.prototype._determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + // A sandboxed iframe without the 'allow-same-origin' attribute will have a special + // origin designed not to match globalThis.location.origin, and will always require + // crossOrigin requests regardless of whether the location matches. + if (globalThis.origin !== globalThis.location.origin) { + return 'anonymous'; + } + // default is globalThis.location + loc = loc || globalThis.location; + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + var parsedUrl = parseUri(tempAnchor.href, { strictMode: true }); + var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); + var protocol = parsedUrl.protocol ? parsedUrl.protocol + ":" : ''; + // if cross origin + if (parsedUrl.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + return ''; + }; + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * @private + * @returns {PIXI.LoaderResource.XHR_RESPONSE_TYPE} The responseType to use. + */ + LoaderResource.prototype._determineXhrType = function () { + return LoaderResource._xhrTypeMap[this.extension] || LoaderResource.XHR_RESPONSE_TYPE.TEXT; + }; + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * @private + * @returns {PIXI.LoaderResource.LOAD_TYPE} The loadType to use. + */ + LoaderResource.prototype._determineLoadType = function () { + return LoaderResource._loadTypeMap[this.extension] || LoaderResource.LOAD_TYPE.XHR; + }; + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * @param [url] - url to parse, `this.url` by default. + * @returns The extension. + */ + LoaderResource.prototype._getExtension = function (url) { + if (url === void 0) { url = this.url; } + var ext = ''; + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } + else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + return ext.toLowerCase(); + }; + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * @param type - The type to get a mime type for. + * @private + * @returns The mime type to use. + */ + LoaderResource.prototype._getMimeFromXhrType = function (type) { + switch (type) { + case LoaderResource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + case LoaderResource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + case LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + case LoaderResource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + case LoaderResource.XHR_RESPONSE_TYPE.DEFAULT: + case LoaderResource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + } + }; + return LoaderResource; + }()); + // eslint-disable-next-line @typescript-eslint/no-namespace + (function (LoaderResource) { + (function (STATUS_FLAGS) { + /** None */ + STATUS_FLAGS[STATUS_FLAGS["NONE"] = 0] = "NONE"; + /** Data URL */ + STATUS_FLAGS[STATUS_FLAGS["DATA_URL"] = 1] = "DATA_URL"; + /** Complete */ + STATUS_FLAGS[STATUS_FLAGS["COMPLETE"] = 2] = "COMPLETE"; + /** Loading */ + STATUS_FLAGS[STATUS_FLAGS["LOADING"] = 4] = "LOADING"; + })(LoaderResource.STATUS_FLAGS || (LoaderResource.STATUS_FLAGS = {})); + (function (TYPE) { + /** Unknown */ + TYPE[TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + /** JSON */ + TYPE[TYPE["JSON"] = 1] = "JSON"; + /** XML */ + TYPE[TYPE["XML"] = 2] = "XML"; + /** Image */ + TYPE[TYPE["IMAGE"] = 3] = "IMAGE"; + /** Audio */ + TYPE[TYPE["AUDIO"] = 4] = "AUDIO"; + /** Video */ + TYPE[TYPE["VIDEO"] = 5] = "VIDEO"; + /** Plain text */ + TYPE[TYPE["TEXT"] = 6] = "TEXT"; + })(LoaderResource.TYPE || (LoaderResource.TYPE = {})); + (function (LOAD_TYPE) { + /** Uses XMLHttpRequest to load the resource. */ + LOAD_TYPE[LOAD_TYPE["XHR"] = 1] = "XHR"; + /** Uses an `Image` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["IMAGE"] = 2] = "IMAGE"; + /** Uses an `Audio` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["AUDIO"] = 3] = "AUDIO"; + /** Uses a `Video` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["VIDEO"] = 4] = "VIDEO"; + })(LoaderResource.LOAD_TYPE || (LoaderResource.LOAD_TYPE = {})); + (function (XHR_RESPONSE_TYPE) { + /** string */ + XHR_RESPONSE_TYPE["DEFAULT"] = "text"; + /** ArrayBuffer */ + XHR_RESPONSE_TYPE["BUFFER"] = "arraybuffer"; + /** Blob */ + XHR_RESPONSE_TYPE["BLOB"] = "blob"; + /** Document */ + XHR_RESPONSE_TYPE["DOCUMENT"] = "document"; + /** Object */ + XHR_RESPONSE_TYPE["JSON"] = "json"; + /** String */ + XHR_RESPONSE_TYPE["TEXT"] = "text"; + })(LoaderResource.XHR_RESPONSE_TYPE || (LoaderResource.XHR_RESPONSE_TYPE = {})); + LoaderResource._loadTypeMap = { + // images + gif: LoaderResource.LOAD_TYPE.IMAGE, + png: LoaderResource.LOAD_TYPE.IMAGE, + bmp: LoaderResource.LOAD_TYPE.IMAGE, + jpg: LoaderResource.LOAD_TYPE.IMAGE, + jpeg: LoaderResource.LOAD_TYPE.IMAGE, + tif: LoaderResource.LOAD_TYPE.IMAGE, + tiff: LoaderResource.LOAD_TYPE.IMAGE, + webp: LoaderResource.LOAD_TYPE.IMAGE, + tga: LoaderResource.LOAD_TYPE.IMAGE, + svg: LoaderResource.LOAD_TYPE.IMAGE, + 'svg+xml': LoaderResource.LOAD_TYPE.IMAGE, + // audio + mp3: LoaderResource.LOAD_TYPE.AUDIO, + ogg: LoaderResource.LOAD_TYPE.AUDIO, + wav: LoaderResource.LOAD_TYPE.AUDIO, + // videos + mp4: LoaderResource.LOAD_TYPE.VIDEO, + webm: LoaderResource.LOAD_TYPE.VIDEO, + }; + LoaderResource._xhrTypeMap = { + // xml + xhtml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + html: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + // images + gif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + png: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + bmp: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + jpg: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + jpeg: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tiff: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + webp: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tga: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + // json + json: LoaderResource.XHR_RESPONSE_TYPE.JSON, + // text + text: LoaderResource.XHR_RESPONSE_TYPE.TEXT, + txt: LoaderResource.XHR_RESPONSE_TYPE.TEXT, + // fonts + ttf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER, + otf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER, + }; + // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif + LoaderResource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + })(exports.LoaderResource || (exports.LoaderResource = {})); + + /** + * Smaller version of the async library constructs. + * @ignore + */ + function _noop() { + } + /** + * Ensures a function is only called once. + * @ignore + * @param {Function} fn - The function to wrap. + * @returns {Function} The wrapping function. + */ + function onlyOnce(fn) { + return function onceWrapper() { + var arguments$1 = arguments; + + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + if (fn === null) { + throw new Error('Callback was already called.'); + } + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + /** + * @private + * @memberof PIXI + */ + var AsyncQueueItem = /** @class */ (function () { + /** + * @param data + * @param callback + * @private + */ + function AsyncQueueItem(data, callback) { + this.data = data; + this.callback = callback; + } + return AsyncQueueItem; + }()); + /** + * @private + * @memberof PIXI + */ + var AsyncQueue = /** @class */ (function () { + /** + * @param worker + * @param concurrency + * @private + */ + function AsyncQueue(worker, concurrency) { + var _this = this; + if (concurrency === void 0) { concurrency = 1; } + this.workers = 0; + this.saturated = _noop; + this.unsaturated = _noop; + this.empty = _noop; + this.drain = _noop; + this.error = _noop; + this.started = false; + this.paused = false; + this._tasks = []; + this._insert = function (data, insertAtFront, callback) { + if (callback && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + _this.started = true; + // eslint-disable-next-line no-eq-null,eqeqeq + if (data == null && _this.idle()) { + // call drain immediately if there are no tasks + setTimeout(function () { return _this.drain(); }, 1); + return; + } + var item = new AsyncQueueItem(data, typeof callback === 'function' ? callback : _noop); + if (insertAtFront) { + _this._tasks.unshift(item); + } + else { + _this._tasks.push(item); + } + setTimeout(_this.process, 1); + }; + this.process = function () { + while (!_this.paused && _this.workers < _this.concurrency && _this._tasks.length) { + var task = _this._tasks.shift(); + if (_this._tasks.length === 0) { + _this.empty(); + } + _this.workers += 1; + if (_this.workers === _this.concurrency) { + _this.saturated(); + } + _this._worker(task.data, onlyOnce(_this._next(task))); + } + }; + this._worker = worker; + if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + this.concurrency = concurrency; + this.buffer = concurrency / 4.0; + } + /** + * @param task + * @private + */ + AsyncQueue.prototype._next = function (task) { + var _this = this; + return function () { + var arguments$1 = arguments; + + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + _this.workers -= 1; + task.callback.apply(task, args); + // eslint-disable-next-line no-eq-null,eqeqeq + if (args[0] != null) { + _this.error(args[0], task.data); + } + if (_this.workers <= (_this.concurrency - _this.buffer)) { + _this.unsaturated(); + } + if (_this.idle()) { + _this.drain(); + } + _this.process(); + }; + }; + // That was in object + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + AsyncQueue.prototype.push = function (data, callback) { + this._insert(data, false, callback); + }; + AsyncQueue.prototype.kill = function () { + this.workers = 0; + this.drain = _noop; + this.started = false; + this._tasks = []; + }; + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + AsyncQueue.prototype.unshift = function (data, callback) { + this._insert(data, true, callback); + }; + AsyncQueue.prototype.length = function () { + return this._tasks.length; + }; + AsyncQueue.prototype.running = function () { + return this.workers; + }; + AsyncQueue.prototype.idle = function () { + return this._tasks.length + this.workers === 0; + }; + AsyncQueue.prototype.pause = function () { + if (this.paused === true) { + return; + } + this.paused = true; + }; + AsyncQueue.prototype.resume = function () { + if (this.paused === false) { + return; + } + this.paused = false; + // Need to call this.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= this.concurrency; w++) { + this.process(); + } + }; + /** + * Iterates an array in series. + * @param {Array.<*>} array - Array to iterate. + * @param {Function} iterator - Function to call for each element. + * @param {Function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ + AsyncQueue.eachSeries = function (array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + return; + } + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } + else { + iterator(array[i++], next); + } + } + next(); + }; + /** + * Async queue implementation, + * @param {Function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @returns {*} The async queue object. + */ + AsyncQueue.queue = function (worker, concurrency) { + return new AsyncQueue(worker, concurrency); + }; + return AsyncQueue; + }()); + + // some constants + var MAX_PROGRESS = 100; + var rgxExtractUrlHash = /(#[\w-]+)?$/; + /** + * The new loader, forked from Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use. + * // or + * const loader = new PIXI.Loader(); // You can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * @memberof PIXI + */ + var Loader = /** @class */ (function () { + /** + * @param baseUrl - The base url for all resources loaded by this loader. + * @param concurrency - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + var _this = this; + if (baseUrl === void 0) { baseUrl = ''; } + if (concurrency === void 0) { concurrency = 10; } + /** The progress percent of the loader going through the queue. */ + this.progress = 0; + /** Loading state of the loader, true if it is currently loading resources. */ + this.loading = false; + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + */ + this.defaultQueryString = ''; + /** The middleware to run before loading each resource. */ + this._beforeMiddleware = []; + /** The middleware to run after loading each resource. */ + this._afterMiddleware = []; + /** The tracks the resources we are currently completing parsing for. */ + this._resourcesParsing = []; + /** + * The `_loadResource` function bound with this object context. + * @param r - The resource to load + * @param d - The dequeue function + */ + this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); }; + /** All the resources for this loader keyed by name. */ + this.resources = {}; + this.baseUrl = baseUrl; + this._beforeMiddleware = []; + this._afterMiddleware = []; + this._resourcesParsing = []; + this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); }; + this._queue = AsyncQueue.queue(this._boundLoadResource, concurrency); + this._queue.pause(); + this.resources = {}; + this.onProgress = new Signal(); + this.onError = new Signal(); + this.onLoad = new Signal(); + this.onStart = new Signal(); + this.onComplete = new Signal(); + for (var i = 0; i < Loader._plugins.length; ++i) { + var plugin = Loader._plugins[i]; + var pre = plugin.pre, use = plugin.use; + if (pre) { + this.pre(pre); + } + if (use) { + this.use(use); + } + } + this._protected = false; + } + /** + * Same as add, params have strict order + * @private + * @param name - The name of the resource to load. + * @param url - The url for this resource, relative to the baseUrl of this loader. + * @param options - The options for the load. + * @param callback - Function to call when this specific resource completes loading. + * @returns The loader itself. + */ + Loader.prototype._add = function (name, url, options, callback) { + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + // check if resource already exists. + if (this.resources[name]) { + throw new Error("Resource named \"" + name + "\" already exists."); + } + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + // create the store the resource + this.resources[name] = new exports.LoaderResource(name, url, options); + if (typeof callback === 'function') { + this.resources[name].onAfterMiddleware.once(callback); + } + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + for (var i = 0; i < parent.children.length; ++i) { + if (!parent.children[i].isComplete) { + incompleteChildren.push(parent.children[i]); + } + } + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + for (var i = 0; i < incompleteChildren.length; ++i) { + incompleteChildren[i].progressChunk = eachChunk; + } + this.resources[name].progressChunk = eachChunk; + } + // add the resource to the queue + this._queue.push(this.resources[name]); + return this; + }; + /* eslint-enable require-jsdoc,valid-jsdoc */ + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * @param fn - The middleware function to register. + * @returns The loader itself. + */ + Loader.prototype.pre = function (fn) { + this._beforeMiddleware.push(fn); + return this; + }; + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * @param fn - The middleware function to register. + * @returns The loader itself. + */ + Loader.prototype.use = function (fn) { + this._afterMiddleware.push(fn); + return this; + }; + /** + * Resets the queue of the loader to prepare for a new load. + * @returns The loader itself. + */ + Loader.prototype.reset = function () { + this.progress = 0; + this.loading = false; + this._queue.kill(); + this._queue.pause(); + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + if (res.isLoading) { + res.abort('loader reset'); + } + } + this.resources = {}; + return this; + }; + /** + * Starts loading the queued resources. + * @param cb - Optional callback that will be bound to the `complete` event. + * @returns The loader itself. + */ + Loader.prototype.load = function (cb) { + deprecation$1('6.5.0', '@pixi/loaders is being replaced with @pixi/assets in the next major release.'); + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + // if the queue has already started we are done here + if (this.loading) { + return this; + } + if (this._queue.idle()) { + this._onStart(); + this._onComplete(); + } + else { + // distribute progress chunks + var numTasks = this._queue._tasks.length; + var chunk = MAX_PROGRESS / numTasks; + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + // notify we are starting + this._onStart(); + // start loading + this._queue.resume(); + } + return this; + }; + Object.defineProperty(Loader.prototype, "concurrency", { + /** + * The number of resources to load concurrently. + * @default 10 + */ + get: function () { + return this._queue.concurrency; + }, + set: function (concurrency) { + this._queue.concurrency = concurrency; + }, + enumerable: false, + configurable: true + }); + /** + * Prepares a url for usage based on the configuration of this object + * @param url - The url to prepare. + * @returns The prepared url. + */ + Loader.prototype._prepareUrl = function (url) { + var parsedUrl = parseUri(url, { strictMode: true }); + var result; + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length + && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 + && url.charAt(0) !== '/') { + result = this.baseUrl + "/" + url; + } + else { + result = this.baseUrl + url; + } + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + result = result.slice(0, result.length - hash.length); + if (result.indexOf('?') !== -1) { + result += "&" + this.defaultQueryString; + } + else { + result += "?" + this.defaultQueryString; + } + result += hash; + } + return result; + }; + /** + * Loads a single resource. + * @param resource - The resource to load. + * @param dequeue - The function to call when we need to dequeue this item. + */ + Loader.prototype._loadResource = function (resource, dequeue) { + var _this = this; + resource._dequeue = dequeue; + // run before middleware + AsyncQueue.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this._onLoad(resource); + } + else { + resource._onLoadBinding = resource.onComplete.once(_this._onLoad, _this); + resource.load(); + } + }, true); + }; + /** Called once loading has started. */ + Loader.prototype._onStart = function () { + this.progress = 0; + this.loading = true; + this.onStart.dispatch(this); + }; + /** Called once each resource has loaded. */ + Loader.prototype._onComplete = function () { + this.progress = MAX_PROGRESS; + this.loading = false; + this.onComplete.dispatch(this, this.resources); + }; + /** + * Called each time a resources is loaded. + * @param resource - The resource that was loaded + */ + Loader.prototype._onLoad = function (resource) { + var _this = this; + resource._onLoadBinding = null; + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + // run all the after middleware for this resource + AsyncQueue.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + _this.progress = Math.min(MAX_PROGRESS, _this.progress + resource.progressChunk); + _this.onProgress.dispatch(_this, resource); + if (resource.error) { + _this.onError.dispatch(resource.error, _this, resource); + } + else { + _this.onLoad.dispatch(_this, resource); + } + _this._resourcesParsing.splice(_this._resourcesParsing.indexOf(resource), 1); + // do completion check + if (_this._queue.idle() && _this._resourcesParsing.length === 0) { + _this._onComplete(); + } + }, true); + }; + /** Destroy the loader, removes references. */ + Loader.prototype.destroy = function () { + if (!this._protected) { + this.reset(); + } + }; + Object.defineProperty(Loader, "shared", { + /** A premade instance of the loader that can be used to load resources. */ + get: function () { + var shared = Loader._shared; + if (!shared) { + shared = new Loader(); + shared._protected = true; + Loader._shared = shared; + } + return shared; + }, + enumerable: false, + configurable: true + }); + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @param plugin - The plugin to add + * @returns Reference to PIXI.Loader for chaining + */ + Loader.registerPlugin = function (plugin) { + deprecation$1('6.5.0', 'Loader.registerPlugin() is deprecated, use extensions.add() instead.'); + extensions.add({ + type: exports.ExtensionType.Loader, + ref: plugin, + }); + return Loader; + }; + Loader._plugins = []; + return Loader; + }()); + extensions.handleByList(exports.ExtensionType.Loader, Loader._plugins); + Loader.prototype.add = function add(name, url, options, callback) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + return this; + } + // if an object is passed instead of params + if (typeof name === 'object') { + options = name; + callback = url || options.callback || options.onComplete; + url = options.url; + name = options.name || options.key || options.url; + } + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + callback = options; + options = url; + url = name; + } + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + callback = options; + options = null; + } + return this._add(name, url, options, callback); + }; + + /** + * Application plugin for supporting loader option. Installing the LoaderPlugin + * is not necessary if using **pixi.js** or **pixi.js-legacy**. + * @example + * import {AppLoaderPlugin} from '@pixi/loaders'; + * import {extensions} from '@pixi/core'; + * extensions.add(AppLoaderPlugin); + * @memberof PIXI + */ + var AppLoaderPlugin = /** @class */ (function () { + function AppLoaderPlugin() { + } + /** + * Called on application constructor + * @param options + * @private + */ + AppLoaderPlugin.init = function (options) { + options = Object.assign({ + sharedLoader: false, + }, options); + this.loader = options.sharedLoader ? Loader.shared : new Loader(); + }; + /** + * Called when application destroyed + * @private + */ + AppLoaderPlugin.destroy = function () { + if (this.loader) { + this.loader.destroy(); + this.loader = null; + } + }; + /** @ignore */ + AppLoaderPlugin.extension = exports.ExtensionType.Application; + return AppLoaderPlugin; + }()); + + /** + * Loader plugin for handling Texture resources. + * @memberof PIXI + */ + var TextureLoader = /** @class */ (function () { + function TextureLoader() { + } + /** Handle SVG elements a text, render with SVGResource. */ + TextureLoader.add = function () { + exports.LoaderResource.setExtensionLoadType('svg', exports.LoaderResource.LOAD_TYPE.XHR); + exports.LoaderResource.setExtensionXhrType('svg', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT); + }; + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param resource + * @param {Function} next + */ + TextureLoader.use = function (resource, next) { + // create a new texture if the data is an Image object + if (resource.data && (resource.type === exports.LoaderResource.TYPE.IMAGE || resource.extension === 'svg')) { + var data = resource.data, url = resource.url, name = resource.name, metadata = resource.metadata; + Texture.fromLoader(data, url, name, metadata).then(function (texture) { + resource.texture = texture; + next(); + }) + // TODO: handle errors in Texture.fromLoader + // so we can pass them to the Loader + .catch(next); + } + else { + next(); + } + }; + /** @ignore */ + TextureLoader.extension = exports.ExtensionType.Loader; + return TextureLoader; + }()); + + var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + /** + * Encodes binary into base64. + * @function encodeBinary + * @param {string} input - The input data to encode. + * @returns {string} The encoded base64 string + */ + function encodeBinary(input) { + var output = ''; + var inx = 0; + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } + else { + bytebuffer[jnx] = 0; + } + } + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + } + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var jnx = 0; jnx < encodedCharIndexes.length; ++jnx) { + output += _keyStr.charAt(encodedCharIndexes[jnx]); + } + } + return output; + } + + /** + * A middleware for transforming XHR loaded Blobs into more useful objects + * @ignore + * @function parsing + * @example + * import { Loader, middleware } from 'resource-loader'; + * const loader = new Loader(); + * loader.use(middleware.parsing); + * @param resource - Current Resource + * @param next - Callback when complete + */ + function parsing(resource, next) { + if (!resource.data) { + next(); + return; + } + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === exports.LoaderResource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!self.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText); + resource.type = exports.LoaderResource.TYPE.IMAGE; + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + next(); + }; + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var Url_1 = globalThis.URL || globalThis.webkitURL; + var src_1 = Url_1.createObjectURL(resource.data); + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src_1; + resource.type = exports.LoaderResource.TYPE.IMAGE; + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url_1.revokeObjectURL(src_1); + resource.data.onload = null; + next(); + }; + // next will be called on load. + return; + } + } + next(); + } + + /** + * Parse any blob into more usable objects (e.g. Image). + * @memberof PIXI + */ + var ParsingLoader = /** @class */ (function () { + function ParsingLoader() { + } + /** @ignore */ + ParsingLoader.extension = exports.ExtensionType.Loader; + ParsingLoader.use = parsing; + return ParsingLoader; + }()); + + extensions.add(TextureLoader, ParsingLoader); + + /*! + * @pixi/compressed-textures - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/compressed-textures is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + var _a$2; + /** + * WebGL internal formats, including compressed texture formats provided by extensions + * @memberof PIXI + * @static + * @name INTERNAL_FORMATS + * @enum {number} + * @property {number} [COMPRESSED_RGB_S3TC_DXT1_EXT=0x83F0] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT1_EXT=0x83F1] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT3_EXT=0x83F2] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT5_EXT=0x83F3] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919] - + * @property {number} [COMPRESSED_SRGB_S3TC_DXT1_EXT=35916] - + * @property {number} [COMPRESSED_R11_EAC=0x9270] - + * @property {number} [COMPRESSED_SIGNED_R11_EAC=0x9271] - + * @property {number} [COMPRESSED_RG11_EAC=0x9272] - + * @property {number} [COMPRESSED_SIGNED_RG11_EAC=0x9273] - + * @property {number} [COMPRESSED_RGB8_ETC2=0x9274] - + * @property {number} [COMPRESSED_RGBA8_ETC2_EAC=0x9278] - + * @property {number} [COMPRESSED_SRGB8_ETC2=0x9275] - + * @property {number} [COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=0x9279] - + * @property {number} [COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9276] - + * @property {number} [COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9277] - + * @property {number} [COMPRESSED_RGB_PVRTC_4BPPV1_IMG=0x8C00] - + * @property {number} [COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=0x8C02] - + * @property {number} [COMPRESSED_RGB_PVRTC_2BPPV1_IMG=0x8C01] - + * @property {number} [COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=0x8C03] - + * @property {number} [COMPRESSED_RGB_ETC1_WEBGL=0x8D64] - + * @property {number} [COMPRESSED_RGB_ATC_WEBGL=0x8C92] - + * @property {number} [COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=0x8C92] - + * @property {number} [COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=0x87EE] - + */ + exports.INTERNAL_FORMATS = void 0; + (function (INTERNAL_FORMATS) { + // WEBGL_compressed_texture_s3tc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; + // WEBGL_compressed_texture_s3tc_srgb + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT"; + // WEBGL_compressed_texture_etc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + // WEBGL_compressed_texture_pvrtc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; + // WEBGL_compressed_texture_etc1 + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; + // WEBGL_compressed_texture_atc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"; + })(exports.INTERNAL_FORMATS || (exports.INTERNAL_FORMATS = {})); + /** + * Maps the compressed texture formats in {@link PIXI.INTERNAL_FORMATS} to the number of bytes taken by + * each texel. + * @memberof PIXI + * @static + * @ignore + */ + var INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = (_a$2 = {}, + // WEBGL_compressed_texture_s3tc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1, + // WEBGL_compressed_texture_s3tc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT] = 1, + // WEBGL_compressed_texture_etc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_R11_EAC] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_R11_EAC] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RG11_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_RG11_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA8_ETC2_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5, + // WEBGL_compressed_texture_pvrtc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25, + // WEBGL_compressed_texture_etc1 + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ETC1_WEBGL] = 0.5, + // @see https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_compressed_ATC_texture.txt + // WEBGL_compressed_texture_atc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ATC_WEBGL] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1, + _a$2); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$g = function(d, b) { + extendStatics$g = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$g(d, b); + }; + + function __extends$g(d, b) { + extendStatics$g(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) { throw t[1]; } return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) { throw new TypeError("Generator is already executing."); } + while (_) { try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) { return t; } + if (y = 0, t) { op = [op[0] & 2, t.value]; } + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) { _.ops.pop(); } + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } } + if (op[0] & 5) { throw op[1]; } return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + /** + * Resource that fetches texture data over the network and stores it in a buffer. + * @class + * @extends PIXI.Resource + * @memberof PIXI + */ + var BlobResource = /** @class */ (function (_super) { + __extends$g(BlobResource, _super); + /** + * @param {string} source - the URL of the texture file + * @param {PIXI.IBlobOptions} options + * @param {boolean}[options.autoLoad] - whether to fetch the data immediately; + * you can fetch it later via {@link BlobResource#load} + * @param {boolean}[options.width] - the width in pixels. + * @param {boolean}[options.height] - the height in pixels. + */ + function BlobResource(source, options) { + if (options === void 0) { options = { width: 1, height: 1, autoLoad: true }; } + var _this = this; + var origin; + var data; + if (typeof source === 'string') { + origin = source; + data = new Uint8Array(); + } + else { + origin = null; + data = source; + } + _this = _super.call(this, data, options) || this; + /** + * The URL of the texture file + * @member {string} + */ + _this.origin = origin; + /** + * The viewable buffer on the data + * @member {ViewableBuffer} + */ + // HINT: BlobResource allows "null" sources, assuming the child class provides an alternative + _this.buffer = data ? new ViewableBuffer(data) : null; + // Allow autoLoad = "undefined" still load the resource by default + if (_this.origin && options.autoLoad !== false) { + _this.load(); + } + if (data && data.length) { + _this.loaded = true; + _this.onBlobLoaded(_this.buffer.rawBinaryData); + } + return _this; + } + BlobResource.prototype.onBlobLoaded = function (_data) { + // TODO: Override this method + }; + /** Loads the blob */ + BlobResource.prototype.load = function () { + return __awaiter(this, void 0, Promise, function () { + var response, blob, arrayBuffer; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, fetch(this.origin)]; + case 1: + response = _a.sent(); + return [4 /*yield*/, response.blob()]; + case 2: + blob = _a.sent(); + return [4 /*yield*/, blob.arrayBuffer()]; + case 3: + arrayBuffer = _a.sent(); + this.data = new Uint32Array(arrayBuffer); + this.buffer = new ViewableBuffer(arrayBuffer); + this.loaded = true; + this.onBlobLoaded(arrayBuffer); + this.update(); + return [2 /*return*/, this]; + } + }); + }); + }; + return BlobResource; + }(BufferResource)); + + /** + * Resource for compressed texture formats, as follows: S3TC/DXTn (& their sRGB formats), ATC, ASTC, ETC 1/2, PVRTC. + * + * Compressed textures improve performance when rendering is texture-bound. The texture data stays compressed in + * graphics memory, increasing memory locality and speeding up texture fetches. These formats can also be used to store + * more detail in the same amount of memory. + * + * For most developers, container file formats are a better abstraction instead of directly handling raw texture + * data. PixiJS provides native support for the following texture file formats (via {@link PIXI.Loader}): + * + * **.dds** - the DirectDraw Surface file format stores DXTn (DXT-1,3,5) data. See {@link PIXI.DDSLoader} + * **.ktx** - the Khronos Texture Container file format supports storing all the supported WebGL compression formats. + * See {@link PIXI.KTXLoader}. + * **.basis** - the BASIS supercompressed file format stores texture data in an internal format that is transcoded + * to the compression format supported on the device at _runtime_. It also supports transcoding into a uncompressed + * format as a fallback; you must install the `@pixi/basis-loader`, `@pixi/basis-transcoder` packages separately to + * use these files. See {@link PIXI.BasisLoader}. + * + * The loaders for the aforementioned formats use `CompressedTextureResource` internally. It is strongly suggested that + * they be used instead. + * + * ## Working directly with CompressedTextureResource + * + * Since `CompressedTextureResource` inherits `BlobResource`, you can provide it a URL pointing to a file containing + * the raw texture data (with no file headers!): + * + * ```js + * // The resource backing the texture data for your textures. + * // NOTE: You can also provide a ArrayBufferView instead of a URL. This is used when loading data from a container file + * // format such as KTX, DDS, or BASIS. + * const compressedResource = new PIXI.CompressedTextureResource("bunny.dxt5", { + * format: PIXI.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + * width: 256, + * height: 256 + * }); + * + * // You can create a base-texture to the cache, so that future `Texture`s can be created using the `Texture.from` API. + * const baseTexture = new PIXI.BaseTexture(compressedResource, { pmaMode: PIXI.ALPHA_MODES.NPM }); + * + * // Create a Texture to add to the TextureCache + * const texture = new PIXI.Texture(baseTexture); + * + * // Add baseTexture & texture to the global texture cache + * PIXI.BaseTexture.addToCache(baseTexture, "bunny.dxt5"); + * PIXI.Texture.addToCache(texture, "bunny.dxt5"); + * ``` + * @memberof PIXI + */ + var CompressedTextureResource = /** @class */ (function (_super) { + __extends$g(CompressedTextureResource, _super); + /** + * @param source - the buffer/URL holding the compressed texture data + * @param options + * @param {PIXI.INTERNAL_FORMATS} options.format - the compression format + * @param {number} options.width - the image width in pixels. + * @param {number} options.height - the image height in pixels. + * @param {number} [options.level=1] - the mipmap levels stored in the compressed texture, including level 0. + * @param {number} [options.levelBuffers] - the buffers for each mipmap level. `CompressedTextureResource` can allows you + * to pass `null` for `source`, for cases where each level is stored in non-contiguous memory. + */ + function CompressedTextureResource(source, options) { + var _this = _super.call(this, source, options) || this; + _this.format = options.format; + _this.levels = options.levels || 1; + _this._width = options.width; + _this._height = options.height; + _this._extension = CompressedTextureResource._formatToExtension(_this.format); + if (options.levelBuffers || _this.buffer) { + // ViewableBuffer doesn't support byteOffset :-( so allow source to be Uint8Array + _this._levelBuffers = options.levelBuffers + || CompressedTextureResource._createLevelBuffers(source instanceof Uint8Array ? source : _this.buffer.uint8View, _this.format, _this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode + _this.width, _this.height); + } + return _this; + } + /** + * @override + * @param renderer - A reference to the current renderer + * @param _texture - the texture + * @param _glTexture - texture instance for this webgl context + */ + CompressedTextureResource.prototype.upload = function (renderer, _texture, _glTexture) { + var gl = renderer.gl; + var extension = renderer.context.extensions[this._extension]; + if (!extension) { + throw new Error(this._extension + " textures are not supported on the current machine"); + } + if (!this._levelBuffers) { + // Do not try to upload data before BlobResource loads, unless the levelBuffers were provided directly! + return false; + } + for (var i = 0, j = this.levels; i < j; i++) { + var _a = this._levelBuffers[i], levelID = _a.levelID, levelWidth = _a.levelWidth, levelHeight = _a.levelHeight, levelBuffer = _a.levelBuffer; + gl.compressedTexImage2D(gl.TEXTURE_2D, levelID, this.format, levelWidth, levelHeight, 0, levelBuffer); + } + return true; + }; + /** @protected */ + CompressedTextureResource.prototype.onBlobLoaded = function () { + this._levelBuffers = CompressedTextureResource._createLevelBuffers(this.buffer.uint8View, this.format, this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode + this.width, this.height); + }; + /** + * Returns the key (to ContextSystem#extensions) for the WebGL extension supporting the compression format + * @private + * @param format - the compression format to get the extension for. + */ + CompressedTextureResource._formatToExtension = function (format) { + if (format >= 0x83F0 && format <= 0x83F3) { + return 's3tc'; + } + else if (format >= 0x9270 && format <= 0x9279) { + return 'etc'; + } + else if (format >= 0x8C00 && format <= 0x8C03) { + return 'pvrtc'; + } + else if (format >= 0x8D64) { + return 'etc1'; + } + else if (format >= 0x8C92 && format <= 0x87EE) { + return 'atc'; + } + throw new Error('Invalid (compressed) texture format given!'); + }; + /** + * Pre-creates buffer views for each mipmap level + * @private + * @param buffer - + * @param format - compression formats + * @param levels - mipmap levels + * @param blockWidth - + * @param blockHeight - + * @param imageWidth - width of the image in pixels + * @param imageHeight - height of the image in pixels + */ + CompressedTextureResource._createLevelBuffers = function (buffer, format, levels, blockWidth, blockHeight, imageWidth, imageHeight) { + // The byte-size of the first level buffer + var buffers = new Array(levels); + var offset = buffer.byteOffset; + var levelWidth = imageWidth; + var levelHeight = imageHeight; + var alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1); + var alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1); + var levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; + for (var i = 0; i < levels; i++) { + buffers[i] = { + levelID: i, + levelWidth: levels > 1 ? levelWidth : alignedLevelWidth, + levelHeight: levels > 1 ? levelHeight : alignedLevelHeight, + levelBuffer: new Uint8Array(buffer.buffer, offset, levelSize) + }; + offset += levelSize; + // Calculate levelBuffer dimensions for next iteration + levelWidth = (levelWidth >> 1) || 1; + levelHeight = (levelHeight >> 1) || 1; + alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1); + alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1); + levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; + } + return buffers; + }; + return CompressedTextureResource; + }(BlobResource)); + + /* eslint-enable camelcase */ + /** + * Loader plugin for handling compressed textures for all platforms. + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + */ + var CompressedTextureLoader = /** @class */ (function () { + function CompressedTextureLoader() { + } + /** + * Called after a compressed-textures manifest is loaded. + * + * This will then load the correct compression format for the device. Your manifest should adhere + * to the following schema: + * + * ```js + * import { INTERNAL_FORMATS } from '@pixi/constants'; + * + * type CompressedTextureManifest = { + * textures: Array<{ src: string, format?: keyof INTERNAL_FORMATS}>, + * cacheID: string; + * }; + * ``` + * + * This is an example of a .json manifest file + * + * ```json + * { + * "cacheID":"asset", + * "textures":[ + * { "src":"asset.fallback.png" }, + * { "format":"COMPRESSED_RGBA_S3TC_DXT5_EXT", "src":"asset.s3tc.ktx" }, + * { "format":"COMPRESSED_RGBA8_ETC2_EAC", "src":"asset.etc.ktx" }, + * { "format":"RGBA_PVRTC_4BPPV1_IMG", "src":"asset.pvrtc.ktx" } + * ] + * } + * ``` + */ + CompressedTextureLoader.use = function (resource, next) { + var data = resource.data; + var loader = this; + if (resource.type === exports.LoaderResource.TYPE.JSON + && data + && data.cacheID + && data.textures) { + var textures = data.textures; + var textureURL = void 0; + var fallbackURL = void 0; + // Search for an extension that holds one the formats + for (var i = 0, j = textures.length; i < j; i++) { + var texture = textures[i]; + var url_1 = texture.src; + var format = texture.format; + if (!format) { + fallbackURL = url_1; + } + if (CompressedTextureLoader.textureFormats[format]) { + textureURL = url_1; + break; + } + } + textureURL = textureURL || fallbackURL; + // Make sure we have a URL + if (!textureURL) { + next(new Error("Cannot load compressed-textures in " + resource.url + ", make sure you provide a fallback")); + return; + } + if (textureURL === resource.url) { + // Prevent infinite loops + next(new Error('URL of compressed texture cannot be the same as the manifest\'s URL')); + return; + } + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + var resourcePath = url.resolve(resource.url.replace(loader.baseUrl, ''), textureURL); + var resourceName = data.cacheID; + // The appropriate loader should register the texture + loader.add(resourceName, resourcePath, loadOptions, function (res) { + if (res.error) { + next(res.error); + return; + } + var _a = res.texture, texture = _a === void 0 ? null : _a, _b = res.textures, textures = _b === void 0 ? {} : _b; + // Make sure texture/textures is assigned to parent resource + Object.assign(resource, { texture: texture, textures: textures }); + // Pass along any error + next(); + }); + } + else { + next(); + } + }; + Object.defineProperty(CompressedTextureLoader, "textureExtensions", { + /** Map of available texture extensions. */ + get: function () { + if (!CompressedTextureLoader._textureExtensions) { + // Auto-detect WebGL compressed-texture extensions + var canvas = settings$1.ADAPTER.createCanvas(); + var gl = canvas.getContext('webgl'); + if (!gl) { + console.warn('WebGL not available for compressed textures. Silently failing.'); + return {}; + } + var extensions = { + s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'), + s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'), + etc: gl.getExtension('WEBGL_compressed_texture_etc'), + etc1: gl.getExtension('WEBGL_compressed_texture_etc1'), + pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc') + || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'), + atc: gl.getExtension('WEBGL_compressed_texture_atc'), + astc: gl.getExtension('WEBGL_compressed_texture_astc') + }; + CompressedTextureLoader._textureExtensions = extensions; + } + return CompressedTextureLoader._textureExtensions; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CompressedTextureLoader, "textureFormats", { + /** Map of available texture formats. */ + get: function () { + if (!CompressedTextureLoader._textureFormats) { + var extensions = CompressedTextureLoader.textureExtensions; + CompressedTextureLoader._textureFormats = {}; + // Assign all available compressed-texture formats + for (var extensionName in extensions) { + var extension = extensions[extensionName]; + if (!extension) { + continue; + } + Object.assign(CompressedTextureLoader._textureFormats, Object.getPrototypeOf(extension)); + } + } + return CompressedTextureLoader._textureFormats; + }, + enumerable: false, + configurable: true + }); + /** @ignore */ + CompressedTextureLoader.extension = exports.ExtensionType.Loader; + return CompressedTextureLoader; + }()); + + /** + * Creates base-textures and textures for each compressed-texture resource and adds them into the global + * texture cache. The first texture has two IDs - `${url}`, `${url}-1`; while the rest have an ID of the + * form `${url}-i`. + * @param url - the original address of the resources + * @param resources - the resources backing texture data + * @ignore + */ + function registerCompressedTextures(url, resources, metadata) { + var result = { + textures: {}, + texture: null, + }; + if (!resources) { + return result; + } + var textures = resources.map(function (resource) { + return (new Texture(new BaseTexture(resource, Object.assign({ + mipmap: exports.MIPMAP_MODES.OFF, + alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA + }, metadata)))); + }); + textures.forEach(function (texture, i) { + var baseTexture = texture.baseTexture; + var cacheID = url + "-" + (i + 1); + BaseTexture.addToCache(baseTexture, cacheID); + Texture.addToCache(texture, cacheID); + if (i === 0) { + BaseTexture.addToCache(baseTexture, url); + Texture.addToCache(texture, url); + result.texture = texture; + } + result.textures[cacheID] = texture; + }); + return result; + } + + var _a$1, _b$1; + var DDS_MAGIC_SIZE = 4; + var DDS_HEADER_SIZE = 124; + var DDS_HEADER_PF_SIZE = 32; + var DDS_HEADER_DX10_SIZE = 20; + // DDS file format magic word + var DDS_MAGIC = 0x20534444; + /** + * DWORD offsets of the DDS file header fields (relative to file start). + * @ignore + */ + var DDS_FIELDS = { + SIZE: 1, + FLAGS: 2, + HEIGHT: 3, + WIDTH: 4, + MIPMAP_COUNT: 7, + PIXEL_FORMAT: 19, + }; + /** + * DWORD offsets of the DDS PIXEL_FORMAT fields. + * @ignore + */ + var DDS_PF_FIELDS = { + SIZE: 0, + FLAGS: 1, + FOURCC: 2, + RGB_BITCOUNT: 3, + R_BIT_MASK: 4, + G_BIT_MASK: 5, + B_BIT_MASK: 6, + A_BIT_MASK: 7 + }; + /** + * DWORD offsets of the DDS_HEADER_DX10 fields. + * @ignore + */ + var DDS_DX10_FIELDS = { + DXGI_FORMAT: 0, + RESOURCE_DIMENSION: 1, + MISC_FLAG: 2, + ARRAY_SIZE: 3, + MISC_FLAGS2: 4 + }; + /** + * @see https://docs.microsoft.com/en-us/windows/win32/api/dxgiformat/ne-dxgiformat-dxgi_format + * @ignore + */ + // This is way over-blown for us! Lend us a hand, and remove the ones that aren't used (but set the remaining + // ones to their correct value) + var DXGI_FORMAT; + (function (DXGI_FORMAT) { + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_UNKNOWN"] = 0] = "DXGI_FORMAT_UNKNOWN"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_TYPELESS"] = 1] = "DXGI_FORMAT_R32G32B32A32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_FLOAT"] = 2] = "DXGI_FORMAT_R32G32B32A32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_UINT"] = 3] = "DXGI_FORMAT_R32G32B32A32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_SINT"] = 4] = "DXGI_FORMAT_R32G32B32A32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_TYPELESS"] = 5] = "DXGI_FORMAT_R32G32B32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_FLOAT"] = 6] = "DXGI_FORMAT_R32G32B32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_UINT"] = 7] = "DXGI_FORMAT_R32G32B32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_SINT"] = 8] = "DXGI_FORMAT_R32G32B32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_TYPELESS"] = 9] = "DXGI_FORMAT_R16G16B16A16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_FLOAT"] = 10] = "DXGI_FORMAT_R16G16B16A16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UNORM"] = 11] = "DXGI_FORMAT_R16G16B16A16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UINT"] = 12] = "DXGI_FORMAT_R16G16B16A16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SNORM"] = 13] = "DXGI_FORMAT_R16G16B16A16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SINT"] = 14] = "DXGI_FORMAT_R16G16B16A16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_TYPELESS"] = 15] = "DXGI_FORMAT_R32G32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_FLOAT"] = 16] = "DXGI_FORMAT_R32G32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_UINT"] = 17] = "DXGI_FORMAT_R32G32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_SINT"] = 18] = "DXGI_FORMAT_R32G32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G8X24_TYPELESS"] = 19] = "DXGI_FORMAT_R32G8X24_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT_S8X24_UINT"] = 20] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"] = 21] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"] = 22] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_TYPELESS"] = 23] = "DXGI_FORMAT_R10G10B10A2_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UNORM"] = 24] = "DXGI_FORMAT_R10G10B10A2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UINT"] = 25] = "DXGI_FORMAT_R10G10B10A2_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R11G11B10_FLOAT"] = 26] = "DXGI_FORMAT_R11G11B10_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_TYPELESS"] = 27] = "DXGI_FORMAT_R8G8B8A8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM"] = 28] = "DXGI_FORMAT_R8G8B8A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"] = 29] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UINT"] = 30] = "DXGI_FORMAT_R8G8B8A8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SNORM"] = 31] = "DXGI_FORMAT_R8G8B8A8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SINT"] = 32] = "DXGI_FORMAT_R8G8B8A8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_TYPELESS"] = 33] = "DXGI_FORMAT_R16G16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_FLOAT"] = 34] = "DXGI_FORMAT_R16G16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UNORM"] = 35] = "DXGI_FORMAT_R16G16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UINT"] = 36] = "DXGI_FORMAT_R16G16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SNORM"] = 37] = "DXGI_FORMAT_R16G16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SINT"] = 38] = "DXGI_FORMAT_R16G16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_TYPELESS"] = 39] = "DXGI_FORMAT_R32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT"] = 40] = "DXGI_FORMAT_D32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT"] = 41] = "DXGI_FORMAT_R32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_UINT"] = 42] = "DXGI_FORMAT_R32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_SINT"] = 43] = "DXGI_FORMAT_R32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24G8_TYPELESS"] = 44] = "DXGI_FORMAT_R24G8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D24_UNORM_S8_UINT"] = 45] = "DXGI_FORMAT_D24_UNORM_S8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24_UNORM_X8_TYPELESS"] = 46] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X24_TYPELESS_G8_UINT"] = 47] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_TYPELESS"] = 48] = "DXGI_FORMAT_R8G8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UNORM"] = 49] = "DXGI_FORMAT_R8G8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UINT"] = 50] = "DXGI_FORMAT_R8G8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SNORM"] = 51] = "DXGI_FORMAT_R8G8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SINT"] = 52] = "DXGI_FORMAT_R8G8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_TYPELESS"] = 53] = "DXGI_FORMAT_R16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_FLOAT"] = 54] = "DXGI_FORMAT_R16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D16_UNORM"] = 55] = "DXGI_FORMAT_D16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UNORM"] = 56] = "DXGI_FORMAT_R16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UINT"] = 57] = "DXGI_FORMAT_R16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SNORM"] = 58] = "DXGI_FORMAT_R16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SINT"] = 59] = "DXGI_FORMAT_R16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_TYPELESS"] = 60] = "DXGI_FORMAT_R8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UNORM"] = 61] = "DXGI_FORMAT_R8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UINT"] = 62] = "DXGI_FORMAT_R8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SNORM"] = 63] = "DXGI_FORMAT_R8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SINT"] = 64] = "DXGI_FORMAT_R8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8_UNORM"] = 65] = "DXGI_FORMAT_A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R1_UNORM"] = 66] = "DXGI_FORMAT_R1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R9G9B9E5_SHAREDEXP"] = 67] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_B8G8_UNORM"] = 68] = "DXGI_FORMAT_R8G8_B8G8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_G8R8_G8B8_UNORM"] = 69] = "DXGI_FORMAT_G8R8_G8B8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_TYPELESS"] = 70] = "DXGI_FORMAT_BC1_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM"] = 71] = "DXGI_FORMAT_BC1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM_SRGB"] = 72] = "DXGI_FORMAT_BC1_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_TYPELESS"] = 73] = "DXGI_FORMAT_BC2_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM"] = 74] = "DXGI_FORMAT_BC2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM_SRGB"] = 75] = "DXGI_FORMAT_BC2_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_TYPELESS"] = 76] = "DXGI_FORMAT_BC3_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM"] = 77] = "DXGI_FORMAT_BC3_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM_SRGB"] = 78] = "DXGI_FORMAT_BC3_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_TYPELESS"] = 79] = "DXGI_FORMAT_BC4_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_UNORM"] = 80] = "DXGI_FORMAT_BC4_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_SNORM"] = 81] = "DXGI_FORMAT_BC4_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_TYPELESS"] = 82] = "DXGI_FORMAT_BC5_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_UNORM"] = 83] = "DXGI_FORMAT_BC5_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_SNORM"] = 84] = "DXGI_FORMAT_BC5_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G6R5_UNORM"] = 85] = "DXGI_FORMAT_B5G6R5_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G5R5A1_UNORM"] = 86] = "DXGI_FORMAT_B5G5R5A1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM"] = 87] = "DXGI_FORMAT_B8G8R8A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM"] = 88] = "DXGI_FORMAT_B8G8R8X8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"] = 89] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_TYPELESS"] = 90] = "DXGI_FORMAT_B8G8R8A8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"] = 91] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_TYPELESS"] = 92] = "DXGI_FORMAT_B8G8R8X8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"] = 93] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_TYPELESS"] = 94] = "DXGI_FORMAT_BC6H_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_UF16"] = 95] = "DXGI_FORMAT_BC6H_UF16"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_SF16"] = 96] = "DXGI_FORMAT_BC6H_SF16"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_TYPELESS"] = 97] = "DXGI_FORMAT_BC7_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM"] = 98] = "DXGI_FORMAT_BC7_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM_SRGB"] = 99] = "DXGI_FORMAT_BC7_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AYUV"] = 100] = "DXGI_FORMAT_AYUV"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y410"] = 101] = "DXGI_FORMAT_Y410"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y416"] = 102] = "DXGI_FORMAT_Y416"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV12"] = 103] = "DXGI_FORMAT_NV12"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P010"] = 104] = "DXGI_FORMAT_P010"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P016"] = 105] = "DXGI_FORMAT_P016"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_420_OPAQUE"] = 106] = "DXGI_FORMAT_420_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_YUY2"] = 107] = "DXGI_FORMAT_YUY2"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y210"] = 108] = "DXGI_FORMAT_Y210"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y216"] = 109] = "DXGI_FORMAT_Y216"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV11"] = 110] = "DXGI_FORMAT_NV11"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AI44"] = 111] = "DXGI_FORMAT_AI44"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_IA44"] = 112] = "DXGI_FORMAT_IA44"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P8"] = 113] = "DXGI_FORMAT_P8"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8P8"] = 114] = "DXGI_FORMAT_A8P8"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B4G4R4A4_UNORM"] = 115] = "DXGI_FORMAT_B4G4R4A4_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P208"] = 116] = "DXGI_FORMAT_P208"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V208"] = 117] = "DXGI_FORMAT_V208"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V408"] = 118] = "DXGI_FORMAT_V408"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"] = 119] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"] = 120] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_FORCE_UINT"] = 121] = "DXGI_FORMAT_FORCE_UINT"; + })(DXGI_FORMAT || (DXGI_FORMAT = {})); + /** + * Possible values of the field {@link DDS_DX10_FIELDS.RESOURCE_DIMENSION} + * @ignore + */ + var D3D10_RESOURCE_DIMENSION; + (function (D3D10_RESOURCE_DIMENSION) { + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE1D"] = 2] = "DDS_DIMENSION_TEXTURE1D"; + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE2D"] = 3] = "DDS_DIMENSION_TEXTURE2D"; + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE3D"] = 6] = "DDS_DIMENSION_TEXTURE3D"; + })(D3D10_RESOURCE_DIMENSION || (D3D10_RESOURCE_DIMENSION = {})); + var PF_FLAGS = 1; + // PIXEL_FORMAT flags + var DDPF_ALPHA = 0x2; + var DDPF_FOURCC = 0x4; + var DDPF_RGB = 0x40; + var DDPF_YUV = 0x200; + var DDPF_LUMINANCE = 0x20000; + // Four character codes for DXTn formats + var FOURCC_DXT1 = 0x31545844; + var FOURCC_DXT3 = 0x33545844; + var FOURCC_DXT5 = 0x35545844; + var FOURCC_DX10 = 0x30315844; + // Cubemap texture flag (for DDS_DX10_FIELDS.MISC_FLAG) + var DDS_RESOURCE_MISC_TEXTURECUBE = 0x4; + /** + * Maps `FOURCC_*` formats to internal formats (see {@link PIXI.INTERNAL_FORMATS}). + * @ignore + */ + var FOURCC_TO_FORMAT = (_a$1 = {}, + _a$1[FOURCC_DXT1] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _a$1[FOURCC_DXT3] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _a$1[FOURCC_DXT5] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + _a$1); + /** + * Maps {@link DXGI_FORMAT} to types/internal-formats (see {@link PIXI.TYPES}, {@link PIXI.INTERNAL_FORMATS}) + * @ignore + */ + var DXGI_TO_FORMAT = (_b$1 = {}, + // WEBGL_compressed_texture_s3tc + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + // WEBGL_compressed_texture_s3tc_srgb + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, + _b$1); + /** + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide + */ + /** + * Parses the DDS file header, generates base-textures, and puts them into the texture cache. + * @param arrayBuffer + */ + function parseDDS(arrayBuffer) { + var data = new Uint32Array(arrayBuffer); + var magicWord = data[0]; + if (magicWord !== DDS_MAGIC) { + throw new Error('Invalid DDS file magic word'); + } + var header = new Uint32Array(arrayBuffer, 0, DDS_HEADER_SIZE / Uint32Array.BYTES_PER_ELEMENT); + // DDS header fields + var height = header[DDS_FIELDS.HEIGHT]; + var width = header[DDS_FIELDS.WIDTH]; + var mipmapCount = header[DDS_FIELDS.MIPMAP_COUNT]; + // PIXEL_FORMAT fields + var pixelFormat = new Uint32Array(arrayBuffer, DDS_FIELDS.PIXEL_FORMAT * Uint32Array.BYTES_PER_ELEMENT, DDS_HEADER_PF_SIZE / Uint32Array.BYTES_PER_ELEMENT); + var formatFlags = pixelFormat[PF_FLAGS]; + // File contains compressed texture(s) + if (formatFlags & DDPF_FOURCC) { + var fourCC = pixelFormat[DDS_PF_FIELDS.FOURCC]; + // File contains one DXTn compressed texture + if (fourCC !== FOURCC_DX10) { + var internalFormat_1 = FOURCC_TO_FORMAT[fourCC]; + var dataOffset_1 = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; + var texData = new Uint8Array(arrayBuffer, dataOffset_1); + var resource = new CompressedTextureResource(texData, { + format: internalFormat_1, + width: width, + height: height, + levels: mipmapCount // CompressedTextureResource will separate the levelBuffers for us! + }); + return [resource]; + } + // FOURCC_DX10 indicates there is a 20-byte DDS_HEADER_DX10 after DDS_HEADER + var dx10Offset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; + var dx10Header = new Uint32Array(data.buffer, dx10Offset, DDS_HEADER_DX10_SIZE / Uint32Array.BYTES_PER_ELEMENT); + var dxgiFormat = dx10Header[DDS_DX10_FIELDS.DXGI_FORMAT]; + var resourceDimension = dx10Header[DDS_DX10_FIELDS.RESOURCE_DIMENSION]; + var miscFlag = dx10Header[DDS_DX10_FIELDS.MISC_FLAG]; + var arraySize = dx10Header[DDS_DX10_FIELDS.ARRAY_SIZE]; + // Map dxgiFormat to PIXI.INTERNAL_FORMATS + var internalFormat_2 = DXGI_TO_FORMAT[dxgiFormat]; + if (internalFormat_2 === undefined) { + throw new Error("DDSParser cannot parse texture data with DXGI format " + dxgiFormat); + } + if (miscFlag === DDS_RESOURCE_MISC_TEXTURECUBE) { + // FIXME: Anybody excited about cubemap compressed textures? + throw new Error('DDSParser does not support cubemap textures'); + } + if (resourceDimension === D3D10_RESOURCE_DIMENSION.DDS_DIMENSION_TEXTURE3D) { + // FIXME: Anybody excited about 3D compressed textures? + throw new Error('DDSParser does not supported 3D texture data'); + } + // Uint8Array buffers of image data, including all mipmap levels in each image + var imageBuffers = new Array(); + var dataOffset = DDS_MAGIC_SIZE + + DDS_HEADER_SIZE + + DDS_HEADER_DX10_SIZE; + if (arraySize === 1) { + // No need bothering with the imageSize calculation! + imageBuffers.push(new Uint8Array(arrayBuffer, dataOffset)); + } + else { + // Calculate imageSize for each texture, and then locate each image's texture data + var pixelSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[internalFormat_2]; + var imageSize = 0; + var levelWidth = width; + var levelHeight = height; + for (var i = 0; i < mipmapCount; i++) { + var alignedLevelWidth = Math.max(1, (levelWidth + 3) & ~3); + var alignedLevelHeight = Math.max(1, (levelHeight + 3) & ~3); + var levelSize = alignedLevelWidth * alignedLevelHeight * pixelSize; + imageSize += levelSize; + levelWidth = levelWidth >>> 1; + levelHeight = levelHeight >>> 1; + } + var imageOffset = dataOffset; + // NOTE: Cubemaps have 6-images per texture (but they aren't supported so ^_^) + for (var i = 0; i < arraySize; i++) { + imageBuffers.push(new Uint8Array(arrayBuffer, imageOffset, imageSize)); + imageOffset += imageSize; + } + } + // Uint8Array -> CompressedTextureResource, and we're done! + return imageBuffers.map(function (buffer) { return new CompressedTextureResource(buffer, { + format: internalFormat_2, + width: width, + height: height, + levels: mipmapCount + }); }); + } + if (formatFlags & DDPF_RGB) { + // FIXME: We might want to allow uncompressed *.dds files? + throw new Error('DDSParser does not support uncompressed texture data.'); + } + if (formatFlags & DDPF_YUV) { + // FIXME: Does anybody need this feature? + throw new Error('DDSParser does not supported YUV uncompressed texture data.'); + } + if (formatFlags & DDPF_LUMINANCE) { + // FIXME: Microsoft says older DDS filers use this feature! Probably not worth the effort! + throw new Error('DDSParser does not support single-channel (lumninance) texture data!'); + } + if (formatFlags & DDPF_ALPHA) { + // FIXME: I'm tired! See above =) + throw new Error('DDSParser does not support single-channel (alpha) texture data!'); + } + throw new Error('DDSParser failed to load a texture file due to an unknown reason!'); + } + + var _a$3, _b, _c; + /** + * The 12-byte KTX file identifier + * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.1 + * @ignore + */ + var FILE_IDENTIFIER = [0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A]; + /** + * The value stored in the "endianness" field. + * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.2 + * @ignore + */ + var ENDIANNESS = 0x04030201; + /** + * Byte offsets of the KTX file header fields + * @ignore + */ + var KTX_FIELDS = { + FILE_IDENTIFIER: 0, + ENDIANNESS: 12, + GL_TYPE: 16, + GL_TYPE_SIZE: 20, + GL_FORMAT: 24, + GL_INTERNAL_FORMAT: 28, + GL_BASE_INTERNAL_FORMAT: 32, + PIXEL_WIDTH: 36, + PIXEL_HEIGHT: 40, + PIXEL_DEPTH: 44, + NUMBER_OF_ARRAY_ELEMENTS: 48, + NUMBER_OF_FACES: 52, + NUMBER_OF_MIPMAP_LEVELS: 56, + BYTES_OF_KEY_VALUE_DATA: 60 + }; + /** + * Byte size of the file header fields in {@code KTX_FIELDS} + * @ignore + */ + var FILE_HEADER_SIZE = 64; + /** + * Maps {@link PIXI.TYPES} to the bytes taken per component, excluding those ones that are bit-fields. + * @ignore + */ + var TYPES_TO_BYTES_PER_COMPONENT = (_a$3 = {}, + _a$3[exports.TYPES.UNSIGNED_BYTE] = 1, + _a$3[exports.TYPES.UNSIGNED_SHORT] = 2, + _a$3[exports.TYPES.INT] = 4, + _a$3[exports.TYPES.UNSIGNED_INT] = 4, + _a$3[exports.TYPES.FLOAT] = 4, + _a$3[exports.TYPES.HALF_FLOAT] = 8, + _a$3); + /** + * Number of components in each {@link PIXI.FORMATS} + * @ignore + */ + var FORMATS_TO_COMPONENTS = (_b = {}, + _b[exports.FORMATS.RGBA] = 4, + _b[exports.FORMATS.RGB] = 3, + _b[exports.FORMATS.RG] = 2, + _b[exports.FORMATS.RED] = 1, + _b[exports.FORMATS.LUMINANCE] = 1, + _b[exports.FORMATS.LUMINANCE_ALPHA] = 2, + _b[exports.FORMATS.ALPHA] = 1, + _b); + /** + * Number of bytes per pixel in bit-field types in {@link PIXI.TYPES} + * @ignore + */ + var TYPES_TO_BYTES_PER_PIXEL = (_c = {}, + _c[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = 2, + _c[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = 2, + _c[exports.TYPES.UNSIGNED_SHORT_5_6_5] = 2, + _c); + function parseKTX(url, arrayBuffer, loadKeyValueData) { + if (loadKeyValueData === void 0) { loadKeyValueData = false; } + var dataView = new DataView(arrayBuffer); + if (!validate(url, dataView)) { + return null; + } + var littleEndian = dataView.getUint32(KTX_FIELDS.ENDIANNESS, true) === ENDIANNESS; + var glType = dataView.getUint32(KTX_FIELDS.GL_TYPE, littleEndian); + // const glTypeSize = dataView.getUint32(KTX_FIELDS.GL_TYPE_SIZE, littleEndian); + var glFormat = dataView.getUint32(KTX_FIELDS.GL_FORMAT, littleEndian); + var glInternalFormat = dataView.getUint32(KTX_FIELDS.GL_INTERNAL_FORMAT, littleEndian); + var pixelWidth = dataView.getUint32(KTX_FIELDS.PIXEL_WIDTH, littleEndian); + var pixelHeight = dataView.getUint32(KTX_FIELDS.PIXEL_HEIGHT, littleEndian) || 1; // "pixelHeight = 0" -> "1" + var pixelDepth = dataView.getUint32(KTX_FIELDS.PIXEL_DEPTH, littleEndian) || 1; // ^^ + var numberOfArrayElements = dataView.getUint32(KTX_FIELDS.NUMBER_OF_ARRAY_ELEMENTS, littleEndian) || 1; // ^^ + var numberOfFaces = dataView.getUint32(KTX_FIELDS.NUMBER_OF_FACES, littleEndian); + var numberOfMipmapLevels = dataView.getUint32(KTX_FIELDS.NUMBER_OF_MIPMAP_LEVELS, littleEndian); + var bytesOfKeyValueData = dataView.getUint32(KTX_FIELDS.BYTES_OF_KEY_VALUE_DATA, littleEndian); + // Whether the platform architecture is little endian. If littleEndian !== platformLittleEndian, then the + // file contents must be endian-converted! + // TODO: Endianness conversion + // const platformLittleEndian = new Uint8Array((new Uint32Array([ENDIANNESS])).buffer)[0] === 0x01; + if (pixelHeight === 0 || pixelDepth !== 1) { + throw new Error('Only 2D textures are supported'); + } + if (numberOfFaces !== 1) { + throw new Error('CubeTextures are not supported by KTXLoader yet!'); + } + if (numberOfArrayElements !== 1) { + // TODO: Support splitting array-textures into multiple BaseTextures + throw new Error('WebGL does not support array textures'); + } + // TODO: 8x4 blocks for 2bpp pvrtc + var blockWidth = 4; + var blockHeight = 4; + var alignedWidth = (pixelWidth + 3) & ~3; + var alignedHeight = (pixelHeight + 3) & ~3; + var imageBuffers = new Array(numberOfArrayElements); + var imagePixels = pixelWidth * pixelHeight; + if (glType === 0) { + // Align to 16 pixels (4x4 blocks) + imagePixels = alignedWidth * alignedHeight; + } + var imagePixelByteSize; + if (glType !== 0) { + // Uncompressed texture format + if (TYPES_TO_BYTES_PER_COMPONENT[glType]) { + imagePixelByteSize = TYPES_TO_BYTES_PER_COMPONENT[glType] * FORMATS_TO_COMPONENTS[glFormat]; + } + else { + imagePixelByteSize = TYPES_TO_BYTES_PER_PIXEL[glType]; + } + } + else { + imagePixelByteSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[glInternalFormat]; + } + if (imagePixelByteSize === undefined) { + throw new Error('Unable to resolve the pixel format stored in the *.ktx file!'); + } + var kvData = loadKeyValueData + ? parseKvData(dataView, bytesOfKeyValueData, littleEndian) + : null; + var imageByteSize = imagePixels * imagePixelByteSize; + var mipByteSize = imageByteSize; + var mipWidth = pixelWidth; + var mipHeight = pixelHeight; + var alignedMipWidth = alignedWidth; + var alignedMipHeight = alignedHeight; + var imageOffset = FILE_HEADER_SIZE + bytesOfKeyValueData; + for (var mipmapLevel = 0; mipmapLevel < numberOfMipmapLevels; mipmapLevel++) { + var imageSize = dataView.getUint32(imageOffset, littleEndian); + var elementOffset = imageOffset + 4; + for (var arrayElement = 0; arrayElement < numberOfArrayElements; arrayElement++) { + // TODO: Maybe support 3D textures? :-) + // for (let zSlice = 0; zSlice < pixelDepth; zSlice) + var mips = imageBuffers[arrayElement]; + if (!mips) { + mips = imageBuffers[arrayElement] = new Array(numberOfMipmapLevels); + } + mips[mipmapLevel] = { + levelID: mipmapLevel, + // don't align mipWidth when texture not compressed! (glType not zero) + levelWidth: numberOfMipmapLevels > 1 || glType !== 0 ? mipWidth : alignedMipWidth, + levelHeight: numberOfMipmapLevels > 1 || glType !== 0 ? mipHeight : alignedMipHeight, + levelBuffer: new Uint8Array(arrayBuffer, elementOffset, mipByteSize) + }; + elementOffset += mipByteSize; + } + // HINT: Aligns to 4-byte boundary after jumping imageSize (in lieu of mipPadding) + imageOffset += imageSize + 4; // (+4 to jump the imageSize field itself) + imageOffset = imageOffset % 4 !== 0 ? imageOffset + 4 - (imageOffset % 4) : imageOffset; + // Calculate mipWidth, mipHeight for _next_ iteration + mipWidth = (mipWidth >> 1) || 1; + mipHeight = (mipHeight >> 1) || 1; + alignedMipWidth = (mipWidth + blockWidth - 1) & ~(blockWidth - 1); + alignedMipHeight = (mipHeight + blockHeight - 1) & ~(blockHeight - 1); + // Each mipmap level is 4-times smaller? + mipByteSize = alignedMipWidth * alignedMipHeight * imagePixelByteSize; + } + // We use the levelBuffers feature of CompressedTextureResource b/c texture data is image-major, not level-major. + if (glType !== 0) { + return { + uncompressed: imageBuffers.map(function (levelBuffers) { + var buffer = levelBuffers[0].levelBuffer; + var convertToInt = false; + if (glType === exports.TYPES.FLOAT) { + buffer = new Float32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + else if (glType === exports.TYPES.UNSIGNED_INT) { + convertToInt = true; + buffer = new Uint32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + else if (glType === exports.TYPES.INT) { + convertToInt = true; + buffer = new Int32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + return { + resource: new BufferResource(buffer, { + width: levelBuffers[0].levelWidth, + height: levelBuffers[0].levelHeight, + }), + type: glType, + format: convertToInt ? convertFormatToInteger(glFormat) : glFormat, + }; + }), + kvData: kvData + }; + } + return { + compressed: imageBuffers.map(function (levelBuffers) { return new CompressedTextureResource(null, { + format: glInternalFormat, + width: pixelWidth, + height: pixelHeight, + levels: numberOfMipmapLevels, + levelBuffers: levelBuffers, + }); }), + kvData: kvData + }; + } + /** + * Checks whether the arrayBuffer contains a valid *.ktx file. + * @param url + * @param dataView + */ + function validate(url, dataView) { + // NOTE: Do not optimize this into 3 32-bit integer comparison because the endianness + // of the data is not specified. + for (var i = 0; i < FILE_IDENTIFIER.length; i++) { + if (dataView.getUint8(i) !== FILE_IDENTIFIER[i]) { + console.error(url + " is not a valid *.ktx file!"); + return false; + } + } + return true; + } + function convertFormatToInteger(format) { + switch (format) { + case exports.FORMATS.RGBA: return exports.FORMATS.RGBA_INTEGER; + case exports.FORMATS.RGB: return exports.FORMATS.RGB_INTEGER; + case exports.FORMATS.RG: return exports.FORMATS.RG_INTEGER; + case exports.FORMATS.RED: return exports.FORMATS.RED_INTEGER; + default: return format; + } + } + function parseKvData(dataView, bytesOfKeyValueData, littleEndian) { + var kvData = new Map(); + var bytesIntoKeyValueData = 0; + while (bytesIntoKeyValueData < bytesOfKeyValueData) { + var keyAndValueByteSize = dataView.getUint32(FILE_HEADER_SIZE + bytesIntoKeyValueData, littleEndian); + var keyAndValueByteOffset = FILE_HEADER_SIZE + bytesIntoKeyValueData + 4; + var valuePadding = 3 - ((keyAndValueByteSize + 3) % 4); + // Bounds check + if (keyAndValueByteSize === 0 || keyAndValueByteSize > bytesOfKeyValueData - bytesIntoKeyValueData) { + console.error('KTXLoader: keyAndValueByteSize out of bounds'); + break; + } + // Note: keyNulByte can't be 0 otherwise the key is an empty string. + var keyNulByte = 0; + for (; keyNulByte < keyAndValueByteSize; keyNulByte++) { + if (dataView.getUint8(keyAndValueByteOffset + keyNulByte) === 0x00) { + break; + } + } + if (keyNulByte === -1) { + console.error('KTXLoader: Failed to find null byte terminating kvData key'); + break; + } + var key = new TextDecoder().decode(new Uint8Array(dataView.buffer, keyAndValueByteOffset, keyNulByte)); + var value = new DataView(dataView.buffer, keyAndValueByteOffset + keyNulByte + 1, keyAndValueByteSize - keyNulByte - 1); + kvData.set(key, value); + // 4 = the keyAndValueByteSize field itself + // keyAndValueByteSize = the bytes taken by the key and value + // valuePadding = extra padding to align with 4 bytes + bytesIntoKeyValueData += 4 + keyAndValueByteSize + valuePadding; + } + return kvData; + } + + // Set DDS files to be loaded as an ArrayBuffer + exports.LoaderResource.setExtensionXhrType('dds', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER); + /** + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide + */ + var DDSLoader = /** @class */ (function () { + function DDSLoader() { + } + /** + * Registers a DDS compressed texture + * @see PIXI.Loader.loaderMiddleware + * @param resource - loader resource that is checked to see if it is a DDS file + * @param next - callback Function to call when done + */ + DDSLoader.use = function (resource, next) { + if (resource.extension === 'dds' && resource.data) { + try { + Object.assign(resource, registerCompressedTextures(resource.name || resource.url, parseDDS(resource.data), resource.metadata)); + } + catch (err) { + next(err); + return; + } + } + next(); + }; + /** @ignore */ + DDSLoader.extension = exports.ExtensionType.Loader; + return DDSLoader; + }()); + + // Set KTX files to be loaded as an ArrayBuffer + exports.LoaderResource.setExtensionXhrType('ktx', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER); + /** + * Loader plugin for handling KTX texture container files. + * + * This KTX loader does not currently support the following features: + * * cube textures + * * 3D textures + * * endianness conversion for big-endian machines + * * embedded *.basis files + * + * It does supports the following features: + * * multiple textures per file + * * mipmapping (only for compressed formats) + * * vendor-specific key/value data parsing (enable {@link PIXI.KTXLoader.loadKeyValueData}) + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + */ + var KTXLoader = /** @class */ (function () { + function KTXLoader() { + } + /** + * Called after a KTX file is loaded. + * + * This will parse the KTX file header and add a {@code BaseTexture} to the texture + * cache. + * @see PIXI.Loader.loaderMiddleware + * @param resource - loader resource that is checked to see if it is a KTX file + * @param next - callback Function to call when done + */ + KTXLoader.use = function (resource, next) { + if (resource.extension === 'ktx' && resource.data) { + try { + var url_1 = resource.name || resource.url; + var _a = parseKTX(url_1, resource.data, this.loadKeyValueData), compressed = _a.compressed, uncompressed = _a.uncompressed, kvData_1 = _a.kvData; + if (compressed) { + var result = registerCompressedTextures(url_1, compressed, resource.metadata); + if (kvData_1 && result.textures) { + for (var textureId in result.textures) { + result.textures[textureId].baseTexture.ktxKeyValueData = kvData_1; + } + } + Object.assign(resource, result); + } + else if (uncompressed) { + var textures_1 = {}; + uncompressed.forEach(function (image, i) { + var texture = new Texture(new BaseTexture(image.resource, { + mipmap: exports.MIPMAP_MODES.OFF, + alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA, + type: image.type, + format: image.format, + })); + var cacheID = url_1 + "-" + (i + 1); + if (kvData_1) + { texture.baseTexture.ktxKeyValueData = kvData_1; } + BaseTexture.addToCache(texture.baseTexture, cacheID); + Texture.addToCache(texture, cacheID); + if (i === 0) { + textures_1[url_1] = texture; + BaseTexture.addToCache(texture.baseTexture, url_1); + Texture.addToCache(texture, url_1); + } + textures_1[cacheID] = texture; + }); + Object.assign(resource, { textures: textures_1 }); + } + } + catch (err) { + next(err); + return; + } + } + next(); + }; + /** @ignore */ + KTXLoader.extension = exports.ExtensionType.Loader; + /** + * If set to `true`, {@link PIXI.KTXLoader} will parse key-value data in KTX textures. This feature relies + * on the [Encoding Standard]{@link https://encoding.spec.whatwg.org}. + * + * The key-value data will be available on the base-textures as {@code PIXI.BaseTexture.ktxKeyValueData}. They + * will hold a reference to the texture data buffer, so make sure to delete key-value data once you are done + * using it. + */ + KTXLoader.loadKeyValueData = false; + return KTXLoader; + }()); + + /*! + * @pixi/particle-container - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/particle-container is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$f = function(d, b) { + extendStatics$f = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$f(d, b); + }; + + function __extends$f(d, b) { + extendStatics$f(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. + * + * The tradeoff of the ParticleContainer is that most advanced functionality will not work. + * ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). + * + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. + * + * It's extremely easy to use: + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = PIXI.Sprite.from("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * @memberof PIXI + */ + var ParticleContainer = /** @class */ (function (_super) { + __extends$f(ParticleContainer, _super); + /** + * @param maxSize - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param properties - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. + * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=false] - If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer(maxSize, properties, batchSize, autoResize) { + if (maxSize === void 0) { maxSize = 1500; } + if (batchSize === void 0) { batchSize = 16384; } + if (autoResize === void 0) { autoResize = false; } + var _this = _super.call(this) || this; + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var maxBatchSize = 16384; + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + _this._properties = [false, true, false, false, false]; + _this._maxSize = maxSize; + _this._batchSize = batchSize; + _this._buffers = null; + _this._bufferUpdateIDs = []; + _this._updateID = 0; + _this.interactiveChildren = false; + _this.blendMode = exports.BLEND_MODES.NORMAL; + _this.autoResize = autoResize; + _this.roundPixels = true; + _this.baseTexture = null; + _this.setProperties(properties); + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * @param properties - The properties to be uploaded + */ + ParticleContainer.prototype.setProperties = function (properties) { + if (properties) { + this._properties[0] = 'vertices' in properties || 'scale' in properties + ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'tint' in properties || 'alpha' in properties + ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + }; + ParticleContainer.prototype.updateTransform = function () { + // TODO don't need to! + this.displayObjectUpdateTransform(); + }; + Object.defineProperty(ParticleContainer.prototype, "tint", { + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + hex2rgb(value, this.tintRgb); + }, + enumerable: false, + configurable: true + }); + /** + * Renders the container using the WebGL renderer. + * @param renderer - The WebGL renderer. + */ + ParticleContainer.prototype.render = function (renderer) { + var _this = this; + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.valid) { + this.baseTexture.once('update', function () { return _this.onChildrenChange(0); }); + } + } + renderer.batch.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + /** + * Set the flag that static data should be updated to true + * @param smallestChildIndex - The smallest child index. + */ + ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + }; + ParticleContainer.prototype.dispose = function () { + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + this._buffers = null; + } + }; + /** + * Destroys the container + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + ParticleContainer.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this.dispose(); + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + }; + return ParticleContainer; + }(Container)); + + /* + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + /** + * The particle buffer manages the static and dynamic buffers for a particle container. + * @private + * @memberof PIXI + */ + var ParticleBuffer = /** @class */ (function () { + /** + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(properties, dynamicPropertyFlags, size) { + this.geometry = new Geometry(); + this.indexBuffer = null; + this.size = size; + this.dynamicProperties = []; + this.staticProperties = []; + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attributeName: property.attributeName, + size: property.size, + uploadFunction: property.uploadFunction, + type: property.type || exports.TYPES.FLOAT, + offset: property.offset, + }; + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } + else { + this.staticProperties.push(property); + } + } + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this._updateID = 0; + this.initBuffers(); + } + /** Sets up the renderer context and necessary buffers. */ + ParticleBuffer.prototype.initBuffers = function () { + var geometry = this.geometry; + var dynamicOffset = 0; + this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true); + geometry.addIndex(this.indexBuffer); + this.dynamicStride = 0; + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = new Buffer(this.dynamicData, false, false); + // static // + var staticOffset = 0; + this.staticStride = 0; + for (var i = 0; i < this.staticProperties.length; ++i) { + var property = this.staticProperties[i]; + property.offset = staticOffset; + staticOffset += property.size; + this.staticStride += property.size; + } + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = new Buffer(this.staticData, true, false); + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4); + } + for (var i = 0; i < this.staticProperties.length; ++i) { + var property = this.staticProperties[i]; + geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4); + } + }; + /** + * Uploads the dynamic properties. + * @param children - The children to upload. + * @param startIndex - The index to start at. + * @param amount - The number to upload. + */ + ParticleBuffer.prototype.uploadDynamic = function (children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + this.dynamicBuffer._updateID++; + }; + /** + * Uploads the static properties. + * @param children - The children to upload. + * @param startIndex - The index to start at. + * @param amount - The number to upload. + */ + ParticleBuffer.prototype.uploadStatic = function (children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + this.staticBuffer._updateID++; + }; + /** Destroys the ParticleBuffer. */ + ParticleBuffer.prototype.destroy = function () { + this.indexBuffer = null; + this.dynamicProperties = null; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this.staticProperties = null; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + // all buffers are destroyed inside geometry + this.geometry.destroy(); + }; + return ParticleBuffer; + }()); + + var fragment$6 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; + + var vertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; + + /* + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + /** + * Renderer for Particles that is designer for speed over feature set. + * @memberof PIXI + */ + var ParticleRenderer = /** @class */ (function (_super) { + __extends$f(ParticleRenderer, _super); + /** + * @param renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + _this.shader = null; + _this.properties = null; + _this.tempMatrix = new Matrix(); + _this.properties = [ + // verticesData + { + attributeName: 'aVertexPosition', + size: 2, + uploadFunction: _this.uploadVertices, + offset: 0, + }, + // positionData + { + attributeName: 'aPositionCoord', + size: 2, + uploadFunction: _this.uploadPosition, + offset: 0, + }, + // rotationData + { + attributeName: 'aRotation', + size: 1, + uploadFunction: _this.uploadRotation, + offset: 0, + }, + // uvsData + { + attributeName: 'aTextureCoord', + size: 2, + uploadFunction: _this.uploadUvs, + offset: 0, + }, + // tintData + { + attributeName: 'aColor', + size: 1, + type: exports.TYPES.UNSIGNED_BYTE, + uploadFunction: _this.uploadTint, + offset: 0, + } ]; + _this.shader = Shader.from(vertex$3, fragment$6, {}); + _this.state = State.for2d(); + return _this; + } + /** + * Renders the particle container object. + * @param container - The container to render using this ParticleRenderer. + */ + ParticleRenderer.prototype.render = function (container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + if (totalChildren === 0) { + return; + } + else if (totalChildren > maxSize && !container.autoResize) { + totalChildren = maxSize; + } + var buffers = container._buffers; + if (!buffers) { + buffers = container._buffers = this.generateBuffers(container); + } + var baseTexture = children[0]._texture.baseTexture; + var premultiplied = baseTexture.alphaMode > 0; + // if the uvs have not updated then no point rendering just yet! + this.state.blendMode = correctBlendMode(container.blendMode, premultiplied); + renderer.state.set(this.state); + var gl = renderer.gl; + var m = container.worldTransform.copyTo(this.tempMatrix); + m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); + this.shader.uniforms.translationMatrix = m.toArray(true); + this.shader.uniforms.uColor = premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, premultiplied); + this.shader.uniforms.uSampler = baseTexture; + this.renderer.shader.bind(this.shader); + var updateStatic = false; + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = (totalChildren - i); + if (amount > batchSize) { + amount = batchSize; + } + if (j >= buffers.length) { + buffers.push(this._generateOneMoreBuffer(container)); + } + var buffer = buffers[j]; + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + var bid = container._bufferUpdateIDs[j] || 0; + updateStatic = updateStatic || (buffer._updateID < bid); + // we only upload the static content when we have to! + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + // bind the buffer + renderer.geometry.bind(buffer.geometry); + gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + } + }; + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties. + * @param container - The container to render using this ParticleRenderer + * @returns - The buffers + */ + ParticleRenderer.prototype.generateBuffers = function (container) { + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + for (var i = 0; i < size; i += batchSize) { + buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); + } + return buffers; + }; + /** + * Creates one more particle buffer, because container has autoResize feature. + * @param container - The container to render using this ParticleRenderer + * @returns - The generated buffer + */ + ParticleRenderer.prototype._generateOneMoreBuffer = function (container) { + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); + }; + /** + * Uploads the vertices. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their vertices uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - (sprite.anchor.x * orig.width); + w0 = w1 + trim.width; + h1 = trim.y - (sprite.anchor.y * orig.height); + h0 = h1 + trim.height; + } + else { + w0 = (orig.width) * (1 - sprite.anchor.x); + w1 = (orig.width) * -sprite.anchor.x; + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + array[offset + (stride * 2)] = w0 * sx; + array[offset + (stride * 2) + 1] = h0 * sy; + array[offset + (stride * 3)] = w1 * sx; + array[offset + (stride * 3) + 1] = h0 * sy; + offset += stride * 4; + } + }; + /** + * Uploads the position. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their positions uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadPosition = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + array[offset + (stride * 2)] = spritePosition.x; + array[offset + (stride * 2) + 1] = spritePosition.y; + array[offset + (stride * 3)] = spritePosition.x; + array[offset + (stride * 3) + 1] = spritePosition.y; + offset += stride * 4; + } + }; + /** + * Uploads the rotation. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadRotation = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + (stride * 2)] = spriteRotation; + array[offset + (stride * 3)] = spriteRotation; + offset += stride * 4; + } + }; + /** + * Uploads the UVs. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadUvs = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + array[offset + (stride * 2)] = textureUvs.x2; + array[offset + (stride * 2) + 1] = textureUvs.y2; + array[offset + (stride * 3)] = textureUvs.x3; + array[offset + (stride * 3) + 1] = textureUvs.y3; + offset += stride * 4; + } + else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + array[offset + (stride * 2)] = 0; + array[offset + (stride * 2) + 1] = 0; + array[offset + (stride * 3)] = 0; + array[offset + (stride * 3) + 1] = 0; + offset += stride * 4; + } + } + }; + /** + * Uploads the tint. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadTint = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.alphaMode > 0; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied + ? premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + array[offset] = argb; + array[offset + stride] = argb; + array[offset + (stride * 2)] = argb; + array[offset + (stride * 3)] = argb; + offset += stride * 4; + } + }; + /** Destroys the ParticleRenderer. */ + ParticleRenderer.prototype.destroy = function () { + _super.prototype.destroy.call(this); + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + this.tempMatrix = null; + }; + /** @ignore */ + ParticleRenderer.extension = { + name: 'particle', + type: exports.ExtensionType.RendererPlugin, + }; + return ParticleRenderer; + }(ObjectRenderer)); + + /*! + * @pixi/graphics - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/graphics is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Supported line joints in `PIXI.LineStyle` for graphics. + * @see PIXI.Graphics#lineStyle + * @see https://graphicdesign.stackexchange.com/questions/59018/what-is-a-bevel-join-of-two-lines-exactly-illustrator + * @name LINE_JOIN + * @memberof PIXI + * @static + * @enum {string} + * @property {string} MITER - 'miter': make a sharp corner where outer part of lines meet + * @property {string} BEVEL - 'bevel': add a square butt at each end of line segment and fill the triangle at turn + * @property {string} ROUND - 'round': add an arc at the joint + */ + exports.LINE_JOIN = void 0; + (function (LINE_JOIN) { + LINE_JOIN["MITER"] = "miter"; + LINE_JOIN["BEVEL"] = "bevel"; + LINE_JOIN["ROUND"] = "round"; + })(exports.LINE_JOIN || (exports.LINE_JOIN = {})); + /** + * Support line caps in `PIXI.LineStyle` for graphics. + * @see PIXI.Graphics#lineStyle + * @name LINE_CAP + * @memberof PIXI + * @static + * @enum {string} + * @property {string} BUTT - 'butt': don't add any cap at line ends (leaves orthogonal edges) + * @property {string} ROUND - 'round': add semicircle at ends + * @property {string} SQUARE - 'square': add square at end (like `BUTT` except more length at end) + */ + exports.LINE_CAP = void 0; + (function (LINE_CAP) { + LINE_CAP["BUTT"] = "butt"; + LINE_CAP["ROUND"] = "round"; + LINE_CAP["SQUARE"] = "square"; + })(exports.LINE_CAP || (exports.LINE_CAP = {})); + /** + * Graphics curves resolution settings. If `adaptive` flag is set to `true`, + * the resolution is calculated based on the curve's length to ensure better visual quality. + * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * @static + * @constant + * @memberof PIXI + * @name GRAPHICS_CURVES + * @type {object} + * @property {boolean} [adaptive=true] - flag indicating if the resolution should be adaptive + * @property {number} [maxLength=10] - maximal length of a single segment of the curve (if adaptive = false, ignored) + * @property {number} [minSegments=8] - minimal number of segments in the curve (if adaptive = false, ignored) + * @property {number} [maxSegments=2048] - maximal number of segments in the curve (if adaptive = false, ignored) + */ + var GRAPHICS_CURVES = { + adaptive: true, + maxLength: 10, + minSegments: 8, + maxSegments: 2048, + epsilon: 0.0001, + _segmentsCount: function (length, defaultSegments) { + if (defaultSegments === void 0) { defaultSegments = 20; } + if (!this.adaptive || !length || isNaN(length)) { + return defaultSegments; + } + var result = Math.ceil(length / this.maxLength); + if (result < this.minSegments) { + result = this.minSegments; + } + else if (result > this.maxSegments) { + result = this.maxSegments; + } + return result; + }, + }; + + /** + * Fill style object for Graphics. + * @memberof PIXI + */ + var FillStyle = /** @class */ (function () { + function FillStyle() { + /** + * The hex color value used when coloring the Graphics object. + * @default 0xFFFFFF + */ + this.color = 0xFFFFFF; + /** The alpha value used when filling the Graphics object. */ + this.alpha = 1.0; + /** + * The texture to be used for the fill. + * @default 0 + */ + this.texture = Texture.WHITE; + /** + * The transform applied to the texture. + * @default null + */ + this.matrix = null; + /** If the current fill is visible. */ + this.visible = false; + this.reset(); + } + /** Clones the object */ + FillStyle.prototype.clone = function () { + var obj = new FillStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + return obj; + }; + /** Reset */ + FillStyle.prototype.reset = function () { + this.color = 0xFFFFFF; + this.alpha = 1; + this.texture = Texture.WHITE; + this.matrix = null; + this.visible = false; + }; + /** Destroy and don't use after this. */ + FillStyle.prototype.destroy = function () { + this.texture = null; + this.matrix = null; + }; + return FillStyle; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$e = function(d, b) { + extendStatics$e = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$e(d, b); + }; + + function __extends$e(d, b) { + extendStatics$e(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + function fixOrientation(points, hole) { + var _a, _b; + if (hole === void 0) { hole = false; } + var m = points.length; + if (m < 6) { + return; + } + var area = 0; + for (var i = 0, x1 = points[m - 2], y1 = points[m - 1]; i < m; i += 2) { + var x2 = points[i]; + var y2 = points[i + 1]; + area += (x2 - x1) * (y2 + y1); + x1 = x2; + y1 = y2; + } + if ((!hole && area > 0) || (hole && area <= 0)) { + var n = m / 2; + for (var i = n + (n % 2); i < m; i += 2) { + var i1 = m - i - 2; + var i2 = m - i - 1; + var i3 = i; + var i4 = i + 1; + _a = [points[i3], points[i1]], points[i1] = _a[0], points[i3] = _a[1]; + _b = [points[i4], points[i2]], points[i2] = _b[0], points[i4] = _b[1]; + } + } + } + /** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildPoly = { + build: function (graphicsData) { + graphicsData.points = graphicsData.shape.points.slice(); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var holes = graphicsData.holes; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + if (points.length >= 6) { + fixOrientation(points, false); + var holeArray = []; + // Process holes.. + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + fixOrientation(hole.points, true); + holeArray.push(points.length / 2); + points = points.concat(hole.points); + } + // sort color + var triangles = earcut_1(points, holeArray, 2); + if (!triangles) { + return; + } + var vertPos = verts.length / 2; + for (var i = 0; i < triangles.length; i += 3) { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i + 1] + vertPos); + indices.push(triangles[i + 2] + vertPos); + } + for (var i = 0; i < points.length; i++) { + verts.push(points[i]); + } + } + }, + }; + + // for type only + /** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildCircle = { + build: function (graphicsData) { + // need to convert points to a nice regular data + var points = graphicsData.points; + var x; + var y; + var dx; + var dy; + var rx; + var ry; + if (graphicsData.type === exports.SHAPES.CIRC) { + var circle = graphicsData.shape; + x = circle.x; + y = circle.y; + rx = ry = circle.radius; + dx = dy = 0; + } + else if (graphicsData.type === exports.SHAPES.ELIP) { + var ellipse = graphicsData.shape; + x = ellipse.x; + y = ellipse.y; + rx = ellipse.width; + ry = ellipse.height; + dx = dy = 0; + } + else { + var roundedRect = graphicsData.shape; + var halfWidth = roundedRect.width / 2; + var halfHeight = roundedRect.height / 2; + x = roundedRect.x + halfWidth; + y = roundedRect.y + halfHeight; + rx = ry = Math.max(0, Math.min(roundedRect.radius, Math.min(halfWidth, halfHeight))); + dx = halfWidth - rx; + dy = halfHeight - ry; + } + if (!(rx >= 0 && ry >= 0 && dx >= 0 && dy >= 0)) { + points.length = 0; + return; + } + // Choose a number of segments such that the maximum absolute deviation from the circle is approximately 0.029 + var n = Math.ceil(2.3 * Math.sqrt(rx + ry)); + var m = (n * 8) + (dx ? 4 : 0) + (dy ? 4 : 0); + points.length = m; + if (m === 0) { + return; + } + if (n === 0) { + points.length = 8; + points[0] = points[6] = x + dx; + points[1] = points[3] = y + dy; + points[2] = points[4] = x - dx; + points[5] = points[7] = y - dy; + return; + } + var j1 = 0; + var j2 = (n * 4) + (dx ? 2 : 0) + 2; + var j3 = j2; + var j4 = m; + { + var x0 = dx + rx; + var y0 = dy; + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j2] = y1; + points[--j2] = x2; + if (dy) { + var y2 = y - y0; + points[j3++] = x2; + points[j3++] = y2; + points[--j4] = y2; + points[--j4] = x1; + } + } + for (var i = 1; i < n; i++) { + var a = Math.PI / 2 * (i / n); + var x0 = dx + (Math.cos(a) * rx); + var y0 = dy + (Math.sin(a) * ry); + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + var y2 = y - y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j2] = y1; + points[--j2] = x2; + points[j3++] = x2; + points[j3++] = y2; + points[--j4] = y2; + points[--j4] = x1; + } + { + var x0 = dx; + var y0 = dy + ry; + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + var y2 = y - y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j4] = y2; + points[--j4] = x1; + if (dx) { + points[j1++] = x2; + points[j1++] = y1; + points[--j4] = y2; + points[--j4] = x2; + } + } + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + if (points.length === 0) { + return; + } + var vertPos = verts.length / 2; + var center = vertPos; + var x; + var y; + if (graphicsData.type !== exports.SHAPES.RREC) { + var circle = graphicsData.shape; + x = circle.x; + y = circle.y; + } + else { + var roundedRect = graphicsData.shape; + x = roundedRect.x + (roundedRect.width / 2); + y = roundedRect.y + (roundedRect.height / 2); + } + var matrix = graphicsData.matrix; + // Push center (special point) + verts.push(graphicsData.matrix ? (matrix.a * x) + (matrix.c * y) + matrix.tx : x, graphicsData.matrix ? (matrix.b * x) + (matrix.d * y) + matrix.ty : y); + vertPos++; + verts.push(points[0], points[1]); + for (var i = 2; i < points.length; i += 2) { + verts.push(points[i], points[i + 1]); + // add some uvs + indices.push(vertPos++, center, vertPos); + } + indices.push(center + 1, center, vertPos); + }, + }; + + /** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildRectangle = { + build: function (graphicsData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + var points = graphicsData.points; + points.length = 0; + points.push(x, y, x + width, y, x + width, y + height, x, y + height); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var vertPos = verts.length / 2; + verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]); + graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3); + }, + }; + + /** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @returns {number} the result + */ + function getPt(n1, n2, perc) { + var diff = n2 - n1; + return n1 + (diff * perc); + } + /** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @returns {number[]} an array of points + */ + function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) { + if (out === void 0) { out = []; } + var n = 20; + var points = out; + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + // Handle case when first curve points overlaps and earcut fails to triangulate + if (i === 0 && points[points.length - 2] === x && points[points.length - 1] === y) { + continue; + } + points.push(x, y); + } + return points; + } + /** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildRoundedRectangle = { + build: function (graphicsData) { + if (Graphics.nextRoundedRectBehavior) { + buildCircle.build(graphicsData); + return; + } + var rrectData = graphicsData.shape; + var points = graphicsData.points; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + // Don't allow negative radius or greater than half the smallest width + var radius = Math.max(0, Math.min(rrectData.radius, Math.min(width, height) / 2)); + points.length = 0; + // No radius, do a simple rectangle + if (!radius) { + points.push(x, y, x + width, y, x + width, y + height, x, y + height); + } + else { + quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points); + quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points); + quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points); + quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points); + } + }, + triangulate: function (graphicsData, graphicsGeometry) { + if (Graphics.nextRoundedRectBehavior) { + buildCircle.triangulate(graphicsData, graphicsGeometry); + return; + } + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var vecPos = verts.length / 2; + var triangles = earcut_1(points, null, 2); + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + // indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + // indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + for (var i = 0, j = points.length; i < j; i++) { + verts.push(points[i], points[++i]); + } + }, + }; + + /** + * Buffers vertices to draw a square cap. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} x - X-coord of end point + * @param {number} y - Y-coord of end point + * @param {number} nx - X-coord of line normal pointing inside + * @param {number} ny - Y-coord of line normal pointing inside + * @param {number} innerWeight - Weight of inner points + * @param {number} outerWeight - Weight of outer points + * @param {boolean} clockwise - Whether the cap is drawn clockwise + * @param {Array} verts - vertex buffer + * @returns {number} - no. of vertices pushed + */ + function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, /* rotation for square (true at left end, false at right end) */ verts) { + var ix = x - (nx * innerWeight); + var iy = y - (ny * innerWeight); + var ox = x + (nx * outerWeight); + var oy = y + (ny * outerWeight); + /* Rotate nx,ny for extension vector */ + var exx; + var eyy; + if (clockwise) { + exx = ny; + eyy = -nx; + } + else { + exx = -ny; + eyy = nx; + } + /* [i|0]x,y extended at cap */ + var eix = ix + exx; + var eiy = iy + eyy; + var eox = ox + exx; + var eoy = oy + eyy; + /* Square itself must be inserted clockwise*/ + verts.push(eix, eiy); + verts.push(eox, eoy); + return 2; + } + /** + * Buffers vertices to draw an arc at the line joint or cap. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} cx - X-coord of center + * @param {number} cy - Y-coord of center + * @param {number} sx - X-coord of arc start + * @param {number} sy - Y-coord of arc start + * @param {number} ex - X-coord of arc end + * @param {number} ey - Y-coord of arc end + * @param {Array} verts - buffer of vertices + * @param {boolean} clockwise - orientation of vertices + * @returns {number} - no. of vertices pushed + */ + function round(cx, cy, sx, sy, ex, ey, verts, clockwise) { + var cx2p0x = sx - cx; + var cy2p0y = sy - cy; + var angle0 = Math.atan2(cx2p0x, cy2p0y); + var angle1 = Math.atan2(ex - cx, ey - cy); + if (clockwise && angle0 < angle1) { + angle0 += Math.PI * 2; + } + else if (!clockwise && angle0 > angle1) { + angle1 += Math.PI * 2; + } + var startAngle = angle0; + var angleDiff = angle1 - angle0; + var absAngleDiff = Math.abs(angleDiff); + /* if (absAngleDiff >= PI_LBOUND && absAngleDiff <= PI_UBOUND) + { + const r1x = cx - nxtPx; + const r1y = cy - nxtPy; + + if (r1x === 0) + { + if (r1y > 0) + { + angleDiff = -angleDiff; + } + } + else if (r1x >= -GRAPHICS_CURVES.epsilon) + { + angleDiff = -angleDiff; + } + }*/ + var radius = Math.sqrt((cx2p0x * cx2p0x) + (cy2p0y * cy2p0y)); + var segCount = ((15 * absAngleDiff * Math.sqrt(radius) / Math.PI) >> 0) + 1; + var angleInc = angleDiff / segCount; + startAngle += angleInc; + if (clockwise) { + verts.push(cx, cy); + verts.push(sx, sy); + for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx, cy); + verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); + } + verts.push(cx, cy); + verts.push(ex, ey); + } + else { + verts.push(sx, sy); + verts.push(cx, cy); + for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); + verts.push(cx, cy); + } + verts.push(ex, ey); + verts.push(cx, cy); + } + return segCount * 2; + } + /** + * Builds a line to draw using the polygon method. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildNonNativeLine(graphicsData, graphicsGeometry) { + var shape = graphicsData.shape; + var points = graphicsData.points || shape.points.slice(); + var eps = graphicsGeometry.closePointEps; + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + var style = graphicsData.lineStyle; + // get first and last point.. figure out the middle! + var firstPoint = new Point(points[0], points[1]); + var lastPoint = new Point(points[points.length - 2], points[points.length - 1]); + var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; + var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps + && Math.abs(firstPoint.y - lastPoint.y) < eps; + // if the first point is the last point - gonna have issues :) + if (closedShape) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + if (closedPath) { + points.pop(); + points.pop(); + lastPoint.set(points[points.length - 2], points[points.length - 1]); + } + var midPointX = (firstPoint.x + lastPoint.x) * 0.5; + var midPointY = (lastPoint.y + firstPoint.y) * 0.5; + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + var verts = graphicsGeometry.points; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 2; + // Max. inner and outer width + var width = style.width / 2; + var widthSquared = width * width; + var miterLimitSquared = style.miterLimit * style.miterLimit; + /* Line segments of interest where (x1,y1) forms the corner. */ + var x0 = points[0]; + var y0 = points[1]; + var x1 = points[2]; + var y1 = points[3]; + var x2 = 0; + var y2 = 0; + /* perp[?](x|y) = the line normal with magnitude lineWidth. */ + var perpx = -(y0 - y1); + var perpy = x0 - x1; + var perp1x = 0; + var perp1y = 0; + var dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + var ratio = style.alignment; // 0.5; + var innerWeight = (1 - ratio) * 2; + var outerWeight = ratio * 2; + if (!closedShape) { + if (style.cap === exports.LINE_CAP.ROUND) { + indexCount += round(x0 - (perpx * (innerWeight - outerWeight) * 0.5), y0 - (perpy * (innerWeight - outerWeight) * 0.5), x0 - (perpx * innerWeight), y0 - (perpy * innerWeight), x0 + (perpx * outerWeight), y0 + (perpy * outerWeight), verts, true) + 2; + } + else if (style.cap === exports.LINE_CAP.SQUARE) { + indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts); + } + } + // Push first point (below & above vertices) + verts.push(x0 - (perpx * innerWeight), y0 - (perpy * innerWeight)); + verts.push(x0 + (perpx * outerWeight), y0 + (perpy * outerWeight)); + for (var i = 1; i < length - 1; ++i) { + x0 = points[(i - 1) * 2]; + y0 = points[((i - 1) * 2) + 1]; + x1 = points[i * 2]; + y1 = points[(i * 2) + 1]; + x2 = points[(i + 1) * 2]; + y2 = points[((i + 1) * 2) + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + perp1x = -(y1 - y2); + perp1y = x1 - x2; + dist = Math.sqrt((perp1x * perp1x) + (perp1y * perp1y)); + perp1x /= dist; + perp1y /= dist; + perp1x *= width; + perp1y *= width; + /* d[x|y](0|1) = the component displacement between points p(0,1|1,2) */ + var dx0 = x1 - x0; + var dy0 = y0 - y1; + var dx1 = x1 - x2; + var dy1 = y2 - y1; + /* +ve if internal angle counterclockwise, -ve if internal angle clockwise. */ + var cross = (dy0 * dx1) - (dy1 * dx0); + var clockwise = (cross < 0); + /* Going nearly straight? */ + if (Math.abs(cross) < 0.1) { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + continue; + } + /* p[x|y] is the miter point. pdist is the distance between miter point and p1. */ + var c1 = ((-perpx + x0) * (-perpy + y1)) - ((-perpx + x1) * (-perpy + y0)); + var c2 = ((-perp1x + x2) * (-perp1y + y1)) - ((-perp1x + x1) * (-perp1y + y2)); + var px = ((dx0 * c2) - (dx1 * c1)) / cross; + var py = ((dy1 * c1) - (dy0 * c2)) / cross; + var pdist = ((px - x1) * (px - x1)) + ((py - y1) * (py - y1)); + /* Inner miter point */ + var imx = x1 + ((px - x1) * innerWeight); + var imy = y1 + ((py - y1) * innerWeight); + /* Outer miter point */ + var omx = x1 - ((px - x1) * outerWeight); + var omy = y1 - ((py - y1) * outerWeight); + /* Is the inside miter point too far away, creating a spike? */ + var smallerInsideSegmentSq = Math.min((dx0 * dx0) + (dy0 * dy0), (dx1 * dx1) + (dy1 * dy1)); + var insideWeight = clockwise ? innerWeight : outerWeight; + var smallerInsideDiagonalSq = smallerInsideSegmentSq + (insideWeight * insideWeight * widthSquared); + var insideMiterOk = pdist <= smallerInsideDiagonalSq; + if (insideMiterOk) { + if (style.join === exports.LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) { + if (clockwise) /* rotating at inner angle */ { + verts.push(imx, imy); // inner miter point + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex + verts.push(imx, imy); // inner miter point + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex + } + else /* rotating at outer angle */ { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex + verts.push(omx, omy); // outer miter point + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's outer vertex + verts.push(omx, omy); // outer miter point + } + indexCount += 2; + } + else if (style.join === exports.LINE_JOIN.ROUND) { + if (clockwise) /* arc is outside */ { + verts.push(imx, imy); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 4; + verts.push(imx, imy); + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); + } + else /* arc is inside */ { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(omx, omy); + indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4; + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); + verts.push(omx, omy); + } + } + else { + verts.push(imx, imy); + verts.push(omx, omy); + } + } + else // inside miter is NOT ok + { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex + if (style.join === exports.LINE_JOIN.ROUND) { + if (clockwise) /* arc is outside */ { + indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 2; + } + else /* arc is inside */ { + indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 2; + } + } + else if (style.join === exports.LINE_JOIN.MITER && pdist / widthSquared <= miterLimitSquared) { + if (clockwise) { + verts.push(omx, omy); // inner miter point + verts.push(omx, omy); // inner miter point + } + else { + verts.push(imx, imy); // outer miter point + verts.push(imx, imy); // outer miter point + } + indexCount += 2; + } + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's inner vertex + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex + indexCount += 2; + } + } + x0 = points[(length - 2) * 2]; + y0 = points[((length - 2) * 2) + 1]; + x1 = points[(length - 1) * 2]; + y1 = points[((length - 1) * 2) + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + if (!closedShape) { + if (style.cap === exports.LINE_CAP.ROUND) { + indexCount += round(x1 - (perpx * (innerWeight - outerWeight) * 0.5), y1 - (perpy * (innerWeight - outerWeight) * 0.5), x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), verts, false) + 2; + } + else if (style.cap === exports.LINE_CAP.SQUARE) { + indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts); + } + } + var indices = graphicsGeometry.indices; + var eps2 = GRAPHICS_CURVES.epsilon * GRAPHICS_CURVES.epsilon; + // indices.push(indexStart); + for (var i = indexStart; i < indexCount + indexStart - 2; ++i) { + x0 = verts[(i * 2)]; + y0 = verts[(i * 2) + 1]; + x1 = verts[(i + 1) * 2]; + y1 = verts[((i + 1) * 2) + 1]; + x2 = verts[(i + 2) * 2]; + y2 = verts[((i + 2) * 2) + 1]; + /* Skip zero area triangles */ + if (Math.abs((x0 * (y1 - y2)) + (x1 * (y2 - y0)) + (x2 * (y0 - y1))) < eps2) { + continue; + } + indices.push(i, i + 1, i + 2); + } + } + /** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildNativeLine(graphicsData, graphicsGeometry) { + var i = 0; + var shape = graphicsData.shape; + var points = graphicsData.points || shape.points; + var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; + if (points.length === 0) + { return; } + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var length = points.length / 2; + var startIndex = verts.length / 2; + var currentIndex = startIndex; + verts.push(points[0], points[1]); + for (i = 1; i < length; i++) { + verts.push(points[i * 2], points[(i * 2) + 1]); + indices.push(currentIndex, currentIndex + 1); + currentIndex++; + } + if (closedShape) { + indices.push(currentIndex, startIndex); + } + } + /** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildLine(graphicsData, graphicsGeometry) { + if (graphicsData.lineStyle.native) { + buildNativeLine(graphicsData, graphicsGeometry); + } + else { + buildNonNativeLine(graphicsData, graphicsGeometry); + } + } + + /** + * Utilities for arc curves. + * @private + */ + var ArcUtils = /** @class */ (function () { + function ArcUtils() { + } + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * @private + * @param x1 - The x-coordinate of the beginning of the arc + * @param y1 - The y-coordinate of the beginning of the arc + * @param x2 - The x-coordinate of the end of the arc + * @param y2 - The y-coordinate of the end of the arc + * @param radius - The radius of the arc + * @param points - + * @returns - If the arc length is valid, return center of circle, radius and other info otherwise `null`. + */ + ArcUtils.curveTo = function (x1, y1, x2, y2, radius, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs((a1 * b2) - (b1 * a2)); + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + return null; + } + var dd = (a1 * a1) + (b1 * b1); + var cc = (a2 * a2) + (b2 * b2); + var tt = (a1 * a2) + (b1 * b2); + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = (k1 * b2) + (k2 * b1); + var cy = (k1 * a2) + (k2 * a1); + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + return { + cx: (cx + x1), + cy: (cy + y1), + radius: radius, + startAngle: startAngle, + endAngle: endAngle, + anticlockwise: (b1 * a2 > b2 * a1), + }; + }; + /* eslint-disable max-len */ + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * @private + * @param _startX - Start x location of arc + * @param _startY - Start y location of arc + * @param cx - The x-coordinate of the center of the circle + * @param cy - The y-coordinate of the center of the circle + * @param radius - The radius of the circle + * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param endAngle - The ending angle, in radians + * @param _anticlockwise - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @param points - Collection of points to add to + */ + ArcUtils.arc = function (_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) { + var sweep = endAngle - startAngle; + var n = GRAPHICS_CURVES._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40); + var theta = (sweep) / (n * 2); + var theta2 = theta * 2; + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + var segMinus = n - 1; + var remainder = (segMinus % 1) / segMinus; + for (var i = 0; i <= segMinus; ++i) { + var real = i + (remainder * i); + var angle = ((theta) + startAngle + (theta2 * real)); + var c = Math.cos(angle); + var s = -Math.sin(angle); + points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy); + } + }; + return ArcUtils; + }()); + + /** + * Utilities for bezier curves + * @private + */ + var BezierUtils = /** @class */ (function () { + function BezierUtils() { + } + /** + * Calculate length of bezier curve. + * Analytical solution is impossible, since it involves an integral that does not integrate in general. + * Therefore numerical solution is used. + * @private + * @param fromX - Starting point x + * @param fromY - Starting point y + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns - Length of bezier curve + */ + BezierUtils.curveLength = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var n = 10; + var result = 0.0; + var t = 0.0; + var t2 = 0.0; + var t3 = 0.0; + var nt = 0.0; + var nt2 = 0.0; + var nt3 = 0.0; + var x = 0.0; + var y = 0.0; + var dx = 0.0; + var dy = 0.0; + var prevX = fromX; + var prevY = fromY; + for (var i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = (1.0 - t); + nt2 = nt * nt; + nt3 = nt2 * nt; + x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX); + y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY); + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + result += Math.sqrt((dx * dx) + (dy * dy)); + } + return result; + }; + /** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @param points - Path array to push points into + */ + BezierUtils.curveTo = function (cpX, cpY, cpX2, cpY2, toX, toY, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + points.length -= 2; + var n = GRAPHICS_CURVES._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)); + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + points.push(fromX, fromY); + for (var 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; + points.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY)); + } + }; + return BezierUtils; + }()); + + /** + * Utilities for quadratic curves. + * @private + */ + var QuadraticUtils = /** @class */ (function () { + function QuadraticUtils() { + } + /** + * Calculate length of quadratic curve + * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} + * for the detailed explanation of math behind this. + * @private + * @param fromX - x-coordinate of curve start point + * @param fromY - y-coordinate of curve start point + * @param cpX - x-coordinate of curve control point + * @param cpY - y-coordinate of curve control point + * @param toX - x-coordinate of curve end point + * @param toY - y-coordinate of curve end point + * @returns - Length of quadratic curve + */ + QuadraticUtils.curveLength = function (fromX, fromY, cpX, cpY, toX, toY) { + var ax = fromX - (2.0 * cpX) + toX; + var ay = fromY - (2.0 * cpY) + toY; + var bx = (2.0 * cpX) - (2.0 * fromX); + var by = (2.0 * cpY) - (2.0 * fromY); + var a = 4.0 * ((ax * ax) + (ay * ay)); + var b = 4.0 * ((ax * bx) + (ay * by)); + var c = (bx * bx) + (by * by); + var s = 2.0 * Math.sqrt(a + b + c); + var a2 = Math.sqrt(a); + var a32 = 2.0 * a * a2; + var c2 = 2.0 * Math.sqrt(c); + var ba = b / a2; + return ((a32 * s) + + (a2 * b * (s - c2)) + + (((4.0 * c * a) - (b * b)) + * Math.log(((2.0 * a2) + ba + s) / (ba + c2)))) / (4.0 * a32); + }; + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * @private + * @param cpX - Control point x + * @param cpY - Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @param points - Points to add segments to. + */ + QuadraticUtils.curveTo = function (cpX, cpY, toX, toY, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var n = GRAPHICS_CURVES._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY)); + var xa = 0; + var ya = 0; + for (var i = 1; i <= n; ++i) { + var j = i / n; + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j)); + } + }; + return QuadraticUtils; + }()); + + /** + * A structure to hold interim batch objects for Graphics. + * @memberof PIXI.graphicsUtils + */ + var BatchPart = /** @class */ (function () { + function BatchPart() { + this.reset(); + } + /** + * Begin batch part. + * @param style + * @param startIndex + * @param attribStart + */ + BatchPart.prototype.begin = function (style, startIndex, attribStart) { + this.reset(); + this.style = style; + this.start = startIndex; + this.attribStart = attribStart; + }; + /** + * End batch part. + * @param endIndex + * @param endAttrib + */ + BatchPart.prototype.end = function (endIndex, endAttrib) { + this.attribSize = endAttrib - this.attribStart; + this.size = endIndex - this.start; + }; + BatchPart.prototype.reset = function () { + this.style = null; + this.size = 0; + this.start = 0; + this.attribStart = 0; + this.attribSize = 0; + }; + return BatchPart; + }()); + + /** + * Generalized convenience utilities for Graphics. + * @namespace graphicsUtils + * @memberof PIXI + */ + var _a; + /** + * Map of fill commands for each shape type. + * @memberof PIXI.graphicsUtils + * @member {object} FILL_COMMANDS + */ + var FILL_COMMANDS = (_a = {}, + _a[exports.SHAPES.POLY] = buildPoly, + _a[exports.SHAPES.CIRC] = buildCircle, + _a[exports.SHAPES.ELIP] = buildCircle, + _a[exports.SHAPES.RECT] = buildRectangle, + _a[exports.SHAPES.RREC] = buildRoundedRectangle, + _a); + /** + * Batch pool, stores unused batches for preventing allocations. + * @memberof PIXI.graphicsUtils + * @member {Array} BATCH_POOL + */ + var BATCH_POOL = []; + /** + * Draw call pool, stores unused draw calls for preventing allocations. + * @memberof PIXI.graphicsUtils + * @member {Array} DRAW_CALL_POOL + */ + var DRAW_CALL_POOL = []; + + /** + * A class to contain data useful for Graphics objects + * @memberof PIXI + */ + var GraphicsData = /** @class */ (function () { + /** + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param fillStyle - the width of the line to draw + * @param lineStyle - the color of the line to draw + * @param matrix - Transform matrix + */ + function GraphicsData(shape, fillStyle, lineStyle, matrix) { + if (fillStyle === void 0) { fillStyle = null; } + if (lineStyle === void 0) { lineStyle = null; } + if (matrix === void 0) { matrix = null; } + /** The collection of points. */ + this.points = []; + /** The collection of holes. */ + this.holes = []; + this.shape = shape; + this.lineStyle = lineStyle; + this.fillStyle = fillStyle; + this.matrix = matrix; + this.type = shape.type; + } + /** + * Creates a new GraphicsData object with the same values as this one. + * @returns - Cloned GraphicsData object + */ + GraphicsData.prototype.clone = function () { + return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix); + }; + /** Destroys the Graphics data. */ + GraphicsData.prototype.destroy = function () { + this.shape = null; + this.holes.length = 0; + this.holes = null; + this.points.length = 0; + this.points = null; + this.lineStyle = null; + this.fillStyle = null; + }; + return GraphicsData; + }()); + + var tmpPoint = new Point(); + /** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive + * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster. + * @memberof PIXI + */ + var GraphicsGeometry = /** @class */ (function (_super) { + __extends$e(GraphicsGeometry, _super); + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function GraphicsGeometry() { + var _this = _super.call(this) || this; + /** Minimal distance between points that are considered different. Affects line tesselation. */ + _this.closePointEps = 1e-4; + /** Padding to add to the bounds. */ + _this.boundsPadding = 0; + _this.uvsFloat32 = null; + _this.indicesUint16 = null; + _this.batchable = false; + /** An array of points to draw, 2 numbers per point */ + _this.points = []; + /** The collection of colors */ + _this.colors = []; + /** The UVs collection */ + _this.uvs = []; + /** The indices of the vertices */ + _this.indices = []; + /** Reference to the texture IDs. */ + _this.textureIds = []; + /** + * The collection of drawn shapes. + * @member {PIXI.GraphicsData[]} + */ + _this.graphicsData = []; + /** + * List of current draw calls drived from the batches. + * @member {PIXI.BatchDrawCall[]} + */ + _this.drawCalls = []; + /** Batches need to regenerated if the geometry is updated. */ + _this.batchDirty = -1; + /** + * Intermediate abstract format sent to batch system. + * Can be converted to drawCalls or to batchable objects. + * @member {PIXI.graphicsUtils.BatchPart[]} + */ + _this.batches = []; + /** Used to detect if the graphics object has changed. */ + _this.dirty = 0; + /** Used to check if the cache is dirty. */ + _this.cacheDirty = -1; + /** Used to detect if we cleared the graphicsData. */ + _this.clearDirty = 0; + /** Index of the last batched shape in the stack of calls. */ + _this.shapeIndex = 0; + /** Cached bounds. */ + _this._bounds = new Bounds(); + /** The bounds dirty flag. */ + _this.boundsDirty = -1; + return _this; + } + Object.defineProperty(GraphicsGeometry.prototype, "bounds", { + /** + * Get the current bounds of the graphic geometry. + * @readonly + */ + get: function () { + this.updateBatches(); + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.calculateBounds(); + } + return this._bounds; + }, + enumerable: false, + configurable: true + }); + /** Call if you changed graphicsData manually. Empties all batch buffers. */ + GraphicsGeometry.prototype.invalidate = function () { + this.boundsDirty = -1; + this.dirty++; + this.batchDirty++; + this.shapeIndex = 0; + this.points.length = 0; + this.colors.length = 0; + this.uvs.length = 0; + this.indices.length = 0; + this.textureIds.length = 0; + for (var i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + for (var i = 0; i < this.batches.length; i++) { + var batchPart = this.batches[i]; + batchPart.reset(); + BATCH_POOL.push(batchPart); + } + this.batches.length = 0; + }; + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * @returns - This GraphicsGeometry object. Good for chaining method calls + */ + GraphicsGeometry.prototype.clear = function () { + if (this.graphicsData.length > 0) { + this.invalidate(); + this.clearDirty++; + this.graphicsData.length = 0; + } + return this; + }; + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param fillStyle - Defines style of the fill. + * @param lineStyle - Defines style of the lines. + * @param matrix - Transform applied to the points of the shape. + * @returns - Returns geometry for chaining. + */ + GraphicsGeometry.prototype.drawShape = function (shape, fillStyle, lineStyle, matrix) { + if (fillStyle === void 0) { fillStyle = null; } + if (lineStyle === void 0) { lineStyle = null; } + if (matrix === void 0) { matrix = null; } + var data = new GraphicsData(shape, fillStyle, lineStyle, matrix); + this.graphicsData.push(data); + this.dirty++; + return this; + }; + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param matrix - Transform applied to the points of the shape. + * @returns - Returns geometry for chaining. + */ + GraphicsGeometry.prototype.drawHole = function (shape, matrix) { + if (matrix === void 0) { matrix = null; } + if (!this.graphicsData.length) { + return null; + } + var data = new GraphicsData(shape, null, null, matrix); + var lastShape = this.graphicsData[this.graphicsData.length - 1]; + data.lineStyle = lastShape.lineStyle; + lastShape.holes.push(data); + this.dirty++; + return this; + }; + /** Destroys the GraphicsGeometry object. */ + GraphicsGeometry.prototype.destroy = function () { + _super.prototype.destroy.call(this); + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + this.points.length = 0; + this.points = null; + this.colors.length = 0; + this.colors = null; + this.uvs.length = 0; + this.uvs = null; + this.indices.length = 0; + this.indices = null; + this.indexBuffer.destroy(); + this.indexBuffer = null; + this.graphicsData.length = 0; + this.graphicsData = null; + this.drawCalls.length = 0; + this.drawCalls = null; + this.batches.length = 0; + this.batches = null; + this._bounds = null; + }; + /** + * Check to see if a point is contained within this geometry. + * @param point - Point to check if it's contained. + * @returns {boolean} `true` if the point is contained within geometry. + */ + GraphicsGeometry.prototype.containsPoint = function (point) { + var graphicsData = this.graphicsData; + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + if (!data.fillStyle.visible) { + continue; + } + // only deal with fills.. + if (data.shape) { + if (data.matrix) { + data.matrix.applyInverse(point, tmpPoint); + } + else { + tmpPoint.copyFrom(point); + } + if (data.shape.contains(tmpPoint.x, tmpPoint.y)) { + var hitHole = false; + if (data.holes) { + for (var i_1 = 0; i_1 < data.holes.length; i_1++) { + var hole = data.holes[i_1]; + if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) { + hitHole = true; + break; + } + } + } + if (!hitHole) { + return true; + } + } + } + } + return false; + }; + /** + * Generates intermediate batch data. Either gets converted to drawCalls + * or used to convert to batch objects directly by the Graphics object. + */ + GraphicsGeometry.prototype.updateBatches = function () { + if (!this.graphicsData.length) { + this.batchable = true; + return; + } + if (!this.validateBatching()) { + return; + } + this.cacheDirty = this.dirty; + var uvs = this.uvs; + var graphicsData = this.graphicsData; + var batchPart = null; + var currentStyle = null; + if (this.batches.length > 0) { + batchPart = this.batches[this.batches.length - 1]; + currentStyle = batchPart.style; + } + for (var i = this.shapeIndex; i < graphicsData.length; i++) { + this.shapeIndex++; + var data = graphicsData[i]; + var fillStyle = data.fillStyle; + var lineStyle = data.lineStyle; + var command = FILL_COMMANDS[data.type]; + // build out the shapes points.. + command.build(data); + if (data.matrix) { + this.transformPoints(data.points, data.matrix); + } + if (fillStyle.visible || lineStyle.visible) { + this.processHoles(data.holes); + } + for (var j = 0; j < 2; j++) { + var style = (j === 0) ? fillStyle : lineStyle; + if (!style.visible) + { continue; } + var nextTexture = style.texture.baseTexture; + var index_1 = this.indices.length; + var attribIndex = this.points.length / 2; + nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; + if (j === 0) { + this.processFill(data); + } + else { + this.processLine(data); + } + var size = (this.points.length / 2) - attribIndex; + if (size === 0) + { continue; } + // close batch if style is different + if (batchPart && !this._compareStyles(currentStyle, style)) { + batchPart.end(index_1, attribIndex); + batchPart = null; + } + // spawn new batch if its first batch or previous was closed + if (!batchPart) { + batchPart = BATCH_POOL.pop() || new BatchPart(); + batchPart.begin(style, index_1, attribIndex); + this.batches.push(batchPart); + currentStyle = style; + } + this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix); + } + } + var index = this.indices.length; + var attrib = this.points.length / 2; + if (batchPart) { + batchPart.end(index, attrib); + } + if (this.batches.length === 0) { + // there are no visible styles in GraphicsData + // its possible that someone wants Graphics just for the bounds + this.batchable = true; + return; + } + var need32 = attrib > 0xffff; + // prevent allocation when length is same as buffer + if (this.indicesUint16 && this.indices.length === this.indicesUint16.length + && need32 === (this.indicesUint16.BYTES_PER_ELEMENT > 2)) { + this.indicesUint16.set(this.indices); + } + else { + this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices); + } + // TODO make this a const.. + this.batchable = this.isBatchable(); + if (this.batchable) { + this.packBatches(); + } + else { + this.buildDrawCalls(); + } + }; + /** + * Affinity check + * @param styleA + * @param styleB + */ + GraphicsGeometry.prototype._compareStyles = function (styleA, styleB) { + if (!styleA || !styleB) { + return false; + } + if (styleA.texture.baseTexture !== styleB.texture.baseTexture) { + return false; + } + if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) { + return false; + } + if (!!styleA.native !== !!styleB.native) { + return false; + } + return true; + }; + /** Test geometry for batching process. */ + GraphicsGeometry.prototype.validateBatching = function () { + if (this.dirty === this.cacheDirty || !this.graphicsData.length) { + return false; + } + for (var i = 0, l = this.graphicsData.length; i < l; i++) { + var data = this.graphicsData[i]; + var fill = data.fillStyle; + var line = data.lineStyle; + if (fill && !fill.texture.baseTexture.valid) + { return false; } + if (line && !line.texture.baseTexture.valid) + { return false; } + } + return true; + }; + /** Offset the indices so that it works with the batcher. */ + GraphicsGeometry.prototype.packBatches = function () { + this.batchDirty++; + this.uvsFloat32 = new Float32Array(this.uvs); + var batches = this.batches; + for (var i = 0, l = batches.length; i < l; i++) { + var batch = batches[i]; + for (var j = 0; j < batch.size; j++) { + var index = batch.start + j; + this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; + } + } + }; + /** + * Checks to see if this graphics geometry can be batched. + * Currently it needs to be small enough and not contain any native lines. + */ + GraphicsGeometry.prototype.isBatchable = function () { + // prevent heavy mesh batching + if (this.points.length > 0xffff * 2) { + return false; + } + var batches = this.batches; + for (var i = 0; i < batches.length; i++) { + if (batches[i].style.native) { + return false; + } + } + return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2); + }; + /** Converts intermediate batches data to drawCalls. */ + GraphicsGeometry.prototype.buildDrawCalls = function () { + var TICK = ++BaseTexture._globalBatch; + for (var i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + var colors = this.colors; + var textureIds = this.textureIds; + var currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new BatchDrawCall(); + currentGroup.texArray = new BatchTextureArray(); + } + currentGroup.texArray.count = 0; + currentGroup.start = 0; + currentGroup.size = 0; + currentGroup.type = exports.DRAW_MODES.TRIANGLES; + var textureCount = 0; + var currentTexture = null; + var textureId = 0; + var native = false; + var drawMode = exports.DRAW_MODES.TRIANGLES; + var index = 0; + this.drawCalls.push(currentGroup); + // TODO - this can be simplified + for (var i = 0; i < this.batches.length; i++) { + var data = this.batches[i]; + // TODO add some full on MAX_TEXTURE CODE.. + var MAX_TEXTURES = 8; + // Forced cast for checking `native` without errors + var style = data.style; + var nextTexture = style.texture.baseTexture; + if (native !== !!style.native) { + native = !!style.native; + drawMode = native ? exports.DRAW_MODES.LINES : exports.DRAW_MODES.TRIANGLES; + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + if (nextTexture._batchEnabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + textureCount = 0; + if (currentGroup.size > 0) { + currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new BatchDrawCall(); + currentGroup.texArray = new BatchTextureArray(); + } + this.drawCalls.push(currentGroup); + } + currentGroup.start = index; + currentGroup.size = 0; + currentGroup.texArray.count = 0; + currentGroup.type = drawMode; + } + // TODO add this to the render part.. + // Hack! Because texture has protected `touched` + nextTexture.touched = 1; // touch; + nextTexture._batchEnabled = TICK; + nextTexture._batchLocation = textureCount; + nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; + currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture; + textureCount++; + } + } + currentGroup.size += data.size; + index += data.size; + textureId = nextTexture._batchLocation; + this.addColors(colors, style.color, style.alpha, data.attribSize, data.attribStart); + this.addTextureIds(textureIds, textureId, data.attribSize, data.attribStart); + } + BaseTexture._globalBatch = TICK; + // upload.. + // merge for now! + this.packAttributes(); + }; + /** Packs attributes to single buffer. */ + GraphicsGeometry.prototype.packAttributes = function () { + var verts = this.points; + var uvs = this.uvs; + var colors = this.colors; + var textureIds = this.textureIds; + // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes + var glPoints = new ArrayBuffer(verts.length * 3 * 4); + var f32 = new Float32Array(glPoints); + var u32 = new Uint32Array(glPoints); + var p = 0; + for (var i = 0; i < verts.length / 2; i++) { + f32[p++] = verts[i * 2]; + f32[p++] = verts[(i * 2) + 1]; + f32[p++] = uvs[i * 2]; + f32[p++] = uvs[(i * 2) + 1]; + u32[p++] = colors[i]; + f32[p++] = textureIds[i]; + } + this._buffer.update(glPoints); + this._indexBuffer.update(this.indicesUint16); + }; + /** + * Process fill part of Graphics. + * @param data + */ + GraphicsGeometry.prototype.processFill = function (data) { + if (data.holes.length) { + buildPoly.triangulate(data, this); + } + else { + var command = FILL_COMMANDS[data.type]; + command.triangulate(data, this); + } + }; + /** + * Process line part of Graphics. + * @param data + */ + GraphicsGeometry.prototype.processLine = function (data) { + buildLine(data, this); + for (var i = 0; i < data.holes.length; i++) { + buildLine(data.holes[i], this); + } + }; + /** + * Process the holes data. + * @param holes + */ + GraphicsGeometry.prototype.processHoles = function (holes) { + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + var command = FILL_COMMANDS[hole.type]; + command.build(hole); + if (hole.matrix) { + this.transformPoints(hole.points, hole.matrix); + } + } + }; + /** Update the local bounds of the object. Expensive to use performance-wise. */ + GraphicsGeometry.prototype.calculateBounds = function () { + var bounds = this._bounds; + bounds.clear(); + bounds.addVertexData(this.points, 0, this.points.length); + bounds.pad(this.boundsPadding, this.boundsPadding); + }; + /** + * Transform points using matrix. + * @param points - Points to transform + * @param matrix - Transform matrix + */ + GraphicsGeometry.prototype.transformPoints = function (points, matrix) { + for (var i = 0; i < points.length / 2; i++) { + var x = points[(i * 2)]; + var y = points[(i * 2) + 1]; + points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx; + points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty; + } + }; + /** + * Add colors. + * @param colors - List of colors to add to + * @param color - Color to add + * @param alpha - Alpha to use + * @param size - Number of colors to add + * @param offset + */ + GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size, offset) { + if (offset === void 0) { offset = 0; } + // TODO use the premultiply bits Ivan added + var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); + var rgba = premultiplyTint(rgb, alpha); + colors.length = Math.max(colors.length, offset + size); + for (var i = 0; i < size; i++) { + colors[offset + i] = rgba; + } + }; + /** + * Add texture id that the shader/fragment wants to use. + * @param textureIds + * @param id + * @param size + * @param offset + */ + GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size, offset) { + if (offset === void 0) { offset = 0; } + textureIds.length = Math.max(textureIds.length, offset + size); + for (var i = 0; i < size; i++) { + textureIds[offset + i] = id; + } + }; + /** + * Generates the UVs for a shape. + * @param verts - Vertices + * @param uvs - UVs + * @param texture - Reference to Texture + * @param start - Index buffer start index. + * @param size - The size/length for index buffer. + * @param matrix - Optional transform for all points. + */ + GraphicsGeometry.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) { + if (matrix === void 0) { matrix = null; } + var index = 0; + var uvsStart = uvs.length; + var frame = texture.frame; + while (index < size) { + var x = verts[(start + index) * 2]; + var y = verts[((start + index) * 2) + 1]; + if (matrix) { + var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx; + y = (matrix.b * x) + (matrix.d * y) + matrix.ty; + x = nx; + } + index++; + uvs.push(x / frame.width, y / frame.height); + } + var baseTexture = texture.baseTexture; + if (frame.width < baseTexture.width + || frame.height < baseTexture.height) { + this.adjustUvs(uvs, texture, uvsStart, size); + } + }; + /** + * Modify uvs array according to position of texture region + * Does not work with rotated or trimmed textures + * @param uvs - array + * @param texture - region + * @param start - starting index for uvs + * @param size - how many points to adjust + */ + GraphicsGeometry.prototype.adjustUvs = function (uvs, texture, start, size) { + var baseTexture = texture.baseTexture; + var eps = 1e-6; + var finish = start + (size * 2); + var frame = texture.frame; + var scaleX = frame.width / baseTexture.width; + var scaleY = frame.height / baseTexture.height; + var offsetX = frame.x / frame.width; + var offsetY = frame.y / frame.height; + var minX = Math.floor(uvs[start] + eps); + var minY = Math.floor(uvs[start + 1] + eps); + for (var i = start + 2; i < finish; i += 2) { + minX = Math.min(minX, Math.floor(uvs[i] + eps)); + minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); + } + offsetX -= minX; + offsetY -= minY; + for (var i = start; i < finish; i += 2) { + uvs[i] = (uvs[i] + offsetX) * scaleX; + uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY; + } + }; + /** + * The maximum number of points to consider an object "batchable", + * able to be batched by the renderer's batch system. + \ + */ + GraphicsGeometry.BATCHABLE_SIZE = 100; + return GraphicsGeometry; + }(BatchGeometry)); + + /** + * Represents the line style for Graphics. + * @memberof PIXI + */ + var LineStyle = /** @class */ (function (_super) { + __extends$e(LineStyle, _super); + function LineStyle() { + var _this = _super !== null && _super.apply(this, arguments) || this; + /** The width (thickness) of any lines drawn. */ + _this.width = 0; + /** The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). WebGL only. */ + _this.alignment = 0.5; + /** If true the lines will be draw using LINES instead of TRIANGLE_STRIP. */ + _this.native = false; + /** + * Line cap style. + * @member {PIXI.LINE_CAP} + * @default PIXI.LINE_CAP.BUTT + */ + _this.cap = exports.LINE_CAP.BUTT; + /** + * Line join style. + * @member {PIXI.LINE_JOIN} + * @default PIXI.LINE_JOIN.MITER + */ + _this.join = exports.LINE_JOIN.MITER; + /** Miter limit. */ + _this.miterLimit = 10; + return _this; + } + /** Clones the object. */ + LineStyle.prototype.clone = function () { + var obj = new LineStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + obj.width = this.width; + obj.alignment = this.alignment; + obj.native = this.native; + obj.cap = this.cap; + obj.join = this.join; + obj.miterLimit = this.miterLimit; + return obj; + }; + /** Reset the line style to default. */ + LineStyle.prototype.reset = function () { + _super.prototype.reset.call(this); + // Override default line style color + this.color = 0x0; + this.alignment = 0.5; + this.width = 0; + this.native = false; + }; + return LineStyle; + }(FillStyle)); + + var temp = new Float32Array(3); + // a default shaders map used by graphics.. + var DEFAULT_SHADERS = {}; + /** + * The Graphics class is primarily used to render primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. However, you can also use a Graphics + * object to build a list of primitives to use as a mask, or as a complex hitArea. + * + * Please note that due to legacy naming conventions, the behavior of some functions in this class + * can be confusing. Each call to `drawRect()`, `drawPolygon()`, etc. actually stores that primitive + * in the Geometry class's GraphicsGeometry object for later use in rendering or hit testing - the + * functions do not directly draw anything to the screen. Similarly, the `clear()` function doesn't + * change the screen, it simply resets the list of primitives, which can be useful if you want to + * rebuild the contents of an existing Graphics object. + * + * Once a GraphicsGeometry list is built, you can re-use it in other Geometry objects as + * an optimization, by passing it into a new Geometry object's constructor. Because of this + * ability, it's important to call `destroy()` on Geometry objects once you are done with them, to + * properly dereference each GraphicsGeometry and prevent memory leaks. + * @memberof PIXI + */ + var Graphics = /** @class */ (function (_super) { + __extends$e(Graphics, _super); + /** + * @param geometry - Geometry to use, if omitted will create a new GraphicsGeometry instance. + */ + function Graphics(geometry) { + if (geometry === void 0) { geometry = null; } + var _this = _super.call(this) || this; + /** + * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. + * Can be shared between multiple Graphics objects. + */ + _this.shader = null; + /** Renderer plugin for batching */ + _this.pluginName = 'batch'; + /** + * Current path + * @readonly + */ + _this.currentPath = null; + /** A collections of batches! These can be drawn by the renderer batch system. */ + _this.batches = []; + /** Update dirty for limiting calculating tints for batches. */ + _this.batchTint = -1; + /** Update dirty for limiting calculating batches.*/ + _this.batchDirty = -1; + /** Copy of the object vertex data. */ + _this.vertexData = null; + /** Current fill style. */ + _this._fillStyle = new FillStyle(); + /** Current line style. */ + _this._lineStyle = new LineStyle(); + /** Current shape transform matrix. */ + _this._matrix = null; + /** Current hole mode is enabled. */ + _this._holeMode = false; + /** + * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g., + * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. + */ + _this.state = State.for2d(); + _this._geometry = geometry || new GraphicsGeometry(); + _this._geometry.refCount++; + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + _this._transformID = -1; + // Set default + _this.tint = 0xFFFFFF; + _this.blendMode = exports.BLEND_MODES.NORMAL; + return _this; + } + Object.defineProperty(Graphics.prototype, "geometry", { + /** + * Includes vertex positions, face indices, normals, colors, UVs, and + * custom attributes within buffers, reducing the cost of passing all + * this data to the GPU. Can be shared between multiple Mesh or Graphics objects. + * @readonly + */ + get: function () { + return this._geometry; + }, + enumerable: false, + configurable: true + }); + /** + * Creates a new Graphics object with the same values as this one. + * Note that only the geometry of the object is cloned, not its transform (position,scale,etc) + * @returns - A clone of the graphics object + */ + Graphics.prototype.clone = function () { + this.finishPoly(); + return new Graphics(this._geometry); + }; + Object.defineProperty(Graphics.prototype, "blendMode", { + get: function () { + return this.state.blendMode; + }, + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. Note that, since each + * primitive in the GraphicsGeometry list is rendered sequentially, modes + * such as `PIXI.BLEND_MODES.ADD` and `PIXI.BLEND_MODES.MULTIPLY` will + * be applied per-primitive. + * @default PIXI.BLEND_MODES.NORMAL + */ + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "tint", { + /** + * The tint applied to each graphic shape. This is a hex value. A value of + * 0xFFFFFF will remove any tint effect. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "fill", { + /** + * The current fill style. + * @readonly + */ + get: function () { + return this._fillStyle; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "line", { + /** + * The current line style. + * @readonly + */ + get: function () { + return this._lineStyle; + }, + enumerable: false, + configurable: true + }); + Graphics.prototype.lineStyle = function (options, color, alpha, alignment, native) { + if (options === void 0) { options = null; } + if (color === void 0) { color = 0x0; } + if (alpha === void 0) { alpha = 1; } + if (alignment === void 0) { alignment = 0.5; } + if (native === void 0) { native = false; } + // Support non-object params: (width, color, alpha, alignment, native) + if (typeof options === 'number') { + options = { width: options, color: color, alpha: alpha, alignment: alignment, native: native }; + } + return this.lineTextureStyle(options); + }; + /** + * Like line style but support texture for line fill. + * @param [options] - Collection of options for setting line style. + * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style + * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use + * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style. + * Default 0xFFFFFF if texture present. + * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {PIXI.Matrix} [options.matrix=null] - Texture matrix to transform texture + * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outer). + * WebGL only. + * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style + * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style + * @param {number}[options.miterLimit=10] - miter limit ratio + * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.lineTextureStyle = function (options) { + // Apply defaults + options = Object.assign({ + width: 0, + texture: Texture.WHITE, + color: (options && options.texture) ? 0xFFFFFF : 0x0, + alpha: 1, + matrix: null, + alignment: 0.5, + native: false, + cap: exports.LINE_CAP.BUTT, + join: exports.LINE_JOIN.MITER, + miterLimit: 10, + }, options); + if (this.currentPath) { + this.startPoly(); + } + var visible = options.width > 0 && options.alpha > 0; + if (!visible) { + this._lineStyle.reset(); + } + else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); + } + Object.assign(this._lineStyle, { visible: visible }, options); + } + return this; + }; + /** + * Start a polygon object internally. + * @protected + */ + Graphics.prototype.startPoly = function () { + if (this.currentPath) { + var points = this.currentPath.points; + var len = this.currentPath.points.length; + if (len > 2) { + this.drawShape(this.currentPath); + this.currentPath = new Polygon(); + this.currentPath.closeStroke = false; + this.currentPath.points.push(points[len - 2], points[len - 1]); + } + } + else { + this.currentPath = new Polygon(); + this.currentPath.closeStroke = false; + } + }; + /** + * Finish the polygon object. + * @protected + */ + Graphics.prototype.finishPoly = function () { + if (this.currentPath) { + if (this.currentPath.points.length > 2) { + this.drawShape(this.currentPath); + this.currentPath = null; + } + else { + this.currentPath.points.length = 0; + } + } + }; + /** + * Moves the current drawing position to x, y. + * @param x - the X coordinate to move to + * @param y - the Y coordinate to move to + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.moveTo = function (x, y) { + this.startPoly(); + this.currentPath.points[0] = x; + this.currentPath.points[1] = y; + return this; + }; + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * @param x - the X coordinate to draw to + * @param y - the Y coordinate to draw to + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.lineTo = function (x, y) { + if (!this.currentPath) { + this.moveTo(0, 0); + } + // remove duplicates.. + var points = this.currentPath.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + if (fromX !== x || fromY !== y) { + points.push(x, y); + } + return this; + }; + /** + * Initialize the curve + * @param x + * @param y + */ + Graphics.prototype._initCurve = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (this.currentPath) { + if (this.currentPath.points.length === 0) { + this.currentPath.points = [x, y]; + } + } + else { + this.moveTo(x, y); + } + }; + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * @param cpX - Control point x + * @param cpY - Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + this._initCurve(); + var points = this.currentPath.points; + if (points.length === 0) { + this.moveTo(0, 0); + } + QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); + return this; + }; + /** + * Calculate the points for a bezier curve and then draws it. + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns This Graphics object. Good for chaining method calls + */ + Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + this._initCurve(); + BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); + return this; + }; + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * @param x1 - The x-coordinate of the first tangent point of the arc + * @param y1 - The y-coordinate of the first tangent point of the arc + * @param x2 - The x-coordinate of the end of the arc + * @param y2 - The y-coordinate of the end of the arc + * @param radius - The radius of the arc + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + this._initCurve(x1, y1); + var points = this.currentPath.points; + var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); + if (result) { + var cx = result.cx, cy = result.cy, radius_1 = result.radius, startAngle = result.startAngle, endAngle = result.endAngle, anticlockwise = result.anticlockwise; + this.arc(cx, cy, radius_1, startAngle, endAngle, anticlockwise); + } + return this; + }; + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * @param cx - The x-coordinate of the center of the circle + * @param cy - The y-coordinate of the center of the circle + * @param radius - The radius of the circle + * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param endAngle - The ending angle, in radians + * @param anticlockwise - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { + if (anticlockwise === void 0) { anticlockwise = false; } + if (startAngle === endAngle) { + return this; + } + if (!anticlockwise && endAngle <= startAngle) { + endAngle += PI_2; + } + else if (anticlockwise && startAngle <= endAngle) { + startAngle += PI_2; + } + var sweep = endAngle - startAngle; + if (sweep === 0) { + return this; + } + var startX = cx + (Math.cos(startAngle) * radius); + var startY = cy + (Math.sin(startAngle) * radius); + var eps = this._geometry.closePointEps; + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.points : null; + if (points) { + // TODO: make a better fix. + // We check how far our start is from the last existing point + var xDiff = Math.abs(points[points.length - 2] - startX); + var yDiff = Math.abs(points[points.length - 1] - startY); + if (xDiff < eps && yDiff < eps) { ; } + else { + points.push(startX, startY); + } + } + else { + this.moveTo(startX, startY); + points = this.currentPath.points; + } + ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); + return this; + }; + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * @param color - the color of the fill + * @param alpha - the alpha of the fill + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.beginFill = function (color, alpha) { + if (color === void 0) { color = 0; } + if (alpha === void 0) { alpha = 1; } + return this.beginTextureFill({ texture: Texture.WHITE, color: color, alpha: alpha }); + }; + /** + * Begin the texture fill + * @param options - Object object. + * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill + * @param {number} [options.color=0xffffff] - Background to fill behind texture + * @param {number} [options.alpha=1] - Alpha of fill + * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix + * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.beginTextureFill = function (options) { + // Apply defaults + options = Object.assign({ + texture: Texture.WHITE, + color: 0xFFFFFF, + alpha: 1, + matrix: null, + }, options); + if (this.currentPath) { + this.startPoly(); + } + var visible = options.alpha > 0; + if (!visible) { + this._fillStyle.reset(); + } + else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); + } + Object.assign(this._fillStyle, { visible: visible }, options); + } + return this; + }; + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.endFill = function () { + this.finishPoly(); + this._fillStyle.reset(); + return this; + }; + /** + * Draws a rectangle shape. + * @param x - The X coord of the top-left of the rectangle + * @param y - The Y coord of the top-left of the rectangle + * @param width - The width of the rectangle + * @param height - The height of the rectangle + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawRect = function (x, y, width, height) { + return this.drawShape(new Rectangle(x, y, width, height)); + }; + /** + * Draw a rectangle shape with rounded/beveled corners. + * @param x - The X coord of the top-left of the rectangle + * @param y - The Y coord of the top-left of the rectangle + * @param width - The width of the rectangle + * @param height - The height of the rectangle + * @param radius - Radius of the rectangle corners + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + return this.drawShape(new RoundedRectangle(x, y, width, height, radius)); + }; + /** + * Draws a circle. + * @param x - The X coordinate of the center of the circle + * @param y - The Y coordinate of the center of the circle + * @param radius - The radius of the circle + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawCircle = function (x, y, radius) { + return this.drawShape(new Circle(x, y, radius)); + }; + /** + * Draws an ellipse. + * @param x - The X coordinate of the center of the ellipse + * @param y - The Y coordinate of the center of the ellipse + * @param width - The half width of the ellipse + * @param height - The half height of the ellipse + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawEllipse = function (x, y, width, height) { + return this.drawShape(new Ellipse(x, y, width, height)); + }; + /** + * Draws a polygon using the given path. + * @param {number[]|PIXI.IPointData[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawPolygon = function () { + var arguments$1 = arguments; + + var path = []; + for (var _i = 0; _i < arguments.length; _i++) { + path[_i] = arguments$1[_i]; + } + var points; + var closeStroke = true; // !!this._fillStyle; + var poly = path[0]; + // check if data has points.. + if (poly.points) { + closeStroke = poly.closeStroke; + points = poly.points; + } + else if (Array.isArray(path[0])) { + points = path[0]; + } + else { + points = path; + } + var shape = new Polygon(points); + shape.closeStroke = closeStroke; + this.drawShape(shape); + return this; + }; + /** + * Draw any shape. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawShape = function (shape) { + if (!this._holeMode) { + this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix); + } + else { + this._geometry.drawHole(shape, this._matrix); + } + return this; + }; + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.clear = function () { + this._geometry.clear(); + this._lineStyle.reset(); + this._fillStyle.reset(); + this._boundsID++; + this._matrix = null; + this._holeMode = false; + this.currentPath = null; + return this; + }; + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * @returns - True if only 1 rect. + */ + Graphics.prototype.isFastRect = function () { + var data = this._geometry.graphicsData; + return data.length === 1 + && data[0].shape.type === exports.SHAPES.RECT + && !data[0].matrix + && !data[0].holes.length + && !(data[0].lineStyle.visible && data[0].lineStyle.width); + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + Graphics.prototype._render = function (renderer) { + this.finishPoly(); + var geometry = this._geometry; + // batch part.. + // batch it! + geometry.updateBatches(); + if (geometry.batchable) { + if (this.batchDirty !== geometry.batchDirty) { + this._populateBatches(); + } + this._renderBatched(renderer); + } + else { + // no batching... + renderer.batch.flush(); + this._renderDirect(renderer); + } + }; + /** Populating batches for rendering. */ + Graphics.prototype._populateBatches = function () { + var geometry = this._geometry; + var blendMode = this.blendMode; + var len = geometry.batches.length; + this.batchTint = -1; + this._transformID = -1; + this.batchDirty = geometry.batchDirty; + this.batches.length = len; + this.vertexData = new Float32Array(geometry.points); + for (var i = 0; i < len; i++) { + var gI = geometry.batches[i]; + var color = gI.style.color; + var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size); + var batch = { + vertexData: vertexData, + blendMode: blendMode, + indices: indices, + uvs: uvs, + _batchRGB: hex2rgb(color), + _tintRGB: color, + _texture: gI.style.texture, + alpha: gI.style.alpha, + worldAlpha: 1 + }; + this.batches[i] = batch; + } + }; + /** + * Renders the batches using the BathedRenderer plugin + * @param renderer - The renderer + */ + Graphics.prototype._renderBatched = function (renderer) { + if (!this.batches.length) { + return; + } + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + this.calculateVertices(); + this.calculateTints(); + for (var i = 0, l = this.batches.length; i < l; i++) { + var batch = this.batches[i]; + batch.worldAlpha = this.worldAlpha * batch.alpha; + renderer.plugins[this.pluginName].render(batch); + } + }; + /** + * Renders the graphics direct + * @param renderer - The renderer + */ + Graphics.prototype._renderDirect = function (renderer) { + var shader = this._resolveDirectShader(renderer); + var geometry = this._geometry; + var tint = this.tint; + var worldAlpha = this.worldAlpha; + var uniforms = shader.uniforms; + var drawCalls = geometry.drawCalls; + // lets set the transfomr + uniforms.translationMatrix = this.transform.worldTransform; + // and then lets set the tint.. + uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha; + uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha; + uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha; + uniforms.tint[3] = worldAlpha; + // the first draw call, we can set the uniforms of the shader directly here. + // this means that we can tack advantage of the sync function of pixi! + // bind and sync uniforms.. + // there is a way to optimise this.. + renderer.shader.bind(shader); + renderer.geometry.bind(geometry, shader); + // set state.. + renderer.state.set(this.state); + // then render the rest of them... + for (var i = 0, l = drawCalls.length; i < l; i++) { + this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); + } + }; + /** + * Renders specific DrawCall + * @param renderer + * @param drawCall + */ + Graphics.prototype._renderDrawCallDirect = function (renderer, drawCall) { + var texArray = drawCall.texArray, type = drawCall.type, size = drawCall.size, start = drawCall.start; + var groupTextureCount = texArray.count; + for (var j = 0; j < groupTextureCount; j++) { + renderer.texture.bind(texArray.elements[j], j); + } + renderer.geometry.draw(type, size, start); + }; + /** + * Resolves shader for direct rendering + * @param renderer - The renderer + */ + Graphics.prototype._resolveDirectShader = function (renderer) { + var shader = this.shader; + var pluginName = this.pluginName; + if (!shader) { + // if there is no shader here, we can use the default shader. + // and that only gets created if we actually need it.. + // but may be more than one plugins for graphics + if (!DEFAULT_SHADERS[pluginName]) { + var MAX_TEXTURES = renderer.plugins[pluginName].MAX_TEXTURES; + var sampleValues = new Int32Array(MAX_TEXTURES); + for (var i = 0; i < MAX_TEXTURES; i++) { + sampleValues[i] = i; + } + var uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new Matrix(), + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; + var program = renderer.plugins[pluginName]._shader.program; + DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms); + } + shader = DEFAULT_SHADERS[pluginName]; + } + return shader; + }; + /** Retrieves the bounds of the graphic shape as a rectangle object. */ + Graphics.prototype._calculateBounds = function () { + this.finishPoly(); + var geometry = this._geometry; + // skipping when graphics is empty, like a container + if (!geometry.graphicsData.length) { + return; + } + var _a = geometry.bounds, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY; + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + /** + * Tests if a point is inside this graphics object + * @param point - the point to test + * @returns - the result of the test + */ + Graphics.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, Graphics._TEMP_POINT); + return this._geometry.containsPoint(Graphics._TEMP_POINT); + }; + /** Recalculate the tint by applying tint to batches using Graphics tint. */ + Graphics.prototype.calculateTints = function () { + if (this.batchTint !== this.tint) { + this.batchTint = this.tint; + var tintRGB = hex2rgb(this.tint, temp); + for (var i = 0; i < this.batches.length; i++) { + var batch = this.batches[i]; + var batchTint = batch._batchRGB; + var r = (tintRGB[0] * batchTint[0]) * 255; + var g = (tintRGB[1] * batchTint[1]) * 255; + var b = (tintRGB[2] * batchTint[2]) * 255; + // TODO Ivan, can this be done in one go? + var color = (r << 16) + (g << 8) + (b | 0); + batch._tintRGB = (color >> 16) + + (color & 0xff00) + + ((color & 0xff) << 16); + } + } + }; + /** If there's a transform update or a change to the shape of the geometry, recalculate the vertices. */ + Graphics.prototype.calculateVertices = function () { + var wtID = this.transform._worldID; + if (this._transformID === wtID) { + return; + } + this._transformID = wtID; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var data = this._geometry.points; // batch.vertexDataOriginal; + var vertexData = this.vertexData; + var count = 0; + for (var i = 0; i < data.length; i += 2) { + var x = data[i]; + var y = data[i + 1]; + vertexData[count++] = (a * x) + (c * y) + tx; + vertexData[count++] = (d * y) + (b * x) + ty; + } + }; + /** + * Closes the current path. + * @returns - Returns itself. + */ + Graphics.prototype.closePath = function () { + var currentPath = this.currentPath; + if (currentPath) { + // we don't need to add extra point in the end because buildLine will take care of that + currentPath.closeStroke = true; + // ensure that the polygon is completed, and is available for hit detection + // (even if the graphics is not rendered yet) + this.finishPoly(); + } + return this; + }; + /** + * Apply a matrix to the positional data. + * @param matrix - Matrix to use for transform current shape. + * @returns - Returns itself. + */ + Graphics.prototype.setMatrix = function (matrix) { + this._matrix = matrix; + return this; + }; + /** + * Begin adding holes to the last draw shape + * IMPORTANT: holes must be fully inside a shape to work + * Also weirdness ensues if holes overlap! + * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer, + * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle. + * @returns - Returns itself. + */ + Graphics.prototype.beginHole = function () { + this.finishPoly(); + this._holeMode = true; + return this; + }; + /** + * End adding holes to the last draw shape. + * @returns - Returns itself. + */ + Graphics.prototype.endHole = function () { + this.finishPoly(); + this._holeMode = false; + return this; + }; + /** + * Destroys the Graphics object. + * @param options - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Graphics.prototype.destroy = function (options) { + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + this._matrix = null; + this.currentPath = null; + this._lineStyle.destroy(); + this._lineStyle = null; + this._fillStyle.destroy(); + this._fillStyle = null; + this._geometry = null; + this.shader = null; + this.vertexData = null; + this.batches.length = 0; + this.batches = null; + _super.prototype.destroy.call(this, options); + }; + /** + * New rendering behavior for rounded rectangles: circular arcs instead of quadratic bezier curves. + * In the next major release, we'll enable this by default. + */ + Graphics.nextRoundedRectBehavior = false; + /** + * Temporary point to use for containsPoint. + * @private + */ + Graphics._TEMP_POINT = new Point(); + return Graphics; + }(Container)); + + var graphicsUtils = { + buildPoly: buildPoly, + buildCircle: buildCircle, + buildRectangle: buildRectangle, + buildRoundedRectangle: buildRoundedRectangle, + buildLine: buildLine, + ArcUtils: ArcUtils, + BezierUtils: BezierUtils, + QuadraticUtils: QuadraticUtils, + BatchPart: BatchPart, + FILL_COMMANDS: FILL_COMMANDS, + BATCH_POOL: BATCH_POOL, + DRAW_CALL_POOL: DRAW_CALL_POOL + }; + + /*! + * @pixi/sprite - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/sprite is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$d = function(d, b) { + extendStatics$d = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$d(d, b); + }; + + function __extends$d(d, b) { + extendStatics$d(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var tempPoint$2 = new Point(); + var indices = new Uint16Array([0, 1, 2, 0, 2, 3]); + /** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = PIXI.Sprite.from('assets/image.png'); + * ``` + * + * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}, + * as swapping base textures when rendering to the screen is inefficient. + * + * ```js + * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; + * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); + * ... + * } + * ``` + * @memberof PIXI + */ + var Sprite = /** @class */ (function (_super) { + __extends$d(Sprite, _super); + /** @param texture - The texture for this sprite. */ + function Sprite(texture) { + var _this = _super.call(this) || this; + _this._anchor = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0)); + _this._texture = null; + _this._width = 0; + _this._height = 0; + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + _this.blendMode = exports.BLEND_MODES.NORMAL; + _this._cachedTint = 0xFFFFFF; + _this.uvs = null; + // call texture setter + _this.texture = texture || Texture.EMPTY; + _this.vertexData = new Float32Array(8); + _this.vertexTrimmedData = null; + _this._transformID = -1; + _this._textureID = -1; + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + // Batchable stuff.. + // TODO could make this a mixin? + _this.indices = indices; + _this.pluginName = 'batch'; + /** + * Used to fast check if a sprite is.. a sprite! + * @member {boolean} + */ + _this.isSprite = true; + _this._roundPixels = settings$1.ROUND_PIXELS; + return _this; + } + /** When the texture is updated, this event will fire to update the scale and frame. */ + Sprite.prototype._onTextureUpdate = function () { + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 0xFFFFFF; + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width; + } + if (this._height) { + this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height; + } + }; + /** Called when the anchor position updates. */ + Sprite.prototype._onAnchorUpdate = function () { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + /** Calculates worldTransform * vertices, store it in vertexData. */ + Sprite.prototype.calculateVertices = function () { + var texture = this._texture; + if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) { + return; + } + // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` + if (this._textureID !== texture._updateID) { + this.uvs = this._texture._uvs.uvsFloat32; + } + this._transformID = this.transform._worldID; + this._textureID = texture._updateID; + // set the vertex data + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - (anchor._x * orig.width); + w0 = w1 + trim.width; + h1 = trim.y - (anchor._y * orig.height); + h0 = h1 + trim.height; + } + else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + // xy + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + // xy + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + // xy + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + // xy + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + if (this._roundPixels) { + var resolution = settings$1.RESOLUTION; + for (var i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); + } + } + }; + /** + * Calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData. + * + * This is used to ensure that the true width and height of a trimmed texture is respected. + */ + Sprite.prototype.calculateTrimmedVertices = function () { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } + else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + // xy + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + // xy + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + // xy + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + // xy + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + }; + /** + * + * Renders the object using the WebGL renderer + * @param renderer - The webgl renderer to use. + */ + Sprite.prototype._render = function (renderer) { + this.calculateVertices(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + /** Updates the bounds of the sprite. */ + Sprite.prototype._calculateBounds = function () { + var trim = this._texture.trim; + var orig = this._texture.orig; + // First lets check to see if the current texture has a trim.. + if (!trim || (trim.width === orig.width && trim.height === orig.height)) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } + else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + /** + * Gets the local bounds of the sprite object. + * @param rect - Optional output rectangle. + * @returns The bounds. + */ + Sprite.prototype.getLocalBounds = function (rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + this._localBounds.minX = this._texture.orig.width * -this._anchor._x; + this._localBounds.minY = this._texture.orig.height * -this._anchor._y; + this._localBounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._localBounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + return this._localBounds.getRectangle(rect); + } + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** + * Tests if a point is inside this sprite + * @param point - the point to test + * @returns The result of the test + */ + Sprite.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, tempPoint$2); + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + if (tempPoint$2.x >= x1 && tempPoint$2.x < x1 + width) { + y1 = -height * this.anchor.y; + if (tempPoint$2.y >= y1 && tempPoint$2.y < y1 + height) { + return true; + } + } + return false; + }; + /** + * Destroys this sprite and optionally its texture and children. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + Sprite.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this._texture.off('update', this._onTextureUpdate, this); + this._anchor = null; + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + this._texture.destroy(!!destroyBaseTexture); + } + this._texture = null; + }; + // some helper functions.. + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options. + * @returns The newly created sprite + */ + Sprite.from = function (source, options) { + var texture = (source instanceof Texture) + ? source + : Texture.from(source, options); + return new Sprite(texture); + }; + Object.defineProperty(Sprite.prototype, "roundPixels", { + get: function () { + return this._roundPixels; + }, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}. + * @default false + */ + set: function (value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "width", { + /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function (value) { + var s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "height", { + /** The height of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) { + var s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "anchor", { + /** + * The anchor sets the origin point of the sprite. The default value is taken from the {@link PIXI.Texture|Texture} + * and passed to the constructor. + * + * The default is `(0,0)`, this means the sprite's origin is the top left. + * + * Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered. + * + * Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner. + * + * If you pass only single parameter, it will set both x and y to the same value as shown in the example below. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5). + */ + get: function () { + return this._anchor; + }, + set: function (value) { + this._anchor.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "tint", { + /** + * The tint applied to the sprite. This is a hex value. + * + * A value of 0xFFFFFF will remove any tint effect. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "texture", { + /** The texture that the sprite is using. */ + get: function () { + return this._texture; + }, + set: function (value) { + if (this._texture === value) { + return; + } + if (this._texture) { + this._texture.off('update', this._onTextureUpdate, this); + } + this._texture = value || Texture.EMPTY; + this._cachedTint = 0xFFFFFF; + this._textureID = -1; + this._textureTrimmedID = -1; + if (value) { + // wait for the texture to load + if (value.baseTexture.valid) { + this._onTextureUpdate(); + } + else { + value.once('update', this._onTextureUpdate, this); + } + } + }, + enumerable: false, + configurable: true + }); + return Sprite; + }(Container)); + + /*! + * @pixi/text - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/text is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$c = function(d, b) { + extendStatics$c = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$c(d, b); + }; + + function __extends$c(d, b) { + extendStatics$c(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * Constants that define the type of gradient on text. + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ + exports.TEXT_GRADIENT = void 0; + (function (TEXT_GRADIENT) { + TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL"; + TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL"; + })(exports.TEXT_GRADIENT || (exports.TEXT_GRADIENT = {})); + + // disabling eslint for now, going to rewrite this in v5 + var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: exports.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + whiteSpace: 'pre', + wordWrap: false, + wordWrapWidth: 100, + leading: 0, + }; + var genericFontFamilies = [ + 'serif', + 'sans-serif', + 'monospace', + 'cursive', + 'fantasy', + 'system-ui' ]; + /** + * A TextStyle Object contains information to decorate a Text objects. + * + * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it. + * + * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style). + * + * @memberof PIXI + */ + var TextStyle = /** @class */ (function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', '800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {string} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" + * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + this.styleID = 0; + this.reset(); + deepCopyProperties(this, style, style); + } + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return New cloned TextStyle object + */ + TextStyle.prototype.clone = function () { + var clonedProperties = {}; + deepCopyProperties(clonedProperties, this, defaultStyle); + return new TextStyle(clonedProperties); + }; + /** Resets all properties to the defaults specified in TextStyle.prototype._default */ + TextStyle.prototype.reset = function () { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + Object.defineProperty(TextStyle.prototype, "align", { + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + get: function () { + return this._align; + }, + set: function (align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "breakWords", { + /** Indicates if lines can be wrapped within words, it needs wordWrap to be set to true. */ + get: function () { + return this._breakWords; + }, + set: function (breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadow", { + /** Set a drop shadow for the text. */ + get: function () { + return this._dropShadow; + }, + set: function (dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowAlpha", { + /** Set alpha for the drop shadow. */ + get: function () { + return this._dropShadowAlpha; + }, + set: function (dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowAngle", { + /** Set a angle of the drop shadow. */ + get: function () { + return this._dropShadowAngle; + }, + set: function (dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowBlur", { + /** Set a shadow blur radius. */ + get: function () { + return this._dropShadowBlur; + }, + set: function (dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowColor", { + /** A fill style to be used on the dropshadow e.g 'red', '#00FF00'. */ + get: function () { + return this._dropShadowColor; + }, + set: function (dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowDistance", { + /** Set a distance of the drop shadow. */ + get: function () { + return this._dropShadowDistance; + }, + set: function (dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fill", { + /** + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + get: function () { + return this._fill; + }, + set: function (fill) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + // TODO: Not sure if getColor works properly with CanvasGradient and/or CanvasPattern, can't pass in + // without casting here. + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fillGradientType", { + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * + * @see PIXI.TEXT_GRADIENT + */ + get: function () { + return this._fillGradientType; + }, + set: function (fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fillGradientStops", { + /** + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + */ + get: function () { + return this._fillGradientStops; + }, + set: function (fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontFamily", { + /** The font family. */ + get: function () { + return this._fontFamily; + }, + set: function (fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontSize", { + /** + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + */ + get: function () { + return this._fontSize; + }, + set: function (fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontStyle", { + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + get: function () { + return this._fontStyle; + }, + set: function (fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontVariant", { + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + get: function () { + return this._fontVariant; + }, + set: function (fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontWeight", { + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + get: function () { + return this._fontWeight; + }, + set: function (fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "letterSpacing", { + /** The amount of spacing between letters, default is 0. */ + get: function () { + return this._letterSpacing; + }, + set: function (letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "lineHeight", { + /** The line height, a number that represents the vertical space that a letter uses. */ + get: function () { + return this._lineHeight; + }, + set: function (lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "leading", { + /** The space between lines. */ + get: function () { + return this._leading; + }, + set: function (leading) { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "lineJoin", { + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + get: function () { + return this._lineJoin; + }, + set: function (lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "miterLimit", { + /** + * The miter limit to use when using the 'miter' lineJoin mode. + * + * This can reduce or increase the spikiness of rendered text. + */ + get: function () { + return this._miterLimit; + }, + set: function (miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "padding", { + /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + */ + get: function () { + return this._padding; + }, + set: function (padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "stroke", { + /** + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + */ + get: function () { + return this._stroke; + }, + set: function (stroke) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "strokeThickness", { + /** + * A number that represents the thickness of the stroke. + * + * @default 0 + */ + get: function () { + return this._strokeThickness; + }, + set: function (strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "textBaseline", { + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + get: function () { + return this._textBaseline; + }, + set: function (textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "trim", { + /** Trim transparent borders. */ + get: function () { + return this._trim; + }, + set: function (trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "whiteSpace", { + /** + * How newlines and spaces should be handled. + * Default is 'pre' (preserve, preserve). + * + * value | New lines | Spaces + * --- | --- | --- + * 'normal' | Collapse | Collapse + * 'pre' | Preserve | Preserve + * 'pre-line' | Preserve | Collapse + * + * @member {string} + */ + get: function () { + return this._whiteSpace; + }, + set: function (whiteSpace) { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "wordWrap", { + /** Indicates if word wrap should be used. */ + get: function () { + return this._wordWrap; + }, + set: function (wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "wordWrapWidth", { + /** The width at which text will wrap, it needs wordWrap to be set to true. */ + get: function () { + return this._wordWrapWidth; + }, + set: function (wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function () { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = (typeof this.fontSize === 'number') ? this.fontSize + "px" : this.fontSize; + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + // Check if font already contains strings + if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { + fontFamily = "\"" + fontFamily + "\""; + } + fontFamilies[i] = fontFamily; + } + return this.fontStyle + " " + this.fontVariant + " " + this.fontWeight + " " + fontSizeString + " " + fontFamilies.join(','); + }; + return TextStyle; + }()); + /** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * @private + * @param color + * @return The color as a string. + */ + function getSingleColor(color) { + if (typeof color === 'number') { + return hex2string(color); + } + else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + return color; + } + function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } + else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + return color; + } + } + /** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param array1 - First array to compare + * @param array2 - Second array to compare + * @return Do the arrays contain the same values in the same order + */ + function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; + } + /** + * Utility function to ensure that object properties are copied by value, and not by reference + * @private + * @param target - Target object to copy properties into + * @param source - Source object for the properties to copy + * @param propertyObj - Object containing properties names we want to loop over + */ + function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } + else { + target[prop] = source[prop]; + } + } + } + + /** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * ```js + * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) + * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) + * ``` + * @memberof PIXI + */ + var TextMetrics = /** @class */ (function () { + /** + * @param text - the text that was measured + * @param style - the style that was measured + * @param width - the measured width of the text + * @param height - the measured height of the text + * @param lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param lineWidths - an array of the line widths for each line matched to `lines` + * @param lineHeight - the measured line height for this style + * @param maxLineWidth - the maximum line width for all measured lines + * @param {PIXI.IFontMetrics} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + /** + * Measures the supplied string of text and returns a Rectangle. + * @param text - The text to measure. + * @param style - The text style to use for measuring + * @param wordWrap - Override for if word-wrap should be applied to the text. + * @param canvas - optional specification of the canvas to use for measuring. + * @returns Measured width and height of the text. + */ + TextMetrics.measureText = function (text, style, wordWrap, canvas) { + if (canvas === void 0) { canvas = TextMetrics._canvas; } + wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + // fallback in case UA disallow canvas data extraction + // (toDataURI, getImageData functions) + if (fontProperties.fontSize === 0) { + fontProperties.fontSize = style.fontSize; + fontProperties.ascent = style.fontSize; + } + var context = canvas.getContext('2d'); + context.font = font; + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + if (style.dropShadow) { + width += style.dropShadowDistance; + } + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + + ((lines.length - 1) * (lineHeight + style.leading)); + if (style.dropShadow) { + height += style.dropShadowDistance; + } + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * @param text - String to apply word wrapping to + * @param style - the style to use when wrapping + * @param canvas - optional specification of the canvas to use for measuring. + * @returns New string with new lines applied where required + */ + TextMetrics.wordWrap = function (text, style, canvas) { + if (canvas === void 0) { canvas = TextMetrics._canvas; } + var context = canvas.getContext('2d'); + var width = 0; + var line = ''; + var lines = ''; + var cache = Object.create(null); + var letterSpacing = style.letterSpacing, whiteSpace = style.whiteSpace; + // How to handle whitespaces + var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); + var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); + // whether or not spaces may be added to the beginning of lines + var canPrependSpaces = !collapseSpaces; + // There is letterSpacing after every char except the last one + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! + // so for convenience the above needs to be compared to width + 1 extra letterSpace + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ + // ________________________________________________ + // And then the final space is simply no appended to each line + var wordWrapWidth = style.wordWrapWidth + letterSpacing; + // break text into words, spaces and newline chars + var tokens = TextMetrics.tokenize(text); + for (var i = 0; i < tokens.length; i++) { + // get the word, space or newlineChar + var token = tokens[i]; + // if word is a new line + if (TextMetrics.isNewline(token)) { + // keep the new line + if (!collapseNewlines) { + lines += TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ''; + width = 0; + continue; + } + // if we should collapse new lines + // we simply convert it into a space + token = ' '; + } + // if we should collapse repeated whitespaces + if (collapseSpaces) { + // check both this and the last tokens for spaces + var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); + var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + // get word width from cache if possible + var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); + // word is longer than desired bounds + if (tokenWidth > wordWrapWidth) { + // if we are not already at the beginning of a line + if (line !== '') { + // start newlines for overflow words + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + // break large word over multiple lines + if (TextMetrics.canBreakWords(token, style.breakWords)) { + // break word into characters + var characters = TextMetrics.wordWrapSplit(token); + // loop the characters + for (var j = 0; j < characters.length; j++) { + var char = characters[j]; + var k = 1; + // we are not at the end of the token + while (characters[j + k]) { + var nextChar = characters[j + k]; + var lastChar = char[char.length - 1]; + // should not split chars + if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + // combine chars & move forward one + char += nextChar; + } + else { + break; + } + k++; + } + j += char.length - 1; + var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); + if (characterWidth + width > wordWrapWidth) { + lines += TextMetrics.addLine(line); + canPrependSpaces = false; + line = ''; + width = 0; + } + line += char; + width += characterWidth; + } + } + // run word out of the bounds + else { + // if there are words in this line already + // finish that line and start a new one + if (line.length > 0) { + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + var isLastToken = i === tokens.length - 1; + // give it its own line if it's not the end + lines += TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ''; + width = 0; + } + } + // word could fit + else { + // word won't fit because of existing words + // start a new line + if (tokenWidth + width > wordWrapWidth) { + // if its a space we don't want it + canPrependSpaces = false; + // add a new line + lines += TextMetrics.addLine(line); + // start a new line + line = ''; + width = 0; + } + // don't add spaces to the beginning of lines + if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + // add the word to the current line + line += token; + // update width counter + width += tokenWidth; + } + } + } + lines += TextMetrics.addLine(line, false); + return lines; + }; + /** + * Convienience function for logging each line added during the wordWrap method. + * @param line - The line of text to add + * @param newLine - Add new line character to end + * @returns A formatted line + */ + TextMetrics.addLine = function (line, newLine) { + if (newLine === void 0) { newLine = true; } + line = TextMetrics.trimRight(line); + line = (newLine) ? line + "\n" : line; + return line; + }; + /** + * Gets & sets the widths of calculated characters in a cache object + * @param key - The key + * @param letterSpacing - The letter spacing + * @param cache - The cache + * @param context - The canvas context + * @returns The from cache. + */ + TextMetrics.getFromCache = function (key, letterSpacing, cache, context) { + var width = cache[key]; + if (typeof width !== 'number') { + var spacing = ((key.length) * letterSpacing); + width = context.measureText(key).width + spacing; + cache[key] = width; + } + return width; + }; + /** + * Determines whether we should collapse breaking spaces. + * @param whiteSpace - The TextStyle property whiteSpace + * @returns Should collapse + */ + TextMetrics.collapseSpaces = function (whiteSpace) { + return (whiteSpace === 'normal' || whiteSpace === 'pre-line'); + }; + /** + * Determines whether we should collapse newLine chars. + * @param whiteSpace - The white space + * @returns should collapse + */ + TextMetrics.collapseNewlines = function (whiteSpace) { + return (whiteSpace === 'normal'); + }; + /** + * Trims breaking whitespaces from string. + * @param text - The text + * @returns Trimmed string + */ + TextMetrics.trimRight = function (text) { + if (typeof text !== 'string') { + return ''; + } + for (var i = text.length - 1; i >= 0; i--) { + var char = text[i]; + if (!TextMetrics.isBreakingSpace(char)) { + break; + } + text = text.slice(0, -1); + } + return text; + }; + /** + * Determines if char is a newline. + * @param char - The character + * @returns True if newline, False otherwise. + */ + TextMetrics.isNewline = function (char) { + if (typeof char !== 'string') { + return false; + } + return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0); + }; + /** + * Determines if char is a breaking whitespace. + * + * It allows one to determine whether char should be a breaking whitespace + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * @param char - The character + * @param [_nextChar] - The next character + * @returns True if whitespace, False otherwise. + */ + TextMetrics.isBreakingSpace = function (char, _nextChar) { + if (typeof char !== 'string') { + return false; + } + return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0); + }; + /** + * Splits a string into words, breaking-spaces and newLine characters + * @param text - The text + * @returns A tokenized array + */ + TextMetrics.tokenize = function (text) { + var tokens = []; + var token = ''; + if (typeof text !== 'string') { + return tokens; + } + for (var i = 0; i < text.length; i++) { + var char = text[i]; + var nextChar = text[i + 1]; + if (TextMetrics.isBreakingSpace(char, nextChar) || TextMetrics.isNewline(char)) { + if (token !== '') { + tokens.push(token); + token = ''; + } + tokens.push(char); + continue; + } + token += char; + } + if (token !== '') { + tokens.push(token); + } + return tokens; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It allows one to customise which words should break + * Examples are if the token is CJK or numbers. + * It must return a boolean. + * @param _token - The token + * @param breakWords - The style attr break words + * @returns Whether to break word or not + */ + TextMetrics.canBreakWords = function (_token, breakWords) { + return breakWords; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It allows one to determine whether a pair of characters + * should be broken by newlines + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * @param _char - The character + * @param _nextChar - The next character + * @param _token - The token/word the characters are from + * @param _index - The index in the token of the char + * @param _breakWords - The style attr break words + * @returns whether to break word or not + */ + TextMetrics.canBreakChars = function (_char, _nextChar, _token, _index, _breakWords) { + return true; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It is called when a token (usually a word) has to be split into separate pieces + * in order to determine the point to break a word. + * It must return an array of characters. + * @example + * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji. + * TextMetrics.wordWrapSplit = (token) => [...token]; + * @param token - The token to split + * @returns The characters of the token + */ + TextMetrics.wordWrapSplit = function (token) { + return token.split(''); + }; + /** + * Calculates the ascent, descent and fontSize of a given font-style + * @param font - String representing the style of the font + * @returns Font properties object + */ + TextMetrics.measureFont = function (font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + var properties = { + ascent: 0, + descent: 0, + fontSize: 0, + }; + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + context.font = font; + var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; + var width = Math.ceil(context.measureText(metricsString).width); + var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); + var height = Math.ceil(TextMetrics.HEIGHT_MULTIPLIER * baseline); + baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; + canvas.width = width; + canvas.height = height; + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + context.font = font; + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(metricsString, 0, baseline); + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + var i = 0; + var idx = 0; + var stop = false; + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } + else { + break; + } + } + properties.ascent = baseline - i; + idx = pixels - line; + stop = false; + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx -= line; + } + else { + break; + } + } + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + TextMetrics._fonts[font] = properties; + return properties; + }; + /** + * Clear font metrics in metrics cache. + * @param {string} [font] - font name. If font name not set then clear cache for all fonts. + */ + TextMetrics.clearMetrics = function (font) { + if (font === void 0) { font = ''; } + if (font) { + delete TextMetrics._fonts[font]; + } + else { + TextMetrics._fonts = {}; + } + }; + Object.defineProperty(TextMetrics, "_canvas", { + /** + * Cached canvas element for measuring text + * TODO: this should be private, but isn't because of backward compat, will fix later. + * @ignore + */ + get: function () { + if (!TextMetrics.__canvas) { + var canvas = void 0; + try { + // OffscreenCanvas2D measureText can be up to 40% faster. + var c = new OffscreenCanvas(0, 0); + var context = c.getContext('2d'); + if (context && context.measureText) { + TextMetrics.__canvas = c; + return c; + } + canvas = settings$1.ADAPTER.createCanvas(); + } + catch (ex) { + canvas = settings$1.ADAPTER.createCanvas(); + } + canvas.width = canvas.height = 10; + TextMetrics.__canvas = canvas; + } + return TextMetrics.__canvas; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextMetrics, "_context", { + /** + * TODO: this should be private, but isn't because of backward compat, will fix later. + * @ignore + */ + get: function () { + if (!TextMetrics.__context) { + TextMetrics.__context = TextMetrics._canvas.getContext('2d'); + } + return TextMetrics.__context; + }, + enumerable: false, + configurable: true + }); + return TextMetrics; + }()); + /** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @typedef {object} FontMetrics + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + * @memberof PIXI.TextMetrics + * @private + */ + /** + * Cache of {@see PIXI.TextMetrics.FontMetrics} objects. + * @memberof PIXI.TextMetrics + * @type {object} + * @private + */ + TextMetrics._fonts = {}; + /** + * String used for calculate font metrics. + * These characters are all tall to help calculate the height required for text. + * @static + * @memberof PIXI.TextMetrics + * @name METRICS_STRING + * @type {string} + * @default |ÉqÅ + */ + TextMetrics.METRICS_STRING = '|ÉqÅ'; + /** + * Baseline symbol for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_SYMBOL + * @type {string} + * @default M + */ + TextMetrics.BASELINE_SYMBOL = 'M'; + /** + * Baseline multiplier for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_MULTIPLIER + * @type {number} + * @default 1.4 + */ + TextMetrics.BASELINE_MULTIPLIER = 1.4; + /** + * Height multiplier for setting height of canvas to calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name HEIGHT_MULTIPLIER + * @type {number} + * @default 2.00 + */ + TextMetrics.HEIGHT_MULTIPLIER = 2.0; + /** + * Cache of new line chars. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ + TextMetrics._newlines = [ + 0x000A, + 0x000D ]; + /** + * Cache of breaking spaces. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ + TextMetrics._breakingSpaces = [ + 0x0009, + 0x0020, + 0x2000, + 0x2001, + 0x2002, + 0x2003, + 0x2004, + 0x2005, + 0x2006, + 0x2008, + 0x2009, + 0x200A, + 0x205F, + 0x3000 ]; + /** + * A number, or a string containing a number. + * @memberof PIXI + * @typedef {object} IFontMetrics + * @property {number} ascent - Font ascent + * @property {number} descent - Font descent + * @property {number} fontSize - Font size + */ + + var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true, + }; + /** + * A Text Object will create a line or multiple lines of text. + * + * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). + * + * The primary advantage of this class over BitmapText is that you have great control over the style of the text, + * which you can change at runtime. + * + * The primary disadvantages is that each piece of text has it's own texture, which can use more memory. + * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time. + * + * To split a line you can use '\n' in your text string, or, on the `style` object, + * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value. + * + * A Text can be created directly from a string and a style object, + * which can be generated [here](https://pixijs.io/pixi-text-style). + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * @memberof PIXI + */ + var Text = /** @class */ (function (_super) { + __extends$c(Text, _super); + /** + * @param text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param canvas - The canvas element for drawing text + */ + function Text(text, style, canvas) { + var _this = this; + var ownCanvas = false; + if (!canvas) { + canvas = settings$1.ADAPTER.createCanvas(); + ownCanvas = true; + } + canvas.width = 3; + canvas.height = 3; + var texture = Texture.from(canvas); + texture.orig = new Rectangle(); + texture.trim = new Rectangle(); + _this = _super.call(this, texture) || this; + _this._ownCanvas = ownCanvas; + _this.canvas = canvas; + _this.context = canvas.getContext('2d'); + _this._resolution = settings$1.RESOLUTION; + _this._autoResolution = true; + _this._text = null; + _this._style = null; + _this._styleListener = null; + _this._font = ''; + _this.text = text; + _this.style = style; + _this.localStyleID = -1; + return _this; + } + /** + * Renders text to its canvas, and updates its texture. + * + * By default this is used internally to ensure the texture is correct before rendering, + * but it can be used called externally, for example from this class to 'pre-generate' the texture from a piece of text, + * and then shared across multiple Sprites. + * @param respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + Text.prototype.updateText = function (respectDirty) { + var style = this._style; + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + if (!this.dirty && respectDirty) { + return; + } + this._font = this._style.toFontString(); + var context = this.context; + var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + this.canvas.width = Math.ceil(Math.ceil((Math.max(1, width) + (style.padding * 2))) * this._resolution); + this.canvas.height = Math.ceil(Math.ceil((Math.max(1, height) + (style.padding * 2))) * this._resolution); + context.scale(this._resolution, this._resolution); + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + context.font = this._font; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + var linePositionX; + var linePositionY; + // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text + var passesCount = style.dropShadow ? 2 : 1; + // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex, + // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow. + // + // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more + // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill + // and the stroke; and fill drop shadows would appear over the top of the stroke. + // + // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal + // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the + // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow + // beneath the text, whilst also having the proper text shadow styling. + for (var i = 0; i < passesCount; ++i) { + var isShadowPass = style.dropShadow && i === 0; + // we only want the drop shadow, so put text way off-screen + var dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, height) + (style.padding * 2)) : 0; + var dsOffsetShadow = dsOffsetText * this._resolution; + if (isShadowPass) { + // On Safari, text with gradient and drop shadows together do not position correctly + // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689 + // Therefore we'll set the styles to be a plain black whilst generating this drop shadow + context.fillStyle = 'black'; + context.strokeStyle = 'black'; + var dropShadowColor = style.dropShadowColor; + var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); + var dropShadowBlur = style.dropShadowBlur * this._resolution; + var dropShadowDistance = style.dropShadowDistance * this._resolution; + context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; + context.shadowBlur = dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; + context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * dropShadowDistance) + dsOffsetShadow; + } + else { + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines, measured); + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + context.strokeStyle = style.stroke; + context.shadowColor = 'black'; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + var linePositionYShift = (lineHeight - fontProperties.fontSize) / 2; + if (!Text.nextLineHeightBehavior || lineHeight - fontProperties.fontSize < 0) { + linePositionYShift = 0; + } + // draw lines line by line + for (var i_1 = 0; i_1 < lines.length; i_1++) { + linePositionX = style.strokeThickness / 2; + linePositionY = ((style.strokeThickness / 2) + (i_1 * lineHeight)) + fontProperties.ascent + + linePositionYShift; + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i_1]; + } + else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i_1]) / 2; + } + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true); + } + if (style.fill) { + this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText); + } + } + } + this.updateTexture(); + }; + /** + * Render the text with letter-spacing. + * @param text - The text to draw + * @param x - Horizontal position to draw the text + * @param y - Vertical position to draw the text + * @param isStroke - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + */ + Text.prototype.drawLetterSpacing = function (text, x, y, isStroke) { + if (isStroke === void 0) { isStroke = false; } + var style = this._style; + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + // Checking that we can use moddern canvas2D api + // https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441 + // note: this is unstable API, Chrome less 94 use a `textLetterSpacing`, newest use a letterSpacing + // eslint-disable-next-line max-len + var supportLetterSpacing = Text.experimentalLetterSpacing + && ('letterSpacing' in CanvasRenderingContext2D.prototype + || 'textLetterSpacing' in CanvasRenderingContext2D.prototype); + if (letterSpacing === 0 || supportLetterSpacing) { + if (supportLetterSpacing) { + this.context.letterSpacing = letterSpacing; + this.context.textLetterSpacing = letterSpacing; + } + if (isStroke) { + this.context.strokeText(text, x, y); + } + else { + this.context.fillText(text, x, y); + } + return; + } + var currentPosition = x; + // Using Array.from correctly splits characters whilst keeping emoji together. + // This is not supported on IE as it requires ES6, so regular text splitting occurs. + // This also doesn't account for emoji that are multiple emoji put together to make something else. + // Handling all of this would require a big library itself. + // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 + // https://github.com/orling/grapheme-splitter + var stringArray = Array.from ? Array.from(text) : text.split(''); + var previousWidth = this.context.measureText(text).width; + var currentWidth = 0; + for (var i = 0; i < stringArray.length; ++i) { + var currentChar = stringArray[i]; + if (isStroke) { + this.context.strokeText(currentChar, currentPosition, y); + } + else { + this.context.fillText(currentChar, currentPosition, y); + } + var textStr = ''; + for (var j = i + 1; j < stringArray.length; ++j) { + textStr += stringArray[j]; + } + currentWidth = this.context.measureText(textStr).width; + currentPosition += previousWidth - currentWidth + letterSpacing; + previousWidth = currentWidth; + } + }; + /** Updates texture size based on canvas size. */ + Text.prototype.updateTexture = function () { + var canvas = this.canvas; + if (this._style.trim) { + var trimmed = trimCanvas(canvas); + if (trimmed.data) { + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + } + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + texture.trim.width = texture._frame.width = canvas.width / this._resolution; + texture.trim.height = texture._frame.height = canvas.height / this._resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + texture.orig.width = texture._frame.width - (padding * 2); + texture.orig.height = texture._frame.height - (padding * 2); + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); + texture.updateUvs(); + this.dirty = false; + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + Text.prototype._render = function (renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + this.updateText(true); + _super.prototype._render.call(this, renderer); + }; + /** Updates the transform on all children of this container for rendering. */ + Text.prototype.updateTransform = function () { + this.updateText(true); + _super.prototype.updateTransform.call(this); + }; + Text.prototype.getBounds = function (skipUpdate, rect) { + this.updateText(true); + if (this._textureID === -1) { + // texture was updated: recalculate transforms + skipUpdate = false; + } + return _super.prototype.getBounds.call(this, skipUpdate, rect); + }; + /** + * Gets the local bounds of the text object. + * @param rect - The output rectangle. + * @returns The bounds. + */ + Text.prototype.getLocalBounds = function (rect) { + this.updateText(true); + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** Calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. */ + Text.prototype._calculateBounds = function () { + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * @param style - The style. + * @param lines - The lines of text. + * @param metrics + * @returns The fill style + */ + Text.prototype._generateFillStyle = function (style, lines, metrics) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } + else if (fillStyle.length === 1) { + return fillStyle[0]; + } + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient; + // a dropshadow will enlarge the canvas and result in the gradient being + // generated with the incorrect dimensions + var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; + // should also take padding into account, padding can offset the gradient + var padding = style.padding || 0; + var width = (this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2); + var height = (this.canvas.height / this._resolution) - dropShadowCorrection - (padding * 2); + // make a copy of the style settings, so we can manipulate them later + var fill = fillStyle.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding); + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc + var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + for (var i = 0; i < lines.length; i++) { + var lastLineBottom = (metrics.lineHeight * (i - 1)) + textHeight; + var thisLineTop = metrics.lineHeight * i; + var thisLineGradientStart = thisLineTop; + // Handle case where last & this line overlap + if (i > 0 && lastLineBottom > thisLineTop) { + thisLineGradientStart = (thisLineTop + lastLineBottom) / 2; + } + var thisLineBottom = thisLineTop + textHeight; + var nextLineTop = metrics.lineHeight * (i + 1); + var thisLineGradientEnd = thisLineBottom; + // Handle case where this & next line overlap + if (i + 1 < lines.length && nextLineTop < thisLineBottom) { + thisLineGradientEnd = (thisLineBottom + nextLineTop) / 2; + } + // textHeight, but as a 0-1 size in global gradient stop space + var gradStopLineHeight = (thisLineGradientEnd - thisLineGradientStart) / height; + for (var j = 0; j < fill.length; j++) { + // 0-1 stop point for the current line, multiplied to global space afterwards + var lineStop = 0; + if (typeof fillGradientStops[j] === 'number') { + lineStop = fillGradientStops[j]; + } + else { + lineStop = j / fill.length; + } + var globalStop = Math.min(1, Math.max(0, (thisLineGradientStart / height) + (lineStop * gradStopLineHeight))); + // There's potential for floating point precision issues at the seams between gradient repeats. + globalStop = Number(globalStop.toFixed(5)); + gradient.addColorStop(globalStop, fill[j]); + } + } + } + else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2); + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + var totalIterations = fill.length + 1; + var currentIteration = 1; + for (var i = 0; i < fill.length; i++) { + var stop = void 0; + if (typeof fillGradientStops[i] === 'number') { + stop = fillGradientStops[i]; + } + else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; + }; + /** + * Destroys this text object. + * + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + Text.prototype.destroy = function (options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + options = Object.assign({}, defaultDestroyOptions, options); + _super.prototype.destroy.call(this, options); + // set canvas width and height to 0 to workaround memory leak in Safari < 13 + // https://stackoverflow.com/questions/52532614/total-canvas-memory-use-exceeds-the-maximum-limit-safari-12 + if (this._ownCanvas) { + this.canvas.height = this.canvas.width = 0; + } + // make sure to reset the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + this._style = null; + }; + Object.defineProperty(Text.prototype, "width", { + /** The width of the Text, setting this will actually modify the scale to achieve the value set. */ + get: function () { + this.updateText(true); + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function (value) { + this.updateText(true); + var s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "height", { + /** The height of the Text, setting this will actually modify the scale to achieve the value set. */ + get: function () { + this.updateText(true); + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) { + this.updateText(true); + var s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "style", { + /** + * Set the style of the text. + * + * Set up an event listener to listen for changes on the style object and mark the text as dirty. + */ + get: function () { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the ITextStyle + // since the setter creates the TextStyle. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + return this._style; + }, + set: function (style) { + style = style || {}; + if (style instanceof TextStyle) { + this._style = style; + } + else { + this._style = new TextStyle(style); + } + this.localStyleID = -1; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "text", { + /** Set the copy for the text object. To split a line you can use '\n'. */ + get: function () { + return this._text; + }, + set: function (text) { + text = String(text === null || text === undefined ? '' : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "resolution", { + /** + * The resolution / device pixel ratio of the canvas. + * + * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. + * @default 1 + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + /** + * New behavior for `lineHeight` that's meant to mimic HTML text. A value of `true` will + * make sure the first baseline is offset by the `lineHeight` value if it is greater than `fontSize`. + * A value of `false` will use the legacy behavior and not change the baseline of the first line. + * In the next major release, we'll enable this by default. + */ + Text.nextLineHeightBehavior = false; + /** + * New rendering behavior for letter-spacing which uses Chrome's new native API. This will + * lead to more accurate letter-spacing results because it does not try to manually draw + * each character. However, this Chrome API is experimental and may not serve all cases yet. + */ + Text.experimentalLetterSpacing = false; + return Text; + }(Sprite)); + + /*! + * @pixi/prepare - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/prepare is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Default number of uploads per frame using prepare plugin. + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ + settings$1.UPLOADS_PER_FRAME = 4; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$b = function(d, b) { + extendStatics$b = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$b(d, b); + }; + + function __extends$b(d, b) { + extendStatics$b(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of items per frame. + * @memberof PIXI + */ + var CountLimiter = /** @class */ (function () { + /** + * @param maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + this.maxItemsPerFrame = maxItemsPerFrame; + this.itemsLeft = 0; + } + /** Resets any counting properties to start fresh on a new frame. */ + CountLimiter.prototype.beginFrame = function () { + this.itemsLeft = this.maxItemsPerFrame; + }; + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @returns If the item is allowed to be uploaded. + */ + CountLimiter.prototype.allowedToUpload = function () { + return this.itemsLeft-- > 0; + }; + return CountLimiter; + }()); + + /** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findMultipleBaseTextures(item, queue) { + var result = false; + // Objects with multiple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof Texture) { + var baseTexture = item._textures[i].baseTexture; + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + return result; + } + /** + * Built-in hook to find BaseTextures from Texture. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findBaseTexture(item, queue) { + if (item.baseTexture instanceof BaseTexture) { + var texture = item.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to find textures from objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findTexture(item, queue) { + if (item._texture && item._texture instanceof Texture) { + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to draw PIXI.Text to its texture. + * @private + * @param _helper - Not used by this upload handler + * @param item - Item to check + * @returns If item was uploaded. + */ + function drawText(_helper, item) { + if (item instanceof Text) { + // updating text will return early if it is not dirty + item.updateText(true); + return true; + } + return false; + } + /** + * Built-in hook to calculate a text style for a PIXI.Text object. + * @private + * @param _helper - Not used by this upload handler + * @param item - Item to check + * @returns If item was uploaded. + */ + function calculateTextStyle(_helper, item) { + if (item instanceof TextStyle) { + var font = item.toFontString(); + TextMetrics.measureFont(font); + return true; + } + return false; + } + /** + * Built-in hook to find Text objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns if a PIXI.Text object was found. + */ + function findText(item, queue) { + if (item instanceof Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to find TextStyle objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.TextStyle object was found. + */ + function findTextStyle(item, queue) { + if (item instanceof TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + return true; + } + return false; + } + /** + * The prepare manager provides functionality to upload content to the GPU. + * + * BasePrepare handles basic queuing functionality and is extended by + * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * @example + * // Create a sprite + * const sprite = PIXI.Sprite.from('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * @abstract + * @memberof PIXI + */ + var BasePrepare = /** @class */ (function () { + /** + * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + this.limiter = new CountLimiter(settings$1.UPLOADS_PER_FRAME); + this.renderer = renderer; + this.uploadHookHelper = null; + this.queue = []; + this.addHooks = []; + this.uploadHooks = []; + this.completes = []; + this.ticking = false; + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + /** @ignore */ + BasePrepare.prototype.upload = function (item, done) { + var _this = this; + if (typeof item === 'function') { + done = item; + item = null; + } + if (done) { + deprecation$1('6.5.0', 'BasePrepare.upload callback is deprecated, use the return Promise instead.'); + } + return new Promise(function (resolve) { + // If a display object, search for items + // that we could upload + if (item) { + _this.add(item); + } + // TODO: remove done callback and just use resolve + var complete = function () { + done === null || done === void 0 ? void 0 : done(); + resolve(); + }; + // Get the items for upload from the display + if (_this.queue.length) { + _this.completes.push(complete); + if (!_this.ticking) { + _this.ticking = true; + Ticker.system.addOnce(_this.tick, _this, exports.UPDATE_PRIORITY.UTILITY); + } + } + else { + complete(); + } + }); + }; + /** + * Handle tick update + * @private + */ + BasePrepare.prototype.tick = function () { + setTimeout(this.delayedTick, 0); + }; + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * @private + */ + BasePrepare.prototype.prepareItems = function () { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + if (!uploaded) { + this.queue.shift(); + } + } + // We're finished + if (!this.queue.length) { + this.ticking = false; + var completes = this.completes.slice(0); + this.completes.length = 0; + for (var i = 0, len = completes.length; i < len; i++) { + completes[i](); + } + } + else { + // if we are not finished, on the next rAF do this again + Ticker.system.addOnce(this.tick, this, exports.UPDATE_PRIORITY.UTILITY); + } + }; + /** + * Adds hooks for finding items. + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.registerFindHook = function (addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + return this; + }; + /** + * Adds hooks for uploading items. + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.registerUploadHook = function (uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + return this; + }; + /** + * Manually add an item to the uploading queue. + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.add = function (item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + // Get children recursively + if (item instanceof Container) { + for (var i = item.children.length - 1; i >= 0; i--) { + this.add(item.children[i]); + } + } + return this; + }; + /** Destroys the plugin, don't use after this. */ + BasePrepare.prototype.destroy = function () { + if (this.ticking) { + Ticker.system.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + return BasePrepare; + }()); + + /** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * @private + * @param renderer - instance of the webgl renderer + * @param item - Item to check + * @returns If item was uploaded. + */ + function uploadBaseTextures(renderer, item) { + if (item instanceof BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.texture.bind(item); + } + return true; + } + return false; + } + /** + * Built-in hook to upload PIXI.Graphics to the GPU. + * @private + * @param renderer - instance of the webgl renderer + * @param item - Item to check + * @returns If item was uploaded. + */ + function uploadGraphics(renderer, item) { + if (!(item instanceof Graphics)) { + return false; + } + var geometry = item.geometry; + // update dirty graphics to get batches + item.finishPoly(); + geometry.updateBatches(); + var batches = geometry.batches; + // upload all textures found in styles + for (var i = 0; i < batches.length; i++) { + var texture = batches[i].style.texture; + if (texture) { + uploadBaseTextures(renderer, texture.baseTexture); + } + } + // if its not batchable - update vao for particular shader + if (!geometry.batchable) { + renderer.geometry.bind(geometry, item._resolveDirectShader(renderer)); + } + return true; + } + /** + * Built-in hook to find graphics. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns if a PIXI.Graphics object was found. + */ + function findGraphics(item, queue) { + if (item instanceof Graphics) { + queue.push(item); + return true; + } + return false; + } + /** + * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for + * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed. + * + * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. + * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. + * @example + * // Create a new application + * const app = new PIXI.Application(); + * document.body.appendChild(app.view); + * + * // Don't start rendering right away + * app.stop(); + * + * // create a display object + * const rect = new PIXI.Graphics() + * .beginFill(0x00ff00) + * .drawRect(40, 40, 200, 200); + * + * // Add to the stage + * app.stage.addChild(rect); + * + * // Don't start rendering until the graphic is uploaded to the GPU + * app.renderer.plugins.prepare.upload(app.stage, () => { + * app.start(); + * }); + * @memberof PIXI + */ + var Prepare = /** @class */ (function (_super) { + __extends$b(Prepare, _super); + /** + * @param {PIXI.Renderer} renderer - A reference to the current renderer + */ + function Prepare(renderer) { + var _this = _super.call(this, renderer) || this; + _this.uploadHookHelper = _this.renderer; + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + /** @ignore */ + Prepare.extension = { + name: 'prepare', + type: exports.ExtensionType.RendererPlugin, + }; + return Prepare; + }(BasePrepare)); + + /** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * @memberof PIXI + */ + var TimeLimiter = /** @class */ (function () { + /** @param maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. */ + function TimeLimiter(maxMilliseconds) { + this.maxMilliseconds = maxMilliseconds; + this.frameStart = 0; + } + /** Resets any counting properties to start fresh on a new frame. */ + TimeLimiter.prototype.beginFrame = function () { + this.frameStart = Date.now(); + }; + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @returns - If the item is allowed to be uploaded. + */ + TimeLimiter.prototype.allowedToUpload = function () { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + return TimeLimiter; + }()); + + /*! + * @pixi/spritesheet - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/spritesheet is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader: + * + * ```js + * PIXI.Loader.shared.add("images/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet; + * ... + * } + * ``` + * + * Alternately, you may circumvent the loader by instantiating the Spritesheet directly: + * ```js + * const sheet = new PIXI.Spritesheet(texture, spritesheetData); + * await sheet.parse(); + * console.log('Spritesheet ready to use!'); + * ``` + * + * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. + * + * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, + * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. + * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only + * supported by TexturePacker. + * @memberof PIXI + */ + var Spritesheet = /** @class */ (function () { + /** + * @param texture - Reference to the source BaseTexture object. + * @param {object} data - Spritesheet image data. + * @param resolutionFilename - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + function Spritesheet(texture, data, resolutionFilename) { + if (resolutionFilename === void 0) { resolutionFilename = null; } + /** For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on. */ + this.linkedSheets = []; + this._texture = texture instanceof Texture ? texture : null; + this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture; + this.textures = {}; + this.animations = {}; + this.data = data; + var resource = this.baseTexture.resource; + this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null)); + this._frames = this.data.frames; + this._frameKeys = Object.keys(this._frames); + this._batchIndex = 0; + this._callback = null; + } + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * @param resolutionFilename - The filename to use for resolving + * the default resolution. + * @returns Resolution to use for spritesheet. + */ + Spritesheet.prototype._updateResolution = function (resolutionFilename) { + if (resolutionFilename === void 0) { resolutionFilename = null; } + var scale = this.data.meta.scale; + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = getResolutionOfUrl(resolutionFilename, null); + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.setResolution(resolution); + } + return resolution; + }; + /** @ignore */ + Spritesheet.prototype.parse = function (callback) { + var _this = this; + if (callback) { + deprecation$1('6.5.0', 'Spritesheet.parse callback is deprecated, use the return Promise instead.'); + } + return new Promise(function (resolve) { + _this._callback = function (textures) { + callback === null || callback === void 0 ? void 0 : callback(textures); + resolve(textures); + }; + _this._batchIndex = 0; + if (_this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + _this._processFrames(0); + _this._processAnimations(); + _this._parseComplete(); + } + else { + _this._nextBatch(); + } + }); + }; + /** + * Process a batch of frames + * @param initialFrameIndex - The index of frame to start. + */ + Spritesheet.prototype._processFrames = function (initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var data = this._frames[i]; + var rect = data.frame; + if (rect) { + var frame = null; + var trim = null; + var sourceSize = data.trimmed !== false && data.sourceSize + ? data.sourceSize : data.frame; + var orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution); + if (data.rotated) { + frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution); + } + else { + frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + // Check to see if the sprite is trimmed + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); + // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions + Texture.addToCache(this.textures[i], i); + } + frameIndex++; + } + }; + /** Parse animations config. */ + Spritesheet.prototype._processAnimations = function () { + var animations = this.data.animations || {}; + for (var animName in animations) { + this.animations[animName] = []; + for (var i = 0; i < animations[animName].length; i++) { + var frameName = animations[animName][i]; + this.animations[animName].push(this.textures[frameName]); + } + } + }; + /** The parse has completed. */ + Spritesheet.prototype._parseComplete = function () { + var callback = this._callback; + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + /** Begin the next batch of textures. */ + Spritesheet.prototype._nextBatch = function () { + var _this = this; + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } + else { + _this._processAnimations(); + _this._parseComplete(); + } + }, 0); + }; + /** + * Destroy Spritesheet and don't use after this. + * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well + */ + Spritesheet.prototype.destroy = function (destroyBase) { + var _a; + if (destroyBase === void 0) { destroyBase = false; } + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy(); + this.baseTexture.destroy(); + } + this._texture = null; + this.baseTexture = null; + this.linkedSheets = []; + }; + /** The maximum number of Textures to build per process. */ + Spritesheet.BATCH_SIZE = 1000; + return Spritesheet; + }()); + /** + * Reference to Spritesheet object created. + * @member {PIXI.Spritesheet} spritesheet + * @memberof PIXI.LoaderResource + * @instance + */ + /** + * Dictionary of textures from Spritesheet. + * @member {Object} textures + * @memberof PIXI.LoaderResource + * @instance + */ + + /** + * {@link PIXI.Loader} middleware for loading texture atlases that have been created with + * TexturePacker or similar JSON-based spritesheet. + * + * This middleware automatically generates Texture resources. + * + * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON, + * use the {@link PIXI.Spritesheet} class to directly parse the JSON. + * + * The Loader's image Resource name is automatically appended with `"_image"`. + * If a Resource with this name is already loaded, the Loader will skip parsing the + * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`. + * @example + * loader.add('myatlas', 'path/to/myatlas.json'); + * loader.load(() => { + * loader.resources.myatlas; // atlas JSON resource + * loader.resources.myatlas_image; // atlas Image resource + * }); + * @memberof PIXI + */ + var SpritesheetLoader = /** @class */ (function () { + function SpritesheetLoader() { + } + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param resource + * @param next + */ + SpritesheetLoader.use = function (resource, next) { + var _a, _b; + // because this is middleware, it execute in loader context. `this` = loader + var loader = this; + var imageResourceName = resource.name + "_image"; + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data + || resource.type !== exports.LoaderResource.TYPE.JSON + || !resource.data.frames + || loader.resources[imageResourceName]) { + next(); + return; + } + // Check and add the multi atlas + // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js + // eslint-disable-next-line camelcase + var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs; + if (Array.isArray(multiPacks)) { + var _loop_1 = function (item) { + if (typeof item !== 'string') { + return "continue"; + } + var itemName = item.replace('.json', ''); + var itemUrl = url.resolve(resource.url.replace(loader.baseUrl, ''), item); + // Check if the file wasn't already added as multipacks are redundant + if (loader.resources[itemName] + || Object.values(loader.resources).some(function (r) { return url.format(url.parse(r.url)) === itemUrl; })) { + return "continue"; + } + var options = { + crossOrigin: resource.crossOrigin, + loadType: exports.LoaderResource.LOAD_TYPE.XHR, + xhrType: exports.LoaderResource.XHR_RESPONSE_TYPE.JSON, + parentResource: resource, + metadata: resource.metadata + }; + loader.add(itemName, itemUrl, options); + }; + for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) { + var item = multiPacks_1[_i]; + _loop_1(item); + } + } + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource, + }; + var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl); + // load the image for this sheet + loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + if (res.error) { + next(res.error); + return; + } + var spritesheet = new Spritesheet(res.texture, resource.data, resource.url); + spritesheet.parse().then(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; + /** + * Get the spritesheets root path + * @param resource - Resource to check path + * @param baseUrl - Base root url + */ + SpritesheetLoader.getResourcePath = function (resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); + }; + /** @ignore */ + SpritesheetLoader.extension = exports.ExtensionType.Loader; + return SpritesheetLoader; + }()); + + /*! + * @pixi/sprite-tiling - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/sprite-tiling is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$a = function(d, b) { + extendStatics$a = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$a(d, b); + }; + + function __extends$a(d, b) { + extendStatics$a(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var tempPoint$1 = new Point(); + /** + * A tiling sprite is a fast way of rendering a tiling image. + * @memberof PIXI + */ + var TilingSprite = /** @class */ (function (_super) { + __extends$a(TilingSprite, _super); + /** + * @param texture - The texture of the tiling sprite. + * @param width - The width of the tiling sprite. + * @param height - The height of the tiling sprite. + */ + function TilingSprite(texture, width, height) { + if (width === void 0) { width = 100; } + if (height === void 0) { height = 100; } + var _this = _super.call(this, texture) || this; + _this.tileTransform = new Transform(); + // The width of the tiling sprite + _this._width = width; + // The height of the tiling sprite + _this._height = height; + _this.uvMatrix = _this.texture.uvMatrix || new TextureMatrix(texture); + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_render' method. + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + _this.uvRespectAnchor = false; + return _this; + } + Object.defineProperty(TilingSprite.prototype, "clampMargin", { + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * @default 0.5 + * @member {number} + */ + get: function () { + return this.uvMatrix.clampMargin; + }, + set: function (value) { + this.uvMatrix.clampMargin = value; + this.uvMatrix.update(true); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "tileScale", { + /** The scaling of the image that is being tiled. */ + get: function () { + return this.tileTransform.scale; + }, + set: function (value) { + this.tileTransform.scale.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "tilePosition", { + /** The offset of the image that is being tiled. */ + get: function () { + return this.tileTransform.position; + }, + set: function (value) { + this.tileTransform.position.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + /** + * @protected + */ + TilingSprite.prototype._onTextureUpdate = function () { + if (this.uvMatrix) { + this.uvMatrix.texture = this._texture; + } + this._cachedTint = 0xFFFFFF; + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + TilingSprite.prototype._render = function (renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + if (!texture || !texture.valid) { + return; + } + this.tileTransform.updateLocalTransform(); + this.uvMatrix.update(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + /** Updates the bounds of the tiling sprite. */ + TilingSprite.prototype._calculateBounds = function () { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + /** + * Gets the local bounds of the sprite object. + * @param rect - Optional output rectangle. + * @returns The bounds. + */ + TilingSprite.prototype.getLocalBounds = function (rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + return this._bounds.getRectangle(rect); + } + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** + * Checks if a point is inside this tiling sprite. + * @param point - The point to check. + * @returns Whether or not the sprite contains the point. + */ + TilingSprite.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, tempPoint$1); + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width) { + var y1 = -height * this.anchor._y; + if (tempPoint$1.y >= y1 && tempPoint$1.y < y1 + height) { + return true; + } + } + return false; + }; + /** + * Destroys this sprite and optionally its texture and children + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + TilingSprite.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this.tileTransform = null; + this.uvMatrix = null; + }; + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @static + * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {object} options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {number} options.width - required width of the tiling sprite + * @param {number} options.height - required height of the tiling sprite + * @returns {PIXI.TilingSprite} The newly created texture + */ + TilingSprite.from = function (source, options) { + var texture = (source instanceof Texture) + ? source + : Texture.from(source, options); + return new TilingSprite(texture, options.width, options.height); + }; + Object.defineProperty(TilingSprite.prototype, "width", { + /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this._width; + }, + set: function (value) { + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "height", { + /** The height of the TilingSprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this._height; + }, + set: function (value) { + this._height = value; + }, + enumerable: false, + configurable: true + }); + return TilingSprite; + }(Sprite)); + + var fragmentSimpleSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-Simple-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 texSample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = texSample * uColor;\n}\n"; + + var gl1VertexSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + var gl1FragmentSrc = "#version 100\n#ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n#endif\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n #ifdef GL_EXT_shader_texture_lod\n vec4 texSample = unclamped == coord\n ? texture2D(uSampler, coord) \n : texture2DLodEXT(uSampler, coord, 0);\n #else\n vec4 texSample = texture2D(uSampler, coord);\n #endif\n\n gl_FragColor = texSample * uColor;\n}\n"; + + var gl2VertexSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-300\n\nprecision lowp float;\n\nin vec2 aVertexPosition;\nin vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nout vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + var gl2FragmentSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nin vec2 vTextureCoord;\n\nout vec4 fragmentColor;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture(uSampler, coord, unclamped == coord ? 0.0f : -32.0f);// lod-bias very negative to force lod 0\n\n fragmentColor = texSample * uColor;\n}\n"; + + var tempMat = new Matrix(); + /** + * WebGL renderer plugin for tiling sprites + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + var TilingSpriteRenderer = /** @class */ (function (_super) { + __extends$a(TilingSpriteRenderer, _super); + /** + * constructor for renderer + * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + // WebGL version is not available during initialization! + renderer.runners.contextChange.add(_this); + _this.quad = new QuadUv(); + /** + * The WebGL state in which this renderer will work. + * @member {PIXI.State} + * @readonly + */ + _this.state = State.for2d(); + return _this; + } + /** Creates shaders when context is initialized. */ + TilingSpriteRenderer.prototype.contextChange = function () { + var renderer = this.renderer; + var uniforms = { globals: renderer.globalUniforms }; + this.simpleShader = Shader.from(gl1VertexSrc, fragmentSimpleSrc, uniforms); + this.shader = renderer.context.webGLVersion > 1 + ? Shader.from(gl2VertexSrc, gl2FragmentSrc, uniforms) + : Shader.from(gl1VertexSrc, gl1FragmentSrc, uniforms); + }; + /** + * @param {PIXI.TilingSprite} ts - tilingSprite to be rendered + */ + TilingSpriteRenderer.prototype.render = function (ts) { + var renderer = this.renderer; + var quad = this.quad; + var vertices = quad.vertices; + vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + var anchorX = ts.uvRespectAnchor ? ts.anchor.x : 0; + var anchorY = ts.uvRespectAnchor ? ts.anchor.y : 0; + vertices = quad.uvs; + vertices[0] = vertices[6] = -anchorX; + vertices[1] = vertices[3] = -anchorY; + vertices[2] = vertices[4] = 1.0 - anchorX; + vertices[5] = vertices[7] = 1.0 - anchorY; + quad.invalidate(); + var tex = ts._texture; + var baseTex = tex.baseTexture; + var premultiplied = baseTex.alphaMode > 0; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvMatrix; + var isSimple = baseTex.isPowerOfTwo + && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === exports.WRAP_MODES.CLAMP) { + baseTex.wrapMode = exports.WRAP_MODES.REPEAT; + } + } + else { + isSimple = baseTex.wrapMode !== exports.WRAP_MODES.CLAMP; + } + } + var shader = isSimple ? this.simpleShader : this.shader; + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } + else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, premultiplied); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + shader.uniforms.uSampler = tex; + renderer.shader.bind(shader); + renderer.geometry.bind(quad); + this.state.blendMode = correctBlendMode(ts.blendMode, premultiplied); + renderer.state.set(this.state); + renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + /** @ignore */ + TilingSpriteRenderer.extension = { + name: 'tilingSprite', + type: exports.ExtensionType.RendererPlugin, + }; + return TilingSpriteRenderer; + }(ObjectRenderer)); + + /*! + * @pixi/mesh - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mesh is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$9 = function(d, b) { + extendStatics$9 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$9(d, b); + }; + + function __extends$9(d, b) { + extendStatics$9(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space. + * @memberof PIXI + */ + var MeshBatchUvs = /** @class */ (function () { + /** + * @param uvBuffer - Buffer with normalized uv's + * @param uvMatrix - Material UV matrix + */ + function MeshBatchUvs(uvBuffer, uvMatrix) { + this.uvBuffer = uvBuffer; + this.uvMatrix = uvMatrix; + this.data = null; + this._bufferUpdateId = -1; + this._textureUpdateId = -1; + this._updateID = 0; + } + /** + * Updates + * @param forceUpdate - force the update + */ + MeshBatchUvs.prototype.update = function (forceUpdate) { + if (!forceUpdate + && this._bufferUpdateId === this.uvBuffer._updateID + && this._textureUpdateId === this.uvMatrix._updateID) { + return; + } + this._bufferUpdateId = this.uvBuffer._updateID; + this._textureUpdateId = this.uvMatrix._updateID; + var data = this.uvBuffer.data; + if (!this.data || this.data.length !== data.length) { + this.data = new Float32Array(data.length); + } + this.uvMatrix.multiplyUvs(data, this.data); + this._updateID++; + }; + return MeshBatchUvs; + }()); + + var tempPoint = new Point(); + var tempPolygon = new Polygon(); + /** + * Base mesh class. + * + * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of. + * This class assumes a certain level of WebGL knowledge. + * If you know a bit this should abstract enough away to make your life easier! + * + * Pretty much ALL WebGL can be broken down into the following: + * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc.. + * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry) + * - State - This is the state of WebGL required to render the mesh. + * + * Through a combination of the above elements you can render anything you want, 2D or 3D! + * @memberof PIXI + */ + var Mesh = /** @class */ (function (_super) { + __extends$9(Mesh, _super); + /** + * @param geometry - The geometry the mesh will use. + * @param {PIXI.MeshMaterial} shader - The shader the mesh will use. + * @param state - The state that the WebGL context is required to be in to render the mesh + * if no state is provided, uses {@link PIXI.State.for2d} to create a 2D state for PixiJS. + * @param drawMode - The drawMode, can be any of the {@link PIXI.DRAW_MODES} constants. + */ + function Mesh(geometry, shader, state, drawMode) { + if (drawMode === void 0) { drawMode = exports.DRAW_MODES.TRIANGLES; } + var _this = _super.call(this) || this; + _this.geometry = geometry; + _this.shader = shader; + _this.state = state || State.for2d(); + _this.drawMode = drawMode; + _this.start = 0; + _this.size = 0; + _this.uvs = null; + _this.indices = null; + _this.vertexData = new Float32Array(1); + _this.vertexDirty = -1; + _this._transformID = -1; + _this._roundPixels = settings$1.ROUND_PIXELS; + _this.batchUvs = null; + return _this; + } + Object.defineProperty(Mesh.prototype, "geometry", { + /** + * Includes vertex positions, face indices, normals, colors, UVs, and + * custom attributes within buffers, reducing the cost of passing all + * this data to the GPU. Can be shared between multiple Mesh objects. + */ + get: function () { + return this._geometry; + }, + set: function (value) { + if (this._geometry === value) { + return; + } + if (this._geometry) { + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + } + this._geometry = value; + if (this._geometry) { + this._geometry.refCount++; + } + this.vertexDirty = -1; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "uvBuffer", { + /** + * To change mesh uv's, change its uvBuffer data and increment its _updateID. + * @readonly + */ + get: function () { + return this.geometry.buffers[1]; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "verticesBuffer", { + /** + * To change mesh vertices, change its uvBuffer data and increment its _updateID. + * Incrementing _updateID is optional because most of Mesh objects do it anyway. + * @readonly + */ + get: function () { + return this.geometry.buffers[0]; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "material", { + get: function () { + return this.shader; + }, + /** Alias for {@link PIXI.Mesh#shader}. */ + set: function (value) { + this.shader = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "blendMode", { + get: function () { + return this.state.blendMode; + }, + /** + * The blend mode to be applied to the Mesh. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * @default PIXI.BLEND_MODES.NORMAL; + */ + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "roundPixels", { + get: function () { + return this._roundPixels; + }, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} + * @default false + */ + set: function (value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "tint", { + /** + * The multiply tint applied to the Mesh. This is a hex value. A value of + * `0xFFFFFF` will remove any tint effect. + * + * Null for non-MeshMaterial shaders + * @default 0xFFFFFF + */ + get: function () { + return 'tint' in this.shader ? this.shader.tint : null; + }, + set: function (value) { + this.shader.tint = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "texture", { + /** The texture that the Mesh uses. Null for non-MeshMaterial shaders */ + get: function () { + return 'texture' in this.shader ? this.shader.texture : null; + }, + set: function (value) { + this.shader.texture = value; + }, + enumerable: false, + configurable: true + }); + /** + * Standard renderer draw. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._render = function (renderer) { + // set properties for batching.. + // TODO could use a different way to grab verts? + var vertices = this.geometry.buffers[0].data; + var shader = this.shader; + // TODO benchmark check for attribute size.. + if (shader.batchable + && this.drawMode === exports.DRAW_MODES.TRIANGLES + && vertices.length < Mesh.BATCHABLE_SIZE * 2) { + this._renderToBatch(renderer); + } + else { + this._renderDefault(renderer); + } + }; + /** + * Standard non-batching way of rendering. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._renderDefault = function (renderer) { + var shader = this.shader; + shader.alpha = this.worldAlpha; + if (shader.update) { + shader.update(); + } + renderer.batch.flush(); + // bind and sync uniforms.. + shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); + renderer.shader.bind(shader); + // set state.. + renderer.state.set(this.state); + // bind the geometry... + renderer.geometry.bind(this.geometry, shader); + // then render it + renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); + }; + /** + * Rendering by using the Batch system. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._renderToBatch = function (renderer) { + var geometry = this.geometry; + var shader = this.shader; + if (shader.uvMatrix) { + shader.uvMatrix.update(); + this.calculateUvs(); + } + // set properties for batching.. + this.calculateVertices(); + this.indices = geometry.indexBuffer.data; + this._tintRGB = shader._tintRGB; + this._texture = shader.texture; + var pluginName = this.material.pluginName; + renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); + renderer.plugins[pluginName].render(this); + }; + /** Updates vertexData field based on transform and vertices. */ + Mesh.prototype.calculateVertices = function () { + var geometry = this.geometry; + var verticesBuffer = geometry.buffers[0]; + var vertices = verticesBuffer.data; + var vertexDirtyId = verticesBuffer._updateID; + if (vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) { + return; + } + this._transformID = this.transform._worldID; + if (this.vertexData.length !== vertices.length) { + this.vertexData = new Float32Array(vertices.length); + } + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + for (var i = 0; i < vertexData.length / 2; i++) { + var x = vertices[(i * 2)]; + var y = vertices[(i * 2) + 1]; + vertexData[(i * 2)] = (a * x) + (c * y) + tx; + vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; + } + if (this._roundPixels) { + var resolution = settings$1.RESOLUTION; + for (var i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); + } + } + this.vertexDirty = vertexDirtyId; + }; + /** Updates uv field based on from geometry uv's or batchUvs. */ + Mesh.prototype.calculateUvs = function () { + var geomUvs = this.geometry.buffers[1]; + var shader = this.shader; + if (!shader.uvMatrix.isSimple) { + if (!this.batchUvs) { + this.batchUvs = new MeshBatchUvs(geomUvs, shader.uvMatrix); + } + this.batchUvs.update(); + this.uvs = this.batchUvs.data; + } + else { + this.uvs = geomUvs.data; + } + }; + /** + * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly. + */ + Mesh.prototype._calculateBounds = function () { + this.calculateVertices(); + this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); + }; + /** + * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES. + * @param point - The point to test. + * @returns - The result of the test. + */ + Mesh.prototype.containsPoint = function (point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + this.worldTransform.applyInverse(point, tempPoint); + var vertices = this.geometry.getBuffer('aVertexPosition').data; + var points = tempPolygon.points; + var indices = this.geometry.getIndex().data; + var len = indices.length; + var step = this.drawMode === 4 ? 3 : 1; + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + return false; + }; + Mesh.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + if (this._cachedTexture) { + this._cachedTexture.destroy(); + this._cachedTexture = null; + } + this.geometry = null; + this.shader = null; + this.state = null; + this.uvs = null; + this.indices = null; + this.vertexData = null; + }; + /** The maximum number of vertices to consider batchable. Generally, the complexity of the geometry. */ + Mesh.BATCHABLE_SIZE = 100; + return Mesh; + }(Container)); + + var fragment$5 = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; + + var vertex$2 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + /** + * Slightly opinionated default shader for PixiJS 2D objects. + * @memberof PIXI + */ + var MeshMaterial = /** @class */ (function (_super) { + __extends$9(MeshMaterial, _super); + /** + * @param uSampler - Texture that material uses to render. + * @param options - Additional options + * @param {number} [options.alpha=1] - Default alpha. + * @param {number} [options.tint=0xFFFFFF] - Default tint. + * @param {string} [options.pluginName='batch'] - Renderer plugin for batching. + * @param {PIXI.Program} [options.program=0xFFFFFF] - Custom program. + * @param {object} [options.uniforms] - Custom uniforms. + */ + function MeshMaterial(uSampler, options) { + var _this = this; + var uniforms = { + uSampler: uSampler, + alpha: 1, + uTextureMatrix: Matrix.IDENTITY, + uColor: new Float32Array([1, 1, 1, 1]), + }; + // Set defaults + options = Object.assign({ + tint: 0xFFFFFF, + alpha: 1, + pluginName: 'batch', + }, options); + if (options.uniforms) { + Object.assign(uniforms, options.uniforms); + } + _this = _super.call(this, options.program || Program.from(vertex$2, fragment$5), uniforms) || this; + _this._colorDirty = false; + _this.uvMatrix = new TextureMatrix(uSampler); + _this.batchable = options.program === undefined; + _this.pluginName = options.pluginName; + _this.tint = options.tint; + _this.alpha = options.alpha; + return _this; + } + Object.defineProperty(MeshMaterial.prototype, "texture", { + /** Reference to the texture being rendered. */ + get: function () { + return this.uniforms.uSampler; + }, + set: function (value) { + if (this.uniforms.uSampler !== value) { + if (!this.uniforms.uSampler.baseTexture.alphaMode !== !value.baseTexture.alphaMode) { + this._colorDirty = true; + } + this.uniforms.uSampler = value; + this.uvMatrix.texture = value; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(MeshMaterial.prototype, "alpha", { + get: function () { + return this._alpha; + }, + /** + * This gets automatically set by the object using this. + * @default 1 + */ + set: function (value) { + if (value === this._alpha) + { return; } + this._alpha = value; + this._colorDirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(MeshMaterial.prototype, "tint", { + get: function () { + return this._tint; + }, + /** + * Multiply tint for the material. + * @default 0xFFFFFF + */ + set: function (value) { + if (value === this._tint) + { return; } + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + this._colorDirty = true; + }, + enumerable: false, + configurable: true + }); + /** Gets called automatically by the Mesh. Intended to be overridden for custom {@link MeshMaterial} objects. */ + MeshMaterial.prototype.update = function () { + if (this._colorDirty) { + this._colorDirty = false; + var baseTexture = this.texture.baseTexture; + premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode); + } + if (this.uvMatrix.update()) { + this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; + } + }; + return MeshMaterial; + }(Shader)); + + /** + * Standard 2D geometry used in PixiJS. + * + * Geometry can be defined without passing in a style or data if required. + * + * ```js + * const geometry = new PIXI.Geometry(); + * + * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); + * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2); + * geometry.addIndex([0,1,2,1,3,2]); + * + * ``` + * @memberof PIXI + */ + var MeshGeometry = /** @class */ (function (_super) { + __extends$9(MeshGeometry, _super); + /** + * @param {Float32Array|number[]} [vertices] - Positional data on geometry. + * @param {Float32Array|number[]} [uvs] - Texture UVs. + * @param {Uint16Array|number[]} [index] - IndexBuffer + */ + function MeshGeometry(vertices, uvs, index) { + var _this = _super.call(this) || this; + var verticesBuffer = new Buffer(vertices); + var uvsBuffer = new Buffer(uvs, true); + var indexBuffer = new Buffer(index, true, true); + _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aTextureCoord', uvsBuffer, 2, false, exports.TYPES.FLOAT) + .addIndex(indexBuffer); + _this._updateId = -1; + return _this; + } + Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", { + /** + * If the vertex position is updated. + * @readonly + * @private + */ + get: function () { + return this.buffers[0]._updateID; + }, + enumerable: false, + configurable: true + }); + return MeshGeometry; + }(Geometry)); + + /*! + * @pixi/text-bitmap - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/text-bitmap is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$8 = function(d, b) { + extendStatics$8 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$8(d, b); + }; + + function __extends$8(d, b) { + extendStatics$8(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /* eslint-disable max-len */ + /** + * Normalized parsed data from .fnt files. + * @memberof PIXI + */ + var BitmapFontData = /** @class */ (function () { + function BitmapFontData() { + this.info = []; + this.common = []; + this.page = []; + this.char = []; + this.kerning = []; + this.distanceField = []; + } + return BitmapFontData; + }()); + + /** + * BitmapFont format that's Text-based. + * @private + */ + var TextFormat = /** @class */ (function () { + function TextFormat() { + } + /** + * Check if resource refers to txt font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + TextFormat.test = function (data) { + return typeof data === 'string' && data.indexOf('info face=') === 0; + }; + /** + * Convert text font data to a javascript object. + * @param txt - Raw string data to be converted + * @returns - Parsed font data + */ + TextFormat.parse = function (txt) { + // Retrieve data item + var items = txt.match(/^[a-z]+\s+.+$/gm); + var rawData = { + info: [], + common: [], + page: [], + char: [], + chars: [], + kerning: [], + kernings: [], + distanceField: [], + }; + for (var i in items) { + // Extract item name + var name = items[i].match(/^[a-z]+/gm)[0]; + // Extract item attribute list as string ex.: "width=10" + var attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm); + // Convert attribute list into an object + var itemData = {}; + for (var i_1 in attributeList) { + // Split key-value pairs + var split = attributeList[i_1].split('='); + var key = split[0]; + // Remove eventual quotes from value + var strValue = split[1].replace(/"/gm, ''); + // Try to convert value into float + var floatValue = parseFloat(strValue); + // Use string value case float value is NaN + var value = isNaN(floatValue) ? strValue : floatValue; + itemData[key] = value; + } + // Push current item to the resulting data + rawData[name].push(itemData); + } + var font = new BitmapFontData(); + rawData.info.forEach(function (info) { return font.info.push({ + face: info.face, + size: parseInt(info.size, 10), + }); }); + rawData.common.forEach(function (common) { return font.common.push({ + lineHeight: parseInt(common.lineHeight, 10), + }); }); + rawData.page.forEach(function (page) { return font.page.push({ + id: parseInt(page.id, 10), + file: page.file, + }); }); + rawData.char.forEach(function (char) { return font.char.push({ + id: parseInt(char.id, 10), + page: parseInt(char.page, 10), + x: parseInt(char.x, 10), + y: parseInt(char.y, 10), + width: parseInt(char.width, 10), + height: parseInt(char.height, 10), + xoffset: parseInt(char.xoffset, 10), + yoffset: parseInt(char.yoffset, 10), + xadvance: parseInt(char.xadvance, 10), + }); }); + rawData.kerning.forEach(function (kerning) { return font.kerning.push({ + first: parseInt(kerning.first, 10), + second: parseInt(kerning.second, 10), + amount: parseInt(kerning.amount, 10), + }); }); + rawData.distanceField.forEach(function (df) { return font.distanceField.push({ + distanceRange: parseInt(df.distanceRange, 10), + fieldType: df.fieldType, + }); }); + return font; + }; + return TextFormat; + }()); + + /** + * BitmapFont format that's XML-based. + * @private + */ + var XMLFormat = /** @class */ (function () { + function XMLFormat() { + } + /** + * Check if resource refers to xml font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + XMLFormat.test = function (data) { + return data instanceof XMLDocument + && data.getElementsByTagName('page').length + && data.getElementsByTagName('info')[0].getAttribute('face') !== null; + }; + /** + * Convert the XML into BitmapFontData that we can use. + * @param xml + * @returns - Data to use for BitmapFont + */ + XMLFormat.parse = function (xml) { + var data = new BitmapFontData(); + var info = xml.getElementsByTagName('info'); + var common = xml.getElementsByTagName('common'); + var page = xml.getElementsByTagName('page'); + var char = xml.getElementsByTagName('char'); + var kerning = xml.getElementsByTagName('kerning'); + var distanceField = xml.getElementsByTagName('distanceField'); + for (var i = 0; i < info.length; i++) { + data.info.push({ + face: info[i].getAttribute('face'), + size: parseInt(info[i].getAttribute('size'), 10), + }); + } + for (var i = 0; i < common.length; i++) { + data.common.push({ + lineHeight: parseInt(common[i].getAttribute('lineHeight'), 10), + }); + } + for (var i = 0; i < page.length; i++) { + data.page.push({ + id: parseInt(page[i].getAttribute('id'), 10) || 0, + file: page[i].getAttribute('file'), + }); + } + for (var i = 0; i < char.length; i++) { + var letter = char[i]; + data.char.push({ + id: parseInt(letter.getAttribute('id'), 10), + page: parseInt(letter.getAttribute('page'), 10) || 0, + x: parseInt(letter.getAttribute('x'), 10), + y: parseInt(letter.getAttribute('y'), 10), + width: parseInt(letter.getAttribute('width'), 10), + height: parseInt(letter.getAttribute('height'), 10), + xoffset: parseInt(letter.getAttribute('xoffset'), 10), + yoffset: parseInt(letter.getAttribute('yoffset'), 10), + xadvance: parseInt(letter.getAttribute('xadvance'), 10), + }); + } + for (var i = 0; i < kerning.length; i++) { + data.kerning.push({ + first: parseInt(kerning[i].getAttribute('first'), 10), + second: parseInt(kerning[i].getAttribute('second'), 10), + amount: parseInt(kerning[i].getAttribute('amount'), 10), + }); + } + for (var i = 0; i < distanceField.length; i++) { + data.distanceField.push({ + fieldType: distanceField[i].getAttribute('fieldType'), + distanceRange: parseInt(distanceField[i].getAttribute('distanceRange'), 10), + }); + } + return data; + }; + return XMLFormat; + }()); + + /** + * BitmapFont format that's XML-based. + * @private + */ + var XMLStringFormat = /** @class */ (function () { + function XMLStringFormat() { + } + /** + * Check if resource refers to text xml font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + XMLStringFormat.test = function (data) { + if (typeof data === 'string' && data.indexOf('') > -1) { + var xml = new globalThis.DOMParser().parseFromString(data, 'text/xml'); + return XMLFormat.test(xml); + } + return false; + }; + /** + * Convert the text XML into BitmapFontData that we can use. + * @param xmlTxt + * @returns - Data to use for BitmapFont + */ + XMLStringFormat.parse = function (xmlTxt) { + var xml = new globalThis.DOMParser().parseFromString(xmlTxt, 'text/xml'); + return XMLFormat.parse(xml); + }; + return XMLStringFormat; + }()); + + // Registered formats, maybe make this extensible in the future? + var formats = [ + TextFormat, + XMLFormat, + XMLStringFormat ]; + /** + * Auto-detect BitmapFont parsing format based on data. + * @private + * @param {any} data - Data to detect format + * @returns {any} Format or null + */ + function autoDetectFormat(data) { + for (var i = 0; i < formats.length; i++) { + if (formats[i].test(data)) { + return formats[i]; + } + } + return null; + } + + // TODO: Prevent code duplication b/w generateFillStyle & Text#generateFillStyle + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * @private + * @param canvas + * @param context + * @param {object} style - The style. + * @param resolution + * @param {string[]} lines - The lines of text. + * @param metrics + * @returns {string|number|CanvasGradient} The fill style + */ + function generateFillStyle(canvas, context, style, resolution, lines, metrics) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } + else if (fillStyle.length === 1) { + return fillStyle[0]; + } + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient; + // a dropshadow will enlarge the canvas and result in the gradient being + // generated with the incorrect dimensions + var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; + // should also take padding into account, padding can offset the gradient + var padding = style.padding || 0; + var width = (canvas.width / resolution) - dropShadowCorrection - (padding * 2); + var height = (canvas.height / resolution) - dropShadowCorrection - (padding * 2); + // make a copy of the style settings, so we can manipulate them later + var fill = fillStyle.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding); + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + // There's potential for floating point precision issues at the seams between gradient repeats. + // The loop below generates the stops in order, so track the last generated one to prevent + // floating point precision from making us go the teeniest bit backwards, resulting in + // the first and last colors getting swapped. + var lastIterationStop = 0; + // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc + var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + // textHeight, but as a 0-1 size in global gradient stop space + var gradStopLineHeight = textHeight / height; + for (var i = 0; i < lines.length; i++) { + var thisLineTop = metrics.lineHeight * i; + for (var j = 0; j < fill.length; j++) { + // 0-1 stop point for the current line, multiplied to global space afterwards + var lineStop = 0; + if (typeof fillGradientStops[j] === 'number') { + lineStop = fillGradientStops[j]; + } + else { + lineStop = j / fill.length; + } + var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight); + // Prevent color stop generation going backwards from floating point imprecision + var clampedStop = Math.max(lastIterationStop, globalStop); + clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw. + gradient.addColorStop(clampedStop, fill[j]); + lastIterationStop = clampedStop; + } + } + } + else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2); + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + var totalIterations = fill.length + 1; + var currentIteration = 1; + for (var i = 0; i < fill.length; i++) { + var stop = void 0; + if (typeof fillGradientStops[i] === 'number') { + stop = fillGradientStops[i]; + } + else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; + } + + // TODO: Prevent code duplication b/w drawGlyph & Text#updateText + /** + * Draws the glyph `metrics.text` on the given canvas. + * + * Ignored because not directly exposed. + * @ignore + * @param {HTMLCanvasElement} canvas + * @param {CanvasRenderingContext2D} context + * @param {TextMetrics} metrics + * @param {number} x + * @param {number} y + * @param {number} resolution + * @param {TextStyle} style + */ + function drawGlyph(canvas, context, metrics, x, y, resolution, style) { + var char = metrics.text; + var fontProperties = metrics.fontProperties; + context.translate(x, y); + context.scale(resolution, resolution); + var tx = style.strokeThickness / 2; + var ty = -(style.strokeThickness / 2); + context.font = style.toFontString(); + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + // set canvas text styles + context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); + context.strokeStyle = style.stroke; + if (style.dropShadow) { + var dropShadowColor = style.dropShadowColor; + var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); + var dropShadowBlur = style.dropShadowBlur * resolution; + var dropShadowDistance = style.dropShadowDistance * resolution; + context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; + context.shadowBlur = dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; + context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance; + } + else { + context.shadowColor = 'black'; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + if (style.stroke && style.strokeThickness) { + context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + if (style.fill) { + context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + context.setTransform(1, 0, 0, 1, 0, 0); // defaults needed for older browsers (e.g. Opera 29) + context.fillStyle = 'rgba(0, 0, 0, 0)'; + } + + /** + * Ponyfill for IE because it doesn't support `Array.from` + * @param text + * @private + */ + function splitTextToCharacters(text) { + return Array.from ? Array.from(text) : text.split(''); + } + + /** + * Processes the passed character set data and returns a flattened array of all the characters. + * + * Ignored because not directly exposed. + * @ignore + * @param {string | string[] | string[][] } chars + * @returns {string[]} the flattened array of characters + */ + function resolveCharacters(chars) { + // Split the chars string into individual characters + if (typeof chars === 'string') { + chars = [chars]; + } + // Handle an array of characters+ranges + var result = []; + for (var i = 0, j = chars.length; i < j; i++) { + var item = chars[i]; + // Handle range delimited by start/end chars + if (Array.isArray(item)) { + if (item.length !== 2) { + throw new Error("[BitmapFont]: Invalid character range length, expecting 2 got " + item.length + "."); + } + var startCode = item[0].charCodeAt(0); + var endCode = item[1].charCodeAt(0); + if (endCode < startCode) { + throw new Error('[BitmapFont]: Invalid character range.'); + } + for (var i_1 = startCode, j_1 = endCode; i_1 <= j_1; i_1++) { + result.push(String.fromCharCode(i_1)); + } + } + // Handle a character set string + else { + result.push.apply(result, splitTextToCharacters(item)); + } + } + if (result.length === 0) { + throw new Error('[BitmapFont]: Empty set when resolving characters.'); + } + return result; + } + + /** + * Ponyfill for IE because it doesn't support `codePointAt` + * @param str + * @private + */ + function extractCharCode(str) { + return str.codePointAt ? str.codePointAt(0) : str.charCodeAt(0); + } + + /** + * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install` + * method for adding a font to be used. + * @memberof PIXI + */ + var BitmapFont = /** @class */ (function () { + /** + * @param data + * @param textures + * @param ownsTextures - Setting to `true` will destroy page textures + * when the font is uninstalled. + */ + function BitmapFont(data, textures, ownsTextures) { + var _a, _b; + var info = data.info[0]; + var common = data.common[0]; + var page = data.page[0]; + var distanceField = data.distanceField[0]; + var res = getResolutionOfUrl(page.file); + var pageTextures = {}; + this._ownsTextures = ownsTextures; + this.font = info.face; + this.size = info.size; + this.lineHeight = common.lineHeight / res; + this.chars = {}; + this.pageTextures = pageTextures; + // Convert the input Texture, Textures or object + // into a page Texture lookup by "id" + for (var i = 0; i < data.page.length; i++) { + var _c = data.page[i], id = _c.id, file = _c.file; + pageTextures[id] = textures instanceof Array + ? textures[i] : textures[file]; + // only MSDF and SDF fonts need no-premultiplied-alpha + if ((distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) && distanceField.fieldType !== 'none') { + pageTextures[id].baseTexture.alphaMode = exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA; + } + } + // parse letters + for (var i = 0; i < data.char.length; i++) { + var _d = data.char[i], id = _d.id, page_1 = _d.page; + var _e = data.char[i], x = _e.x, y = _e.y, width = _e.width, height = _e.height, xoffset = _e.xoffset, yoffset = _e.yoffset, xadvance = _e.xadvance; + x /= res; + y /= res; + width /= res; + height /= res; + xoffset /= res; + yoffset /= res; + xadvance /= res; + var rect = new Rectangle(x + (pageTextures[page_1].frame.x / res), y + (pageTextures[page_1].frame.y / res), width, height); + this.chars[id] = { + xOffset: xoffset, + yOffset: yoffset, + xAdvance: xadvance, + kerning: {}, + texture: new Texture(pageTextures[page_1].baseTexture, rect), + page: page_1, + }; + } + // parse kernings + for (var i = 0; i < data.kerning.length; i++) { + var _f = data.kerning[i], first = _f.first, second = _f.second, amount = _f.amount; + first /= res; + second /= res; + amount /= res; + if (this.chars[second]) { + this.chars[second].kerning[first] = amount; + } + } + // Store distance field information + this.distanceFieldRange = distanceField === null || distanceField === void 0 ? void 0 : distanceField.distanceRange; + this.distanceFieldType = (_b = (_a = distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'none'; + } + /** Remove references to created glyph textures. */ + BitmapFont.prototype.destroy = function () { + for (var id in this.chars) { + this.chars[id].texture.destroy(); + this.chars[id].texture = null; + } + for (var id in this.pageTextures) { + if (this._ownsTextures) { + this.pageTextures[id].destroy(true); + } + this.pageTextures[id] = null; + } + // Set readonly null. + this.chars = null; + this.pageTextures = null; + }; + /** + * Register a new bitmap font. + * @param data - The + * characters map that could be provided as xml or raw string. + * @param textures - List of textures for each page. + * @param ownsTextures - Set to `true` to destroy page textures + * when the font is uninstalled. By default fonts created with + * `BitmapFont.from` or from the `BitmapFontLoader` are `true`. + * @returns {PIXI.BitmapFont} Result font object with font, size, lineHeight + * and char fields. + */ + BitmapFont.install = function (data, textures, ownsTextures) { + var fontData; + if (data instanceof BitmapFontData) { + fontData = data; + } + else { + var format = autoDetectFormat(data); + if (!format) { + throw new Error('Unrecognized data format for font.'); + } + fontData = format.parse(data); + } + // Single texture, convert to list + if (textures instanceof Texture) { + textures = [textures]; + } + var font = new BitmapFont(fontData, textures, ownsTextures); + BitmapFont.available[font.font] = font; + return font; + }; + /** + * Remove bitmap font by name. + * @param name - Name of the font to uninstall. + */ + BitmapFont.uninstall = function (name) { + var font = BitmapFont.available[name]; + if (!font) { + throw new Error("No font found named '" + name + "'"); + } + font.destroy(); + delete BitmapFont.available[name]; + }; + /** + * Generates a bitmap-font for the given style and character set. This does not support + * kernings yet. With `style` properties, only the following non-layout properties are used: + * + * - {@link PIXI.TextStyle#dropShadow|dropShadow} + * - {@link PIXI.TextStyle#dropShadowDistance|dropShadowDistance} + * - {@link PIXI.TextStyle#dropShadowColor|dropShadowColor} + * - {@link PIXI.TextStyle#dropShadowBlur|dropShadowBlur} + * - {@link PIXI.TextStyle#dropShadowAngle|dropShadowAngle} + * - {@link PIXI.TextStyle#fill|fill} + * - {@link PIXI.TextStyle#fillGradientStops|fillGradientStops} + * - {@link PIXI.TextStyle#fillGradientType|fillGradientType} + * - {@link PIXI.TextStyle#fontFamily|fontFamily} + * - {@link PIXI.TextStyle#fontSize|fontSize} + * - {@link PIXI.TextStyle#fontVariant|fontVariant} + * - {@link PIXI.TextStyle#fontWeight|fontWeight} + * - {@link PIXI.TextStyle#lineJoin|lineJoin} + * - {@link PIXI.TextStyle#miterLimit|miterLimit} + * - {@link PIXI.TextStyle#stroke|stroke} + * - {@link PIXI.TextStyle#strokeThickness|strokeThickness} + * - {@link PIXI.TextStyle#textBaseline|textBaseline} + * @param name - The name of the custom font to use with BitmapText. + * @param textStyle - Style options to render with BitmapFont. + * @param options - Setup options for font or name of the font. + * @param {string|string[]|string[][]} [options.chars=PIXI.BitmapFont.ALPHANUMERIC] - characters included + * in the font set. You can also use ranges. For example, `[['a', 'z'], ['A', 'Z'], "!@#$%^&*()~{}[] "]`. + * Don't forget to include spaces ' ' in your character set! + * @param {number} [options.resolution=1] - Render resolution for glyphs. + * @param {number} [options.textureWidth=512] - Optional width of atlas, smaller values to reduce memory. + * @param {number} [options.textureHeight=512] - Optional height of atlas, smaller values to reduce memory. + * @param {number} [options.padding=4] - Padding between glyphs on texture atlas. + * @returns Font generated by style options. + * @example + * PIXI.BitmapFont.from("TitleFont", { + * fontFamily: "Arial", + * fontSize: 12, + * strokeThickness: 2, + * fill: "purple" + * }); + * + * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" }); + */ + BitmapFont.from = function (name, textStyle, options) { + if (!name) { + throw new Error('[BitmapFont] Property `name` is required.'); + } + var _a = Object.assign({}, BitmapFont.defaultOptions, options), chars = _a.chars, padding = _a.padding, resolution = _a.resolution, textureWidth = _a.textureWidth, textureHeight = _a.textureHeight; + var charsList = resolveCharacters(chars); + var style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle); + var lineWidth = textureWidth; + var fontData = new BitmapFontData(); + fontData.info[0] = { + face: style.fontFamily, + size: style.fontSize, + }; + fontData.common[0] = { + lineHeight: style.fontSize, + }; + var positionX = 0; + var positionY = 0; + var canvas; + var context; + var baseTexture; + var maxCharHeight = 0; + var textures = []; + for (var i = 0; i < charsList.length; i++) { + if (!canvas) { + canvas = settings$1.ADAPTER.createCanvas(); + canvas.width = textureWidth; + canvas.height = textureHeight; + context = canvas.getContext('2d'); + baseTexture = new BaseTexture(canvas, { resolution: resolution }); + textures.push(new Texture(baseTexture)); + fontData.page.push({ + id: textures.length - 1, + file: '', + }); + } + // Measure glyph dimensions + var metrics = TextMetrics.measureText(charsList[i], style, false, canvas); + var width = metrics.width; + var height = Math.ceil(metrics.height); + // This is ugly - but italics are given more space so they don't overlap + var textureGlyphWidth = Math.ceil((style.fontStyle === 'italic' ? 2 : 1) * width); + // Can't fit char anymore: next canvas please! + if (positionY >= textureHeight - (height * resolution)) { + if (positionY === 0) { + // We don't want user debugging an infinite loop (or do we? :) + throw new Error("[BitmapFont] textureHeight " + textureHeight + "px is " + + ("too small for " + style.fontSize + "px fonts")); + } + --i; + // Create new atlas once current has filled up + canvas = null; + context = null; + baseTexture = null; + positionY = 0; + positionX = 0; + maxCharHeight = 0; + continue; + } + maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight); + // Wrap line once full row has been rendered + if ((textureGlyphWidth * resolution) + positionX >= lineWidth) { + --i; + positionY += maxCharHeight * resolution; + positionY = Math.ceil(positionY); + positionX = 0; + maxCharHeight = 0; + continue; + } + drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style); + // Unique (numeric) ID mapping to this glyph + var id = extractCharCode(metrics.text); + // Create a texture holding just the glyph + fontData.char.push({ + id: id, + page: textures.length - 1, + x: positionX / resolution, + y: positionY / resolution, + width: textureGlyphWidth, + height: height, + xoffset: 0, + yoffset: 0, + xadvance: Math.ceil(width + - (style.dropShadow ? style.dropShadowDistance : 0) + - (style.stroke ? style.strokeThickness : 0)), + }); + positionX += (textureGlyphWidth + (2 * padding)) * resolution; + positionX = Math.ceil(positionX); + } + // Brute-force kerning info, this can be expensive b/c it's an O(n²), + // but we're using measureText which is native and fast. + for (var i = 0, len = charsList.length; i < len; i++) { + var first = charsList[i]; + for (var j = 0; j < len; j++) { + var second = charsList[j]; + var c1 = context.measureText(first).width; + var c2 = context.measureText(second).width; + var total = context.measureText(first + second).width; + var amount = total - (c1 + c2); + if (amount) { + fontData.kerning.push({ + first: extractCharCode(first), + second: extractCharCode(second), + amount: amount, + }); + } + } + } + var font = new BitmapFont(fontData, textures, true); + // Make it easier to replace a font + if (BitmapFont.available[name] !== undefined) { + BitmapFont.uninstall(name); + } + BitmapFont.available[name] = font; + return font; + }; + /** + * This character set includes all the letters in the alphabet (both lower- and upper- case). + * @type {string[][]} + * @example + * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA }) + */ + BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' ']; + /** + * This character set includes all decimal digits (from 0 to 9). + * @type {string[][]} + * @example + * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC }) + */ + BitmapFont.NUMERIC = [['0', '9']]; + /** + * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`. + * @type {string[][]} + */ + BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' ']; + /** + * This character set consists of all the ASCII table. + * @member {string[][]} + * @see http://www.asciitable.com/ + */ + BitmapFont.ASCII = [[' ', '~']]; + /** + * Collection of default options when using `BitmapFont.from`. + * @property {number} [resolution=1] - + * @property {number} [textureWidth=512] - + * @property {number} [textureHeight=512] - + * @property {number} [padding=4] - + * @property {string|string[]|string[][]} chars = PIXI.BitmapFont.ALPHANUMERIC + */ + BitmapFont.defaultOptions = { + resolution: 1, + textureWidth: 512, + textureHeight: 512, + padding: 4, + chars: BitmapFont.ALPHANUMERIC, + }; + /** Collection of available/installed fonts. */ + BitmapFont.available = {}; + return BitmapFont; + }()); + + var msdfFrag = "// Pixi texture info\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\n\r\n// Tint\r\nuniform vec4 uColor;\r\n\r\n// on 2D applications fwidth is screenScale / glyphAtlasScale * distanceFieldRange\r\nuniform float uFWidth;\r\n\r\nvoid main(void) {\r\n\r\n // To stack MSDF and SDF we need a non-pre-multiplied-alpha texture.\r\n vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n\r\n // MSDF\r\n float median = texColor.r + texColor.g + texColor.b -\r\n min(texColor.r, min(texColor.g, texColor.b)) -\r\n max(texColor.r, max(texColor.g, texColor.b));\r\n // SDF\r\n median = min(median, texColor.a);\r\n\r\n float screenPxDistance = uFWidth * (median - 0.5);\r\n float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);\r\n\r\n // NPM Textures, NPM outputs\r\n gl_FragColor = vec4(uColor.rgb, uColor.a * alpha);\r\n\r\n}\r\n"; + + var msdfVert = "// Mesh material default fragment\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTextureMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n"; + + // If we ever need more than two pools, please make a Dict or something better. + var pageMeshDataDefaultPageMeshData = []; + var pageMeshDataMSDFPageMeshData = []; + var charRenderDataPool = []; + /** + * A BitmapText object will create a line or multiple lines of text using bitmap font. + * + * The primary advantage of this class over Text is that all of your textures are pre-generated and loading, + * meaning that rendering is fast, and changing text has no performance implications. + * + * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters. + * + * To split a line you can use '\n', '\r' or '\r\n' in your string. + * + * PixiJS can auto-generate fonts on-the-fly using BitmapFont or use fnt files provided by: + * http://www.angelcode.com/products/bmfont/ for Windows or + * http://www.bmglyph.com/ for Mac. + * + * You can also use SDF, MSDF and MTSDF BitmapFonts for vector-like scaling appearance provided by: + * https://github.com/soimy/msdf-bmfont-xml for SDF and MSDF fnt files or + * https://github.com/Chlumsky/msdf-atlas-gen for SDF, MSDF and MTSDF json files + * + * A BitmapText can only be created when the font is loaded. + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.BitmapText("text using a fancy font!", { + * fontName: "Desyrel", + * fontSize: 35, + * align: "right" + * }); + * ``` + * @memberof PIXI + */ + var BitmapText = /** @class */ (function (_super) { + __extends$8(BitmapText, _super); + /** + * @param text - A string that you would like the text to display. + * @param style - The style parameters. + * @param {string} style.fontName - The installed BitmapFont name. + * @param {number} [style.fontSize] - The size of the font in pixels, e.g. 24. If undefined, + *. this will default to the BitmapFont size. + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center', 'right' or 'justify'), + * does not affect single line text. + * @param {number} [style.tint=0xFFFFFF] - The tint color. + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters. + * @param {number} [style.maxWidth=0] - The max width of the text before line wrapping. + */ + function BitmapText(text, style) { + if (style === void 0) { style = {}; } + var _this = _super.call(this) || this; + /** + * Private tracker for the current tint. + * @private + */ + _this._tint = 0xFFFFFF; + // Apply the defaults + var _a = Object.assign({}, BitmapText.styleDefaults, style), align = _a.align, tint = _a.tint, maxWidth = _a.maxWidth, letterSpacing = _a.letterSpacing, fontName = _a.fontName, fontSize = _a.fontSize; + if (!BitmapFont.available[fontName]) { + throw new Error("Missing BitmapFont \"" + fontName + "\""); + } + _this._activePagesMeshData = []; + _this._textWidth = 0; + _this._textHeight = 0; + _this._align = align; + _this._tint = tint; + _this._fontName = fontName; + _this._fontSize = fontSize || BitmapFont.available[fontName].size; + _this.text = text; + _this._maxWidth = maxWidth; + _this._maxLineHeight = 0; + _this._letterSpacing = letterSpacing; + _this._anchor = new ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0); + _this._roundPixels = settings$1.ROUND_PIXELS; + _this.dirty = true; + _this._resolution = settings$1.RESOLUTION; + _this._autoResolution = true; + _this._textureCache = {}; + return _this; + } + /** Renders text and updates it when needed. This should only be called if the BitmapFont is regenerated. */ + BitmapText.prototype.updateText = function () { + var _a; + var data = BitmapFont.available[this._fontName]; + var scale = this._fontSize / data.size; + var pos = new Point(); + var chars = []; + var lineWidths = []; + var lineSpaces = []; + var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' '; + var charsInput = splitTextToCharacters(text); + var maxWidth = this._maxWidth * data.size / this._fontSize; + var pageMeshDataPool = data.distanceFieldType === 'none' + ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData; + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastBreakPos = -1; + var lastBreakWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + var spaceCount = 0; + for (var i = 0; i < charsInput.length; i++) { + var char = charsInput[i]; + var charCode = extractCharCode(char); + if ((/(?:\s)/).test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + spaceCount++; + } + if (char === '\r' || char === '\n') { + lineWidths.push(lastLineWidth); + lineSpaces.push(-1); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + spaceCount = 0; + continue; + } + var charData = data.chars[charCode]; + if (!charData) { + continue; + } + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + var charRenderData = charRenderDataPool.pop() || { + texture: Texture.EMPTY, + line: 0, + charCode: 0, + prevSpaces: 0, + position: new Point(), + }; + charRenderData.texture = charData.texture; + charRenderData.line = line; + charRenderData.charCode = charCode; + charRenderData.position.x = pos.x + charData.xOffset + (this._letterSpacing / 2); + charRenderData.position.y = pos.y + charData.yOffset; + charRenderData.prevSpaces = spaceCount; + chars.push(charRenderData); + lastLineWidth = charRenderData.position.x + + Math.max(charData.xAdvance - charData.xOffset, charData.texture.orig.width); + pos.x += charData.xAdvance + this._letterSpacing; + maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); + prevCharCode = charCode; + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + lineWidths.push(lastBreakWidth); + lineSpaces.push(chars.length > 0 ? chars[chars.length - 1].prevSpaces : 0); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + spaceCount = 0; + } + } + var lastChar = charsInput[charsInput.length - 1]; + if (lastChar !== '\r' && lastChar !== '\n') { + if ((/(?:\s)/).test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + lineSpaces.push(-1); + } + var lineAlignOffsets = []; + for (var i = 0; i <= line; i++) { + var alignOffset = 0; + if (this._align === 'right') { + alignOffset = maxLineWidth - lineWidths[i]; + } + else if (this._align === 'center') { + alignOffset = (maxLineWidth - lineWidths[i]) / 2; + } + else if (this._align === 'justify') { + alignOffset = lineSpaces[i] < 0 ? 0 : (maxLineWidth - lineWidths[i]) / lineSpaces[i]; + } + lineAlignOffsets.push(alignOffset); + } + var lenChars = chars.length; + var pagesMeshData = {}; + var newPagesMeshData = []; + var activePagesMeshData = this._activePagesMeshData; + for (var i = 0; i < activePagesMeshData.length; i++) { + pageMeshDataPool.push(activePagesMeshData[i]); + } + for (var i = 0; i < lenChars; i++) { + var texture = chars[i].texture; + var baseTextureUid = texture.baseTexture.uid; + if (!pagesMeshData[baseTextureUid]) { + var pageMeshData = pageMeshDataPool.pop(); + if (!pageMeshData) { + var geometry = new MeshGeometry(); + var material = void 0; + var meshBlendMode = void 0; + if (data.distanceFieldType === 'none') { + material = new MeshMaterial(Texture.EMPTY); + meshBlendMode = exports.BLEND_MODES.NORMAL; + } + else { + material = new MeshMaterial(Texture.EMPTY, { program: Program.from(msdfVert, msdfFrag), uniforms: { uFWidth: 0 } }); + meshBlendMode = exports.BLEND_MODES.NORMAL_NPM; + } + var mesh = new Mesh(geometry, material); + mesh.blendMode = meshBlendMode; + pageMeshData = { + index: 0, + indexCount: 0, + vertexCount: 0, + uvsCount: 0, + total: 0, + mesh: mesh, + vertices: null, + uvs: null, + indices: null, + }; + } + // reset data.. + pageMeshData.index = 0; + pageMeshData.indexCount = 0; + pageMeshData.vertexCount = 0; + pageMeshData.uvsCount = 0; + pageMeshData.total = 0; + // TODO need to get page texture here somehow.. + var _textureCache = this._textureCache; + _textureCache[baseTextureUid] = _textureCache[baseTextureUid] || new Texture(texture.baseTexture); + pageMeshData.mesh.texture = _textureCache[baseTextureUid]; + pageMeshData.mesh.tint = this._tint; + newPagesMeshData.push(pageMeshData); + pagesMeshData[baseTextureUid] = pageMeshData; + } + pagesMeshData[baseTextureUid].total++; + } + // lets find any previously active pageMeshDatas that are no longer required for + // the updated text (if any), removed and return them to the pool. + for (var i = 0; i < activePagesMeshData.length; i++) { + if (newPagesMeshData.indexOf(activePagesMeshData[i]) === -1) { + this.removeChild(activePagesMeshData[i].mesh); + } + } + // next lets add any new meshes, that have not yet been added to this BitmapText + // we only add if its not already a child of this BitmapObject + for (var i = 0; i < newPagesMeshData.length; i++) { + if (newPagesMeshData[i].mesh.parent !== this) { + this.addChild(newPagesMeshData[i].mesh); + } + } + // active page mesh datas are set to be the new pages added. + this._activePagesMeshData = newPagesMeshData; + for (var i in pagesMeshData) { + var pageMeshData = pagesMeshData[i]; + var total = pageMeshData.total; + // lets only allocate new buffers if we can fit the new text in the current ones.. + // unless that is, we will be batching. Currently batching dose not respect the size property of mesh + if (!(((_a = pageMeshData.indices) === null || _a === void 0 ? void 0 : _a.length) > 6 * total) || pageMeshData.vertices.length < Mesh.BATCHABLE_SIZE * 2) { + pageMeshData.vertices = new Float32Array(4 * 2 * total); + pageMeshData.uvs = new Float32Array(4 * 2 * total); + pageMeshData.indices = new Uint16Array(6 * total); + } + else { + var total_1 = pageMeshData.total; + var vertices = pageMeshData.vertices; + // Clear the garbage at the end of the vertices buffer. This will prevent the bounds miscalculation. + for (var i_1 = total_1 * 4 * 2; i_1 < vertices.length; i_1++) { + vertices[i_1] = 0; + } + } + // as a buffer maybe bigger than the current word, we set the size of the meshMaterial + // to match the number of letters needed + pageMeshData.mesh.size = 6 * total; + } + for (var i = 0; i < lenChars; i++) { + var char = chars[i]; + var offset = char.position.x + (lineAlignOffsets[char.line] * (this._align === 'justify' ? char.prevSpaces : 1)); + if (this._roundPixels) { + offset = Math.round(offset); + } + var xPos = offset * scale; + var yPos = char.position.y * scale; + var texture = char.texture; + var pageMesh = pagesMeshData[texture.baseTexture.uid]; + var textureFrame = texture.frame; + var textureUvs = texture._uvs; + var index = pageMesh.index++; + pageMesh.indices[(index * 6) + 0] = 0 + (index * 4); + pageMesh.indices[(index * 6) + 1] = 1 + (index * 4); + pageMesh.indices[(index * 6) + 2] = 2 + (index * 4); + pageMesh.indices[(index * 6) + 3] = 0 + (index * 4); + pageMesh.indices[(index * 6) + 4] = 2 + (index * 4); + pageMesh.indices[(index * 6) + 5] = 3 + (index * 4); + pageMesh.vertices[(index * 8) + 0] = xPos; + pageMesh.vertices[(index * 8) + 1] = yPos; + pageMesh.vertices[(index * 8) + 2] = xPos + (textureFrame.width * scale); + pageMesh.vertices[(index * 8) + 3] = yPos; + pageMesh.vertices[(index * 8) + 4] = xPos + (textureFrame.width * scale); + pageMesh.vertices[(index * 8) + 5] = yPos + (textureFrame.height * scale); + pageMesh.vertices[(index * 8) + 6] = xPos; + pageMesh.vertices[(index * 8) + 7] = yPos + (textureFrame.height * scale); + pageMesh.uvs[(index * 8) + 0] = textureUvs.x0; + pageMesh.uvs[(index * 8) + 1] = textureUvs.y0; + pageMesh.uvs[(index * 8) + 2] = textureUvs.x1; + pageMesh.uvs[(index * 8) + 3] = textureUvs.y1; + pageMesh.uvs[(index * 8) + 4] = textureUvs.x2; + pageMesh.uvs[(index * 8) + 5] = textureUvs.y2; + pageMesh.uvs[(index * 8) + 6] = textureUvs.x3; + pageMesh.uvs[(index * 8) + 7] = textureUvs.y3; + } + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + for (var i in pagesMeshData) { + var pageMeshData = pagesMeshData[i]; + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + var vertexCount = 0; + var anchorOffsetX = this._textWidth * this.anchor.x; + var anchorOffsetY = this._textHeight * this.anchor.y; + for (var i_2 = 0; i_2 < pageMeshData.total; i_2++) { + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + } + } + this._maxLineHeight = maxLineHeight * scale; + var vertexBuffer = pageMeshData.mesh.geometry.getBuffer('aVertexPosition'); + var textureBuffer = pageMeshData.mesh.geometry.getBuffer('aTextureCoord'); + var indexBuffer = pageMeshData.mesh.geometry.getIndex(); + vertexBuffer.data = pageMeshData.vertices; + textureBuffer.data = pageMeshData.uvs; + indexBuffer.data = pageMeshData.indices; + vertexBuffer.update(); + textureBuffer.update(); + indexBuffer.update(); + } + for (var i = 0; i < chars.length; i++) { + charRenderDataPool.push(chars[i]); + } + }; + BitmapText.prototype.updateTransform = function () { + this.validate(); + this.containerUpdateTransform(); + }; + BitmapText.prototype._render = function (renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + // Update the uniform + var _a = BitmapFont.available[this._fontName], distanceFieldRange = _a.distanceFieldRange, distanceFieldType = _a.distanceFieldType, size = _a.size; + if (distanceFieldType !== 'none') { + // Inject the shader code with the correct value + var _b = this.worldTransform, a = _b.a, b = _b.b, c = _b.c, d = _b.d; + var dx = Math.sqrt((a * a) + (b * b)); + var dy = Math.sqrt((c * c) + (d * d)); + var worldScale = (Math.abs(dx) + Math.abs(dy)) / 2; + var fontScale = this._fontSize / size; + for (var _i = 0, _c = this._activePagesMeshData; _i < _c.length; _i++) { + var mesh = _c[_i]; + mesh.mesh.shader.uniforms.uFWidth = worldScale * distanceFieldRange * fontScale * this._resolution; + } + } + _super.prototype._render.call(this, renderer); + }; + /** + * Validates text before calling parent's getLocalBounds + * @returns - The rectangular bounding area + */ + BitmapText.prototype.getLocalBounds = function () { + this.validate(); + return _super.prototype.getLocalBounds.call(this); + }; + /** + * Updates text when needed + * @private + */ + BitmapText.prototype.validate = function () { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + Object.defineProperty(BitmapText.prototype, "tint", { + /** + * The tint of the BitmapText object. + * @default 0xffffff + */ + get: function () { + return this._tint; + }, + set: function (value) { + if (this._tint === value) + { return; } + this._tint = value; + for (var i = 0; i < this._activePagesMeshData.length; i++) { + this._activePagesMeshData[i].mesh.tint = value; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "align", { + /** + * The alignment of the BitmapText object. + * @member {string} + * @default 'left' + */ + get: function () { + return this._align; + }, + set: function (value) { + if (this._align !== value) { + this._align = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "fontName", { + /** The name of the BitmapFont. */ + get: function () { + return this._fontName; + }, + set: function (value) { + if (!BitmapFont.available[value]) { + throw new Error("Missing BitmapFont \"" + value + "\""); + } + if (this._fontName !== value) { + this._fontName = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "fontSize", { + /** The size of the font to display. */ + get: function () { + return this._fontSize; + }, + set: function (value) { + if (this._fontSize !== value) { + this._fontSize = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "anchor", { + /** + * The anchor sets the origin point of the text. + * + * The default is `(0,0)`, this means the text's origin is the top left. + * + * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. + * + * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. + */ + get: function () { + return this._anchor; + }, + set: function (value) { + if (typeof value === 'number') { + this._anchor.set(value); + } + else { + this._anchor.copyFrom(value); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "text", { + /** The text of the BitmapText object. */ + get: function () { + return this._text; + }, + set: function (text) { + text = String(text === null || text === undefined ? '' : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "maxWidth", { + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting the value to 0. + */ + get: function () { + return this._maxWidth; + }, + set: function (value) { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "maxLineHeight", { + /** + * The max line height. This is useful when trying to use the total height of the Text, + * i.e. when trying to vertically align. + * @readonly + */ + get: function () { + this.validate(); + return this._maxLineHeight; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "textWidth", { + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object. + * @readonly + */ + get: function () { + this.validate(); + return this._textWidth; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "letterSpacing", { + /** Additional space between characters. */ + get: function () { + return this._letterSpacing; + }, + set: function (value) { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "roundPixels", { + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} + * @default PIXI.settings.ROUND_PIXELS + */ + get: function () { + return this._roundPixels; + }, + set: function (value) { + if (value !== this._roundPixels) { + this._roundPixels = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "textHeight", { + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object. + * @readonly + */ + get: function () { + this.validate(); + return this._textHeight; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "resolution", { + /** + * The resolution / device pixel ratio of the canvas. + * + * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. + * @default 1 + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + BitmapText.prototype.destroy = function (options) { + var _textureCache = this._textureCache; + for (var id in _textureCache) { + var texture = _textureCache[id]; + texture.destroy(); + delete _textureCache[id]; + } + this._textureCache = null; + _super.prototype.destroy.call(this, options); + }; + BitmapText.styleDefaults = { + align: 'left', + tint: 0xFFFFFF, + maxWidth: 0, + letterSpacing: 0, + }; + return BitmapText; + }(Container)); + + /** + * {@link PIXI.Loader Loader} middleware for loading + * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}. + * @memberof PIXI + */ + var BitmapFontLoader = /** @class */ (function () { + function BitmapFontLoader() { + } + /** + * Called when the plugin is installed. + * @see PIXI.extensions.add + */ + BitmapFontLoader.add = function () { + exports.LoaderResource.setExtensionXhrType('fnt', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT); + }; + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param this + * @param {PIXI.LoaderResource} resource + * @param {Function} next + */ + BitmapFontLoader.use = function (resource, next) { + var format = autoDetectFormat(resource.data); + // Resource was not recognised as any of the expected font data format + if (!format) { + next(); + return; + } + var baseUrl = BitmapFontLoader.getBaseUrl(this, resource); + var data = format.parse(resource.data); + var textures = {}; + // Handle completed, when the number of textures + // load is the same number as references in the fnt file + var completed = function (page) { + textures[page.metadata.pageFile] = page.texture; + if (Object.keys(textures).length === data.page.length) { + resource.bitmapFont = BitmapFont.install(data, textures, true); + next(); + } + }; + for (var i = 0; i < data.page.length; ++i) { + var pageFile = data.page[i].file; + var url = baseUrl + pageFile; + var exists = false; + // incase the image is loaded outside + // using the same loader, resource will be available + for (var name in this.resources) { + var bitmapResource = this.resources[name]; + if (bitmapResource.url === url) { + bitmapResource.metadata.pageFile = pageFile; + if (bitmapResource.texture) { + completed(bitmapResource); + } + else { + bitmapResource.onAfterMiddleware.add(completed); + } + exists = true; + break; + } + } + // texture is not loaded, we'll attempt to add + // it to the load and add the texture to the list + if (!exists) { + // Standard loading options for images + var options = { + crossOrigin: resource.crossOrigin, + loadType: exports.LoaderResource.LOAD_TYPE.IMAGE, + metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), + parentResource: resource, + }; + this.add(url, options, completed); + } + } + }; + /** + * Get folder path from a resource. + * @param loader + * @param resource + */ + BitmapFontLoader.getBaseUrl = function (loader, resource) { + var resUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : ''; + if (resource.isDataUrl) { + if (resUrl === '.') { + resUrl = ''; + } + if (loader.baseUrl && resUrl) { + // if baseurl has a trailing slash then add one to resUrl so the replace works below + if (loader.baseUrl.charAt(loader.baseUrl.length - 1) === '/') { + resUrl += '/'; + } + } + } + // remove baseUrl from resUrl + resUrl = resUrl.replace(loader.baseUrl, ''); + // if there is an resUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (resUrl && resUrl.charAt(resUrl.length - 1) !== '/') { + resUrl += '/'; + } + return resUrl; + }; + /** + * Replacement for NodeJS's path.dirname + * @param {string} url - Path to get directory for + */ + BitmapFontLoader.dirname = function (url) { + var dir = url + .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character + .replace(/\/$/, '') // replace trailing slash + .replace(/\/[^\/]*$/, ''); // remove everything after the last + // File request is relative, use current directory + if (dir === url) { + return '.'; + } + // Started with a slash + else if (dir === '') { + return '/'; + } + return dir; + }; + /** @ignore */ + BitmapFontLoader.extension = exports.ExtensionType.Loader; + return BitmapFontLoader; + }()); + + /*! + * @pixi/filter-alpha - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-alpha is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$7 = function(d, b) { + extendStatics$7 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$7(d, b); + }; + + function __extends$7(d, b) { + extendStatics$7(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var fragment$4 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; + + /** + * Simplest filter - applies alpha. + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. + * @memberof PIXI.filters + */ + var AlphaFilter = /** @class */ (function (_super) { + __extends$7(AlphaFilter, _super); + /** + * @param alpha - Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter(alpha) { + if (alpha === void 0) { alpha = 1.0; } + var _this = _super.call(this, defaultVertex$1, fragment$4, { uAlpha: 1 }) || this; + _this.alpha = alpha; + return _this; + } + Object.defineProperty(AlphaFilter.prototype, "alpha", { + /** + * Coefficient for alpha multiplication + * @default 1 + */ + get: function () { + return this.uniforms.uAlpha; + }, + set: function (value) { + this.uniforms.uAlpha = value; + }, + enumerable: false, + configurable: true + }); + return AlphaFilter; + }(Filter)); + + /*! + * @pixi/filter-blur - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-blur is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$6 = function(d, b) { + extendStatics$6 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$6(d, b); + }; + + function __extends$6(d, b) { + extendStatics$6(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }"; + function generateBlurVertSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + var vertSource = vertTemplate; + var blurLoop = ''; + var template; + if (x) { + template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } + else { + template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i.toString()); + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0"); + blurLoop += blur; + blurLoop += '\n'; + } + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize.toString()); + return vertSource; + } + + var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448], + }; + var fragTemplate = [ + 'varying vec2 vBlurTexCoords[%size%];', + 'uniform sampler2D uSampler;', + 'void main(void)', + '{', + ' gl_FragColor = vec4(0.0);', + ' %blur%', + '}' ].join('\n'); + function generateBlurFragSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + var fragSource = fragTemplate; + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value; + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i.toString()); + value = i; + if (i >= halfLength) { + value = kernelSize - i - 1; + } + blur = blur.replace('%value%', kernel[value].toString()); + blurLoop += blur; + blurLoop += '\n'; + } + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize.toString()); + return fragSource; + } + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$3; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$3 || (ENV$3 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$3; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$3 || (RENDERER_TYPE$3 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$3; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$3 || (BUFFER_BITS$3 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$3; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$3 || (BLEND_MODES$3 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$3; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$3 || (DRAW_MODES$3 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$3; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$3 || (FORMATS$3 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$3; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$3 || (TARGETS$3 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$3; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$3 || (TYPES$3 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$3; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$3 || (SAMPLER_TYPES$3 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$3; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$3 || (SCALE_MODES$3 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$3; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$3 || (WRAP_MODES$3 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$3; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$3 || (MIPMAP_MODES$3 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$3; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$3 || (ALPHA_MODES$3 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$3; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$3 || (CLEAR_MODES$3 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$3; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$3 || (GC_MODES$3 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$3; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$3 || (PRECISION$3 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$3; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$3 || (MASK_TYPES$3 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$3; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$3 || (COLOR_MASK_BITS$3 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$3; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$3 || (MSAA_QUALITY$3 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$3; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$3 || (BUFFER_TYPE$3 = {})); + + /** + * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. + * @memberof PIXI.filters + */ + var BlurFilterPass = /** @class */ (function (_super) { + __extends$6(BlurFilterPass, _super); + /** + * @param horizontal - Do pass along the x-axis (`true`) or y-axis (`false`). + * @param strength - The strength of the blur filter. + * @param quality - The quality of the blur filter. + * @param resolution - The resolution of the blur filter. + * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) { + if (strength === void 0) { strength = 8; } + if (quality === void 0) { quality = 4; } + if (resolution === void 0) { resolution = settings$1.FILTER_RESOLUTION; } + if (kernelSize === void 0) { kernelSize = 5; } + var _this = this; + var vertSrc = generateBlurVertSource(kernelSize, horizontal); + var fragSrc = generateBlurFragSource(kernelSize); + _this = _super.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc) || this; + _this.horizontal = horizontal; + _this.resolution = resolution; + _this._quality = 0; + _this.quality = quality; + _this.blur = strength; + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - How to clear + */ + BlurFilterPass.prototype.apply = function (filterManager, input, output, clearMode) { + if (output) { + if (this.horizontal) { + this.uniforms.strength = (1 / output.width) * (output.width / input.width); + } + else { + this.uniforms.strength = (1 / output.height) * (output.height / input.height); + } + } + else { + if (this.horizontal) // eslint-disable-line + { + this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); + } + else { + this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line + } + } + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clearMode); + } + else { + var renderTarget = filterManager.getFilterTexture(); + var renderer = filterManager.renderer; + var flip = input; + var flop = renderTarget; + this.state.blend = false; + filterManager.applyFilter(this, flip, flop, CLEAR_MODES$3.CLEAR); + for (var i = 1; i < this.passes - 1; i++) { + filterManager.bindAndClear(flip, CLEAR_MODES$3.BLIT); + this.uniforms.uSampler = flop; + var temp = flop; + flop = flip; + flip = temp; + renderer.shader.bind(this); + renderer.geometry.draw(5); + } + this.state.blend = true; + filterManager.applyFilter(this, flop, output, clearMode); + filterManager.returnFilterTexture(renderTarget); + } + }; + Object.defineProperty(BlurFilterPass.prototype, "blur", { + /** + * Sets the strength of both the blur. + * @default 16 + */ + get: function () { + return this.strength; + }, + set: function (value) { + this.padding = 1 + (Math.abs(value) * 2); + this.strength = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilterPass.prototype, "quality", { + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quality bluring but the lower the performance. + * @default 4 + */ + get: function () { + return this._quality; + }, + set: function (value) { + this._quality = value; + this.passes = value; + }, + enumerable: false, + configurable: true + }); + return BlurFilterPass; + }(Filter)); + + /** + * The BlurFilter applies a Gaussian blur to an object. + * + * The strength of the blur can be set for the x-axis and y-axis separately. + * @memberof PIXI.filters + */ + var BlurFilter = /** @class */ (function (_super) { + __extends$6(BlurFilter, _super); + /** + * @param strength - The strength of the blur filter. + * @param quality - The quality of the blur filter. + * @param [resolution=PIXI.settings.FILTER_RESOLUTION] - The resolution of the blur filter. + * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + if (strength === void 0) { strength = 8; } + if (quality === void 0) { quality = 4; } + if (resolution === void 0) { resolution = settings$1.FILTER_RESOLUTION; } + if (kernelSize === void 0) { kernelSize = 5; } + var _this = _super.call(this) || this; + _this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); + _this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); + _this.resolution = resolution; + _this.quality = quality; + _this.blur = strength; + _this.repeatEdgePixels = false; + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - How to clear + */ + BlurFilter.prototype.apply = function (filterManager, input, output, clearMode) { + var xStrength = Math.abs(this.blurXFilter.strength); + var yStrength = Math.abs(this.blurYFilter.strength); + if (xStrength && yStrength) { + var renderTarget = filterManager.getFilterTexture(); + this.blurXFilter.apply(filterManager, input, renderTarget, CLEAR_MODES$3.CLEAR); + this.blurYFilter.apply(filterManager, renderTarget, output, clearMode); + filterManager.returnFilterTexture(renderTarget); + } + else if (yStrength) { + this.blurYFilter.apply(filterManager, input, output, clearMode); + } + else { + this.blurXFilter.apply(filterManager, input, output, clearMode); + } + }; + BlurFilter.prototype.updatePadding = function () { + if (this._repeatEdgePixels) { + this.padding = 0; + } + else { + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }; + Object.defineProperty(BlurFilter.prototype, "blur", { + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * @default 2 + */ + get: function () { + return this.blurXFilter.blur; + }, + set: function (value) { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "quality", { + /** + * Sets the number of passes for blur. More passes means higher quality bluring. + * @default 1 + */ + get: function () { + return this.blurXFilter.quality; + }, + set: function (value) { + this.blurXFilter.quality = this.blurYFilter.quality = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blurX", { + /** + * Sets the strength of the blurX property + * @default 2 + */ + get: function () { + return this.blurXFilter.blur; + }, + set: function (value) { + this.blurXFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blurY", { + /** + * Sets the strength of the blurY property + * @default 2 + */ + get: function () { + return this.blurYFilter.blur; + }, + set: function (value) { + this.blurYFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blendMode", { + /** + * Sets the blendmode of the filter + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this.blurYFilter.blendMode; + }, + set: function (value) { + this.blurYFilter.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", { + /** + * If set to true the edge of the target will be clamped + * @default false + */ + get: function () { + return this._repeatEdgePixels; + }, + set: function (value) { + this._repeatEdgePixels = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + return BlurFilter; + }(Filter)); + + /*! + * @pixi/filter-color-matrix - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-color-matrix is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$5 = function(d, b) { + extendStatics$5 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$5(d, b); + }; + + function __extends$5(d, b) { + extendStatics$5(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var fragment$3 = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; + + /** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @memberof PIXI.filters + */ + var ColorMatrixFilter = /** @class */ (function (_super) { + __extends$5(ColorMatrixFilter, _super); + function ColorMatrixFilter() { + var _this = this; + var uniforms = { + m: new Float32Array([1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0]), + uAlpha: 1, + }; + _this = _super.call(this, defaultFilterVertex, fragment$3, uniforms) || this; + _this.alpha = 1; + return _this; + } + /** + * Transforms current matrix and set the new one + * @param {number[]} matrix - 5x4 matrix + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) { + if (multiply === void 0) { multiply = false; } + var newMatrix = matrix; + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + // set the new matrix + this.uniforms.m = newMatrix; + }; + /** + * Multiplies two mat5's + * @private + * @param out - 5x4 matrix the receiving matrix + * @param a - 5x4 matrix the first operand + * @param b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + ColorMatrixFilter.prototype._multiply = function (out, a, b) { + // Red Channel + out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); + out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); + out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); + out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); + out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4]; + // Green Channel + out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); + out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); + out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); + out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); + out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9]; + // Blue Channel + out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); + out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); + out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); + out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); + out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14]; + // Alpha Channel + out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); + out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); + out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); + out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); + out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19]; + return out; + }; + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * @param {number[]} matrix - 5x4 matrix + * @returns {number[]} 5x4 matrix with all values between 0-1 + */ + ColorMatrixFilter.prototype._colorMatrix = function (matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + return m; + }; + /** + * Adjusts brightness + * @param b - value of the brigthness (0-1, where 0 is black) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.brightness = function (b, multiply) { + var matrix = [ + b, 0, 0, 0, 0, + 0, b, 0, 0, 0, + 0, 0, b, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Sets each channel on the diagonal of the color matrix. + * This can be used to achieve a tinting effect on Containers similar to the tint field of some + * display objects like Sprite, Text, Graphics, and Mesh. + * @param color - Color of the tint. This is a hex value. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.tint = function (color, multiply) { + var r = (color >> 16) & 0xff; + var g = (color >> 8) & 0xff; + var b = color & 0xff; + var matrix = [ + r / 255, 0, 0, 0, 0, + 0, g / 255, 0, 0, 0, + 0, 0, b / 255, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the matrices in grey scales + * @param scale - value of the grey (0-1, where 0 is black) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.greyscale = function (scale, multiply) { + var matrix = [ + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the black and white matrice. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.blackAndWhite = function (multiply) { + var matrix = [ + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the hue property of the color + * @param rotation - in degrees + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.hue = function (rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + var a00 = cosR + ((1.0 - cosR) * w); + var a01 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a02 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a10 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a11 = cosR + (w * (1.0 - cosR)); + var a12 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a20 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a21 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a22 = cosR + (w * (1.0 - cosR)); + var matrix = [ + a00, a01, a02, 0, 0, + a10, a11, a12, 0, 0, + a20, a21, a22, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * @param amount - value of the contrast (0-1) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.contrast = function (amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + var matrix = [ + v, 0, 0, 0, o, + 0, v, 0, 0, o, + 0, 0, v, 0, o, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * @param amount - The saturation amount (0-1) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.saturate = function (amount, multiply) { + if (amount === void 0) { amount = 0; } + var x = (amount * 2 / 3) + 1; + var y = ((x - 1) * -0.5); + var matrix = [ + x, y, y, 0, 0, + y, x, y, 0, 0, + y, y, x, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** Desaturate image (remove color) Call the saturate function */ + ColorMatrixFilter.prototype.desaturate = function () { + this.saturate(-1); + }; + /** + * Negative image (inverse of classic rgb matrix) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.negative = function (multiply) { + var matrix = [ + -1, 0, 0, 1, 0, + 0, -1, 0, 1, 0, + 0, 0, -1, 1, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Sepia image + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.sepia = function (multiply) { + var matrix = [ + 0.393, 0.7689999, 0.18899999, 0, 0, + 0.349, 0.6859999, 0.16799999, 0, 0, + 0.272, 0.5339999, 0.13099999, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.technicolor = function (multiply) { + var matrix = [ + 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, + -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, + -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Polaroid filter + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.polaroid = function (multiply) { + var matrix = [ + 1.438, -0.062, -0.062, 0, 0, + -0.122, 1.378, -0.122, 0, 0, + -0.016, -0.016, 1.483, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.toBGR = function (multiply) { + var matrix = [ + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.kodachrome = function (multiply) { + var matrix = [ + 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, + -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, + -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.browni = function (multiply) { + var matrix = [ + 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, + -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, + 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Vintage filter (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.vintage = function (multiply) { + var matrix = [ + 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, + 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, + 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * @param desaturation - Tone values. + * @param toned - Tone values. + * @param lightColor - Tone values, example: `0xFFE580` + * @param darkColor - Tone values, example: `0xFFE580` + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + var lR = ((lightColor >> 16) & 0xFF) / 255; + var lG = ((lightColor >> 8) & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + var dR = ((darkColor >> 16) & 0xFF) / 255; + var dG = ((darkColor >> 8) & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + var matrix = [ + 0.3, 0.59, 0.11, 0, 0, + lR, lG, lB, desaturation, 0, + dR, dG, dB, toned, 0, + lR - dR, lG - dG, lB - dB, 0, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Night effect + * @param intensity - The intensity of the night effect. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.night = function (intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [ + intensity * (-2.0), -intensity, 0, 0, 0, + -intensity, 0, intensity, 0, 0, + 0, intensity, intensity * 2.0, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * @param amount - how much the predator feels his future victim + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.predator = function (amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, + -4.794486999511719 * amount, + -2.8746118545532227 * amount, + 0 * amount, + 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, + 9.193157196044922 * amount, + -2.951810836791992 * amount, + 0 * amount, + -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, + -4.2375030517578125 * amount, + 7.476448059082031 * amount, + 0 * amount, + 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * LSD effect + * + * Multiply the current matrix + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.lsd = function (multiply) { + var matrix = [ + 2, -0.4, 0.5, 0, 0, + -0.5, 2, -0.4, 0, 0, + -0.4, -0.5, 3, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** Erase the current matrix by setting the default one. */ + ColorMatrixFilter.prototype.reset = function () { + var matrix = [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, false); + }; + Object.defineProperty(ColorMatrixFilter.prototype, "matrix", { + /** + * The matrix of the color matrix filter + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + get: function () { + return this.uniforms.m; + }, + set: function (value) { + this.uniforms.m = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ColorMatrixFilter.prototype, "alpha", { + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * @default 1 + */ + get: function () { + return this.uniforms.uAlpha; + }, + set: function (value) { + this.uniforms.uAlpha = value; + }, + enumerable: false, + configurable: true + }); + return ColorMatrixFilter; + }(Filter)); + // Americanized alias + ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + + /*! + * @pixi/filter-displacement - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-displacement is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$4 = function(d, b) { + extendStatics$4 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$4(d, b); + }; + + function __extends$4(d, b) { + extendStatics$4(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var fragment$2 = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; + + var vertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; + + /** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. + * + * You can use this filter to apply all manor of crazy warping effects. + * Currently the `r` property of the texture is used to offset the `x` + * and the `g` property of the texture is used to offset the `y`. + * + * The way it works is it uses the values of the displacement map to look up the + * correct pixels to output. This means it's not technically moving the original. + * Instead, it's starting at the output and asking "which pixel from the original goes here". + * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`, + * this filter will output the pixel approximately 20 pixels to the right of the original. + * @memberof PIXI.filters + */ + var DisplacementFilter = /** @class */ (function (_super) { + __extends$4(DisplacementFilter, _super); + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + var _this = this; + var maskMatrix = new Matrix(); + sprite.renderable = false; + _this = _super.call(this, vertex$1, fragment$2, { + mapSampler: sprite._texture, + filterMatrix: maskMatrix, + scale: { x: 1, y: 1 }, + rotation: new Float32Array([1, 0, 0, 1]), + }) || this; + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + if (scale === null || scale === undefined) { + scale = 20; + } + /** + * scaleX, scaleY for displacements + * @member {PIXI.Point} + */ + _this.scale = new Point(scale, scale); + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - clearMode. + */ + DisplacementFilter.prototype.apply = function (filterManager, input, output, clearMode) { + // fill maskMatrix with _normalized sprite texture coords_ + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + // Extract rotation from world transform + var wt = this.maskSprite.worldTransform; + var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b)); + var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d)); + if (lenX !== 0 && lenY !== 0) { + this.uniforms.rotation[0] = wt.a / lenX; + this.uniforms.rotation[1] = wt.b / lenX; + this.uniforms.rotation[2] = wt.c / lenY; + this.uniforms.rotation[3] = wt.d / lenY; + } + // draw the filter... + filterManager.applyFilter(this, input, output, clearMode); + }; + Object.defineProperty(DisplacementFilter.prototype, "map", { + /** The texture used for the displacement map. Must be power of 2 sized texture. */ + get: function () { + return this.uniforms.mapSampler; + }, + set: function (value) { + this.uniforms.mapSampler = value; + }, + enumerable: false, + configurable: true + }); + return DisplacementFilter; + }(Filter)); + + /*! + * @pixi/filter-fxaa - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-fxaa is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$3 = function(d, b) { + extendStatics$3 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$3(d, b); + }; + + function __extends$3(d, b) { + extendStatics$3(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; + + var fragment$1 = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputSize;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; + + /** + * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com + * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. + * @see https://github.com/mitsuhiko/webgl-meincraft + * @memberof PIXI.filters + */ + var FXAAFilter = /** @class */ (function (_super) { + __extends$3(FXAAFilter, _super); + function FXAAFilter() { + // TODO - needs work + return _super.call(this, vertex, fragment$1) || this; + } + return FXAAFilter; + }(Filter)); + + /*! + * @pixi/filter-noise - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-noise is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$2 = function(d, b) { + extendStatics$2 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$2(d, b); + }; + + function __extends$2(d, b) { + extendStatics$2(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; + + /** + * A Noise effect filter. + * + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + * @memberof PIXI.filters + * @author Vico @vicocotea + */ + var NoiseFilter = /** @class */ (function (_super) { + __extends$2(NoiseFilter, _super); + /** + * @param {number} [noise=0.5] - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} [seed] - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter(noise, seed) { + if (noise === void 0) { noise = 0.5; } + if (seed === void 0) { seed = Math.random(); } + var _this = _super.call(this, defaultFilterVertex, fragment, { + uNoise: 0, + uSeed: 0, + }) || this; + _this.noise = noise; + _this.seed = seed; + return _this; + } + Object.defineProperty(NoiseFilter.prototype, "noise", { + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * @default 0.5 + */ + get: function () { + return this.uniforms.uNoise; + }, + set: function (value) { + this.uniforms.uNoise = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NoiseFilter.prototype, "seed", { + /** A seed value to apply to the random noise generation. `Math.random()` is a good value to use. */ + get: function () { + return this.uniforms.uSeed; + }, + set: function (value) { + this.uniforms.uSeed = value; + }, + enumerable: false, + configurable: true + }); + return NoiseFilter; + }(Filter)); + + /*! + * @pixi/mixin-cache-as-bitmap - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mixin-cache-as-bitmap is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$2; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$2 || (ENV$2 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$2; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$2 || (RENDERER_TYPE$2 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$2; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$2 || (BUFFER_BITS$2 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$2; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$2 || (BLEND_MODES$2 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$2; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$2 || (DRAW_MODES$2 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$2; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$2 || (FORMATS$2 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$2; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$2 || (TARGETS$2 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$2; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$2 || (TYPES$2 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$2; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$2 || (SAMPLER_TYPES$2 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$2; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$2 || (SCALE_MODES$2 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$2; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$2 || (WRAP_MODES$2 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$2; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$2 || (MIPMAP_MODES$2 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$2; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$2 || (ALPHA_MODES$2 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$2; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$2 || (CLEAR_MODES$2 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$2; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$2 || (GC_MODES$2 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$2; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$2 || (PRECISION$2 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$2; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$2 || (MASK_TYPES$2 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$2; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$2 || (COLOR_MASK_BITS$2 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$2; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$2 || (MSAA_QUALITY$2 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$2; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$2 || (BUFFER_TYPE$2 = {})); + + var _tempMatrix = new Matrix(); + DisplayObject.prototype._cacheAsBitmap = false; + DisplayObject.prototype._cacheData = null; + DisplayObject.prototype._cacheAsBitmapResolution = null; + DisplayObject.prototype._cacheAsBitmapMultisample = MSAA_QUALITY$2.NONE; + // figured there's no point adding ALL the extra variables to prototype. + // this model can hold the information needed. This can also be generated on demand as + // most objects are not cached as bitmaps. + /** + * @class + * @ignore + * @private + */ + var CacheData = /** @class */ (function () { + function CacheData() { + this.textureCacheId = null; + this.originalRender = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + this.originalUpdateTransform = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.originalContainsPoint = null; + this.sprite = null; + } + return CacheData; + }()); + Object.defineProperties(DisplayObject.prototype, { + /** + * The resolution to use for cacheAsBitmap. By default this will use the renderer's resolution + * but can be overriden for performance. Lower values will reduce memory usage at the expense + * of render quality. A falsey value of `null` or `0` will default to the renderer's resolution. + * If `cacheAsBitmap` is set to `true`, this will re-render with the new resolution. + * @member {number} cacheAsBitmapResolution + * @memberof PIXI.DisplayObject# + * @default null + */ + cacheAsBitmapResolution: { + get: function () { + return this._cacheAsBitmapResolution; + }, + set: function (resolution) { + if (resolution === this._cacheAsBitmapResolution) { + return; + } + this._cacheAsBitmapResolution = resolution; + if (this.cacheAsBitmap) { + // Toggle to re-render at the new resolution + this.cacheAsBitmap = false; + this.cacheAsBitmap = true; + } + }, + }, + /** + * The number of samples to use for cacheAsBitmap. If set to `null`, the renderer's + * sample count is used. + * If `cacheAsBitmap` is set to `true`, this will re-render with the new number of samples. + * @member {number} cacheAsBitmapMultisample + * @memberof PIXI.DisplayObject# + * @default PIXI.MSAA_QUALITY.NONE + */ + cacheAsBitmapMultisample: { + get: function () { + return this._cacheAsBitmapMultisample; + }, + set: function (multisample) { + if (multisample === this._cacheAsBitmapMultisample) { + return; + } + this._cacheAsBitmapMultisample = multisample; + if (this.cacheAsBitmap) { + // Toggle to re-render with new multisample + this.cacheAsBitmap = false; + this.cacheAsBitmap = true; + } + }, + }, + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to `false` + * + * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function () { + return this._cacheAsBitmap; + }, + set: function (value) { + if (this._cacheAsBitmap === value) { + return; + } + this._cacheAsBitmap = value; + var data; + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + data = this._cacheData; + data.originalRender = this.render; + data.originalRenderCanvas = this.renderCanvas; + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this.calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + data.originalDestroy = this.destroy; + data.originalContainsPoint = this.containsPoint; + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + this.render = this._renderCached; + this.renderCanvas = this._renderCachedCanvas; + this.destroy = this._cacheAsBitmapDestroy; + } + else { + data = this._cacheData; + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + this.render = data.originalRender; + this.renderCanvas = data.originalRenderCanvas; + this.calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + this.destroy = data.originalDestroy; + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + }, + }, + }); + /** + * Renders a cached version of the sprite with WebGL + * @private + * @method _renderCached + * @memberof PIXI.DisplayObject# + * @param {PIXI.Renderer} renderer - the WebGL renderer + */ + DisplayObject.prototype._renderCached = function _renderCached(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObject(renderer); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._render(renderer); + }; + /** + * Prepares the WebGL renderer to cache the sprite + * @private + * @method _initCachedDisplayObject + * @memberof PIXI.DisplayObject# + * @param {PIXI.Renderer} renderer - the WebGL renderer + */ + DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + var _a; + if (this._cacheData && this._cacheData.sprite) { + return; + } + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + this.alpha = 1; + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.batch.flush(); + // this.filters= []; + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds(null, true).clone(); + // add some padding! + if (this.filters && this.filters.length) { + var padding = this.filters[0].padding; + bounds.pad(padding); + } + bounds.ceil(settings$1.RESOLUTION); + // for now we cache the current renderTarget that the WebGL renderer is currently using. + // this could be more elegant.. + var cachedRenderTexture = renderer.renderTexture.current; + var cachedSourceFrame = renderer.renderTexture.sourceFrame.clone(); + var cachedDestinationFrame = renderer.renderTexture.destinationFrame.clone(); + var cachedProjectionTransform = renderer.projection.transform; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + // const stack = renderer.filterManager.filterStack; + // this renderTexture will be used to store the cached DisplayObject + var renderTexture = RenderTexture.create({ + width: bounds.width, + height: bounds.height, + resolution: this.cacheAsBitmapResolution || renderer.resolution, + multisample: (_a = this.cacheAsBitmapMultisample) !== null && _a !== void 0 ? _a : renderer.multisample, + }); + var textureCacheId = "cacheAsBitmap_" + uid(); + this._cacheData.textureCacheId = textureCacheId; + BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + Texture.addToCache(renderTexture, textureCacheId); + // need to set // + var m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y); + // set all properties to there original so we can render to a texture + this.render = this._cacheData.originalRender; + renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false }); + renderer.framebuffer.blit(); + // now restore the state be setting the new properties + renderer.projection.transform = cachedProjectionTransform; + renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame, cachedDestinationFrame); + // renderer.filterManager.filterStack = stack; + this.render = this._renderCached; + // the rest is the same as for Canvas + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + this.alpha = cacheAlpha; + // create our cached sprite + var cachedSprite = new Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.enableTempParent(); + this.updateTransform(); + this.disableTempParent(null); + } + else { + this.updateTransform(); + } + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; + /** + * Renders a cached version of the sprite with canvas + * @private + * @method _renderCachedCanvas + * @memberof PIXI.DisplayObject# + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObjectCanvas(renderer); + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderCanvas(renderer); + }; + // TODO this can be the same as the WebGL version.. will need to do a little tweaking first though.. + /** + * Prepares the Canvas renderer to cache the sprite + * @private + * @method _initCachedDisplayObjectCanvas + * @memberof PIXI.DisplayObject# + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(null, true); + var cacheAlpha = this.alpha; + this.alpha = 1; + var cachedRenderTarget = renderer.context; + var cachedProjectionTransform = renderer._projTransform; + bounds.ceil(settings$1.RESOLUTION); + var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height }); + var textureCacheId = "cacheAsBitmap_" + uid(); + this._cacheData.textureCacheId = textureCacheId; + BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + Texture.addToCache(renderTexture, textureCacheId); + // need to set // + var m = _tempMatrix; + this.transform.localTransform.copyTo(m); + m.invert(); + m.tx -= bounds.x; + m.ty -= bounds.y; + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false }); + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + renderer._projTransform = cachedProjectionTransform; + this.renderCanvas = this._renderCachedCanvas; + // the rest is the same as for WebGL + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + this.alpha = cacheAlpha; + // create our cached sprite + var cachedSprite = new Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } + else { + this.updateTransform(); + } + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; + /** + * Calculates the bounds of the cached sprite + * @private + * @method + */ + DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._bounds.clear(); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite._calculateBounds(); + this._bounds.updateID = this._boundsID; + }; + /** + * Gets the bounds of the cached sprite. + * @private + * @method + * @returns {Rectangle} The local bounds. + */ + DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(null); + }; + /** + * Destroys the cached sprite. + * @private + * @method + */ + DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + BaseTexture.removeFromCache(this._cacheData.textureCacheId); + Texture.removeFromCache(this._cacheData.textureCacheId); + this._cacheData.textureCacheId = null; + }; + /** + * Destroys the cached object. + * @private + * @method + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ + DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); + }; + + /*! + * @pixi/mixin-get-child-by-name - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mixin-get-child-by-name is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * The instance name of the object. + * @memberof PIXI.DisplayObject# + * @member {string} name + */ + DisplayObject.prototype.name = null; + /** + * Returns the display object in the container. + * + * Recursive searches are done in a preorder traversal. + * @method getChildByName + * @memberof PIXI.Container# + * @param {string} name - Instance name. + * @param {boolean}[deep=false] - Whether to search recursively + * @returns {PIXI.DisplayObject} The child with the specified name. + */ + Container.prototype.getChildByName = function getChildByName(name, deep) { + for (var i = 0, j = this.children.length; i < j; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + if (deep) { + for (var i = 0, j = this.children.length; i < j; i++) { + var child = this.children[i]; + if (!child.getChildByName) { + continue; + } + var target = child.getChildByName(name, true); + if (target) { + return target; + } + } + } + return null; + }; + + /*! + * @pixi/mixin-get-global-position - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mixin-get-global-position is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * @method getGlobalPosition + * @memberof PIXI.DisplayObject# + * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to. + * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost. + * @returns {PIXI.Point} The updated point. + */ + DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) { + if (point === void 0) { point = new Point(); } + if (skipUpdate === void 0) { skipUpdate = false; } + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } + else { + point.x = this.position.x; + point.y = this.position.y; + } + return point; + }; + + /*! + * @pixi/app - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/app is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Middleware for for Application's resize functionality + * @private + * @class + */ + var ResizePlugin = /** @class */ (function () { + function ResizePlugin() { + } + /** + * Initialize the plugin with scope of application instance + * @static + * @private + * @param {object} [options] - See application options + */ + ResizePlugin.init = function (options) { + var _this = this; + Object.defineProperty(this, 'resizeTo', + /** + * The HTML element or window to automatically resize the + * renderer's view element to match width and height. + * @member {Window|HTMLElement} + * @name resizeTo + * @memberof PIXI.Application# + */ + { + set: function (dom) { + globalThis.removeEventListener('resize', this.queueResize); + this._resizeTo = dom; + if (dom) { + globalThis.addEventListener('resize', this.queueResize); + this.resize(); + } + }, + get: function () { + return this._resizeTo; + }, + }); + /** + * Resize is throttled, so it's safe to call this multiple times per frame and it'll + * only be called once. + * @memberof PIXI.Application# + * @method queueResize + * @private + */ + this.queueResize = function () { + if (!_this._resizeTo) { + return; + } + _this.cancelResize(); + // // Throttle resize events per raf + _this._resizeId = requestAnimationFrame(function () { return _this.resize(); }); + }; + /** + * Cancel the resize queue. + * @memberof PIXI.Application# + * @method cancelResize + * @private + */ + this.cancelResize = function () { + if (_this._resizeId) { + cancelAnimationFrame(_this._resizeId); + _this._resizeId = null; + } + }; + /** + * Execute an immediate resize on the renderer, this is not + * throttled and can be expensive to call many times in a row. + * Will resize only if `resizeTo` property is set. + * @memberof PIXI.Application# + * @method resize + */ + this.resize = function () { + if (!_this._resizeTo) { + return; + } + // clear queue resize + _this.cancelResize(); + var width; + var height; + // Resize to the window + if (_this._resizeTo === globalThis.window) { + width = globalThis.innerWidth; + height = globalThis.innerHeight; + } + // Resize to other HTML entities + else { + var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight; + width = clientWidth; + height = clientHeight; + } + _this.renderer.resize(width, height); + }; + // On resize + this._resizeId = null; + this._resizeTo = null; + this.resizeTo = options.resizeTo || null; + }; + /** + * Clean up the ticker, scoped to application + * @static + * @private + */ + ResizePlugin.destroy = function () { + globalThis.removeEventListener('resize', this.queueResize); + this.cancelResize(); + this.cancelResize = null; + this.queueResize = null; + this.resizeTo = null; + this.resize = null; + }; + /** @ignore */ + ResizePlugin.extension = exports.ExtensionType.Application; + return ResizePlugin; + }()); + + /*! + * @pixi/settings - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/settings is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$1; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$1 || (ENV$1 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$1; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$1 || (RENDERER_TYPE$1 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$1; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$1 || (BUFFER_BITS$1 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$1; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$1 || (BLEND_MODES$1 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$1; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$1 || (DRAW_MODES$1 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$1; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$1 || (FORMATS$1 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$1; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$1 || (TARGETS$1 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$1; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$1 || (TYPES$1 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$1; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$1 || (SAMPLER_TYPES$1 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$1; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$1 || (SCALE_MODES$1 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$1; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$1 || (WRAP_MODES$1 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$1; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$1 || (MIPMAP_MODES$1 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$1; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$1 || (ALPHA_MODES$1 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$1; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$1 || (CLEAR_MODES$1 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$1; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$1 || (GC_MODES$1 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$1; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$1 || (PRECISION$1 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$1; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$1 || (MASK_TYPES$1 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$1; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$1 || (COLOR_MASK_BITS$1 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$1; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$1 || (MSAA_QUALITY$1 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$1; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$1 || (BUFFER_TYPE$1 = {})); + + var BrowserAdapter = { + /** + * Creates a canvas element of the given size. + * This canvas is created using the browser's native canvas element. + * @param width - width of the canvas + * @param height - height of the canvas + */ + createCanvas: function (width, height) { + var canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + return canvas; + }, + getWebGLRenderingContext: function () { return WebGLRenderingContext; }, + getNavigator: function () { return navigator; }, + getBaseUrl: function () { var _a; return ((_a = document.baseURI) !== null && _a !== void 0 ? _a : window.location.href); }, + fetch: function (url, options) { return fetch(url, options); }, + }; + + var appleIphone = /iPhone/i; + var appleIpod = /iPod/i; + var appleTablet = /iPad/i; + var appleUniversal = /\biOS-universal(?:.+)Mac\b/i; + var androidPhone = /\bAndroid(?:.+)Mobile\b/i; + var androidTablet = /Android/i; + var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; + var amazonTablet = /Silk/i; + var windowsPhone = /Windows Phone/i; + var windowsTablet = /\bWindows(?:.+)ARM\b/i; + var otherBlackBerry = /BlackBerry/i; + var otherBlackBerry10 = /BB10/i; + var otherOpera = /Opera Mini/i; + var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i; + var otherFirefox = /Mobile(?:.+)Firefox\b/i; + var isAppleTabletOnIos13 = function (navigator) { + return (typeof navigator !== 'undefined' && + navigator.platform === 'MacIntel' && + typeof navigator.maxTouchPoints === 'number' && + navigator.maxTouchPoints > 1 && + typeof MSStream === 'undefined'); + }; + function createMatch(userAgent) { + return function (regex) { return regex.test(userAgent); }; + } + function isMobile$1(param) { + var nav = { + userAgent: '', + platform: '', + maxTouchPoints: 0 + }; + if (!param && typeof navigator !== 'undefined') { + nav = { + userAgent: navigator.userAgent, + platform: navigator.platform, + maxTouchPoints: navigator.maxTouchPoints || 0 + }; + } + else if (typeof param === 'string') { + nav.userAgent = param; + } + else if (param && param.userAgent) { + nav = { + userAgent: param.userAgent, + platform: param.platform, + maxTouchPoints: param.maxTouchPoints || 0 + }; + } + var userAgent = nav.userAgent; + var tmp = userAgent.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + tmp = userAgent.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + var match = createMatch(userAgent); + var result = { + apple: { + phone: match(appleIphone) && !match(windowsPhone), + ipod: match(appleIpod), + tablet: !match(appleIphone) && + (match(appleTablet) || isAppleTabletOnIos13(nav)) && + !match(windowsPhone), + universal: match(appleUniversal), + device: (match(appleIphone) || + match(appleIpod) || + match(appleTablet) || + match(appleUniversal) || + isAppleTabletOnIos13(nav)) && + !match(windowsPhone) + }, + amazon: { + phone: match(amazonPhone), + tablet: !match(amazonPhone) && match(amazonTablet), + device: match(amazonPhone) || match(amazonTablet) + }, + android: { + phone: (!match(windowsPhone) && match(amazonPhone)) || + (!match(windowsPhone) && match(androidPhone)), + tablet: !match(windowsPhone) && + !match(amazonPhone) && + !match(androidPhone) && + (match(amazonTablet) || match(androidTablet)), + device: (!match(windowsPhone) && + (match(amazonPhone) || + match(amazonTablet) || + match(androidPhone) || + match(androidTablet))) || + match(/\bokhttp\b/i) + }, + windows: { + phone: match(windowsPhone), + tablet: match(windowsTablet), + device: match(windowsPhone) || match(windowsTablet) + }, + other: { + blackberry: match(otherBlackBerry), + blackberry10: match(otherBlackBerry10), + opera: match(otherOpera), + firefox: match(otherFirefox), + chrome: match(otherChrome), + device: match(otherBlackBerry) || + match(otherBlackBerry10) || + match(otherOpera) || + match(otherFirefox) || + match(otherChrome) + }, + any: false, + phone: false, + tablet: false + }; + result.any = + result.apple.device || + result.android.device || + result.windows.device || + result.other.device; + result.phone = + result.apple.phone || result.android.phone || result.windows.phone; + result.tablet = + result.apple.tablet || result.android.tablet || result.windows.tablet; + return result; + } + + var isMobile = isMobile$1(globalThis.navigator); + + /** + * Uploading the same buffer multiple times in a single frame can cause performance issues. + * Apparent on iOS so only check for that at the moment + * This check may become more complex if this issue pops up elsewhere. + * @private + * @returns {boolean} `true` if the same buffer may be uploaded more than once. + */ + function canUploadSameBuffer() { + return !isMobile.apple.device; + } + + /** + * The maximum recommended texture units to use. + * In theory the bigger the better, and for desktop we'll use as many as we can. + * But some mobile devices slow down if there is to many branches in the shader. + * So in practice there seems to be a sweet spot size that varies depending on the device. + * + * In v4, all mobile devices were limited to 4 texture units because for this. + * In v5, we allow all texture units to be used on modern Apple or Android devices. + * @private + * @param {number} max + * @returns {number} The maximum recommended texture units to use. + */ + function maxRecommendedTextures(max) { + var allowMax = true; + if (isMobile.tablet || isMobile.phone) { + if (isMobile.apple.device) { + var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below iOS 11, which will be older hardware + if (majorVersion < 11) { + allowMax = false; + } + } + } + if (isMobile.android.device) { + var match = (navigator.userAgent).match(/Android\s([0-9.]*)/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below Android 7 (Nougat), which will be older hardware + if (majorVersion < 7) { + allowMax = false; + } + } + } + } + return allowMax ? max : 4; + } + + /** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float precision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio; + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ + var settings = { + /** + * This adapter is used to call methods that are platform dependent. + * For example `document.createElement` only runs on the web but fails in node environments. + * This allows us to support more platforms by abstracting away specific implementations per platform. + * + * By default the adapter is set to work in the browser. However you can create your own + * by implementing the `IAdapter` interface. See `IAdapter` for more information. + * @name ADAPTER + * @memberof PIXI.settings + * @type {PIXI.IAdapter} + * @default PIXI.BrowserAdapter + */ + ADAPTER: BrowserAdapter, + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * @static + * @name MIPMAP_TEXTURES + * @memberof PIXI.settings + * @type {PIXI.MIPMAP_MODES} + * @default PIXI.MIPMAP_MODES.POW2 + */ + MIPMAP_TEXTURES: MIPMAP_MODES$1.POW2, + /** + * Default anisotropic filtering level of textures. + * Usually from 0 to 16 + * @static + * @name ANISOTROPIC_LEVEL + * @memberof PIXI.settings + * @type {number} + * @default 0 + */ + ANISOTROPIC_LEVEL: 0, + /** + * Default resolution / device pixel ratio of the renderer. + * @static + * @name RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + /** + * Default filter resolution. + * @static + * @name FILTER_RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + /** + * Default filter samples. + * @static + * @name FILTER_MULTISAMPLE + * @memberof PIXI.settings + * @type {PIXI.MSAA_QUALITY} + * @default PIXI.MSAA_QUALITY.NONE + */ + FILTER_MULTISAMPLE: MSAA_QUALITY$1.NONE, + /** + * The maximum textures that this device supports. + * @static + * @name SPRITE_MAX_TEXTURES + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: maxRecommendedTextures(32), + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * @static + * @name SPRITE_BATCH_SIZE + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + /** + * The default render options if none are supplied to {@link PIXI.Renderer} + * or {@link PIXI.CanvasRenderer}. + * @static + * @name RENDER_OPTIONS + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} [view=null] - + * @property {boolean} [antialias=false] - + * @property {boolean} [autoDensity=false] - + * @property {boolean} [useContextAlpha=true] - + * @property {number} [backgroundColor=0x000000] - + * @property {number} [backgroundAlpha=1] - + * @property {boolean} [clearBeforeRender=true] - + * @property {boolean} [preserveDrawingBuffer=false] - + * @property {number} [width=800] - + * @property {number} [height=600] - + * @property {boolean} [legacy=false] - + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + autoDensity: false, + backgroundColor: 0x000000, + backgroundAlpha: 1, + useContextAlpha: true, + clearBeforeRender: true, + preserveDrawingBuffer: false, + width: 800, + height: 600, + legacy: false, + }, + /** + * Default Garbage Collection mode. + * @static + * @name GC_MODE + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: GC_MODES$1.AUTO, + /** + * Default Garbage Collection max idle. + * @static + * @name GC_MAX_IDLE + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + /** + * Default Garbage Collection maximum check count. + * @static + * @name GC_MAX_CHECK_COUNT + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + /** + * Default wrap modes that are supported by pixi. + * @static + * @name WRAP_MODE + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: WRAP_MODES$1.CLAMP, + /** + * Default scale mode for textures. + * @static + * @name SCALE_MODE + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: SCALE_MODES$1.LINEAR, + /** + * Default specify float precision in vertex shader. + * @static + * @name PRECISION_VERTEX + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: PRECISION$1.HIGH, + /** + * Default specify float precision in fragment shader. + * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 + * @static + * @name PRECISION_FRAGMENT + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: isMobile.apple.device ? PRECISION$1.HIGH : PRECISION$1.MEDIUM, + /** + * Can we upload the same buffer in a single frame? + * @static + * @name CAN_UPLOAD_SAME_BUFFER + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(), + /** + * Enables bitmap creation before image load. This feature is experimental. + * @static + * @name CREATE_IMAGE_BITMAP + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + CREATE_IMAGE_BITMAP: false, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + ROUND_PIXELS: false, + }; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } + + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } + + createCommonjsModule(function (module) { + + var has = Object.prototype.hasOwnProperty + , prefix = '~'; + + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) { prefix = false; } + } + + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; } + else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); } + else { emitter._events[evt] = [emitter._events[evt], listener]; } + + return emitter; + } + + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) { emitter._events = new Events(); } + else { delete emitter._events[evt]; } + } + + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) { return names; } + + for (name in (events = this._events)) { + if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); } + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; + }; + + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) { return []; } + if (handlers.fn) { return [handlers.fn]; } + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; + }; + + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) { return 0; } + if (listeners.fn) { return 1; } + return listeners.length; + }; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var arguments$1 = arguments; + + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) { return false; } + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); } + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments$1[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); } + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments$1[j]; + } } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; + }; + + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) { return this; } + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; } + else { clearEvent(this, evt); } + } + + return this; + }; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { clearEvent(this, evt); } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; + + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; + + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; + + // + // Expose the module. + // + { + module.exports = EventEmitter; + } + }); + + createCommonjsModule(function (module, exports) { + (function(root) { + + /** Detect free variables */ + var freeExports = exports && + !exports.nodeType && exports; + var freeModule = module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + + }(commonjsGlobal)); + }); + + // Copyright Joyent, Inc. and other Node contributors. + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var decode = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }; + + // Copyright Joyent, Inc. and other Node contributors. + + var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + }; + + var encode = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) { return ''; } + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + }; + + createCommonjsModule(function (module, exports) { + + exports.decode = exports.parse = decode; + exports.encode = exports.stringify = encode; + }); + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV || (ENV = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE || (RENDERER_TYPE = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS || (BUFFER_BITS = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES || (BLEND_MODES = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES || (DRAW_MODES = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS || (FORMATS = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS || (TARGETS = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES || (TYPES = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES || (SAMPLER_TYPES = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES || (SCALE_MODES = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES || (WRAP_MODES = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES || (MIPMAP_MODES = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES || (ALPHA_MODES = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES || (CLEAR_MODES = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES || (GC_MODES = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION || (PRECISION = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES || (MASK_TYPES = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS || (COLOR_MASK_BITS = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY || (MSAA_QUALITY = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE || (BUFFER_TYPE = {})); + + /*! + * @pixi/utils - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/utils is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * The prefix that denotes a URL is for a retina asset. + * @static + * @name RETINA_PREFIX + * @memberof PIXI.settings + * @type {RegExp} + * @default /@([0-9\.]+)x/ + * @example `@2x` + */ + settings.RETINA_PREFIX = /@([0-9\.]+)x/; + /** + * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. + * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when + * using WebGL. + * + * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible. + * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the + * browser. + * + * If your application requires high performance rendering, you may wish to set this to false. + * We recommend one of two options if you decide to set this flag to false: + * + * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is + * not supported. + * + * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS + * renderer, and show an error message to the user if the function returns false, explaining that their device & browser + * combination does not support high performance WebGL. + * This is a much better strategy than trying to create a PixiJS renderer and finding it then fails. + * @static + * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false; + + /** + * Corrects PixiJS blend, takes premultiplied alpha into account + * @memberof PIXI.utils + * @function mapPremultipliedBlendModes + * @private + * @returns {Array} Mapped modes. + */ + function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL; + pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD; + pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN; + npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM; + npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM; + npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM; + var array = []; + array.push(npm); + array.push(pm); + return array; + } + /** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @constant premultiplyBlendMode + * @type {Array} + */ + mapPremultipliedBlendModes(); + + // A map of warning messages already fired + var warnings = {}; + /** + * Helper for warning developers about deprecated features & settings. + * A stack track for warnings is given; useful for tracking-down where + * deprecated methods/properties/classes are being used within the code. + * @memberof PIXI.utils + * @function deprecation + * @param {string} version - The version where the feature became deprecated + * @param {string} message - Message should include what is deprecated, where, and the new solution + * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack + * this is mostly to ignore internal deprecation calls. + */ + function deprecation(version, message, ignoreDepth) { + if (ignoreDepth === void 0) { ignoreDepth = 3; } + // Ignore duplicat + if (warnings[message]) { + return; + } + /* eslint-disable no-console */ + var stack = new Error().stack; + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + } + else { + // chop off the stack trace which includes PixiJS internal calls + stack = stack.split('\n').splice(ignoreDepth).join('\n'); + if (console.groupCollapsed) { + console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); + console.warn(stack); + console.groupEnd(); + } + else { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + console.warn(stack); + } + } + /* eslint-enable no-console */ + warnings[message] = true; + } + + /** + * Creates a Canvas element of the given size to be used as a target for rendering to. + * @class + * @memberof PIXI.utils + */ + /** @class */ ((function () { + /** + * @param width - the width for the newly created canvas + * @param height - the height for the newly created canvas + * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + this.canvas = settings.ADAPTER.createCanvas(); + this.context = this.canvas.getContext('2d'); + this.resolution = resolution || settings.RESOLUTION; + this.resize(width, height); + } + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * @private + */ + CanvasRenderTarget.prototype.clear = function () { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + /** + * Resizes the canvas to the specified width and height. + * @param desiredWidth - the desired width of the canvas + * @param desiredHeight - the desired height of the canvas + */ + CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) { + this.canvas.width = Math.round(desiredWidth * this.resolution); + this.canvas.height = Math.round(desiredHeight * this.resolution); + }; + /** Destroys this canvas. */ + CanvasRenderTarget.prototype.destroy = function () { + this.context = null; + this.canvas = null; + }; + Object.defineProperty(CanvasRenderTarget.prototype, "width", { + /** + * The width of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.width; + }, + set: function (val) { + this.canvas.width = Math.round(val); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CanvasRenderTarget.prototype, "height", { + /** + * The height of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.height; + }, + set: function (val) { + this.canvas.height = Math.round(val); + }, + enumerable: false, + configurable: true + }); + return CanvasRenderTarget; + })()); + + /** + * Convenience class to create a new PIXI application. + * + * This class automatically creates the renderer, ticker and root container. + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.from('something.png')); + * @class + * @memberof PIXI + */ + var Application = /** @class */ (function () { + /** + * @param {object} [options] - The optional renderer parameters. + * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction. + * **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set + * options.sharedTicker to true in case that it is already started. Stop it by your own. + * @param {number} [options.width=800] - The width of the renderers view. + * @param {number} [options.height=600] - The height of the renderers view. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. + * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the WebGL context. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this + * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise + * it is ignored. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card. **(WebGL only)**. + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker. + * If set to false, you cannot register a handler to occur before anything that runs on the shared ticker. + * The system ticker will always run before both the shared ticker and the app ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader. + * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to. + */ + function Application(options) { + var _this = this; + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new Container(); + // The default options + options = Object.assign({ + forceCanvas: false, + }, options); + this.renderer = autoDetectRenderer(options); + // install plugins here + Application._plugins.forEach(function (plugin) { + plugin.init.call(_this, options); + }); + } + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @static + * @param {PIXI.IApplicationPlugin} plugin - Plugin being installed + */ + Application.registerPlugin = function (plugin) { + deprecation('6.5.0', 'Application.registerPlugin() is deprecated, use extensions.add()'); + extensions.add({ + type: exports.ExtensionType.Application, + ref: plugin, + }); + }; + /** Render the current stage. */ + Application.prototype.render = function () { + this.renderer.render(this.stage); + }; + Object.defineProperty(Application.prototype, "view", { + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + get: function () { + return this.renderer.view; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Application.prototype, "screen", { + /** + * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. + * @member {PIXI.Rectangle} + * @readonly + */ + get: function () { + return this.renderer.screen; + }, + enumerable: false, + configurable: true + }); + /** + * Destroy and don't use after this. + * @param {boolean} [removeView=false] - Automatically remove canvas from DOM. + * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy + * method called as well. 'stageOptions' will be passed on to those calls. + * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the texture of the child sprite + * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the base texture of the child sprite + */ + Application.prototype.destroy = function (removeView, stageOptions) { + var _this = this; + // Destroy plugins in the opposite order + // which they were constructed + var plugins = Application._plugins.slice(0); + plugins.reverse(); + plugins.forEach(function (plugin) { + plugin.destroy.call(_this); + }); + this.stage.destroy(stageOptions); + this.stage = null; + this.renderer.destroy(removeView); + this.renderer = null; + }; + /** Collection of installed plugins. */ + Application._plugins = []; + return Application; + }()); + extensions.handleByList(exports.ExtensionType.Application, Application._plugins); + + extensions.add(ResizePlugin); + + /*! + * @pixi/mesh-extras - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mesh-extras is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$1 = function(d, b) { + extendStatics$1 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$1(d, b); + }; + + function __extends$1(d, b) { + extendStatics$1(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * @memberof PIXI + */ + var PlaneGeometry = /** @class */ (function (_super) { + __extends$1(PlaneGeometry, _super); + /** + * @param width - The width of the plane. + * @param height - The height of the plane. + * @param segWidth - Number of horizontal segments. + * @param segHeight - Number of vertical segments. + */ + function PlaneGeometry(width, height, segWidth, segHeight) { + if (width === void 0) { width = 100; } + if (height === void 0) { height = 100; } + if (segWidth === void 0) { segWidth = 10; } + if (segHeight === void 0) { segHeight = 10; } + var _this = _super.call(this) || this; + _this.segWidth = segWidth; + _this.segHeight = segHeight; + _this.width = width; + _this.height = height; + _this.build(); + return _this; + } + /** + * Refreshes plane coordinates + * @private + */ + PlaneGeometry.prototype.build = function () { + var total = this.segWidth * this.segHeight; + var verts = []; + var uvs = []; + var indices = []; + var segmentsX = this.segWidth - 1; + var segmentsY = this.segHeight - 1; + var sizeX = (this.width) / segmentsX; + var sizeY = (this.height) / segmentsY; + for (var i = 0; i < total; i++) { + var x = (i % this.segWidth); + var y = ((i / this.segWidth) | 0); + verts.push(x * sizeX, y * sizeY); + uvs.push(x / segmentsX, y / segmentsY); + } + var totalSub = segmentsX * segmentsY; + for (var i = 0; i < totalSub; i++) { + var xpos = i % segmentsX; + var ypos = (i / segmentsX) | 0; + var value = (ypos * this.segWidth) + xpos; + var value2 = (ypos * this.segWidth) + xpos + 1; + var value3 = ((ypos + 1) * this.segWidth) + xpos; + var value4 = ((ypos + 1) * this.segWidth) + xpos + 1; + indices.push(value, value2, value3, value2, value4, value3); + } + this.buffers[0].data = new Float32Array(verts); + this.buffers[1].data = new Float32Array(uvs); + this.indexBuffer.data = new Uint16Array(indices); + // ensure that the changes are uploaded + this.buffers[0].update(); + this.buffers[1].update(); + this.indexBuffer.update(); + }; + return PlaneGeometry; + }(MeshGeometry)); + + /** + * RopeGeometry allows you to draw a geometry across several points and then manipulate these points. + * + * ```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * const rope = new PIXI.RopeGeometry(100, points); + * ``` + * @memberof PIXI + */ + var RopeGeometry = /** @class */ (function (_super) { + __extends$1(RopeGeometry, _super); + /** + * @param width - The width (i.e., thickness) of the rope. + * @param points - An array of {@link PIXI.Point} objects to construct this rope. + * @param textureScale - By default the rope texture will be stretched to match + * rope length. If textureScale is positive this value will be treated as a scaling + * factor and the texture will preserve its aspect ratio instead. To create a tiling rope + * set baseTexture.wrapMode to {@link PIXI.WRAP_MODES.REPEAT} and use a power of two texture, + * then set textureScale=1 to keep the original texture pixel size. + * In order to reduce alpha channel artifacts provide a larger texture and downsample - + * i.e. set textureScale=0.5 to scale it down twice. + */ + function RopeGeometry(width, points, textureScale) { + if (width === void 0) { width = 200; } + if (textureScale === void 0) { textureScale = 0; } + var _this = _super.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)) || this; + _this.points = points; + _this._width = width; + _this.textureScale = textureScale; + _this.build(); + return _this; + } + Object.defineProperty(RopeGeometry.prototype, "width", { + /** + * The width (i.e., thickness) of the rope. + * @readonly + */ + get: function () { + return this._width; + }, + enumerable: false, + configurable: true + }); + /** Refreshes Rope indices and uvs */ + RopeGeometry.prototype.build = function () { + var points = this.points; + if (!points) + { return; } + var vertexBuffer = this.getBuffer('aVertexPosition'); + var uvBuffer = this.getBuffer('aTextureCoord'); + var indexBuffer = this.getIndex(); + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1) { + return; + } + // if the number of points has changed we will need to recreate the arraybuffers + if (vertexBuffer.data.length / 4 !== points.length) { + vertexBuffer.data = new Float32Array(points.length * 4); + uvBuffer.data = new Float32Array(points.length * 4); + indexBuffer.data = new Uint16Array((points.length - 1) * 6); + } + var uvs = uvBuffer.data; + var indices = indexBuffer.data; + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + var amount = 0; + var prev = points[0]; + var textureWidth = this._width * this.textureScale; + var total = points.length; // - 1; + for (var i = 0; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + if (this.textureScale > 0) { + // calculate pixel distance from previous point + var dx = prev.x - points[i].x; + var dy = prev.y - points[i].y; + var distance = Math.sqrt((dx * dx) + (dy * dy)); + prev = points[i]; + amount += distance / textureWidth; + } + else { + // stretch texture + amount = i / (total - 1); + } + uvs[index] = amount; + uvs[index + 1] = 0; + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + var indexCount = 0; + for (var i = 0; i < total - 1; i++) { + var index = i * 2; + indices[indexCount++] = index; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 3; + } + // ensure that the changes are uploaded + uvBuffer.update(); + indexBuffer.update(); + this.updateVertices(); + }; + /** refreshes vertices of Rope mesh */ + RopeGeometry.prototype.updateVertices = function () { + var points = this.points; + if (points.length < 1) { + return; + } + var lastPoint = points[0]; + var nextPoint; + var perpX = 0; + var perpY = 0; + var vertices = this.buffers[0].data; + var total = points.length; + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } + else { + nextPoint = point; + } + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY)); + var num = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2; + perpX /= perpLength; + perpY /= perpLength; + perpX *= num; + perpY *= num; + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + lastPoint = point; + } + this.buffers[0].update(); + }; + RopeGeometry.prototype.update = function () { + if (this.textureScale > 0) { + this.build(); // we need to update UVs + } + else { + this.updateVertices(); + } + }; + return RopeGeometry; + }(MeshGeometry)); + + /** + * The rope allows you to draw a texture across several points and then manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points); + * ``` + * @memberof PIXI + */ + var SimpleRope = /** @class */ (function (_super) { + __extends$1(SimpleRope, _super); + /** + * @param texture - The texture to use on the rope. + * @param points - An array of {@link PIXI.Point} objects to construct this rope. + * @param {number} textureScale - Optional. Positive values scale rope texture + * keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture + * and downsampling here. If set to zero, texture will be stretched instead. + */ + function SimpleRope(texture, points, textureScale) { + if (textureScale === void 0) { textureScale = 0; } + var _this = this; + var ropeGeometry = new RopeGeometry(texture.height, points, textureScale); + var meshMaterial = new MeshMaterial(texture); + if (textureScale > 0) { + // attempt to set UV wrapping, will fail on non-power of two textures + texture.baseTexture.wrapMode = exports.WRAP_MODES.REPEAT; + } + _this = _super.call(this, ropeGeometry, meshMaterial) || this; + /** + * re-calculate vertices by rope points each frame + * @member {boolean} + */ + _this.autoUpdate = true; + return _this; + } + SimpleRope.prototype._render = function (renderer) { + var geometry = this.geometry; + if (this.autoUpdate || geometry._width !== this.shader.texture.height) { + geometry._width = this.shader.texture.height; + geometry.update(); + } + _super.prototype._render.call(this, renderer); + }; + return SimpleRope; + }(Mesh)); + + /** + * The SimplePlane allows you to draw a texture across several points and then manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points); + * ``` + * @memberof PIXI + */ + var SimplePlane = /** @class */ (function (_super) { + __extends$1(SimplePlane, _super); + /** + * @param texture - The texture to use on the SimplePlane. + * @param verticesX - The number of vertices in the x-axis + * @param verticesY - The number of vertices in the y-axis + */ + function SimplePlane(texture, verticesX, verticesY) { + var _this = this; + var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); + var meshMaterial = new MeshMaterial(Texture.WHITE); + _this = _super.call(this, planeGeometry, meshMaterial) || this; + // lets call the setter to ensure all necessary updates are performed + _this.texture = texture; + _this.autoResize = true; + return _this; + } + /** + * Method used for overrides, to do something in case texture frame was changed. + * Meshes based on plane can override it and change more details based on texture. + */ + SimplePlane.prototype.textureUpdated = function () { + this._textureID = this.shader.texture._updateID; + var geometry = this.geometry; + var _a = this.shader.texture, width = _a.width, height = _a.height; + if (this.autoResize && (geometry.width !== width || geometry.height !== height)) { + geometry.width = this.shader.texture.width; + geometry.height = this.shader.texture.height; + geometry.build(); + } + }; + Object.defineProperty(SimplePlane.prototype, "texture", { + get: function () { + return this.shader.texture; + }, + set: function (value) { + // Track texture same way sprite does. + // For generated meshes like NineSlicePlane it can change the geometry. + // Unfortunately, this method might not work if you directly change texture in material. + if (this.shader.texture === value) { + return; + } + this.shader.texture = value; + this._textureID = -1; + if (value.baseTexture.valid) { + this.textureUpdated(); + } + else { + value.once('update', this.textureUpdated, this); + } + }, + enumerable: false, + configurable: true + }); + SimplePlane.prototype._render = function (renderer) { + if (this._textureID !== this.shader.texture._updateID) { + this.textureUpdated(); + } + _super.prototype._render.call(this, renderer); + }; + SimplePlane.prototype.destroy = function (options) { + this.shader.texture.off('update', this.textureUpdated, this); + _super.prototype.destroy.call(this, options); + }; + return SimplePlane; + }(Mesh)); + + /** + * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments. + * For more robust customization, use {@link PIXI.Mesh}. + * @memberof PIXI + */ + var SimpleMesh = /** @class */ (function (_super) { + __extends$1(SimpleMesh, _super); + /** + * @param texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param drawMode - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function SimpleMesh(texture, vertices, uvs, indices, drawMode) { + if (texture === void 0) { texture = Texture.EMPTY; } + var _this = this; + var geometry = new MeshGeometry(vertices, uvs, indices); + geometry.getBuffer('aVertexPosition').static = false; + var meshMaterial = new MeshMaterial(texture); + _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this; + _this.autoUpdate = true; + return _this; + } + Object.defineProperty(SimpleMesh.prototype, "vertices", { + /** + * Collection of vertices data. + * @type {Float32Array} + */ + get: function () { + return this.geometry.getBuffer('aVertexPosition').data; + }, + set: function (value) { + this.geometry.getBuffer('aVertexPosition').data = value; + }, + enumerable: false, + configurable: true + }); + SimpleMesh.prototype._render = function (renderer) { + if (this.autoUpdate) { + this.geometry.getBuffer('aVertexPosition').update(); + } + _super.prototype._render.call(this, renderer); + }; + return SimpleMesh; + }(Mesh)); + + var DEFAULT_BORDER_SIZE = 10; + /** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
      +   *      A                          B
      +   *    +---+----------------------+---+
      +   *  C | 1 |          2           | 3 |
      +   *    +---+----------------------+---+
      +   *    |   |                      |   |
      +   *    | 4 |          5           | 6 |
      +   *    |   |                      |   |
      +   *    +---+----------------------+---+
      +   *  D | 7 |          8           | 9 |
      +   *    +---+----------------------+---+
      +   *  When changing this objects width and/or height:
      +   *     areas 1 3 7 and 9 will remain unscaled.
      +   *     areas 2 and 8 will be stretched horizontally
      +   *     areas 4 and 6 will be stretched vertically
      +   *     area 5 will be stretched both horizontally and vertically
      +   * 
      + * @memberof PIXI + */ + var NineSlicePlane = /** @class */ (function (_super) { + __extends$1(NineSlicePlane, _super); + /** + * @param texture - The texture to use on the NineSlicePlane. + * @param {number} [leftWidth=10] - size of the left vertical bar (A) + * @param {number} [topHeight=10] - size of the top horizontal bar (C) + * @param {number} [rightWidth=10] - size of the right vertical bar (B) + * @param {number} [bottomHeight=10] - size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + if (leftWidth === void 0) { leftWidth = DEFAULT_BORDER_SIZE; } + if (topHeight === void 0) { topHeight = DEFAULT_BORDER_SIZE; } + if (rightWidth === void 0) { rightWidth = DEFAULT_BORDER_SIZE; } + if (bottomHeight === void 0) { bottomHeight = DEFAULT_BORDER_SIZE; } + var _this = _super.call(this, Texture.WHITE, 4, 4) || this; + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + _this._width = _this._origWidth; + /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + _this._height = _this._origHeight; + _this._leftWidth = leftWidth; + _this._rightWidth = rightWidth; + _this._topHeight = topHeight; + _this._bottomHeight = bottomHeight; + // lets call the setter to ensure all necessary updates are performed + _this.texture = texture; + return _this; + } + NineSlicePlane.prototype.textureUpdated = function () { + this._textureID = this.shader.texture._updateID; + this._refresh(); + }; + Object.defineProperty(NineSlicePlane.prototype, "vertices", { + get: function () { + return this.geometry.getBuffer('aVertexPosition').data; + }, + set: function (value) { + this.geometry.getBuffer('aVertexPosition').data = value; + }, + enumerable: false, + configurable: true + }); + /** Updates the horizontal vertices. */ + NineSlicePlane.prototype.updateHorizontalVertices = function () { + var vertices = this.vertices; + var scale = this._getMinScale(); + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale); + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + /** Updates the vertical vertices. */ + NineSlicePlane.prototype.updateVerticalVertices = function () { + var vertices = this.vertices; + var scale = this._getMinScale(); + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale); + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + /** + * Returns the smaller of a set of vertical and horizontal scale of nine slice corners. + * @returns Smaller number of vertical and horizontal scale. + */ + NineSlicePlane.prototype._getMinScale = function () { + var w = this._leftWidth + this._rightWidth; + var scaleW = this._width > w ? 1.0 : this._width / w; + var h = this._topHeight + this._bottomHeight; + var scaleH = this._height > h ? 1.0 : this._height / h; + var scale = Math.min(scaleW, scaleH); + return scale; + }; + Object.defineProperty(NineSlicePlane.prototype, "width", { + /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + get: function () { + return this._width; + }, + set: function (value) { + this._width = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "height", { + /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + get: function () { + return this._height; + }, + set: function (value) { + this._height = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "leftWidth", { + /** The width of the left column. */ + get: function () { + return this._leftWidth; + }, + set: function (value) { + this._leftWidth = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "rightWidth", { + /** The width of the right column. */ + get: function () { + return this._rightWidth; + }, + set: function (value) { + this._rightWidth = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "topHeight", { + /** The height of the top row. */ + get: function () { + return this._topHeight; + }, + set: function (value) { + this._topHeight = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", { + /** The height of the bottom row. */ + get: function () { + return this._bottomHeight; + }, + set: function (value) { + this._bottomHeight = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + /** Refreshes NineSlicePlane coords. All of them. */ + NineSlicePlane.prototype._refresh = function () { + var texture = this.texture; + var uvs = this.geometry.buffers[1].data; + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth); + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight); + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + this.geometry.buffers[0].update(); + this.geometry.buffers[1].update(); + }; + return NineSlicePlane; + }(SimplePlane)); + + /*! + * @pixi/sprite-animated - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/sprite-animated is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.from(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let animatedSprite = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} + * containing the animation definitions: + * + * ```js + * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; + * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]); + * ... + * } + * ``` + * @memberof PIXI + */ + var AnimatedSprite = /** @class */ (function (_super) { + __extends(AnimatedSprite, _super); + /** + * @param textures - An array of {@link PIXI.Texture} or frame + * objects that make up the animation. + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.Ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + if (autoUpdate === void 0) { autoUpdate = true; } + var _this = _super.call(this, textures[0] instanceof Texture ? textures[0] : textures[0].texture) || this; + _this._textures = null; + _this._durations = null; + _this._autoUpdate = autoUpdate; + _this._isConnectedToTicker = false; + _this.animationSpeed = 1; + _this.loop = true; + _this.updateAnchor = false; + _this.onComplete = null; + _this.onFrameChange = null; + _this.onLoop = null; + _this._currentTime = 0; + _this._playing = false; + _this._previousFrame = null; + _this.textures = textures; + return _this; + } + /** Stops the AnimatedSprite. */ + AnimatedSprite.prototype.stop = function () { + if (!this._playing) { + return; + } + this._playing = false; + if (this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + }; + /** Plays the AnimatedSprite. */ + AnimatedSprite.prototype.play = function () { + if (this._playing) { + return; + } + this._playing = true; + if (this._autoUpdate && !this._isConnectedToTicker) { + Ticker.shared.add(this.update, this, exports.UPDATE_PRIORITY.HIGH); + this._isConnectedToTicker = true; + } + }; + /** + * Stops the AnimatedSprite and goes to a specific frame. + * @param frameNumber - Frame index to stop at. + */ + AnimatedSprite.prototype.gotoAndStop = function (frameNumber) { + this.stop(); + var previousFrame = this.currentFrame; + this._currentTime = frameNumber; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + /** + * Goes to a specific frame and begins playing the AnimatedSprite. + * @param frameNumber - Frame index to start at. + */ + AnimatedSprite.prototype.gotoAndPlay = function (frameNumber) { + var previousFrame = this.currentFrame; + this._currentTime = frameNumber; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + this.play(); + }; + /** + * Updates the object transform for rendering. + * @param deltaTime - Time since last tick. + */ + AnimatedSprite.prototype.update = function (deltaTime) { + if (!this._playing) { + return; + } + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + lag += elapsed / 60 * 1000; + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + var sign = Math.sign(this.animationSpeed * deltaTime); + this._currentTime = Math.floor(this._currentTime); + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + this._currentTime += lag / this._durations[this.currentFrame]; + } + else { + this._currentTime += elapsed; + } + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + if (this.onComplete) { + this.onComplete(); + } + } + else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + if (this.onComplete) { + this.onComplete(); + } + } + else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } + else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + this.updateTexture(); + } + }; + /** Updates the displayed texture to match the current frame index. */ + AnimatedSprite.prototype.updateTexture = function () { + var currentFrame = this.currentFrame; + if (this._previousFrame === currentFrame) { + return; + } + this._previousFrame = currentFrame; + this._texture = this._textures[currentFrame]; + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 0xFFFFFF; + this.uvs = this._texture._uvs.uvsFloat32; + if (this.updateAnchor) { + this._anchor.copyFrom(this._texture.defaultAnchor); + } + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + /** + * Stops the AnimatedSprite and destroys it. + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well. + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well. + */ + AnimatedSprite.prototype.destroy = function (options) { + this.stop(); + _super.prototype.destroy.call(this, options); + this.onComplete = null; + this.onFrameChange = null; + this.onLoop = null; + }; + /** + * A short hand way of creating an AnimatedSprite from an array of frame ids. + * @param frames - The array of frames ids the AnimatedSprite will use as its texture frames. + * @returns - The new animated sprite with the specified frames. + */ + AnimatedSprite.fromFrames = function (frames) { + var textures = []; + for (var i = 0; i < frames.length; ++i) { + textures.push(Texture.from(frames[i])); + } + return new AnimatedSprite(textures); + }; + /** + * A short hand way of creating an AnimatedSprite from an array of image ids. + * @param images - The array of image urls the AnimatedSprite will use as its texture frames. + * @returns The new animate sprite with the specified images as frames. + */ + AnimatedSprite.fromImages = function (images) { + var textures = []; + for (var i = 0; i < images.length; ++i) { + textures.push(Texture.from(images[i])); + } + return new AnimatedSprite(textures); + }; + Object.defineProperty(AnimatedSprite.prototype, "totalFrames", { + /** + * The total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * @readonly + * @default 0 + */ + get: function () { + return this._textures.length; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "textures", { + /** The array of textures used for this AnimatedSprite. */ + get: function () { + return this._textures; + }, + set: function (value) { + if (value[0] instanceof Texture) { + this._textures = value; + this._durations = null; + } + else { + this._textures = []; + this._durations = []; + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this._previousFrame = null; + this.gotoAndStop(0); + this.updateTexture(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "currentFrame", { + /** + * The AnimatedSprites current frame index. + * @readonly + */ + get: function () { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + return currentFrame; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "playing", { + /** + * Indicates if the AnimatedSprite is currently playing. + * @readonly + */ + get: function () { + return this._playing; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "autoUpdate", { + /** Whether to use PIXI.Ticker.shared to auto update animation time. */ + get: function () { + return this._autoUpdate; + }, + set: function (value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + }, + enumerable: false, + configurable: true + }); + return AnimatedSprite; + }(Sprite)); + + extensions.add( + // Install renderer plugins + AccessibilityManager, Extract, InteractionManager, ParticleRenderer, Prepare, BatchRenderer, TilingSpriteRenderer, + // Install loader plugins + BitmapFontLoader, CompressedTextureLoader, DDSLoader, KTXLoader, SpritesheetLoader, + // Install application plugins + TickerPlugin, AppLoaderPlugin); + /** + * This namespace contains WebGL-only display filters that can be applied + * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property. + * + * Since PixiJS only had a handful of built-in filters, additional filters + * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the + * PixiJS Filters repository. + * + * All filters must extend {@link PIXI.Filter}. + * @example + * // Create a new application + * const app = new PIXI.Application(); + * + * // Draw a green rectangle + * const rect = new PIXI.Graphics() + * .beginFill(0x00ff00) + * .drawRect(40, 40, 200, 200); + * + * // Add a blur filter + * rect.filters = [new PIXI.filters.BlurFilter()]; + * + * // Display rectangle + * app.stage.addChild(rect); + * document.body.appendChild(app.view); + * @namespace PIXI.filters + */ + var filters = { + AlphaFilter: AlphaFilter, + BlurFilter: BlurFilter, + BlurFilterPass: BlurFilterPass, + ColorMatrixFilter: ColorMatrixFilter, + DisplacementFilter: DisplacementFilter, + FXAAFilter: FXAAFilter, + NoiseFilter: NoiseFilter, + }; + + exports.AbstractBatchRenderer = AbstractBatchRenderer; + exports.AbstractMultiResource = AbstractMultiResource; + exports.AbstractRenderer = AbstractRenderer; + exports.AccessibilityManager = AccessibilityManager; + exports.AnimatedSprite = AnimatedSprite; + exports.AppLoaderPlugin = AppLoaderPlugin; + exports.Application = Application; + exports.ArrayResource = ArrayResource; + exports.Attribute = Attribute; + exports.BaseImageResource = BaseImageResource; + exports.BasePrepare = BasePrepare; + exports.BaseRenderTexture = BaseRenderTexture; + exports.BaseTexture = BaseTexture; + exports.BatchDrawCall = BatchDrawCall; + exports.BatchGeometry = BatchGeometry; + exports.BatchPluginFactory = BatchPluginFactory; + exports.BatchRenderer = BatchRenderer; + exports.BatchShaderGenerator = BatchShaderGenerator; + exports.BatchSystem = BatchSystem; + exports.BatchTextureArray = BatchTextureArray; + exports.BitmapFont = BitmapFont; + exports.BitmapFontData = BitmapFontData; + exports.BitmapFontLoader = BitmapFontLoader; + exports.BitmapText = BitmapText; + exports.BlobResource = BlobResource; + exports.Bounds = Bounds; + exports.BrowserAdapter = BrowserAdapter$1; + exports.Buffer = Buffer; + exports.BufferResource = BufferResource; + exports.CanvasResource = CanvasResource; + exports.Circle = Circle; + exports.CompressedTextureLoader = CompressedTextureLoader; + exports.CompressedTextureResource = CompressedTextureResource; + exports.Container = Container; + exports.ContextSystem = ContextSystem; + exports.CountLimiter = CountLimiter; + exports.CubeResource = CubeResource; + exports.DDSLoader = DDSLoader; + exports.DEG_TO_RAD = DEG_TO_RAD; + exports.DisplayObject = DisplayObject; + exports.Ellipse = Ellipse; + exports.Extract = Extract; + exports.FORMATS_TO_COMPONENTS = FORMATS_TO_COMPONENTS; + exports.FillStyle = FillStyle; + exports.Filter = Filter; + exports.FilterState = FilterState; + exports.FilterSystem = FilterSystem; + exports.Framebuffer = Framebuffer; + exports.FramebufferSystem = FramebufferSystem; + exports.GLFramebuffer = GLFramebuffer; + exports.GLProgram = GLProgram; + exports.GLTexture = GLTexture; + exports.GRAPHICS_CURVES = GRAPHICS_CURVES; + exports.Geometry = Geometry; + exports.GeometrySystem = GeometrySystem; + exports.Graphics = Graphics; + exports.GraphicsData = GraphicsData; + exports.GraphicsGeometry = GraphicsGeometry; + exports.IGLUniformData = IGLUniformData; + exports.INSTALLED = INSTALLED; + exports.INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL; + exports.ImageBitmapResource = ImageBitmapResource; + exports.ImageResource = ImageResource; + exports.InteractionData = InteractionData; + exports.InteractionEvent = InteractionEvent; + exports.InteractionManager = InteractionManager; + exports.InteractionTrackingData = InteractionTrackingData; + exports.KTXLoader = KTXLoader; + exports.LineStyle = LineStyle; + exports.Loader = Loader; + exports.MaskData = MaskData; + exports.MaskSystem = MaskSystem; + exports.Matrix = Matrix; + exports.Mesh = Mesh; + exports.MeshBatchUvs = MeshBatchUvs; + exports.MeshGeometry = MeshGeometry; + exports.MeshMaterial = MeshMaterial; + exports.NineSlicePlane = NineSlicePlane; + exports.ObjectRenderer = ObjectRenderer; + exports.ObservablePoint = ObservablePoint; + exports.PI_2 = PI_2; + exports.ParticleContainer = ParticleContainer; + exports.ParticleRenderer = ParticleRenderer; + exports.PlaneGeometry = PlaneGeometry; + exports.Point = Point; + exports.Polygon = Polygon; + exports.Prepare = Prepare; + exports.Program = Program; + exports.ProjectionSystem = ProjectionSystem; + exports.Quad = Quad; + exports.QuadUv = QuadUv; + exports.RAD_TO_DEG = RAD_TO_DEG; + exports.Rectangle = Rectangle; + exports.RenderTexture = RenderTexture; + exports.RenderTexturePool = RenderTexturePool; + exports.RenderTextureSystem = RenderTextureSystem; + exports.Renderer = Renderer; + exports.ResizePlugin = ResizePlugin; + exports.Resource = Resource; + exports.RopeGeometry = RopeGeometry; + exports.RoundedRectangle = RoundedRectangle; + exports.Runner = Runner; + exports.SVGResource = SVGResource; + exports.ScissorSystem = ScissorSystem; + exports.Shader = Shader; + exports.ShaderSystem = ShaderSystem; + exports.SimpleMesh = SimpleMesh; + exports.SimplePlane = SimplePlane; + exports.SimpleRope = SimpleRope; + exports.Sprite = Sprite; + exports.SpriteMaskFilter = SpriteMaskFilter; + exports.Spritesheet = Spritesheet; + exports.SpritesheetLoader = SpritesheetLoader; + exports.State = State; + exports.StateSystem = StateSystem; + exports.StencilSystem = StencilSystem; + exports.System = System; + exports.TYPES_TO_BYTES_PER_COMPONENT = TYPES_TO_BYTES_PER_COMPONENT; + exports.TYPES_TO_BYTES_PER_PIXEL = TYPES_TO_BYTES_PER_PIXEL; + exports.TemporaryDisplayObject = TemporaryDisplayObject; + exports.Text = Text; + exports.TextFormat = TextFormat; + exports.TextMetrics = TextMetrics; + exports.TextStyle = TextStyle; + exports.Texture = Texture; + exports.TextureGCSystem = TextureGCSystem; + exports.TextureLoader = TextureLoader; + exports.TextureMatrix = TextureMatrix; + exports.TextureSystem = TextureSystem; + exports.TextureUvs = TextureUvs; + exports.Ticker = Ticker; + exports.TickerPlugin = TickerPlugin; + exports.TilingSprite = TilingSprite; + exports.TilingSpriteRenderer = TilingSpriteRenderer; + exports.TimeLimiter = TimeLimiter; + exports.Transform = Transform; + exports.UniformGroup = UniformGroup; + exports.VERSION = VERSION; + exports.VideoResource = VideoResource; + exports.ViewableBuffer = ViewableBuffer; + exports.XMLFormat = XMLFormat; + exports.XMLStringFormat = XMLStringFormat; + exports.accessibleTarget = accessibleTarget; + exports.autoDetectFormat = autoDetectFormat; + exports.autoDetectRenderer = autoDetectRenderer; + exports.autoDetectResource = autoDetectResource; + exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; + exports.createUBOElements = createUBOElements; + exports.defaultFilterVertex = defaultFilterVertex; + exports.defaultVertex = defaultVertex$1; + exports.extensions = extensions; + exports.filters = filters; + exports.generateProgram = generateProgram; + exports.generateUniformBufferSync = generateUniformBufferSync; + exports.getTestContext = getTestContext; + exports.getUBOData = getUBOData; + exports.graphicsUtils = graphicsUtils; + exports.groupD8 = groupD8; + exports.interactiveTarget = interactiveTarget; + exports.isMobile = isMobile$2; + exports.parseDDS = parseDDS; + exports.parseKTX = parseKTX; + exports.resources = resources; + exports.settings = settings$1; + exports.systems = systems; + exports.uniformParsers = uniformParsers; + exports.utils = utils; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); +//# sourceMappingURL=pixi.js.map diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/ReadMe.txt b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/ReadMe.txt new file mode 100644 index 000000000..59536f277 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/ReadMe.txt @@ -0,0 +1,72 @@ + +============================================================ + +示例模型 +桃濑日和 - PRO + +============================================================ + + 该示例时基于Cubism3.0制作的标准模型素材。 + + 可用于学习变形器的构造以及参数的使用方法。 + 模型的肩部应用了新功能【胶水】。 + + +------------------------------ +素材使用许可 +------------------------------ + + 普通用户以及小规模企业在同意授权协议的情况下可用于商业用途。 + 中/大规模的企业只能用于非公开的内部试用。 + 在使用该素材时,请确认以下的【无偿提供素材使用授权协议】中的“授权类型”、“Live2D原创角色”等的相关内容, + 并必须接受【Live2D Cubism 示例模型的使用授权要求】中的利用条件。 + + 有关许可证的更多信息,请参阅以下页面。 + https://www.live2d.com/zh-CHS/download/sample-data/ + + +------------------------------ +创作者 +------------------------------ + + 插画:Kani Biimu + 模型:Live2D + + +------------------------------ +素材内容 +------------------------------ + + 模型文件(cmo3) ※包含物理模拟的设定 + 动画文件(can3) + 嵌入文件列表(runtime文件夹) + ・模型数据(moc3) + ・动作数据(motion3.json) + ・模型设定文件(model3.json) + ・物理模拟设定文件(physics3.json) + ・姿势设定文件(pose3.json) + ・辅助显示的文件(cdi3.json) + + +------------------------------ +更新记录 +------------------------------ + +【cmo3】 + + hiyori_pro_t11 + 2023年03月08日 修改了部分模型关键点 + + hiyori_pro_t10 + 2021年06月10日 公开 + + +【can3】 + + hiyori_pro_t04 + 2023年03月08日 修改了部分动画关键帧 + + hiyori_pro_t03 + 2021年06月10日 公开 + +  \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/hiyori_pro_t04.can3 b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/hiyori_pro_t04.can3 new file mode 100644 index 000000000..03695b3b9 Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/hiyori_pro_t04.can3 differ diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/hiyori_pro_t11.cmo3 b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/hiyori_pro_t11.cmo3 new file mode 100644 index 000000000..57ea71ebd Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/hiyori_pro_t11.cmo3 differ diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.2048/texture_00.png b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.2048/texture_00.png new file mode 100644 index 000000000..ec1107f2a Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.2048/texture_00.png differ diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.2048/texture_01.png b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.2048/texture_01.png new file mode 100644 index 000000000..2f50d2fd7 Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.2048/texture_01.png differ diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.cdi3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.cdi3.json new file mode 100644 index 000000000..3816ad899 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.cdi3.json @@ -0,0 +1,533 @@ +{ + "Version": 3, + "Parameters": [ + { + "Id": "ParamAngleX", + "GroupId": "ParamGroupFace", + "Name": "角度 X" + }, + { + "Id": "ParamAngleY", + "GroupId": "ParamGroupFace", + "Name": "角度 Y" + }, + { + "Id": "ParamAngleZ", + "GroupId": "ParamGroupFace", + "Name": "角度 Z" + }, + { + "Id": "ParamCheek", + "GroupId": "ParamGroupFace", + "Name": "脸颊泛红" + }, + { + "Id": "ParamEyeLOpen", + "GroupId": "ParamGroupEyes", + "Name": "左眼 开闭" + }, + { + "Id": "ParamEyeLSmile", + "GroupId": "ParamGroupEyes", + "Name": "左眼 微笑" + }, + { + "Id": "ParamEyeROpen", + "GroupId": "ParamGroupEyes", + "Name": "右眼 开闭" + }, + { + "Id": "ParamEyeRSmile", + "GroupId": "ParamGroupEyes", + "Name": "右眼 微笑" + }, + { + "Id": "ParamEyeBallX", + "GroupId": "ParamGroupEyeballs", + "Name": "眼珠 X" + }, + { + "Id": "ParamEyeBallY", + "GroupId": "ParamGroupEyeballs", + "Name": "眼珠 Y" + }, + { + "Id": "ParamBrowLY", + "GroupId": "ParamGroupBrows", + "Name": "左眉 上下" + }, + { + "Id": "ParamBrowRY", + "GroupId": "ParamGroupBrows", + "Name": "右眉 上下" + }, + { + "Id": "ParamBrowLX", + "GroupId": "ParamGroupBrows", + "Name": "左眉 左右" + }, + { + "Id": "ParamBrowRX", + "GroupId": "ParamGroupBrows", + "Name": "右眉 左右" + }, + { + "Id": "ParamBrowLAngle", + "GroupId": "ParamGroupBrows", + "Name": "左眉 角度" + }, + { + "Id": "ParamBrowRAngle", + "GroupId": "ParamGroupBrows", + "Name": "右眉 角度" + }, + { + "Id": "ParamBrowLForm", + "GroupId": "ParamGroupBrows", + "Name": "左眉 变形" + }, + { + "Id": "ParamBrowRForm", + "GroupId": "ParamGroupBrows", + "Name": "右眉 变形" + }, + { + "Id": "ParamMouthForm", + "GroupId": "ParamGroupMouth", + "Name": "嘴 变形" + }, + { + "Id": "ParamMouthOpenY", + "GroupId": "ParamGroupMouth", + "Name": "嘴 开闭" + }, + { + "Id": "ParamBodyAngleX", + "GroupId": "ParamGroupBody", + "Name": "身体的旋转 X" + }, + { + "Id": "ParamBodyAngleY", + "GroupId": "ParamGroupBody", + "Name": "身体的旋转 Y" + }, + { + "Id": "ParamBodyAngleZ", + "GroupId": "ParamGroupBody", + "Name": "身体的旋转 Z" + }, + { + "Id": "ParamBreath", + "GroupId": "ParamGroupBody", + "Name": "呼吸" + }, + { + "Id": "ParamShoulder", + "GroupId": "ParamGroupBody", + "Name": "肩" + }, + { + "Id": "ParamLeg", + "GroupId": "ParamGroupBody", + "Name": "腿" + }, + { + "Id": "ParamArmLA", + "GroupId": "ParamGroupArms", + "Name": "左臂 A" + }, + { + "Id": "ParamArmRA", + "GroupId": "ParamGroupArms", + "Name": "右臂 A" + }, + { + "Id": "ParamArmLB", + "GroupId": "ParamGroupArms", + "Name": "左臂 B" + }, + { + "Id": "ParamArmRB", + "GroupId": "ParamGroupArms", + "Name": "右臂 B" + }, + { + "Id": "ParamHandLB", + "GroupId": "ParamGroupArms", + "Name": "左手B 旋转" + }, + { + "Id": "ParamHandRB", + "GroupId": "ParamGroupArms", + "Name": "右手B 旋转" + }, + { + "Id": "ParamHandL", + "GroupId": "ParamGroupArms", + "Name": "左手" + }, + { + "Id": "ParamHandR", + "GroupId": "ParamGroupArms", + "Name": "右手" + }, + { + "Id": "ParamBustY", + "GroupId": "ParamGroupSway", + "Name": "胸部 摇动" + }, + { + "Id": "ParamHairAhoge", + "GroupId": "ParamGroupSway", + "Name": "头发摇动 呆毛" + }, + { + "Id": "ParamHairFront", + "GroupId": "ParamGroupSway", + "Name": "头发摇动 前" + }, + { + "Id": "ParamHairBack", + "GroupId": "ParamGroupSway", + "Name": "头发摇动 后" + }, + { + "Id": "ParamSideupRibbon", + "GroupId": "ParamGroupSway", + "Name": "发饰的摇动" + }, + { + "Id": "ParamRibbon", + "GroupId": "ParamGroupSway", + "Name": "蝴蝶结的摇动" + }, + { + "Id": "ParamSkirt", + "GroupId": "ParamGroupSway", + "Name": "短裙的摇动" + }, + { + "Id": "ParamSkirt2", + "GroupId": "ParamGroupSway", + "Name": "短裙的上卷" + }, + { + "Id": "Param_Angle_Rotation_1_ArtMesh62", + "GroupId": "ParamGroup2", + "Name": "[0]辫子左" + }, + { + "Id": "Param_Angle_Rotation_2_ArtMesh62", + "GroupId": "ParamGroup2", + "Name": "[1]辫子左" + }, + { + "Id": "Param_Angle_Rotation_3_ArtMesh62", + "GroupId": "ParamGroup2", + "Name": "[2]辫子左" + }, + { + "Id": "Param_Angle_Rotation_4_ArtMesh62", + "GroupId": "ParamGroup2", + "Name": "[3]辫子左" + }, + { + "Id": "Param_Angle_Rotation_5_ArtMesh62", + "GroupId": "ParamGroup2", + "Name": "[4]辫子左" + }, + { + "Id": "Param_Angle_Rotation_6_ArtMesh62", + "GroupId": "ParamGroup2", + "Name": "[5]辫子左" + }, + { + "Id": "Param_Angle_Rotation_7_ArtMesh62", + "GroupId": "ParamGroup2", + "Name": "[6]辫子左" + }, + { + "Id": "Param_Angle_Rotation_1_ArtMesh61", + "GroupId": "ParamGroup", + "Name": "[0]辫子右" + }, + { + "Id": "Param_Angle_Rotation_2_ArtMesh61", + "GroupId": "ParamGroup", + "Name": "[1]辫子右" + }, + { + "Id": "Param_Angle_Rotation_3_ArtMesh61", + "GroupId": "ParamGroup", + "Name": "[2]辫子右" + }, + { + "Id": "Param_Angle_Rotation_4_ArtMesh61", + "GroupId": "ParamGroup", + "Name": "[3]辫子右" + }, + { + "Id": "Param_Angle_Rotation_5_ArtMesh61", + "GroupId": "ParamGroup", + "Name": "[4]辫子右" + }, + { + "Id": "Param_Angle_Rotation_6_ArtMesh61", + "GroupId": "ParamGroup", + "Name": "[5]辫子右" + }, + { + "Id": "Param_Angle_Rotation_7_ArtMesh61", + "GroupId": "ParamGroup", + "Name": "[6]辫子右" + }, + { + "Id": "Param_Angle_Rotation_1_ArtMesh55", + "GroupId": "ParamGroup4", + "Name": "[0]侧发左" + }, + { + "Id": "Param_Angle_Rotation_2_ArtMesh55", + "GroupId": "ParamGroup4", + "Name": "[1]侧发左" + }, + { + "Id": "Param_Angle_Rotation_3_ArtMesh55", + "GroupId": "ParamGroup4", + "Name": "[2]侧发左" + }, + { + "Id": "Param_Angle_Rotation_4_ArtMesh55", + "GroupId": "ParamGroup4", + "Name": "[3]侧发左" + }, + { + "Id": "Param_Angle_Rotation_5_ArtMesh55", + "GroupId": "ParamGroup4", + "Name": "[4]侧发左" + }, + { + "Id": "Param_Angle_Rotation_6_ArtMesh55", + "GroupId": "ParamGroup4", + "Name": "[5]侧发左" + }, + { + "Id": "Param_Angle_Rotation_7_ArtMesh55", + "GroupId": "ParamGroup4", + "Name": "[6]侧发左" + }, + { + "Id": "Param_Angle_Rotation_1_ArtMesh54", + "GroupId": "ParamGroup3", + "Name": "[0]侧发右" + }, + { + "Id": "Param_Angle_Rotation_2_ArtMesh54", + "GroupId": "ParamGroup3", + "Name": "[1]侧发右" + }, + { + "Id": "Param_Angle_Rotation_3_ArtMesh54", + "GroupId": "ParamGroup3", + "Name": "[2]侧发右" + }, + { + "Id": "Param_Angle_Rotation_4_ArtMesh54", + "GroupId": "ParamGroup3", + "Name": "[3]侧发右" + }, + { + "Id": "Param_Angle_Rotation_5_ArtMesh54", + "GroupId": "ParamGroup3", + "Name": "[4]侧发右" + }, + { + "Id": "Param_Angle_Rotation_6_ArtMesh54", + "GroupId": "ParamGroup3", + "Name": "[5]侧发右" + }, + { + "Id": "Param_Angle_Rotation_7_ArtMesh54", + "GroupId": "ParamGroup3", + "Name": "[6]侧发右" + } + ], + "ParameterGroups": [ + { + "Id": "ParamGroupFace", + "GroupId": "", + "Name": "脸" + }, + { + "Id": "ParamGroupEyes", + "GroupId": "", + "Name": "眼睛" + }, + { + "Id": "ParamGroupEyeballs", + "GroupId": "", + "Name": "眼珠" + }, + { + "Id": "ParamGroupBrows", + "GroupId": "", + "Name": "眉毛" + }, + { + "Id": "ParamGroupMouth", + "GroupId": "", + "Name": "嘴" + }, + { + "Id": "ParamGroupBody", + "GroupId": "", + "Name": "身体" + }, + { + "Id": "ParamGroupArms", + "GroupId": "", + "Name": "手臂" + }, + { + "Id": "ParamGroupSway", + "GroupId": "", + "Name": "摇动" + }, + { + "Id": "ParamGroup2", + "GroupId": "", + "Name": "摇动 辫子左" + }, + { + "Id": "ParamGroup", + "GroupId": "", + "Name": "摇动 辫子右" + }, + { + "Id": "ParamGroup4", + "GroupId": "", + "Name": "摇动 侧发左" + }, + { + "Id": "ParamGroup3", + "GroupId": "", + "Name": "摇动 侧发右" + } + ], + "Parts": [ + { + "Id": "PartCore", + "Name": "Core" + }, + { + "Id": "PartCheek", + "Name": "脸颊" + }, + { + "Id": "PartBrow", + "Name": "眉毛" + }, + { + "Id": "PartEye", + "Name": "眼睛" + }, + { + "Id": "PartNose", + "Name": "鼻子" + }, + { + "Id": "PartMouth", + "Name": "嘴" + }, + { + "Id": "PartFace", + "Name": "脸" + }, + { + "Id": "PartEar", + "Name": "耳朵" + }, + { + "Id": "PartHairSide", + "Name": "侧发" + }, + { + "Id": "PartHairFront", + "Name": "前发" + }, + { + "Id": "PartHairBack", + "Name": "后发" + }, + { + "Id": "PartNeck", + "Name": "脖子" + }, + { + "Id": "PartArmA", + "Name": "手臂A" + }, + { + "Id": "PartArmB", + "Name": "手臂B" + }, + { + "Id": "PartBody", + "Name": "身体" + }, + { + "Id": "PartBackground", + "Name": "背景" + }, + { + "Id": "PartSketch", + "Name": "[参考图]" + }, + { + "Id": "PartEyeBall", + "Name": "眼珠" + }, + { + "Id": "ArtMesh55_Skinning", + "Name": "侧发右" + }, + { + "Id": "Part4", + "Name": "侧发左(旋转)" + }, + { + "Id": "ArtMesh54_Skinning", + "Name": "侧发右(蒙皮)" + }, + { + "Id": "Part3", + "Name": "侧发右(旋转)" + }, + { + "Id": "ArtMesh61_Skinning", + "Name": "辫子右(蒙皮)" + }, + { + "Id": "Part", + "Name": "辫子右(旋转)" + }, + { + "Id": "ArtMesh62_Skinning", + "Name": "辫子左(蒙皮)" + }, + { + "Id": "Part2", + "Name": "辫子左(旋转)" + } + ], + "CombinedParameters": [ + [ + "ParamAngleX", + "ParamAngleY" + ], + [ + "ParamMouthForm", + "ParamMouthOpenY" + ] + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.moc3 b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.moc3 new file mode 100644 index 000000000..dc6308538 Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.moc3 differ diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.model3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.model3.json new file mode 100644 index 000000000..f2046763a --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.model3.json @@ -0,0 +1,82 @@ +{ + "Version": 3, + "FileReferences": { + "Moc": "hiyori_pro_t11.moc3", + "Textures": [ + "hiyori_pro_t11.2048/texture_00.png", + "hiyori_pro_t11.2048/texture_01.png" + ], + "Physics": "hiyori_pro_t11.physics3.json", + "Pose": "hiyori_pro_t11.pose3.json", + "DisplayInfo": "hiyori_pro_t11.cdi3.json", + "Motions": { + "Idle": [ + { + "File": "motion/hiyori_m01.motion3.json" + }, + { + "File": "motion/hiyori_m02.motion3.json" + }, + { + "File": "motion/hiyori_m05.motion3.json" + } + ], + "Flick": [ + { + "File": "motion/hiyori_m03.motion3.json" + } + ], + "FlickDown": [ + { + "File": "motion/hiyori_m04.motion3.json" + } + ], + "FlickUp": [ + { + "File": "motion/hiyori_m06.motion3.json" + } + ], + "Tap": [ + { + "File": "motion/hiyori_m07.motion3.json" + }, + { + "File": "motion/hiyori_m08.motion3.json" + } + ], + "Tap@Body": [ + { + "File": "motion/hiyori_m09.motion3.json" + } + ], + "Flick@Body": [ + { + "File": "motion/hiyori_m10.motion3.json" + } + ] + } + }, + "Groups": [ + { + "Target": "Parameter", + "Name": "LipSync", + "Ids": [ + "ParamMouthOpenY" + ] + }, + { + "Target": "Parameter", + "Name": "EyeBlink", + "Ids": [ + "ParamEyeLOpen", + "ParamEyeROpen" + ] + } + ], + "HitAreas": [ + { + "Id": "HitArea", + "Name": "Body" + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.physics3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.physics3.json new file mode 100644 index 000000000..51e724ca6 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.physics3.json @@ -0,0 +1,1569 @@ +{ + "Version": 3, + "Meta": { + "PhysicsSettingCount": 11, + "TotalInputCount": 34, + "TotalOutputCount": 35, + "VertexCount": 58, + "EffectiveForces": { + "Gravity": { + "X": 0, + "Y": -1 + }, + "Wind": { + "X": 0, + "Y": 0 + } + }, + "PhysicsDictionary": [ + { + "Id": "PhysicsSetting1", + "Name": "前发" + }, + { + "Id": "PhysicsSetting2", + "Name": "后发" + }, + { + "Id": "PhysicsSetting3", + "Name": "丝带 头发" + }, + { + "Id": "PhysicsSetting4", + "Name": "短裙 横向摇动" + }, + { + "Id": "PhysicsSetting5", + "Name": "短裙 纵向摇动" + }, + { + "Id": "PhysicsSetting6", + "Name": "丝带 身体" + }, + { + "Id": "PhysicsSetting7", + "Name": "胸 摇动" + }, + { + "Id": "PhysicsSetting8", + "Name": "辫子 右" + }, + { + "Id": "PhysicsSetting9", + "Name": "辫子 左" + }, + { + "Id": "PhysicsSetting10", + "Name": "侧发 右" + }, + { + "Id": "PhysicsSetting11", + "Name": "侧发 左" + } + ] + }, + "PhysicsSettings": [ + { + "Id": "PhysicsSetting1", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamHairFront" + }, + "VertexIndex": 1, + "Scale": 1.522, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 3 + }, + "Mobility": 0.95, + "Delay": 0.9, + "Acceleration": 1.5, + "Radius": 3 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting2", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamHairBack" + }, + "VertexIndex": 1, + "Scale": 2.061, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 15 + }, + "Mobility": 0.95, + "Delay": 0.8, + "Acceleration": 1.5, + "Radius": 15 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -30, + "Default": 0, + "Maximum": 30 + } + } + }, + { + "Id": "PhysicsSetting3", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamSideupRibbon" + }, + "VertexIndex": 1, + "Scale": 1.775, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 10 + }, + "Mobility": 0.9, + "Delay": 0.6, + "Acceleration": 1.5, + "Radius": 10 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -7.8, + "Default": 0, + "Maximum": 8 + } + } + }, + { + "Id": "PhysicsSetting4", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamSkirt" + }, + "VertexIndex": 1, + "Scale": 1.434, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 10 + }, + "Mobility": 0.9, + "Delay": 0.6, + "Acceleration": 1.5, + "Radius": 10 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting5", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleY" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamSkirt2" + }, + "VertexIndex": 1, + "Scale": 1.306, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 10 + }, + "Mobility": 0.8, + "Delay": 0.9, + "Acceleration": 2, + "Radius": 10 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting6", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamRibbon" + }, + "VertexIndex": 1, + "Scale": 1.402, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 10 + }, + "Mobility": 0.9, + "Delay": 0.6, + "Acceleration": 1.5, + "Radius": 10 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10.6 + } + } + }, + { + "Id": "PhysicsSetting7", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleY" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamBustY" + }, + "VertexIndex": 1, + "Scale": 1, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 3 + }, + "Mobility": 0.8, + "Delay": 0.9, + "Acceleration": 1.5, + "Radius": 3 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting8", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_1_ArtMesh61" + }, + "VertexIndex": 1, + "Scale": 10, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_2_ArtMesh61" + }, + "VertexIndex": 2, + "Scale": 20, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_3_ArtMesh61" + }, + "VertexIndex": 3, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_4_ArtMesh61" + }, + "VertexIndex": 4, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_5_ArtMesh61" + }, + "VertexIndex": 5, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_6_ArtMesh61" + }, + "VertexIndex": 6, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_7_ArtMesh61" + }, + "VertexIndex": 7, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 10 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 20 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 30 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 40 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 50 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 60 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 70 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 80 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 90 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 100 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting9", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_1_ArtMesh62" + }, + "VertexIndex": 1, + "Scale": 10, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_2_ArtMesh62" + }, + "VertexIndex": 2, + "Scale": 20, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_3_ArtMesh62" + }, + "VertexIndex": 3, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_4_ArtMesh62" + }, + "VertexIndex": 4, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_5_ArtMesh62" + }, + "VertexIndex": 5, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_6_ArtMesh62" + }, + "VertexIndex": 6, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_7_ArtMesh62" + }, + "VertexIndex": 7, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 10 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 20 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 30 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 40 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 50 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 60 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 70 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 80 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 90 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + }, + { + "Position": { + "X": 0, + "Y": 100 + }, + "Mobility": 0.85, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 10 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting10", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_1_ArtMesh54" + }, + "VertexIndex": 1, + "Scale": 5, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_2_ArtMesh54" + }, + "VertexIndex": 2, + "Scale": 5, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_3_ArtMesh54" + }, + "VertexIndex": 3, + "Scale": 10, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_4_ArtMesh54" + }, + "VertexIndex": 4, + "Scale": 20, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_5_ArtMesh54" + }, + "VertexIndex": 5, + "Scale": 20, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_6_ArtMesh54" + }, + "VertexIndex": 6, + "Scale": 25, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_7_ArtMesh54" + }, + "VertexIndex": 7, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 0.9, + "Delay": 1, + "Acceleration": 1, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 15 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 30 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 45 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 60 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 75 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 90 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 105 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 120 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 135 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 150 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting11", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_1_ArtMesh55" + }, + "VertexIndex": 1, + "Scale": 5, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_2_ArtMesh55" + }, + "VertexIndex": 2, + "Scale": 5, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_3_ArtMesh55" + }, + "VertexIndex": 3, + "Scale": 10, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_4_ArtMesh55" + }, + "VertexIndex": 4, + "Scale": 20, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_5_ArtMesh55" + }, + "VertexIndex": 5, + "Scale": 20, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_6_ArtMesh55" + }, + "VertexIndex": 6, + "Scale": 25, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "Param_Angle_Rotation_7_ArtMesh55" + }, + "VertexIndex": 7, + "Scale": 30, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 0.9, + "Delay": 0.7, + "Acceleration": 1, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 15 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 30 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 45 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 60 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 75 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 90 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 105 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 120 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 135 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + }, + { + "Position": { + "X": 0, + "Y": 150 + }, + "Mobility": 0.9, + "Delay": 0.85, + "Acceleration": 1.2, + "Radius": 15 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.pose3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.pose3.json new file mode 100644 index 000000000..28bda7cc7 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/hiyori_pro_t11.pose3.json @@ -0,0 +1,15 @@ +{ + "Type": "Live2D Pose", + "Groups": [ + [ + { + "Id": "PartArmA", + "Link": [] + }, + { + "Id": "PartArmB", + "Link": [] + } + ] + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m01.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m01.motion3.json new file mode 100644 index 000000000..69d1b28de --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m01.motion3.json @@ -0,0 +1,1063 @@ +{ + "Version": 3, + "Meta": { + "Duration": 4.7, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 29, + "TotalSegmentCount": 135, + "TotalPointCount": 374, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + -8, + 1, + 0.067, + -8, + 0.133, + -8, + 0.2, + -8, + 1, + 0.278, + -8, + 0.356, + -8, + 0.433, + -8, + 1, + 0.556, + -8, + 0.678, + -8, + 0.8, + -8, + 1, + 0.956, + -8, + 1.111, + -8, + 1.267, + -8, + 1, + 1.522, + -8, + 1.778, + 0, + 2.033, + 0, + 1, + 2.122, + 0, + 2.211, + 0, + 2.3, + 0, + 1, + 2.556, + 0, + 2.811, + 9, + 3.067, + 9, + 1, + 3.356, + 9, + 3.644, + 0, + 3.933, + 0, + 1, + 4.067, + 0, + 4.2, + 1, + 4.333, + 1, + 0, + 4.7, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + -5, + 1, + 0.067, + -5, + 0.133, + -5, + 0.2, + -5, + 1, + 0.322, + -5, + 0.444, + 16, + 0.567, + 16, + 1, + 0.711, + 16, + 0.856, + -12, + 1, + -12, + 1, + 1.089, + -12, + 1.178, + 11, + 1.267, + 11, + 1, + 1.356, + 11, + 1.444, + 9.376, + 1.533, + 3, + 1, + 1.611, + -2.579, + 1.689, + -8, + 1.767, + -8, + 1, + 1.856, + -8, + 1.944, + 0, + 2.033, + 0, + 1, + 2.122, + 0, + 2.211, + 0, + 2.3, + 0, + 1, + 2.578, + 0, + 2.856, + -30, + 3.133, + -30, + 1, + 3.278, + -30, + 3.422, + 15, + 3.567, + 15, + 1, + 3.689, + 15, + 3.811, + -9, + 3.933, + -9, + 0, + 4.7, + -9 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + 0, + 0.433, + 0, + 1, + 0.711, + 0, + 0.989, + 0, + 1.267, + 0, + 1, + 1.522, + 0, + 1.778, + 14, + 2.033, + 14, + 1, + 2.178, + 14, + 2.322, + 14, + 2.467, + 14, + 1, + 2.8, + 14, + 3.133, + 16, + 3.467, + 16, + 1, + 3.633, + 16, + 3.8, + -13, + 3.967, + -13, + 1, + 4.111, + -13, + 4.256, + -11.207, + 4.4, + -11.207, + 0, + 4.7, + -11.207 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.556, + 1, + 1.111, + 1, + 1.667, + 1, + 1, + 1.711, + 1, + 1.756, + 0, + 1.8, + 0, + 1, + 1.822, + 0, + 1.844, + 0, + 1.867, + 0, + 1, + 1.911, + 0, + 1.956, + 1, + 2, + 1, + 1, + 2.489, + 1, + 2.978, + 1, + 3.467, + 1, + 1, + 3.511, + 1, + 3.556, + 0, + 3.6, + 0, + 1, + 3.622, + 0, + 3.644, + 0, + 3.667, + 0, + 1, + 3.733, + 0, + 3.8, + 1, + 3.867, + 1, + 0, + 4.7, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.556, + 1, + 1.111, + 1, + 1.667, + 1, + 1, + 1.711, + 1, + 1.756, + 0, + 1.8, + 0, + 1, + 1.822, + 0, + 1.844, + 0, + 1.867, + 0, + 1, + 1.911, + 0, + 1.956, + 1, + 2, + 1, + 1, + 2.489, + 1, + 2.978, + 1, + 3.467, + 1, + 1, + 3.511, + 1, + 3.556, + 0, + 3.6, + 0, + 1, + 3.622, + 0, + 3.644, + 0, + 3.667, + 0, + 1, + 3.733, + 0, + 3.8, + 1, + 3.867, + 1, + 0, + 4.7, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.156, + 0, + 0.311, + -0.02, + 0.467, + -0.02, + 1, + 0.578, + -0.02, + 0.689, + 0, + 0.8, + 0, + 1, + 1.056, + 0, + 1.311, + 0, + 1.567, + 0, + 1, + 1.767, + 0, + 1.967, + -0.131, + 2.167, + -0.15, + 1, + 2.644, + -0.195, + 3.122, + -0.2, + 3.6, + -0.2, + 1, + 3.622, + -0.2, + 3.644, + 0.803, + 3.667, + 0.803, + 0, + 4.7, + 0.803 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.156, + 0, + 0.311, + 0.01, + 0.467, + 0.08, + 1, + 0.578, + 0.13, + 0.689, + 0.21, + 0.8, + 0.21, + 1, + 1.056, + 0.21, + 1.311, + 0.21, + 1.567, + 0.21, + 1, + 1.767, + 0.21, + 1.967, + 0.08, + 2.167, + 0.08, + 1, + 2.644, + 0.08, + 3.122, + 0.086, + 3.6, + 0.1, + 1, + 3.622, + 0.101, + 3.644, + 0.794, + 3.667, + 0.794, + 0, + 4.7, + 0.794 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 1, + 1, + 0.856, + 1, + 1.711, + 1, + 2.567, + 1, + 1, + 2.789, + 1, + 3.011, + 1.145, + 3.233, + 0, + 1, + 3.467, + -1.202, + 3.7, + -6, + 3.933, + -6, + 0, + 4.7, + -6 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + 7, + 0.433, + 7, + 1, + 0.611, + 7, + 0.789, + -4, + 0.967, + -4, + 1, + 1.078, + -4, + 1.189, + 6, + 1.3, + 6, + 1, + 1.433, + 6, + 1.567, + -3, + 1.7, + -3, + 1, + 1.789, + -3, + 1.878, + -1.459, + 1.967, + 0, + 1, + 2.067, + 1.642, + 2.167, + 3.47, + 2.267, + 4, + 1, + 2.367, + 4.53, + 2.467, + 4.312, + 2.567, + 5, + 1, + 2.889, + 7.215, + 3.211, + 10, + 3.533, + 10, + 1, + 3.667, + 10, + 3.8, + 0, + 3.933, + 0, + 1, + 4.067, + 0, + 4.2, + 0, + 4.333, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.822, + 0, + 1.644, + 0, + 2.467, + 0, + 1, + 2.722, + 0, + 2.978, + 5, + 3.233, + 5, + 1, + 3.489, + 5, + 3.744, + -5, + 4, + -5, + 1, + 4.156, + -5, + 4.311, + -3.976, + 4.467, + -3.976, + 0, + 4.7, + -3.976 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0.2, + 0.333, + 0.2, + 1, + 0.422, + 0.2, + 0.511, + -0.1, + 0.6, + -0.1, + 1, + 1.578, + -0.1, + 2.556, + -0.1, + 3.533, + -0.1, + 1, + 3.611, + -0.1, + 3.689, + 0.2, + 3.767, + 0.2, + 1, + 3.989, + 0.2, + 4.211, + -0.9, + 4.433, + -0.9, + 0, + 4.7, + -0.9 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 0, + 4.7, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + -10, + 1, + 0.178, + -10, + 0.356, + -7, + 0.533, + -7, + 1, + 0.7, + -7, + 0.867, + -10, + 1.033, + -10, + 1, + 1.2, + -10, + 1.367, + -8, + 1.533, + -8, + 1, + 1.611, + -8, + 1.689, + -8.746, + 1.767, + -9, + 1, + 2.011, + -9.797, + 2.256, + -10, + 2.5, + -10, + 1, + 2.556, + -10, + 2.611, + -10, + 2.667, + -10, + 1, + 2.789, + -10, + 2.911, + -10, + 3.033, + -10, + 0, + 4.7, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + -10, + 1, + 0.178, + -10, + 0.356, + -7, + 0.533, + -7, + 1, + 0.7, + -7, + 0.867, + -10, + 1.033, + -10, + 1, + 1.2, + -10, + 1.367, + -6, + 1.533, + -6, + 1, + 1.611, + -6, + 1.689, + -6.903, + 1.767, + -7.5, + 1, + 2.011, + -9.377, + 2.256, + -10, + 2.5, + -10, + 1, + 2.567, + -10, + 2.633, + -8.958, + 2.7, + -8.958, + 1, + 2.811, + -8.958, + 2.922, + -10, + 3.033, + -10, + 0, + 4.7, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.144, + 0, + 0.289, + 10, + 0.433, + 10, + 1, + 0.578, + 10, + 0.722, + -10, + 0.867, + -10, + 1, + 0.989, + -10, + 1.111, + 4, + 1.233, + 4, + 1, + 1.322, + 4, + 1.411, + 2.767, + 1.5, + 0, + 1, + 1.611, + -3.459, + 1.722, + -5.351, + 1.833, + -5.351, + 1, + 1.922, + -5.351, + 2.011, + 1.661, + 2.1, + 1.661, + 1, + 2.233, + 1.661, + 2.367, + 0, + 2.5, + 0, + 1, + 2.867, + 0, + 3.233, + 10, + 3.6, + 10, + 1, + 3.722, + 10, + 3.844, + -10, + 3.967, + -10, + 1, + 4.078, + -10, + 4.189, + 6, + 4.3, + 6, + 1, + 4.356, + 6, + 4.411, + 0, + 4.467, + 0, + 0, + 4.7, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 1, + 0, + 4.7, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0, + 0, + 4.7, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m02.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m02.motion3.json new file mode 100644 index 000000000..9a873fc65 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m02.motion3.json @@ -0,0 +1,1428 @@ +{ + "Version": 3, + "Meta": { + "Duration": 5.93, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 31, + "TotalSegmentCount": 190, + "TotalPointCount": 537, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 18, + 1, + 0.211, + 18, + 0.422, + 0, + 0.633, + 0, + 1, + 0.889, + 0, + 1.144, + 22, + 1.4, + 22, + 1, + 1.578, + 22, + 1.756, + 22, + 1.933, + 22, + 1, + 2.1, + 22, + 2.267, + 14.992, + 2.433, + 0, + 1, + 2.6, + -14.992, + 2.767, + -23, + 2.933, + -23, + 1, + 3.244, + -23, + 3.556, + -23, + 3.867, + -23, + 1, + 4.078, + -23, + 4.289, + 0, + 4.5, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + -24, + 1, + 0.211, + -24, + 0.422, + 0, + 0.633, + 0, + 1, + 0.889, + 0, + 1.144, + -18, + 1.4, + -18, + 1, + 1.522, + -18, + 1.644, + -11, + 1.767, + -11, + 1, + 1.822, + -11, + 1.878, + -11, + 1.933, + -11, + 1, + 2.1, + -11, + 2.267, + -3, + 2.433, + -3, + 1, + 2.6, + -3, + 2.767, + -30, + 2.933, + -30, + 1, + 3.133, + -30, + 3.333, + -23, + 3.533, + -23, + 1, + 3.644, + -23, + 3.756, + -23, + 3.867, + -23, + 1, + 3.911, + -23, + 3.956, + -23, + 4, + -23, + 1, + 4.167, + -23, + 4.333, + 0, + 4.5, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.222, + 0, + 0.444, + 0, + 0.667, + 0, + 1, + 0.756, + 0, + 0.844, + 1.707, + 0.933, + 8, + 1, + 1.122, + 21.373, + 1.311, + 30, + 1.5, + 30, + 1, + 1.656, + 30, + 1.811, + 30, + 1.967, + 30, + 1, + 2.289, + 30, + 2.611, + -30, + 2.933, + -30, + 1, + 3.244, + -30, + 3.556, + -30, + 3.867, + -30, + 1, + 4.078, + -30, + 4.289, + -21.337, + 4.5, + 1, + 1, + 4.578, + 9.23, + 4.656, + 17, + 4.733, + 17, + 0, + 5.933, + 17 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 1, + 0, + 5.933, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.333, + 1, + 0.667, + 1, + 1, + 1, + 1, + 1.044, + 1, + 1.089, + 0, + 1.133, + 0, + 1, + 1.156, + 0, + 1.178, + 0, + 1.2, + 0, + 1, + 1.256, + 0, + 1.311, + 1, + 1.367, + 1, + 1, + 1.833, + 1, + 2.3, + 1, + 2.767, + 1, + 1, + 2.867, + 1, + 2.967, + 1.2, + 3.067, + 1.2, + 1, + 3.233, + 1.2, + 3.4, + 1, + 3.567, + 1, + 1, + 3.689, + 1, + 3.811, + 1, + 3.933, + 1, + 1, + 3.978, + 1, + 4.022, + 0, + 4.067, + 0, + 1, + 4.089, + 0, + 4.111, + 0, + 4.133, + 0, + 1, + 4.189, + 0, + 4.244, + 1, + 4.3, + 1, + 1, + 4.4, + 1, + 4.5, + 1, + 4.6, + 1, + 1, + 4.633, + 1, + 4.667, + 0, + 4.7, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0.63, + 1, + 1.433, + 0.63, + 2.867, + 0.6, + 4.3, + 0.6, + 1, + 4.4, + 0.6, + 4.5, + 0.771, + 4.6, + 0.771, + 0, + 5.933, + 0.771 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.333, + 1, + 0.667, + 1, + 1, + 1, + 1, + 1.044, + 1, + 1.089, + 0, + 1.133, + 0, + 1, + 1.156, + 0, + 1.178, + 0, + 1.2, + 0, + 1, + 1.256, + 0, + 1.311, + 1, + 1.367, + 1, + 1, + 1.833, + 1, + 2.3, + 1, + 2.767, + 1, + 1, + 2.867, + 1, + 2.967, + 1.2, + 3.067, + 1.2, + 1, + 3.233, + 1.2, + 3.4, + 1, + 3.567, + 1, + 1, + 3.689, + 1, + 3.811, + 1, + 3.933, + 1, + 1, + 3.978, + 1, + 4.022, + 0, + 4.067, + 0, + 1, + 4.089, + 0, + 4.111, + 0, + 4.133, + 0, + 1, + 4.189, + 0, + 4.244, + 1, + 4.3, + 1, + 1, + 4.4, + 1, + 4.5, + 1, + 4.6, + 1, + 1, + 4.633, + 1, + 4.667, + 0, + 4.7, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0.63, + 1, + 1.433, + 0.63, + 2.867, + 0.6, + 4.3, + 0.6, + 1, + 4.4, + 0.6, + 4.5, + 0.76, + 4.6, + 0.76, + 0, + 5.933, + 0.76 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + -0.002, + 1, + 0.211, + -0.002, + 0.422, + 0, + 0.633, + 0, + 1, + 0.889, + 0, + 1.144, + -0.31, + 1.4, + -0.31, + 1, + 1.578, + -0.31, + 1.756, + -0.31, + 1.933, + -0.31, + 1, + 2.233, + -0.31, + 2.533, + 0.67, + 2.833, + 0.67, + 1, + 3.144, + 0.67, + 3.456, + 0.67, + 3.767, + 0.67, + 1, + 4.011, + 0.67, + 4.256, + 0, + 4.5, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.211, + 0, + 0.422, + 0, + 0.633, + 0, + 1, + 0.889, + 0, + 1.144, + 0.38, + 1.4, + 0.38, + 1, + 1.578, + 0.38, + 1.756, + 0.38, + 1.933, + 0.38, + 1, + 2.233, + 0.38, + 2.533, + 0.46, + 2.833, + 0.46, + 1, + 3.144, + 0.46, + 3.456, + 0.46, + 3.767, + 0.46, + 1, + 4.011, + 0.46, + 4.256, + 0, + 4.5, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.956, + 0, + 1.911, + 0, + 2.867, + 0, + 1, + 2.933, + 0, + 3, + 0.125, + 3.067, + 0.125, + 1, + 3.133, + 0.125, + 3.2, + 0, + 3.267, + 0, + 1, + 3.711, + 0, + 4.156, + 0, + 4.6, + 0, + 1, + 4.667, + 0, + 4.733, + 0.396, + 4.8, + 0.396, + 0, + 5.933, + 0.396 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.956, + 0, + 1.911, + 0, + 2.867, + 0, + 1, + 2.933, + 0, + 3, + 0.125, + 3.067, + 0.125, + 1, + 3.133, + 0.125, + 3.2, + 0, + 3.267, + 0, + 1, + 3.711, + 0, + 4.156, + 0, + 4.6, + 0, + 1, + 4.667, + 0, + 4.733, + 0.417, + 4.8, + 0.417, + 0, + 5.933, + 0.417 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0.03, + 0, + 5.933, + 0.03 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.244, + 0, + 0.489, + 0, + 0.733, + 0, + 1, + 0.778, + 0, + 0.822, + 0.667, + 0.867, + 2, + 1, + 1.044, + 7.333, + 1.222, + 10, + 1.4, + 10, + 1, + 1.533, + 10, + 1.667, + 10, + 1.8, + 10, + 1, + 2.178, + 10, + 2.556, + 6, + 2.933, + 6, + 1, + 3.244, + 6, + 3.556, + 6, + 3.867, + 6, + 1, + 4.189, + 6, + 4.511, + 0, + 4.833, + 0, + 1, + 4.956, + 0, + 5.078, + 1.192, + 5.2, + 1.192, + 1, + 5.322, + 1.192, + 5.444, + 0.013, + 5.567, + 0.013, + 0, + 5.933, + 0.013 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.211, + 0, + 0.422, + 0, + 0.633, + 0, + 1, + 0.667, + 0, + 0.7, + 0, + 0.733, + 0, + 1, + 1.133, + 0, + 1.533, + 0, + 1.933, + 0, + 1, + 2.078, + 0, + 2.222, + 4, + 2.367, + 4, + 1, + 2.556, + 4, + 2.744, + -2.18, + 2.933, + -2.18, + 1, + 3.022, + -2.18, + 3.111, + 0, + 3.2, + 0, + 1, + 3.456, + 0, + 3.711, + -1, + 3.967, + -1, + 1, + 4.067, + -1, + 4.167, + -1.018, + 4.267, + 0, + 1, + 4.333, + 0.679, + 4.4, + 10, + 4.467, + 10, + 1, + 4.567, + 10, + 4.667, + -5, + 4.767, + -5, + 1, + 4.889, + -5, + 5.011, + 0, + 5.133, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.233, + 0, + 0.467, + 0, + 0.7, + 0, + 1, + 0.733, + 0, + 0.767, + 0, + 0.8, + 0, + 1, + 1.278, + 0, + 1.756, + -4, + 2.233, + -4, + 1, + 2.544, + -4, + 2.856, + 8, + 3.167, + 8, + 1, + 3.4, + 8, + 3.633, + 8.008, + 3.867, + 7.985, + 1, + 4.178, + 7.954, + 4.489, + -3, + 4.8, + -3, + 0, + 5.933, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 1, + 0.367, + 1, + 1, + 0.511, + 1, + 0.656, + 0, + 0.8, + 0, + 1, + 1.022, + 0, + 1.244, + 1, + 1.467, + 1, + 1, + 1.689, + 1, + 1.911, + 0, + 2.133, + 0, + 1, + 2.344, + 0, + 2.556, + 1, + 2.767, + 1, + 1, + 2.967, + 1, + 3.167, + 0, + 3.367, + 0, + 1, + 3.578, + 0, + 3.789, + 1, + 4, + 1, + 1, + 4.233, + 1, + 4.467, + 0, + 4.7, + 0, + 1, + 4.9, + 0, + 5.1, + 0, + 5.3, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0, + 1, + 0.456, + 0, + 0.911, + 0.4, + 1.367, + 0.4, + 1, + 1.889, + 0.4, + 2.411, + -1, + 2.933, + -1, + 1, + 3.244, + -1, + 3.556, + -1, + 3.867, + -1, + 0, + 5.933, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 0, + 5.933, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + -8.7, + 1, + 0.289, + -8.7, + 0.578, + -8.7, + 0.867, + -8.7, + 1, + 1, + -8.7, + 1.133, + -10, + 1.267, + -10, + 1, + 1.578, + -10, + 1.889, + -10, + 2.2, + -10, + 1, + 2.444, + -10, + 2.689, + -6.9, + 2.933, + -6.9, + 1, + 3.244, + -6.9, + 3.556, + -6.9, + 3.867, + -6.9, + 1, + 3.989, + -6.9, + 4.111, + -8.3, + 4.233, + -8.3, + 1, + 4.344, + -8.3, + 4.456, + -3, + 4.567, + -3, + 1, + 4.689, + -3, + 4.811, + -4, + 4.933, + -4, + 1, + 5.1, + -4, + 5.267, + -3, + 5.433, + -3, + 0, + 5.933, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + -8.7, + 1, + 0.289, + -8.7, + 0.578, + -8.7, + 0.867, + -8.7, + 1, + 1, + -8.7, + 1.133, + -10, + 1.267, + -10, + 1, + 1.578, + -10, + 1.889, + -10, + 2.2, + -10, + 1, + 2.444, + -10, + 2.689, + -10, + 2.933, + -10, + 1, + 3.244, + -10, + 3.556, + -10, + 3.867, + -10, + 1, + 3.989, + -10, + 4.111, + -9.998, + 4.233, + -7.8, + 1, + 4.344, + -5.802, + 4.456, + 0.03, + 4.567, + 0.03, + 1, + 4.689, + 0.03, + 4.811, + -1, + 4.933, + -1, + 1, + 5.122, + -1, + 5.311, + -0.002, + 5.5, + -0.002, + 0, + 5.933, + -0.002 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandL", + "Segments": [ + 0, + 0, + 1, + 1.067, + 0, + 2.133, + 0, + 3.2, + 0, + 1, + 3.633, + 0, + 4.067, + 1, + 4.5, + 1, + 1, + 4.667, + 1, + 4.833, + -1, + 5, + -1, + 1, + 5.122, + -1, + 5.244, + 0.208, + 5.367, + 0.208, + 0, + 5.933, + 0.208 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandR", + "Segments": [ + 0, + 0, + 1, + 1.067, + 0, + 2.133, + 0, + 3.2, + 0, + 1, + 3.633, + 0, + 4.067, + 1, + 4.5, + 1, + 1, + 4.667, + 1, + 4.833, + -1, + 5, + -1, + 1, + 5.122, + -1, + 5.244, + 0.208, + 5.367, + 0.208, + 0, + 5.933, + 0.208 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.333, + 0, + 0.667, + 0, + 1, + 0, + 1, + 1.133, + 0, + 1.267, + 10, + 1.4, + 10, + 1, + 1.489, + 10, + 1.578, + 2.177, + 1.667, + 2.177, + 1, + 1.789, + 2.177, + 1.911, + 10, + 2.033, + 10, + 1, + 2.289, + 10, + 2.544, + -10, + 2.8, + -10, + 1, + 2.933, + -10, + 3.067, + 7.54, + 3.2, + 7.54, + 1, + 3.344, + 7.54, + 3.489, + 0, + 3.633, + 0, + 1, + 3.911, + 0, + 4.189, + 0, + 4.467, + 0, + 1, + 4.6, + 0, + 4.733, + 10, + 4.867, + 10, + 1, + 4.989, + 10, + 5.111, + -10, + 5.233, + -10, + 1, + 5.322, + -10, + 5.411, + 3.456, + 5.5, + 3.456, + 1, + 5.556, + 3.456, + 5.611, + 0, + 5.667, + 0, + 0, + 5.933, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 1, + 0, + 5.93, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0, + 0, + 5.93, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m03.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m03.motion3.json new file mode 100644 index 000000000..e35ceff7e --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m03.motion3.json @@ -0,0 +1,1295 @@ +{ + "Version": 3, + "Meta": { + "Duration": 4.2, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 31, + "TotalSegmentCount": 169, + "TotalPointCount": 474, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.389, + 0, + 0.611, + 0, + 0.833, + 0, + 1, + 0.933, + 0, + 1.033, + 0, + 1.133, + 0, + 1, + 1.311, + 0, + 1.489, + 0, + 1.667, + 0, + 1, + 1.778, + 0, + 1.889, + -0.268, + 2, + -1, + 1, + 2.089, + -1.585, + 2.178, + -2, + 2.267, + -2, + 0, + 4.2, + -2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.3, + 0, + 0.433, + -18, + 0.567, + -18, + 1, + 0.656, + -18, + 0.744, + 8, + 0.833, + 8, + 1, + 0.933, + 8, + 1.033, + -8, + 1.133, + -8, + 1, + 1.311, + -8, + 1.489, + 10, + 1.667, + 10, + 1, + 1.778, + 10, + 1.889, + -21, + 2, + -21, + 1, + 2.089, + -21, + 2.178, + -3, + 2.267, + -3, + 0, + 4.2, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.289, + 0, + 0.411, + -1, + 0.533, + -1, + 1, + 0.722, + -1, + 0.911, + 17, + 1.1, + 17, + 1, + 1.411, + 17, + 1.722, + -22, + 2.033, + -22, + 1, + 2.244, + -22, + 2.456, + 11, + 2.667, + 11, + 0, + 4.2, + 11 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.2, + 1, + 0.233, + 1, + 0.267, + 1, + 1, + 0.322, + 1, + 0.378, + 0, + 0.433, + 0, + 1, + 0.478, + 0, + 0.522, + 0, + 0.567, + 0, + 1, + 0.644, + 0, + 0.722, + 1, + 0.8, + 1, + 1, + 1.056, + 1, + 1.311, + 0.988, + 1.567, + 0.988, + 1, + 1.789, + 0.988, + 2.011, + 1, + 2.233, + 1, + 1, + 2.267, + 1, + 2.3, + 1, + 2.333, + 1, + 1, + 2.367, + 1, + 2.4, + 0, + 2.433, + 0, + 1, + 2.478, + 0, + 2.522, + 0, + 2.567, + 0, + 1, + 2.622, + 0, + 2.678, + 1, + 2.733, + 1, + 0, + 4.2, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.2, + 1, + 0.233, + 1, + 0.267, + 1, + 1, + 0.322, + 1, + 0.378, + 0, + 0.433, + 0, + 1, + 0.478, + 0, + 0.522, + 0, + 0.567, + 0, + 1, + 0.644, + 0, + 0.722, + 1, + 0.8, + 1, + 1, + 1.056, + 1, + 1.311, + 1, + 1.567, + 1, + 1, + 1.789, + 1, + 2.011, + 1, + 2.233, + 1, + 1, + 2.267, + 1, + 2.3, + 1, + 2.333, + 1, + 1, + 2.367, + 1, + 2.4, + 0, + 2.433, + 0, + 1, + 2.478, + 0, + 2.522, + 0, + 2.567, + 0, + 1, + 2.622, + 0, + 2.678, + 1, + 2.733, + 1, + 0, + 4.2, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 0, + 0.433, + 0, + 1, + 0.478, + 0, + 0.522, + -1, + 0.567, + -1, + 1, + 0.8, + -1, + 1.033, + -1, + 1.267, + -1, + 1, + 1.422, + -1, + 1.578, + 0.583, + 1.733, + 0.583, + 1, + 1.967, + 0.583, + 2.2, + 0.583, + 2.433, + 0.583, + 1, + 2.478, + 0.583, + 2.522, + 0, + 2.567, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 0, + 0.433, + 0, + 1, + 0.478, + 0, + 0.522, + 1, + 0.567, + 1, + 1, + 0.8, + 1, + 1.033, + 1, + 1.267, + 1, + 1, + 1.422, + 1, + 1.578, + 0.75, + 1.733, + 0.75, + 1, + 1.967, + 0.75, + 2.2, + 0.75, + 2.433, + 0.75, + 1, + 2.478, + 0.75, + 2.522, + 0, + 2.567, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + -4, + 0.4, + -4, + 1, + 0.478, + -4, + 0.556, + 10, + 0.633, + 10, + 1, + 0.8, + 10, + 0.967, + -0.386, + 1.133, + -0.386, + 1, + 1.244, + -0.386, + 1.356, + 10, + 1.467, + 10, + 1, + 1.6, + 10, + 1.733, + 0, + 1.867, + 0, + 1, + 2.044, + 0, + 2.222, + 10, + 2.4, + 10, + 1, + 2.444, + 10, + 2.512, + 10, + 2.533, + 9.649, + 1, + 2.7, + 6.854, + 2.867, + -3.526, + 3.033, + -3.526, + 1, + 3.267, + -3.526, + 3.5, + 6.807, + 3.733, + 6.807, + 1, + 3.811, + 6.807, + 3.889, + 6, + 3.967, + 6, + 0, + 4.2, + 6 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + -1, + 0.433, + -1, + 1, + 0.656, + -1, + 0.878, + 6, + 1.1, + 6, + 1, + 1.333, + 6, + 1.567, + -3, + 1.8, + -3, + 1, + 2.256, + -3, + 2.711, + 8, + 3.167, + 8, + 0, + 4.2, + 8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.189, + 0, + 0.378, + 1, + 0.567, + 1, + 1, + 0.733, + 1, + 0.9, + 0, + 1.067, + 0, + 1, + 1.3, + 0, + 1.533, + 1, + 1.767, + 1, + 1, + 2.033, + 1, + 2.3, + 0, + 2.567, + 0, + 1, + 2.778, + 0, + 2.989, + 1, + 3.2, + 1, + 1, + 3.4, + 1, + 3.6, + 0, + 3.8, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 1, + 0.8, + 1, + 1.6, + 1, + 2.4, + 1, + 1, + 2.522, + 1, + 2.644, + 0, + 2.767, + 0, + 1, + 3.011, + 0, + 3.256, + 0.062, + 3.5, + 0.062, + 0, + 4.2, + 0.062 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + -10, + 1, + 0.256, + -10, + 0.511, + 0, + 0.767, + 0, + 1, + 0.889, + 0, + 1.011, + -6.5, + 1.133, + -6.5, + 1, + 1.289, + -6.5, + 1.444, + 0, + 1.6, + 0, + 1, + 1.756, + 0, + 1.911, + -8, + 2.067, + -8, + 1, + 2.344, + -8, + 2.622, + -1.4, + 2.9, + -1.4, + 1, + 2.978, + -1.4, + 3.056, + -1.775, + 3.133, + -2.3, + 1, + 3.211, + -2.825, + 3.289, + -3, + 3.367, + -3, + 1, + 3.433, + -3, + 3.5, + -2.5, + 3.567, + -2.5, + 1, + 3.733, + -2.5, + 3.9, + -3, + 4.067, + -3, + 0, + 4.2, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + -10, + 1, + 0.256, + -10, + 0.511, + 0, + 0.767, + 0, + 1, + 0.867, + 0, + 0.967, + -5.2, + 1.067, + -5.2, + 1, + 1.244, + -5.2, + 1.422, + 0, + 1.6, + 0, + 1, + 1.778, + 0, + 1.956, + -6.3, + 2.133, + -6.3, + 1, + 2.422, + -6.3, + 2.711, + 0.029, + 3, + 0.029, + 1, + 3.144, + 0.029, + 3.289, + 0, + 3.433, + 0, + 1, + 3.5, + 0, + 3.567, + 0, + 3.633, + 0, + 1, + 3.722, + 0, + 3.811, + -0.029, + 3.9, + -0.029, + 0, + 4.2, + -0.029 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandL", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 1, + 0.433, + 1, + 1, + 0.589, + 1, + 0.744, + -1, + 0.9, + -1, + 1, + 1.111, + -1, + 1.322, + 1, + 1.533, + 1, + 1, + 1.733, + 1, + 1.933, + -1, + 2.133, + -1, + 1, + 2.411, + -1, + 2.689, + 1, + 2.967, + 1, + 1, + 3.111, + 1, + 3.256, + -1, + 3.4, + -1, + 1, + 3.5, + -1, + 3.6, + 0.8, + 3.7, + 0.8, + 0, + 4.2, + 0.8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandR", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 1, + 0.433, + 1, + 1, + 0.589, + 1, + 0.744, + -1, + 0.9, + -1, + 1, + 1.111, + -1, + 1.322, + 1, + 1.533, + 1, + 1, + 1.733, + 1, + 1.933, + -1, + 2.133, + -1, + 1, + 2.411, + -1, + 2.689, + 1, + 2.967, + 1, + 1, + 3.111, + 1, + 3.256, + -0.6, + 3.4, + -0.6, + 1, + 3.5, + -0.6, + 3.6, + 0.8, + 3.7, + 0.8, + 0, + 4.2, + 0.8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + -3.127, + 0.367, + -4, + 1, + 0.511, + -5.032, + 0.656, + -5, + 0.8, + -5, + 1, + 0.9, + -5, + 1, + 10, + 1.1, + 10, + 1, + 1.267, + 10, + 1.439, + 10, + 1.6, + 8, + 1, + 1.722, + 6.481, + 1.844, + -10, + 1.967, + -10, + 1, + 2.122, + -10, + 2.31, + -10, + 2.433, + -9.434, + 1, + 2.589, + -8.722, + 2.744, + 10, + 2.9, + 10, + 1, + 3.011, + 10, + 3.122, + -5.646, + 3.233, + -5.646, + 1, + 3.367, + -5.646, + 3.5, + 3.825, + 3.633, + 3.825, + 1, + 3.767, + 3.825, + 3.9, + 0, + 4.033, + 0, + 0, + 4.2, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 1, + 0, + 4.2, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0, + 0, + 4.2, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m04.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m04.motion3.json new file mode 100644 index 000000000..2f91a7948 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m04.motion3.json @@ -0,0 +1,860 @@ +{ + "Version": 3, + "Meta": { + "Duration": 4.43, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 29, + "TotalSegmentCount": 106, + "TotalPointCount": 287, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 1, + 1, + 0.211, + 1, + 0.422, + 0, + 0.633, + 0, + 1, + 0.911, + 0, + 1.189, + 5, + 1.467, + 5, + 1, + 1.689, + 5, + 1.911, + -16, + 2.133, + -16, + 1, + 2.356, + -16, + 2.578, + 13.871, + 2.8, + 13.871, + 1, + 2.956, + 13.871, + 3.111, + 0, + 3.267, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.211, + 0, + 0.422, + 0, + 0.633, + 0, + 1, + 0.911, + 0, + 1.189, + -25, + 1.467, + -25, + 1, + 1.689, + -25, + 1.911, + -15.225, + 2.133, + -11, + 1, + 2.356, + -6.775, + 2.578, + -5.127, + 2.8, + -2.5, + 1, + 2.956, + -0.661, + 3.111, + 0, + 3.267, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.222, + 0, + 0.444, + 0, + 0.667, + 0, + 1, + 0.756, + 0, + 0.844, + -4, + 0.933, + -4, + 1, + 1.122, + -4, + 1.311, + 18, + 1.5, + 18, + 1, + 1.722, + 18, + 1.944, + -14, + 2.167, + -14, + 1, + 2.567, + -14, + 2.967, + -14, + 3.367, + -14, + 1, + 3.511, + -14, + 3.656, + -12, + 3.8, + -12, + 0, + 4.433, + -12 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 1, + 0, + 4.433, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1.2, + 1, + 0.389, + 1.2, + 0.778, + 1.148, + 1.167, + 1, + 1, + 1.211, + 0.983, + 1.256, + 0, + 1.3, + 0, + 1, + 1.322, + 0, + 1.344, + 0, + 1.367, + 0, + 1, + 1.422, + 0, + 1.478, + 1, + 1.533, + 1, + 1, + 1.944, + 1, + 2.356, + 1, + 2.767, + 1, + 1, + 2.811, + 1, + 2.856, + 0, + 2.9, + 0, + 1, + 2.922, + 0, + 2.944, + 0, + 2.967, + 0, + 1, + 3.022, + 0, + 3.078, + 1, + 3.133, + 1, + 0, + 4.433, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1.2, + 1, + 0.389, + 1.2, + 0.778, + 1.148, + 1.167, + 1, + 1, + 1.211, + 0.983, + 1.256, + 0, + 1.3, + 0, + 1, + 1.322, + 0, + 1.344, + 0, + 1.367, + 0, + 1, + 1.422, + 0, + 1.478, + 1, + 1.533, + 1, + 1, + 1.944, + 1, + 2.356, + 1, + 2.767, + 1, + 1, + 2.811, + 1, + 2.856, + 0, + 2.9, + 0, + 1, + 2.922, + 0, + 2.944, + 0, + 2.967, + 0, + 1, + 3.022, + 0, + 3.078, + 1, + 3.133, + 1, + 0, + 4.433, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.211, + 0, + 0.422, + 0, + 0.633, + 0, + 1, + 0.911, + 0, + 1.189, + -0.44, + 1.467, + -0.44, + 1, + 1.689, + -0.44, + 1.911, + 0.79, + 2.133, + 0.79, + 1, + 2.511, + 0.79, + 2.889, + 0, + 3.267, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.211, + 0, + 0.422, + 0, + 0.633, + 0, + 1, + 0.911, + 0, + 1.189, + -1, + 1.467, + -1, + 1, + 1.689, + -1, + 1.911, + -1, + 2.133, + -1, + 1, + 2.511, + -1, + 2.889, + 0, + 3.267, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 1, + 1, + 0.544, + 1, + 1.089, + 1, + 1.633, + 1, + 1, + 1.856, + 1, + 2.078, + 0, + 2.3, + 0, + 1, + 2.5, + 0, + 2.7, + 1, + 2.9, + 1, + 0, + 4.433, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 1, + 1, + 0.544, + 1, + 1.089, + 1, + 1.633, + 1, + 1, + 1.856, + 1, + 2.078, + 0, + 2.3, + 0, + 1, + 2.5, + 0, + 2.7, + 1, + 2.9, + 1, + 0, + 4.433, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + -1, + 0, + 4.433, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + -1, + 0, + 4.433, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.244, + 0, + 0.489, + 0, + 0.733, + 0, + 1, + 0.933, + 0, + 1.133, + -7, + 1.333, + -7, + 1, + 1.644, + -7, + 1.956, + 0, + 2.267, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.244, + 0, + 0.489, + 0, + 0.733, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 2, + 1, + 0.233, + 2, + 0.467, + 0, + 0.7, + 0, + 1, + 0.733, + 0, + 0.767, + 0, + 0.8, + 0, + 1, + 1, + 0, + 1.2, + -4, + 1.4, + -4, + 1, + 1.711, + -4, + 2.022, + 5, + 2.333, + 5, + 1, + 2.567, + 5, + 2.8, + 3.64, + 3.033, + 0, + 1, + 3.133, + -1.56, + 3.233, + -3, + 3.333, + -3, + 1, + 3.467, + -3, + 3.6, + -2, + 3.733, + -2, + 0, + 4.433, + -2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.189, + 0, + 0.378, + 1, + 0.567, + 1, + 1, + 0.711, + 1, + 0.856, + 0, + 1, + 0, + 1, + 1.222, + 0, + 1.444, + 1, + 1.667, + 1, + 1, + 1.889, + 1, + 2.111, + 0, + 2.333, + 0, + 1, + 2.544, + 0, + 2.756, + 1, + 2.967, + 1, + 1, + 3.167, + 1, + 3.367, + 0, + 3.567, + 0, + 0, + 4.433, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0.1, + 1, + 0.467, + 0.1, + 0.933, + 1, + 1.4, + 1, + 1, + 1.844, + 1, + 2.289, + 1, + 2.733, + 1, + 1, + 2.967, + 1, + 3.2, + -1, + 3.433, + -1, + 0, + 4.433, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 0, + 4.433, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + -10, + 0, + 4.433, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + -10, + 0, + 4.433, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.3, + 0, + 0.6, + 0, + 0.9, + -0.012, + 1, + 1.067, + -0.019, + 1.233, + -6.827, + 1.4, + -6.827, + 1, + 1.511, + -6.827, + 1.622, + 7.958, + 1.733, + 7.958, + 1, + 1.944, + 7.958, + 2.156, + -7.565, + 2.367, + -7.565, + 1, + 2.5, + -7.565, + 2.633, + 9.434, + 2.767, + 9.434, + 1, + 2.978, + 9.434, + 3.189, + -8.871, + 3.4, + -8.871, + 1, + 3.5, + -8.871, + 3.6, + 7.588, + 3.7, + 7.588, + 1, + 3.789, + 7.588, + 3.878, + -3.904, + 3.967, + -3.904, + 1, + 4.011, + -3.904, + 4.056, + -0.032, + 4.1, + -0.032, + 0, + 4.433, + -0.032 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 1, + 0, + 4.43, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0, + 0, + 4.43, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m05.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m05.motion3.json new file mode 100644 index 000000000..faea7240d --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m05.motion3.json @@ -0,0 +1,1543 @@ +{ + "Version": 3, + "Meta": { + "Duration": 8.57, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 30, + "TotalSegmentCount": 218, + "TotalPointCount": 622, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.189, + 0, + 0.378, + 1, + 0.567, + 1, + 1, + 1.122, + 1, + 1.678, + 1, + 2.233, + 1, + 1, + 2.533, + 1, + 2.833, + -30, + 3.133, + -30, + 1, + 4.067, + -30, + 5, + -30, + 5.933, + -30, + 1, + 6.322, + -30, + 6.711, + 0, + 7.1, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.189, + 0, + 0.378, + 18, + 0.567, + 18, + 1, + 0.856, + 18, + 1.144, + -9.95, + 1.433, + -9.95, + 1, + 1.522, + -9.95, + 1.611, + -1.589, + 1.7, + -1.589, + 1, + 1.911, + -1.589, + 2.122, + -8.047, + 2.333, + -8.047, + 1, + 2.6, + -8.047, + 2.867, + 30, + 3.133, + 30, + 1, + 3.478, + 30, + 3.822, + 29.529, + 4.167, + 27.847, + 1, + 4.311, + 27.142, + 4.456, + 25.42, + 4.6, + 24.243, + 1, + 4.922, + 21.616, + 5.244, + 20.338, + 5.567, + 20.338, + 1, + 5.789, + 20.338, + 6.011, + 27.397, + 6.233, + 27.397, + 1, + 6.522, + 27.397, + 6.811, + 0, + 7.1, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.189, + 0, + 0.378, + 0, + 0.567, + 0, + 1, + 0.8, + 0, + 1.033, + 25, + 1.267, + 25, + 1, + 1.4, + 25, + 1.533, + 25, + 1.667, + 25, + 1, + 1.878, + 25, + 2.089, + 25, + 2.3, + 25, + 1, + 2.578, + 25, + 2.856, + -30, + 3.133, + -30, + 1, + 4, + -30, + 4.867, + -30, + 5.733, + -30, + 1, + 5.8, + -30, + 5.867, + -30, + 5.933, + -30, + 1, + 6.322, + -30, + 6.711, + 0, + 7.1, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 1, + 2.844, + 0, + 5.089, + 0, + 7.333, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.278, + 1, + 0.556, + 1, + 0.833, + 1, + 1, + 0.867, + 1, + 0.9, + 0, + 0.933, + 0, + 1, + 1.222, + 0, + 1.511, + 0, + 1.8, + 0, + 1, + 1.889, + 0, + 1.978, + 1, + 2.067, + 1, + 1, + 2.322, + 1, + 2.578, + 1, + 2.833, + 1, + 1, + 2.889, + 1, + 2.944, + 0, + 3, + 0, + 1, + 3.022, + 0, + 3.044, + 0, + 3.067, + 0, + 1, + 3.122, + 0, + 3.178, + 1, + 3.233, + 1, + 1, + 3.5, + 1, + 3.767, + 1, + 4.033, + 1, + 1, + 4.089, + 1, + 4.144, + 0, + 4.2, + 0, + 1, + 4.222, + 0, + 4.244, + 0, + 4.267, + 0, + 1, + 4.322, + 0, + 4.378, + 1, + 4.433, + 1, + 1, + 5.133, + 1, + 5.833, + 1, + 6.533, + 1, + 1, + 6.589, + 1, + 6.644, + 0, + 6.7, + 0, + 1, + 6.722, + 0, + 6.744, + 0, + 6.767, + 0, + 1, + 6.822, + 0, + 6.878, + 1, + 6.933, + 1, + 1, + 7.067, + 1, + 7.2, + 1, + 7.333, + 1, + 0, + 8.567, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.278, + 0, + 0.556, + 0.812, + 0.833, + 0.812, + 0, + 8.567, + 0.812 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.278, + 1, + 0.556, + 1, + 0.833, + 1, + 1, + 0.867, + 1, + 0.9, + 0, + 0.933, + 0, + 1, + 1.222, + 0, + 1.511, + 0, + 1.8, + 0, + 1, + 1.889, + 0, + 1.978, + 1, + 2.067, + 1, + 1, + 2.322, + 1, + 2.578, + 1, + 2.833, + 1, + 1, + 2.889, + 1, + 2.944, + 0, + 3, + 0, + 1, + 3.022, + 0, + 3.044, + 0, + 3.067, + 0, + 1, + 3.122, + 0, + 3.178, + 1, + 3.233, + 1, + 1, + 3.5, + 1, + 3.767, + 1, + 4.033, + 1, + 1, + 4.089, + 1, + 4.144, + 0, + 4.2, + 0, + 1, + 4.222, + 0, + 4.244, + 0, + 4.267, + 0, + 1, + 4.322, + 0, + 4.378, + 1, + 4.433, + 1, + 1, + 5.133, + 1, + 5.833, + 1, + 6.533, + 1, + 1, + 6.589, + 1, + 6.644, + 0, + 6.7, + 0, + 1, + 6.722, + 0, + 6.744, + 0, + 6.767, + 0, + 1, + 6.822, + 0, + 6.878, + 1, + 6.933, + 1, + 1, + 7.067, + 1, + 7.2, + 1, + 7.333, + 1, + 0, + 8.567, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.278, + 0, + 0.556, + 0.812, + 0.833, + 0.812, + 1, + 1.967, + 0.812, + 3.1, + 0.8, + 4.233, + 0.8, + 0, + 8.567, + 0.8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + -0.065, + 0.6, + -0.14, + 1, + 0.811, + -0.219, + 1.022, + -0.24, + 1.233, + -0.24, + 1, + 1.367, + -0.24, + 1.5, + -0.24, + 1.633, + -0.24, + 1, + 1.844, + -0.24, + 2.056, + -0.24, + 2.267, + -0.24, + 1, + 2.556, + -0.24, + 2.844, + 0.661, + 3.133, + 0.68, + 1, + 3.5, + 0.704, + 3.867, + 0.7, + 4.233, + 0.7, + 1, + 4.5, + 0.7, + 4.767, + -0.75, + 5.033, + -0.75, + 1, + 5.589, + -0.75, + 6.144, + 0.68, + 6.7, + 0.68, + 1, + 6.789, + 0.68, + 6.878, + 0, + 6.967, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + -0.38, + 0.6, + -0.38, + 1, + 0.811, + -0.38, + 1.022, + 0.21, + 1.233, + 0.21, + 1, + 1.367, + 0.21, + 1.5, + 0.21, + 1.633, + 0.21, + 1, + 1.844, + 0.21, + 2.056, + 0.21, + 2.267, + 0.21, + 1, + 2.556, + 0.21, + 2.844, + -0.33, + 3.133, + -0.33, + 1, + 3.767, + -0.33, + 4.4, + 0.625, + 5.033, + 0.625, + 1, + 5.589, + 0.625, + 6.144, + -0.33, + 6.7, + -0.33, + 1, + 6.789, + -0.33, + 6.878, + 0, + 6.967, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 1, + 0.656, + 0, + 0.711, + 0, + 0.767, + 0, + 1, + 0.822, + 0, + 0.878, + 0.667, + 0.933, + 0.667, + 1, + 1.211, + 0.667, + 1.489, + 0.667, + 1.767, + 0.667, + 1, + 2.011, + 0.667, + 2.256, + 0, + 2.5, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 1, + 0.656, + 0, + 0.711, + 0, + 0.767, + 0, + 1, + 0.822, + 0, + 0.878, + 0.646, + 0.933, + 0.646, + 1, + 1.211, + 0.646, + 1.489, + 0.646, + 1.767, + 0.646, + 1, + 2.011, + 0.646, + 2.256, + 0, + 2.5, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 0, + 0.6, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.133, + 0, + 0.267, + 0, + 0.4, + 0, + 1, + 0.5, + 0, + 0.6, + -1.353, + 0.7, + -1.353, + 1, + 0.933, + -1.353, + 1.167, + 10, + 1.4, + 10, + 1, + 1.544, + 10, + 1.689, + 9.799, + 1.833, + 9.8, + 1, + 2.089, + 9.799, + 2.344, + 9.875, + 2.6, + 9.875, + 1, + 2.944, + 9.875, + 3.289, + -9.599, + 3.633, + -9.599, + 1, + 3.844, + -9.599, + 4.056, + -2.657, + 4.267, + -2.657, + 1, + 4.467, + -2.657, + 4.667, + -9.098, + 4.867, + -9.098, + 1, + 5.144, + -9.098, + 5.422, + -4.812, + 5.7, + -4.812, + 1, + 5.967, + -4.812, + 6.233, + -10, + 6.5, + -10, + 1, + 6.778, + -10, + 7.056, + -1.43, + 7.333, + 0, + 1, + 7.533, + 1.03, + 7.733, + 0.752, + 7.933, + 0.752, + 1, + 8.011, + 0.752, + 8.089, + -0.326, + 8.167, + -0.326, + 0, + 8.567, + -0.326 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 5.421, + 0.6, + 5.421, + 1, + 0.867, + 5.421, + 1.133, + -3.737, + 1.4, + -3.737, + 1, + 1.511, + -3.737, + 1.622, + 0.246, + 1.733, + 0.246, + 1, + 1.933, + 0.246, + 2.133, + 0, + 2.333, + 0, + 1, + 2.389, + 0, + 2.444, + 2.993, + 2.5, + 4, + 1, + 2.711, + 7.827, + 2.922, + 9, + 3.133, + 9, + 1, + 4.256, + 9, + 5.378, + 9, + 6.5, + 9, + 1, + 6.778, + 9, + 7.056, + -5, + 7.333, + -5, + 1, + 7.5, + -5, + 7.667, + 2, + 7.833, + 2, + 1, + 7.9, + 2, + 7.967, + 0, + 8.033, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.2, + 0, + 0.4, + 2, + 0.6, + 2, + 1, + 0.867, + 2, + 1.133, + -10, + 1.4, + -10, + 1, + 1.533, + -10, + 1.667, + -10, + 1.8, + -10, + 1, + 2, + -10, + 2.211, + -10, + 2.4, + -6.566, + 1, + 2.6, + -2.936, + 2.8, + 10, + 3, + 10, + 1, + 3.433, + 10, + 3.867, + -4.436, + 4.3, + -4.436, + 1, + 4.578, + -4.436, + 4.856, + 10, + 5.133, + 10, + 1, + 5.433, + 10, + 5.733, + 0.695, + 6.033, + -4.261, + 1, + 6.211, + -7.197, + 6.389, + -6.792, + 6.567, + -6.792, + 1, + 6.644, + -6.792, + 6.722, + -6.224, + 6.8, + -4.11, + 1, + 6.989, + 1.023, + 7.178, + 4.236, + 7.367, + 4.236, + 1, + 7.689, + 4.236, + 8.011, + 0.025, + 8.333, + 0.025, + 0, + 8.567, + 0.025 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 1, + 0.367, + 1, + 1, + 0.511, + 1, + 0.656, + 0, + 0.8, + 0, + 1, + 1.022, + 0, + 1.244, + 1, + 1.467, + 1, + 1, + 1.689, + 1, + 1.911, + 0, + 2.133, + 0, + 1, + 2.344, + 0, + 2.556, + 1, + 2.767, + 1, + 1, + 2.967, + 1, + 3.167, + 0, + 3.367, + 0, + 1, + 3.578, + 0, + 3.789, + 1, + 4, + 1, + 1, + 4.233, + 1, + 4.467, + 0, + 4.7, + 0, + 1, + 4.9, + 0, + 5.1, + 0, + 5.3, + 0, + 1, + 5.522, + 0, + 5.744, + 1, + 5.967, + 1, + 1, + 6.244, + 1, + 6.522, + 0, + 6.8, + 0, + 1, + 7.022, + 0, + 7.244, + 1, + 7.467, + 1, + 1, + 7.689, + 1, + 7.911, + 0, + 8.133, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 0, + 8.567, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + -10, + 1, + 0.2, + -10, + 0.4, + -10, + 0.6, + -10, + 1, + 0.833, + -10, + 1.067, + -7.083, + 1.3, + -7.083, + 1, + 1.433, + -7.083, + 1.567, + -7.083, + 1.7, + -7.083, + 1, + 1.911, + -7.083, + 2.122, + -10, + 2.333, + -10, + 1, + 3.467, + -10, + 4.6, + -10, + 5.733, + -10, + 1, + 5.8, + -10, + 5.867, + -10, + 5.933, + -10, + 1, + 6.4, + -10, + 6.867, + -10, + 7.333, + -10, + 0, + 8.567, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + -10, + 1, + 0.2, + -10, + 0.4, + -10, + 0.6, + -10, + 1, + 0.833, + -10, + 1.067, + 2.917, + 1.3, + 2.917, + 1, + 1.478, + 2.917, + 1.656, + 3.029, + 1.833, + 2.6, + 1, + 2.033, + 2.117, + 2.233, + -10, + 2.433, + -10, + 1, + 3.533, + -10, + 4.633, + -10, + 5.733, + -10, + 1, + 5.8, + -10, + 5.867, + -10, + 5.933, + -10, + 1, + 6.133, + -10, + 6.333, + -10, + 6.533, + -10, + 1, + 6.8, + -10, + 7.067, + -10, + 7.333, + -10, + 0, + 8.567, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRB", + "Segments": [ + 0, + 0.02, + 0, + 8.567, + 0.02 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.178, + 0, + 0.356, + -10, + 0.533, + -10, + 1, + 0.833, + -10, + 1.133, + 10, + 1.433, + 10, + 1, + 1.567, + 10, + 1.7, + 0, + 1.833, + 0, + 1, + 2.311, + 0, + 2.789, + 10, + 3.267, + 10, + 1, + 3.344, + 10, + 3.422, + 10, + 3.5, + 10, + 1, + 3.633, + 10, + 3.767, + -10, + 3.9, + -10, + 1, + 4.267, + -10, + 4.633, + 7.69, + 5, + 9.705, + 1, + 5.054, + 10, + 5.244, + 10, + 5.367, + 10, + 1, + 5.756, + 10, + 6.144, + -9.975, + 6.533, + -9.975, + 1, + 6.622, + -9.975, + 6.754, + -10, + 6.8, + -9.779, + 1, + 7.033, + -8.654, + 7.267, + 10, + 7.5, + 10, + 1, + 7.7, + 10, + 7.9, + -6.753, + 8.1, + -6.753, + 1, + 8.2, + -6.753, + 8.3, + 0, + 8.4, + 0, + 0, + 8.567, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 1, + 0, + 8.57, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0, + 0, + 8.57, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m06.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m06.motion3.json new file mode 100644 index 000000000..73302c38f --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m06.motion3.json @@ -0,0 +1,1947 @@ +{ + "Version": 3, + "Meta": { + "Duration": 5.37, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 33, + "TotalSegmentCount": 262, + "TotalPointCount": 751, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 1, + 0.333, + 1, + 1, + 0.7, + 1, + 1.067, + 0, + 1.433, + 0, + 1, + 1.711, + 0, + 1.989, + 10, + 2.267, + 10, + 1, + 2.522, + 10, + 2.778, + -7, + 3.033, + -7, + 1, + 3.233, + -7, + 3.433, + 13, + 3.633, + 13, + 1, + 3.811, + 13, + 3.989, + 7.017, + 4.167, + 2, + 1, + 4.244, + -0.195, + 4.322, + 0, + 4.4, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 18, + 0.333, + 18, + 1, + 0.522, + 18, + 0.711, + -9.95, + 0.9, + -9.95, + 1, + 0.956, + -9.95, + 1.011, + -1.664, + 1.067, + -1.589, + 1, + 1.911, + -0.462, + 2.756, + 0, + 3.6, + 0, + 1, + 3.789, + 0, + 3.978, + -18, + 4.167, + -18, + 1, + 4.244, + -18, + 4.322, + -10, + 4.4, + -10, + 0, + 5.367, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.489, + 0, + 0.644, + 25, + 0.8, + 25, + 1, + 0.878, + 25, + 0.956, + 25, + 1.033, + 25, + 1, + 1.233, + 25, + 1.433, + 25, + 1.633, + 25, + 1, + 1.867, + 25, + 2.1, + -5, + 2.333, + -5, + 1, + 2.533, + -5, + 2.733, + 23, + 2.933, + 23, + 1, + 3.189, + 23, + 3.444, + -3, + 3.7, + -3, + 0, + 5.367, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 0, + 0.367, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.178, + 1, + 0.356, + 1, + 0.533, + 1, + 1, + 0.567, + 1, + 0.6, + 0, + 0.633, + 0, + 1, + 0.644, + 0, + 0.656, + 0, + 0.667, + 0, + 1, + 0.7, + 0, + 0.733, + 1, + 0.767, + 1, + 1, + 1.056, + 1, + 1.344, + 1, + 1.633, + 1, + 1, + 1.667, + 1, + 1.7, + 0, + 1.733, + 0, + 1, + 1.744, + 0, + 1.756, + 0, + 1.767, + 0, + 1, + 1.8, + 0, + 1.833, + 1, + 1.867, + 1, + 1, + 2.433, + 1, + 3, + 1, + 3.567, + 1, + 1, + 3.6, + 1, + 3.633, + 0, + 3.667, + 0, + 1, + 3.678, + 0, + 3.689, + 0, + 3.7, + 0, + 1, + 3.733, + 0, + 3.767, + 1, + 3.8, + 1, + 1, + 3.944, + 1, + 4.089, + 1, + 4.233, + 1, + 1, + 4.256, + 1, + 4.278, + 0, + 4.3, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 1.378, + 0, + 2.756, + 0, + 4.133, + 0, + 1, + 4.167, + 0, + 4.2, + 0.833, + 4.233, + 0.833, + 0, + 5.367, + 0.833 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.178, + 1, + 0.356, + 1, + 0.533, + 1, + 1, + 0.567, + 1, + 0.6, + 0, + 0.633, + 0, + 1, + 0.644, + 0, + 0.656, + 0, + 0.667, + 0, + 1, + 0.7, + 0, + 0.733, + 1, + 0.767, + 1, + 1, + 1.056, + 1, + 1.344, + 1, + 1.633, + 1, + 1, + 1.667, + 1, + 1.7, + 0, + 1.733, + 0, + 1, + 1.744, + 0, + 1.756, + 0, + 1.767, + 0, + 1, + 1.8, + 0, + 1.833, + 1, + 1.867, + 1, + 1, + 2.433, + 1, + 3, + 1, + 3.567, + 1, + 1, + 3.6, + 1, + 3.633, + 0, + 3.667, + 0, + 1, + 3.678, + 0, + 3.689, + 0, + 3.7, + 0, + 1, + 3.733, + 0, + 3.767, + 0.998, + 3.8, + 1, + 1, + 3.944, + 1.01, + 4.089, + 1.012, + 4.233, + 1.012, + 1, + 4.256, + 1.012, + 4.278, + 0, + 4.3, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 1.378, + 0, + 2.756, + 0, + 4.133, + 0, + 1, + 4.167, + 0, + 4.2, + 0.823, + 4.233, + 0.823, + 0, + 5.367, + 0.823 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + -0.067, + 0.367, + -0.14, + 1, + 0.5, + -0.22, + 0.633, + -0.24, + 0.767, + -0.24, + 1, + 0.856, + -0.24, + 0.944, + -0.24, + 1.033, + -0.24, + 1, + 1.311, + -0.24, + 1.589, + -0.24, + 1.867, + -0.25, + 1, + 2.022, + -0.256, + 2.178, + -0.51, + 2.333, + -0.51, + 1, + 2.578, + -0.51, + 2.822, + 0.22, + 3.067, + 0.22, + 1, + 3.267, + 0.22, + 3.467, + -0.57, + 3.667, + -0.57, + 1, + 3.911, + -0.57, + 4.156, + -0.28, + 4.4, + -0.28, + 0, + 5.367, + -0.28 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + -0.38, + 0.367, + -0.38, + 1, + 0.5, + -0.38, + 0.633, + 0.21, + 0.767, + 0.21, + 1, + 0.856, + 0.21, + 0.944, + 0.21, + 1.033, + 0.21, + 1, + 1.311, + 0.21, + 1.589, + 0.29, + 1.867, + 0.29, + 1, + 2.022, + 0.29, + 2.178, + 0.21, + 2.333, + 0.21, + 1, + 2.578, + 0.21, + 2.822, + 0.29, + 3.067, + 0.29, + 1, + 3.267, + 0.29, + 3.467, + 0.08, + 3.667, + 0.08, + 1, + 3.911, + 0.08, + 4.156, + 0.13, + 4.4, + 0.13, + 0, + 5.367, + 0.13 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.078, + 0, + 0.156, + -0.008, + 0.233, + 0.021, + 1, + 0.322, + 0.053, + 0.411, + 0.625, + 0.5, + 0.625, + 1, + 0.567, + 0.625, + 0.633, + 0, + 0.7, + 0, + 1, + 1.144, + 0, + 1.589, + 0, + 2.033, + 0, + 1, + 2.089, + 0, + 2.144, + 0.229, + 2.2, + 0.229, + 1, + 2.278, + 0.229, + 2.356, + 0, + 2.433, + 0, + 1, + 2.544, + 0, + 2.656, + 0, + 2.767, + 0, + 1, + 2.822, + 0, + 2.878, + 0.229, + 2.933, + 0.229, + 1, + 3.011, + 0.229, + 3.089, + 0, + 3.167, + 0, + 1, + 3.456, + 0, + 3.744, + 0, + 4.033, + 0, + 1, + 4.133, + 0, + 4.233, + 0.479, + 4.333, + 0.479, + 0, + 5.367, + 0.479 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.078, + 0, + 0.156, + 0, + 0.233, + 0, + 1, + 0.322, + 0, + 0.411, + 0.625, + 0.5, + 0.625, + 1, + 0.567, + 0.625, + 0.633, + 0, + 0.7, + 0, + 1, + 1.144, + 0, + 1.589, + 0.005, + 2.033, + 0.021, + 1, + 2.089, + 0.023, + 2.144, + 0.188, + 2.2, + 0.188, + 1, + 2.278, + 0.188, + 2.356, + 0, + 2.433, + 0, + 1, + 2.544, + 0, + 2.656, + 0.001, + 2.767, + 0.021, + 1, + 2.822, + 0.031, + 2.878, + 0.229, + 2.933, + 0.229, + 1, + 3.011, + 0.229, + 3.089, + 0, + 3.167, + 0, + 1, + 3.456, + 0, + 3.744, + 0, + 4.033, + 0, + 1, + 4.133, + 0, + 4.233, + 0.479, + 4.333, + 0.479, + 0, + 5.367, + 0.479 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.167, + 0, + 0.333, + 0, + 0.5, + 0, + 1, + 1.678, + 0, + 2.856, + 0, + 4.033, + 0, + 1, + 4.133, + 0, + 4.233, + -0.479, + 4.333, + -0.479, + 0, + 5.367, + -0.479 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 0, + 0.367, + 0, + 1, + 1.589, + 0, + 2.811, + 0, + 4.033, + 0, + 1, + 4.133, + 0, + 4.233, + -0.69, + 4.333, + -0.69, + 0, + 5.367, + -0.69 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.167, + 0, + 0.333, + 0, + 0.5, + 0, + 1, + 1.678, + 0, + 2.856, + 0, + 4.033, + 0, + 1, + 4.133, + 0, + 4.233, + 0, + 4.333, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 0, + 0.367, + 0, + 1, + 1.589, + 0, + 2.811, + 0, + 4.033, + 0, + 1, + 4.133, + 0, + 4.233, + 0, + 4.333, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 0, + 0.367, + 0, + 1, + 1.589, + 0, + 2.811, + 0, + 4.033, + 0, + 1, + 4.133, + 0, + 4.233, + 0, + 4.333, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 0, + 0.367, + 0, + 1, + 1.589, + 0, + 2.811, + 0, + 4.033, + 0, + 1, + 4.133, + 0, + 4.233, + 0, + 4.333, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + -10, + 1, + 0.078, + -10, + 0.156, + 0, + 0.233, + 0, + 1, + 0.311, + 0, + 0.389, + -1.353, + 0.467, + -1.353, + 1, + 0.6, + -1.353, + 0.733, + 10, + 0.867, + 10, + 1, + 0.956, + 10, + 1.044, + 9.8, + 1.133, + 9.8, + 1, + 1.233, + 9.8, + 1.333, + 10, + 1.433, + 10, + 1, + 1.667, + 10, + 1.9, + -2.975, + 2.133, + -2.975, + 1, + 2.211, + -2.975, + 2.289, + -2.975, + 2.367, + -2.975, + 1, + 2.522, + -2.975, + 2.678, + 9.025, + 2.833, + 9.025, + 1, + 2.978, + 9.025, + 3.122, + 9.025, + 3.267, + 9.025, + 1, + 3.489, + 9.025, + 3.711, + 2.025, + 3.933, + 2.025, + 0, + 5.367, + 2.025 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 10, + 1, + 0.122, + 10, + 0.244, + 9.141, + 0.367, + 5.421, + 1, + 0.533, + 0.348, + 0.7, + -3.737, + 0.867, + -3.737, + 1, + 0.978, + -3.737, + 1.089, + 2.181, + 1.2, + 2.181, + 1, + 1.3, + 2.181, + 1.4, + 1.948, + 1.5, + 0.298, + 1, + 1.6, + -1.351, + 1.7, + -3.396, + 1.8, + -3.396, + 1, + 1.944, + -3.396, + 2.089, + 4.673, + 2.233, + 4.673, + 1, + 2.378, + 4.673, + 2.522, + -3.858, + 2.667, + -3.858, + 1, + 2.767, + -3.858, + 2.867, + 4.794, + 2.967, + 4.794, + 1, + 3.089, + 4.794, + 3.211, + -3.573, + 3.333, + -3.573, + 1, + 3.533, + -3.573, + 3.733, + 5.269, + 3.933, + 5.269, + 1, + 4.044, + 5.269, + 4.156, + -5.393, + 4.267, + -5.393, + 1, + 4.356, + -5.393, + 4.444, + 0.095, + 4.533, + 0.095, + 0, + 5.367, + 0.095 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 2, + 0.367, + 2, + 1, + 0.533, + 2, + 0.7, + -10, + 0.867, + -10, + 1, + 1.078, + -10, + 1.359, + -10, + 1.5, + -9.975, + 1, + 1.767, + -9.927, + 2.033, + 2.026, + 2.3, + 2.026, + 1, + 2.522, + 2.026, + 2.744, + -9.975, + 2.967, + -9.975, + 1, + 3.322, + -9.975, + 3.678, + -6.592, + 4.033, + 1.8, + 1, + 4.178, + 5.21, + 4.322, + 8, + 4.467, + 8, + 0, + 5.367, + 8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.122, + 0, + 0.244, + 1, + 0.367, + 1, + 1, + 0.511, + 1, + 0.656, + 0, + 0.8, + 0, + 1, + 1.022, + 0, + 1.244, + 1, + 1.467, + 1, + 1, + 1.689, + 1, + 1.911, + 0, + 2.133, + 0, + 1, + 2.344, + 0, + 2.556, + 1, + 2.767, + 1, + 1, + 2.967, + 1, + 3.167, + 0, + 3.367, + 0, + 1, + 3.578, + 0, + 3.789, + 1, + 4, + 1, + 1, + 4.233, + 1, + 4.467, + 0, + 4.7, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0, + 1, + 0.144, + 0, + 0.289, + 1, + 0.433, + 1, + 1, + 0.6, + 1, + 0.767, + 0.049, + 0.933, + -0.1, + 1, + 1.167, + -0.309, + 1.4, + -0.3, + 1.633, + -0.3, + 1, + 1.844, + -0.3, + 2.056, + 0.9, + 2.267, + 0.9, + 1, + 2.411, + 0.9, + 2.556, + -0.22, + 2.7, + -0.22, + 1, + 2.844, + -0.22, + 2.989, + 0.6, + 3.133, + 0.6, + 1, + 3.289, + 0.6, + 3.444, + -0.4, + 3.6, + -0.4, + 1, + 3.7, + -0.4, + 3.8, + 0.5, + 3.9, + 0.5, + 1, + 4.044, + 0.5, + 4.189, + 0.238, + 4.333, + 0, + 1, + 4.444, + -0.183, + 4.556, + -0.2, + 4.667, + -0.2, + 0, + 5.367, + -0.2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 1, + 1.344, + 1, + 2.689, + 1, + 4.033, + 1, + 1, + 4.144, + 1, + 4.256, + 0, + 4.367, + 0, + 1, + 4.578, + 0, + 4.789, + 0.052, + 5, + 0.052, + 0, + 5.367, + 0.052 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLB", + "Segments": [ + 0, + 0, + 1, + 0.1, + 0, + 0.2, + 1.3, + 0.3, + 1.3, + 1, + 0.544, + 1.3, + 0.789, + 0, + 1.033, + 0, + 1, + 1.222, + 0, + 1.411, + 0, + 1.6, + 0, + 1, + 1.811, + 0, + 2.022, + -10, + 2.233, + -10, + 1, + 2.811, + -10, + 3.389, + -10, + 3.967, + -10, + 1, + 4.133, + -10, + 4.3, + -6.458, + 4.467, + -6.458, + 0, + 5.367, + -6.458 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRB", + "Segments": [ + 0, + 0, + 1, + 0.1, + 0, + 0.2, + 1.9, + 0.3, + 1.9, + 1, + 0.544, + 1.9, + 0.789, + 0, + 1.033, + 0, + 1, + 1.222, + 0, + 1.411, + 0, + 1.6, + 0, + 1, + 1.811, + 0, + 2.022, + -10, + 2.233, + -10, + 1, + 2.7, + -10, + 3.167, + -10, + 3.633, + -10, + 1, + 3.744, + -10, + 3.856, + -10, + 3.967, + -10, + 1, + 4.133, + -10, + 4.3, + -5.833, + 4.467, + -5.833, + 0, + 5.367, + -5.833 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandLB", + "Segments": [ + 0, + 0, + 1, + 0.156, + 0, + 0.311, + 0, + 0.467, + 0, + 1, + 0.656, + 0, + 0.844, + 6.25, + 1.033, + 6.25, + 1, + 1.222, + 6.25, + 1.411, + 6.365, + 1.6, + 5.833, + 1, + 1.811, + 5.239, + 2.022, + -4.07, + 2.233, + -4.583, + 1, + 2.367, + -4.907, + 2.5, + -4.792, + 2.633, + -4.792, + 1, + 2.778, + -4.792, + 2.922, + -3.75, + 3.067, + -3.75, + 1, + 3.256, + -3.75, + 3.444, + -6.25, + 3.633, + -6.25, + 1, + 3.756, + -6.25, + 3.878, + -6.419, + 4, + -5.833, + 1, + 4.156, + -5.087, + 4.311, + 9.4, + 4.467, + 9.4, + 1, + 4.533, + 9.4, + 4.6, + 7.1, + 4.667, + 7.1, + 0, + 5.367, + 7.1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandRB", + "Segments": [ + 0, + 0, + 1, + 0.156, + 0, + 0.311, + 0, + 0.467, + 0, + 1, + 0.656, + 0, + 0.844, + 8.064, + 1.033, + 8.333, + 1, + 1.222, + 8.603, + 1.411, + 8.542, + 1.6, + 8.542, + 1, + 1.811, + 8.542, + 2.022, + -5.8, + 2.233, + -7.292, + 1, + 2.367, + -8.234, + 2.5, + -7.917, + 2.633, + -7.917, + 1, + 2.778, + -7.917, + 2.922, + -7.917, + 3.067, + -7.917, + 1, + 3.256, + -7.917, + 3.444, + -8.084, + 3.633, + -8.333, + 1, + 3.756, + -8.494, + 3.878, + -8.542, + 4, + -8.542, + 1, + 4.156, + -8.542, + 4.311, + 10, + 4.467, + 10, + 1, + 4.533, + 10, + 4.6, + 6.8, + 4.667, + 6.8, + 0, + 5.367, + 6.8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandL", + "Segments": [ + 0, + 0, + 1, + 0.144, + 0, + 0.289, + 0.958, + 0.433, + 0.958, + 1, + 0.611, + 0.958, + 0.789, + -1, + 0.967, + -1, + 1, + 1.222, + -1, + 1.478, + 0.4, + 1.733, + 0.4, + 1, + 1.922, + 0.4, + 2.111, + -1, + 2.3, + -1, + 1, + 2.544, + -1, + 2.789, + 1, + 3.033, + 1, + 1, + 3.344, + 1, + 3.656, + -1, + 3.967, + -1, + 1, + 4.222, + -1, + 4.478, + 0.4, + 4.733, + 0.4, + 0, + 5.367, + 0.4 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandR", + "Segments": [ + 0, + 0, + 1, + 0.144, + 0, + 0.289, + 1, + 0.433, + 1, + 1, + 0.611, + 1, + 0.789, + -1, + 0.967, + -1, + 1, + 1.222, + -1, + 1.478, + 0.4, + 1.733, + 0.4, + 1, + 1.922, + 0.4, + 2.111, + -1, + 2.3, + -1, + 1, + 2.544, + -1, + 2.789, + 1, + 3.033, + 1, + 1, + 3.344, + 1, + 3.656, + -1, + 3.967, + -1, + 1, + 4.222, + -1, + 4.478, + 0.3, + 4.733, + 0.3, + 0, + 5.367, + 0.3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.022, + 0, + 0.044, + 0, + 0.067, + 0, + 1, + 0.144, + 0, + 0.222, + -10, + 0.3, + -10, + 1, + 0.456, + -10, + 0.611, + 8.967, + 0.767, + 8.967, + 1, + 0.889, + 8.967, + 1.011, + -5.867, + 1.133, + -5.867, + 1, + 1.244, + -5.867, + 1.356, + -3.178, + 1.467, + -0.111, + 1, + 1.522, + 1.423, + 1.578, + 1.562, + 1.633, + 1.562, + 1, + 1.733, + 1.562, + 1.833, + -4.563, + 1.933, + -4.563, + 1, + 2.078, + -4.563, + 2.222, + 10, + 2.367, + 10, + 1, + 2.411, + 10, + 2.477, + 10, + 2.5, + 9.828, + 1, + 2.6, + 9.082, + 2.7, + -8.352, + 2.8, + -8.352, + 1, + 2.867, + -8.352, + 2.933, + -8.632, + 3, + -7.761, + 1, + 3.111, + -6.31, + 3.222, + 6.63, + 3.333, + 6.63, + 1, + 3.389, + 6.63, + 3.444, + -4.883, + 3.5, + -4.883, + 1, + 3.544, + -4.883, + 3.589, + -5.066, + 3.633, + -4.785, + 1, + 3.811, + -3.661, + 3.989, + 9.803, + 4.167, + 9.803, + 1, + 4.256, + 9.803, + 4.344, + -9.656, + 4.433, + -9.656, + 1, + 4.567, + -9.656, + 4.7, + 5.375, + 4.833, + 5.375, + 1, + 4.967, + 5.375, + 5.1, + 0, + 5.233, + 0, + 0, + 5.367, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 0, + 0, + 5.37, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 1, + 0, + 5.37, + 1 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m07.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m07.motion3.json new file mode 100644 index 000000000..488b078b2 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m07.motion3.json @@ -0,0 +1,927 @@ +{ + "Version": 3, + "Meta": { + "Duration": 1.9, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 30, + "TotalSegmentCount": 121, + "TotalPointCount": 331, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.444, + 0, + 0.556, + 8, + 0.667, + 8, + 0, + 1.9, + 8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.111, + 1, + 0.222, + 1, + 0.333, + 1, + 1, + 0.378, + 1, + 0.422, + 0, + 0.467, + 0, + 1, + 0.522, + 0, + 0.578, + 1.2, + 0.633, + 1.2, + 1, + 0.744, + 1.2, + 0.856, + 1.2, + 0.967, + 1.2, + 1, + 0.989, + 1.2, + 1.011, + 0, + 1.033, + 0, + 1, + 1.067, + 0, + 1.1, + 1.2, + 1.133, + 1.2, + 1, + 1.167, + 1.2, + 1.2, + 1.2, + 1.233, + 1.2, + 1, + 1.267, + 1.2, + 1.3, + 0, + 1.333, + 0, + 1, + 1.356, + 0, + 1.378, + 1.2, + 1.4, + 1.2, + 0, + 1.9, + 1.2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.111, + 1, + 0.222, + 1, + 0.333, + 1, + 1, + 0.378, + 1, + 0.422, + 0, + 0.467, + 0, + 1, + 0.522, + 0, + 0.578, + 1.2, + 0.633, + 1.2, + 1, + 0.744, + 1.2, + 0.856, + 1.2, + 0.967, + 1.2, + 1, + 0.989, + 1.2, + 1.011, + 0, + 1.033, + 0, + 1, + 1.067, + 0, + 1.1, + 1.2, + 1.133, + 1.2, + 1, + 1.167, + 1.2, + 1.2, + 1.2, + 1.233, + 1.2, + 1, + 1.267, + 1.2, + 1.3, + 0, + 1.333, + 0, + 1, + 1.356, + 0, + 1.378, + 1.2, + 1.4, + 1.2, + 0, + 1.9, + 1.2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0, + 0.667, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0, + 0.667, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0, + 0.667, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0.26, + 0.667, + 0.26, + 0, + 1.9, + 0.26 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0.36, + 0.667, + 0.36, + 0, + 1.9, + 0.36 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0, + 0.667, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + -0.27, + 0.667, + -0.27, + 0, + 1.9, + -0.27 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0.26, + 0.667, + 0.26, + 0, + 1.9, + 0.26 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + -0.03, + 0.667, + -0.03, + 0, + 1.9, + -0.03 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0.33, + 0.667, + 0.33, + 0, + 1.9, + 0.33 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.356, + 0, + 0.378, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0.21, + 0.667, + 0.21, + 0, + 1.9, + 0.21 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.444, + 0, + 0.556, + -6, + 0.667, + -6, + 0, + 1.9, + -6 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.422, + 0, + 0.511, + 10, + 0.6, + 10, + 1, + 0.667, + 10, + 0.733, + -6, + 0.8, + -6, + 1, + 0.833, + -6, + 0.867, + 5, + 0.9, + 5, + 1, + 1.011, + 5, + 1.122, + 0, + 1.233, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.444, + 0, + 0.556, + -3, + 0.667, + -3, + 0, + 1.9, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + -0.062, + 1, + 0.111, + -0.062, + 0.222, + -0.103, + 0.333, + 0, + 1, + 0.589, + 0.238, + 0.844, + 1, + 1.1, + 1, + 0, + 1.9, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.478, + 0, + 0.622, + -10, + 0.767, + -10, + 1, + 0.811, + -10, + 0.856, + -8.2, + 0.9, + -8.2, + 0, + 1.9, + -8.2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 1, + 0.478, + 0, + 0.622, + -10, + 0.767, + -10, + 1, + 0.811, + -10, + 0.856, + -7.2, + 0.9, + -7.2, + 0, + 1.9, + -7.2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLB", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRB", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 0, + 0.333, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.111, + 0, + 0.222, + 1.9, + 0.333, + 5.2, + 1, + 0.444, + 8.5, + 0.556, + 9.926, + 0.667, + 9.926, + 1, + 0.744, + 9.926, + 0.822, + -10, + 0.9, + -10, + 1, + 0.956, + -10, + 1.011, + 6, + 1.067, + 6, + 1, + 1.144, + 6, + 1.222, + -4, + 1.3, + -4, + 1, + 1.367, + -4, + 1.433, + 0, + 1.5, + 0, + 0, + 1.9, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 1, + 0, + 1.9, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0, + 0, + 1.9, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m08.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m08.motion3.json new file mode 100644 index 000000000..c93722a5d --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m08.motion3.json @@ -0,0 +1,1023 @@ +{ + "Version": 3, + "Meta": { + "Duration": 2.1, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 33, + "TotalSegmentCount": 133, + "TotalPointCount": 364, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 1, + 0.344, + 0, + 0.389, + 0, + 0.433, + 0, + 1, + 0.522, + 0, + 0.611, + 0, + 0.7, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 1, + 0.344, + 0, + 0.389, + -15, + 0.433, + -15, + 1, + 0.522, + -15, + 0.611, + 11, + 0.7, + 11, + 0, + 2.1, + 11 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 1, + 0.411, + 0, + 0.522, + -15, + 0.633, + -15, + 1, + 0.689, + -15, + 0.744, + -9, + 0.8, + -9, + 0, + 2.1, + -9 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.211, + 1, + 0.256, + 1, + 0.3, + 1, + 1, + 0.422, + 1, + 0.544, + 0, + 0.667, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 1, + 0.422, + 0, + 0.544, + 1, + 0.667, + 1, + 0, + 2.1, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.211, + 1, + 0.256, + 1, + 0.3, + 1, + 1, + 0.422, + 1, + 0.544, + 0, + 0.667, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 1, + 0.422, + 0, + 0.544, + 1, + 0.667, + 1, + 0, + 2.1, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 1, + 0.422, + 0, + 0.544, + -0.14, + 0.667, + -0.14, + 0, + 2.1, + -0.14 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 1, + 0.422, + 0, + 0.544, + -0.14, + 0.667, + -0.14, + 0, + 2.1, + -0.14 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + -0.21, + 0.667, + -0.21, + 0, + 2.1, + -0.21 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + -0.2, + 0.667, + -0.2, + 0, + 2.1, + -0.2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0.25, + 0.667, + 0.25, + 0, + 2.1, + 0.25 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0.23, + 0.667, + 0.23, + 0, + 2.1, + 0.23 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0, + 0.667, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 1, + 0.489, + 0, + 0.578, + 0, + 0.667, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 8, + 0.4, + 8, + 1, + 0.467, + 8, + 0.533, + -7, + 0.6, + -7, + 1, + 0.656, + -7, + 0.711, + 3, + 0.767, + 3, + 1, + 0.811, + 3, + 0.856, + 0, + 0.9, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 1, + 0.478, + 0, + 0.556, + 4, + 0.633, + 4, + 1, + 0.689, + 4, + 0.744, + 2, + 0.8, + 2, + 0, + 2.1, + 2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0, + 0.4, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + -1, + 0.4, + -1, + 1, + 0.467, + -1, + 0.533, + 1, + 0.6, + 1, + 1, + 0.656, + 1, + 0.711, + -0.4, + 0.767, + -0.4, + 1, + 0.922, + -0.4, + 1.078, + 0, + 1.233, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 0, + 2.1, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLB", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + -5.208, + 0.3, + -5.208, + 1, + 0.367, + -5.208, + 0.433, + 9.583, + 0.5, + 9.583, + 0, + 2.1, + 9.583 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRB", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + -4.583, + 0.3, + -4.583, + 1, + 0.367, + -4.583, + 0.433, + 4.375, + 0.5, + 4.375, + 0, + 2.1, + 4.375 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandLB", + "Segments": [ + 0, + 9.971, + 1, + 0.111, + 9.768, + 0.222, + 8.46, + 0.333, + 4.167, + 1, + 0.378, + 2.449, + 0.422, + -4.583, + 0.467, + -4.583, + 1, + 0.511, + -4.583, + 0.556, + 4.792, + 0.6, + 4.792, + 0, + 2.1, + 4.792 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHandRB", + "Segments": [ + 0, + 9.971, + 1, + 0.111, + 9.768, + 0.222, + 8.46, + 0.333, + 4.167, + 1, + 0.378, + 2.449, + 0.422, + -4.583, + 0.467, + -4.583, + 1, + 0.511, + -4.583, + 0.556, + 7.292, + 0.6, + 7.292, + 0, + 2.1, + 7.292 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + -0.142, + 0.3, + 0.234, + 1, + 0.378, + 0.89, + 0.456, + 10, + 0.533, + 10, + 1, + 0.578, + 10, + 0.622, + -10, + 0.667, + -10, + 1, + 0.733, + -10, + 0.8, + 9.951, + 0.867, + 9.951, + 1, + 0.944, + 9.951, + 1.022, + -9.508, + 1.1, + -9.508, + 1, + 1.178, + -9.508, + 1.256, + 5.892, + 1.333, + 5.892, + 1, + 1.4, + 5.892, + 1.467, + -2, + 1.533, + -2, + 1, + 1.578, + -2, + 1.622, + 1, + 1.667, + 1, + 1, + 1.722, + 1, + 1.778, + 0, + 1.833, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 0, + 0, + 2.1, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0.99, + 0, + 2.1, + 0.99 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m09.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m09.motion3.json new file mode 100644 index 000000000..8ec17a596 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m09.motion3.json @@ -0,0 +1,1113 @@ +{ + "Version": 3, + "Meta": { + "Duration": 1.6, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 31, + "TotalSegmentCount": 150, + "TotalPointCount": 417, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.333, + 0, + 0.467, + -4, + 0.6, + -4, + 0, + 1.6, + -4 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.289, + 0, + 0.378, + -20, + 0.467, + -20, + 1, + 0.522, + -20, + 0.578, + 2, + 0.633, + 2, + 1, + 0.667, + 2, + 0.7, + 0, + 0.733, + 0, + 1, + 0.8, + 0, + 0.867, + 0, + 0.933, + 0, + 1, + 1, + 0, + 1.067, + -21, + 1.133, + -21, + 1, + 1.167, + -21, + 1.2, + -17, + 1.233, + -17, + 0, + 1.6, + -17 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.356, + 0, + 0.511, + 0, + 0.667, + 0, + 1, + 0.778, + 0, + 0.889, + 1, + 1, + 1, + 0, + 1.6, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.067, + 1, + 0.133, + 1, + 0.2, + 1, + 1, + 0.244, + 1, + 0.289, + 1, + 0.333, + 1, + 1, + 0.378, + 1, + 0.422, + 0, + 0.467, + 0, + 1, + 0.489, + 0, + 0.511, + 0, + 0.533, + 0, + 1, + 0.578, + 0, + 0.622, + 1, + 0.667, + 1, + 1, + 0.8, + 1, + 0.933, + 1, + 1.067, + 1, + 1, + 1.122, + 1, + 1.178, + 0.825, + 1.233, + 0.825, + 0, + 1.6, + 0.825 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.544, + 0, + 0.889, + 0, + 1.233, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.067, + 1, + 0.133, + 1, + 0.2, + 1, + 1, + 0.244, + 1, + 0.289, + 1, + 0.333, + 1, + 1, + 0.378, + 1, + 0.422, + 0, + 0.467, + 0, + 1, + 0.489, + 0, + 0.511, + 0, + 0.533, + 0, + 1, + 0.578, + 0, + 0.622, + 0.996, + 0.667, + 1, + 1, + 0.8, + 1.011, + 0.933, + 1.012, + 1.067, + 1.012, + 1, + 1.122, + 1.012, + 1.178, + 0.8, + 1.233, + 0.8, + 0, + 1.6, + 0.8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + 0, + 0.567, + 0, + 1, + 0.789, + 0, + 1.011, + 0, + 1.233, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + 0, + 0.567, + 0, + 1, + 0.789, + 0, + 1.011, + 0, + 1.233, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + 0, + 0.567, + 0, + 1, + 0.789, + 0, + 1.011, + 0, + 1.233, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + 1, + 0.567, + 1, + 1, + 0.733, + 1, + 0.9, + 1, + 1.067, + 1, + 1, + 1.122, + 1, + 1.178, + -0.417, + 1.233, + -0.417, + 0, + 1.6, + -0.417 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + 1, + 0.567, + 1, + 1, + 0.733, + 1, + 0.9, + 1, + 1.067, + 1, + 1, + 1.122, + 1, + 1.178, + -1, + 1.233, + -1, + 0, + 1.6, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + 0, + 0.567, + 0, + 1, + 0.789, + 0, + 1.011, + 0, + 1.233, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + 0, + 0.567, + 0, + 1, + 0.789, + 0, + 1.011, + 0, + 1.233, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + -1, + 0.567, + -1, + 1, + 0.789, + -1, + 1.011, + -1, + 1.233, + -1, + 0, + 1.6, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + -1, + 0.567, + -1, + 1, + 0.789, + -1, + 1.011, + -1, + 1.233, + -1, + 0, + 1.6, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + -1, + 0.567, + -1, + 1, + 0.789, + -1, + 1.011, + -1, + 1.233, + -1, + 0, + 1.6, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.322, + 0, + 0.444, + -1, + 0.567, + -1, + 1, + 0.789, + -1, + 1.011, + -1, + 1.233, + -1, + 0, + 1.6, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.156, + 0, + 0.311, + 0, + 0.467, + 0, + 1, + 0.556, + 0, + 0.644, + -10, + 0.733, + -10, + 1, + 0.833, + -10, + 0.933, + -9, + 1.033, + -9, + 0, + 1.6, + -9 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + -4, + 0.433, + -4, + 1, + 0.522, + -4, + 0.611, + 5, + 0.7, + 5, + 1, + 0.789, + 5, + 0.878, + 5, + 0.967, + 5, + 1, + 1.044, + 5, + 1.122, + -7, + 1.2, + -7, + 1, + 1.267, + -7, + 1.333, + 0, + 1.4, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.367, + 0, + 0.533, + 0.479, + 0.7, + 0.479, + 1, + 0.889, + 0.479, + 1.078, + -1, + 1.267, + -1, + 1, + 1.322, + -1, + 1.378, + -1, + 1.433, + -1, + 0, + 1.6, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 0, + 1.6, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.233, + 0, + 0.267, + 0, + 0.3, + 0, + 1, + 0.367, + 0, + 0.433, + -4.5, + 0.5, + -4.5, + 1, + 0.578, + -4.5, + 0.656, + 0.8, + 0.733, + 0.8, + 1, + 0.811, + 0.8, + 0.889, + -0.156, + 0.967, + -0.6, + 1, + 1.011, + -0.854, + 1.056, + -0.72, + 1.1, + -1, + 1, + 1.167, + -1.42, + 1.233, + -3.7, + 1.3, + -3.7, + 1, + 1.356, + -3.7, + 1.411, + -2.4, + 1.467, + -2.4, + 0, + 1.6, + -2.4 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.233, + 0, + 0.267, + 0, + 0.3, + 0, + 1, + 0.367, + 0, + 0.433, + -4.5, + 0.5, + -4.5, + 1, + 0.578, + -4.5, + 0.656, + 2.2, + 0.733, + 2.2, + 1, + 0.811, + 2.2, + 0.889, + -0.749, + 0.967, + -0.9, + 1, + 1.011, + -0.987, + 1.056, + -0.921, + 1.1, + -1, + 1, + 1.167, + -1.119, + 1.233, + -3.6, + 1.3, + -3.6, + 1, + 1.356, + -3.6, + 1.411, + -1.8, + 1.467, + -1.8, + 0, + 1.6, + -1.8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLB", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 1.6, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRB", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.378, + 0, + 0.556, + 0.84, + 0.733, + 0.84, + 1, + 0.744, + 0.84, + 0.756, + 0.65, + 0.767, + 0.65, + 1, + 0.8, + 0.65, + 0.833, + 0.86, + 0.867, + 0.86, + 0, + 1.6, + 0.86 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.289, + 0, + 0.378, + 6, + 0.467, + 6, + 1, + 0.5, + 6, + 0.533, + 4, + 0.567, + 0, + 1, + 0.622, + -6.667, + 0.678, + -10, + 0.733, + -10, + 1, + 0.767, + -10, + 0.8, + -6, + 0.833, + -6, + 1, + 0.933, + -6, + 1.033, + -10, + 1.133, + -10, + 1, + 1.178, + -10, + 1.222, + -2, + 1.267, + -2, + 1, + 1.311, + -2, + 1.356, + -9, + 1.4, + -9, + 0, + 1.6, + -9 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 1, + 0, + 1.6, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0, + 0, + 1.6, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m10.motion3.json b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m10.motion3.json new file mode 100644 index 000000000..ee27769a8 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/hiyori_pro_zh/runtime/motion/hiyori_m10.motion3.json @@ -0,0 +1,924 @@ +{ + "Version": 3, + "Meta": { + "Duration": 4.17, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": false, + "CurveCount": 31, + "TotalSegmentCount": 118, + "TotalPointCount": 321, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.4, + 0, + 0.6, + 0, + 0.8, + 0, + 1, + 1.067, + 0, + 1.333, + 1.041, + 1.6, + 1.041, + 1, + 1.844, + 1.041, + 2.089, + -8, + 2.333, + -8, + 1, + 2.656, + -8, + 2.978, + 6, + 3.3, + 6, + 0, + 4.167, + 6 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.344, + 0, + 0.489, + -30, + 0.633, + -30, + 0, + 4.167, + -30 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.067, + 1, + 0.133, + 1, + 0.2, + 1, + 1, + 0.311, + 1, + 0.422, + 0.988, + 0.533, + 0.8, + 1, + 0.589, + 0.706, + 0.644, + 0, + 0.7, + 0, + 1, + 0.722, + 0, + 0.744, + 0, + 0.767, + 0, + 1, + 0.822, + 0, + 0.878, + 0.8, + 0.933, + 0.8, + 1, + 1.422, + 0.8, + 1.911, + 0.8, + 2.4, + 0.8, + 1, + 2.456, + 0.8, + 2.511, + 0, + 2.567, + 0, + 1, + 2.589, + 0, + 2.611, + 0, + 2.633, + 0, + 1, + 2.689, + 0, + 2.744, + 0.8, + 2.8, + 0.8, + 0, + 4.167, + 0.8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.067, + 1, + 0.133, + 1, + 0.2, + 1, + 1, + 0.311, + 1, + 0.422, + 0.988, + 0.533, + 0.8, + 1, + 0.589, + 0.706, + 0.644, + 0, + 0.7, + 0, + 1, + 0.722, + 0, + 0.744, + 0, + 0.767, + 0, + 1, + 0.822, + 0, + 0.878, + 0.8, + 0.933, + 0.8, + 1, + 1.422, + 0.8, + 1.911, + 0.8, + 2.4, + 0.8, + 1, + 2.456, + 0.8, + 2.511, + 0, + 2.567, + 0, + 1, + 2.589, + 0, + 2.611, + 0, + 2.633, + 0, + 1, + 2.689, + 0, + 2.744, + 0.8, + 2.8, + 0.8, + 0, + 4.167, + 0.8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + 0, + 0.433, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + 0, + 0.433, + 0, + 1, + 0.667, + 0, + 0.9, + 0.004, + 1.133, + -0.01, + 1, + 1.4, + -0.025, + 1.667, + -0.43, + 1.933, + -0.43, + 1, + 2.211, + -0.43, + 2.489, + 0.283, + 2.767, + 0.283, + 0, + 4.167, + 0.283 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + -1, + 0.433, + -1, + 0, + 4.167, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + 0.19, + 0.433, + 0.19, + 0, + 4.167, + 0.19 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + 0.11, + 0.433, + 0.11, + 0, + 4.167, + 0.11 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + -0.48, + 0.433, + -0.48, + 0, + 4.167, + -0.48 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + -0.29, + 0.433, + -0.29, + 0, + 4.167, + -0.29 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + 1, + 0.433, + 1, + 0, + 4.167, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + 0.85, + 0.433, + 0.85, + 0, + 4.167, + 0.85 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + -0.75, + 0.433, + -0.75, + 0, + 4.167, + -0.75 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.278, + 0, + 0.356, + -0.87, + 0.433, + -0.87, + 0, + 4.167, + -0.87 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.444, + 0, + 0.689, + 0, + 0.933, + 0, + 1, + 1.211, + 0, + 1.489, + 0, + 1.767, + 0, + 1, + 2.056, + 0, + 2.344, + -6, + 2.633, + -6, + 1, + 3.033, + -6, + 3.433, + 10, + 3.833, + 10, + 0, + 4.167, + 10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.8, + 0, + 1.4, + -2, + 2, + -2, + 1, + 2.456, + -2, + 2.911, + 8.125, + 3.367, + 8.125, + 0, + 4.167, + 8.125 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamShoulder", + "Segments": [ + 0, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeg", + "Segments": [ + 0, + 1, + 1, + 0.667, + 1, + 1.333, + 1, + 2, + 1, + 1, + 2.267, + 1, + 2.533, + 0.948, + 2.8, + 0.948, + 0, + 4.167, + 0.948 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLA", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.233, + 0, + 0.267, + 0, + 0.3, + 0, + 1, + 0.478, + 0, + 0.656, + -10, + 0.833, + -10, + 1, + 0.922, + -10, + 1.011, + -8.846, + 1.1, + -8.846, + 1, + 1.467, + -8.846, + 1.833, + -8.835, + 2.2, + -9.1, + 1, + 2.622, + -9.405, + 3.044, + -10, + 3.467, + -10, + 0, + 4.167, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRA", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.233, + 0, + 0.267, + 0, + 0.3, + 0, + 1, + 0.478, + 0, + 0.656, + -10, + 0.833, + -10, + 1, + 0.922, + -10, + 1.011, + -8.972, + 1.1, + -8.846, + 1, + 1.467, + -8.328, + 1.833, + -8.2, + 2.2, + -8.2, + 1, + 2.622, + -8.2, + 3.044, + -10, + 3.467, + -10, + 0, + 4.167, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmLB", + "Segments": [ + 0, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmRB", + "Segments": [ + 0, + 0, + 0, + 4.167, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairAhoge", + "Segments": [ + 0, + 0, + 1, + 0.067, + 0, + 0.133, + 0, + 0.2, + 0, + 1, + 0.233, + 0, + 0.267, + -5, + 0.3, + -5, + 1, + 0.378, + -5, + 0.456, + 10, + 0.533, + 10, + 1, + 0.633, + 10, + 0.733, + 4, + 0.833, + 4, + 0, + 4.167, + 4 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmA", + "Segments": [ + 0, + 1, + 0, + 4.17, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmB", + "Segments": [ + 0, + 0, + 0, + 4.17, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/ReadMe.txt b/main/feedback-backend/admin-ui/resources/natori_pro_zh/ReadMe.txt new file mode 100644 index 000000000..f0cec40fd --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/ReadMe.txt @@ -0,0 +1,79 @@ + +============================================================ + +示例模型 +名执 尽 - PRO + +============================================================ + + 该示例可用于学习商用的游戏和App中常用到的手臂切换等难度较高的制作方法。 + + 该模型角色由画师先崎真琴设计。 + 模型的手臂通过渐变实现不同部件间的切换,这种制作方法经常应用于商用的游戏和App中。 + 通过该模型,可以学习部件的切换来实现更丰富的动画。 + + 另外,可以通过Cubism3 Viewer (for OW)来查看嵌入式文件组的动画,了解完整的工作流程中使用到的数据结构。 + + +------------------------------ +素材使用许可 +------------------------------ + + 普通用户以及小规模企业在同意授权协议的情况下可用于商业用途。 + 中/大规模的企业只能用于非公开的内部试用。 + 在使用该素材时,请确认以下的【无偿提供素材使用授权协议】中的“授权类型”、“Live2D原创角色”等的相关内容, + 并必须接受【Live2D Cubism 示例模型的使用授权要求】中的利用条件。 + + 有关许可证的更多信息,请参阅以下页面。 + https://www.live2d.com/zh-CHS/download/sample-data/ + + +------------------------------ +创作者 +------------------------------ + + 插画:先崎 真琴【http://senzakimakoto.com/】 + 配音:小野友树【https://web.onoyuki.com/】 + (※配音数据的发布为限定发布,已于2018/06/04结束。) + 模型:Live2D + + +------------------------------ +素材内容 +------------------------------ + + 模型文件(cmo3) ※包含物理模拟的设定 + 表情动画文件(can3) + 基本动画文件(can3) + 嵌入文件组(runtime文件夹) + ・模型数据(moc3) + ・表情数据(exp3.json) + ・动作数据(motion3.json) + ・模型设定文件(model3.json) + ・姿势设定文件(pose3.json) + ・物理模拟设定文件(physics3.json) + ・辅助显示的文件(cdi3.json) + + +------------------------------ +更新记录 +------------------------------ + ※配音数据的发布已于2018/06/04结束。 + +【cmo3】 + + natori_pro_t06.cmo3 + 2021年6月10日 公开 + + +【can3】 + + natori_pro_exp_t03.can3 + 2021年6月10日 公开 + + +【can3】 + + natori_pro_motions_t03.can3 + 2021年6月10日 公开 + diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_exp_t03.can3 b/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_exp_t03.can3 new file mode 100644 index 000000000..c179d4877 Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_exp_t03.can3 differ diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_motions_t03.can3 b/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_motions_t03.can3 new file mode 100644 index 000000000..1af88ba7f Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_motions_t03.can3 differ diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_t06.cmo3 b/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_t06.cmo3 new file mode 100644 index 000000000..a5cce3529 Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/natori_pro_zh/natori_pro_t06.cmo3 differ diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Angry.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Angry.exp3.json new file mode 100644 index 000000000..4505fc031 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Angry.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": -2, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": -2, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0.3, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0.3, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": -0.4, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": -0.4, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Blushing.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Blushing.exp3.json new file mode 100644 index 000000000..6e442c4e8 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Blushing.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Normal.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Normal.exp3.json new file mode 100644 index 000000000..bca849571 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Normal.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Sad.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Sad.exp3.json new file mode 100644 index 000000000..e2595511a --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Sad.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": -2, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": -2, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Smile.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Smile.exp3.json new file mode 100644 index 000000000..e431584d4 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Smile.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Surprised.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Surprised.exp3.json new file mode 100644 index 000000000..43921870a --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/Surprised.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0.3, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0.3, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0.2, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0.2, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": -0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": -0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_01.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_01.exp3.json new file mode 100644 index 000000000..6f0a8dc6b --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_01.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 3, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 3, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": -0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": -0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_02.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_02.exp3.json new file mode 100644 index 000000000..f3ccbadc0 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_02.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_03.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_03.exp3.json new file mode 100644 index 000000000..fea12162b --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_03.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_04.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_04.exp3.json new file mode 100644 index 000000000..fdef0d720 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_04.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": 0.2, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": 0.2, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0.2, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0.2, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": -0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": -0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0.1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_05.exp3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_05.exp3.json new file mode 100644 index 000000000..6f8515fe5 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/exp/exp_05.exp3.json @@ -0,0 +1,120 @@ +{ + "Type": "Live2D Expression", + "Parameters": [ + { + "Id": "ParamEyeLOpen", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamEyeLSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeLForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeROpen", + "Value": -1, + "Blend": "Add" + }, + { + "Id": "ParamEyeRSmile", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeRForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamEyeBallForm", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRY", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRX", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRAngle", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamBrowLForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm", + "Value": 1, + "Blend": "Add" + }, + { + "Id": "ParamBrowRForm2", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamTeethOn", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamCheek", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGlassUD", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassWhite", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlight", + "Value": 0, + "Blend": "Add" + }, + { + "Id": "ParamGrassHighlightMove", + "Value": 0, + "Blend": "Add" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_00.motion3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_00.motion3.json new file mode 100644 index 000000000..534066d85 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_00.motion3.json @@ -0,0 +1,1432 @@ +{ + "Version": 3, + "Meta": { + "Duration": 7.97, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": true, + "CurveCount": 93, + "TotalSegmentCount": 78, + "TotalPointCount": 362, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.611, + 0, + 1.222, + 5, + 1.833, + 5, + 1, + 2.4, + 5, + 2.967, + 0, + 3.533, + 0, + 1, + 4.278, + 0, + 5.022, + 4, + 5.767, + 4, + 1, + 6.5, + 4, + 7.233, + 0.119, + 7.967, + 0.003 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 2.656, + 1, + 5.311, + 1, + 7.967, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLForm", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 2.656, + 1, + 5.311, + 1, + 7.967, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRForm", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallForm", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm2", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm2", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamTeethOn", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGlassUD", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassWhite", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlight", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlightMove", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 1, + 1, + 0.589, + 1, + 1.178, + -1, + 1.767, + -1, + 1, + 2.333, + -1, + 2.9, + 1, + 3.467, + 1, + 1, + 4.2, + 1, + 4.933, + -1, + 5.667, + -1, + 1, + 6.433, + -1, + 7.2, + 0.943, + 7.967, + 0.999 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWaistAngleZ", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyPosition", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.6, + 0, + 1.2, + 1, + 1.8, + 1, + 1, + 2.367, + 1, + 2.933, + 0, + 3.5, + 0, + 1, + 4.244, + 0, + 4.989, + 1, + 5.733, + 1, + 1, + 6.478, + 1, + 7.222, + 0.029, + 7.967, + 0.001 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeftShoulderUp", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamRightShoulderUp", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllX", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllY", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllRotate", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFront", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSide", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBack", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSideFuwa", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBackFuwa", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamJacket", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamChainWaist", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA1", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA2", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchAX", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBSwitch", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBX", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL01", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL02", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL03", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR01", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR02", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR03", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR01", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR02", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR03", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01Roll", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll1", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll2", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll3", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR01", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR02", + "Segments": [ + 0, + -30, + 1, + 2.656, + -30, + 5.311, + -0.25, + 7.967, + -0.002 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR03", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCLHandRoll1", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL01", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL02", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL03", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDLHand03Roll", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER01", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER02", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER03", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER04", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll1", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll2", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06", + "Segments": [ + 0, + 0, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll1", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll2", + "Segments": [ + 0, + 0, + 1, + 2.656, + 0, + 5.311, + 0, + 7.967, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchA", + "Segments": [ + 0, + 1, + 0, + 7.97, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchB", + "Segments": [ + 0, + 0, + 0, + 7.97, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAL", + "Segments": [ + 0, + 1, + 0, + 7.97, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAR", + "Segments": [ + 0, + 1, + 0, + 7.97, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmBR", + "Segments": [ + 0, + 0, + 0, + 7.97, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmCL", + "Segments": [ + 0, + 0, + 0, + 7.97, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmDL", + "Segments": [ + 0, + 0, + 0, + 7.97, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmER", + "Segments": [ + 0, + 0, + 0, + 7.97, + 0 + ] + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_01.motion3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_01.motion3.json new file mode 100644 index 000000000..066dbfcd1 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_01.motion3.json @@ -0,0 +1,1971 @@ +{ + "Version": 3, + "Meta": { + "Duration": 5, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": true, + "CurveCount": 94, + "TotalSegmentCount": 228, + "TotalPointCount": 587, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.511, + 0, + 0.856, + 0, + 1.2, + 0, + 1, + 1.856, + 0, + 2.511, + -0.883, + 3.167, + -4, + 1, + 3.578, + -5.955, + 3.989, + -8.02, + 4.4, + -8.02, + 0, + 5, + -8.02 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.189, + 0, + 0.211, + 0, + 0.233, + 0, + 1, + 0.378, + 0, + 0.522, + 2.709, + 0.667, + 4.062, + 1, + 0.856, + 5.832, + 1.044, + 6, + 1.233, + 6, + 1, + 1.878, + 6, + 2.522, + -12, + 3.167, + -12, + 1, + 3.589, + -12, + 4.011, + -9, + 4.433, + -9, + 0, + 5, + -9 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.222, + 0, + 0.278, + 0, + 0.333, + 0, + 1, + 0.611, + 0, + 0.889, + 8, + 1.167, + 8, + 1, + 1.178, + 8, + 1.189, + 8, + 1.2, + 8, + 1, + 1.856, + 8, + 2.511, + -14, + 3.167, + -14, + 1, + 3.467, + -14, + 3.767, + -13, + 4.067, + -13, + 0, + 5, + -13 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.722, + 1, + 1.278, + 1, + 1.833, + 1, + 1, + 1.933, + 1, + 2.033, + 0, + 2.133, + 0, + 1, + 2.478, + 0, + 2.822, + 0, + 3.167, + 0, + 1, + 3.322, + 0, + 3.478, + 0.7, + 3.633, + 0.7, + 0, + 5, + 0.7 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLForm", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.722, + 1, + 1.278, + 1, + 1.833, + 1, + 1, + 1.933, + 1, + 2.033, + 0, + 2.133, + 0, + 1, + 2.478, + 0, + 2.822, + 0, + 3.167, + 0, + 1, + 3.322, + 0, + 3.478, + 0.7, + 3.633, + 0.7, + 0, + 5, + 0.7 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRForm", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.233, + 0, + 0.3, + 0, + 0.367, + 0, + 1, + 0.656, + 0, + 0.944, + 0, + 1.233, + 0, + 1, + 1.878, + 0, + 2.522, + -0.3, + 3.167, + -0.3, + 0, + 5, + -0.3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.233, + 0, + 0.3, + 0, + 0.367, + 0, + 1, + 0.656, + 0, + 0.944, + -0.2, + 1.233, + -0.2, + 1, + 1.878, + -0.2, + 2.522, + -0.2, + 3.167, + -0.2, + 0, + 5, + -0.2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm2", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm2", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamTeethOn", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGlassUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassWhite", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlight", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlightMove", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + -1, + 1, + 0.056, + -1, + 0.111, + -1, + 0.167, + -1, + 1, + 0.489, + -1, + 0.811, + 0, + 1.133, + 0, + 1, + 1.778, + 0, + 2.422, + -3, + 3.067, + -3, + 0, + 5, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 1.011, + 0.433, + 1.616, + 1, + 0.6, + 2.751, + 0.767, + 3, + 0.933, + 3, + 1, + 1, + 3, + 1.067, + 3, + 1.133, + 3, + 1, + 1.778, + 3, + 2.422, + -2, + 3.067, + -2, + 1, + 3.511, + -2, + 3.956, + -1.5, + 4.4, + -1.5, + 0, + 5, + -1.5 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWaistAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyPosition", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.467, + 0, + 0.767, + 1, + 1.067, + 1, + 1, + 1.089, + 1, + 1.111, + 1, + 1.133, + 1, + 1, + 1.911, + 1, + 2.689, + 0, + 3.467, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeftShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.489, + 0, + 0.811, + 0, + 1.133, + 0, + 1, + 1.778, + 0, + 2.422, + -9, + 3.067, + -9, + 0, + 5, + -9 + ] + }, + { + "Target": "Parameter", + "Id": "ParamRightShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.489, + 0, + 0.811, + 0, + 1.133, + 0, + 1, + 1.778, + 0, + 2.422, + 8, + 3.067, + 8, + 0, + 5, + 8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllRotate", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFront", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSide", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBack", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSideFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBackFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamJacket", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamChainWaist", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchAX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBSwitch", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.544, + 0, + 0.922, + 1, + 1.3, + 1, + 1, + 1.911, + 1, + 2.522, + 0, + 3.133, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.556, + 0, + 0.944, + -1, + 1.333, + -1, + 1, + 1.944, + -1, + 2.556, + 0, + 3.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.556, + 0, + 0.944, + 0, + 1.333, + 0, + 1, + 1.944, + 0, + 2.556, + -3, + 3.167, + -3, + 0, + 5, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR02", + "Segments": [ + 0, + -40, + 1, + 0.056, + -40, + 0.111, + -40, + 0.167, + -40, + 0, + 5, + -40 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR03", + "Segments": [ + 0, + -9, + 1, + 0.056, + -9, + 0.111, + -9, + 0.167, + -9, + 0, + 5, + -9 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll3", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCLHandRoll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDLHand03Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.2, + 0, + 0.233, + 0, + 0.267, + 0, + 1, + 0.6, + 0, + 0.933, + 6, + 1.267, + 6, + 1, + 1.9, + 6, + 2.533, + -2, + 3.167, + -2, + 0, + 5, + -2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.544, + 0, + 0.922, + 3, + 1.3, + 3, + 1, + 1.933, + 3, + 2.567, + -2, + 3.2, + -2, + 1, + 3.589, + -2, + 3.978, + -1, + 4.367, + -1, + 0, + 5, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0.2, + 0.3, + 0.2, + 1, + 0.633, + 0.2, + 0.967, + 0, + 1.3, + 0, + 1, + 1.933, + 0, + 2.567, + 2, + 3.2, + 2, + 1, + 3.589, + 2, + 3.978, + 1, + 4.367, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER04", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.533, + 0, + 0.9, + 0, + 1.267, + 0, + 1, + 1.9, + 0, + 2.533, + 2, + 3.167, + 2, + 0, + 5, + 2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll1", + "Segments": [ + 0, + 9, + 1, + 0.056, + 9, + 0.111, + 9, + 0.167, + 9, + 1, + 0.556, + 9, + 0.944, + 11, + 1.333, + 11, + 1, + 2.067, + 11, + 2.8, + -23, + 3.533, + -23, + 0, + 5, + -23 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll2", + "Segments": [ + 0, + 9, + 1, + 0.056, + 9, + 0.111, + 9, + 0.167, + 9, + 1, + 0.556, + 9, + 0.944, + 14, + 1.333, + 14, + 1, + 2.067, + 14, + 2.8, + -14, + 3.533, + -14, + 0, + 5, + -14 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchA", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchB", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAL", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAR", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmBR", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmCL", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmDL", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmER", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_02.motion3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_02.motion3.json new file mode 100644 index 000000000..6cff19188 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_02.motion3.json @@ -0,0 +1,2182 @@ +{ + "Version": 3, + "Meta": { + "Duration": 5.5, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": true, + "CurveCount": 93, + "TotalSegmentCount": 262, + "TotalPointCount": 690, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.822, + 0, + 1.478, + 0, + 2.133, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.222, + 0, + 0.278, + 0, + 0.333, + 0, + 1, + 0.544, + 0, + 0.756, + 10.2, + 0.967, + 10.2, + 1, + 1.356, + 10.2, + 1.744, + -30, + 2.133, + -30, + 1, + 2.267, + -30, + 2.4, + -27.952, + 2.533, + -27.952, + 1, + 2.867, + -27.952, + 3.2, + -30, + 3.533, + -30, + 1, + 3.822, + -30, + 4.111, + 2.617, + 4.4, + 2.617, + 1, + 4.533, + 2.617, + 4.667, + 0, + 4.8, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.567, + 1, + 0.967, + 1, + 1.367, + 1, + 1, + 1.478, + 1, + 1.589, + 0, + 1.7, + 0, + 1, + 2.4, + 0, + 3.1, + 0, + 3.8, + 0, + 1, + 3.944, + 0, + 4.089, + 1, + 4.233, + 1, + 0, + 5.5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.567, + 1, + 0.967, + 1, + 1.367, + 1, + 1, + 1.478, + 1, + 1.589, + 0, + 1.7, + 0, + 1, + 2.4, + 0, + 3.1, + 0, + 3.8, + 0, + 1, + 3.944, + 0, + 4.089, + 1, + 4.233, + 1, + 0, + 5.5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamTeethOn", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGlassUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassWhite", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlight", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlightMove", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.411, + 0, + 0.656, + 1.24, + 0.9, + 1.24, + 1, + 1.3, + 1.24, + 1.7, + -5, + 2.1, + -5.92, + 1, + 2.533, + -6.917, + 2.967, + -6.78, + 3.4, + -6.78, + 1, + 3.856, + -6.78, + 4.311, + 0, + 4.767, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.411, + 0, + 0.656, + 1, + 0.9, + 1, + 1, + 1.311, + 1, + 1.722, + -1.464, + 2.133, + -2, + 1, + 2.567, + -2.564, + 3, + -2.5, + 3.433, + -2.5, + 1, + 3.878, + -2.5, + 4.322, + 0, + 4.767, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWaistAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.422, + 0, + 0.678, + 2, + 0.933, + 2, + 1, + 1.333, + 2, + 1.733, + -1.026, + 2.133, + -2, + 1, + 2.567, + -3.055, + 3, + -3, + 3.433, + -3, + 1, + 3.878, + -3, + 4.322, + 0, + 4.767, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyPosition", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.411, + 0, + 0.656, + -1, + 0.9, + -1, + 1, + 1.289, + -1, + 1.678, + 9.133, + 2.067, + 9.133, + 1, + 2.178, + 9.133, + 2.289, + 9, + 2.4, + 9, + 1, + 2.656, + 9, + 2.911, + 9, + 3.167, + 9, + 1, + 3.478, + 9, + 3.789, + -0.5, + 4.1, + -0.5, + 1, + 4.422, + -0.5, + 4.744, + 0, + 5.067, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.411, + 0, + 0.656, + 1, + 0.9, + 1, + 1, + 1.733, + 1, + 2.567, + 0, + 3.4, + 0, + 1, + 3.633, + 0, + 3.867, + 0.6, + 4.1, + 0.6, + 1, + 4.333, + 0.6, + 4.567, + 0, + 4.8, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeftShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.422, + 0, + 0.678, + 0, + 0.933, + 0, + 1, + 1.322, + 0, + 1.711, + -9, + 2.1, + -9, + 1, + 2.989, + -9, + 3.878, + 0, + 4.767, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamRightShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.422, + 0, + 0.678, + 0, + 0.933, + 0, + 1, + 1.322, + 0, + 1.711, + 8, + 2.1, + 8, + 1, + 2.989, + 8, + 3.878, + 0, + 4.767, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllRotate", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFront", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSide", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBack", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSideFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBackFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamJacket", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamChainWaist", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchAX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBSwitch", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL02", + "Segments": [ + 0, + -28, + 1, + 0.056, + -28, + 0.111, + -28, + 0.167, + -28, + 0, + 5.5, + -28 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL03", + "Segments": [ + 0, + 19, + 1, + 0.056, + 19, + 0.111, + 19, + 0.167, + 19, + 0, + 5.5, + 19 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.422, + 0, + 0.678, + 0.8, + 0.933, + 0.8, + 1, + 1.322, + 0.8, + 1.711, + -3, + 2.1, + -3, + 1, + 2.556, + -3, + 3.011, + -3, + 3.467, + -3, + 1, + 3.789, + -3, + 4.111, + 0.8, + 4.433, + 0.8, + 1, + 4.589, + 0.8, + 4.744, + 0, + 4.9, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.433, + 0, + 0.7, + 0.8, + 0.967, + 0.8, + 1, + 1.356, + 0.8, + 1.744, + -6, + 2.133, + -6, + 1, + 2.589, + -6, + 3.044, + -6, + 3.5, + -6, + 1, + 3.822, + -6, + 4.144, + 1, + 4.467, + 1, + 1, + 4.622, + 1, + 4.778, + 0, + 4.933, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.433, + 0, + 0.7, + 0, + 0.967, + 0, + 1, + 1.356, + 0, + 1.744, + -10, + 2.133, + -10, + 1, + 2.589, + -10, + 3.044, + -10, + 3.5, + -10, + 1, + 3.822, + -10, + 4.144, + 1, + 4.467, + 1, + 1, + 4.622, + 1, + 4.778, + 0, + 4.933, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 1, + 0.311, + 0, + 0.622, + 0, + 0.933, + 0, + 1, + 0.944, + 0, + 0.956, + -1, + 0.967, + -1, + 1, + 2.111, + -1, + 3.256, + -1, + 4.4, + -1, + 1, + 4.411, + -1, + 4.422, + 0, + 4.433, + 0, + 1, + 4.733, + 0, + 5.033, + 0, + 5.333, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll3", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR01", + "Segments": [ + 0, + 3, + 1, + 0.056, + 3, + 0.111, + 3, + 0.167, + 3, + 1, + 0.422, + 3, + 0.678, + 5, + 0.933, + 5, + 1, + 1.311, + 5, + 1.689, + -6, + 2.067, + -6, + 1, + 2.522, + -6, + 2.978, + -6, + 3.433, + -6, + 1, + 3.922, + -6, + 4.411, + 3, + 4.9, + 3, + 0, + 5.5, + 3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR02", + "Segments": [ + 0, + -29, + 1, + 0.056, + -29, + 0.111, + -29, + 0.167, + -29, + 1, + 0.444, + -29, + 0.722, + -30, + 1, + -30, + 1, + 1.367, + -30, + 1.733, + -21, + 2.1, + -21, + 1, + 2.556, + -21, + 3.011, + -21, + 3.467, + -21, + 1, + 3.956, + -21, + 4.444, + -29, + 4.933, + -29, + 0, + 5.5, + -29 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR03", + "Segments": [ + 0, + 11, + 1, + 0.056, + 11, + 0.111, + 11, + 0.167, + 11, + 1, + 0.444, + 11, + 0.722, + 9, + 1, + 9, + 1, + 1.367, + 9, + 1.733, + 28, + 2.1, + 28, + 1, + 2.556, + 28, + 3.011, + 28, + 3.467, + 28, + 1, + 3.956, + 28, + 4.444, + 11, + 4.933, + 11, + 0, + 5.5, + 11 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCLHandRoll1", + "Segments": [ + 0, + -18, + 1, + 0.056, + -18, + 0.111, + -18, + 0.167, + -18, + 1, + 0.456, + -18, + 0.744, + -18.077, + 1.033, + -21, + 1, + 1.411, + -24.822, + 1.789, + -30, + 2.167, + -30, + 1, + 2.622, + -30, + 3.078, + -30, + 3.533, + -30, + 1, + 4, + -30, + 4.467, + -18, + 4.933, + -18, + 0, + 5.5, + -18 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDLHand03Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER04", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 0, + 5.5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchA", + "Segments": [ + 0, + 1, + 0, + 5.5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchB", + "Segments": [ + 0, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAL", + "Segments": [ + 0, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAR", + "Segments": [ + 0, + 1, + 0, + 5.5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmBR", + "Segments": [ + 0, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmCL", + "Segments": [ + 0, + 1, + 0, + 5.5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmDL", + "Segments": [ + 0, + 0, + 0, + 5.5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmER", + "Segments": [ + 0, + 0, + 0, + 5.5, + 0 + ] + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_03.motion3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_03.motion3.json new file mode 100644 index 000000000..bc2472039 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_03.motion3.json @@ -0,0 +1,2596 @@ +{ + "Version": 3, + "Meta": { + "Duration": 5, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": true, + "CurveCount": 98, + "TotalSegmentCount": 318, + "TotalPointCount": 853, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.322, + 0, + 0.478, + 0, + 0.633, + 0, + 1, + 1.089, + 0, + 1.544, + -10.65, + 2, + -14, + 1, + 2.211, + -15.553, + 2.422, + -15, + 2.633, + -15, + 1, + 2.844, + -15, + 3.056, + 0, + 3.267, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.278, + 0, + 0.389, + 1, + 0.5, + 1, + 1, + 0.744, + 1, + 0.989, + -16.215, + 1.233, + -16.215, + 1, + 1.433, + -16.215, + 1.633, + -11.8, + 1.833, + -11.8, + 1, + 2.133, + -11.8, + 2.433, + -14.898, + 2.733, + -14.898, + 1, + 3.056, + -14.898, + 3.378, + 0, + 3.7, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.189, + 0, + 0.378, + 0, + 0.567, + 0, + 1, + 0.867, + 0, + 1.167, + 10, + 1.467, + 10, + 1, + 1.8, + 10, + 2.133, + 10, + 2.467, + 10, + 1, + 2.733, + 10, + 3, + 0, + 3.267, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.378, + 1, + 0.589, + 1, + 0.8, + 1, + 1, + 0.833, + 1, + 0.867, + 0, + 0.9, + 0, + 1, + 0.922, + 0, + 0.944, + 0, + 0.967, + 0, + 1, + 1.044, + 0, + 1.122, + 1, + 1.2, + 1, + 1, + 1.711, + 1, + 2.222, + 1, + 2.733, + 1, + 1, + 2.767, + 1, + 2.8, + 0, + 2.833, + 0, + 1, + 2.856, + 0, + 2.878, + 0, + 2.9, + 0, + 1, + 2.978, + 0, + 3.056, + 1, + 3.133, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.378, + 1, + 0.589, + 1, + 0.8, + 1, + 1, + 0.833, + 1, + 0.867, + 0, + 0.9, + 0, + 1, + 0.922, + 0, + 0.944, + 0, + 0.967, + 0, + 1, + 1.044, + 0, + 1.122, + 1, + 1.2, + 1, + 1, + 1.711, + 1, + 2.222, + 1, + 2.733, + 1, + 1, + 2.767, + 1, + 2.8, + 0, + 2.833, + 0, + 1, + 2.856, + 0, + 2.878, + 0, + 2.9, + 0, + 1, + 2.978, + 0, + 3.056, + 1, + 3.133, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.322, + 0, + 0.478, + 0, + 0.633, + 0, + 1, + 0.833, + 0, + 1.033, + -0.5, + 1.233, + -0.5, + 1, + 1.7, + -0.5, + 2.167, + -0.5, + 2.633, + -0.5, + 1, + 2.833, + -0.5, + 3.033, + 0, + 3.233, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.322, + 0, + 0.478, + 0, + 0.633, + 0, + 1, + 0.833, + 0, + 1.033, + -0.2, + 1.233, + -0.2, + 1, + 1.7, + -0.2, + 2.167, + -0.2, + 2.633, + -0.2, + 1, + 2.833, + -0.2, + 3.033, + 0, + 3.233, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + -0.1, + 1, + 0.056, + -0.1, + 0.111, + -0.1, + 0.167, + -0.1, + 0, + 5, + -0.1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + -0.1, + 1, + 0.056, + -0.1, + 0.111, + -0.1, + 0.167, + -0.1, + 0, + 5, + -0.1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm2", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm2", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamTeethOn", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGlassUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassWhite", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlight", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlightMove", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.333, + 0, + 0.5, + 0.5, + 0.667, + 0.5, + 1, + 0.922, + 0.5, + 1.178, + -3, + 1.433, + -3, + 1, + 1.789, + -3, + 2.144, + -3, + 2.5, + -3, + 1, + 2.722, + -3, + 2.944, + 0, + 3.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.333, + 0, + 0.5, + -0.538, + 0.667, + -1, + 1, + 0.878, + -1.585, + 1.089, + -1.707, + 1.3, + -1.707, + 1, + 1.711, + -1.707, + 2.122, + 0.274, + 2.533, + 0.274, + 1, + 2.767, + 0.274, + 3, + 0, + 3.233, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWaistAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyPosition", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.356, + 0, + 0.544, + 0, + 0.733, + 0, + 1, + 1.489, + 0, + 2.244, + 0, + 3, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.333, + 0, + 0.5, + 0, + 0.667, + 0, + 1, + 0.944, + 0, + 1.222, + 0.42, + 1.5, + 0.5, + 1, + 1.867, + 0.605, + 2.233, + 0.6, + 2.6, + 0.6, + 1, + 3.111, + 0.6, + 3.622, + 0, + 4.133, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeftShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.333, + 0, + 0.5, + 0, + 0.667, + 0, + 1, + 0.922, + 0, + 1.178, + -8.227, + 1.433, + -9, + 1, + 1.789, + -10.076, + 2.144, + -10, + 2.5, + -10, + 1, + 2.744, + -10, + 2.989, + 0, + 3.233, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamRightShoulderUp", + "Segments": [ + 0, + 8, + 1, + 0.056, + 8, + 0.111, + 8, + 0.167, + 8, + 1, + 0.267, + 8, + 0.367, + 8, + 0.467, + 8, + 1, + 0.533, + 8, + 0.6, + 4, + 0.667, + 4, + 1, + 0.767, + 4, + 0.867, + 9, + 0.967, + 9, + 1, + 1.5, + 9, + 2.033, + 9, + 2.567, + 9, + 1, + 2.722, + 9, + 2.878, + 0, + 3.033, + 0, + 1, + 3.267, + 0, + 3.5, + 8, + 3.733, + 8, + 0, + 5, + 8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllRotate", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFront", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSide", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBack", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSideFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBackFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamJacket", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamChainWaist", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchAX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBSwitch", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.3, + 0, + 0.433, + 0, + 0.567, + 0, + 1, + 0.611, + 0, + 0.656, + -1, + 0.7, + -1, + 1, + 0.733, + -1, + 0.767, + 0, + 0.8, + 0, + 1, + 1.667, + 0, + 2.533, + 0, + 3.4, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 1.011, + 0, + 1.856, + 0, + 2.7, + 0, + 1, + 2.756, + 0, + 2.811, + 16, + 2.867, + 16, + 1, + 2.889, + 16, + 2.911, + 16, + 2.933, + 16, + 1, + 3.089, + 16, + 3.244, + 0, + 3.4, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.344, + 0, + 0.522, + 0, + 0.7, + 0, + 1, + 0.744, + 0, + 0.789, + 30, + 0.833, + 30, + 1, + 1.456, + 30, + 2.078, + 30, + 2.7, + 30, + 1, + 2.756, + 30, + 2.811, + 16, + 2.867, + 16, + 1, + 2.889, + 16, + 2.911, + 16, + 2.933, + 16, + 1, + 3.089, + 16, + 3.244, + 0, + 3.4, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.3, + 0, + 0.433, + 0, + 0.567, + 0, + 1, + 0.7, + 0, + 0.833, + -6.9, + 0.967, + -6.9, + 1, + 1.544, + -6.9, + 2.122, + -6.9, + 2.7, + -6.9, + 1, + 2.756, + -6.9, + 2.811, + 0, + 2.867, + 0, + 1, + 2.889, + 0, + 2.911, + 0, + 2.933, + 0, + 1, + 3.089, + 0, + 3.244, + 0, + 3.4, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBRoll", + "Segments": [ + 0, + -12, + 1, + 0.056, + -12, + 0.111, + -12, + 0.167, + -12, + 1, + 0.3, + -12, + 0.433, + -12, + 0.567, + -12, + 1, + 0.611, + -12, + 0.656, + -9, + 0.7, + -9, + 1, + 1.367, + -9, + 2.033, + -9, + 2.7, + -9, + 1, + 2.756, + -9, + 2.811, + -12, + 2.867, + -12, + 1, + 2.889, + -12, + 2.911, + -12, + 2.933, + -12, + 1, + 3.089, + -12, + 3.244, + -12, + 3.4, + -12, + 0, + 5, + -12 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBLR", + "Segments": [ + 0, + 2, + 1, + 0.056, + 2, + 0.111, + 2, + 0.167, + 2, + 1, + 0.3, + 2, + 0.433, + 2, + 0.567, + 2, + 1, + 0.7, + 2, + 0.833, + -3.4, + 0.967, + -3.4, + 1, + 1.544, + -3.4, + 2.122, + -3.331, + 2.7, + -3.144, + 1, + 2.756, + -3.126, + 2.811, + 0, + 2.867, + 0, + 1, + 2.889, + 0, + 2.911, + 0, + 2.933, + 0, + 1, + 3.089, + 0, + 3.244, + 2, + 3.4, + 2, + 0, + 5, + 2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBUD", + "Segments": [ + 0, + -2, + 1, + 0.056, + -2, + 0.111, + -2, + 0.167, + -2, + 1, + 1.011, + -2, + 1.856, + 1.06, + 2.7, + 1.06, + 1, + 2.756, + 1.06, + 2.811, + 0.241, + 2.867, + 0, + 1, + 2.889, + -0.096, + 2.911, + 0.01, + 2.933, + -0.11, + 1, + 3.089, + -0.955, + 3.244, + -2, + 3.4, + -2, + 0, + 5, + -2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR01", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR02", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR03", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR01", + "Segments": [ + 0, + -7, + 1, + 0.056, + -7, + 0.111, + -7, + 0.167, + -7, + 1, + 0.378, + -7, + 0.589, + -7, + 0.8, + -7, + 1, + 0.989, + -7, + 1.178, + -5, + 1.367, + -5, + 1, + 1.744, + -5, + 2.122, + -5, + 2.5, + -5, + 1, + 2.589, + -5, + 2.678, + -6, + 2.767, + -6, + 1, + 2.789, + -6, + 2.811, + -6, + 2.833, + -6, + 1, + 3.022, + -6, + 3.211, + -7, + 3.4, + -7, + 0, + 5, + -7 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR02", + "Segments": [ + 0, + 18, + 1, + 0.056, + 18, + 0.111, + 18, + 0.167, + 18, + 1, + 0.444, + 18, + 0.722, + 18, + 1, + 18, + 1, + 1.356, + 18, + 1.711, + 16.881, + 2.067, + 15, + 1, + 2.211, + 14.236, + 2.356, + 14, + 2.5, + 14, + 1, + 2.589, + 14, + 2.678, + 16.023, + 2.767, + 18, + 1, + 2.811, + 18.988, + 2.856, + 19, + 2.9, + 19, + 1, + 3.067, + 19, + 3.233, + 18, + 3.4, + 18, + 0, + 5, + 18 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.3, + 0, + 0.433, + -6, + 0.567, + -6, + 1, + 0.611, + -6, + 0.656, + 9, + 0.7, + 9, + 1, + 0.8, + 9, + 0.9, + 0.266, + 1, + 0, + 1, + 1.322, + -0.858, + 1.644, + -1, + 1.967, + -1, + 1, + 2.211, + -1, + 2.456, + -1, + 2.7, + -1, + 1, + 2.744, + -1, + 2.789, + 14, + 2.833, + 14, + 1, + 2.867, + 14, + 2.9, + 14, + 2.933, + 14, + 1, + 3.078, + 14, + 3.222, + 0, + 3.367, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05", + "FadeInTime": 0.2, + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 1.011, + 0, + 1.856, + 0, + 2.7, + 0, + 1, + 2.756, + 0, + 2.811, + 30, + 2.867, + 30, + 1, + 2.889, + 30, + 2.911, + 30, + 2.933, + 30, + 1, + 3.089, + 30, + 3.244, + 0, + 3.4, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.3, + 0, + 0.433, + 0, + 0.567, + 0, + 1, + 0.611, + 0, + 0.656, + 7.5, + 0.7, + 7.5, + 1, + 0.811, + 7.5, + 0.922, + 0, + 1.033, + 0, + 1, + 1.589, + 0, + 2.144, + 0, + 2.7, + 0, + 1, + 2.756, + 0, + 2.811, + 21, + 2.867, + 21, + 1, + 2.889, + 21, + 2.911, + 21, + 2.933, + 21, + 1, + 3.089, + 21, + 3.244, + 0, + 3.4, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll3", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 1.011, + 0, + 1.856, + 0, + 2.7, + 0, + 1, + 2.756, + 0, + 2.811, + 30, + 2.867, + 30, + 1, + 2.889, + 30, + 2.911, + 30, + 2.933, + 30, + 1, + 3.089, + 30, + 3.244, + 0, + 3.4, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCLHandRoll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDLHand03Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER03", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER04", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchA", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchB", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAL", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAR", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmBR", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmCL", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmDL", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmER", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_04.motion3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_04.motion3.json new file mode 100644 index 000000000..8da501708 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_04.motion3.json @@ -0,0 +1,2316 @@ +{ + "Version": 3, + "Meta": { + "Duration": 3.33, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": true, + "CurveCount": 98, + "TotalSegmentCount": 278, + "TotalPointCount": 733, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.189, + 0, + 0.211, + 0, + 0.233, + 0, + 1, + 0.3, + 0, + 0.367, + 0, + 0.433, + 0, + 1, + 0.667, + 0, + 0.9, + 4.019, + 1.133, + 4.019, + 1, + 1.444, + 4.019, + 1.756, + 0, + 2.067, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + -9.011, + 1, + 0.056, + -9.011, + 0.111, + -9.011, + 0.167, + -9.011, + 1, + 0.222, + -9.011, + 0.278, + -9.011, + 0.333, + -9.011, + 1, + 0.544, + -9.011, + 0.756, + -30, + 0.967, + -30, + 1, + 1.089, + -30, + 1.211, + -30, + 1.333, + -30, + 1, + 1.567, + -30, + 1.8, + 0, + 2.033, + 0, + 1, + 2.067, + 0, + 2.1, + 0, + 2.133, + 0, + 1, + 2.356, + 0, + 2.578, + -5, + 2.8, + -5, + 0, + 3.333, + -5 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.233, + 0, + 0.3, + 0, + 0.367, + 0, + 1, + 0.622, + 0, + 0.878, + -4, + 1.133, + -4, + 1, + 1.533, + -4, + 1.933, + 1, + 2.333, + 1, + 0, + 3.333, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.311, + 1, + 0.456, + 1, + 0.6, + 1, + 1, + 0.689, + 1, + 0.778, + 0, + 0.867, + 0, + 1, + 1.133, + 0, + 1.4, + 0, + 1.667, + 0, + 1, + 1.756, + 0, + 1.844, + 1, + 1.933, + 1, + 0, + 3.333, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.311, + 1, + 0.456, + 1, + 0.6, + 1, + 1, + 0.689, + 1, + 0.778, + 0, + 0.867, + 0, + 1, + 1.133, + 0, + 1.4, + 0, + 1.667, + 0, + 1, + 1.756, + 0, + 1.844, + 1, + 1.933, + 1, + 0, + 3.333, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.311, + 0, + 0.456, + 0, + 0.6, + 0, + 1, + 0.689, + 0, + 0.778, + 0.2, + 0.867, + 0.2, + 1, + 1.133, + 0.2, + 1.4, + 0.2, + 1.667, + 0.2, + 1, + 1.756, + 0.2, + 1.844, + 0, + 1.933, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.311, + 0, + 0.456, + 0, + 0.6, + 0, + 1, + 0.689, + 0, + 0.778, + -0.8, + 0.867, + -0.8, + 1, + 1.133, + -0.8, + 1.4, + -0.8, + 1.667, + -0.8, + 1, + 1.756, + -0.8, + 1.844, + 0, + 1.933, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamTeethOn", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGlassUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.222, + 0, + 0.278, + 0, + 0.333, + 0, + 1, + 0.544, + 0, + 0.756, + -10, + 0.967, + -10, + 1, + 1.044, + -10, + 1.122, + 10, + 1.2, + 10, + 1, + 1.222, + 10, + 1.244, + 10, + 1.267, + 10, + 1, + 1.333, + 10, + 1.4, + 0, + 1.467, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassWhite", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.433, + 0, + 0.7, + 0, + 0.967, + 0, + 1, + 1.067, + 0, + 1.167, + 0.4, + 1.267, + 0.4, + 1, + 1.367, + 0.4, + 1.467, + 0, + 1.567, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlight", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.422, + 0, + 0.678, + 0, + 0.933, + 0, + 1, + 1.011, + 0, + 1.089, + 1, + 1.167, + 1, + 1, + 1.2, + 1, + 1.233, + 1, + 1.267, + 1, + 1, + 1.4, + 1, + 1.533, + 0, + 1.667, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlightMove", + "Segments": [ + 0, + -30, + 1, + 0.056, + -30, + 0.111, + -30, + 0.167, + -30, + 1, + 0.444, + -30, + 0.722, + -30, + 1, + -30, + 1, + 1.189, + -30, + 1.378, + 30, + 1.567, + 30, + 0, + 3.333, + 30 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.189, + 0, + 0.211, + 0, + 0.233, + 0, + 1, + 0.289, + 0, + 0.344, + 0, + 0.4, + 0, + 1, + 0.611, + 0, + 0.822, + 2, + 1.033, + 2, + 1, + 1.078, + 2, + 1.122, + 2, + 1.167, + 2, + 1, + 1.422, + 2, + 1.678, + 0, + 1.933, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.189, + 0, + 0.211, + 0, + 0.233, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWaistAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyPosition", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 0, + 0.433, + 0, + 1, + 0.633, + 0, + 0.833, + 2, + 1.033, + 2, + 1, + 1.244, + 2, + 1.456, + 0, + 1.667, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.233, + 0, + 0.3, + 0, + 0.367, + 0, + 1, + 0.722, + 0, + 1.078, + 1, + 1.433, + 1, + 1, + 1.667, + 1, + 1.9, + 1, + 2.133, + 1, + 0, + 3.333, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeftShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamRightShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.189, + 0, + 0.211, + 0, + 0.233, + 0, + 1, + 0.478, + 0, + 0.722, + 2.225, + 0.967, + 9, + 1, + 1.056, + 11.464, + 1.144, + 15, + 1.233, + 15, + 1, + 1.589, + 15, + 1.944, + -6, + 2.3, + -6, + 1, + 2.489, + -6, + 2.678, + -3, + 2.867, + -3, + 0, + 3.333, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllRotate", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFront", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSide", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBack", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSideFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBackFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamJacket", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamChainWaist", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchAX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBSwitch", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBRoll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBLR", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll3", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCLHandRoll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDLHand03Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER01", + "Segments": [ + 0, + 16, + 1, + 0.056, + 16, + 0.111, + 16, + 0.167, + 16, + 1, + 0.311, + 16, + 0.456, + 16, + 0.6, + 16, + 1, + 1.033, + 16, + 1.467, + 16, + 1.9, + 16, + 1, + 2.044, + 16, + 2.189, + 18, + 2.333, + 18, + 0, + 3.333, + 18 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER02", + "Segments": [ + 0, + 11, + 1, + 0.056, + 11, + 0.111, + 11, + 0.167, + 11, + 1, + 0.311, + 11, + 0.456, + 14.565, + 0.6, + 18, + 1, + 0.711, + 20.643, + 0.822, + 21, + 0.933, + 21, + 1, + 1.267, + 21, + 1.6, + 13.953, + 1.933, + 0, + 1, + 2.078, + -6.046, + 2.222, + -9, + 2.367, + -9, + 1, + 2.544, + -9, + 2.722, + -8, + 2.9, + -8, + 0, + 3.333, + -8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER03", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.189, + 1, + 0.211, + 1, + 0.233, + 1, + 1, + 0.356, + 1, + 0.478, + 1, + 0.6, + 1, + 1, + 0.711, + 1, + 0.822, + -5.698, + 0.933, + -7, + 1, + 1.033, + -8.171, + 1.133, + -8.083, + 1.233, + -9, + 1, + 1.389, + -10.427, + 1.544, + -11.838, + 1.7, + -11.838, + 1, + 1.933, + -11.838, + 2.167, + 19, + 2.4, + 19, + 1, + 2.578, + 19, + 2.756, + 15.092, + 2.933, + 15.092, + 0, + 3.333, + 15.092 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER04", + "Segments": [ + 0, + 30, + 1, + 0.056, + 30, + 0.111, + 30, + 0.167, + 30, + 1, + 0.422, + 30, + 0.678, + 30, + 0.933, + 30, + 1, + 1.089, + 30, + 1.244, + 30, + 1.4, + 30, + 1, + 1.744, + 30, + 2.089, + 9, + 2.433, + 9, + 0, + 3.333, + 9 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06", + "FadeInTime": 0.2, + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.311, + 1, + 0.456, + 1, + 0.6, + 1, + 0, + 3.333, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.311, + 0, + 0.456, + 0, + 0.6, + 0, + 1, + 0.711, + 0, + 0.822, + 12.92, + 0.933, + 14, + 1, + 1.278, + 17.347, + 1.622, + 18, + 1.967, + 18, + 1, + 2.144, + 18, + 2.322, + 3, + 2.5, + 3, + 0, + 3.333, + 3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.411, + 0, + 0.656, + -30, + 0.9, + -30, + 1, + 1.167, + -30, + 1.433, + -30, + 1.7, + -30, + 1, + 1.956, + -30, + 2.211, + -24, + 2.467, + -24, + 0, + 3.333, + -24 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchA", + "Segments": [ + 0, + 1, + 0, + 3.33, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchB", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAL", + "Segments": [ + 0, + 1, + 0, + 3.33, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAR", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmBR", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmCL", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmDL", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmER", + "Segments": [ + 0, + 1, + 0, + 3.33, + 1 + ] + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_05.motion3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_05.motion3.json new file mode 100644 index 000000000..f2b4621e1 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_05.motion3.json @@ -0,0 +1,2345 @@ +{ + "Version": 3, + "Meta": { + "Duration": 5, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": true, + "CurveCount": 96, + "TotalSegmentCount": 283, + "TotalPointCount": 752, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.4, + 0, + 0.633, + 0, + 0.867, + 0, + 1, + 1.167, + 0, + 1.467, + 13.505, + 1.767, + 16, + 1, + 2.011, + 18.033, + 2.256, + 17.623, + 2.5, + 17.623, + 1, + 2.856, + 17.623, + 3.211, + -4.813, + 3.567, + -6, + 1, + 3.8, + -6.779, + 4.033, + -6.496, + 4.267, + -6.496, + 0, + 5, + -6.496 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0.017, + 1, + 0.056, + 0.017, + 0.111, + 0.017, + 0.167, + 0.017, + 1, + 0.456, + 0.017, + 0.744, + 0.229, + 1.033, + 1, + 1, + 1.211, + 1.475, + 1.389, + 2, + 1.567, + 2, + 1, + 1.744, + 2, + 1.922, + 0, + 2.1, + 0, + 1, + 2.4, + 0, + 2.7, + 3, + 3, + 3, + 1, + 3.211, + 3, + 3.422, + -5.586, + 3.633, + -5.586, + 1, + 3.644, + -5.586, + 3.656, + -5.586, + 3.667, + -5.586, + 1, + 3.822, + -5.586, + 3.978, + 1, + 4.133, + 1, + 1, + 4.389, + 1, + 4.644, + 0, + 4.9, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.433, + 0, + 0.7, + -3, + 0.967, + -3, + 1, + 1.256, + -3, + 1.544, + 4.968, + 1.833, + 6, + 1, + 2.156, + 7.151, + 2.478, + 7, + 2.8, + 7, + 1, + 3, + 7, + 3.2, + -2, + 3.4, + -2, + 1, + 3.578, + -2, + 3.756, + 0, + 3.933, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.589, + 1, + 1.011, + 1, + 1.433, + 1, + 1, + 1.467, + 1, + 1.5, + 0, + 1.533, + 0, + 1, + 1.556, + 0, + 1.578, + 0, + 1.6, + 0, + 1, + 1.678, + 0, + 1.756, + 1, + 1.833, + 1, + 1, + 2.344, + 1, + 2.856, + 1, + 3.367, + 1, + 1, + 3.4, + 1, + 3.433, + 0, + 3.467, + 0, + 1, + 3.489, + 0, + 3.511, + 0, + 3.533, + 0, + 1, + 3.611, + 0, + 3.689, + 1, + 3.767, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.589, + 1, + 1.011, + 1, + 1.433, + 1, + 1, + 1.467, + 1, + 1.5, + 0, + 1.533, + 0, + 1, + 1.556, + 0, + 1.578, + 0, + 1.6, + 0, + 1, + 1.678, + 0, + 1.756, + 1, + 1.833, + 1, + 1, + 2.344, + 1, + 2.856, + 1, + 3.367, + 1, + 1, + 3.4, + 1, + 3.433, + 0, + 3.467, + 0, + 1, + 3.489, + 0, + 3.511, + 0, + 3.533, + 0, + 1, + 3.611, + 0, + 3.689, + 1, + 3.767, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.578, + 0, + 0.989, + 0, + 1.4, + 0, + 1, + 1.544, + 0, + 1.689, + 0.542, + 1.833, + 0.542, + 1, + 2.056, + 0.542, + 2.278, + 0.542, + 2.5, + 0.542, + 1, + 2.789, + 0.542, + 3.078, + 0, + 3.367, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.578, + 0, + 0.989, + 0, + 1.4, + 0, + 1, + 1.544, + 0, + 1.689, + -0.386, + 1.833, + -0.386, + 1, + 2.056, + -0.386, + 2.278, + -0.386, + 2.5, + -0.386, + 1, + 2.789, + -0.386, + 3.078, + 0, + 3.367, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamTeethOn", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGlassUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassWhite", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlight", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlightMove", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.356, + 0, + 0.544, + -1, + 0.733, + -1, + 1, + 1.044, + -1, + 1.356, + 4.155, + 1.667, + 5, + 1, + 1.911, + 5.664, + 2.156, + 5.5, + 2.4, + 5.5, + 1, + 2.656, + 5.5, + 2.911, + -1.168, + 3.167, + -2, + 1, + 3.5, + -3.085, + 3.833, + -3, + 4.167, + -3, + 0, + 5, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.356, + 0, + 0.544, + 1.915, + 0.733, + 2, + 1, + 0.878, + 2.065, + 1.022, + 2.028, + 1.167, + 2.088, + 1, + 1.344, + 2.162, + 1.522, + 2.904, + 1.7, + 2.904, + 1, + 1.867, + 2.904, + 2.033, + 2, + 2.2, + 2, + 1, + 2.356, + 2, + 2.511, + 2.5, + 2.667, + 2.5, + 1, + 2.978, + 2.5, + 3.289, + -1.006, + 3.6, + -1.006, + 1, + 3.8, + -1.006, + 4, + 0.139, + 4.2, + 0.139, + 1, + 4.378, + 0.139, + 4.556, + 0, + 4.733, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.433, + 0, + 0.7, + 0, + 0.967, + 0, + 1, + 1.222, + 0, + 1.478, + 1, + 1.733, + 1, + 1, + 2.456, + 1, + 3.178, + 1, + 3.9, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWaistAngleZ", + "Segments": [ + 0, + 0.124, + 1, + 0.056, + 0.124, + 0.111, + 0.124, + 0.167, + 0.124, + 1, + 0.478, + 0.124, + 0.789, + 2, + 1.1, + 2, + 1, + 1.3, + 2, + 1.5, + -1, + 1.7, + -1, + 1, + 2.2, + -1, + 2.7, + -1, + 3.2, + -1, + 1, + 3.456, + -1, + 3.711, + 0, + 3.967, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyPosition", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 1.656, + 0, + 3.144, + 0, + 4.633, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.411, + 0, + 0.656, + 0, + 0.9, + 0, + 1, + 1.411, + 0, + 1.922, + 0.501, + 2.433, + 0.501, + 1, + 2.511, + 0.501, + 2.589, + 0.501, + 2.667, + 0.501, + 1, + 3.178, + 0.501, + 3.689, + 0, + 4.2, + 0, + 1, + 4.322, + 0, + 4.444, + 0, + 4.567, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeftShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.356, + 0, + 0.544, + -6, + 0.733, + -6, + 1, + 0.933, + -6, + 1.133, + 6, + 1.333, + 6, + 1, + 1.522, + 6, + 1.711, + 2, + 1.9, + 2, + 0, + 5, + 2 + ] + }, + { + "Target": "Parameter", + "Id": "ParamRightShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.289, + 0, + 0.411, + 0, + 0.533, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllRotate", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFront", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSide", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBack", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSideFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBackFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamJacket", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamChainWaist", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchAX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBSwitch", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBRoll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBLR", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL01", + "Segments": [ + 0, + 0.232, + 1, + 0.056, + 0.232, + 0.111, + 0.232, + 0.167, + 0.232, + 0, + 5, + 0.232 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL02", + "Segments": [ + 0, + -0.373, + 1, + 0.056, + -0.373, + 0.111, + -0.373, + 0.167, + -0.373, + 0, + 5, + -0.373 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL03", + "Segments": [ + 0, + -0.305, + 1, + 0.056, + -0.305, + 0.111, + -0.305, + 0.167, + -0.305, + 0, + 5, + -0.305 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.333, + 0, + 0.5, + 0, + 0.667, + 0, + 1, + 1, + 0, + 1.333, + 1, + 1.667, + 1, + 1, + 1.889, + 1, + 2.111, + 1, + 2.333, + 1, + 1, + 2.689, + 1, + 3.044, + 0, + 3.4, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.333, + 0, + 0.5, + 0, + 0.667, + 0, + 1, + 1.011, + 0, + 1.356, + -3, + 1.7, + -3, + 1, + 1.922, + -3, + 2.144, + -3, + 2.367, + -3, + 1, + 2.722, + -3, + 3.078, + 0, + 3.433, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.333, + 0, + 0.5, + 0, + 0.667, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll3", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCLHandRoll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL01", + "Segments": [ + 0, + -0.938, + 1, + 0.056, + -0.938, + 0.111, + -0.938, + 0.167, + -0.938, + 1, + 0.322, + -0.938, + 0.478, + -0.938, + 0.633, + -0.938, + 1, + 0.956, + -0.938, + 1.278, + -4, + 1.6, + -4, + 1, + 1.944, + -4, + 2.289, + 4, + 2.633, + 4, + 1, + 3.033, + 4, + 3.433, + 0, + 3.833, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL02", + "Segments": [ + 0, + -1.719, + 1, + 0.056, + -1.719, + 0.111, + -1.719, + 0.167, + -1.719, + 1, + 0.322, + -1.719, + 0.478, + -1.719, + 0.633, + -1.719, + 1, + 0.967, + -1.719, + 1.3, + 4.142, + 1.633, + 7, + 1, + 1.978, + 9.953, + 2.322, + 10, + 2.667, + 10, + 1, + 3.111, + 10, + 3.556, + 6, + 4, + 6, + 0, + 5, + 6 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL03", + "Segments": [ + 0, + -4.688, + 1, + 0.056, + -4.688, + 0.111, + -4.688, + 0.167, + -4.688, + 1, + 0.322, + -4.688, + 0.478, + -4.688, + 0.633, + -4.688, + 1, + 0.978, + -4.688, + 1.322, + 14.713, + 1.667, + 18, + 1, + 2.022, + 21.393, + 2.378, + 21, + 2.733, + 21, + 1, + 2.967, + 21, + 3.2, + 13, + 3.433, + 13, + 0, + 5, + 13 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDLHand03Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 1.044, + 0, + 1.922, + -30, + 2.8, + -30, + 1, + 3.2, + -30, + 3.6, + -5.084, + 4, + -2, + 1, + 4.333, + 0.57, + 4.667, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER04", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchA", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchB", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAL", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAR", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmBR", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmCL", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmDL", + "Segments": [ + 0, + 1, + 0, + 5, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmER", + "Segments": [ + 0, + 0, + 0, + 5, + 0 + ] + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_06.motion3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_06.motion3.json new file mode 100644 index 000000000..20fd6d0fd --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_06.motion3.json @@ -0,0 +1,2082 @@ +{ + "Version": 3, + "Meta": { + "Duration": 3.33, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": true, + "CurveCount": 96, + "TotalSegmentCount": 246, + "TotalPointCount": 639, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 0, + 0.433, + 0, + 1, + 0.622, + 0, + 0.811, + 10, + 1, + 10, + 0, + 3.333, + 10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.178, + 0, + 0.189, + 0, + 0.2, + 0, + 1, + 0.267, + 0, + 0.333, + 1.753, + 0.4, + 3.095, + 1, + 0.444, + 3.989, + 0.489, + 3.997, + 0.533, + 3.997, + 1, + 0.744, + 3.997, + 0.956, + -27.096, + 1.167, + -27.096, + 1, + 1.256, + -27.096, + 1.344, + -25.324, + 1.433, + -25.065, + 1, + 1.811, + -23.961, + 2.189, + -23.671, + 2.567, + -23.671, + 0, + 3.333, + -23.671 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.211, + 0, + 0.256, + 0, + 0.3, + 0, + 1, + 0.378, + 0, + 0.456, + 0.319, + 0.533, + -1.334, + 1, + 0.7, + -4.877, + 0.867, + -11, + 1.033, + -11, + 1, + 1.289, + -11, + 1.544, + -10, + 1.8, + -10, + 0, + 3.333, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.344, + 1, + 0.522, + 1, + 0.7, + 1, + 1, + 0.744, + 1, + 0.789, + 0, + 0.833, + 0, + 1, + 0.989, + 0, + 1.144, + 0, + 1.3, + 0, + 1, + 1.378, + 0, + 1.456, + 1, + 1.533, + 1, + 0, + 3.333, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.344, + 1, + 0.522, + 1, + 0.7, + 1, + 1, + 0.744, + 1, + 0.789, + 0, + 0.833, + 0, + 1, + 0.989, + 0, + 1.144, + 0, + 1.3, + 0, + 1, + 1.378, + 0, + 1.456, + 1, + 1.533, + 1, + 0, + 3.333, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.389, + 0, + 0.611, + 0.1, + 0.833, + 0.1, + 1, + 1.067, + 0.1, + 1.3, + -0.4, + 1.533, + -0.4, + 0, + 3.333, + -0.4 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.389, + 0, + 0.611, + -0.2, + 0.833, + -0.2, + 1, + 1.067, + -0.2, + 1.3, + 0.7, + 1.533, + 0.7, + 0, + 3.333, + 0.7 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamTeethOn", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGlassUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassWhite", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlight", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlightMove", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + -0.5, + 0.4, + -0.5, + 1, + 0.622, + -0.5, + 0.844, + 6, + 1.067, + 6, + 1, + 1.3, + 6, + 1.533, + 5, + 1.767, + 5, + 0, + 3.333, + 5 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 0.625, + 0.4, + 0.625, + 1, + 0.633, + 0.625, + 0.867, + -4.741, + 1.1, + -4.741, + 1, + 1.333, + -4.741, + 1.567, + -4, + 1.8, + -4, + 0, + 3.333, + -4 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 0, + 0.433, + 0, + 1, + 0.611, + 0, + 0.789, + -3, + 0.967, + -3, + 0, + 3.333, + -3 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWaistAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 0, + 0.433, + 0, + 1, + 0.611, + 0, + 0.789, + -5, + 0.967, + -5, + 0, + 3.333, + -5 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyPosition", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + -3, + 0.4, + -3, + 1, + 0.544, + -3, + 0.689, + 0.972, + 0.833, + 3.4, + 1, + 1.144, + 8.63, + 1.456, + 10, + 1.767, + 10, + 0, + 3.333, + 10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.178, + 0, + 0.189, + 0, + 0.2, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeftShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 1.58, + 0.4, + 4, + 1, + 0.589, + 9.878, + 0.778, + 16.122, + 0.967, + 21, + 1, + 1.222, + 27.599, + 1.478, + 30, + 1.733, + 30, + 0, + 3.333, + 30 + ] + }, + { + "Target": "Parameter", + "Id": "ParamRightShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.244, + 0, + 0.322, + 2, + 0.4, + 2, + 1, + 0.589, + 2, + 0.778, + -19, + 0.967, + -19, + 1, + 1.222, + -19, + 1.478, + -13, + 1.733, + -13, + 0, + 3.333, + -13 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllRotate", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFront", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSide", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBack", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSideFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBackFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamJacket", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamChainWaist", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchAX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBSwitch", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBRoll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBLR", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL01", + "Segments": [ + 0, + 0.7, + 1, + 0.056, + 0.7, + 0.111, + 0.7, + 0.167, + 0.7, + 1, + 0.422, + 0.7, + 0.678, + 0.191, + 0.933, + -0.5, + 1, + 1.211, + -1.251, + 1.489, + -1.5, + 1.767, + -1.5, + 0, + 3.333, + -1.5 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL02", + "Segments": [ + 0, + -8, + 1, + 0.056, + -8, + 0.111, + -8, + 0.167, + -8, + 1, + 0.433, + -8, + 0.7, + -8, + 0.967, + -8, + 1, + 1.233, + -8, + 1.5, + -8, + 1.767, + -8, + 0, + 3.333, + -8 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL03", + "Segments": [ + 0, + -3, + 1, + 0.056, + -3, + 0.111, + -3, + 0.167, + -3, + 1, + 0.433, + -3, + 0.7, + -3, + 0.967, + -3, + 1, + 1.233, + -3, + 1.5, + 0, + 1.767, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL04", + "FadeInTime": 0.2, + "Segments": [ + 0, + -1, + 1, + 0.056, + -1, + 0.111, + -1, + 0.167, + -1, + 0, + 3.333, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR01", + "Segments": [ + 0, + 0.7, + 1, + 0.056, + 0.7, + 0.111, + 0.7, + 0.167, + 0.7, + 1, + 0.422, + 0.7, + 0.678, + 0.191, + 0.933, + -0.5, + 1, + 1.211, + -1.251, + 1.489, + -1.5, + 1.767, + -1.5, + 0, + 3.333, + -1.5 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR02", + "Segments": [ + 0, + -8, + 1, + 0.056, + -8, + 0.111, + -8, + 0.167, + -8, + 1, + 0.433, + -8, + 0.7, + -8, + 0.967, + -8, + 1, + 1.233, + -8, + 1.5, + -7, + 1.767, + -7, + 0, + 3.333, + -7 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR03", + "Segments": [ + 0, + -3, + 1, + 0.056, + -3, + 0.111, + -3, + 0.167, + -3, + 1, + 0.433, + -3, + 0.7, + -3, + 0.967, + -3, + 1, + 1.233, + -3, + 1.5, + -10, + 1.767, + -10, + 0, + 3.333, + -10 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR04", + "FadeInTime": 0.2, + "Segments": [ + 0, + -1, + 1, + 0.056, + -1, + 0.111, + -1, + 0.167, + -1, + 0, + 3.333, + -1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll3", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCLHandRoll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDLHand03Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER04", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 3.333, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchA", + "Segments": [ + 0, + 1, + 0, + 3.33, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchB", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAL", + "Segments": [ + 0, + 1, + 0, + 3.33, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAR", + "Segments": [ + 0, + 1, + 0, + 3.33, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmBR", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmCL", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmDL", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmER", + "Segments": [ + 0, + 0, + 0, + 3.33, + 0 + ] + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_07.motion3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_07.motion3.json new file mode 100644 index 000000000..0809923ce --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/motions/mtn_07.motion3.json @@ -0,0 +1,1907 @@ +{ + "Version": 3, + "Meta": { + "Duration": 4, + "Fps": 30.0, + "Loop": true, + "AreBeziersRestricted": true, + "CurveCount": 96, + "TotalSegmentCount": 221, + "TotalPointCount": 564, + "UserDataCount": 0, + "TotalUserDataSize": 0 + }, + "Curves": [ + { + "Target": "Parameter", + "Id": "ParamAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.333, + 0, + 0.5, + 0, + 0.667, + 0, + 1, + 0.767, + 0, + 0.867, + -13, + 0.967, + -13, + 1, + 1.067, + -13, + 1.167, + 11, + 1.267, + 11, + 1, + 1.4, + 11, + 1.533, + -8, + 1.667, + -8, + 1, + 1.833, + -8, + 2, + 0, + 2.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.2, + 0, + 0.233, + 0, + 0.267, + 0, + 1, + 0.333, + 0, + 0.4, + 9, + 0.467, + 9, + 1, + 0.7, + 9, + 0.933, + -6, + 1.167, + -6, + 1, + 1.6, + -6, + 2.033, + -1, + 2.467, + -1, + 1, + 2.622, + -1, + 2.778, + -4, + 2.933, + -4, + 1, + 3.078, + -4, + 3.222, + 0, + 3.367, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.3, + 0, + 0.433, + 4, + 0.567, + 4, + 1, + 0.978, + 4, + 1.389, + 0, + 1.8, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLOpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.289, + 1, + 0.411, + 1, + 0.533, + 1, + 1, + 0.622, + 1, + 0.711, + 0, + 0.8, + 0, + 1, + 1.522, + 0, + 2.244, + 0, + 2.967, + 0, + 1, + 3.078, + 0, + 3.189, + 1, + 3.3, + 1, + 0, + 4, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeROpen", + "Segments": [ + 0, + 1, + 1, + 0.056, + 1, + 0.111, + 1, + 0.167, + 1, + 1, + 0.289, + 1, + 0.411, + 1, + 0.533, + 1, + 1, + 0.622, + 1, + 0.711, + 0, + 0.8, + 0, + 1, + 1.522, + 0, + 2.244, + 0, + 2.967, + 0, + 1, + 3.078, + 0, + 3.189, + 1, + 3.3, + 1, + 0, + 4, + 1 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRSmile", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.289, + 0, + 0.411, + -0.4, + 0.533, + -0.4, + 1, + 1.344, + -0.4, + 2.156, + -0.4, + 2.967, + -0.4, + 1, + 3.078, + -0.4, + 3.189, + 0, + 3.3, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamEyeBallForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRAngle", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowLForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBrowRForm2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamTeethOn", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamCheek", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGlassUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassWhite", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlight", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamGrassHighlightMove", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 2.02, + 0.433, + 2.02, + 1, + 0.856, + 2.02, + 1.278, + 0, + 1.7, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWaistAngleZ", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBodyPosition", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamBreath", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.256, + 0, + 0.344, + 0.5, + 0.433, + 0.5, + 1, + 0.633, + 0.5, + 0.833, + 0.279, + 1.033, + 0.2, + 1, + 1.467, + 0.029, + 1.9, + 0, + 2.333, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamLeftShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.278, + 0, + 0.389, + 10, + 0.5, + 10, + 1, + 0.633, + 10, + 0.767, + -5, + 0.9, + -5, + 0, + 4, + -5 + ] + }, + { + "Target": "Parameter", + "Id": "ParamRightShoulderUp", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 1, + 0.278, + 0, + 0.389, + 10, + 0.5, + 10, + 1, + 0.633, + 10, + 0.767, + -5, + 0.9, + -5, + 0, + 4, + -5 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllY", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamAllRotate", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFront", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSide", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBack", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairSideFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamHairBackFuwa", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamJacket", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamChainWaist", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchSwingA2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchAX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBSwitch", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBOpen2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBX", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBRoll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBLR", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamWatchBUD", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAL04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmAR04", + "FadeInTime": 0.2, + "Segments": [ + 0, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand01Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmBRHand05Roll3", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCR03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmCLHandRoll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDL03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmDLHand03Roll", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER01", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER02", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER03", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmER04", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand04Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll1", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "Parameter", + "Id": "ParamArmERHand06Roll2", + "Segments": [ + 0, + 0, + 1, + 0.056, + 0, + 0.111, + 0, + 0.167, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchA", + "Segments": [ + 0, + 1, + 0, + 4, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartWatchB", + "Segments": [ + 0, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAL", + "Segments": [ + 0, + 1, + 0, + 4, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmAR", + "Segments": [ + 0, + 1, + 0, + 4, + 1 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmBR", + "Segments": [ + 0, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmCL", + "Segments": [ + 0, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmDL", + "Segments": [ + 0, + 0, + 0, + 4, + 0 + ] + }, + { + "Target": "PartOpacity", + "Id": "PartArmER", + "Segments": [ + 0, + 0, + 0, + 4, + 0 + ] + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori.pose3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori.pose3.json new file mode 100644 index 000000000..c3da66e5a --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori.pose3.json @@ -0,0 +1,44 @@ +{ + "Type": "Live2D Pose", + "FadeInTime": 0.2, + "Groups": [ + [ + { + "Id": "PartArmAL", + "Link": [] + }, + { + "Id": "PartArmCL", + "Link": [] + }, + { + "Id": "PartArmDL", + "Link": [] + } + ], + [ + { + "Id": "PartArmAR", + "Link": [] + }, + { + "Id": "PartArmBR", + "Link": [] + }, + { + "Id": "PartArmER", + "Link": [] + } + ], + [ + { + "Id": "PartWatchA", + "Link": [] + }, + { + "Id": "PartWatchB", + "Link": [] + } + ] + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.4096/texture_00.png b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.4096/texture_00.png new file mode 100644 index 000000000..c677c881c Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.4096/texture_00.png differ diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.cdi3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.cdi3.json new file mode 100644 index 000000000..ada83b4ca --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.cdi3.json @@ -0,0 +1,711 @@ +{ + "Version": 3, + "Parameters": [ + { + "Id": "ParamAngleX", + "GroupId": "", + "Name": "角度 X" + }, + { + "Id": "ParamAngleY", + "GroupId": "", + "Name": "角度 Y" + }, + { + "Id": "ParamAngleZ", + "GroupId": "", + "Name": "角度 Z" + }, + { + "Id": "ParamEyeLOpen", + "GroupId": "ParamGroupExpression", + "Name": "左眼 开闭" + }, + { + "Id": "ParamEyeLSmile", + "GroupId": "ParamGroupExpression", + "Name": "左眼 微笑" + }, + { + "Id": "ParamEyeLForm", + "GroupId": "ParamGroupExpression", + "Name": "左眼 变形" + }, + { + "Id": "ParamEyeROpen", + "GroupId": "ParamGroupExpression", + "Name": "右眼 开闭" + }, + { + "Id": "ParamEyeRSmile", + "GroupId": "ParamGroupExpression", + "Name": "右眼 微笑" + }, + { + "Id": "ParamEyeRForm", + "GroupId": "ParamGroupExpression", + "Name": "右眼 变形" + }, + { + "Id": "ParamEyeBallX", + "GroupId": "ParamGroupExpression", + "Name": "眼珠 X" + }, + { + "Id": "ParamEyeBallY", + "GroupId": "ParamGroupExpression", + "Name": "眼珠 Y" + }, + { + "Id": "ParamEyeBallForm", + "GroupId": "ParamGroupExpression", + "Name": "眼珠 缩放" + }, + { + "Id": "ParamBrowLY", + "GroupId": "ParamGroupExpression", + "Name": "左眉 上下" + }, + { + "Id": "ParamBrowRY", + "GroupId": "ParamGroupExpression", + "Name": "右眉 上下" + }, + { + "Id": "ParamBrowLX", + "GroupId": "ParamGroupExpression", + "Name": "左眉 左右" + }, + { + "Id": "ParamBrowRX", + "GroupId": "ParamGroupExpression", + "Name": "右眉 左右" + }, + { + "Id": "ParamBrowLAngle", + "GroupId": "ParamGroupExpression", + "Name": "左眉 角度" + }, + { + "Id": "ParamBrowRAngle", + "GroupId": "ParamGroupExpression", + "Name": "右眉 角度" + }, + { + "Id": "ParamBrowLForm", + "GroupId": "ParamGroupExpression", + "Name": "左眉 变形" + }, + { + "Id": "ParamBrowLForm2", + "GroupId": "ParamGroupExpression", + "Name": "左眉 变形2" + }, + { + "Id": "ParamBrowRForm", + "GroupId": "ParamGroupExpression", + "Name": "右眉 变形" + }, + { + "Id": "ParamBrowRForm2", + "GroupId": "ParamGroupExpression", + "Name": "右眉 变形2" + }, + { + "Id": "ParamMouthForm", + "GroupId": "ParamGroupExpression", + "Name": "嘴 变形" + }, + { + "Id": "ParamMouthOpenY", + "GroupId": "ParamGroupExpression", + "Name": "嘴 开闭" + }, + { + "Id": "ParamMouthForm2", + "GroupId": "ParamGroupExpression", + "Name": "嘴 变形2" + }, + { + "Id": "ParamTeethOn", + "GroupId": "ParamGroupExpression", + "Name": "牙齿的显示" + }, + { + "Id": "ParamCheek", + "GroupId": "ParamGroupExpression", + "Name": "害羞" + }, + { + "Id": "ParamGlassUD", + "GroupId": "ParamGroupExpression", + "Name": "眼镜 上下" + }, + { + "Id": "ParamGrassWhite", + "GroupId": "ParamGroupExpression", + "Name": "镜片 白" + }, + { + "Id": "ParamGrassHighlight", + "GroupId": "ParamGroupExpression", + "Name": "镜片 反光显示" + }, + { + "Id": "ParamGrassHighlightMove", + "GroupId": "ParamGroupExpression", + "Name": "镜片 反光移动" + }, + { + "Id": "ParamBodyAngleX", + "GroupId": "ParamGroupBody", + "Name": "身体的旋转 X" + }, + { + "Id": "ParamBodyAngleY", + "GroupId": "ParamGroupBody", + "Name": "身体的旋转 Y" + }, + { + "Id": "ParamBodyAngleZ", + "GroupId": "ParamGroupBody", + "Name": "身体的旋转 Z" + }, + { + "Id": "ParamWaistAngleZ", + "GroupId": "ParamGroupBody", + "Name": "腰的旋转 Z" + }, + { + "Id": "ParamBodyPosition", + "GroupId": "ParamGroupBody", + "Name": "身体的前后" + }, + { + "Id": "ParamBreath", + "GroupId": "ParamGroupBody", + "Name": "呼吸" + }, + { + "Id": "ParamLeftShoulderUp", + "GroupId": "ParamGroupBody", + "Name": "左肩的上下" + }, + { + "Id": "ParamRightShoulderUp", + "GroupId": "ParamGroupBody", + "Name": "右肩的上下" + }, + { + "Id": "ParamAllX", + "GroupId": "ParamGroup", + "Name": "整体的移动 X" + }, + { + "Id": "ParamAllY", + "GroupId": "ParamGroup", + "Name": "整体的移动 Y" + }, + { + "Id": "ParamAllRotate", + "GroupId": "ParamGroup", + "Name": "整体的旋转" + }, + { + "Id": "ParamHairFront", + "GroupId": "ParamGroupSway", + "Name": "头发摇动 前" + }, + { + "Id": "ParamHairSide", + "GroupId": "ParamGroupSway", + "Name": "头发摇动 侧" + }, + { + "Id": "ParamHairBack", + "GroupId": "ParamGroupSway", + "Name": "头发摇动 后" + }, + { + "Id": "ParamHairFrontFuwa", + "GroupId": "ParamGroupSway", + "Name": "前发 蓬松" + }, + { + "Id": "ParamHairSideFuwa", + "GroupId": "ParamGroupSway", + "Name": "侧发 蓬松" + }, + { + "Id": "ParamHairBackFuwa", + "GroupId": "ParamGroupSway", + "Name": "后发 蓬松" + }, + { + "Id": "ParamJacket", + "GroupId": "ParamGroupSway", + "Name": "燕尾的摇动" + }, + { + "Id": "ParamChainWaist", + "GroupId": "ParamGroupSway", + "Name": "表链A的摇动" + }, + { + "Id": "ParamWatchSwingA1", + "GroupId": "ParamGroupSway", + "Name": "怀表A 摇动1" + }, + { + "Id": "ParamWatchSwingA2", + "GroupId": "ParamGroupSway", + "Name": "怀表A 摇动2" + }, + { + "Id": "ParamWatchBChain", + "GroupId": "ParamGroupSway", + "Name": "怀表B 表链的摇动" + }, + { + "Id": "ParamWatchAX", + "GroupId": "ParamGroup8", + "Name": "怀表A 横向旋转" + }, + { + "Id": "ParamWatchBSwitch", + "GroupId": "ParamGroup9", + "Name": "怀表B 开关" + }, + { + "Id": "ParamWatchBOpen", + "GroupId": "ParamGroup9", + "Name": "怀表B 表盖的开闭" + }, + { + "Id": "ParamWatchBOpen2", + "GroupId": "ParamGroup9", + "Name": "怀表B 表盘的开闭" + }, + { + "Id": "ParamWatchBX", + "GroupId": "ParamGroup9", + "Name": "怀表B 横向旋转" + }, + { + "Id": "ParamWatchBRoll", + "GroupId": "ParamGroup9", + "Name": "怀表B 旋转" + }, + { + "Id": "ParamWatchBLR", + "GroupId": "ParamGroup9", + "Name": "怀表B 左右" + }, + { + "Id": "ParamWatchBUD", + "GroupId": "ParamGroup9", + "Name": "怀表B 上下" + }, + { + "Id": "ParamArmAL01", + "GroupId": "ParamGroup3", + "Name": "左手臂A 肩" + }, + { + "Id": "ParamArmAL02", + "GroupId": "ParamGroup3", + "Name": "左肩A 手肘旋转" + }, + { + "Id": "ParamArmAL03", + "GroupId": "ParamGroup3", + "Name": "左手臂A 手腕" + }, + { + "Id": "ParamArmAL04", + "GroupId": "ParamGroup3", + "Name": "左手臂A 前臂的前后" + }, + { + "Id": "ParamArmAR01", + "GroupId": "ParamGroup2", + "Name": "右手臂A 肩的旋转" + }, + { + "Id": "ParamArmAR02", + "GroupId": "ParamGroup2", + "Name": "右手臂A 手肘的旋转" + }, + { + "Id": "ParamArmAR03", + "GroupId": "ParamGroup2", + "Name": "右手臂A 手腕的旋转" + }, + { + "Id": "ParamArmAR04", + "GroupId": "ParamGroup2", + "Name": "右手臂A 前臂的前后" + }, + { + "Id": "ParamArmBR01", + "GroupId": "ParamGroup4", + "Name": "右手臂B 肩的旋转" + }, + { + "Id": "ParamArmBR02", + "GroupId": "ParamGroup4", + "Name": "右手臂B 手肘的旋转" + }, + { + "Id": "ParamArmBR03", + "GroupId": "ParamGroup4", + "Name": "右手臂B 手腕的旋转" + }, + { + "Id": "ParamArmBRHand01", + "GroupId": "ParamGroup4", + "Name": "右手01 显示" + }, + { + "Id": "ParamArmBRHand01Roll", + "GroupId": "ParamGroup4", + "Name": "右手01 手指弯曲" + }, + { + "Id": "ParamArmBRHand05", + "GroupId": "ParamGroup4", + "Name": "右手05 显示" + }, + { + "Id": "ParamArmBRHand05Roll1", + "GroupId": "ParamGroup4", + "Name": "右手05 手指弯曲1" + }, + { + "Id": "ParamArmBRHand05Roll2", + "GroupId": "ParamGroup4", + "Name": "右手05 手指弯曲2" + }, + { + "Id": "ParamArmBRHand05Roll3", + "GroupId": "ParamGroup4", + "Name": "右手05 手指弯曲3" + }, + { + "Id": "ParamArmCR01", + "GroupId": "ParamGroup5", + "Name": "左手臂C 肩的旋转" + }, + { + "Id": "ParamArmCR02", + "GroupId": "ParamGroup5", + "Name": "左手臂C 手肘的旋转" + }, + { + "Id": "ParamArmCR03", + "GroupId": "ParamGroup5", + "Name": "左手臂C 手腕的旋转" + }, + { + "Id": "ParamArmCLHandRoll1", + "GroupId": "ParamGroup5", + "Name": "左手C 手指弯曲1" + }, + { + "Id": "ParamArmDL01", + "GroupId": "ParamGroup6", + "Name": "左手臂D 肩的旋转" + }, + { + "Id": "ParamArmDL02", + "GroupId": "ParamGroup6", + "Name": "左手臂D 手肘的旋转" + }, + { + "Id": "ParamArmDL03", + "GroupId": "ParamGroup6", + "Name": "左手臂D 手腕的旋转" + }, + { + "Id": "ParamArmDLHand03Roll", + "GroupId": "ParamGroup6", + "Name": "左手03 手指弯曲" + }, + { + "Id": "ParamArmER01", + "GroupId": "ParamGroup7", + "Name": "右手臂E 肩的旋转" + }, + { + "Id": "ParamArmER02", + "GroupId": "ParamGroup7", + "Name": "右手臂E 手肘的旋转" + }, + { + "Id": "ParamArmER03", + "GroupId": "ParamGroup7", + "Name": "右手臂E 手腕的旋转" + }, + { + "Id": "ParamArmER04", + "GroupId": "ParamGroup7", + "Name": "右手臂E 上臂的长度" + }, + { + "Id": "ParamArmERHand04", + "GroupId": "ParamGroup7", + "Name": "右手04 显示" + }, + { + "Id": "ParamArmERHand04Roll1", + "GroupId": "ParamGroup7", + "Name": "右手04 手指弯曲1" + }, + { + "Id": "ParamArmERHand04Roll2", + "GroupId": "ParamGroup7", + "Name": "右手04 手指弯曲2" + }, + { + "Id": "ParamArmERHand06", + "GroupId": "ParamGroup7", + "Name": "右手06 显示" + }, + { + "Id": "ParamArmERHand06Roll1", + "GroupId": "ParamGroup7", + "Name": "右手06 手指弯曲1" + }, + { + "Id": "ParamArmERHand06Roll2", + "GroupId": "ParamGroup7", + "Name": "右手06 手指弯曲2" + } + ], + "ParameterGroups": [ + { + "Id": "ParamGroupExpression", + "GroupId": "", + "Name": "表情" + }, + { + "Id": "ParamGroupBody", + "GroupId": "", + "Name": "身体" + }, + { + "Id": "ParamGroup", + "GroupId": "", + "Name": "整体移动" + }, + { + "Id": "ParamGroupSway", + "GroupId": "", + "Name": "摇动" + }, + { + "Id": "ParamGroup8", + "GroupId": "", + "Name": "怀表A" + }, + { + "Id": "ParamGroup9", + "GroupId": "", + "Name": "怀表B" + }, + { + "Id": "ParamGroup3", + "GroupId": "", + "Name": "左手臂A" + }, + { + "Id": "ParamGroup2", + "GroupId": "", + "Name": "右手臂A" + }, + { + "Id": "ParamGroup4", + "GroupId": "", + "Name": "右手臂B" + }, + { + "Id": "ParamGroup5", + "GroupId": "", + "Name": "左手臂C" + }, + { + "Id": "ParamGroup6", + "GroupId": "", + "Name": "左手臂D" + }, + { + "Id": "ParamGroup7", + "GroupId": "", + "Name": "右手臂E" + } + ], + "Parts": [ + { + "Id": "PartCredit", + "Name": "名牌" + }, + { + "Id": "PartCore", + "Name": "CORE" + }, + { + "Id": "PartGlass", + "Name": "眼镜" + }, + { + "Id": "PartWatchA", + "Name": "怀表A" + }, + { + "Id": "PartWatchB", + "Name": "怀表B" + }, + { + "Id": "PartHairFront", + "Name": "前发" + }, + { + "Id": "PartHead", + "Name": "头" + }, + { + "Id": "PartUpperBody", + "Name": "上半身" + }, + { + "Id": "PartHairBack", + "Name": "后发" + }, + { + "Id": "PartLowerBody", + "Name": "下半身" + }, + { + "Id": "PartArmAL", + "Name": "左手臂A" + }, + { + "Id": "PartArmAR", + "Name": "右手臂A" + }, + { + "Id": "PartArmBR", + "Name": "右手臂B" + }, + { + "Id": "PartArmCL", + "Name": "左手臂C" + }, + { + "Id": "PartArmDL", + "Name": "左手臂D" + }, + { + "Id": "PartArmER", + "Name": "右手臂E" + }, + { + "Id": "PartEyeBlow", + "Name": "眉毛" + }, + { + "Id": "PartEyeR", + "Name": "右眼" + }, + { + "Id": "PartEyeL", + "Name": "左眼" + }, + { + "Id": "PartHairLine", + "Name": "发际线" + }, + { + "Id": "PartHairShadow", + "Name": "头发阴影" + }, + { + "Id": "PartNose", + "Name": "鼻子" + }, + { + "Id": "PartMouth", + "Name": "嘴" + }, + { + "Id": "PartJacket", + "Name": "燕尾服" + }, + { + "Id": "PartArmALFore", + "Name": "左手臂A 前臂" + }, + { + "Id": "PartArmARFore", + "Name": "右手臂A 前臂" + }, + { + "Id": "PartHand11", + "Name": "手套_1" + }, + { + "Id": "PartHand51", + "Name": "手套_5" + }, + { + "Id": "PartHand21", + "Name": "手套_2" + }, + { + "Id": "PartHand31", + "Name": "手套_3" + }, + { + "Id": "PartHand41", + "Name": "手套_4" + }, + { + "Id": "PartHand61", + "Name": "手套_6" + } + ], + "CombinedParameters": [ + [ + "ParamAngleX", + "ParamAngleY" + ], + [ + "ParamEyeBallX", + "ParamEyeBallY" + ], + [ + "ParamMouthForm", + "ParamMouthOpenY" + ], + [ + "ParamBodyAngleX", + "ParamBodyAngleY" + ], + [ + "ParamLeftShoulderUp", + "ParamRightShoulderUp" + ], + [ + "ParamAllX", + "ParamAllY" + ], + [ + "ParamWatchSwingA1", + "ParamWatchSwingA2" + ], + [ + "ParamWatchBLR", + "ParamWatchBUD" + ] + ] +} \ No newline at end of file diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.moc3 b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.moc3 new file mode 100644 index 000000000..9f7303b43 Binary files /dev/null and b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.moc3 differ diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.model3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.model3.json new file mode 100644 index 000000000..9da5c25ae --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.model3.json @@ -0,0 +1,123 @@ +{ + "Version": 3, + "FileReferences": { + "Moc": "natori_pro_t06.moc3", + "Textures": [ + "natori_pro_t06.4096/texture_00.png" + ], + "Physics": "natori_pro_t06.physics3.json", + "Pose": "natori.pose3.json", + "DisplayInfo": "natori_pro_t06.cdi3.json", + "Expressions": [ + { + "Name": "Angry", + "File": "exp/Angry.exp3.json" + }, + { + "Name": "Blushing", + "File": "exp/Blushing.exp3.json" + }, + { + "Name": "Normal", + "File": "exp/Normal.exp3.json" + }, + { + "Name": "Sad", + "File": "exp/Sad.exp3.json" + }, + { + "Name": "Smile", + "File": "exp/Smile.exp3.json" + }, + { + "Name": "Surprised", + "File": "exp/Surprised.exp3.json" + }, + { + "Name": "exp_01", + "File": "exp/exp_01.exp3.json" + }, + { + "Name": "exp_02", + "File": "exp/exp_02.exp3.json" + }, + { + "Name": "exp_03", + "File": "exp/exp_03.exp3.json" + }, + { + "Name": "exp_04", + "File": "exp/exp_04.exp3.json" + }, + { + "Name": "exp_05", + "File": "exp/exp_05.exp3.json" + } + ], + "Motions": { + "Idle": [ + { + "File": "motions/mtn_00.motion3.json" + }, + { + "File": "motions/mtn_01.motion3.json" + }, + { + "File": "motions/mtn_02.motion3.json" + } + ], + "Tap": [ + { + "File": "motions/mtn_03.motion3.json" + } + ], + "FlickUp@Head": [ + { + "File": "motions/mtn_04.motion3.json" + } + ], + "Flick@Body": [ + { + "File": "motions/mtn_05.motion3.json" + } + ], + "FlickDown@Body": [ + { + "File": "motions/mtn_06.motion3.json" + } + ], + "Tap@Head": [ + { + "File": "motions/mtn_07.motion3.json" + } + ] + } + }, + "Groups": [ + { + "Target": "Parameter", + "Name": "LipSync", + "Ids": [ + "ParamMouthOpenY" + ] + }, + { + "Target": "Parameter", + "Name": "EyeBlink", + "Ids": [ + "ParamEyeLOpen", + "ParamEyeROpen" + ] + } + ], + "HitAreas": [ + { + "Id": "HitAreaHead", + "Name": "" + }, + { + "Id": "HitAreaBody", + "Name": "" + } + ] +} diff --git a/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.physics3.json b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.physics3.json new file mode 100644 index 000000000..857c66592 --- /dev/null +++ b/main/feedback-backend/admin-ui/resources/natori_pro_zh/runtime/natori_pro_t06.physics3.json @@ -0,0 +1,966 @@ +{ + "Version": 3, + "Meta": { + "PhysicsSettingCount": 11, + "TotalInputCount": 34, + "TotalOutputCount": 12, + "VertexCount": 23, + "EffectiveForces": { + "Gravity": { + "X": 0, + "Y": -1 + }, + "Wind": { + "X": 0, + "Y": 0 + } + }, + "PhysicsDictionary": [ + { + "Id": "PhysicsSetting1", + "Name": "前髪 揺れ" + }, + { + "Id": "PhysicsSetting2", + "Name": "横髪 揺れ" + }, + { + "Id": "PhysicsSetting3", + "Name": "後ろ髪 揺れ" + }, + { + "Id": "PhysicsSetting4", + "Name": "前髪ふわ" + }, + { + "Id": "PhysicsSetting5", + "Name": "横髪ふわ" + }, + { + "Id": "PhysicsSetting6", + "Name": "後ろ髪ふわ" + }, + { + "Id": "PhysicsSetting7", + "Name": "燕尾揺れ" + }, + { + "Id": "PhysicsSetting8", + "Name": "懐中時計腰 揺れ" + }, + { + "Id": "PhysicsSetting9", + "Name": "腰のチェーン揺れ" + }, + { + "Id": "PhysicsSetting10", + "Name": "懐中時計腰 横回転" + }, + { + "Id": "PhysicsSetting11", + "Name": "懐中時計B チェーン揺れ" + } + ] + }, + "PhysicsSettings": [ + { + "Id": "PhysicsSetting1", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamHairFront" + }, + "VertexIndex": 1, + "Scale": 1.824, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 12.7 + }, + "Mobility": 0.95, + "Delay": 0.9, + "Acceleration": 1, + "Radius": 12.7 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting2", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamHairSide" + }, + "VertexIndex": 1, + "Scale": 2, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 18.2 + }, + "Mobility": 0.95, + "Delay": 0.9, + "Acceleration": 1, + "Radius": 18.2 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting3", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleX" + }, + "Weight": 60, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleZ" + }, + "Weight": 60, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 40, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 40, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamHairBack" + }, + "VertexIndex": 1, + "Scale": 2, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 14.3 + }, + "Mobility": 1, + "Delay": 0.9, + "Acceleration": 1.42, + "Radius": 14.3 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting4", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleY" + }, + "Weight": 35, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleY" + }, + "Weight": 30, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyPosition" + }, + "Weight": 35, + "Type": "X", + "Reflect": true + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamHairFrontFuwa" + }, + "VertexIndex": 1, + "Scale": 3, + "Weight": 100, + "Type": "Angle", + "Reflect": true + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 11.9 + }, + "Mobility": 0.79, + "Delay": 0.9, + "Acceleration": 1, + "Radius": 11.9 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting5", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleY" + }, + "Weight": 35, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleY" + }, + "Weight": 30, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyPosition" + }, + "Weight": 35, + "Type": "X", + "Reflect": true + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamHairSideFuwa" + }, + "VertexIndex": 1, + "Scale": 3.5, + "Weight": 100, + "Type": "Angle", + "Reflect": true + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 14.3 + }, + "Mobility": 0.79, + "Delay": 0.9, + "Acceleration": 1.1, + "Radius": 14.3 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting6", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamAngleY" + }, + "Weight": 35, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleY" + }, + "Weight": 30, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyPosition" + }, + "Weight": 35, + "Type": "X", + "Reflect": true + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamHairBackFuwa" + }, + "VertexIndex": 1, + "Scale": 5, + "Weight": 100, + "Type": "Angle", + "Reflect": true + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 11.3 + }, + "Mobility": 0.79, + "Delay": 0.9, + "Acceleration": 1.16, + "Radius": 11.3 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting7", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 70, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamWaistAngleZ" + }, + "Weight": 30, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamJacket" + }, + "VertexIndex": 1, + "Scale": 1, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 31.9 + }, + "Mobility": 0.95, + "Delay": 0.8, + "Acceleration": 0.8, + "Radius": 31.9 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting8", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 70, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamWaistAngleZ" + }, + "Weight": 30, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamWatchSwingA1" + }, + "VertexIndex": 1, + "Scale": 1, + "Weight": 100, + "Type": "Angle", + "Reflect": false + }, + { + "Destination": { + "Target": "Parameter", + "Id": "ParamWatchSwingA2" + }, + "VertexIndex": 2, + "Scale": 1, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 15.4 + }, + "Mobility": 0.95, + "Delay": 1, + "Acceleration": 0.8, + "Radius": 15.4 + }, + { + "Position": { + "X": 0, + "Y": 31.9 + }, + "Mobility": 0.9, + "Delay": 1, + "Acceleration": 0.6, + "Radius": 16.5 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting9", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 70, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamWaistAngleZ" + }, + "Weight": 30, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamChainWaist" + }, + "VertexIndex": 1, + "Scale": 1, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 11.6 + }, + "Mobility": 0.95, + "Delay": 1, + "Acceleration": 1, + "Radius": 11.6 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting10", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleX" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamBodyAngleZ" + }, + "Weight": 70, + "Type": "Angle", + "Reflect": false + }, + { + "Source": { + "Target": "Parameter", + "Id": "ParamWaistAngleZ" + }, + "Weight": 30, + "Type": "Angle", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamWatchAX" + }, + "VertexIndex": 1, + "Scale": 2, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 72.1 + }, + "Mobility": 0.95, + "Delay": 1, + "Acceleration": 0.2, + "Radius": 72.1 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + }, + { + "Id": "PhysicsSetting11", + "Input": [ + { + "Source": { + "Target": "Parameter", + "Id": "ParamArmBR03" + }, + "Weight": 100, + "Type": "X", + "Reflect": false + } + ], + "Output": [ + { + "Destination": { + "Target": "Parameter", + "Id": "ParamWatchBChain" + }, + "VertexIndex": 1, + "Scale": 2, + "Weight": 100, + "Type": "Angle", + "Reflect": false + } + ], + "Vertices": [ + { + "Position": { + "X": 0, + "Y": 0 + }, + "Mobility": 1, + "Delay": 1, + "Acceleration": 1, + "Radius": 0 + }, + { + "Position": { + "X": 0, + "Y": 13.1 + }, + "Mobility": 0.95, + "Delay": 1, + "Acceleration": 0.66, + "Radius": 13.1 + } + ], + "Normalization": { + "Position": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + }, + "Angle": { + "Minimum": -10, + "Default": 0, + "Maximum": 10 + } + } + } + ] +} \ No newline at end of file diff --git a/main/feedback-backend/alembic.ini b/main/feedback-backend/alembic.ini new file mode 100644 index 000000000..4601a6019 --- /dev/null +++ b/main/feedback-backend/alembic.ini @@ -0,0 +1,38 @@ +# Alembic 配置文件 + +[alembic] +script_location = migrations +sqlalchemy.url = mysql+pymysql://root:123456@127.0.0.1:3306/feedback_db?charset=utf8mb4 + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/main/feedback-backend/app/__init__.py b/main/feedback-backend/app/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/agent/__init__.py b/main/feedback-backend/app/agent/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/agent/graph.py b/main/feedback-backend/app/agent/graph.py new file mode 100644 index 000000000..8536a7286 --- /dev/null +++ b/main/feedback-backend/app/agent/graph.py @@ -0,0 +1,49 @@ +"""轻量 Agent Graph。 + +不是完整 LangGraph 依赖,而是一个小型有向执行器: +Intent -> Plan -> Execute skills -> Summarize。 +""" + +from dataclasses import dataclass, field +from typing import Any, Callable, Optional + + +@dataclass +class AgentStep: + skill: str + args: dict = field(default_factory=dict) + risk: str = "read" + result: Any = None + error: Optional[str] = None + + +@dataclass +class AgentState: + message: str + store_id: Optional[str] = None + operator: str = "" + intent: str = "unknown" + steps: list[AgentStep] = field(default_factory=list) + final_answer: str = "" + route: Optional[str] = None + data: Any = None + trace: list[dict] = field(default_factory=list) + + +class AgentGraph: + def __init__(self, planner: Callable[[AgentState], AgentState], executor: Callable[[AgentState, AgentStep], Any], summarizer: Callable[[AgentState], AgentState]): + self.planner = planner + self.executor = executor + self.summarizer = summarizer + + async def run(self, state: AgentState) -> AgentState: + state = self.planner(state) + for step in state.steps: + try: + step.result = await self.executor(state, step) + state.trace.append({"skill": step.skill, "risk": step.risk, "ok": True}) + except Exception as exc: # MVP:失败即停止 + step.error = str(exc) + state.trace.append({"skill": step.skill, "risk": step.risk, "ok": False, "error": step.error}) + break + return self.summarizer(state) diff --git a/main/feedback-backend/app/application/__init__.py b/main/feedback-backend/app/application/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/application/agent_chat_service.py b/main/feedback-backend/app/application/agent_chat_service.py new file mode 100644 index 000000000..0482b3ff5 --- /dev/null +++ b/main/feedback-backend/app/application/agent_chat_service.py @@ -0,0 +1,502 @@ +"""后台 AI 助手服务 - 将自然语言路由到 CRM/统计能力。 + +当前是安全 MVP:用规则识别常见意图并调用现有应用服务。 +后续可替换为 LLM + skill/CLI 工具调用。 +""" + +import re +from typing import Optional + +from sqlalchemy.orm import Session + +from app.application.crm_service import CrmService +from app.application.stats_service import StatsService + + +class AgentChatService: + """后台 AI 助手服务""" + + def __init__(self, session: Session): + self.session = session + self.crm = CrmService(session) + self.stats = StatsService(session) + + async def chat(self, message: str, history: Optional[list[dict]] = None, store_id: Optional[str] = None, operator: str = "") -> dict: + from app.agent.graph import AgentGraph, AgentState + + graph = AgentGraph(self._plan, self._execute_step, self._summarize) + contextual_message = self._with_context(message, history or []) + state = await graph.run(AgentState(message=contextual_message, store_id=store_id, operator=operator)) + return {"reply": state.final_answer, "data": state.data, "route": state.route, "intent": state.intent, "trace": state.trace, "action": getattr(state, "action", None)} + + def _plan(self, state): + from app.agent.graph import AgentStep + + original_text = state.message + text = self._current_user_text(original_text) + if not text: + state.intent = "help" + state.steps = [AgentStep("help")] + elif self._has(text, ["帮助", "怎么用", "help", "菜单"]): + state.intent = "help" + state.steps = [AgentStep("help")] + elif self._has(text, ["kpi", "KPI", "员工统计", "员工评价", "好评", "差评排行"]): + state.intent = "employee_kpi" + state.steps = [AgentStep("stats.employee-kpi")] + elif self._has(text, ["概览", "看板", "总览", "crm概况", "CRM概况"]): + state.intent = "crm_overview" + state.steps = [AgentStep("crm.overview")] + elif self._is_appointment_request(text): + state.intent = "appointment_request" + state.steps = [AgentStep("appointment.plan", self._extract_appointment_payload(text), risk="write")] + elif self._has(text, ["创建产品", "新增产品", "新建产品"]): + state.intent = "product_create" + state.steps = [AgentStep("form.open", {"form": "crm.product.create", "payload": self._extract_product_payload(text)}, risk="write")] + elif self._has(text, ["身体变化", "身体状态", "体重", "腰围", "睡眠", "疼痛"]): + tail = self._extract_phone_tail(text) + if tail: + state.intent = "member_body_status" + state.steps = [ + AgentStep("crm.member-list", {"keyword": tail}), + AgentStep("crm.body-status-list", {"from_previous_member": True}), + ] + else: + state.intent = "body_status" + state.steps = [AgentStep("crm.body-status-list")] + elif self._has(text, ["产品", "套餐", "养生", "减肥", "product", "package"]): + tail = self._extract_phone_tail(text) + if tail and self._has(text, ["剩", "还有", "几次", "多少次"]): + state.intent = "member_package_balance" + state.steps = [ + AgentStep("crm.member-list", {"keyword": tail}), + AgentStep("crm.member-product-list", {"from_previous_member": True}), + ] + elif tail and self._has(text, ["消费", "扣", "用一次", "做一次"]): + state.intent = "member_package_consume_plan" + state.steps = [ + AgentStep("crm.member-list", {"keyword": tail}), + AgentStep("crm.member-product-list", {"from_previous_member": True}), + AgentStep("confirm.required", {"action": "product_consume"}, risk="danger"), + ] + else: + state.intent = "products" + state.steps = [AgentStep("crm.product-list", {"keyword": self._extract_keyword(text)})] + elif self._has(text, ["麦凯66", "麦凯", "66字段"]): + state.intent = "mekai66" + state.steps = [AgentStep("crm.mekai66-fields")] + elif self._has(text, ["建议"]): + state.intent = "suggestions" + state.steps = [AgentStep("crm.suggestion-list", {"status": "pending" if self._has(text, ["待处理", "未处理"]) else None})] + elif self._has(text, ["问题", "修复", "投诉"]): + state.intent = "issues" + state.steps = [AgentStep("crm.issue-list", {"status": "identified" if self._has(text, ["待修复", "待处理", "未修复"]) else None})] + elif self._has(text, ["账户流水", "流水"]): + state.intent = "transactions" + state.steps = [AgentStep("crm.transactions", {"member_id": self._extract_id(text, "member")})] + elif self._has(text, ["账户", "卡", "余额", "剩余次数"]): + state.intent = "accounts" + state.steps = [AgentStep("crm.account-list", {"member_id": self._extract_id(text, "member")})] + elif self._has(text, ["创建客户", "新增客户", "新建客户", "创建用户", "新增用户", "新建用户"]): + state.intent = "member_create" + state.steps = [AgentStep("form.open", {"form": "crm.member.create", "payload": self._extract_member_payload(text)}, risk="write")] + else: + tail = self._extract_phone_tail(text) + if tail or self._has(text, ["查客户", "找客户", "客户"]): + state.intent = "member_search" + state.steps = [AgentStep("crm.member-list", {"keyword": tail or self._extract_keyword(text)})] + else: + state.intent = "unknown" + state.steps = [AgentStep("unknown")] + return state + + async def _execute_step(self, state, step): + skill = step.skill + args = step.args + if skill == "help": + return self._help()["reply"] + if skill == "unknown": + return "我暂时没理解。你可以说:查客户尾号1234、员工KPI、CRM概览、产品套餐、待处理建议、待修复问题、账户流水。" + if skill == "appointment.plan": + return args + if skill == "form.open": + return args + if skill == "stats.employee-kpi": + return await self.stats.get_employee_kpi(state.store_id) + if skill == "crm.overview": + return await self.crm.get_overview(state.store_id) + if skill == "crm.body-status-list": + member_id = args.get("member_id") + if args.get("from_previous_member") and state.steps and state.steps[0].result: + members = state.steps[0].result.get("list") if isinstance(state.steps[0].result, dict) else [] + member_id = members[0].get("id") if members else None + return await self.crm.list_body_statuses(page=1, page_size=10, store_id=state.store_id, member_id=member_id) + if skill == "crm.product-create": + if not args.get("productName"): + return {"error": "创建产品需要产品名称,例如:创建产品 冰蚕乌酒"} + return await self.crm.create_product({"store_id": state.store_id, **args}, state.operator) + if skill == "crm.product-list": + return await self.crm.list_products(page=1, page_size=10, store_id=state.store_id, keyword=args.get("keyword")) + if skill == "crm.member-product-list": + member_id = args.get("member_id") + if args.get("from_previous_member") and state.steps and state.steps[0].result: + members = state.steps[0].result.get("list") if isinstance(state.steps[0].result, dict) else [] + member_id = members[0].get("id") if members else None + if not member_id: + return {"list": [], "total": 0, "message": "未找到客户,无法查询已购套餐"} + return await self.crm.list_member_products(page=1, page_size=10, store_id=state.store_id, member_id=member_id, status=1) + if skill == "confirm.required": + return {"needConfirmation": True, "message": "这是会减少客户套餐次数的操作,当前版本先返回待确认计划,暂不自动执行。请在客户套餐页或CLI确认后执行。"} + if skill == "crm.mekai66-fields": + from app.shared.mekai66 import MEKAI66_FIELDS + return MEKAI66_FIELDS + if skill == "crm.suggestion-list": + return await self.crm.list_suggestions(page=1, page_size=10, store_id=state.store_id, status=args.get("status")) + if skill == "crm.issue-list": + return await self.crm.list_issues(page=1, page_size=10, store_id=state.store_id, status=args.get("status")) + if skill == "crm.transactions": + return await self.crm.list_account_transactions(page=1, page_size=10, store_id=state.store_id, member_id=args.get("member_id")) + if skill == "crm.account-list": + return await self.crm.list_accounts(page=1, page_size=10, store_id=state.store_id, member_id=args.get("member_id")) + if skill == "crm.member-create": + if not args.get("phone") and not args.get("name"): + return {"error": "创建客户需要至少提供姓名或手机号,例如:新增客户 张女士 13800001234"} + payload = {"store_id": state.store_id, "source": "agent", **args} + return await self.crm.create_member(payload, state.operator) + if skill == "crm.member-list": + return await self.crm.list_members(page=1, page_size=10, store_id=state.store_id, keyword=args.get("keyword")) + return {"error": f"未注册skill: {skill}"} + + def _summarize(self, state): + if not state.steps: + state.final_answer = "无执行步骤。" + return state + step = state.steps[-1] + data = step.result + state.data = data + if isinstance(data, dict) and data.get("error"): + state.final_answer = data["error"] + return state + if step.skill == "help" or step.skill == "unknown": + state.final_answer = str(data) + elif step.skill == "form.open": + form = data.get("form") + state.action = {"type": "open_form", "form": form, "route": "crm", "payload": data.get("payload") or {}} + state.final_answer = "我已识别到要填写表单,会自动打开并预填已识别的信息。请确认后保存;缺少的字段可以继续告诉我。" + state.route = "crm" + elif step.skill == "appointment.plan": + state.final_answer = "我识别到这是预约需求,已帮你打开预约表单。请先选择客户,系统会自动加载客户套餐;员工和时间我会尽量预填。" + state.action = {"type": "open_form", "form": "crm.appointment.create", "route": "crm", "payload": data} + state.route = "crm" + elif step.skill == "stats.employee-kpi": + state.final_answer = self._format_employee_kpi(data) + state.route = "dashboard" + elif step.skill == "crm.overview": + state.final_answer = self._format_overview(data) + state.route = "crm" + elif step.skill == "crm.body-status-list": + state.final_answer = self._format_body_statuses(data) + state.route = "crm" + elif step.skill == "crm.product-create": + state.final_answer = f"已创建产品:{data.get('productName') or '-'},分类:{data.get('category') or '-'},默认次数:{data.get('defaultCount') or 0}" + state.route = "crm" + elif step.skill == "crm.product-list": + state.final_answer = self._format_products(data) + state.route = "crm" + elif step.skill == "crm.member-product-list": + state.final_answer = self._format_member_products(data) + state.route = "crm" + elif step.skill == "confirm.required": + state.final_answer = data.get("message", "需要确认后执行。") if isinstance(data, dict) else "需要确认后执行。" + state.route = "crm" + elif step.skill == "crm.mekai66-fields": + categories = {} + for field in data: + categories.setdefault(field["category"], 0) + categories[field["category"]] += 1 + state.final_answer = "\n".join(["麦凯66字段已配置,共66项:"] + [f"- {k}: {v}项" for k, v in categories.items()]) + state.route = "crm" + elif step.skill == "crm.suggestion-list": + state.final_answer = self._format_suggestions(data) + state.route = "crm" + elif step.skill == "crm.issue-list": + state.final_answer = self._format_issues(data) + state.route = "crm" + elif step.skill == "crm.transactions": + state.final_answer = self._format_transactions(data) + state.route = "crm" + elif step.skill == "crm.account-list": + state.final_answer = self._format_accounts(data) + state.route = "crm" + elif step.skill == "crm.member-list": + state.final_answer = self._format_members(data) + state.route = "crm" + elif step.skill == "crm.member-create": + state.final_answer = (f"已创建客户:{data.get('name') or '-'},手机号:{data.get('phone') or '-'}。\n" + "还可以继续补充:生日、微信、客户等级、过敏史、皮肤状态、睡眠、体重/腰围、偏好技师、已购产品/套餐、服务力度偏好、下次跟进重点。") + state.route = "crm" + else: + state.final_answer = "已执行。" + return state + + @staticmethod + def _current_user_text(text: str) -> str: + marker = "当前用户说:" + if marker in (text or ""): + return text.rsplit(marker, 1)[-1].strip() + return (text or "").strip() + + @staticmethod + def _with_context(message: str, history: list[dict]) -> str: + """把最近几轮短上下文拼到当前输入,辅助长聊时省略主语的表达。""" + text = (message or "").strip() + if not history: + return text + lines = [] + for item in history[-6:]: + role = "用户" if item.get("role") == "user" else "助手" + content = str(item.get("text") or "").strip() + if content and content != text: + lines.append(f"{role}: {content[:200]}") + if not lines: + return text + return "最近对话上下文:\n" + "\n".join(lines) + "\n当前用户说:" + text + + @staticmethod + def _reply(text: str, data=None, route: Optional[str] = None) -> dict: + return {"reply": text, "data": data, "route": route} + + @staticmethod + def _has(text: str, keywords: list[str]) -> bool: + lower = text.lower() + return any(k.lower() in lower for k in keywords) + + @staticmethod + def _is_appointment_request(text: str) -> bool: + appointment_words = ["预约", "预定", "约一下", "约", "预战", "预占", "排个", "安排"] + time_words = ["今天", "明天", "后天", "上午", "下午", "晚上", "点", "点钟"] + service_words = ["服务", "做身体", "做一下", "过来", "到店", "员工"] + return (any(w in text for w in appointment_words) or (any(w in text for w in time_words) and any(w in text for w in service_words))) + + @staticmethod + def _extract_appointment_payload(text: str) -> dict: + normalized = AgentChatService._normalize_asr_alias(text) + employee = "" + patterns = [ + r"(?:让|找|由|给|约)(?:那个|这个)?([一-龥A-Za-z]{2,8})(?:一号|1号|员工|老师|服务)", + r"([一-龥A-Za-z]{2,8})(?:一号|1号)员工", + r"员工[:: ]*([一-龥A-Za-z]{2,8})", + ] + for pattern in patterns: + emp_match = re.search(pattern, normalized) + if emp_match: + employee = emp_match.group(1) + break + start_hint = "" + time_match = re.search(r"((?:今天|明天|后天)?\s*(?:上午|下午|晚上|中午)?\s*(?:\d{1,2}|[一二两三四五六七八九十]{1,3})点(?:半|\d{1,2}分)?(?:钟)?(?:到(?:\d{1,2}|[一二两三四五六七八九十]{1,3})点(?:半|\d{1,2}分)?(?:钟)?)?)", normalized) + if time_match: + start_hint = time_match.group(1).strip() + phone = re.search(r"1\d{10}|\d{4}", normalized) + service = "" + for kw in ["腰妍", "乌蛇", "冰蚕", "减肥", "养生", "肩颈", "身体"]: + if kw in normalized: + service = kw + break + return {"employeeName": employee, "startHint": start_hint, "memberKeyword": phone.group(0) if phone else "", "serviceKeyword": service, "raw": text, "normalized": normalized} + + @staticmethod + def _normalize_asr_alias(text: str) -> str: + aliases = { + "预战": "预约", "预占": "预约", "场预战": "想预约", "长预战": "想预约", + "李艾元": "李爱媛", "李艾媛": "李爱媛", "李爱元": "李爱媛", + "一号": "1号", + } + for k, v in aliases.items(): + text = text.replace(k, v) + return text + + @staticmethod + def _extract_phone_tail(text: str) -> str: + match = re.search(r"(?:尾号|后四位|手机号)[^0-9]{0,8}(\d{4})", text) + if match: + return match.group(1) + match = re.search(r"(? str: + match = re.search(r"1\d{10}", text) + return match.group(0) if match else "" + + def _extract_member_payload(self, text: str) -> dict: + name = self._extract_name(text) + phone = self._extract_phone(text) + gender = 1 if self._has(text, ["男", "先生"]) else (2 if self._has(text, ["女", "女士"]) else None) + birth_year = self._extract_birth_year(text) + health = [] + for word in ["膝盖积液", "脚踝扭伤", "肩颈酸痛", "腰背酸痛", "睡眠不好", "皮肤干燥"]: + if word in text: + health.append(word) + mekai = {} + if birth_year: + mekai["birthday"] = f"{birth_year}年" + if "已婚" in text: + mekai["marital_status"] = "已婚" + child = re.search(r"(\d+)岁宝宝", text) + if child: + mekai["children"] = f"{child.group(1)}岁宝宝" + job = re.search(r"(?:工作岗位|职业|岗位)[:: ]*([一-龥A-Za-z0-9_+-]{2,20})", text) + if job: + mekai["position"] = job.group(1) + return { + "name": name, + "phone": phone, + "gender": gender, + "healthIssues": health, + "mekaiTags": mekai, + } + + @staticmethod + def _extract_birth_year(text: str) -> str: + match = re.search(r"(19\d{2}|20\d{2}|\d{2})年", text) + if not match: + return "" + year = match.group(1) + if len(year) == 2: + year = "19" + year if int(year) > 30 else "20" + year + return year + + @staticmethod + def _extract_product_payload(text: str) -> dict: + name = "" + match = re.search(r"(?:创建产品|新增产品|新建产品)[,,:: ]*([一-龥A-Za-z0-9_+-]{2,30})", text) + if match: + name = match.group(1).strip() + category = "" + for word in ["减肥", "养生", "美容", "酒", "产品", "套餐"]: + if word in name or word in text: + category = word + break + product_type = "package" if "套餐" in text or "套餐" in name else "product" + price = 0 + price_match = re.search(r"(?:价格|售价|卖|金额)[:: ]*(\d+(?:\.\d+)?)", text) + if not price_match: + price_match = re.search(r"(\d+(?:\.\d+)?)\s*元", text) + if price_match: + price = price_match.group(1) + count = 1 + count_match = re.search(r"(?:默认|次数|共)?\s*(\d+)\s*次", text) + if count_match: + count = count_match.group(1) + category_match = re.search(r"(?:分类|类别)[:: ]*([一-龥A-Za-z0-9_+-]{1,20})", text) + if category_match: + category = category_match.group(1) + return {"productName": name, "productType": product_type, "category": category, "defaultCount": count, "price": price} + + @staticmethod + def _extract_name(text: str) -> str: + patterns = [ + r"(?:姓名|名字|叫)[:: ]*([一-龥A-Za-z]{2,12})", + r"(?:创建客户|新增客户|新建客户|创建用户|新增用户|新建用户)\s*([一-龥A-Za-z]{2,12})", + ] + for pattern in patterns: + match = re.search(pattern, text) + if match: + return match.group(1) + return "" + + @staticmethod + def _extract_keyword(text: str) -> str: + for word in ["查客户", "找客户", "客户", "尾号", "后四位"]: + text = text.replace(word, " ") + return text.strip().split()[0] if text.strip().split() else "" + + @staticmethod + def _extract_id(text: str, prefix: str) -> Optional[str]: + match = re.search(rf"({prefix}[A-Za-z0-9_-]+|[a-f0-9]{{32}})", text) + return match.group(1) if match else None + + def _help(self) -> dict: + return self._reply("\n".join([ + "我可以帮你管理后台:", + "1. 查客户尾号1234 / 查客户张女士", + "2. 新增客户 张女士 13800001234", + "3. 员工KPI / 差评排行", + "4. CRM概览 / 账户流水 / 账户余额", + "5. 待处理建议 / 待修复问题", + "6. 麦凯66字段", + "高风险操作(销卡、删除、批量修改)建议仍通过页面或CLI确认执行。", + ])) + + @staticmethod + def _format_overview(data: dict) -> str: + return (f"CRM概览:客户{data.get('members', 0)}人,到店{data.get('visits', 0)}次," + f"有效账户{data.get('activeAccounts', 0)}个,账户余额¥{data.get('accountBalance', 0)}," + f"待处理建议{data.get('pendingSuggestions', 0)}条,待修复问题{data.get('openIssues', 0)}条。") + + @staticmethod + def _format_employee_kpi(data: list[dict]) -> str: + if not data: + return "暂无员工KPI数据。" + lines = ["员工KPI:"] + for item in data[:8]: + lines.append(f"- {item.get('employeeName')}: 总{item.get('total')},好评{item.get('good')},中评{item.get('middle')},差评{item.get('bad')},好评率{item.get('goodRate')}%") + return "\n".join(lines) + + @staticmethod + def _format_members(data: dict) -> str: + rows = data.get("list") or [] + if not rows: + return "没有找到客户。" + lines = [f"找到{data.get('total', len(rows))}个客户:"] + for m in rows: + lines.append(f"- {m.get('name') or '-'} {m.get('phone') or '-'},到店{m.get('totalVisits', 0)}次,消费¥{m.get('totalSpent', 0)},ID={m.get('id')}") + return "\n".join(lines) + + @staticmethod + def _format_accounts(data: dict) -> str: + rows = data.get("list") or [] + if not rows: + return "暂无账户/卡。" + return "\n".join(["账户/卡:"] + [f"- {a.get('memberName') or '-'} {a.get('cardName') or a.get('accountType')}:余额¥{a.get('balanceAmount')},剩余{a.get('balanceCount')}次,ID={a.get('id')}" for a in rows]) + + @staticmethod + def _format_transactions(data: dict) -> str: + rows = data.get("list") or [] + if not rows: + return "暂无账户流水。" + return "\n".join(["最近账户流水:"] + [f"- {t.get('createDate')} {t.get('memberName') or '-'} {t.get('transactionType')} 金额{t.get('amount')} 次数{t.get('countChange')} 备注:{t.get('notes') or '-'}" for t in rows]) + + @staticmethod + def _format_body_statuses(data: dict) -> str: + rows = data.get("list") or [] + if not rows: + return "暂无身体变化记录。" + return "\n".join(["身体变化记录:"] + [f"- {b.get('recordDate')} {b.get('memberName') or '-'}:体重{b.get('weight') or '-'}kg,腰围{b.get('waistline') or '-'}cm,不适{b.get('painLevel') or '-'}/10,睡眠{b.get('sleepQuality') or '-'}/10,{b.get('notes') or ''}" for b in rows]) + + @staticmethod + def _format_products(data: dict) -> str: + rows = data.get("list") or [] + if not rows: + return "暂无产品/套餐。" + return "\n".join(["产品/套餐:"] + [f"- {p.get('productName')}({p.get('category') or '-'},¥{p.get('price')},默认{p.get('defaultCount')}次,ID={p.get('id')})" for p in rows]) + + @staticmethod + def _format_member_products(data: dict) -> str: + rows = data.get("list") or [] + if not rows: + return data.get("message") or "该客户暂无已购产品/套餐。" + return "\n".join(["客户已购产品/套餐:"] + [f"- {p.get('productName')}:剩余{p.get('balanceCount')}/{p.get('totalCount')}次,余额¥{p.get('balanceAmount')}/¥{p.get('totalAmount')},ID={p.get('id')}" for p in rows]) + + @staticmethod + def _format_suggestions(data: dict) -> str: + rows = data.get("list") or [] + if not rows: + return "暂无建议。" + return "\n".join(["建议:"] + [f"- {s.get('content')}({s.get('status')},出现{s.get('frequency')}次,ID={s.get('id')})" for s in rows]) + + @staticmethod + def _format_issues(data: dict) -> str: + rows = data.get("list") or [] + if not rows: + return "暂无问题。" + return "\n".join(["问题修复:"] + [f"- {i.get('title')}({i.get('status')},{i.get('severity')},负责人:{i.get('assignedTo') or '-'},ID={i.get('id')})" for i in rows]) diff --git a/main/feedback-backend/app/application/agent_config_service.py b/main/feedback-backend/app/application/agent_config_service.py new file mode 100644 index 000000000..8c7c6185b --- /dev/null +++ b/main/feedback-backend/app/application/agent_config_service.py @@ -0,0 +1,71 @@ +"""智能体配置应用服务""" + +from typing import Any, Dict, Optional + +from loguru import logger +from sqlalchemy.orm import Session + +from app.domain.agent.entity import AgentConfig +from app.infrastructure.persistence.agent_repo_impl import AgentConfigRepositoryImpl +from app.shared.exceptions import AgentConfigNotFoundError, ValidationError +from app.shared.utils import generate_id + + +class AgentConfigService: + """智能体配置应用服务""" + + def __init__(self, session: Session): + self.repo = AgentConfigRepositoryImpl(session) + self.session = session + + async def get_by_id(self, config_id: str) -> AgentConfig: + config = await self.repo.get_by_id(config_id) + if not config: + raise AgentConfigNotFoundError(config_id) + return config + + async def get_by_agent_id(self, agent_id: str) -> Optional[AgentConfig]: + return await self.repo.get_by_agent_id(agent_id) + + async def list_page(self, page: int = 1, page_size: int = 20) -> dict: + return await self.repo.list_page(page, page_size) + + async def create_config(self, agent_name: str, agent_id: Optional[str] = None, + dialogue_rounds: int = 7, questions: Optional[list] = None, + prompts_config: Optional[dict] = None, + llm_config: Optional[dict] = None, + review_config: Optional[dict] = None) -> AgentConfig: + config = AgentConfig( + id=generate_id(), + agent_name=agent_name, + agent_id=agent_id, + dialogue_rounds=dialogue_rounds, + questions=questions, + prompts_config=prompts_config, + llm_config=llm_config, + review_config=review_config, + ) + result = await self.repo.save(config) + logger.info(f"创建智能体配置: name={agent_name}") + return result + + async def update_config(self, config_id: str, **kwargs) -> AgentConfig: + config = await self.repo.get_by_id(config_id) + if not config: + raise AgentConfigNotFoundError(config_id) + + for key, value in kwargs.items(): + if hasattr(config, key) and value is not None: + setattr(config, key, value) + + result = await self.repo.save(config) + logger.info(f"更新智能体配置: id={config_id}") + return result + + async def delete_config(self, config_id: str) -> bool: + config = await self.repo.get_by_id(config_id) + if not config: + raise AgentConfigNotFoundError(config_id) + result = await self.repo.delete(config_id) + logger.info(f"删除智能体配置: id={config_id}") + return result diff --git a/main/feedback-backend/app/application/appointment_service.py b/main/feedback-backend/app/application/appointment_service.py new file mode 100644 index 000000000..cff41aae0 --- /dev/null +++ b/main/feedback-backend/app/application/appointment_service.py @@ -0,0 +1,211 @@ +"""预约日历服务""" + +from datetime import date, datetime, time, timedelta +from typing import Optional + +from sqlalchemy.orm import Session + +from app.infrastructure.persistence.models import ( + CrmAppointmentLogModel, + CrmAppointmentModel, + CrmEmployeeScheduleModel, + CrmEmployeeTimeoffModel, + CrmMemberModel, + CrmMemberProductModel, + CrmProductModel, + EmployeeModel, +) +from app.shared.utils import generate_id + +ACTIVE_STATUS = ["pending", "confirmed", "arrived"] + + +class AppointmentService: + def __init__(self, session: Session): + self.session = session + + async def calendar(self, store_id: str, start_date: str, end_date: str, + employee_id: Optional[str] = None) -> dict: + start = self._parse_date(start_date) + end = self._parse_date(end_date) + emp_query = self.session.query(EmployeeModel).filter(EmployeeModel.store_id == store_id, EmployeeModel.status == 1) + if employee_id: + emp_query = emp_query.filter(EmployeeModel.id == employee_id) + employees = emp_query.order_by(EmployeeModel.number).all() + query = self.session.query(CrmAppointmentModel).filter( + CrmAppointmentModel.store_id == store_id, + CrmAppointmentModel.appointment_date >= start, + CrmAppointmentModel.appointment_date <= end, + ) + if employee_id: + query = query.filter(CrmAppointmentModel.employee_id == employee_id) + appointments = query.order_by(CrmAppointmentModel.start_at).all() + return { + "resources": [{"id": e.id, "title": e.name, "number": e.number, "type": e.employee_type} for e in employees], + "events": [self._appointment_to_event(a) for a in appointments], + } + + async def availability(self, store_id: str, appointment_date: str, + employee_id: Optional[str] = None, + duration_minutes: int = 60) -> dict: + day = self._parse_date(appointment_date) + weekday = day.isoweekday() + employees_query = self.session.query(EmployeeModel).filter(EmployeeModel.store_id == store_id, EmployeeModel.status == 1) + if employee_id: + employees_query = employees_query.filter(EmployeeModel.id == employee_id) + employees = employees_query.order_by(EmployeeModel.number).all() + slots = [] + for emp in employees: + schedules = self.session.query(CrmEmployeeScheduleModel).filter( + CrmEmployeeScheduleModel.employee_id == emp.id, + CrmEmployeeScheduleModel.weekday == weekday, + CrmEmployeeScheduleModel.status == 1, + CrmEmployeeScheduleModel.is_working == 1, + ).all() + if not schedules: + schedules = [self._default_schedule(emp, weekday)] + for schedule in schedules: + slots.extend(self._slots_for_schedule(store_id, emp, day, schedule, duration_minutes)) + return {"date": str(day), "slots": slots} + + async def create_appointment(self, data: dict, operator: str = "") -> dict: + start_at = self._parse_datetime(data.get("start_at") or data.get("startAt")) + duration = int(data.get("duration_minutes") or data.get("durationMinutes") or 60) + end_at = self._parse_datetime(data.get("end_at") or data.get("endAt")) or (start_at + timedelta(minutes=duration)) + store_id = data.get("store_id") or data.get("storeId") + employee_id = data.get("employee_id") or data.get("employeeId") + if start_at <= datetime.now(): + raise ValueError("不能预约已经过去的时间") + if self._has_conflict(employee_id, start_at, end_at): + raise ValueError("该员工该时间段已有预约") + member_product = self._member_product(data.get("member_product_id") or data.get("memberProductId")) + product = self._product(data.get("product_id") or data.get("productId") or (member_product.product_id if member_product else None)) + appointment = CrmAppointmentModel( + id=generate_id(), store_id=store_id, + member_id=data.get("member_id") or data.get("memberId"), + employee_id=employee_id, + member_product_id=data.get("member_product_id") or data.get("memberProductId"), + product_id=data.get("product_id") or data.get("productId") or (member_product.product_id if member_product else None), + product_name=data.get("product_name") or data.get("productName") or (member_product.product_name if member_product else (product.product_name if product else None)), + appointment_date=start_at.date(), start_at=start_at, end_at=end_at, + duration_minutes=duration, + source=data.get("source") or "admin", + status=data.get("status") or "pending", + customer_notes=data.get("customer_notes") or data.get("customerNotes"), + store_notes=data.get("store_notes") or data.get("storeNotes"), + created_by=operator, + ) + self.session.add(appointment) + self._log(appointment.id, "create", None, self._appointment_to_dict(appointment), operator) + self.session.commit() + self.session.refresh(appointment) + return self._appointment_to_dict(appointment) + + async def update_status(self, appointment_id: str, status: str, data: dict, operator: str = "") -> Optional[dict]: + appointment = self.session.query(CrmAppointmentModel).filter(CrmAppointmentModel.id == appointment_id).first() + if not appointment: + return None + before = self._appointment_to_dict(appointment) + appointment.status = status + if status == "confirmed": + appointment.confirmed_by = operator + if status == "cancelled": + appointment.cancelled_by = operator + appointment.cancel_reason = data.get("reason") or data.get("cancelReason") + appointment.update_date = datetime.now() + self._log(appointment.id, status, before, self._appointment_to_dict(appointment), operator, data.get("notes")) + if status == "completed" and data.get("consume"): + from app.application.crm_service import CrmService + if appointment.member_product_id: + CrmService(self.session).consume_member_product_sync(appointment.member_product_id, { + "consumeCount": data.get("consumeCount") or 1, + "consumeAmount": data.get("consumeAmount") or 0, + "visitId": data.get("visitId"), + "notes": f"预约完成自动消耗:{appointment.product_name or ''}", + }, appointment.store_id, operator) + self.session.commit() + self.session.refresh(appointment) + return self._appointment_to_dict(appointment) + + def _slots_for_schedule(self, store_id, emp, day, schedule, duration_minutes): + start_t = self._parse_time(schedule.start_time) + end_t = self._parse_time(schedule.end_time) + cursor = datetime.combine(day, start_t) + end_day = datetime.combine(day, end_t) + slots = [] + while cursor + timedelta(minutes=duration_minutes) <= end_day: + slot_end = cursor + timedelta(minutes=duration_minutes) + available = cursor > datetime.now() and not self._has_conflict(emp.id, cursor, slot_end) and not self._has_timeoff(emp.id, cursor, slot_end) + slots.append({"employeeId": emp.id, "employeeName": emp.name, "start": cursor.strftime("%H:%M"), "end": slot_end.strftime("%H:%M"), "available": available}) + cursor += timedelta(minutes=30) + return slots + + def _has_conflict(self, employee_id: str, start_at: datetime, end_at: datetime) -> bool: + return self.session.query(CrmAppointmentModel).filter( + CrmAppointmentModel.employee_id == employee_id, + CrmAppointmentModel.status.in_(ACTIVE_STATUS), + CrmAppointmentModel.start_at < end_at, + CrmAppointmentModel.end_at > start_at, + ).first() is not None + + def _has_timeoff(self, employee_id: str, start_at: datetime, end_at: datetime) -> bool: + return self.session.query(CrmEmployeeTimeoffModel).filter( + CrmEmployeeTimeoffModel.employee_id == employee_id, + CrmEmployeeTimeoffModel.status == 1, + CrmEmployeeTimeoffModel.start_at < end_at, + CrmEmployeeTimeoffModel.end_at > start_at, + ).first() is not None + + def _default_schedule(self, emp, weekday): + return CrmEmployeeScheduleModel(id="default", store_id=emp.store_id, employee_id=emp.id, weekday=weekday, start_time="10:00", end_time="20:00", is_working=1) + + def _member_product(self, member_product_id): + if not member_product_id: + return None + return self.session.query(CrmMemberProductModel).filter(CrmMemberProductModel.id == member_product_id).first() + + def _product(self, product_id): + if not product_id: + return None + return self.session.query(CrmProductModel).filter(CrmProductModel.id == product_id).first() + + def _log(self, appointment_id, action, before, after, operator, notes=None): + self.session.add(CrmAppointmentLogModel(id=generate_id(), appointment_id=appointment_id, action=action, before_json=before, after_json=after, operator=operator, notes=notes)) + + def _appointment_to_event(self, a): + member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == a.member_id).first() + return { + "id": a.id, "resourceId": a.employee_id, + "title": f"{member.name if member else '客户'} - {a.product_name or '预约'}", + "start": a.start_at.isoformat(sep=" "), "end": a.end_at.isoformat(sep=" "), + "status": a.status, "memberId": a.member_id, "memberName": member.name if member else None, + "employeeId": a.employee_id, "productName": a.product_name, + } + + def _appointment_to_dict(self, a): + return { + "id": a.id, "storeId": a.store_id, "memberId": a.member_id, "employeeId": a.employee_id, + "memberProductId": a.member_product_id, "productId": a.product_id, "productName": a.product_name, + "appointmentDate": str(a.appointment_date), "startAt": str(a.start_at), "endAt": str(a.end_at), + "durationMinutes": a.duration_minutes, "source": a.source, "status": a.status, + "customerNotes": a.customer_notes, "storeNotes": a.store_notes, "cancelReason": a.cancel_reason, + } + + @staticmethod + def _parse_date(value): + if isinstance(value, date): + return value + return datetime.fromisoformat(str(value)[:10]).date() + + @staticmethod + def _parse_time(value): + h, m = str(value).split(":")[:2] + return time(int(h), int(m)) + + @staticmethod + def _parse_datetime(value): + if not value: + return None + if isinstance(value, datetime): + return value + return datetime.fromisoformat(str(value).replace("Z", "+00:00")) diff --git a/main/feedback-backend/app/application/crm_service.py b/main/feedback-backend/app/application/crm_service.py new file mode 100644 index 000000000..8f36daffa --- /dev/null +++ b/main/feedback-backend/app/application/crm_service.py @@ -0,0 +1,978 @@ +"""CRM 应用服务 - 客户档案、到店、账户、销卡、建议、问题闭环""" + +import hashlib +import json +import re +from datetime import datetime, timedelta +from decimal import Decimal +from typing import Any, Optional + +from sqlalchemy import func +from sqlalchemy.orm import Session + +from app.infrastructure.persistence.models import ( + CrmAccountModel, + CrmAccountTransactionModel, + CrmBodyStatusModel, + CrmCardCloseModel, + CrmIssueModel, + CrmMemberModel, + CrmMemberProductModel, + CrmProductConsumeModel, + CrmProductModel, + CrmSuggestionModel, + CrmVisitModel, + FeedbackRecordModel, +) +from app.shared.utils import generate_id + + +class CrmService: + """CRM 应用服务""" + + def __init__(self, session: Session): + self.session = session + + # ---- Member ---- + async def list_members(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, keyword: Optional[str] = None, + status: Optional[int] = None) -> dict: + query = self.session.query(CrmMemberModel) + if store_id: + query = query.filter(CrmMemberModel.store_id == store_id) + if keyword: + like = f"%{keyword}%" + query = query.filter((CrmMemberModel.name.like(like)) | (CrmMemberModel.phone.like(like))) + if status is not None: + query = query.filter(CrmMemberModel.status == status) + total = query.count() + rows = query.order_by(CrmMemberModel.update_date.desc()) \ + .offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._member_to_dict(m) for m in rows], "total": total, "page": page, "page_size": page_size} + + async def get_member(self, member_id: str, store_id: Optional[str] = None) -> Optional[dict]: + query = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id) + if store_id: + query = query.filter(CrmMemberModel.store_id == store_id) + member = query.first() + if not member: + return None + data = self._member_to_dict(member) + data["visits"] = [self._visit_to_dict(v) for v in self.session.query(CrmVisitModel) + .filter(CrmVisitModel.member_id == member.id) + .order_by(CrmVisitModel.arrive_at.desc(), CrmVisitModel.create_date.desc()).limit(10).all()] + data["accounts"] = [self._account_to_dict(a) for a in self.session.query(CrmAccountModel) + .filter(CrmAccountModel.member_id == member.id).order_by(CrmAccountModel.create_date.desc()).all()] + data["transactions"] = [self._transaction_to_dict(t) for t in self.session.query(CrmAccountTransactionModel) + .filter(CrmAccountTransactionModel.member_id == member.id) + .order_by(CrmAccountTransactionModel.create_date.desc()).limit(20).all()] + data["products"] = [self._member_product_to_dict(p) for p in self.session.query(CrmMemberProductModel) + .filter(CrmMemberProductModel.member_id == member.id) + .order_by(CrmMemberProductModel.create_date.desc()).all()] + data["productConsumes"] = [self._product_consume_to_dict(c) for c in self.session.query(CrmProductConsumeModel) + .filter(CrmProductConsumeModel.member_id == member.id) + .order_by(CrmProductConsumeModel.create_date.desc()).limit(20).all()] + data["bodyStatuses"] = [self._body_status_to_dict(b) for b in self.session.query(CrmBodyStatusModel) + .filter(CrmBodyStatusModel.member_id == member.id) + .order_by(CrmBodyStatusModel.record_date.desc()).limit(20).all()] + data["feedbacks"] = [self._feedback_to_dict(r) for r in self.session.query(FeedbackRecordModel) + .filter(FeedbackRecordModel.member_id == member.id) + .order_by(FeedbackRecordModel.create_date.desc()).limit(10).all()] + data["suggestions"] = [self._suggestion_to_dict(s) for s in self.session.query(CrmSuggestionModel) + .filter(CrmSuggestionModel.member_id == member.id) + .order_by(CrmSuggestionModel.create_date.desc()).limit(10).all()] + data["issues"] = [self._issue_to_dict(i) for i in self.session.query(CrmIssueModel) + .filter(CrmIssueModel.member_id == member.id) + .order_by(CrmIssueModel.create_date.desc()).limit(10).all()] + return data + + async def create_member(self, data: dict, operator: str = "") -> dict: + member = CrmMemberModel( + id=generate_id(), + store_id=data.get("store_id"), + name=data.get("name"), + phone=data.get("phone"), + gender=data.get("gender"), + birthday=self._parse_date(data.get("birthday")), + wechat=data.get("wechat"), + source=data.get("source") or "manual", + level=data.get("level"), + tags=data.get("tags"), + mekai_tags=data.get("mekai_tags") or data.get("mekaiTags"), + beauty_concerns=data.get("beauty_concerns") or data.get("beautyConcerns"), + health_issues=data.get("health_issues") or data.get("healthIssues"), + allergies=data.get("allergies"), + service_preferences=data.get("service_preferences") or data.get("servicePreferences"), + notes=data.get("notes"), + creator=operator, + updater=operator, + ) + self.session.add(member) + self.session.commit() + self.session.refresh(member) + return self._member_to_dict(member) + + async def update_member(self, member_id: str, data: dict, store_id: Optional[str] = None, + operator: str = "") -> Optional[dict]: + query = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id) + if store_id: + query = query.filter(CrmMemberModel.store_id == store_id) + member = query.first() + if not member: + return None + mapping = { + "name": "name", "phone": "phone", "gender": "gender", "wechat": "wechat", + "level": "level", "tags": "tags", "allergies": "allergies", "notes": "notes", "status": "status", + } + for key, field in mapping.items(): + if key in data: + setattr(member, field, data[key]) + if "birthday" in data: + member.birthday = self._parse_date(data.get("birthday")) + for key, field in [("mekai_tags", "mekai_tags"), ("mekaiTags", "mekai_tags"), + ("beauty_concerns", "beauty_concerns"), ("beautyConcerns", "beauty_concerns"), + ("health_issues", "health_issues"), ("healthIssues", "health_issues"), + ("service_preferences", "service_preferences"), ("servicePreferences", "service_preferences")]: + if key in data: + setattr(member, field, data[key]) + member.updater = operator + member.update_date = datetime.now() + self.session.commit() + self.session.refresh(member) + return self._member_to_dict(member) + + # ---- Visit ---- + async def list_visits(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, member_id: Optional[str] = None) -> dict: + query = self.session.query(CrmVisitModel) + if store_id: + query = query.filter(CrmVisitModel.store_id == store_id) + if member_id: + query = query.filter(CrmVisitModel.member_id == member_id) + total = query.count() + rows = query.order_by(CrmVisitModel.arrive_at.desc(), CrmVisitModel.create_date.desc()) \ + .offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._visit_to_dict(v) for v in rows], "total": total, "page": page, "page_size": page_size} + + async def create_visit(self, data: dict, operator: str = "") -> dict: + arrive_at = self._parse_datetime(data.get("arrive_at") or data.get("arriveAt")) + leave_at = self._parse_datetime(data.get("leave_at") or data.get("leaveAt")) + duration = data.get("duration_minutes") or data.get("durationMinutes") + if not duration and arrive_at and leave_at: + duration = max(0, int((leave_at - arrive_at).total_seconds() // 60)) + visit = CrmVisitModel( + id=generate_id(), + store_id=data.get("store_id"), + member_id=data.get("member_id") or data.get("memberId"), + employee_id=data.get("employee_id") or data.get("employeeId"), + feedback_record_id=data.get("feedback_record_id") or data.get("feedbackRecordId"), + session_id=data.get("session_id") or data.get("sessionId"), + device_mac=data.get("device_mac") or data.get("deviceMac"), + visit_type=data.get("visit_type") or data.get("visitType") or "walk_in", + service_items=data.get("service_items") or data.get("serviceItems"), + arrive_at=arrive_at, + leave_at=leave_at, + duration_minutes=duration, + satisfaction=data.get("satisfaction"), + consumption_amount=self._decimal(data.get("consumption_amount") or data.get("consumptionAmount")), + notes=data.get("notes"), + creator=operator, + updater=operator, + ) + self.session.add(visit) + self._touch_member_visit_stats(visit.member_id, visit.arrive_at, visit.consumption_amount) + self.session.commit() + self.session.refresh(visit) + return self._visit_to_dict(visit) + + async def update_visit(self, visit_id: str, data: dict, store_id: Optional[str] = None, + operator: str = "") -> Optional[dict]: + query = self.session.query(CrmVisitModel).filter(CrmVisitModel.id == visit_id) + if store_id: + query = query.filter(CrmVisitModel.store_id == store_id) + visit = query.first() + if not visit: + return None + for key, field in [("member_id", "member_id"), ("memberId", "member_id"), + ("employee_id", "employee_id"), ("employeeId", "employee_id"), + ("feedback_record_id", "feedback_record_id"), ("feedbackRecordId", "feedback_record_id"), + ("satisfaction", "satisfaction"), ("notes", "notes"), + ("service_items", "service_items"), ("serviceItems", "service_items")]: + if key in data: + setattr(visit, field, data[key]) + if "arrive_at" in data or "arriveAt" in data: + visit.arrive_at = self._parse_datetime(data.get("arrive_at") or data.get("arriveAt")) + if "leave_at" in data or "leaveAt" in data: + visit.leave_at = self._parse_datetime(data.get("leave_at") or data.get("leaveAt")) + if "duration_minutes" in data or "durationMinutes" in data: + visit.duration_minutes = data.get("duration_minutes") or data.get("durationMinutes") + elif visit.arrive_at and visit.leave_at: + visit.duration_minutes = max(0, int((visit.leave_at - visit.arrive_at).total_seconds() // 60)) + if "consumption_amount" in data or "consumptionAmount" in data: + visit.consumption_amount = self._decimal(data.get("consumption_amount") or data.get("consumptionAmount")) + visit.updater = operator + visit.update_date = datetime.now() + self.session.commit() + self.session.refresh(visit) + return self._visit_to_dict(visit) + + # ---- Account ---- + async def list_accounts(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, member_id: Optional[str] = None, + status: Optional[int] = None) -> dict: + query = self.session.query(CrmAccountModel) + if store_id: + query = query.filter(CrmAccountModel.store_id == store_id) + if member_id: + query = query.filter(CrmAccountModel.member_id == member_id) + if status is not None: + query = query.filter(CrmAccountModel.status == status) + total = query.count() + rows = query.order_by(CrmAccountModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._account_to_dict(a) for a in rows], "total": total, "page": page, "page_size": page_size} + + async def create_account(self, data: dict, operator: str = "") -> dict: + total_amount = self._decimal(data.get("total_amount") or data.get("totalAmount")) + balance_amount = self._decimal(data.get("balance_amount") or data.get("balanceAmount") or total_amount) + account = CrmAccountModel( + id=generate_id(), + store_id=data.get("store_id"), + member_id=data.get("member_id") or data.get("memberId"), + account_type=data.get("account_type") or data.get("accountType") or "balance", + card_name=data.get("card_name") or data.get("cardName"), + total_amount=total_amount, + balance_amount=balance_amount, + total_count=data.get("total_count") or data.get("totalCount") or 0, + balance_count=data.get("balance_count") or data.get("balanceCount") or data.get("total_count") or data.get("totalCount") or 0, + valid_start=self._parse_date(data.get("valid_start") or data.get("validStart")), + valid_end=self._parse_date(data.get("valid_end") or data.get("validEnd")), + notes=data.get("notes"), + creator=operator, + updater=operator, + ) + self.session.add(account) + self.session.flush() + self._add_transaction(account, "recharge", balance_amount, account.balance_count, 0, balance_amount, None, "开卡", operator) + self.session.commit() + self.session.refresh(account) + return self._account_to_dict(account) + + async def list_account_transactions(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, + account_id: Optional[str] = None, + member_id: Optional[str] = None) -> dict: + query = self.session.query(CrmAccountTransactionModel) + if store_id: + query = query.filter(CrmAccountTransactionModel.store_id == store_id) + if account_id: + query = query.filter(CrmAccountTransactionModel.account_id == account_id) + if member_id: + query = query.filter(CrmAccountTransactionModel.member_id == member_id) + total = query.count() + rows = query.order_by(CrmAccountTransactionModel.create_date.desc()) \ + .offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._transaction_to_dict(t) for t in rows], "total": total, "page": page, "page_size": page_size} + + async def consume_account(self, account_id: str, data: dict, store_id: Optional[str] = None, + operator: str = "") -> Optional[dict]: + account = self._get_account(account_id, store_id) + if not account: + return None + amount = self._decimal(data.get("amount")) + count_change = int(data.get("count_change") or data.get("countChange") or 0) + before = self._decimal(account.balance_amount) + account.balance_amount = before - amount + account.balance_count = int(account.balance_count or 0) - count_change + account.update_date = datetime.now() + visit_id = data.get("visit_id") or data.get("visitId") or self._latest_visit_id(account.member_id, account.store_id) + if visit_id: + self._sync_visit_consumption(visit_id, amount) + self._add_transaction(account, "consume", -amount, -count_change, before, account.balance_amount, + visit_id, data.get("notes"), operator) + self.session.commit() + self.session.refresh(account) + return self._account_to_dict(account) + + async def close_card(self, data: dict, store_id: Optional[str] = None, operator: str = "") -> Optional[dict]: + account = self._get_account(data.get("account_id") or data.get("accountId"), store_id) + if not account: + return None + close = CrmCardCloseModel( + id=generate_id(), + store_id=account.store_id, + member_id=account.member_id, + account_id=account.id, + feedback_record_id=data.get("feedback_record_id") or data.get("feedbackRecordId"), + close_type=data.get("close_type") or data.get("closeType") or "refund", + reason=data.get("reason"), + refund_amount=self._decimal(data.get("refund_amount") or data.get("refundAmount")), + remaining_count=account.balance_count or 0, + status=data.get("status") or "done", + handled_by=operator, + handle_notes=data.get("handle_notes") or data.get("handleNotes"), + ) + account.status = 0 + account.closed_reason = close.reason + account.closed_at = datetime.now() + self.session.add(close) + self._add_transaction(account, "close", -self._decimal(close.refund_amount), 0, + self._decimal(account.balance_amount), self._decimal(account.balance_amount), + None, close.reason, operator) + if close.feedback_record_id: + self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.id == close.feedback_record_id).update({ + "member_id": account.member_id, + "card_close_id": close.id, + }) + self.session.commit() + self.session.refresh(close) + return self._card_close_to_dict(close) + + async def list_card_closes(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, member_id: Optional[str] = None) -> dict: + query = self.session.query(CrmCardCloseModel) + if store_id: + query = query.filter(CrmCardCloseModel.store_id == store_id) + if member_id: + query = query.filter(CrmCardCloseModel.member_id == member_id) + total = query.count() + rows = query.order_by(CrmCardCloseModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._card_close_to_dict(c) for c in rows], "total": total, "page": page, "page_size": page_size} + + # ---- Body Status ---- + async def list_body_statuses(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, member_id: Optional[str] = None) -> dict: + query = self.session.query(CrmBodyStatusModel) + if store_id: + query = query.filter(CrmBodyStatusModel.store_id == store_id) + if member_id: + query = query.filter(CrmBodyStatusModel.member_id == member_id) + total = query.count() + rows = query.order_by(CrmBodyStatusModel.record_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._body_status_to_dict(b) for b in rows], "total": total, "page": page, "page_size": page_size} + + async def create_body_status(self, data: dict, operator: str = "") -> dict: + body_status = CrmBodyStatusModel( + id=generate_id(), store_id=data.get("store_id"), + member_id=data.get("member_id") or data.get("memberId"), + visit_id=data.get("visit_id") or data.get("visitId"), + member_product_id=data.get("member_product_id") or data.get("memberProductId"), + record_date=self._parse_datetime(data.get("record_date") or data.get("recordDate")) or datetime.now(), + weight=self._decimal(data.get("weight")) if data.get("weight") not in (None, "") else None, + waistline=self._decimal(data.get("waistline")) if data.get("waistline") not in (None, "") else None, + pain_level=data.get("pain_level") or data.get("painLevel"), + sleep_quality=data.get("sleep_quality") or data.get("sleepQuality"), + skin_status=data.get("skin_status") or data.get("skinStatus"), + body_parts=data.get("body_parts") or data.get("bodyParts"), + metrics=data.get("metrics"), notes=data.get("notes"), + creator=operator, updater=operator, + ) + self.session.add(body_status) + self._merge_body_status_to_member(body_status) + self.session.commit() + self.session.refresh(body_status) + return self._body_status_to_dict(body_status) + + def _merge_body_status_to_member(self, body_status): + member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == body_status.member_id).first() + if not member: + return + issues = member.health_issues if isinstance(member.health_issues, list) else [] + if isinstance(issues, str): + try: + issues = json.loads(issues) + except Exception: + issues = [issues] + summary = [] + metrics = body_status.metrics if isinstance(body_status.metrics, dict) else {} + if metrics.get("name"): + summary.append(f"{metrics.get('name')}:{metrics.get('status') or ''}{'(' + str(metrics.get('value')) + ')' if metrics.get('value') else ''}") + if body_status.notes: + summary.append(body_status.notes) + if summary: + text = ";".join(summary) + if text not in issues: + issues.append(text) + member.health_issues = issues + member.update_date = datetime.now() + + # ---- Product / Package ---- + async def list_products(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, keyword: Optional[str] = None, + category: Optional[str] = None, status: Optional[int] = None) -> dict: + query = self.session.query(CrmProductModel) + if store_id: + query = query.filter(CrmProductModel.store_id == store_id) + if keyword: + query = query.filter(CrmProductModel.product_name.like(f"%{keyword}%")) + if category: + query = query.filter(CrmProductModel.category == category) + if status is not None: + query = query.filter(CrmProductModel.status == status) + total = query.count() + rows = query.order_by(CrmProductModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._product_to_dict(p) for p in rows], "total": total, "page": page, "page_size": page_size} + + async def create_product(self, data: dict, operator: str = "") -> dict: + product = CrmProductModel( + id=generate_id(), store_id=data.get("store_id"), + product_name=data.get("product_name") or data.get("productName"), + product_type=data.get("product_type") or data.get("productType") or "service", + category=data.get("category"), price=self._decimal(data.get("price")), + default_count=int(data.get("default_count") or data.get("defaultCount") or 1), + description=data.get("description"), creator=operator, updater=operator, + ) + self.session.add(product) + self.session.commit() + self.session.refresh(product) + return self._product_to_dict(product) + + async def list_member_products(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, member_id: Optional[str] = None, + status: Optional[int] = None) -> dict: + query = self.session.query(CrmMemberProductModel) + if store_id: + query = query.filter(CrmMemberProductModel.store_id == store_id) + if member_id: + query = query.filter(CrmMemberProductModel.member_id == member_id) + if status is not None: + query = query.filter(CrmMemberProductModel.status == status) + total = query.count() + rows = query.order_by(CrmMemberProductModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._member_product_to_dict(p) for p in rows], "total": total, "page": page, "page_size": page_size} + + async def purchase_product(self, data: dict, operator: str = "") -> dict: + product_id = data.get("product_id") or data.get("productId") + product = self.session.query(CrmProductModel).filter(CrmProductModel.id == product_id).first() if product_id else None + total_count = int(data.get("total_count") or data.get("totalCount") or data.get("purchase_count") or data.get("purchaseCount") or (product.default_count if product else 1) or 0) + unit_price = self._decimal(data.get("unit_price") or data.get("unitPrice") or (product.price if product else 0)) + discount = self._decimal(data.get("discount") or 1) + total_amount = self._decimal(data.get("total_amount") or data.get("totalAmount") or (unit_price * total_count * discount)) + valid_start = self._parse_date(data.get("valid_start") or data.get("validStart")) or datetime.now().date() + valid_end = self._parse_date(data.get("valid_end") or data.get("validEnd")) or (valid_start + timedelta(days=365)) + member_product = CrmMemberProductModel( + id=generate_id(), store_id=data.get("store_id"), + member_id=data.get("member_id") or data.get("memberId"), product_id=product_id, + account_id=data.get("account_id") or data.get("accountId"), + product_name=data.get("product_name") or data.get("productName") or (product.product_name if product else "产品套餐"), + package_items=data.get("package_items") or data.get("packageItems"), + unit_price=unit_price, purchase_count=total_count, discount=discount, + total_count=total_count, balance_count=int(data.get("balance_count") or data.get("balanceCount") or total_count), + total_amount=total_amount, balance_amount=self._decimal(data.get("balance_amount") or data.get("balanceAmount") or total_amount), + valid_start=valid_start, + valid_end=valid_end, + notes=data.get("notes"), creator=operator, updater=operator, + ) + self.session.add(member_product) + self.session.commit() + self.session.refresh(member_product) + return self._member_product_to_dict(member_product) + + def consume_member_product_sync(self, member_product_id: str, data: dict, + store_id: Optional[str] = None, operator: str = ""): + query = self.session.query(CrmMemberProductModel).filter(CrmMemberProductModel.id == member_product_id) + if store_id: + query = query.filter(CrmMemberProductModel.store_id == store_id) + member_product = query.first() + if not member_product: + return None + count = int(data.get("consume_count") or data.get("consumeCount") or 1) + amount = self._decimal(data.get("consume_amount") or data.get("consumeAmount") or 0) + member_product.balance_count = max(0, int(member_product.balance_count or 0) - count) + member_product.balance_amount = max(Decimal("0"), self._decimal(member_product.balance_amount) - amount) + if member_product.balance_count == 0 and self._decimal(member_product.balance_amount) == 0: + member_product.status = 0 + member_product.update_date = datetime.now() + visit_id = data.get("visit_id") or data.get("visitId") or self._latest_visit_id(member_product.member_id, member_product.store_id) + if visit_id and amount: + self._sync_visit_consumption(visit_id, amount) + consume = CrmProductConsumeModel( + id=generate_id(), store_id=member_product.store_id, member_id=member_product.member_id, + member_product_id=member_product.id, product_id=member_product.product_id, visit_id=visit_id, + consume_count=count, consume_amount=amount, + balance_count_after=member_product.balance_count, balance_amount_after=member_product.balance_amount, + notes=data.get("notes"), operator=operator, + ) + self.session.add(consume) + return member_product + + async def consume_member_product(self, member_product_id: str, data: dict, + store_id: Optional[str] = None, operator: str = "") -> Optional[dict]: + member_product = self.consume_member_product_sync(member_product_id, data, store_id, operator) + if not member_product: + return None + self.session.commit() + self.session.refresh(member_product) + return self._member_product_to_dict(member_product) + + def _consume_member_product_old_unused(self, member_product_id: str, data: dict, + store_id: Optional[str] = None, operator: str = "") -> Optional[dict]: + query = self.session.query(CrmMemberProductModel).filter(CrmMemberProductModel.id == member_product_id) + if store_id: + query = query.filter(CrmMemberProductModel.store_id == store_id) + member_product = query.first() + if not member_product: + return None + count = int(data.get("consume_count") or data.get("consumeCount") or 1) + amount = self._decimal(data.get("consume_amount") or data.get("consumeAmount") or 0) + member_product.balance_count = max(0, int(member_product.balance_count or 0) - count) + member_product.balance_amount = max(Decimal("0"), self._decimal(member_product.balance_amount) - amount) + if member_product.balance_count == 0 and self._decimal(member_product.balance_amount) == 0: + member_product.status = 0 + member_product.update_date = datetime.now() + visit_id = data.get("visit_id") or data.get("visitId") or self._latest_visit_id(member_product.member_id, member_product.store_id) + if visit_id and amount: + self._sync_visit_consumption(visit_id, amount) + consume = CrmProductConsumeModel( + id=generate_id(), store_id=member_product.store_id, member_id=member_product.member_id, + member_product_id=member_product.id, product_id=member_product.product_id, visit_id=visit_id, + consume_count=count, consume_amount=amount, + balance_count_after=member_product.balance_count, balance_amount_after=member_product.balance_amount, + notes=data.get("notes"), operator=operator, + ) + self.session.add(consume) + self.session.commit() + self.session.refresh(member_product) + return self._member_product_to_dict(member_product) + + async def list_product_consumes(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, + member_id: Optional[str] = None, + member_product_id: Optional[str] = None) -> dict: + query = self.session.query(CrmProductConsumeModel) + if store_id: + query = query.filter(CrmProductConsumeModel.store_id == store_id) + if member_id: + query = query.filter(CrmProductConsumeModel.member_id == member_id) + if member_product_id: + query = query.filter(CrmProductConsumeModel.member_product_id == member_product_id) + total = query.count() + rows = query.order_by(CrmProductConsumeModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._product_consume_to_dict(c) for c in rows], "total": total, "page": page, "page_size": page_size} + + # ---- Suggestion / Issue ---- + async def list_suggestions(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, status: Optional[str] = None) -> dict: + query = self.session.query(CrmSuggestionModel) + if store_id: + query = query.filter(CrmSuggestionModel.store_id == store_id) + if status: + query = query.filter(CrmSuggestionModel.status == status) + total = query.count() + rows = query.order_by(CrmSuggestionModel.frequency.desc(), CrmSuggestionModel.create_date.desc()) \ + .offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._suggestion_to_dict(s) for s in rows], "total": total, "page": page, "page_size": page_size} + + async def create_suggestion(self, data: dict, operator: str = "") -> dict: + content = (data.get("content") or "").strip() + content_hash = self._content_hash(content) + store_id = data.get("store_id") + existing = self.session.query(CrmSuggestionModel).filter( + CrmSuggestionModel.store_id == store_id, + CrmSuggestionModel.content_hash == content_hash, + ).first() + if existing: + existing.frequency = (existing.frequency or 1) + 1 + existing.update_date = datetime.now() + self.session.commit() + self.session.refresh(existing) + return self._suggestion_to_dict(existing) + suggestion = CrmSuggestionModel( + id=generate_id(), store_id=store_id, + feedback_record_id=data.get("feedback_record_id") or data.get("feedbackRecordId"), + member_id=data.get("member_id") or data.get("memberId"), + content=content, content_hash=content_hash, + category=data.get("category") or self._suggestion_category(content), + tags=data.get("tags") or self._suggestion_tags(content), + priority=data.get("priority") or self._suggestion_priority(content), + source=data.get("source") or "manual", + submitter_name=data.get("submitter_name") or data.get("submitterName") or self._member_name(data.get("member_id") or data.get("memberId")), + duplicate_group_id=generate_id(), + status=data.get("status") or "pending", handled_by=operator, + ) + self.session.add(suggestion) + self.session.commit() + self.session.refresh(suggestion) + return self._suggestion_to_dict(suggestion) + + async def update_suggestion_status(self, suggestion_id: str, status: str, data: dict, + store_id: Optional[str] = None, operator: str = "") -> Optional[dict]: + query = self.session.query(CrmSuggestionModel).filter(CrmSuggestionModel.id == suggestion_id) + if store_id: + query = query.filter(CrmSuggestionModel.store_id == store_id) + suggestion = query.first() + if not suggestion: + return None + suggestion.status = status + suggestion.handled_by = operator + suggestion.handle_notes = data.get("handle_notes") or data.get("handleNotes") or suggestion.handle_notes + suggestion.rejected_reason = data.get("rejected_reason") or data.get("rejectedReason") or suggestion.rejected_reason + if status == "adopted": + suggestion.adopted_at = datetime.now() + suggestion.update_date = datetime.now() + self.session.commit() + self.session.refresh(suggestion) + return self._suggestion_to_dict(suggestion) + + async def list_issues(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, status: Optional[str] = None) -> dict: + query = self.session.query(CrmIssueModel) + if store_id: + query = query.filter(CrmIssueModel.store_id == store_id) + if status: + query = query.filter(CrmIssueModel.status == status) + total = query.count() + rows = query.order_by(CrmIssueModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + return {"list": [self._issue_to_dict(i) for i in rows], "total": total, "page": page, "page_size": page_size} + + async def create_issue(self, data: dict, operator: str = "") -> dict: + issue = CrmIssueModel( + id=generate_id(), store_id=data.get("store_id"), + feedback_record_id=data.get("feedback_record_id") or data.get("feedbackRecordId"), + member_id=data.get("member_id") or data.get("memberId"), + card_close_id=data.get("card_close_id") or data.get("cardCloseId"), + title=data.get("title"), description=data.get("description"), + severity=data.get("severity") or "medium", category=data.get("category"), + status=data.get("status") or "identified", + fix_plan=data.get("fix_plan") or data.get("fixPlan"), + fix_deadline=self._parse_datetime(data.get("fix_deadline") or data.get("fixDeadline")), + assigned_to=data.get("assigned_to") or data.get("assignedTo"), + ) + self.session.add(issue) + self.session.commit() + self.session.refresh(issue) + return self._issue_to_dict(issue) + + async def update_issue(self, issue_id: str, data: dict, store_id: Optional[str] = None, + operator: str = "") -> Optional[dict]: + query = self.session.query(CrmIssueModel).filter(CrmIssueModel.id == issue_id) + if store_id: + query = query.filter(CrmIssueModel.store_id == store_id) + issue = query.first() + if not issue: + return None + for key, field in [("title", "title"), ("description", "description"), ("severity", "severity"), + ("category", "category"), ("status", "status"), ("fix_plan", "fix_plan"), + ("fixPlan", "fix_plan"), ("fix_result", "fix_result"), ("fixResult", "fix_result"), + ("assigned_to", "assigned_to"), ("assignedTo", "assigned_to")]: + if key in data: + setattr(issue, field, data[key]) + if issue.status == "fixed" and not issue.fixed_at: + issue.fixed_at = datetime.now() + if issue.status == "closed" and not issue.closed_at: + issue.closed_at = datetime.now() + issue.update_date = datetime.now() + self.session.commit() + self.session.refresh(issue) + return self._issue_to_dict(issue) + + async def bind_feedback(self, feedback_id: str, data: dict, store_id: Optional[str] = None) -> Optional[dict]: + query = self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.id == feedback_id) + if store_id: + query = query.filter(FeedbackRecordModel.store_id == store_id) + record = query.first() + if not record: + return None + for key, field in [("member_id", "member_id"), ("memberId", "member_id"), + ("visit_id", "visit_id"), ("visitId", "visit_id"), + ("card_close_id", "card_close_id"), ("cardCloseId", "card_close_id")]: + if key in data: + setattr(record, field, data[key]) + self.session.commit() + self.session.refresh(record) + return self._feedback_to_dict(record) + + async def get_overview(self, store_id: Optional[str] = None) -> dict: + def count(model, *filters): + q = self.session.query(func.count(model.id)) + if store_id and hasattr(model, "store_id"): + q = q.filter(model.store_id == store_id) + for f in filters: + q = q.filter(f) + return q.scalar() or 0 + total_balance = self.session.query(func.coalesce(func.sum(CrmAccountModel.balance_amount), 0)) + if store_id: + total_balance = total_balance.filter(CrmAccountModel.store_id == store_id) + return { + "members": count(CrmMemberModel), + "visits": count(CrmVisitModel), + "activeAccounts": count(CrmAccountModel, CrmAccountModel.status == 1), + "accountBalance": float(total_balance.scalar() or 0), + "cardCloses": count(CrmCardCloseModel), + "pendingSuggestions": count(CrmSuggestionModel, CrmSuggestionModel.status == "pending"), + "adoptedSuggestions": count(CrmSuggestionModel, CrmSuggestionModel.status == "adopted"), + "openIssues": count(CrmIssueModel, CrmIssueModel.status.in_(["identified", "fixing"])), + "fixedIssues": count(CrmIssueModel, CrmIssueModel.status.in_(["fixed", "closed"])), + } + + # ---- Helpers ---- + def _get_account(self, account_id: str, store_id: Optional[str] = None): + query = self.session.query(CrmAccountModel).filter(CrmAccountModel.id == account_id) + if store_id: + query = query.filter(CrmAccountModel.store_id == store_id) + return query.first() + + def _latest_visit_id(self, member_id: str, store_id: str): + if not member_id: + return None + visit = self.session.query(CrmVisitModel).filter( + CrmVisitModel.member_id == member_id, + CrmVisitModel.store_id == store_id, + CrmVisitModel.status == 1, + ).order_by(CrmVisitModel.arrive_at.desc(), CrmVisitModel.create_date.desc()).first() + return visit.id if visit else None + + def _sync_visit_consumption(self, visit_id: str, amount: Decimal): + visit = self.session.query(CrmVisitModel).filter(CrmVisitModel.id == visit_id).first() + if visit: + visit.consumption_amount = self._decimal(visit.consumption_amount) + self._decimal(amount) + visit.update_date = datetime.now() + + def _add_transaction(self, account, tx_type, amount, count_change, before, after, visit_id, notes, operator): + self.session.add(CrmAccountTransactionModel( + id=generate_id(), account_id=account.id, store_id=account.store_id, member_id=account.member_id, + transaction_type=tx_type, amount=amount, count_change=count_change, + balance_before=before, balance_after=after, related_visit_id=visit_id, + notes=notes, operator=operator, + )) + + def _touch_member_visit_stats(self, member_id, arrive_at, amount): + if not member_id: + return + member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id).first() + if member: + member.total_visits = (member.total_visits or 0) + 1 + member.total_spent = self._decimal(member.total_spent) + self._decimal(amount) + if arrive_at and (not member.last_visit_at or arrive_at > member.last_visit_at): + member.last_visit_at = arrive_at + member.update_date = datetime.now() + + @staticmethod + def _suggestion_category(content: str) -> str: + text = content or "" + if any(k in text for k in ["冷", "热", "空调", "房间", "环境", "卫生", "水"]): + return "environment" + if any(k in text for k in ["态度", "服务", "技师", "沟通"]): + return "service" + if any(k in text for k in ["价格", "优惠", "贵", "便宜", "活动"]): + return "price" + if any(k in text for k in ["产品", "项目", "效果", "套餐"]): + return "product" + return "other" + + @staticmethod + def _suggestion_tags(content: str) -> list: + text = content or "" + tags = [] + mapping = { + "环境": ["冷", "热", "空调", "房间", "环境"], + "卫生": ["卫生", "干净", "毛巾"], + "服务": ["服务", "态度", "沟通", "技师"], + "价格": ["价格", "优惠", "贵", "活动"], + "产品": ["产品", "项目", "套餐", "效果"], + "茶水": ["水", "茶", "饮品"], + } + for tag, keywords in mapping.items(): + if any(k in text for k in keywords): + tags.append(tag) + return tags or ["其他"] + + @staticmethod + def _suggestion_priority(content: str) -> str: + text = content or "" + if any(k in text for k in ["投诉", "退款", "销卡", "很差"]): + return "urgent" + if any(k in text for k in ["不满意", "态度", "卫生", "没效果"]): + return "high" + if any(k in text for k in ["建议", "希望", "可以"]): + return "medium" + return "low" + + @staticmethod + def _should_create_issue_for_close(reason: Optional[str]) -> bool: + text = reason or "" + return any(k in text for k in ["不满意", "没效果", "态度", "投诉", "退款", "服务", "卫生", "太冷", "太热"]) + + @staticmethod + def _content_hash(content: str) -> str: + normalized = re.sub(r"\s+", "", content or "").lower() + normalized = re.sub(r"[,。!?,.!?;;::]", "", normalized) + return hashlib.sha256(normalized.encode("utf-8")).hexdigest() + + @staticmethod + def _decimal(value) -> Decimal: + if value is None or value == "": + return Decimal("0") + return Decimal(str(value)) + + @staticmethod + def _parse_date(value): + if not value: + return None + if hasattr(value, "year"): + return value + return datetime.fromisoformat(str(value).replace("Z", "+00:00")[:10]).date() + + @staticmethod + def _parse_datetime(value): + if not value: + return None + if isinstance(value, datetime): + return value + text = str(value).replace("Z", "+00:00") + try: + return datetime.fromisoformat(text) + except ValueError: + return datetime.strptime(text[:19], "%Y-%m-%d %H:%M:%S") + + @staticmethod + def _json(value): + if isinstance(value, str): + try: + return json.loads(value) + except Exception: + return value + return value + + def _member_name(self, member_id): + if not member_id: + return None + member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id).first() + return member.name if member else None + + def _member_to_dict(self, m): + return { + "id": m.id, "storeId": m.store_id, "name": m.name, "phone": m.phone, "gender": m.gender, + "birthday": str(m.birthday) if m.birthday else None, "wechat": m.wechat, "source": m.source, + "level": m.level, "tags": self._json(m.tags), "mekaiTags": self._json(m.mekai_tags), + "beautyConcerns": self._json(m.beauty_concerns), "healthIssues": self._json(m.health_issues), + "allergies": m.allergies, "servicePreferences": self._json(m.service_preferences), "notes": m.notes, + "lastVisitAt": str(m.last_visit_at) if m.last_visit_at else None, + "totalVisits": m.total_visits or 0, "totalSpent": float(m.total_spent or 0), "status": m.status, + "createDate": str(m.create_date) if m.create_date else None, "updateDate": str(m.update_date) if m.update_date else None, + } + + def _visit_to_dict(self, v): + return { + "id": v.id, "storeId": v.store_id, "memberId": v.member_id, "memberName": self._member_name(v.member_id), "employeeId": v.employee_id, + "feedbackRecordId": v.feedback_record_id, "sessionId": v.session_id, "deviceMac": v.device_mac, + "visitType": v.visit_type, "serviceItems": self._json(v.service_items), + "arriveAt": str(v.arrive_at) if v.arrive_at else None, "leaveAt": str(v.leave_at) if v.leave_at else None, + "durationMinutes": v.duration_minutes, "satisfaction": v.satisfaction, + "consumptionAmount": float(v.consumption_amount or 0), "notes": v.notes, "status": v.status, + "createDate": str(v.create_date) if v.create_date else None, + } + + def _account_to_dict(self, a): + return { + "id": a.id, "storeId": a.store_id, "memberId": a.member_id, "memberName": self._member_name(a.member_id), "accountType": a.account_type, + "cardName": a.card_name, "totalAmount": float(a.total_amount or 0), "balanceAmount": float(a.balance_amount or 0), + "totalCount": a.total_count or 0, "balanceCount": a.balance_count or 0, + "validStart": str(a.valid_start) if a.valid_start else None, "validEnd": str(a.valid_end) if a.valid_end else None, + "status": a.status, "closedReason": a.closed_reason, "closedAt": str(a.closed_at) if a.closed_at else None, + "notes": a.notes, "createDate": str(a.create_date) if a.create_date else None, + } + + def _body_status_to_dict(self, b): + return { + "id": b.id, "storeId": b.store_id, "memberId": b.member_id, + "memberName": self._member_name(b.member_id), "visitId": b.visit_id, + "memberProductId": b.member_product_id, + "recordDate": str(b.record_date) if b.record_date else None, + "weight": float(b.weight) if b.weight is not None else None, + "waistline": float(b.waistline) if b.waistline is not None else None, + "painLevel": b.pain_level, "sleepQuality": b.sleep_quality, + "skinStatus": b.skin_status, "bodyParts": self._json(b.body_parts), + "metrics": self._json(b.metrics), "notes": b.notes, + "createDate": str(b.create_date) if b.create_date else None, + } + + def _product_to_dict(self, p): + return { + "id": p.id, "storeId": p.store_id, "productName": p.product_name, + "productType": p.product_type, "category": p.category, + "price": float(p.price or 0), "defaultCount": p.default_count or 0, + "description": p.description, "status": p.status, + "createDate": str(p.create_date) if p.create_date else None, + } + + def _member_product_to_dict(self, p): + product = self.session.query(CrmProductModel).filter(CrmProductModel.id == p.product_id).first() if p.product_id else None + return { + "id": p.id, "storeId": p.store_id, "memberId": p.member_id, + "memberName": self._member_name(p.member_id), "productId": p.product_id, + "accountId": p.account_id, "productName": p.product_name, + "unitPrice": float(p.unit_price or 0), "purchaseCount": p.purchase_count or 0, + "discount": float(p.discount or 1), "durationMinutes": product.duration_minutes if product else 60, + "packageItems": self._json(p.package_items), "totalCount": p.total_count or 0, + "balanceCount": p.balance_count or 0, "totalAmount": float(p.total_amount or 0), + "balanceAmount": float(p.balance_amount or 0), + "validStart": str(p.valid_start) if p.valid_start else None, + "validEnd": str(p.valid_end) if p.valid_end else None, + "status": p.status, "notes": p.notes, + "createDate": str(p.create_date) if p.create_date else None, + } + + def _product_consume_to_dict(self, c): + return { + "id": c.id, "storeId": c.store_id, "memberId": c.member_id, + "memberName": self._member_name(c.member_id), "memberProductId": c.member_product_id, + "productId": c.product_id, "visitId": c.visit_id, + "consumeCount": c.consume_count or 0, "consumeAmount": float(c.consume_amount or 0), + "balanceCountAfter": c.balance_count_after or 0, + "balanceAmountAfter": float(c.balance_amount_after or 0), + "notes": c.notes, "operator": c.operator, + "createDate": str(c.create_date) if c.create_date else None, + } + + def _transaction_to_dict(self, t): + return { + "id": t.id, "accountId": t.account_id, "storeId": t.store_id, + "memberId": t.member_id, "memberName": self._member_name(t.member_id), + "transactionType": t.transaction_type, "amount": float(t.amount or 0), + "countChange": t.count_change or 0, "balanceBefore": float(t.balance_before or 0), + "balanceAfter": float(t.balance_after or 0), "relatedVisitId": t.related_visit_id, + "notes": t.notes, "operator": t.operator, + "createDate": str(t.create_date) if t.create_date else None, + } + + def _card_close_to_dict(self, c): + return { + "id": c.id, "storeId": c.store_id, "memberId": c.member_id, "memberName": self._member_name(c.member_id), "accountId": c.account_id, + "feedbackRecordId": c.feedback_record_id, "closeType": c.close_type, "reason": c.reason, + "refundAmount": float(c.refund_amount or 0), "remainingCount": c.remaining_count or 0, + "status": c.status, "handledBy": c.handled_by, "approvedBy": c.approved_by, + "handleNotes": c.handle_notes, "createDate": str(c.create_date) if c.create_date else None, + } + + def _suggestion_to_dict(self, s): + return { + "id": s.id, "storeId": s.store_id, "feedbackRecordId": s.feedback_record_id, "memberId": s.member_id, + "content": s.content, "category": s.category, "tags": self._json(s.tags), + "priority": s.priority, "source": s.source, "submitterName": s.submitter_name, + "memberName": self._member_name(s.member_id), + "duplicateGroupId": s.duplicate_group_id, + "frequency": s.frequency or 1, "status": s.status, "adoptedAt": str(s.adopted_at) if s.adopted_at else None, + "rejectedReason": s.rejected_reason, "handledBy": s.handled_by, "handleNotes": s.handle_notes, + "createDate": str(s.create_date) if s.create_date else None, + } + + def _issue_to_dict(self, i): + return { + "id": i.id, "storeId": i.store_id, "feedbackRecordId": i.feedback_record_id, "memberId": i.member_id, + "cardCloseId": i.card_close_id, "title": i.title, "description": i.description, + "severity": i.severity, "category": i.category, "status": i.status, + "identifiedAt": str(i.identified_at) if i.identified_at else None, + "fixPlan": i.fix_plan, "fixDeadline": str(i.fix_deadline) if i.fix_deadline else None, + "fixedAt": str(i.fixed_at) if i.fixed_at else None, "fixResult": i.fix_result, + "assignedTo": i.assigned_to, "closedAt": str(i.closed_at) if i.closed_at else None, + "createDate": str(i.create_date) if i.create_date else None, + } + + def _feedback_to_dict(self, r): + return { + "id": r.id, "storeId": r.store_id, "memberId": r.member_id, "visitId": r.visit_id, + "cardCloseId": r.card_close_id, "satisfaction": r.satisfaction, + "rawAsrText": r.raw_asr_text, "cleanedText": r.cleaned_text, + "qaJson": r.qa_json, "reviewLong": r.review_long, "reviewShort": r.review_short, + "createDate": str(r.create_date) if r.create_date else None, + } diff --git a/main/feedback-backend/app/application/employee_service.py b/main/feedback-backend/app/application/employee_service.py new file mode 100644 index 000000000..6dc1ea717 --- /dev/null +++ b/main/feedback-backend/app/application/employee_service.py @@ -0,0 +1,93 @@ +"""员工应用服务 - 员工 CRUD 用例""" + +from typing import Optional + +from loguru import logger +from sqlalchemy.orm import Session + +from app.domain.employee.entity import Employee +from app.domain.employee.value_objects import EmployeeType +from app.infrastructure.persistence.employee_repo_impl import EmployeeRepositoryImpl +from app.shared.exceptions import EmployeeNotFoundError, StoreNotFoundError, ValidationError +from app.shared.utils import generate_id + + +class EmployeeService: + """员工应用服务""" + + def __init__(self, session: Session): + self.repo = EmployeeRepositoryImpl(session) + self.session = session + + async def list_by_store_id(self, store_id: str, status: Optional[int] = None) -> list: + """获取门店下所有员工(公开接口用)""" + return await self.repo.list_by_store_id(store_id, status) + + async def get_by_id(self, employee_id: str) -> Employee: + """根据 ID 获取员工""" + employee = await self.repo.get_by_id(employee_id) + if not employee: + raise EmployeeNotFoundError(employee_id) + return employee + + async def list_page(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, + name: Optional[str] = None, + status: Optional[int] = None) -> dict: + """分页查询员工""" + return await self.repo.list_page(page, page_size, store_id, name, status) + + async def create_employee(self, name: str, number: int, store_id: str, + employee_type: str = "normal") -> Employee: + """创建员工""" + # 验证员工类型 + if employee_type not in Employee.valid_employee_types(): + raise ValidationError(f"无效的员工类型: {employee_type}") + + # 检查工号唯一性 + if await self.repo.exists_by_store_and_number(store_id, number): + raise ValidationError(f"门店 {store_id} 下工号 {number} 已存在") + + employee = Employee( + id=generate_id(), + name=name, + number=number, + store_id=store_id, + employee_type=employee_type, + ) + result = await self.repo.save(employee) + logger.info(f"创建员工: name={name}, store={store_id}, number={number}") + return result + + async def update_employee(self, employee_id: str, **kwargs) -> Employee: + """更新员工""" + employee = await self.repo.get_by_id(employee_id) + if not employee: + raise EmployeeNotFoundError(employee_id) + + # 如果修改了工号,检查唯一性 + if "number" in kwargs and kwargs["number"] != employee.number: + store_id = kwargs.get("store_id", employee.store_id) + if await self.repo.exists_by_store_and_number(store_id, kwargs["number"], exclude_id=employee_id): + raise ValidationError(f"工号 {kwargs['number']} 已存在") + + if "employee_type" in kwargs: + if kwargs["employee_type"] not in Employee.valid_employee_types(): + raise ValidationError(f"无效的员工类型: {kwargs['employee_type']}") + + for key, value in kwargs.items(): + if hasattr(employee, key) and value is not None: + setattr(employee, key, value) + + result = await self.repo.save(employee) + logger.info(f"更新员工: id={employee_id}") + return result + + async def delete_employee(self, employee_id: str) -> bool: + """删除员工""" + employee = await self.repo.get_by_id(employee_id) + if not employee: + raise EmployeeNotFoundError(employee_id) + result = await self.repo.delete(employee_id) + logger.info(f"删除员工: id={employee_id}") + return result diff --git a/main/feedback-backend/app/application/feedback_service.py b/main/feedback-backend/app/application/feedback_service.py new file mode 100644 index 000000000..43f3cac28 --- /dev/null +++ b/main/feedback-backend/app/application/feedback_service.py @@ -0,0 +1,681 @@ +"""反馈处理应用服务 - AI 处理管线(3步 LLM Pipeline)""" + +import json +from datetime import datetime +from decimal import Decimal +from pathlib import Path +from typing import Any, Dict, Optional + +from loguru import logger +from sqlalchemy.orm import Session + +from app.domain.feedback.entity import FeedbackRecord +from app.domain.feedback.value_objects import Satisfaction +from app.infrastructure.llm.llm_service import LLMService +from app.infrastructure.persistence.feedback_repo_impl import FeedbackRecordRepositoryImpl +from app.infrastructure.persistence.store_repo_impl import StoreRepositoryImpl +from app.infrastructure.persistence.agent_repo_impl import AgentConfigRepositoryImpl +from app.shared.config import settings +from app.shared.exceptions import StoreNotFoundError, LLMProcessingError, PromptTemplateError +from app.shared.utils import generate_id, should_generate_review, render_prompt +from app.infrastructure.persistence.models import ( + CrmIssueModel, + CrmMemberModel, + CrmSuggestionModel, + CrmVisitModel, + FeedbackRecordModel, +) + + +class FeedbackService: + """反馈处理应用服务 - 核心业务逻辑 + + 3 步 AI Pipeline: + 1. ASR 清洗 - 去除语音填充词 + 2. QA 结构化 - 提取结构化 Q&A + 3. 点评生成 - 仅满意时生成点评 + """ + + def __init__(self, session: Session): + self.record_repo = FeedbackRecordRepositoryImpl(session) + self.store_repo = StoreRepositoryImpl(session) + self.agent_repo = AgentConfigRepositoryImpl(session) + self.session = session + + def _get_prompts_dir(self) -> Path: + """获取提示词模板目录""" + base_dir = Path(__file__).resolve().parent.parent.parent # feedback-backend/ + return base_dir / "prompts" + + def _load_prompt(self, filename: str) -> str: + """加载提示词模板""" + path = self._get_prompts_dir() / filename + if not path.exists(): + raise PromptTemplateError(filename, f"模板文件不存在: {path}") + return path.read_text(encoding="utf-8") + + def _resolve_llm_service(self, agent_id: Optional[str] = None) -> LLMService: + """解析 LLM 服务 - 优先使用门店绑定的智能体配置""" + if agent_id: + # 尝试从 agent_config 获取自定义 LLM 配置 + # 注意:这里不能用 async,所以在外层处理 + pass + # 使用默认配置 + return LLMService() + + async def _resolve_llm_service_async(self, agent_id: Optional[str] = None) -> LLMService: + """异步解析 LLM 服务""" + if agent_id: + agent_config = await self.agent_repo.get_by_agent_id(agent_id) + if agent_config and agent_config.llm_config: + return LLMService(llm_config=agent_config.llm_config) + return LLMService() + + async def process_feedback( + self, + store_name: str, + employee_number: str, + asr_text: str, + session_id: Optional[str] = None, + device_mac: Optional[str] = None, + satisfaction: Optional[str] = None, + store_id: Optional[str] = None, + employee_id: Optional[str] = None, + customer_name: Optional[str] = None, + phone_tail: Optional[str] = None, + agent_id: Optional[str] = None, + ) -> Dict[str, Any]: + """ + 处理客户反馈 - 完整的 3 步 AI Pipeline + + Args: + store_name: 门店名称 + employee_number: 技师工号 + asr_text: 原始 ASR 文本 + session_id: 会话 ID + device_mac: 设备 MAC + satisfaction: 满意度 + store_id: 门店 ID + employee_id: 员工 ID + agent_id: 智能体 ID + + Returns: + 处理结果字典 + """ + logger.info(f"开始处理反馈: store={store_name}, employee={employee_number}, satisfaction={satisfaction}") + + # 验证满意度 + satisfaction_text = "" + should_publish = False + if satisfaction: + try: + sat = Satisfaction(satisfaction) + satisfaction_text = sat.text + should_publish = sat.is_positive + except ValueError: + logger.warning(f"无效的满意度值: {satisfaction}") + + # 解析 LLM 服务 + llm = await self._resolve_llm_service_async(agent_id) + + # Step 1: ASR 清洗 + cleaned_text = await self._step_asr_cleanup(llm, store_name, employee_number, asr_text) + logger.info(f"ASR 清洗完成,原文 {len(asr_text)} 字 -> 清洗后 {len(cleaned_text)} 字") + + # Step 2: QA 结构化 + qa_result = await self._step_qa_structured(llm, store_name, employee_number, cleaned_text) + logger.info(f"QA 结构化完成") + + # Step 3: 点评生成(仅满意时) + review_long = None + review_short = None + if should_publish and should_generate_review(satisfaction): + review_long, review_short = await self._step_review_generation( + llm, store_name, employee_number, qa_result, satisfaction + ) + logger.info(f"点评生成完成: 长评={len(review_long or '')}字, 短评={len(review_short or '')}字") + + # 保存记录(通过 session_id upsert,如果 H5 已先保存了 rawAsrText,这里会更新) + record = FeedbackRecord( + id=generate_id(), + store_id=store_id or "", + session_id=session_id, + employee_id=employee_id, + device_mac=device_mac, + raw_asr_text=asr_text, + cleaned_text=cleaned_text, + qa_json=qa_result, + review_long=review_long, + review_short=review_short, + satisfaction=satisfaction, + customer_name=(customer_name or "").strip() or None, + phone_tail=self._normalize_phone_tail(phone_tail) or None, + ) + try: + # 如果已有同 session_id 的记录,更新它 + if session_id: + existing = await self.record_repo.get_by_session_id(session_id) + if existing: + existing.cleaned_text = cleaned_text + existing.qa_json = qa_result + existing.review_long = review_long + existing.review_short = review_short + existing.satisfaction = satisfaction + existing.customer_name = (customer_name or existing.customer_name or "").strip() or None + existing.phone_tail = self._normalize_phone_tail(phone_tail) or existing.phone_tail + record = await self.record_repo.save(existing) + logger.info(f"反馈记录已更新: session_id={session_id}") + else: + record = await self.record_repo.save(record) + logger.info(f"反馈记录已保存: id={record.id}") + else: + record = await self.record_repo.save(record) + logger.info(f"反馈记录已保存: id={record.id}") + except Exception as e: + logger.error(f"反馈记录保存失败: {e}") + # 记录保存失败不影响返回结果 + + self._auto_link_feedback_to_crm(record, cleaned_text, qa_result, satisfaction) + + return { + "success": True, + "cleaned_text": cleaned_text, + "qa_result": qa_result, + "review_long": review_long, + "review_short": review_short, + "satisfaction": satisfaction, + "satisfaction_text": satisfaction_text, + "should_publish": should_publish, + "customer_name": record.customer_name, + "phone_tail": record.phone_tail, + "member_id": record.member_id, + "member_match_status": record.member_match_status, + "member_match_candidates": record.member_match_candidates or [], + } + + def _auto_link_feedback_to_crm(self, record: FeedbackRecord, cleaned_text: str, + qa_result: str, satisfaction: Optional[str]): + """根据已有反馈结构化内容自动关联 CRM。""" + if not record or not record.store_id: + return + try: + phone_tail = record.phone_tail or self._extract_phone_tail(qa_result or cleaned_text or "") + record.phone_tail = phone_tail or None + customer_name = record.customer_name or self._extract_customer_name(qa_result or cleaned_text or "") + record.customer_name = customer_name or None + match_result = self._match_member_by_identity(record.store_id, phone_tail, customer_name) + member = match_result.get("member") + record.member_match_status = match_result.get("status") + record.member_match_candidates = match_result.get("candidates") or [] + if member: + record.member_id = member.id + self._merge_member_profile(member, qa_result) + + visit = self._create_or_update_visit(record, qa_result, satisfaction) + if visit: + record.visit_id = visit.id + + self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.id == record.id).update({ + "member_id": record.member_id, + "visit_id": record.visit_id, + "customer_name": record.customer_name, + "phone_tail": record.phone_tail, + "member_match_status": record.member_match_status, + "member_match_candidates": record.member_match_candidates, + }) + self._auto_create_suggestion(record, qa_result) + self.session.commit() + except Exception as e: + self.session.rollback() + logger.warning(f"自动关联 CRM 失败: {e}") + # 问题修复模块已从主流程下线:反馈只进入建议/客户档案/到店,不再自动创建问题。 + + def _match_member_by_identity(self, store_id: str, phone_tail: str, customer_name: str = "") -> dict: + phone_tail = self._normalize_phone_tail(phone_tail) + if not phone_tail: + return {"status": None, "member": None, "candidates": []} + candidates = self.session.query(CrmMemberModel).filter( + CrmMemberModel.store_id == store_id, + CrmMemberModel.phone.like(f"%{phone_tail}"), + CrmMemberModel.status == 1, + ).order_by(CrmMemberModel.update_date.desc()).all() + candidate_list = [self._member_candidate(m) for m in candidates] + if not candidates: + return {"status": "not_found", "member": None, "candidates": []} + if len(candidates) == 1: + return {"status": "matched", "member": candidates[0], "candidates": candidate_list} + name = (customer_name or "").strip() + if name: + name_matches = [m for m in candidates if self._name_matches(name, m)] + if len(name_matches) == 1: + return {"status": "matched", "member": name_matches[0], "candidates": candidate_list} + return {"status": "conflict", "member": None, "candidates": candidate_list} + + @staticmethod + def _member_candidate(member) -> dict: + return { + "id": member.id, + "name": member.name, + "phone": member.phone, + "phoneTail": (member.phone or "")[-4:], + "nickname": (member.mekai_tags or {}).get("nickname") if isinstance(member.mekai_tags, dict) else None, + } + + @staticmethod + def _normalize_phone_tail(value: str) -> str: + import re + digits = re.sub(r"\D", "", value or "") + return digits[-4:] if len(digits) >= 4 else "" + + @staticmethod + def _name_matches(customer_name: str, member) -> bool: + name = (customer_name or "").strip() + if not name: + return False + candidates = [member.name or ""] + if isinstance(member.mekai_tags, dict): + candidates.append(member.mekai_tags.get("nickname") or "") + normalized = name.replace("女士", "").replace("先生", "").replace("姐", "").replace("哥", "").strip() + for item in candidates: + item = (item or "").strip() + item_norm = item.replace("女士", "").replace("先生", "").replace("姐", "").replace("哥", "").strip() + if name and (name in item or item in name): + return True + if normalized and item_norm and (normalized in item_norm or item_norm in normalized): + return True + return False + + @staticmethod + def _extract_customer_name(text: str) -> str: + import re + patterns = [ + r"(?:怎么称呼您|如何称呼您|称呼您|您的称呼|您怎么称呼)[^\n::,,。]{0,12}[::]?\s*([一-龥A-Za-z]{1,12})", + r"(?:我叫|我是|叫我)([一-龥A-Za-z]{1,12})", + r"Q9[^\n]*\n?A9[::]\s*([^\n,,。]+)", + r"Q9[^A]*A9[::]\s*([^\n,,。]+)", + ] + for pattern in patterns: + match = re.search(pattern, text or "") + if match: + name = match.group(1).strip() + if name and name not in {"未提及", "用户未作答", "不知道"} and not re.fullmatch(r"\d+", name): + return name[:12] + return "" + + @staticmethod + def _extract_phone_tail(text: str) -> str: + import re + match = re.search(r"(?:手机号后四位|手机尾号|尾号|后四位)[^0-9]{0,8}(\d{4})", text or "") + if match: + return match.group(1) + matches = re.findall(r"(? Optional[str]: + if not member_id: + return None + member = self.session.query(CrmMemberModel).filter(CrmMemberModel.id == member_id).first() + return member.name if member else None + + @staticmethod + def _content_hash(content: str) -> str: + import hashlib + import re + normalized = re.sub(r"\s+", "", content or "").lower() + normalized = re.sub(r"[,。!?,.!?;;::]", "", normalized) + return hashlib.sha256(normalized.encode("utf-8")).hexdigest() + + @staticmethod + def _parse_visit_time(text: str): + import re + now = datetime.now() + match = re.search(r"(\d{1,2})[点::](\d{1,2})?", text or "") + if match: + hour = int(match.group(1)) + minute = int(match.group(2) or 0) + if 0 <= hour <= 23 and 0 <= minute <= 59: + return now.replace(hour=hour, minute=minute, second=0, microsecond=0) + return None + + def _auto_create_feedback_issue(self, record: FeedbackRecord, cleaned_text: str, + qa_result: str, satisfaction: Optional[str]): + """基于已有反馈自动生成待修复问题。""" + if not record or not record.store_id: + return + negative = satisfaction in ("unsatisfied", "very_bad") + text = f"{cleaned_text or ''}\n{qa_result or ''}" + keywords = ["退款", "销卡", "投诉", "没效果", "不满意", "很差", "态度", "卫生", "太冷", "太热"] + if not negative and not any(k in text for k in keywords): + return + try: + from app.infrastructure.persistence.models import CrmIssueModel + + title = "客户反馈待修复问题" + if "销卡" in text or "退款" in text: + title = "客户存在销卡/退款风险" + elif "态度" in text: + title = "客户反馈服务态度问题" + elif "太冷" in text or "太热" in text: + title = "客户反馈环境温度问题" + elif "没效果" in text: + title = "客户反馈项目效果问题" + exists = self.session.query(CrmIssueModel).filter( + CrmIssueModel.feedback_record_id == record.id, + CrmIssueModel.title == title, + ).first() + if exists: + return + issue = CrmIssueModel( + id=generate_id(), + store_id=record.store_id, + feedback_record_id=record.id, + member_id=record.member_id, + title=title, + description=text[:1000] if text else None, + severity="high" if satisfaction == "very_bad" else "medium", + category="feedback", + status="identified", + ) + self.session.add(issue) + self.session.commit() + logger.info(f"已从反馈自动创建问题: feedback_id={record.id}, issue_id={issue.id}") + except Exception as e: + self.session.rollback() + logger.warning(f"自动创建反馈问题失败: {e}") + + async def _step_asr_cleanup(self, llm: LLMService, store_name: str, + employee_number: str, asr_text: str) -> str: + """Step 1: ASR 清洗 - 去除语音填充词""" + try: + template = self._load_prompt("asr-cleanup.txt") + prompt = render_prompt( + template, + 门店名称=store_name, + 技师工号=employee_number, + 用户全部语音原话=asr_text, + ) + result = await llm.chat( + system_prompt="你是一位专业的语音文本清洗专家。", + user_message=prompt, + temperature=0.1, + ) + return result.strip() + except PromptTemplateError: + # 模板不存在时,直接使用简单清洗 + logger.warning("ASR 清洗模板不存在,使用简单清洗") + return asr_text.strip() + except Exception as e: + logger.error(f"ASR 清洗失败: {e}") + raise LLMProcessingError(f"ASR 清洗失败: {e}") + + async def _step_qa_structured(self, llm: LLMService, store_name: str, + employee_number: str, cleaned_text: str) -> str: + """Step 2: QA 结构化 - 提取结构化 Q&A""" + try: + template = self._load_prompt("qa-structured.txt") + prompt = render_prompt( + template, + 门店名称=store_name, + 技师编号=employee_number, + 消费项目="", + 规整后ASR文本=cleaned_text, + ) + result = await llm.chat( + system_prompt="你是一位专业的客户反馈分析师。", + user_message=prompt, + temperature=0.2, + ) + return result.strip() + except PromptTemplateError: + logger.warning("QA 结构化模板不存在,跳过结构化") + return cleaned_text + except Exception as e: + logger.error(f"QA 结构化失败: {e}") + raise LLMProcessingError(f"QA 结构化失败: {e}") + + async def _step_review_generation(self, llm: LLMService, store_name: str, + employee_number: str, qa_result: str, + satisfaction: str) -> tuple: + """Step 3: 点评生成 - 生成标准版和精简版点评""" + try: + template = self._load_prompt("review-generation.txt") + + # 从 QA 结果中提取信息(解析 Q1-Q8 格式) + consumption_item = self._extract_qa_answer(qa_result, "Q3") or self._extract_qa_answer(qa_result, "项目") + duration = self._extract_qa_answer(qa_result, "Q2") or self._extract_qa_answer(qa_result, "多久") + visit_time = self._extract_qa_answer(qa_result, "Q4") or self._extract_qa_answer(qa_result, "时间") + discomfort = self._extract_qa_answer(qa_result, "Q5") or self._extract_qa_answer(qa_result, "不舒服") + problem_solved = self._extract_qa_answer(qa_result, "Q6") or self._extract_qa_answer(qa_result, "解决") + satisfaction_level = Satisfaction(satisfaction).text if satisfaction else "" + + prompt = render_prompt( + template, + 门店名称=store_name, + 技师编号=employee_number, + 消费项目=consumption_item or "未提及", + 到店时长=duration or "未提及", + 到店时间=visit_time or "未提及", + 身体不舒服症状=discomfort or "未提及", + 问题是否解决=problem_solved or "未提及", + 满意程度=satisfaction_level or "满意", + ) + + # 将完整的 QA 结果附加到 prompt 中,作为上下文参考 + full_prompt = prompt + "\n\n以下是客户的完整QA反馈记录,请严格基于这些QA内容生成点评(注意区分【客户】和【技师】的归属,不要张冠李戴):\n" + qa_result + + result = await llm.chat( + system_prompt="你是一位专业的点评撰写专家,擅长根据客户反馈撰写真实自然的消费点评。你必须严格基于QA记录中的信息撰写,特别注意区分客户本人和技师的属性(比如来店3年是客户的消费时长,不是技师的工作时长)。", + user_message=full_prompt, + temperature=0.7, + max_tokens=1000, + ) + + # 解析点评结果 + review_long, review_short = self._parse_review_result(result) + return review_long, review_short + + except PromptTemplateError: + logger.warning("点评生成模板不存在,跳过点评生成") + return None, None + except Exception as e: + logger.error(f"点评生成失败: {e}") + return None, None + + @staticmethod + def _parse_review_result(result: str) -> tuple: + """解析 LLM 返回的点评结果 - 支持多种格式""" + import re + review_long = None + review_short = None + + # 清理 markdown 格式符号 + cleaned = re.sub(r'^#{1,6}\s*', '', result, flags=re.MULTILINE) + cleaned = re.sub(r'^---+\s*$', '', cleaned, flags=re.MULTILINE) + + # 策略1: 【标准版点评】...【精简短评】... + long_match = re.search(r"【标准版点评】[::\s]*(.*?)(?=【精简短评】|$)", cleaned, re.DOTALL) + short_match = re.search(r"【精简短评】[::\s]*(.*?)$", cleaned, re.DOTALL) + + # 策略2: 标准版点评:...精简短评:... + if not long_match: + long_match = re.search(r"标准版点评[::\s]*(.*?)(?=精简短评|$)", cleaned, re.DOTALL) + if not short_match: + short_match = re.search(r"精简短评[::\s]*(.*?)$", cleaned, re.DOTALL) + + # 策略3: 长评:...短评:... + if not long_match: + long_match = re.search(r"长评[::\s]*(.*?)(?=短评|$)", cleaned, re.DOTALL) + if not short_match: + short_match = re.search(r"短评[::\s]*(.*?)$", cleaned, re.DOTALL) + + if long_match: + review_long = long_match.group(1).strip() + if short_match: + review_short = short_match.group(1).strip() + + # 如果没有标准格式,整段作为长评 + if not review_long and not review_short: + review_long = result.strip() + + return review_long, review_short + + @staticmethod + def _extract_qa_answer(qa_text: str, question_key: str) -> str: + """从 QA 结构化文本中提取指定问题的答案 + + 支持多种格式: + - Q1: xxx A1: xxx + - Q1:xxx A1:xxx + - 技师工号是多少?xxx => 用关键词匹配 + """ + import re + + if not qa_text: + return "" + + lines = qa_text.strip().split('\n') + + # 尝试按 Q编号 + A编号 格式匹配 + # 先找 question_key 对应的 Q 编号 + if question_key.startswith('Q'): + q_num = question_key[1:] + # 匹配 A{n}: 或 A{n}:格式 + pattern = rf'A{q_num}\s*[::]\s*(.+?)$' + for line in lines: + match = re.search(pattern, line.strip()) + if match: + answer = match.group(1).strip() + if answer and answer != '未提及' and answer != '用户未作答': + return answer + + # 关键词匹配模式 + for line in lines: + if question_key in line: + # 提取 A: 后面的部分 + match = re.search(r'A\d*\s*[::]\s*(.+?)$', line.strip()) + if match: + answer = match.group(1).strip() + if answer and answer != '未提及' and answer != '用户未作答': + return answer + + return "" + + async def save_record(self, record_data: Dict[str, Any]) -> FeedbackRecord: + """保存反馈记录(H5 前端直接调用) + + 支持 upsert 逻辑: + - 如果传了 session_id 且已有该 session 的记录,则更新(补全 AI 处理结果) + - 否则创建新记录 + """ + # 尝试通过 session_id 查找已有记录 + existing = None + session_id = record_data.get("session_id") + if session_id: + existing = await self.record_repo.get_by_session_id(session_id) + + if existing: + # 更新已有记录(仅覆盖非空字段) + if record_data.get("raw_asr_text"): + existing.raw_asr_text = record_data["raw_asr_text"] + if record_data.get("cleaned_text"): + existing.cleaned_text = record_data["cleaned_text"] + if record_data.get("qa_json"): + existing.qa_json = record_data["qa_json"] + if record_data.get("review_long"): + existing.review_long = record_data["review_long"] + if record_data.get("review_short"): + existing.review_short = record_data["review_short"] + if record_data.get("satisfaction"): + existing.satisfaction = record_data["satisfaction"] + if record_data.get("customer_name"): + existing.customer_name = record_data["customer_name"].strip() + if record_data.get("phone_tail"): + existing.phone_tail = self._normalize_phone_tail(record_data["phone_tail"]) + return await self.record_repo.save(existing) + else: + # 创建新记录 + record = FeedbackRecord( + id=generate_id(), + store_id=record_data.get("store_id", ""), + session_id=session_id, + employee_id=record_data.get("employee_id"), + device_mac=record_data.get("device_mac"), + raw_asr_text=record_data.get("raw_asr_text"), + cleaned_text=record_data.get("cleaned_text"), + qa_json=record_data.get("qa_json"), + review_long=record_data.get("review_long"), + review_short=record_data.get("review_short"), + satisfaction=record_data.get("satisfaction"), + customer_name=(record_data.get("customer_name") or "").strip() or None, + phone_tail=self._normalize_phone_tail(record_data.get("phone_tail")), + ) + return await self.record_repo.save(record) + + async def list_records(self, page: int = 1, page_size: int = 20, **filters) -> dict: + """查询反馈记录""" + return await self.record_repo.list_page(page, page_size, **filters) diff --git a/main/feedback-backend/app/application/stats_service.py b/main/feedback-backend/app/application/stats_service.py new file mode 100644 index 000000000..a2643f6f2 --- /dev/null +++ b/main/feedback-backend/app/application/stats_service.py @@ -0,0 +1,184 @@ +"""统计分析应用服务 - 后台管理统计用例""" + +from typing import Dict, List, Optional + +from sqlalchemy import func +from sqlalchemy.orm import Session + +from app.infrastructure.persistence.models import EmployeeModel, FeedbackRecordModel +from app.infrastructure.persistence.feedback_repo_impl import FeedbackRecordRepositoryImpl +from app.infrastructure.persistence.store_repo_impl import StoreRepositoryImpl +from app.infrastructure.persistence.employee_repo_impl import EmployeeRepositoryImpl + + +class StatsService: + """统计分析应用服务""" + + def __init__(self, session: Session): + self.session = session + self.record_repo = FeedbackRecordRepositoryImpl(session) + self.store_repo = StoreRepositoryImpl(session) + self.employee_repo = EmployeeRepositoryImpl(session) + + async def get_overview(self, store_id: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> Dict: + """获取统计概览""" + # 满意度分布 + satisfaction_stats = await self.record_repo.count_by_satisfaction( + store_id, start_date, end_date + ) + + # 总记录数 + total = sum(satisfaction_stats.values()) + + # 满意率 + positive = satisfaction_stats.get("very_satisfied", 0) + satisfaction_stats.get("satisfied", 0) + satisfaction_rate = round(positive / total * 100, 1) if total > 0 else 0 + + return { + "total_records": total, + "satisfaction_distribution": satisfaction_stats, + "satisfaction_rate": satisfaction_rate, + "very_satisfied": satisfaction_stats.get("very_satisfied", 0), + "satisfied": satisfaction_stats.get("satisfied", 0), + "unsatisfied": satisfaction_stats.get("unsatisfied", 0), + "very_bad": satisfaction_stats.get("very_bad", 0), + } + + async def get_daily_stats(self, store_id: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> List[Dict]: + """获取按天统计""" + return await self.record_repo.get_daily_stats(store_id, start_date, end_date) + + async def get_employee_kpi(self, store_id: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> List[Dict]: + """按员工统计好/中/差评,用于店长 KPI。""" + query = self.session.query( + FeedbackRecordModel.employee_id, + EmployeeModel.name.label("employee_name"), + EmployeeModel.number.label("employee_number"), + FeedbackRecordModel.satisfaction, + func.count(FeedbackRecordModel.id).label("count"), + ).outerjoin(EmployeeModel, FeedbackRecordModel.employee_id == EmployeeModel.id) + if store_id: + query = query.filter(FeedbackRecordModel.store_id == store_id) + if start_date: + query = query.filter(FeedbackRecordModel.create_date >= start_date) + if end_date: + query = query.filter(FeedbackRecordModel.create_date <= end_date) + rows = query.group_by( + FeedbackRecordModel.employee_id, + EmployeeModel.name, + EmployeeModel.number, + FeedbackRecordModel.satisfaction, + ).all() + + grouped = {} + for row in rows: + key = row.employee_id or "unknown" + item = grouped.setdefault(key, { + "employeeId": row.employee_id, + "employeeName": row.employee_name or "未绑定员工", + "employeeNumber": row.employee_number, + "good": 0, + "middle": 0, + "bad": 0, + "verySatisfied": 0, + "satisfied": 0, + "unsatisfied": 0, + "veryBad": 0, + "total": 0, + "goodRate": 0, + }) + count = row.count or 0 + sat = row.satisfaction + item["total"] += count + if sat == "very_satisfied": + item["verySatisfied"] += count + item["good"] += count + elif sat == "satisfied": + item["satisfied"] += count + item["good"] += count + elif sat == "unsatisfied": + item["unsatisfied"] += count + item["middle"] += count + elif sat == "very_bad": + item["veryBad"] += count + item["bad"] += count + result = list(grouped.values()) + for item in result: + item["goodRate"] = round(item["good"] / item["total"] * 100, 1) if item["total"] else 0 + return sorted(result, key=lambda x: (x["goodRate"], x["good"], -x["bad"]), reverse=True) + + async def get_employee_records(self, employee_id: str, store_id: Optional[str] = None, + satisfaction_group: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None, + page: int = 1, page_size: int = 20) -> Dict: + """查询某员工完整评价列表。""" + query = self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.employee_id == employee_id) + if store_id: + query = query.filter(FeedbackRecordModel.store_id == store_id) + if start_date: + query = query.filter(FeedbackRecordModel.create_date >= start_date) + if end_date: + query = query.filter(FeedbackRecordModel.create_date <= end_date) + if satisfaction_group == "good": + query = query.filter(FeedbackRecordModel.satisfaction.in_(["very_satisfied", "satisfied"])) + elif satisfaction_group == "middle": + query = query.filter(FeedbackRecordModel.satisfaction == "unsatisfied") + elif satisfaction_group == "bad": + query = query.filter(FeedbackRecordModel.satisfaction == "very_bad") + total = query.count() + rows = query.order_by(FeedbackRecordModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + return { + "list": [{ + "id": r.id, + "employeeId": r.employee_id, + "storeId": r.store_id, + "satisfaction": r.satisfaction, + "reviewLong": r.review_long, + "reviewShort": r.review_short, + "cleanedText": r.cleaned_text, + "rawAsrText": r.raw_asr_text, + "qaJson": r.qa_json, + "memberId": r.member_id, + "visitId": r.visit_id, + "createDate": str(r.create_date) if r.create_date else None, + } for r in rows], + "total": total, + "page": page, + "page_size": page_size, + } + + async def get_single_store_stats(self, store_id: str, start_date: Optional[str] = None, + end_date: Optional[str] = None) -> List[Dict]: + """获取单门店统计""" + store = await self.store_repo.get_by_id(store_id) + if not store: + return [] + count = await self.record_repo.count_by_store(store.id, start_date, end_date) + satisfaction = await self.record_repo.count_by_satisfaction(store.id, start_date, end_date) + total = sum(satisfaction.values()) + positive = satisfaction.get("very_satisfied", 0) + satisfaction.get("satisfied", 0) + rate = round(positive / total * 100, 1) if total > 0 else 0 + return [{ + "store_id": store.id, + "store_name": store.store_name, + "store_code": store.store_code, + "total_records": count, + "satisfaction_rate": rate, + "satisfaction_distribution": satisfaction, + }] + + async def get_store_stats(self, start_date: Optional[str] = None, + end_date: Optional[str] = None) -> List[Dict]: + """获取按门店统计""" + stores = await self.store_repo.list_all(status=1) + result = [] + for store in stores: + result.extend(await self.get_single_store_stats(store.id, start_date, end_date)) + return result diff --git a/main/feedback-backend/app/application/store_service.py b/main/feedback-backend/app/application/store_service.py new file mode 100644 index 000000000..25de50563 --- /dev/null +++ b/main/feedback-backend/app/application/store_service.py @@ -0,0 +1,114 @@ +"""门店应用服务 - 门店 CRUD 用例""" + +from typing import Optional + +from loguru import logger +from sqlalchemy.orm import Session + +from app.domain.store.entity import Store +from app.domain.store.value_objects import StoreCode +from app.infrastructure.persistence.store_repo_impl import StoreRepositoryImpl +from app.shared.exceptions import StoreNotFoundError, ValidationError +from app.shared.utils import generate_id, is_valid_store_code + + +class StoreService: + """门店应用服务""" + + def __init__(self, session: Session): + self.repo = StoreRepositoryImpl(session) + self.session = session + + async def get_by_store_code(self, store_code: str) -> Store: + """根据门店编码获取门店(公开接口用)""" + if not is_valid_store_code(store_code): + raise ValidationError(f"门店编码格式错误: {store_code},应为6位数字") + + store = await self.repo.get_by_store_code(store_code) + if not store: + raise StoreNotFoundError(store_code) + if not store.is_enabled(): + raise StoreNotFoundError(store_code) + return store + + async def get_by_id(self, store_id: str) -> Store: + """根据 ID 获取门店""" + store = await self.repo.get_by_id(store_id) + if not store: + raise StoreNotFoundError(store_id) + return store + + async def list_page(self, page: int = 1, page_size: int = 20, + store_name: Optional[str] = None, + status: Optional[int] = None) -> dict: + """分页查询门店""" + return await self.repo.list_page(page, page_size, store_name, status) + + async def list_all(self, status: Optional[int] = None) -> list: + """获取所有门店""" + return await self.repo.list_all(status) + + async def create_store(self, store_code: str, store_name: str, + manager: Optional[str] = None, + shareholders: Optional[str] = None, + agent_id: Optional[str] = None) -> Store: + """创建门店""" + # 验证门店编码 + if not is_valid_store_code(store_code): + raise ValidationError(f"门店编码格式错误: {store_code},应为6位数字") + + # 检查编码唯一性 + if await self.repo.exists_by_store_code(store_code): + raise ValidationError(f"门店编码已存在: {store_code}") + + store = Store( + id=generate_id(), + store_code=store_code, + store_name=store_name, + manager=manager, + shareholders=shareholders, + agent_id=agent_id, + ) + result = await self.repo.save(store) + logger.info(f"创建门店: code={store_code}, name={store_name}") + return result + + async def update_store(self, store_id: str, **kwargs) -> Store: + """更新门店""" + store = await self.repo.get_by_id(store_id) + if not store: + raise StoreNotFoundError(store_id) + + # 如果修改了 store_code,检查唯一性 + if "store_code" in kwargs and kwargs["store_code"] != store.store_code: + if not is_valid_store_code(kwargs["store_code"]): + raise ValidationError(f"门店编码格式错误: {kwargs['store_code']}") + if await self.repo.exists_by_store_code(kwargs["store_code"], exclude_id=store_id): + raise ValidationError(f"门店编码已存在: {kwargs['store_code']}") + + for key, value in kwargs.items(): + if hasattr(store, key) and value is not None: + setattr(store, key, value) + + result = await self.repo.save(store) + logger.info(f"更新门店: id={store_id}") + return result + + async def delete_store(self, store_id: str) -> bool: + """删除门店""" + store = await self.repo.get_by_id(store_id) + if not store: + raise StoreNotFoundError(store_id) + result = await self.repo.delete(store_id) + logger.info(f"删除门店: id={store_id}") + return result + + async def bind_agent(self, store_id: str, agent_id: str) -> Store: + """绑定智能体""" + store = await self.repo.get_by_id(store_id) + if not store: + raise StoreNotFoundError(store_id) + store.bind_agent(agent_id) + result = await self.repo.save(store) + logger.info(f"门店绑定智能体: store={store_id}, agent={agent_id}") + return result diff --git a/main/feedback-backend/app/domain/__init__.py b/main/feedback-backend/app/domain/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/domain/agent/__init__.py b/main/feedback-backend/app/domain/agent/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/domain/agent/entity.py b/main/feedback-backend/app/domain/agent/entity.py new file mode 100644 index 000000000..cddf18f91 --- /dev/null +++ b/main/feedback-backend/app/domain/agent/entity.py @@ -0,0 +1,51 @@ +"""智能体配置领域实体""" + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any, Dict, List, Optional + + +@dataclass +class AgentConfig: + """智能体配置实体 - 管理对话轮次、提示词、LLM 等可配置项""" + id: str + agent_name: str + agent_id: Optional[str] = None # 对应 xiaozhi-server 的智能体 ID + dialogue_rounds: int = 7 # 对话轮次(问几个问题) + questions: Optional[List[str]] = None # 问题列表 + prompts_config: Optional[Dict[str, Any]] = None # 提示词配置 + llm_config: Optional[Dict[str, Any]] = None # LLM 配置 + review_config: Optional[Dict[str, Any]] = None # 点评生成规则 + status: int = 1 + create_date: Optional[datetime] = None + update_date: Optional[datetime] = None + + def is_enabled(self) -> bool: + return self.status == 1 + + def get_questions(self) -> List[str]: + """获取问题列表,如果没有自定义则返回空列表""" + return self.questions or [] + + def get_prompt_path(self, prompt_type: str) -> Optional[str]: + """获取指定类型的提示词模板路径""" + if self.prompts_config and prompt_type in self.prompts_config: + return self.prompts_config[prompt_type] + return None + + def get_llm_provider(self) -> Optional[str]: + """获取 LLM 提供商""" + if self.llm_config: + return self.llm_config.get("provider") + return None + + def get_review_length(self, review_type: str) -> dict: + """获取点评长度限制""" + if self.review_config and review_type in self.review_config: + return self.review_config[review_type] + # 默认长度 + defaults = { + "long": {"min": 80, "max": 150}, + "short": {"min": 30, "max": 60}, + } + return defaults.get(review_type, {}) diff --git a/main/feedback-backend/app/domain/agent/repository.py b/main/feedback-backend/app/domain/agent/repository.py new file mode 100644 index 000000000..2d4344b76 --- /dev/null +++ b/main/feedback-backend/app/domain/agent/repository.py @@ -0,0 +1,34 @@ +"""智能体配置仓储接口""" + +from abc import ABC, abstractmethod +from typing import List, Optional + +from .entity import AgentConfig + + +class IAgentConfigRepository(ABC): + """智能体配置仓储接口""" + + @abstractmethod + async def get_by_id(self, config_id: str) -> Optional[AgentConfig]: + ... + + @abstractmethod + async def get_by_agent_id(self, agent_id: str) -> Optional[AgentConfig]: + ... + + @abstractmethod + async def list_all(self, status: Optional[int] = None) -> List[AgentConfig]: + ... + + @abstractmethod + async def list_page(self, page: int = 1, page_size: int = 20) -> dict: + ... + + @abstractmethod + async def save(self, config: AgentConfig) -> AgentConfig: + ... + + @abstractmethod + async def delete(self, config_id: str) -> bool: + ... diff --git a/main/feedback-backend/app/domain/agent/value_objects.py b/main/feedback-backend/app/domain/agent/value_objects.py new file mode 100644 index 000000000..60600de9d --- /dev/null +++ b/main/feedback-backend/app/domain/agent/value_objects.py @@ -0,0 +1,33 @@ +"""智能体配置值对象""" + +from dataclasses import dataclass +from typing import List, Optional + + +@dataclass(frozen=True) +class DialogueConfig: + """对话配置值对象""" + rounds: int = 7 + questions: Optional[tuple] = None # 使用 tuple 保证不可变 + + def __post_init__(self): + if self.rounds < 1 or self.rounds > 20: + raise ValueError(f"对话轮次必须在 1-20 之间,当前值: {self.rounds}") + + def get_questions(self) -> List[str]: + """获取前 N 个问题""" + if not self.questions: + return [] + return list(self.questions[:self.rounds]) + + +@dataclass(frozen=True) +class LLMProviderConfig: + """LLM 提供商配置值对象""" + provider: str + api_key: str + base_url: Optional[str] = None + model: Optional[str] = None + + def is_valid(self) -> bool: + return bool(self.provider and self.api_key) diff --git a/main/feedback-backend/app/domain/employee/__init__.py b/main/feedback-backend/app/domain/employee/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/domain/employee/entity.py b/main/feedback-backend/app/domain/employee/entity.py new file mode 100644 index 000000000..4ec8bcdac --- /dev/null +++ b/main/feedback-backend/app/domain/employee/entity.py @@ -0,0 +1,36 @@ +"""员工领域实体""" + +from dataclasses import dataclass +from datetime import datetime +from typing import Optional + + +@dataclass +class Employee: + """员工实体""" + id: str + name: str + number: int # 工号(门店内编号) + store_id: str + employee_type: str = "normal" # manager/excellent/intern/normal + status: int = 1 # 0=禁用 1=启用 + create_date: Optional[datetime] = None + update_date: Optional[datetime] = None + + def is_enabled(self) -> bool: + return self.status == 1 + + def is_manager(self) -> bool: + return self.employee_type == "manager" + + def disable(self): + self.status = 0 + self.update_date = datetime.now() + + def enable(self): + self.status = 1 + self.update_date = datetime.now() + + @staticmethod + def valid_employee_types() -> list: + return ["manager", "excellent", "intern", "normal"] diff --git a/main/feedback-backend/app/domain/employee/repository.py b/main/feedback-backend/app/domain/employee/repository.py new file mode 100644 index 000000000..e9a0f75f6 --- /dev/null +++ b/main/feedback-backend/app/domain/employee/repository.py @@ -0,0 +1,38 @@ +"""员工仓储接口""" + +from abc import ABC, abstractmethod +from typing import List, Optional + +from .entity import Employee + + +class IEmployeeRepository(ABC): + """员工仓储接口""" + + @abstractmethod + async def get_by_id(self, employee_id: str) -> Optional[Employee]: + ... + + @abstractmethod + async def list_by_store_id(self, store_id: str, status: Optional[int] = None) -> List[Employee]: + ... + + @abstractmethod + async def list_page(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, + name: Optional[str] = None, + status: Optional[int] = None) -> dict: + ... + + @abstractmethod + async def save(self, employee: Employee) -> Employee: + ... + + @abstractmethod + async def delete(self, employee_id: str) -> bool: + ... + + @abstractmethod + async def exists_by_store_and_number(self, store_id: str, number: int, + exclude_id: Optional[str] = None) -> bool: + ... diff --git a/main/feedback-backend/app/domain/employee/value_objects.py b/main/feedback-backend/app/domain/employee/value_objects.py new file mode 100644 index 000000000..522b07ce3 --- /dev/null +++ b/main/feedback-backend/app/domain/employee/value_objects.py @@ -0,0 +1,28 @@ +"""员工值对象""" + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class EmployeeType: + """员工类型值对象""" + value: str + + VALID_TYPES = {"manager", "excellent", "intern", "normal"} + + def __post_init__(self): + if self.value not in self.VALID_TYPES: + raise ValueError(f"无效的员工类型: {self.value},有效值: {self.VALID_TYPES}") + + def __str__(self) -> str: + return self.value + + @property + def display_name(self) -> str: + names = { + "manager": "店长", + "excellent": "优秀员工", + "intern": "实习生", + "normal": "普通员工", + } + return names.get(self.value, self.value) diff --git a/main/feedback-backend/app/domain/feedback/__init__.py b/main/feedback-backend/app/domain/feedback/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/domain/feedback/entity.py b/main/feedback-backend/app/domain/feedback/entity.py new file mode 100644 index 000000000..0de50207d --- /dev/null +++ b/main/feedback-backend/app/domain/feedback/entity.py @@ -0,0 +1,47 @@ +"""反馈记录领域实体""" + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Optional + + +@dataclass +class FeedbackRecord: + """反馈记录实体 - 核心领域对象""" + id: str + store_id: str + session_id: Optional[str] = None + employee_id: Optional[str] = None + device_mac: Optional[str] = None + raw_asr_text: Optional[str] = None + cleaned_text: Optional[str] = None + qa_json: Optional[str] = None # JSON 格式的 Q&A 结构 + review_long: Optional[str] = None # 标准点评 (80-150字) + review_short: Optional[str] = None # 精简短评 (30-60字) + satisfaction: Optional[str] = None # very_satisfied/satisfied/unsatisfied/very_bad + member_id: Optional[str] = None # 关联客户ID + visit_id: Optional[str] = None # 关联到店记录ID + card_close_id: Optional[str] = None # 关联销卡记录ID + customer_name: Optional[str] = None # 客户称呼/自报姓名 + phone_tail: Optional[str] = None # 手机号后四位 + member_match_status: Optional[str] = None # matched/conflict/not_found + member_match_candidates: Optional[list] = None # 匹配候选客户 + status: int = 1 # 0=无效 1=有效 + create_date: Optional[datetime] = None + update_date: Optional[datetime] = None + + def is_valid(self) -> bool: + return self.status == 1 + + def invalidate(self): + """标记为无效记录""" + self.status = 0 + self.update_date = datetime.now() + + def has_review(self) -> bool: + """是否已生成点评""" + return bool(self.review_long or self.review_short) + + def should_generate_review(self) -> bool: + """是否应生成点评(仅满意时)""" + return self.satisfaction in ("very_satisfied", "satisfied") diff --git a/main/feedback-backend/app/domain/feedback/repository.py b/main/feedback-backend/app/domain/feedback/repository.py new file mode 100644 index 000000000..7f6409c0a --- /dev/null +++ b/main/feedback-backend/app/domain/feedback/repository.py @@ -0,0 +1,50 @@ +"""反馈记录仓储接口""" + +from abc import ABC, abstractmethod +from typing import List, Optional + +from .entity import FeedbackRecord + + +class IFeedbackRecordRepository(ABC): + """反馈记录仓储接口""" + + @abstractmethod + async def get_by_id(self, record_id: str) -> Optional[FeedbackRecord]: + ... + + @abstractmethod + async def get_by_session_id(self, session_id: str) -> Optional[FeedbackRecord]: + ... + + @abstractmethod + async def save(self, record: FeedbackRecord) -> FeedbackRecord: + ... + + @abstractmethod + async def list_page(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, + employee_id: Optional[str] = None, + satisfaction: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None, + status: Optional[int] = None) -> dict: + ... + + @abstractmethod + async def count_by_store(self, store_id: str, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> int: + ... + + @abstractmethod + async def count_by_satisfaction(self, store_id: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> dict: + ... + + @abstractmethod + async def get_daily_stats(self, store_id: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> List[dict]: + ... diff --git a/main/feedback-backend/app/domain/feedback/value_objects.py b/main/feedback-backend/app/domain/feedback/value_objects.py new file mode 100644 index 000000000..bb7eb5178 --- /dev/null +++ b/main/feedback-backend/app/domain/feedback/value_objects.py @@ -0,0 +1,54 @@ +"""反馈值对象""" + +from dataclasses import dataclass +from typing import Optional + + +@dataclass(frozen=True) +class Satisfaction: + """满意度值对象""" + level: str # very_satisfied / satisfied / unsatisfied / very_bad + + VALID_LEVELS = {"very_satisfied", "satisfied", "unsatisfied", "very_bad"} + + def __post_init__(self): + if self.level not in self.VALID_LEVELS: + raise ValueError(f"无效的满意度等级: {self.level}") + + @property + def text(self) -> str: + mapping = { + "very_satisfied": "非常满意", + "satisfied": "满意", + "unsatisfied": "不满意", + "very_bad": "很差", + } + return mapping.get(self.level, "未知") + + @property + def score(self) -> int: + mapping = { + "very_satisfied": 4, + "satisfied": 3, + "unsatisfied": 2, + "very_bad": 1, + } + return mapping.get(self.level, 0) + + @property + def is_positive(self) -> bool: + return self.level in ("very_satisfied", "satisfied") + + def __str__(self) -> str: + return self.level + + +@dataclass(frozen=True) +class ReviewContent: + """点评内容值对象""" + long_review: Optional[str] = None # 标准版 + short_review: Optional[str] = None # 精简版 + + @property + def has_content(self) -> bool: + return bool(self.long_review or self.short_review) diff --git a/main/feedback-backend/app/domain/store/__init__.py b/main/feedback-backend/app/domain/store/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/domain/store/entity.py b/main/feedback-backend/app/domain/store/entity.py new file mode 100644 index 000000000..cc3acb2f3 --- /dev/null +++ b/main/feedback-backend/app/domain/store/entity.py @@ -0,0 +1,38 @@ +"""门店领域实体""" + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Optional + + +@dataclass +class Store: + """门店实体 - DDD 领域模型,纯 Python,不依赖任何框架""" + id: str + store_code: str # 6位门店编码,客户扫码用 + store_name: str + manager: Optional[str] = None + shareholders: Optional[str] = None # 逗号分隔 + agent_id: Optional[str] = None # 绑定的智能体 ID + status: int = 1 # 0=禁用 1=启用 + create_date: Optional[datetime] = None + update_date: Optional[datetime] = None + + def is_enabled(self) -> bool: + return self.status == 1 + + def disable(self): + self.status = 0 + self.update_date = datetime.now() + + def enable(self): + self.status = 1 + self.update_date = datetime.now() + + def bind_agent(self, agent_id: str): + self.agent_id = agent_id + self.update_date = datetime.now() + + def unbind_agent(self): + self.agent_id = None + self.update_date = datetime.now() diff --git a/main/feedback-backend/app/domain/store/repository.py b/main/feedback-backend/app/domain/store/repository.py new file mode 100644 index 000000000..fff08695e --- /dev/null +++ b/main/feedback-backend/app/domain/store/repository.py @@ -0,0 +1,47 @@ +"""门店仓储接口 - 领域层只定义接口,实现在基础设施层""" + +from abc import ABC, abstractmethod +from typing import List, Optional + +from .entity import Store + + +class IStoreRepository(ABC): + """门店仓储接口""" + + @abstractmethod + async def get_by_id(self, store_id: str) -> Optional[Store]: + """根据 ID 获取门店""" + ... + + @abstractmethod + async def get_by_store_code(self, store_code: str) -> Optional[Store]: + """根据门店编码获取门店""" + ... + + @abstractmethod + async def list_all(self, status: Optional[int] = None) -> List[Store]: + """获取门店列表""" + ... + + @abstractmethod + async def list_page(self, page: int = 1, page_size: int = 20, + store_name: Optional[str] = None, + status: Optional[int] = None) -> dict: + """分页获取门店列表""" + ... + + @abstractmethod + async def save(self, store: Store) -> Store: + """保存门店(新增或更新)""" + ... + + @abstractmethod + async def delete(self, store_id: str) -> bool: + """删除门店""" + ... + + @abstractmethod + async def exists_by_store_code(self, store_code: str, exclude_id: Optional[str] = None) -> bool: + """门店编码是否已存在""" + ... diff --git a/main/feedback-backend/app/domain/store/value_objects.py b/main/feedback-backend/app/domain/store/value_objects.py new file mode 100644 index 000000000..6c5a11203 --- /dev/null +++ b/main/feedback-backend/app/domain/store/value_objects.py @@ -0,0 +1,26 @@ +"""门店值对象""" + +from dataclasses import dataclass +from typing import Optional + + +@dataclass(frozen=True) +class StoreCode: + """门店编码值对象 - 6位数字,不可变""" + value: str + + def __post_init__(self): + if not self.value or not self.value.isdigit() or len(self.value) != 6: + raise ValueError(f"门店编码必须为6位数字,当前值: {self.value}") + + def __str__(self) -> str: + return self.value + + +@dataclass(frozen=True) +class StoreInfo: + """门店基本信息值对象""" + store_code: str + store_name: str + manager: Optional[str] = None + shareholders: Optional[str] = None diff --git a/main/feedback-backend/app/infrastructure/__init__.py b/main/feedback-backend/app/infrastructure/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/infrastructure/llm/__init__.py b/main/feedback-backend/app/infrastructure/llm/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/infrastructure/llm/llm_service.py b/main/feedback-backend/app/infrastructure/llm/llm_service.py new file mode 100644 index 000000000..eeb7af409 --- /dev/null +++ b/main/feedback-backend/app/infrastructure/llm/llm_service.py @@ -0,0 +1,135 @@ +"""LLM 调用服务 - 封装 OpenAI SDK,支持多提供商""" + +import json +from typing import Any, Dict, Optional + +from loguru import logger +from openai import OpenAI + +from app.shared.config import settings +from app.shared.exceptions import LLMProcessingError + + +class LLMService: + """LLM 调用服务""" + + def __init__(self, provider: Optional[str] = None, llm_config: Optional[Dict] = None): + """ + 初始化 LLM 服务 + + Args: + provider: 提供商名称 (openai/dashscope/deepseek) + llm_config: 自定义 LLM 配置(覆盖全局配置) + """ + self.provider = provider or settings.get("llm.provider", "openai") + self.llm_config = llm_config or {} + self._client: Optional[OpenAI] = None + + @property + def client(self) -> OpenAI: + """懒加载 OpenAI 客户端(兼容 OpenAI API 协议的所有提供商)""" + if self._client is None: + config = self._resolve_config() + self._client = OpenAI( + api_key=config["api_key"], + base_url=config.get("base_url"), + ) + return self._client + + def _resolve_config(self) -> Dict[str, Any]: + """解析 LLM 配置:自定义配置 > 全局配置""" + # 优先使用自定义配置 + if self.llm_config: + return { + "api_key": self.llm_config.get("api_key", ""), + "base_url": self.llm_config.get("base_url"), + "model": self.llm_config.get("model"), + } + + # 回退到全局配置 + provider_config = settings.get(f"llm.{self.provider}", {}) + return { + "api_key": provider_config.get("api_key", ""), + "base_url": provider_config.get("base_url"), + "model": provider_config.get("model"), + } + + @property + def model(self) -> str: + """获取模型名称""" + config = self._resolve_config() + return config.get("model", "gpt-4o-mini") + + async def chat(self, system_prompt: str, user_message: str, + temperature: float = 0.3, max_tokens: int = 2000) -> str: + """ + 单轮对话 + + Args: + system_prompt: 系统提示词 + user_message: 用户消息 + temperature: 温度 + max_tokens: 最大 token 数 + + Returns: + 模型回复文本 + """ + try: + logger.info(f"LLM 调用: provider={self.provider}, model={self.model}") + response = self.client.chat.completions.create( + model=self.model, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_message}, + ], + temperature=temperature, + max_tokens=max_tokens, + ) + result = response.choices[0].message.content.strip() + logger.info(f"LLM 响应长度: {len(result)} 字符") + return result + except Exception as e: + logger.error(f"LLM 调用失败: {e}") + raise LLMProcessingError(str(e)) + + async def chat_json(self, system_prompt: str, user_message: str, + temperature: float = 0.1) -> Dict[str, Any]: + """ + 单轮对话,期望返回 JSON 格式 + + Args: + system_prompt: 系统提示词 + user_message: 用户消息 + temperature: 温度(默认更低以获得更稳定的 JSON 输出) + + Returns: + 解析后的 JSON 字典 + """ + text = await self.chat(system_prompt, user_message, temperature=temperature) + + # 尝试提取 JSON + try: + # 尝试直接解析 + return json.loads(text) + except json.JSONDecodeError: + pass + + # 尝试从 markdown 代码块中提取 + import re + json_match = re.search(r"```(?:json)?\s*(.*?)\s*```", text, re.DOTALL) + if json_match: + try: + return json.loads(json_match.group(1)) + except json.JSONDecodeError: + pass + + # 尝试提取第一个 { ... } 块 + brace_match = re.search(r"\{.*\}", text, re.DOTALL) + if brace_match: + try: + return json.loads(brace_match.group(0)) + except json.JSONDecodeError: + pass + + logger.warning(f"无法从 LLM 响应中提取 JSON,原始文本: {text[:200]}") + raise LLMProcessingError(f"LLM 返回内容无法解析为 JSON") diff --git a/main/feedback-backend/app/infrastructure/persistence/__init__.py b/main/feedback-backend/app/infrastructure/persistence/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/infrastructure/persistence/agent_repo_impl.py b/main/feedback-backend/app/infrastructure/persistence/agent_repo_impl.py new file mode 100644 index 000000000..b303a530b --- /dev/null +++ b/main/feedback-backend/app/infrastructure/persistence/agent_repo_impl.py @@ -0,0 +1,112 @@ +"""智能体配置仓储实现""" + +from datetime import datetime +from typing import List, Optional + +from sqlalchemy.orm import Session + +from app.domain.agent.entity import AgentConfig +from app.domain.agent.repository import IAgentConfigRepository +from app.infrastructure.persistence.models import AgentConfigModel +from app.shared.utils import generate_id + + +class AgentConfigRepositoryImpl(IAgentConfigRepository): + """智能体配置仓储实现""" + + def __init__(self, session: Session): + self.session = session + + @staticmethod + def _to_entity(model: AgentConfigModel) -> AgentConfig: + return AgentConfig( + id=model.id, + agent_name=model.agent_name, + agent_id=model.agent_id, + dialogue_rounds=model.dialogue_rounds, + questions=model.questions, + prompts_config=model.prompts_config, + llm_config=model.llm_config, + review_config=model.review_config, + status=model.status, + create_date=model.create_date, + update_date=model.update_date, + ) + + @staticmethod + def _to_model(entity: AgentConfig) -> AgentConfigModel: + return AgentConfigModel( + id=entity.id, + agent_name=entity.agent_name, + agent_id=entity.agent_id, + dialogue_rounds=entity.dialogue_rounds, + questions=entity.questions, + prompts_config=entity.prompts_config, + llm_config=entity.llm_config, + review_config=entity.review_config, + status=entity.status, + create_date=entity.create_date or datetime.now(), + update_date=entity.update_date or datetime.now(), + ) + + async def get_by_id(self, config_id: str) -> Optional[AgentConfig]: + model = self.session.query(AgentConfigModel).filter(AgentConfigModel.id == config_id).first() + return self._to_entity(model) if model else None + + async def get_by_agent_id(self, agent_id: str) -> Optional[AgentConfig]: + model = self.session.query(AgentConfigModel).filter( + AgentConfigModel.agent_id == agent_id, + AgentConfigModel.status == 1, + ).first() + return self._to_entity(model) if model else None + + async def list_all(self, status: Optional[int] = None) -> List[AgentConfig]: + query = self.session.query(AgentConfigModel) + if status is not None: + query = query.filter(AgentConfigModel.status == status) + models = query.order_by(AgentConfigModel.create_date.desc()).all() + return [self._to_entity(m) for m in models] + + async def list_page(self, page: int = 1, page_size: int = 20) -> dict: + query = self.session.query(AgentConfigModel) + total = query.count() + models = query.order_by(AgentConfigModel.create_date.desc()) \ + .offset((page - 1) * page_size) \ + .limit(page_size) \ + .all() + + return { + "list": [self._to_entity(m) for m in models], + "total": total, + "page": page, + "page_size": page_size, + } + + async def save(self, config: AgentConfig) -> AgentConfig: + existing = self.session.query(AgentConfigModel).filter(AgentConfigModel.id == config.id).first() + if existing: + existing.agent_name = config.agent_name + existing.agent_id = config.agent_id + existing.dialogue_rounds = config.dialogue_rounds + existing.questions = config.questions + existing.prompts_config = config.prompts_config + existing.llm_config = config.llm_config + existing.review_config = config.review_config + existing.status = config.status + existing.update_date = datetime.now() + self.session.commit() + self.session.refresh(existing) + return self._to_entity(existing) + else: + if not config.id: + config.id = generate_id() + model = self._to_model(config) + self.session.add(model) + self.session.commit() + self.session.refresh(model) + return self._to_entity(model) + + async def delete(self, config_id: str) -> bool: + count = self.session.query(AgentConfigModel).filter(AgentConfigModel.id == config_id).delete() + self.session.commit() + return count > 0 diff --git a/main/feedback-backend/app/infrastructure/persistence/database.py b/main/feedback-backend/app/infrastructure/persistence/database.py new file mode 100644 index 000000000..bbda18fe4 --- /dev/null +++ b/main/feedback-backend/app/infrastructure/persistence/database.py @@ -0,0 +1,216 @@ +"""数据库连接管理 - SQLAlchemy 2.0 同步引擎 + +两个数据库: +1. feedback_db - 反馈系统独立数据库 +2. xiaozhi_esp32_server - xiaozhi 主数据库(仅用于注册设备到 ai_device 表) +""" + +from sqlalchemy import create_engine, text +from sqlalchemy.orm import DeclarativeBase, sessionmaker + +from app.shared.config import settings + + +class Base(DeclarativeBase): + """ORM 基类""" + pass + + +# ---- 反馈系统数据库 (feedback_db) ---- +engine = create_engine( + settings.database_url, + pool_size=settings.database.get("pool_size", 10), + max_overflow=settings.database.get("max_overflow", 20), + pool_recycle=settings.database.get("pool_recycle", 3600), + echo=settings.server.get("debug", False), +) + +SessionFactory = sessionmaker(bind=engine, autocommit=False, autoflush=False) + + +def get_session(): + """获取 feedback_db session(FastAPI 依赖注入)""" + session = SessionFactory() + try: + yield session + finally: + session.close() + + +def init_database(): + """初始化 feedback_db 数据库表""" + Base.metadata.create_all(bind=engine) + _ensure_feedback_record_crm_columns() + _ensure_feedback_record_identity_columns() + _ensure_suggestion_columns() + _ensure_member_product_columns() + _ensure_product_columns() + + +def _ensure_product_columns(): + columns = { + "duration_minutes": "ALTER TABLE crm_product ADD COLUMN duration_minutes INT NULL DEFAULT 60 COMMENT '默认服务时长'", + } + try: + with engine.begin() as conn: + existing_columns = {row[0] for row in conn.execute(text("SHOW COLUMNS FROM crm_product"))} + for name, ddl in columns.items(): + if name not in existing_columns: + conn.execute(text(ddl)) + except Exception: + pass + + +def _ensure_member_product_columns(): + """兼容已有库:为 crm_member_product 补齐购买计算字段。""" + columns = { + "unit_price": "ALTER TABLE crm_member_product ADD COLUMN unit_price DECIMAL(12,2) NULL DEFAULT 0 COMMENT '购买时单价'", + "purchase_count": "ALTER TABLE crm_member_product ADD COLUMN purchase_count INT NULL DEFAULT 0 COMMENT '购买数量/次数'", + "discount": "ALTER TABLE crm_member_product ADD COLUMN discount DECIMAL(5,2) NULL DEFAULT 1 COMMENT '折扣系数'", + } + try: + with engine.begin() as conn: + existing_columns = {row[0] for row in conn.execute(text("SHOW COLUMNS FROM crm_member_product"))} + for name, ddl in columns.items(): + if name not in existing_columns: + conn.execute(text(ddl)) + except Exception: + pass + + +def _ensure_suggestion_columns(): + """兼容已有库:为 crm_suggestion 补齐建议管理字段。""" + columns = { + "tags": "ALTER TABLE crm_suggestion ADD COLUMN tags JSON NULL COMMENT '标签'", + "priority": "ALTER TABLE crm_suggestion ADD COLUMN priority VARCHAR(16) NULL DEFAULT 'medium' COMMENT '优先级'", + "source": "ALTER TABLE crm_suggestion ADD COLUMN source VARCHAR(32) NULL DEFAULT 'manual' COMMENT '来源'", + "submitter_name": "ALTER TABLE crm_suggestion ADD COLUMN submitter_name VARCHAR(64) NULL COMMENT '提出人'", + } + try: + with engine.begin() as conn: + existing_columns = {row[0] for row in conn.execute(text("SHOW COLUMNS FROM crm_suggestion"))} + for name, ddl in columns.items(): + if name not in existing_columns: + conn.execute(text(ddl)) + except Exception: + # 表不存在时 create_all 会负责创建;这里只做兼容补列 + pass + + +def _ensure_feedback_record_identity_columns(): + """兼容已有库:为 feedback_record 补齐客户身份辅助字段。""" + columns = { + "customer_name": "ALTER TABLE feedback_record ADD COLUMN customer_name VARCHAR(64) NULL COMMENT '客户称呼/自报姓名'", + "phone_tail": "ALTER TABLE feedback_record ADD COLUMN phone_tail VARCHAR(4) NULL COMMENT '客户手机号后四位'", + "member_match_status": "ALTER TABLE feedback_record ADD COLUMN member_match_status VARCHAR(32) NULL COMMENT '客户匹配状态'", + "member_match_candidates": "ALTER TABLE feedback_record ADD COLUMN member_match_candidates JSON NULL COMMENT '手机号后四位匹配候选客户'", + } + indexes = { + "idx_feedback_record_phone_tail": "ALTER TABLE feedback_record ADD INDEX idx_feedback_record_phone_tail (phone_tail)", + } + try: + with engine.begin() as conn: + existing_columns = {row[0] for row in conn.execute(text("SHOW COLUMNS FROM feedback_record"))} + for name, ddl in columns.items(): + if name not in existing_columns: + conn.execute(text(ddl)) + existing_indexes = {row[2] for row in conn.execute(text("SHOW INDEX FROM feedback_record"))} + for name, ddl in indexes.items(): + if name not in existing_indexes: + conn.execute(text(ddl)) + except Exception: + pass + + +def _ensure_feedback_record_crm_columns(): + """兼容已有库:为 feedback_record 补齐 CRM 关联字段。""" + columns = { + "member_id": "ALTER TABLE feedback_record ADD COLUMN member_id VARCHAR(64) NULL COMMENT '关联客户ID'", + "visit_id": "ALTER TABLE feedback_record ADD COLUMN visit_id VARCHAR(64) NULL COMMENT '关联到店记录ID'", + "card_close_id": "ALTER TABLE feedback_record ADD COLUMN card_close_id VARCHAR(64) NULL COMMENT '关联销卡记录ID'", + } + indexes = { + "idx_feedback_record_member_id": "ALTER TABLE feedback_record ADD INDEX idx_feedback_record_member_id (member_id)", + "idx_feedback_record_visit_id": "ALTER TABLE feedback_record ADD INDEX idx_feedback_record_visit_id (visit_id)", + "idx_feedback_record_card_close_id": "ALTER TABLE feedback_record ADD INDEX idx_feedback_record_card_close_id (card_close_id)", + } + with engine.begin() as conn: + existing_columns = {row[0] for row in conn.execute(text("SHOW COLUMNS FROM feedback_record"))} + for name, ddl in columns.items(): + if name not in existing_columns: + conn.execute(text(ddl)) + existing_indexes = {row[2] for row in conn.execute(text("SHOW INDEX FROM feedback_record"))} + for name, ddl in indexes.items(): + if name not in existing_indexes: + conn.execute(text(ddl)) + + +# ---- xiaozhi 主数据库 (xiaozhi_esp32_server) ---- +def _build_xiaozhi_db_url(): + """构建 xiaozhi 主库连接 URL(同 MySQL 实例,不同 schema)""" + db = settings.database + return ( + f"mysql+pymysql://{db['username']}:{db['password']}" + f"@{db['host']}:{db['port']}/xiaozhi_esp32_server" + f"?charset={db.get('charset', 'utf8mb4')}" + ) + + +_xiaozhi_engine = None + + +def get_xiaozhi_engine(): + """懒加载 xiaozhi 主库引擎""" + global _xiaozhi_engine + if _xiaozhi_engine is None: + _xiaozhi_engine = create_engine( + _build_xiaozhi_db_url(), + pool_size=3, + max_overflow=5, + pool_recycle=3600, + ) + return _xiaozhi_engine + + +def register_device_in_xiaozhi(device_mac: str, agent_id: str, alias: str = "") -> bool: + """在 xiaozhi 的 ai_device 表中注册/更新设备 + + 这样 H5 调用 OTA 时,xiaozhi-server 能识别设备并直接返回 WS URL, + 不需要激活码。 + """ + try: + eng = get_xiaozhi_engine() + with eng.connect() as conn: + # 检查设备是否已存在 + result = conn.execute( + text("SELECT id FROM ai_device WHERE mac_address = :mac"), + {"mac": device_mac} + ) + existing = result.fetchone() + + if existing: + # 更新 agent_id + conn.execute( + text("UPDATE ai_device SET agent_id = :agent_id, alias = :alias WHERE mac_address = :mac"), + {"agent_id": agent_id, "alias": alias or "反馈H5设备", "mac": device_mac} + ) + else: + # 插入新设备 + conn.execute( + text(""" + INSERT INTO ai_device (id, mac_address, agent_id, alias, auto_update, sort, create_date) + VALUES (:id, :mac, :agent_id, :alias, 0, 0, NOW()) + """), + { + "id": device_mac.replace(":", "")[:32], + "mac": device_mac, + "agent_id": agent_id, + "alias": alias or "反馈H5设备", + } + ) + conn.commit() + return True + except Exception as e: + from loguru import logger + logger.warning(f"注册设备到 xiaozhi 主库失败: {e}") + return False diff --git a/main/feedback-backend/app/infrastructure/persistence/employee_repo_impl.py b/main/feedback-backend/app/infrastructure/persistence/employee_repo_impl.py new file mode 100644 index 000000000..350f87f1e --- /dev/null +++ b/main/feedback-backend/app/infrastructure/persistence/employee_repo_impl.py @@ -0,0 +1,116 @@ +"""员工仓储实现""" + +from datetime import datetime +from typing import List, Optional + +from sqlalchemy.orm import Session + +from app.domain.employee.entity import Employee +from app.domain.employee.repository import IEmployeeRepository +from app.infrastructure.persistence.models import EmployeeModel +from app.shared.utils import generate_id + + +class EmployeeRepositoryImpl(IEmployeeRepository): + """员工仓储实现""" + + def __init__(self, session: Session): + self.session = session + + @staticmethod + def _to_entity(model: EmployeeModel) -> Employee: + return Employee( + id=model.id, + name=model.name, + number=model.number, + store_id=model.store_id, + employee_type=model.employee_type, + status=model.status, + create_date=model.create_date, + update_date=model.update_date, + ) + + @staticmethod + def _to_model(entity: Employee) -> EmployeeModel: + return EmployeeModel( + id=entity.id, + name=entity.name, + number=entity.number, + store_id=entity.store_id, + employee_type=entity.employee_type, + status=entity.status, + create_date=entity.create_date or datetime.now(), + update_date=entity.update_date or datetime.now(), + ) + + async def get_by_id(self, employee_id: str) -> Optional[Employee]: + model = self.session.query(EmployeeModel).filter(EmployeeModel.id == employee_id).first() + return self._to_entity(model) if model else None + + async def list_by_store_id(self, store_id: str, status: Optional[int] = None) -> List[Employee]: + query = self.session.query(EmployeeModel).filter(EmployeeModel.store_id == store_id) + if status is not None: + query = query.filter(EmployeeModel.status == status) + models = query.order_by(EmployeeModel.number.asc()).all() + return [self._to_entity(m) for m in models] + + async def list_page(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, + name: Optional[str] = None, + status: Optional[int] = None) -> dict: + query = self.session.query(EmployeeModel) + if store_id: + query = query.filter(EmployeeModel.store_id == store_id) + if name: + query = query.filter(EmployeeModel.name.like(f"%{name}%")) + if status is not None: + query = query.filter(EmployeeModel.status == status) + + total = query.count() + models = query.order_by(EmployeeModel.create_date.desc()) \ + .offset((page - 1) * page_size) \ + .limit(page_size) \ + .all() + + return { + "list": [self._to_entity(m) for m in models], + "total": total, + "page": page, + "page_size": page_size, + } + + async def save(self, employee: Employee) -> Employee: + existing = self.session.query(EmployeeModel).filter(EmployeeModel.id == employee.id).first() + if existing: + existing.name = employee.name + existing.number = employee.number + existing.store_id = employee.store_id + existing.employee_type = employee.employee_type + existing.status = employee.status + existing.update_date = datetime.now() + self.session.commit() + self.session.refresh(existing) + return self._to_entity(existing) + else: + if not employee.id: + employee.id = generate_id() + model = self._to_model(employee) + self.session.add(model) + self.session.commit() + self.session.refresh(model) + return self._to_entity(model) + + async def delete(self, employee_id: str) -> bool: + count = self.session.query(EmployeeModel).filter(EmployeeModel.id == employee_id).delete() + self.session.commit() + return count > 0 + + async def exists_by_store_and_number(self, store_id: str, number: int, + exclude_id: Optional[str] = None) -> bool: + query = self.session.query(EmployeeModel).filter( + EmployeeModel.store_id == store_id, + EmployeeModel.number == number, + ) + if exclude_id: + query = query.filter(EmployeeModel.id != exclude_id) + return query.first() is not None diff --git a/main/feedback-backend/app/infrastructure/persistence/feedback_repo_impl.py b/main/feedback-backend/app/infrastructure/persistence/feedback_repo_impl.py new file mode 100644 index 000000000..9ce3aca53 --- /dev/null +++ b/main/feedback-backend/app/infrastructure/persistence/feedback_repo_impl.py @@ -0,0 +1,197 @@ +"""反馈记录仓储实现""" + +from datetime import datetime +from typing import List, Optional + +from sqlalchemy import func +from sqlalchemy.orm import Session + +from app.domain.feedback.entity import FeedbackRecord +from app.domain.feedback.repository import IFeedbackRecordRepository +from app.infrastructure.persistence.models import FeedbackRecordModel +from app.shared.utils import generate_id + + +class FeedbackRecordRepositoryImpl(IFeedbackRecordRepository): + """反馈记录仓储实现""" + + def __init__(self, session: Session): + self.session = session + + @staticmethod + def _to_entity(model: FeedbackRecordModel) -> FeedbackRecord: + return FeedbackRecord( + id=model.id, + session_id=model.session_id, + store_id=model.store_id, + employee_id=model.employee_id, + device_mac=model.device_mac, + raw_asr_text=model.raw_asr_text, + cleaned_text=model.cleaned_text, + qa_json=model.qa_json if isinstance(model.qa_json, str) else ( + str(model.qa_json) if model.qa_json else None + ), + review_long=model.review_long, + review_short=model.review_short, + satisfaction=model.satisfaction, + member_id=model.member_id, + visit_id=model.visit_id, + card_close_id=model.card_close_id, + customer_name=model.customer_name, + phone_tail=model.phone_tail, + member_match_status=model.member_match_status, + member_match_candidates=model.member_match_candidates, + status=model.status, + create_date=model.create_date, + update_date=model.update_date, + ) + + @staticmethod + def _to_model(entity: FeedbackRecord) -> FeedbackRecordModel: + return FeedbackRecordModel( + id=entity.id, + session_id=entity.session_id, + store_id=entity.store_id, + employee_id=entity.employee_id, + device_mac=entity.device_mac, + raw_asr_text=entity.raw_asr_text, + cleaned_text=entity.cleaned_text, + qa_json=entity.qa_json, + review_long=entity.review_long, + review_short=entity.review_short, + satisfaction=entity.satisfaction, + member_id=entity.member_id, + visit_id=entity.visit_id, + card_close_id=entity.card_close_id, + customer_name=entity.customer_name, + phone_tail=entity.phone_tail, + member_match_status=entity.member_match_status, + member_match_candidates=entity.member_match_candidates, + status=entity.status, + create_date=entity.create_date or datetime.now(), + update_date=entity.update_date or datetime.now(), + ) + + async def get_by_id(self, record_id: str) -> Optional[FeedbackRecord]: + model = self.session.query(FeedbackRecordModel).filter( + FeedbackRecordModel.id == record_id + ).first() + return self._to_entity(model) if model else None + + async def get_by_session_id(self, session_id: str) -> Optional[FeedbackRecord]: + model = self.session.query(FeedbackRecordModel).filter( + FeedbackRecordModel.session_id == session_id + ).first() + return self._to_entity(model) if model else None + + async def save(self, record: FeedbackRecord) -> FeedbackRecord: + existing = self.session.query(FeedbackRecordModel).filter( + FeedbackRecordModel.id == record.id + ).first() + if existing: + for field in ["session_id", "store_id", "employee_id", "device_mac", + "raw_asr_text", "cleaned_text", "qa_json", + "review_long", "review_short", "satisfaction", + "member_id", "visit_id", "card_close_id", + "customer_name", "phone_tail", "member_match_status", "member_match_candidates", "status"]: + setattr(existing, field, getattr(record, field)) + existing.update_date = datetime.now() + self.session.commit() + self.session.refresh(existing) + return self._to_entity(existing) + else: + if not record.id: + record.id = generate_id() + model = self._to_model(record) + self.session.add(model) + self.session.commit() + self.session.refresh(model) + return self._to_entity(model) + + async def list_page(self, page: int = 1, page_size: int = 20, + store_id: Optional[str] = None, + employee_id: Optional[str] = None, + satisfaction: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None, + status: Optional[int] = None) -> dict: + query = self.session.query(FeedbackRecordModel) + + if store_id: + query = query.filter(FeedbackRecordModel.store_id == store_id) + if employee_id: + query = query.filter(FeedbackRecordModel.employee_id == employee_id) + if satisfaction: + query = query.filter(FeedbackRecordModel.satisfaction == satisfaction) + if start_date: + query = query.filter(FeedbackRecordModel.create_date >= start_date) + if end_date: + query = query.filter(FeedbackRecordModel.create_date <= end_date) + if status is not None: + query = query.filter(FeedbackRecordModel.status == status) + + total = query.count() + models = query.order_by(FeedbackRecordModel.create_date.desc()) \ + .offset((page - 1) * page_size) \ + .limit(page_size) \ + .all() + + return { + "list": [self._to_entity(m) for m in models], + "total": total, + "page": page, + "page_size": page_size, + } + + async def count_by_store(self, store_id: str, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> int: + query = self.session.query(func.count(FeedbackRecordModel.id)).filter( + FeedbackRecordModel.store_id == store_id + ) + if start_date: + query = query.filter(FeedbackRecordModel.create_date >= start_date) + if end_date: + query = query.filter(FeedbackRecordModel.create_date <= end_date) + return query.scalar() or 0 + + async def count_by_satisfaction(self, store_id: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> dict: + query = self.session.query( + FeedbackRecordModel.satisfaction, + func.count(FeedbackRecordModel.id) + ).filter(FeedbackRecordModel.satisfaction.isnot(None)) + + if store_id: + query = query.filter(FeedbackRecordModel.store_id == store_id) + if start_date: + query = query.filter(FeedbackRecordModel.create_date >= start_date) + if end_date: + query = query.filter(FeedbackRecordModel.create_date <= end_date) + + query = query.group_by(FeedbackRecordModel.satisfaction) + results = query.all() + + return {row[0]: row[1] for row in results} + + async def get_daily_stats(self, store_id: Optional[str] = None, + start_date: Optional[str] = None, + end_date: Optional[str] = None) -> List[dict]: + """按天统计反馈数量""" + query = self.session.query( + func.date(FeedbackRecordModel.create_date).label("date"), + func.count(FeedbackRecordModel.id).label("count"), + ) + + if store_id: + query = query.filter(FeedbackRecordModel.store_id == store_id) + if start_date: + query = query.filter(FeedbackRecordModel.create_date >= start_date) + if end_date: + query = query.filter(FeedbackRecordModel.create_date <= end_date) + + query = query.group_by(func.date(FeedbackRecordModel.create_date)) \ + .order_by(func.date(FeedbackRecordModel.create_date)) + + return [{"date": str(row.date), "count": row.count} for row in query.all()] diff --git a/main/feedback-backend/app/infrastructure/persistence/models.py b/main/feedback-backend/app/infrastructure/persistence/models.py new file mode 100644 index 000000000..31816bcac --- /dev/null +++ b/main/feedback-backend/app/infrastructure/persistence/models.py @@ -0,0 +1,573 @@ +"""SQLAlchemy ORM 模型 - 映射到 MySQL 表 + +注意:这些是基础设施层的持久化模型,与领域层的 Entity 分离。 +Repository 实现负责在 ORM Model 和 Domain Entity 之间转换。 +""" + +from datetime import datetime + +from sqlalchemy import ( + Column, String, Integer, Text, JSON, SmallInteger, DateTime, Index, ForeignKey, + Date, Numeric +) +from sqlalchemy.orm import relationship + +from .database import Base + + +class StoreModel(Base): + """门店表""" + __tablename__ = "feedback_store" + + id = Column(String(64), primary_key=True) + store_code = Column(String(6), unique=True, nullable=False, comment="6位门店编码") + store_name = Column(String(128), nullable=False, comment="门店名称") + manager = Column(String(64), nullable=True, comment="店长") + shareholders = Column(String(256), nullable=True, comment="股东(逗号分隔)") + agent_id = Column(String(32), nullable=True, comment="绑定的智能体ID") + status = Column(SmallInteger, default=1, comment="0=禁用 1=启用") + creator = Column(Integer, nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(Integer, nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + employees = relationship("EmployeeModel", back_populates="store", lazy="selectin", + primaryjoin="StoreModel.id==EmployeeModel.store_id", + foreign_keys="EmployeeModel.store_id") + + def __repr__(self): + return f"" + + +class EmployeeModel(Base): + """员工表""" + __tablename__ = "feedback_employee" + + id = Column(String(64), primary_key=True) + name = Column(String(64), nullable=False, comment="员工姓名") + number = Column(Integer, nullable=False, comment="工号(门店内)") + store_id = Column(String(64), ForeignKey("feedback_store.id"), nullable=False, index=True, comment="门店ID") + employee_type = Column(String(32), default="normal", comment="manager/excellent/intern/normal") + status = Column(SmallInteger, default=1, comment="0=禁用 1=启用") + creator = Column(Integer, nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(Integer, nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + store = relationship("StoreModel", back_populates="employees", + primaryjoin="EmployeeModel.store_id==StoreModel.id", + foreign_keys="EmployeeModel.store_id") + + __table_args__ = ( + Index("idx_store_number", "store_id", "number"), + ) + + def __repr__(self): + return f"" + + +class FeedbackRecordModel(Base): + """反馈记录表""" + __tablename__ = "feedback_record" + + id = Column(String(64), primary_key=True) + session_id = Column(String(128), nullable=True, index=True, comment="WebSocket会话ID") + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + employee_id = Column(String(64), nullable=True, comment="员工ID") + device_mac = Column(String(32), nullable=True, comment="设备MAC地址") + raw_asr_text = Column(Text, nullable=True, comment="原始ASR文本") + cleaned_text = Column(Text, nullable=True, comment="清洗后文本") + qa_json = Column(JSON, nullable=True, comment="结构化Q&A") + review_long = Column(Text, nullable=True, comment="标准点评(80-150字)") + review_short = Column(Text, nullable=True, comment="精简短评(30-60字)") + satisfaction = Column(String(32), nullable=True, comment="满意度: very_satisfied/satisfied/unsatisfied/very_bad") + member_id = Column(String(64), nullable=True, index=True, comment="关联客户ID") + visit_id = Column(String(64), nullable=True, index=True, comment="关联到店记录ID") + card_close_id = Column(String(64), nullable=True, index=True, comment="关联销卡记录ID") + customer_name = Column(String(64), nullable=True, comment="客户称呼/自报姓名") + phone_tail = Column(String(4), nullable=True, index=True, comment="客户手机号后四位") + member_match_status = Column(String(32), nullable=True, comment="客户匹配状态: matched/conflict/not_found") + member_match_candidates = Column(JSON, nullable=True, comment="手机号后四位匹配候选客户") + status = Column(SmallInteger, default=1, comment="0=无效 1=有效") + creator = Column(Integer, nullable=True) + create_date = Column(DateTime, default=datetime.now, index=True, comment="创建时间") + updater = Column(Integer, nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_store_create", "store_id", "create_date"), + ) + + def __repr__(self): + return f"" + + +class AgentConfigModel(Base): + """智能体配置表""" + __tablename__ = "agent_config" + + id = Column(String(64), primary_key=True) + agent_name = Column(String(128), nullable=False, comment="智能体名称") + agent_id = Column(String(32), nullable=True, comment="对应xiaozhi-server智能体ID") + dialogue_rounds = Column(Integer, default=7, comment="对话轮次") + questions = Column(JSON, nullable=True, comment="问题列表") + prompts_config = Column(JSON, nullable=True, comment="提示词配置") + llm_config = Column(JSON, nullable=True, comment="LLM配置") + review_config = Column(JSON, nullable=True, comment="点评生成规则") + status = Column(SmallInteger, default=1, comment="0=禁用 1=启用") + creator = Column(Integer, nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(Integer, nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + def __repr__(self): + return f"" + + +class CrmMemberModel(Base): + """CRM 客户档案表""" + __tablename__ = "crm_member" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="所属门店ID") + name = Column(String(64), nullable=True, comment="姓名") + phone = Column(String(20), nullable=True, comment="手机号") + gender = Column(SmallInteger, nullable=True, comment="0未知 1男 2女") + birthday = Column(Date, nullable=True, comment="生日") + wechat = Column(String(128), nullable=True, comment="微信号") + source = Column(String(32), default="manual", comment="来源 manual/feedback/import") + level = Column(String(32), nullable=True, comment="客户等级") + tags = Column(JSON, nullable=True, comment="普通客户标签") + mekai_tags = Column(JSON, nullable=True, comment="麦凯66信息") + beauty_concerns = Column(JSON, nullable=True, comment="美容关注点") + health_issues = Column(JSON, nullable=True, comment="身体不适/疾病/禁忌") + allergies = Column(Text, nullable=True, comment="过敏信息") + service_preferences = Column(JSON, nullable=True, comment="服务偏好") + notes = Column(Text, nullable=True, comment="备注") + last_visit_at = Column(DateTime, nullable=True, comment="最近到店时间") + total_visits = Column(Integer, default=0, comment="累计到店次数") + total_spent = Column(Numeric(12, 2), default=0, comment="累计消费金额") + status = Column(SmallInteger, default=1, comment="0=禁用 1=启用 2=流失") + creator = Column(String(64), nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(String(64), nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_crm_member_store_phone", "store_id", "phone"), + Index("idx_crm_member_store_name", "store_id", "name"), + ) + + +class CrmVisitModel(Base): + """CRM 到店记录表""" + __tablename__ = "crm_visit" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + member_id = Column(String(64), nullable=True, index=True, comment="客户ID") + employee_id = Column(String(64), nullable=True, index=True, comment="服务员工ID") + feedback_record_id = Column(String(64), nullable=True, index=True, comment="关联反馈记录ID") + session_id = Column(String(128), nullable=True, comment="WebSocket会话ID") + device_mac = Column(String(32), nullable=True, comment="设备MAC") + visit_type = Column(String(32), default="walk_in", comment="walk_in/appointment") + service_items = Column(JSON, nullable=True, comment="服务项目") + arrive_at = Column(DateTime, nullable=True, comment="到店时间") + leave_at = Column(DateTime, nullable=True, comment="离店时间") + duration_minutes = Column(Integer, nullable=True, comment="耗时分钟") + satisfaction = Column(String(32), nullable=True, comment="满意度") + consumption_amount = Column(Numeric(12, 2), default=0, comment="消费金额") + notes = Column(Text, nullable=True, comment="备注") + status = Column(SmallInteger, default=1, comment="0=无效 1=有效") + creator = Column(String(64), nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(String(64), nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_crm_visit_store_arrive", "store_id", "arrive_at"), + ) + + +class CrmAccountModel(Base): + """CRM 账户/会员卡表""" + __tablename__ = "crm_account" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + member_id = Column(String(64), nullable=False, index=True, comment="客户ID") + account_type = Column(String(32), default="balance", comment="balance/count/course/time/coupon") + card_name = Column(String(128), nullable=True, comment="卡名称") + total_amount = Column(Numeric(12, 2), default=0, comment="总金额") + balance_amount = Column(Numeric(12, 2), default=0, comment="余额") + total_count = Column(Integer, default=0, comment="总次数") + balance_count = Column(Integer, default=0, comment="剩余次数") + valid_start = Column(Date, nullable=True, comment="有效期开始") + valid_end = Column(Date, nullable=True, comment="有效期结束") + status = Column(SmallInteger, default=1, comment="0=已销卡 1=使用中 2=已过期") + closed_reason = Column(String(256), nullable=True, comment="销卡原因") + closed_at = Column(DateTime, nullable=True, comment="销卡时间") + notes = Column(Text, nullable=True, comment="备注") + creator = Column(String(64), nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(String(64), nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_crm_account_store_status", "store_id", "status"), + ) + + +class CrmAccountTransactionModel(Base): + """CRM 账户流水表""" + __tablename__ = "crm_account_transaction" + + id = Column(String(64), primary_key=True) + account_id = Column(String(64), nullable=False, index=True, comment="账户ID") + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + member_id = Column(String(64), nullable=False, index=True, comment="客户ID") + transaction_type = Column(String(32), nullable=False, comment="recharge/consume/refund/close/adjust") + amount = Column(Numeric(12, 2), default=0, comment="金额变动") + count_change = Column(Integer, default=0, comment="次数变动") + balance_before = Column(Numeric(12, 2), default=0, comment="变动前余额") + balance_after = Column(Numeric(12, 2), default=0, comment="变动后余额") + related_visit_id = Column(String(64), nullable=True, comment="关联到店记录ID") + notes = Column(String(256), nullable=True, comment="备注") + operator = Column(String(64), nullable=True, comment="操作人") + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + + __table_args__ = ( + Index("idx_crm_tx_store_date", "store_id", "create_date"), + ) + + +class CrmCardCloseModel(Base): + """CRM 销卡记录表""" + __tablename__ = "crm_card_close" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + member_id = Column(String(64), nullable=False, index=True, comment="客户ID") + account_id = Column(String(64), nullable=False, index=True, comment="账户ID") + feedback_record_id = Column(String(64), nullable=True, index=True, comment="关联反馈记录ID") + close_type = Column(String(32), default="refund", comment="refund/transfer/close_only") + reason = Column(String(256), nullable=True, comment="销卡原因") + refund_amount = Column(Numeric(12, 2), default=0, comment="退款金额") + remaining_count = Column(Integer, default=0, comment="剩余次数") + status = Column(String(32), default="pending", comment="pending/processing/done/rejected") + handled_by = Column(String(64), nullable=True, comment="处理人") + approved_by = Column(String(64), nullable=True, comment="审批人") + handle_notes = Column(Text, nullable=True, comment="处理说明") + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + +class CrmSuggestionModel(Base): + """CRM 客户建议表""" + __tablename__ = "crm_suggestion" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + feedback_record_id = Column(String(64), nullable=True, index=True, comment="关联反馈记录ID") + member_id = Column(String(64), nullable=True, index=True, comment="客户ID") + content = Column(Text, nullable=False, comment="建议内容") + content_hash = Column(String(64), nullable=False, index=True, comment="内容哈希") + category = Column(String(32), nullable=True, comment="分类") + tags = Column(JSON, nullable=True, comment="标签") + priority = Column(String(16), default="medium", comment="low/medium/high/urgent") + source = Column(String(32), default="manual", comment="feedback/manual/card_close/agent") + submitter_name = Column(String(64), nullable=True, comment="提出人") + duplicate_group_id = Column(String(64), nullable=True, index=True, comment="去重组ID") + frequency = Column(Integer, default=1, comment="出现次数") + status = Column(String(32), default="pending", comment="pending/adopting/adopted/ignored/duplicate") + adopted_at = Column(DateTime, nullable=True, comment="采纳时间") + rejected_reason = Column(String(256), nullable=True, comment="拒绝原因") + handled_by = Column(String(64), nullable=True, comment="处理人") + handle_notes = Column(Text, nullable=True, comment="处理备注") + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_crm_suggestion_store_status", "store_id", "status"), + ) + + +class CrmIssueModel(Base): + """CRM 问题修复表""" + __tablename__ = "crm_issue" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + feedback_record_id = Column(String(64), nullable=True, index=True, comment="关联反馈记录ID") + member_id = Column(String(64), nullable=True, index=True, comment="客户ID") + card_close_id = Column(String(64), nullable=True, index=True, comment="关联销卡记录ID") + title = Column(String(256), nullable=False, comment="问题标题") + description = Column(Text, nullable=True, comment="问题描述") + severity = Column(String(16), default="medium", comment="low/medium/high/critical") + category = Column(String(32), nullable=True, comment="分类") + status = Column(String(32), default="identified", comment="identified/fixing/fixed/closed") + identified_at = Column(DateTime, default=datetime.now, comment="识别时间") + fix_plan = Column(Text, nullable=True, comment="修复方案") + fix_deadline = Column(DateTime, nullable=True, comment="修复截止时间") + fixed_at = Column(DateTime, nullable=True, comment="修复完成时间") + fix_result = Column(Text, nullable=True, comment="修复结果") + assigned_to = Column(String(64), nullable=True, comment="负责人") + closed_at = Column(DateTime, nullable=True, comment="关闭时间") + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_crm_issue_store_status", "store_id", "status"), + ) + + +class CrmBodyStatusModel(Base): + """客户身体变化状态记录""" + __tablename__ = "crm_body_status" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + member_id = Column(String(64), nullable=False, index=True, comment="客户ID") + visit_id = Column(String(64), nullable=True, index=True, comment="关联到店记录ID") + member_product_id = Column(String(64), nullable=True, index=True, comment="关联客户套餐ID") + record_date = Column(DateTime, default=datetime.now, comment="记录时间") + weight = Column(Numeric(8, 2), nullable=True, comment="体重kg") + waistline = Column(Numeric(8, 2), nullable=True, comment="腰围cm") + pain_level = Column(Integer, nullable=True, comment="疼痛/不适程度 0-10") + sleep_quality = Column(Integer, nullable=True, comment="睡眠质量 0-10") + skin_status = Column(String(128), nullable=True, comment="皮肤状态") + body_parts = Column(JSON, nullable=True, comment="身体部位状态") + metrics = Column(JSON, nullable=True, comment="其他指标") + notes = Column(Text, nullable=True, comment="备注") + creator = Column(String(64), nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(String(64), nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_crm_body_status_member_date", "member_id", "record_date"), + Index("idx_crm_body_status_store_date", "store_id", "record_date"), + ) + + +class CrmProductModel(Base): + """CRM 产品/项目表""" + __tablename__ = "crm_product" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + product_name = Column(String(128), nullable=False, comment="产品/项目名称") + product_type = Column(String(32), default="service", comment="service/package/product") + category = Column(String(64), nullable=True, comment="分类,如养生/减肥/美容") + price = Column(Numeric(12, 2), default=0, comment="单价") + default_count = Column(Integer, default=1, comment="默认次数") + duration_minutes = Column(Integer, default=60, comment="默认服务时长") + description = Column(Text, nullable=True, comment="说明") + status = Column(SmallInteger, default=1, comment="0=下架 1=启用") + creator = Column(String(64), nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(String(64), nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_crm_product_store_category", "store_id", "category"), + ) + + +class CrmMemberProductModel(Base): + """客户已购买产品/套餐表""" + __tablename__ = "crm_member_product" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + member_id = Column(String(64), nullable=False, index=True, comment="客户ID") + product_id = Column(String(64), nullable=True, index=True, comment="产品ID") + account_id = Column(String(64), nullable=True, index=True, comment="关联账户ID") + product_name = Column(String(128), nullable=False, comment="购买产品/套餐名称") + package_items = Column(JSON, nullable=True, comment="套餐明细") + unit_price = Column(Numeric(12, 2), default=0, comment="购买时单价") + purchase_count = Column(Integer, default=0, comment="购买数量/次数") + discount = Column(Numeric(5, 2), default=1, comment="折扣系数,1=10折") + total_count = Column(Integer, default=0, comment="总次数") + balance_count = Column(Integer, default=0, comment="剩余次数") + total_amount = Column(Numeric(12, 2), default=0, comment="购买金额") + balance_amount = Column(Numeric(12, 2), default=0, comment="剩余金额") + valid_start = Column(Date, nullable=True, comment="有效期开始") + valid_end = Column(Date, nullable=True, comment="有效期结束") + status = Column(SmallInteger, default=1, comment="0=已用完/关闭 1=使用中 2=已过期") + notes = Column(Text, nullable=True, comment="备注") + creator = Column(String(64), nullable=True) + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + updater = Column(String(64), nullable=True) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + __table_args__ = ( + Index("idx_crm_member_product_store_status", "store_id", "status"), + Index("idx_crm_member_product_member_status", "member_id", "status"), + ) + + +class CrmProductConsumeModel(Base): + """客户产品/套餐消费记录""" + __tablename__ = "crm_product_consume" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + member_id = Column(String(64), nullable=False, index=True, comment="客户ID") + member_product_id = Column(String(64), nullable=False, index=True, comment="客户已购产品ID") + product_id = Column(String(64), nullable=True, index=True, comment="产品ID") + visit_id = Column(String(64), nullable=True, index=True, comment="到店记录ID") + consume_count = Column(Integer, default=0, comment="消费次数") + consume_amount = Column(Numeric(12, 2), default=0, comment="消费金额") + balance_count_after = Column(Integer, default=0, comment="消费后剩余次数") + balance_amount_after = Column(Numeric(12, 2), default=0, comment="消费后剩余金额") + notes = Column(String(256), nullable=True, comment="备注") + operator = Column(String(64), nullable=True, comment="操作人") + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + + __table_args__ = ( + Index("idx_crm_product_consume_store_date", "store_id", "create_date"), + ) + + +class CrmEmployeeScheduleModel(Base): + """员工每周排班""" + __tablename__ = "crm_employee_schedule" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True, comment="门店ID") + employee_id = Column(String(64), nullable=False, index=True, comment="员工ID") + weekday = Column(SmallInteger, nullable=False, comment="1-7 周一到周日") + start_time = Column(String(8), nullable=False, comment="HH:mm") + end_time = Column(String(8), nullable=False, comment="HH:mm") + is_working = Column(SmallInteger, default=1, comment="0=休息 1=上班") + status = Column(SmallInteger, default=1) + create_date = Column(DateTime, default=datetime.now) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now) + + __table_args__ = ( + Index("idx_crm_schedule_employee_weekday", "employee_id", "weekday"), + ) + + +class CrmEmployeeTimeoffModel(Base): + """员工特殊不可用时间""" + __tablename__ = "crm_employee_timeoff" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True) + employee_id = Column(String(64), nullable=False, index=True) + start_at = Column(DateTime, nullable=False) + end_at = Column(DateTime, nullable=False) + reason = Column(String(256), nullable=True) + status = Column(SmallInteger, default=1) + create_date = Column(DateTime, default=datetime.now) + + __table_args__ = ( + Index("idx_crm_timeoff_employee_time", "employee_id", "start_at", "end_at"), + ) + + +class CrmAppointmentModel(Base): + """门店预约""" + __tablename__ = "crm_appointment" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=False, index=True) + member_id = Column(String(64), nullable=False, index=True) + employee_id = Column(String(64), nullable=False, index=True) + member_product_id = Column(String(64), nullable=True, index=True) + product_id = Column(String(64), nullable=True, index=True) + product_name = Column(String(128), nullable=True) + appointment_date = Column(Date, nullable=False, index=True) + start_at = Column(DateTime, nullable=False, index=True) + end_at = Column(DateTime, nullable=False, index=True) + duration_minutes = Column(Integer, default=60) + source = Column(String(32), default="admin", comment="admin/h5/voice/agent") + status = Column(String(32), default="pending", comment="pending/confirmed/arrived/completed/cancelled/no_show") + customer_notes = Column(Text, nullable=True) + store_notes = Column(Text, nullable=True) + cancel_reason = Column(String(256), nullable=True) + created_by = Column(String(64), nullable=True) + confirmed_by = Column(String(64), nullable=True) + cancelled_by = Column(String(64), nullable=True) + create_date = Column(DateTime, default=datetime.now) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now) + + __table_args__ = ( + Index("idx_crm_appointment_store_date", "store_id", "appointment_date"), + Index("idx_crm_appointment_employee_time", "employee_id", "start_at", "end_at"), + ) + + +class CrmAppointmentLogModel(Base): + """预约变更日志""" + __tablename__ = "crm_appointment_log" + + id = Column(String(64), primary_key=True) + appointment_id = Column(String(64), nullable=False, index=True) + action = Column(String(32), nullable=False) + before_json = Column(JSON, nullable=True) + after_json = Column(JSON, nullable=True) + operator = Column(String(64), nullable=True) + notes = Column(String(256), nullable=True) + create_date = Column(DateTime, default=datetime.now) + + +class AdminNotificationModel(Base): + """后台通知消息""" + __tablename__ = "admin_notification" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=True, index=True) + title = Column(String(128), nullable=False) + content = Column(Text, nullable=True) + notification_type = Column(String(32), default="appointment", comment="appointment/system") + target_route = Column(String(128), nullable=True) + target_id = Column(String(64), nullable=True) + status = Column(String(16), default="unread", comment="unread/read") + create_date = Column(DateTime, default=datetime.now) + read_date = Column(DateTime, nullable=True) + + __table_args__ = ( + Index("idx_admin_notification_store_status", "store_id", "status", "create_date"), + ) + + +class AgentFeedbackCaseModel(Base): + """AI 助手反馈/失败案例""" + __tablename__ = "agent_feedback_case" + + id = Column(String(64), primary_key=True) + store_id = Column(String(64), nullable=True, index=True) + username = Column(String(64), nullable=True) + message = Column(Text, nullable=False) + reply = Column(Text, nullable=True) + intent = Column(String(64), nullable=True) + rating = Column(String(16), nullable=False, comment="like/dislike") + trace = Column(JSON, nullable=True) + status = Column(String(32), default="open", comment="open/reviewed/fixed/ignored") + notes = Column(Text, nullable=True) + create_date = Column(DateTime, default=datetime.now) + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now) + + __table_args__ = ( + Index("idx_agent_feedback_status", "status", "create_date"), + ) + + +class AdminUserModel(Base): + """管理员用户表(后台管理登录用)""" + __tablename__ = "admin_user" + + id = Column(String(64), primary_key=True) + username = Column(String(64), unique=True, nullable=False, comment="用户名") + password_hash = Column(String(256), nullable=False, comment="密码哈希") + display_name = Column(String(64), nullable=True, comment="显示名称") + role = Column(String(32), default="admin", comment="角色: super_admin/admin") + status = Column(SmallInteger, default=1, comment="0=禁用 1=启用") + create_date = Column(DateTime, default=datetime.now, comment="创建时间") + update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间") + + def __repr__(self): + return f"" diff --git a/main/feedback-backend/app/infrastructure/persistence/store_repo_impl.py b/main/feedback-backend/app/infrastructure/persistence/store_repo_impl.py new file mode 100644 index 000000000..9cc907492 --- /dev/null +++ b/main/feedback-backend/app/infrastructure/persistence/store_repo_impl.py @@ -0,0 +1,121 @@ +"""门店仓储实现 - ORM Model <-> Domain Entity 转换""" + +from datetime import datetime +from typing import List, Optional + +from sqlalchemy import or_ +from sqlalchemy.orm import Session + +from app.domain.store.entity import Store +from app.domain.store.repository import IStoreRepository +from app.infrastructure.persistence.models import StoreModel +from app.shared.utils import generate_id + + +class StoreRepositoryImpl(IStoreRepository): + """门店仓储实现""" + + def __init__(self, session: Session): + self.session = session + + @staticmethod + def _to_entity(model: StoreModel) -> Store: + """ORM Model -> Domain Entity""" + return Store( + id=model.id, + store_code=model.store_code, + store_name=model.store_name, + manager=model.manager, + shareholders=model.shareholders, + agent_id=model.agent_id, + status=model.status, + create_date=model.create_date, + update_date=model.update_date, + ) + + @staticmethod + def _to_model(entity: Store) -> StoreModel: + """Domain Entity -> ORM Model""" + return StoreModel( + id=entity.id, + store_code=entity.store_code, + store_name=entity.store_name, + manager=entity.manager, + shareholders=entity.shareholders, + agent_id=entity.agent_id, + status=entity.status, + create_date=entity.create_date or datetime.now(), + update_date=entity.update_date or datetime.now(), + ) + + async def get_by_id(self, store_id: str) -> Optional[Store]: + model = self.session.query(StoreModel).filter(StoreModel.id == store_id).first() + return self._to_entity(model) if model else None + + async def get_by_store_code(self, store_code: str) -> Optional[Store]: + model = self.session.query(StoreModel).filter( + StoreModel.store_code == store_code + ).first() + return self._to_entity(model) if model else None + + async def list_all(self, status: Optional[int] = None) -> List[Store]: + query = self.session.query(StoreModel) + if status is not None: + query = query.filter(StoreModel.status == status) + models = query.order_by(StoreModel.create_date.desc()).all() + return [self._to_entity(m) for m in models] + + async def list_page(self, page: int = 1, page_size: int = 20, + store_name: Optional[str] = None, + status: Optional[int] = None) -> dict: + query = self.session.query(StoreModel) + if store_name: + query = query.filter(StoreModel.store_name.like(f"%{store_name}%")) + if status is not None: + query = query.filter(StoreModel.status == status) + + total = query.count() + models = query.order_by(StoreModel.create_date.desc()) \ + .offset((page - 1) * page_size) \ + .limit(page_size) \ + .all() + + return { + "list": [self._to_entity(m) for m in models], + "total": total, + "page": page, + "page_size": page_size, + } + + async def save(self, store: Store) -> Store: + existing = self.session.query(StoreModel).filter(StoreModel.id == store.id).first() + if existing: + existing.store_code = store.store_code + existing.store_name = store.store_name + existing.manager = store.manager + existing.shareholders = store.shareholders + existing.agent_id = store.agent_id + existing.status = store.status + existing.update_date = datetime.now() + self.session.commit() + self.session.refresh(existing) + return self._to_entity(existing) + else: + if not store.id: + store.id = generate_id() + model = self._to_model(store) + self.session.add(model) + self.session.commit() + self.session.refresh(model) + return self._to_entity(model) + + async def delete(self, store_id: str) -> bool: + count = self.session.query(StoreModel).filter(StoreModel.id == store_id).delete() + self.session.commit() + return count > 0 + + async def exists_by_store_code(self, store_code: str, exclude_id: Optional[str] = None) -> bool: + query = self.session.query(StoreModel).filter(StoreModel.store_code == store_code) + if exclude_id: + query = query.filter(StoreModel.id != exclude_id) + return query.first() is not None diff --git a/main/feedback-backend/app/infrastructure/xiaozhi/__init__.py b/main/feedback-backend/app/infrastructure/xiaozhi/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/infrastructure/xiaozhi/ws_client.py b/main/feedback-backend/app/infrastructure/xiaozhi/ws_client.py new file mode 100644 index 000000000..3891c0419 --- /dev/null +++ b/main/feedback-backend/app/infrastructure/xiaozhi/ws_client.py @@ -0,0 +1,40 @@ +"""xiaozhi-server WebSocket 客户端 - 用于与 xiaozhi-server 通信""" + +from typing import Optional + +import httpx +from loguru import logger + +from app.shared.config import settings + + +class XiaozhiClient: + """xiaozhi-server HTTP/WS 客户端""" + + def __init__(self): + self.base_url = settings.get("xiaozhi.http_url", "http://127.0.0.1:18003") + self.ws_url = settings.get("xiaozhi.ws_url", "ws://127.0.0.1:18000/xiaozhi/v1/voice") + + async def get_device_config(self, device_id: str) -> Optional[dict]: + """通过 xiaozhi-server 获取设备配置(agent 信息)""" + try: + async with httpx.AsyncClient(timeout=10.0) as client: + # 尝试从 xiaozhi-server 获取设备配置 + resp = await client.get( + f"{self.base_url}/xiaozhi/ota/", + params={"device_id": device_id} + ) + if resp.status_code == 200: + return resp.json() + except Exception as e: + logger.warning(f"获取设备配置失败: {e}") + return None + + async def health_check(self) -> bool: + """检查 xiaozhi-server 是否在线""" + try: + async with httpx.AsyncClient(timeout=5.0) as client: + resp = await client.get(f"{self.base_url}/") + return resp.status_code == 200 + except Exception: + return False diff --git a/main/feedback-backend/app/interfaces/__init__.py b/main/feedback-backend/app/interfaces/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/interfaces/admin/__init__.py b/main/feedback-backend/app/interfaces/admin/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/interfaces/api/__init__.py b/main/feedback-backend/app/interfaces/api/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/interfaces/api/agent_chat_controller.py b/main/feedback-backend/app/interfaces/api/agent_chat_controller.py new file mode 100644 index 000000000..a900ed8ad --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/agent_chat_controller.py @@ -0,0 +1,168 @@ +"""后台 AI 数字人助手接口""" + +from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect +from jose import JWTError, jwt +from loguru import logger +from pydantic import BaseModel, Field +from sqlalchemy.orm import Session + +from app.application.agent_chat_service import AgentChatService +from app.infrastructure.persistence.database import SessionFactory, get_session +from app.infrastructure.persistence.models import AgentFeedbackCaseModel +from app.shared.config import settings +from app.shared.utils import generate_id +from app.interfaces.api.auth import ( + ROLE_STORE_MANAGER, + _store_context, + get_current_user, + scoped_store_id, +) + +router = APIRouter(prefix="/agent", tags=["AI助手"]) + + +class AgentChatRequest(BaseModel): + message: str = Field(..., description="用户消息") + history: list[dict] | None = Field(default=None, description="最近对话上下文") + + +class AgentFeedbackRequest(BaseModel): + message: str + reply: str = "" + intent: str = "" + rating: str = Field(..., description="like/dislike") + trace: list | dict | None = None + notes: str = "" + + +@router.post("/chat") +async def chat( + req: AgentChatRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """后台 AI 助手对话""" + service = AgentChatService(session) + result = await service.chat( + message=req.message, + history=req.history or [], + store_id=scoped_store_id(current_user), + operator=current_user.get("username", ""), + ) + return {"code": 0, "msg": "success", "data": result} + + +async def _current_user_from_ws_token(token: str, session: Session) -> dict: + try: + payload = jwt.decode( + token, + settings.get("auth.secret_key"), + algorithms=[settings.get("auth.algorithm", "HS256")], + ) + except JWTError as exc: + raise ValueError("无效的认证凭证") from exc + + username = payload.get("sub") + if not username: + raise ValueError("无效的认证凭证") + role = payload.get("role") or "super_admin" + ctx = { + "username": username, + "role": role, + "store_id": payload.get("store_id"), + "store_code": payload.get("store_code"), + "store_name": payload.get("store_name"), + } + if role == ROLE_STORE_MANAGER and not ctx["store_id"]: + ctx.update(_store_context(session, ctx.get("store_code") or username)) + return ctx + + +@router.websocket("/chat/ws") +async def chat_ws(websocket: WebSocket): + """后台 AI 助手长连接对话。 + + 管理后台数字人使用该通道保持一个持续会话;每条用户消息复用同一份 + conversation history,避免浏览器 ASR 一轮结束后显示 aborted。 + """ + token = websocket.query_params.get("token") or "" + db = SessionFactory() + try: + current_user = await _current_user_from_ws_token(token, db) + except ValueError as exc: + await websocket.close(code=1008, reason=str(exc)) + db.close() + return + + await websocket.accept() + service = AgentChatService(db) + history: list[dict] = [] + session_id = generate_id() + await websocket.send_json({ + "type": "hello", + "session_id": session_id, + "text": "后台 AI 数字人长连接已建立", + }) + + try: + while True: + payload = await websocket.receive_json() + msg_type = payload.get("type") + if msg_type == "ping": + await websocket.send_json({"type": "pong"}) + continue + if msg_type == "reset": + history.clear() + await websocket.send_json({"type": "reset", "text": "上下文已清空"}) + continue + if msg_type != "message": + await websocket.send_json({"type": "error", "text": "不支持的消息类型"}) + continue + + text = str(payload.get("text") or "").strip() + if not text: + continue + + history.append({"role": "user", "text": text}) + await websocket.send_json({"type": "thinking", "text": "正在思考和查询..."}) + try: + result = await service.chat( + message=text, + history=history[-12:], + store_id=scoped_store_id(current_user), + operator=current_user.get("username", ""), + ) + reply = result.get("reply") or "已处理" + history.append({"role": "assistant", "text": reply}) + await websocket.send_json({"type": "reply", "data": result, "text": reply}) + except Exception as exc: + logger.exception(f"AI 长连接处理失败: {exc}") + await websocket.send_json({"type": "error", "text": f"操作失败:{exc}"}) + except WebSocketDisconnect: + logger.info(f"后台 AI 数字人长连接断开: session={session_id}, user={current_user.get('username')}") + finally: + db.close() + + +@router.post("/feedback") +async def feedback( + req: AgentFeedbackRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """记录 AI 助手点赞/点踩反馈。""" + item = AgentFeedbackCaseModel( + id=generate_id(), + store_id=scoped_store_id(current_user), + username=current_user.get("username"), + message=req.message, + reply=req.reply, + intent=req.intent, + rating=req.rating, + trace=req.trace, + notes=req.notes, + status="open" if req.rating == "dislike" else "reviewed", + ) + session.add(item) + session.commit() + return {"code": 0, "msg": "success", "data": {"id": item.id}} diff --git a/main/feedback-backend/app/interfaces/api/agent_config_controller.py b/main/feedback-backend/app/interfaces/api/agent_config_controller.py new file mode 100644 index 000000000..438179e88 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/agent_config_controller.py @@ -0,0 +1,123 @@ +"""智能体配置管理控制器 - 后台管理用""" + +from typing import Optional + +from fastapi import APIRouter, Depends, Query +from loguru import logger +from pydantic import BaseModel, Field +from sqlalchemy.orm import Session + +from app.application.agent_config_service import AgentConfigService +from app.infrastructure.persistence.database import get_session +from app.interfaces.api.auth import get_current_user, require_super_admin + +router = APIRouter(prefix="/agent-config", tags=["智能体配置"]) + + +class CreateAgentConfigRequest(BaseModel): + """创建智能体配置请求""" + agent_name: str = Field(..., description="智能体名称") + agent_id: Optional[str] = Field(None, description="对应 xiaozhi-server 智能体 ID") + dialogue_rounds: int = Field(7, ge=1, le=20, description="对话轮次") + questions: Optional[list] = Field(None, description="问题列表") + prompts_config: Optional[dict] = Field(None, description="提示词配置") + llm_config: Optional[dict] = Field(None, description="LLM 配置") + review_config: Optional[dict] = Field(None, description="点评生成规则") + + +class UpdateAgentConfigRequest(BaseModel): + """更新智能体配置请求""" + agent_name: Optional[str] = Field(None) + agent_id: Optional[str] = Field(None) + dialogue_rounds: Optional[int] = Field(None, ge=1, le=20) + questions: Optional[list] = Field(None) + prompts_config: Optional[dict] = Field(None) + llm_config: Optional[dict] = Field(None) + review_config: Optional[dict] = Field(None) + status: Optional[int] = Field(None) + + +@router.get("/list") +async def list_agent_configs( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """分页查询智能体配置""" + require_super_admin(current_user) + service = AgentConfigService(session) + result = await service.list_page(page, page_size) + return { + "code": 0, + "msg": "success", + "data": { + "list": [ + { + "id": c.id, + "agentName": c.agent_name, + "agentId": c.agent_id, + "dialogueRounds": c.dialogue_rounds, + "questions": c.questions, + "promptsConfig": c.prompts_config, + "llmConfig": c.llm_config, + "reviewConfig": c.review_config, + "status": c.status, + "createDate": str(c.create_date) if c.create_date else None, + } + for c in result["list"] + ], + "total": result["total"], + "page": result["page"], + "pageSize": result["page_size"], + }, + } + + +@router.post("") +async def create_agent_config( + req: CreateAgentConfigRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """创建智能体配置""" + require_super_admin(current_user) + service = AgentConfigService(session) + config = await service.create_config( + agent_name=req.agent_name, + agent_id=req.agent_id, + dialogue_rounds=req.dialogue_rounds, + questions=req.questions, + prompts_config=req.prompts_config, + llm_config=req.llm_config, + review_config=req.review_config, + ) + return {"code": 0, "msg": "success", "data": {"id": config.id}} + + +@router.put("/{config_id}") +async def update_agent_config( + config_id: str, + req: UpdateAgentConfigRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """更新智能体配置""" + require_super_admin(current_user) + service = AgentConfigService(session) + kwargs = req.model_dump(exclude_none=True) + config = await service.update_config(config_id, **kwargs) + return {"code": 0, "msg": "success", "data": {"id": config.id}} + + +@router.post("/delete") +async def delete_agent_config( + config_id: str = Query(...), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """删除智能体配置""" + require_super_admin(current_user) + service = AgentConfigService(session) + await service.delete_config(config_id) + return {"code": 0, "msg": "success"} diff --git a/main/feedback-backend/app/interfaces/api/appointment_controller.py b/main/feedback-backend/app/interfaces/api/appointment_controller.py new file mode 100644 index 000000000..b03480cf6 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/appointment_controller.py @@ -0,0 +1,103 @@ +"""预约日历控制器""" + +from typing import Optional + +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import BaseModel, Field +from sqlalchemy.orm import Session + +from app.application.appointment_service import AppointmentService +from app.infrastructure.persistence.database import get_session +from app.interfaces.api.auth import get_current_user, scoped_store_id + +router = APIRouter(prefix="/appointment", tags=["预约日历"]) + + +class Payload(BaseModel): + data: dict = Field(default_factory=dict) + + +@router.get("/calendar") +async def calendar( + start_date: str = Query(...), + end_date: str = Query(...), + store_id: Optional[str] = Query(None), + employee_id: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = AppointmentService(session) + data = await service.calendar(scoped_store_id(current_user, store_id), start_date, end_date, employee_id) + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/availability") +async def availability( + date: str = Query(...), + store_id: Optional[str] = Query(None), + employee_id: Optional[str] = Query(None), + duration_minutes: int = Query(60, ge=15, le=480), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = AppointmentService(session) + data = await service.availability(scoped_store_id(current_user, store_id), date, employee_id, duration_minutes) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("") +async def create_appointment( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + try: + service = AppointmentService(session) + result = await service.create_appointment(data, current_user.get("username", "")) + return {"code": 0, "msg": "success", "data": result} + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + +@router.post("/{appointment_id}/confirm") +async def confirm_appointment( + appointment_id: str, + payload: Payload = Payload(), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = AppointmentService(session) + result = await service.update_status(appointment_id, "confirmed", payload.data, current_user.get("username", "")) + if not result: + raise HTTPException(status_code=404, detail="预约不存在") + return {"code": 0, "msg": "success", "data": result} + + +@router.post("/{appointment_id}/cancel") +async def cancel_appointment( + appointment_id: str, + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = AppointmentService(session) + result = await service.update_status(appointment_id, "cancelled", payload.data, current_user.get("username", "")) + if not result: + raise HTTPException(status_code=404, detail="预约不存在") + return {"code": 0, "msg": "success", "data": result} + + +@router.post("/{appointment_id}/complete") +async def complete_appointment( + appointment_id: str, + payload: Payload = Payload(), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = AppointmentService(session) + result = await service.update_status(appointment_id, "completed", payload.data, current_user.get("username", "")) + if not result: + raise HTTPException(status_code=404, detail="预约不存在") + return {"code": 0, "msg": "success", "data": result} diff --git a/main/feedback-backend/app/interfaces/api/auth.py b/main/feedback-backend/app/interfaces/api/auth.py new file mode 100644 index 000000000..d49f0a2df --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/auth.py @@ -0,0 +1,151 @@ +"""JWT 认证模块 - 后台管理登录""" + +from datetime import datetime, timedelta +from typing import Optional + +from fastapi import Depends, HTTPException, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from jose import JWTError, jwt +from loguru import logger +from passlib.context import CryptContext +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.infrastructure.persistence.database import get_session +from app.infrastructure.persistence.models import AdminUserModel, StoreModel +from app.shared.config import settings + +# 密码加密 +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +# Bearer Token +security = HTTPBearer() + +ROLE_SUPER_ADMIN = "super_admin" +ROLE_STORE_MANAGER = "store_manager" + + +class LoginRequest(BaseModel): + """登录请求""" + username: str + password: str + + +class TokenResponse(BaseModel): + """Token 响应""" + access_token: str + token_type: str = "bearer" + username: str + display_name: Optional[str] = None + role: str = ROLE_SUPER_ADMIN + store_id: Optional[str] = None + store_code: Optional[str] = None + store_name: Optional[str] = None + + +class ChangePasswordRequest(BaseModel): + """修改密码请求""" + old_password: str + new_password: str + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """验证密码""" + return pwd_context.verify(plain_password, hashed_password) + + +def get_password_hash(password: str) -> str: + """密码哈希""" + return pwd_context.hash(password) + + +def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: + """创建 JWT Token""" + to_encode = data.copy() + expire = datetime.utcnow() + (expires_delta or timedelta( + minutes=settings.get("auth.access_token_expire_minutes", 1440) + )) + to_encode.update({"exp": expire}) + return jwt.encode( + to_encode, + settings.get("auth.secret_key"), + algorithm=settings.get("auth.algorithm", "HS256"), + ) + + +def _store_context(session: Session, store_code: Optional[str]) -> dict: + if not store_code: + return {"store_id": None, "store_code": None, "store_name": None} + store = session.query(StoreModel).filter( + StoreModel.store_code == store_code, + StoreModel.status == 1, + ).first() + if not store: + return {"store_id": None, "store_code": store_code, "store_name": None} + return {"store_id": store.id, "store_code": store.store_code, "store_name": store.store_name} + + +async def get_current_user( + credentials: HTTPAuthorizationCredentials = Depends(security), + session: Session = Depends(get_session), +): + """获取当前用户上下文(依赖注入)""" + token = credentials.credentials + try: + payload = jwt.decode( + token, + settings.get("auth.secret_key"), + algorithms=[settings.get("auth.algorithm", "HS256")], + ) + username: str = payload.get("sub") + role: str = payload.get("role") or ROLE_SUPER_ADMIN + if username is None: + raise HTTPException(status_code=401, detail="无效的认证凭证") + + ctx = { + "username": username, + "role": role, + "store_id": payload.get("store_id"), + "store_code": payload.get("store_code"), + "store_name": payload.get("store_name"), + } + if role == ROLE_STORE_MANAGER and not ctx["store_id"]: + ctx.update(_store_context(session, ctx.get("store_code") or username)) + return ctx + except JWTError: + raise HTTPException(status_code=401, detail="无效的认证凭证") + + +def require_super_admin(current_user: dict): + if current_user.get("role") != ROLE_SUPER_ADMIN: + raise HTTPException(status_code=403, detail="权限不足") + + +def scoped_store_id(current_user: dict, requested_store_id: Optional[str] = None) -> Optional[str]: + """按当前用户角色计算可访问的 store_id。""" + if current_user.get("role") == ROLE_STORE_MANAGER: + store_id = current_user.get("store_id") + if not store_id: + raise HTTPException(status_code=403, detail="未绑定门店") + if requested_store_id and requested_store_id != store_id: + raise HTTPException(status_code=403, detail="无权访问其他门店") + return store_id + return requested_store_id + + +def init_default_admin(session: Session): + """初始化默认管理员账号""" + admin = session.query(AdminUserModel).filter( + AdminUserModel.username == settings.get("admin.username", "admin") + ).first() + if not admin: + admin = AdminUserModel( + id=str(hash("admin"))[:64], + username=settings.get("admin.username", "admin"), + password_hash=get_password_hash(settings.get("admin.password", "admin123")), + display_name="管理员", + role=ROLE_SUPER_ADMIN, + ) + session.add(admin) + session.commit() + logger.info("默认管理员账号已创建") diff --git a/main/feedback-backend/app/interfaces/api/auth_controller.py b/main/feedback-backend/app/interfaces/api/auth_controller.py new file mode 100644 index 000000000..07e4ecce4 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/auth_controller.py @@ -0,0 +1,131 @@ +"""认证控制器 - 登录/获取用户信息""" + +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session + +from app.infrastructure.persistence.database import get_session +from app.infrastructure.persistence.models import AdminUserModel, StoreModel +from app.interfaces.api.auth import ( + ChangePasswordRequest, + LoginRequest, + ROLE_STORE_MANAGER, + ROLE_SUPER_ADMIN, + TokenResponse, + create_access_token, + get_current_user, + get_password_hash, + verify_password, +) + +router = APIRouter(prefix="/auth", tags=["认证"]) + + +@router.post("/login", response_model=TokenResponse) +async def login( + req: LoginRequest, + session: Session = Depends(get_session), +): + """管理员/店长登录""" + user = session.query(AdminUserModel).filter( + AdminUserModel.username == req.username, + AdminUserModel.status == 1, + ).first() + + if user: + if not verify_password(req.password, user.password_hash): + raise HTTPException(status_code=401, detail="用户名或密码错误") + + store = None + if user.role == ROLE_STORE_MANAGER: + store = session.query(StoreModel).filter( + StoreModel.store_code == user.username, + StoreModel.status == 1, + ).first() + if not store: + raise HTTPException(status_code=403, detail="店长账号未绑定门店") + + token_data = {"sub": user.username, "role": user.role or ROLE_SUPER_ADMIN} + if store: + token_data.update({ + "store_id": store.id, + "store_code": store.store_code, + "store_name": store.store_name, + }) + access_token = create_access_token(data=token_data) + + return TokenResponse( + access_token=access_token, + username=user.username, + display_name=user.display_name, + role=user.role or ROLE_SUPER_ADMIN, + store_id=store.id if store else None, + store_code=store.store_code if store else None, + store_name=store.store_name if store else None, + ) + + # 门店店长默认账号:门店编码 / 门店编码。首次登录时自动创建。 + if req.username == req.password and req.username.isdigit() and len(req.username) == 6: + store = session.query(StoreModel).filter( + StoreModel.store_code == req.username, + StoreModel.status == 1, + ).first() + if not store: + raise HTTPException(status_code=401, detail="用户名或密码错误") + + user = AdminUserModel( + id=f"store_manager_{store.store_code}", + username=store.store_code, + password_hash=get_password_hash(req.password), + display_name=store.manager or store.store_name or store.store_code, + role=ROLE_STORE_MANAGER, + status=1, + ) + session.add(user) + session.commit() + + token_data = { + "sub": user.username, + "role": ROLE_STORE_MANAGER, + "store_id": store.id, + "store_code": store.store_code, + "store_name": store.store_name, + } + access_token = create_access_token(data=token_data) + return TokenResponse( + access_token=access_token, + username=user.username, + display_name=user.display_name, + role=ROLE_STORE_MANAGER, + store_id=store.id, + store_code=store.store_code, + store_name=store.store_name, + ) + + raise HTTPException(status_code=401, detail="用户名或密码错误") + + +@router.get("/me") +async def get_me(current_user: dict = Depends(get_current_user)): + """获取当前用户信息""" + return {"code": 0, "msg": "success", "data": current_user} + + +@router.post("/change-password") +async def change_password( + req: ChangePasswordRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """修改当前登录用户密码""" + user = session.query(AdminUserModel).filter( + AdminUserModel.username == current_user["username"], + AdminUserModel.status == 1, + ).first() + if not user or not verify_password(req.old_password, user.password_hash): + raise HTTPException(status_code=401, detail="原密码错误") + if len(req.new_password) < 6: + raise HTTPException(status_code=400, detail="新密码至少 6 位") + + user.password_hash = get_password_hash(req.new_password) + session.commit() + return {"code": 0, "msg": "success"} diff --git a/main/feedback-backend/app/interfaces/api/crm_controller.py b/main/feedback-backend/app/interfaces/api/crm_controller.py new file mode 100644 index 000000000..9a21006e1 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/crm_controller.py @@ -0,0 +1,436 @@ +"""CRM 控制器 - 客户档案、到店、账户、销卡、建议、问题闭环""" + +from typing import Optional + +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import BaseModel, Field +from sqlalchemy.orm import Session + +from app.application.crm_service import CrmService +from app.infrastructure.persistence.database import get_session +from app.interfaces.api.auth import get_current_user, scoped_store_id +from app.shared.mekai66 import MEKAI66_FIELDS + +router = APIRouter(prefix="/crm", tags=["CRM管理"]) + + +class Payload(BaseModel): + data: dict = Field(default_factory=dict) + + +@router.get("/overview") +async def overview( + store_id: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.get_overview(scoped_store_id(current_user, store_id))} + + +@router.get("/mekai66-fields") +async def get_mekai66_fields( + current_user: dict = Depends(get_current_user), +): + """麦凯66客户档案字段""" + return {"code": 0, "msg": "success", "data": MEKAI66_FIELDS} + + +@router.get("/member/list") +async def list_members( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + keyword: Optional[str] = Query(None), + status: Optional[int] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_members(page, page_size, scoped_store_id(current_user, store_id), keyword, status) + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/member/{member_id}") +async def get_member( + member_id: str, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.get_member(member_id, scoped_store_id(current_user)) + if not data: + raise HTTPException(status_code=404, detail="客户不存在") + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/member") +async def create_member( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + if not data.get("store_id"): + raise HTTPException(status_code=400, detail="请选择门店") + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.create_member(data, current_user.get("username", ""))} + + +@router.put("/member/{member_id}") +async def update_member( + member_id: str, + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.update_member(member_id, payload.data, scoped_store_id(current_user), current_user.get("username", "")) + if not data: + raise HTTPException(status_code=404, detail="客户不存在") + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/visit/list") +async def list_visits( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + member_id: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_visits(page, page_size, scoped_store_id(current_user, store_id), member_id) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/visit") +async def create_visit( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + if not data.get("store_id"): + raise HTTPException(status_code=400, detail="请选择门店") + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.create_visit(data, current_user.get("username", ""))} + + +@router.put("/visit/{visit_id}") +async def update_visit( + visit_id: str, + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.update_visit(visit_id, payload.data, scoped_store_id(current_user), current_user.get("username", "")) + if not data: + raise HTTPException(status_code=404, detail="到店记录不存在") + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/account/list") +async def list_accounts( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + member_id: Optional[str] = Query(None), + status: Optional[int] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_accounts(page, page_size, scoped_store_id(current_user, store_id), member_id, status) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/account") +async def create_account( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + if not data.get("store_id"): + raise HTTPException(status_code=400, detail="请选择门店") + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.create_account(data, current_user.get("username", ""))} + + +@router.get("/account/transactions") +async def list_account_transactions( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + account_id: Optional[str] = Query(None), + member_id: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_account_transactions(page, page_size, scoped_store_id(current_user, store_id), account_id, member_id) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/account/{account_id}/consume") +async def consume_account( + account_id: str, + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.consume_account(account_id, payload.data, scoped_store_id(current_user), current_user.get("username", "")) + if not data: + raise HTTPException(status_code=404, detail="账户不存在") + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/card-close") +async def close_card( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.close_card(payload.data, scoped_store_id(current_user), current_user.get("username", "")) + if not data: + raise HTTPException(status_code=404, detail="账户不存在") + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/card-close/list") +async def list_card_closes( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + member_id: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_card_closes(page, page_size, scoped_store_id(current_user, store_id), member_id) + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/body-status/list") +async def list_body_statuses( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + member_id: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_body_statuses(page, page_size, scoped_store_id(current_user, store_id), member_id) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/body-status") +async def create_body_status( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + if not data.get("store_id"): + raise HTTPException(status_code=400, detail="请选择门店") + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.create_body_status(data, current_user.get("username", ""))} + + +@router.get("/product/list") +async def list_products( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + keyword: Optional[str] = Query(None), + category: Optional[str] = Query(None), + status: Optional[int] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_products(page, page_size, scoped_store_id(current_user, store_id), keyword, category, status) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/product") +async def create_product( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + if not data.get("store_id"): + raise HTTPException(status_code=400, detail="请选择门店") + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.create_product(data, current_user.get("username", ""))} + + +@router.get("/member-product/list") +async def list_member_products( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + member_id: Optional[str] = Query(None), + status: Optional[int] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_member_products(page, page_size, scoped_store_id(current_user, store_id), member_id, status) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/member-product/purchase") +async def purchase_product( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + if not data.get("store_id"): + raise HTTPException(status_code=400, detail="请选择门店") + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.purchase_product(data, current_user.get("username", ""))} + + +@router.post("/member-product/{member_product_id}/consume") +async def consume_member_product( + member_product_id: str, + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.consume_member_product(member_product_id, payload.data, scoped_store_id(current_user), current_user.get("username", "")) + if not data: + raise HTTPException(status_code=404, detail="客户产品不存在") + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/product-consume/list") +async def list_product_consumes( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + member_id: Optional[str] = Query(None), + member_product_id: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_product_consumes(page, page_size, scoped_store_id(current_user, store_id), member_id, member_product_id) + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/suggestion/list") +async def list_suggestions( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + status: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_suggestions(page, page_size, scoped_store_id(current_user, store_id), status) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/suggestion") +async def create_suggestion( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + if not data.get("store_id"): + raise HTTPException(status_code=400, detail="请选择门店") + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.create_suggestion(data, current_user.get("username", ""))} + + +@router.post("/suggestion/{suggestion_id}/status") +async def update_suggestion_status( + suggestion_id: str, + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + status = payload.data.get("status") + if not status: + raise HTTPException(status_code=400, detail="缺少状态") + service = CrmService(session) + data = await service.update_suggestion_status(suggestion_id, status, payload.data, scoped_store_id(current_user), current_user.get("username", "")) + if not data: + raise HTTPException(status_code=404, detail="建议不存在") + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/issue/list") +async def list_issues( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + status: Optional[str] = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.list_issues(page, page_size, scoped_store_id(current_user, store_id), status) + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/issue") +async def create_issue( + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + data = payload.data + data["store_id"] = scoped_store_id(current_user, data.get("store_id") or data.get("storeId")) + if not data.get("store_id"): + raise HTTPException(status_code=400, detail="请选择门店") + service = CrmService(session) + return {"code": 0, "msg": "success", "data": await service.create_issue(data, current_user.get("username", ""))} + + +@router.put("/issue/{issue_id}") +async def update_issue( + issue_id: str, + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.update_issue(issue_id, payload.data, scoped_store_id(current_user), current_user.get("username", "")) + if not data: + raise HTTPException(status_code=404, detail="问题不存在") + return {"code": 0, "msg": "success", "data": data} + + +@router.post("/feedback/{feedback_id}/bind") +async def bind_feedback( + feedback_id: str, + payload: Payload, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + service = CrmService(session) + data = await service.bind_feedback(feedback_id, payload.data, scoped_store_id(current_user)) + if not data: + raise HTTPException(status_code=404, detail="反馈不存在") + return {"code": 0, "msg": "success", "data": data} diff --git a/main/feedback-backend/app/interfaces/api/employee_controller.py b/main/feedback-backend/app/interfaces/api/employee_controller.py new file mode 100644 index 000000000..f8f9f1cd1 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/employee_controller.py @@ -0,0 +1,111 @@ +"""员工管理控制器 - 后台管理用,需要认证""" + +from typing import Optional + +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel, Field +from sqlalchemy.orm import Session + +from app.application.employee_service import EmployeeService +from app.infrastructure.persistence.database import get_session +from app.interfaces.api.auth import get_current_user, scoped_store_id + +router = APIRouter(prefix="/employee", tags=["员工管理"]) + + +class CreateEmployeeRequest(BaseModel): + name: str = Field(..., description="员工姓名") + number: int = Field(..., description="工号") + store_id: str = Field(..., description="门店ID") + employee_type: str = Field(default="normal", description="员工类型") + + +class UpdateEmployeeRequest(BaseModel): + name: Optional[str] = Field(default=None, description="员工姓名") + number: Optional[int] = Field(default=None, description="工号") + store_id: Optional[str] = Field(default=None, description="门店ID") + employee_type: Optional[str] = Field(default=None, description="员工类型") + status: Optional[int] = Field(default=None, description="状态") + + +@router.get("/list") +async def list_employees( + page: int = 1, + page_size: int = 20, + store_id: Optional[str] = None, + name: Optional[str] = None, + status: Optional[int] = None, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """分页查询员工列表""" + service = EmployeeService(session) + result = await service.list_page(page, page_size, scoped_store_id(current_user, store_id), name, status) + return { + "code": 0, + "msg": "success", + "data": { + "list": [ + { + "id": e.id, + "name": e.name, + "number": e.number, + "storeId": e.store_id, + "employeeType": e.employee_type, + "status": e.status, + "createDate": str(e.create_date) if e.create_date else None, + } + for e in result["list"] + ], + "total": result["total"], + "page": result["page"], + "pageSize": result["page_size"], + }, + } + + +@router.post("") +async def create_employee( + req: CreateEmployeeRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """创建员工""" + store_id = scoped_store_id(current_user, req.store_id) + service = EmployeeService(session) + employee = await service.create_employee( + req.name, req.number, store_id, req.employee_type + ) + return {"code": 0, "msg": "success", "data": {"id": employee.id}} + + +@router.put("/{employee_id}") +async def update_employee( + employee_id: str, + req: UpdateEmployeeRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """更新员工""" + service = EmployeeService(session) + existing = await service.get_by_id(employee_id) + scoped_store_id(current_user, existing.store_id) + kwargs = {k: v for k, v in req.model_dump().items() if v is not None} + if "store_id" in kwargs: + kwargs["store_id"] = scoped_store_id(current_user, kwargs["store_id"]) + employee = await service.update_employee(employee_id, **kwargs) + return {"code": 0, "msg": "success", "data": {"id": employee.id}} + + +@router.post("/delete") +async def delete_employee( + employee_id: str = None, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """删除员工""" + service = EmployeeService(session) + existing = await service.get_by_id(employee_id) + scoped_store_id(current_user, existing.store_id) + await service.delete_employee(employee_id) + return {"code": 0, "msg": "success"} diff --git a/main/feedback-backend/app/interfaces/api/feedback_controller.py b/main/feedback-backend/app/interfaces/api/feedback_controller.py new file mode 100644 index 000000000..6e85d705a --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/feedback_controller.py @@ -0,0 +1,87 @@ +"""反馈记录管理控制器 - 后台管理用,需要认证""" + +from typing import Optional + +from fastapi import APIRouter, Depends, Query +from sqlalchemy.orm import Session + +from app.application.feedback_service import FeedbackService +from app.infrastructure.persistence.database import get_session +from app.infrastructure.persistence.models import CrmMemberModel, EmployeeModel, StoreModel +from app.interfaces.api.auth import get_current_user, scoped_store_id + +router = APIRouter(prefix="/record", tags=["反馈记录管理"]) + + +@router.get("/list") +async def list_records( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + employee_id: Optional[str] = Query(None), + satisfaction: Optional[str] = Query(None), + start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"), + end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """分页查询反馈记录""" + service = FeedbackService(session) + scoped_id = scoped_store_id(current_user, store_id) + result = await service.list_records( + page, page_size, + store_id=scoped_id, + employee_id=employee_id, + satisfaction=satisfaction, + start_date=start_date, + end_date=end_date, + ) + store_ids = {r.store_id for r in result["list"] if r.store_id} + employee_ids = {r.employee_id for r in result["list"] if r.employee_id} + stores = session.query(StoreModel).filter(StoreModel.id.in_(store_ids)).all() if store_ids else [] + employees = session.query(EmployeeModel).filter(EmployeeModel.id.in_(employee_ids)).all() if employee_ids else [] + store_map = {s.id: s.store_name for s in stores} + employee_map = {e.id: e.name for e in employees} + employee_no_map = {e.id: e.number for e in employees} + member_ids = {r.member_id for r in result["list"] if r.member_id} + members = session.query(CrmMemberModel).filter(CrmMemberModel.id.in_(member_ids)).all() if member_ids else [] + member_map = {m.id: m for m in members} + return { + "code": 0, + "msg": "success", + "data": { + "list": [ + { + "id": r.id, + "sessionId": r.session_id, + "storeId": r.store_id, + "storeName": store_map.get(r.store_id, r.store_id), + "employeeId": r.employee_id, + "employeeName": employee_map.get(r.employee_id, r.employee_id), + "employeeNumber": employee_no_map.get(r.employee_id), + "deviceMac": r.device_mac, + "rawAsrText": r.raw_asr_text, + "cleanedText": r.cleaned_text, + "qaJson": r.qa_json, + "reviewLong": r.review_long, + "reviewShort": r.review_short, + "satisfaction": r.satisfaction, + "memberId": r.member_id, + "memberName": member_map[r.member_id].name if r.member_id in member_map else None, + "memberPhone": member_map[r.member_id].phone if r.member_id in member_map else None, + "customerName": r.customer_name, + "phoneTail": r.phone_tail, + "memberMatchStatus": r.member_match_status, + "memberMatchCandidates": r.member_match_candidates or [], + "visitId": r.visit_id, + "cardCloseId": r.card_close_id, + "status": r.status, + "createDate": str(r.create_date) if r.create_date else None, + } + for r in result["list"] + ], + "total": result["total"], + "page": result["page"], + "pageSize": result["page_size"], + }, + } diff --git a/main/feedback-backend/app/interfaces/api/notification_controller.py b/main/feedback-backend/app/interfaces/api/notification_controller.py new file mode 100644 index 000000000..f23f47e17 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/notification_controller.py @@ -0,0 +1,87 @@ +"""后台通知控制器""" + +from fastapi import APIRouter, Depends, Query +from sqlalchemy.orm import Session + +from app.infrastructure.persistence.database import get_session +from app.infrastructure.persistence.models import AdminNotificationModel +from app.interfaces.api.auth import get_current_user, scoped_store_id + +router = APIRouter(prefix="/notification", tags=["后台通知"]) + + +@router.get("/list") +async def list_notifications( + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + status: str | None = Query(None), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + store_id = scoped_store_id(current_user) + query = session.query(AdminNotificationModel) + if store_id: + query = query.filter(AdminNotificationModel.store_id == store_id) + if status: + query = query.filter(AdminNotificationModel.status == status) + total = query.count() + rows = query.order_by(AdminNotificationModel.create_date.desc()).offset((page - 1) * page_size).limit(page_size).all() + unread = session.query(AdminNotificationModel).filter(AdminNotificationModel.status == "unread") + if store_id: + unread = unread.filter(AdminNotificationModel.store_id == store_id) + return { + "code": 0, + "msg": "success", + "data": { + "list": [ + { + "id": n.id, + "storeId": n.store_id, + "title": n.title, + "content": n.content, + "notificationType": n.notification_type, + "targetRoute": n.target_route, + "targetId": n.target_id, + "status": n.status, + "createDate": str(n.create_date) if n.create_date else None, + } + for n in rows + ], + "total": total, + "unread": unread.count(), + "page": page, + "pageSize": page_size, + }, + } + + +@router.post("/{notification_id}/read") +async def mark_read( + notification_id: str, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + store_id = scoped_store_id(current_user) + query = session.query(AdminNotificationModel).filter(AdminNotificationModel.id == notification_id) + if store_id: + query = query.filter(AdminNotificationModel.store_id == store_id) + item = query.first() + if item: + item.status = "read" + session.commit() + return {"code": 0, "msg": "success"} + + +@router.post("/read-all") +async def mark_all_read( + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + store_id = scoped_store_id(current_user) + query = session.query(AdminNotificationModel).filter(AdminNotificationModel.status == "unread") + if store_id: + query = query.filter(AdminNotificationModel.store_id == store_id) + for item in query.all(): + item.status = "read" + session.commit() + return {"code": 0, "msg": "success"} diff --git a/main/feedback-backend/app/interfaces/api/public_controller.py b/main/feedback-backend/app/interfaces/api/public_controller.py new file mode 100644 index 000000000..a03647335 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/public_controller.py @@ -0,0 +1,697 @@ +"""公开接口控制器 - H5 前端调用,无需认证""" + +from datetime import datetime, timedelta +from typing import Optional + +import httpx +from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi.responses import JSONResponse +from loguru import logger +from pydantic import BaseModel, Field, ConfigDict +from sqlalchemy.orm import Session + +from app.application.appointment_service import AppointmentService +from app.application.employee_service import EmployeeService +from app.application.feedback_service import FeedbackService +from app.application.store_service import StoreService +from app.infrastructure.persistence.database import get_session +from app.infrastructure.persistence.models import AdminNotificationModel, CrmAppointmentModel, CrmMemberModel, CrmMemberProductModel, CrmProductModel +from app.shared.config import settings +from app.shared.exceptions import StoreNotFoundError, LLMProcessingError +from app.shared.utils import generate_id + +router = APIRouter(prefix="/public", tags=["公开接口"]) + + +# ---- Request Models (兼容 H5 前端 camelCase 字段名) ---- + +class ProcessFeedbackRequest(BaseModel): + """AI 处理反馈请求 - 字段名与 H5 前端完全一致""" + storeName: str = Field(..., description="门店名称") + employeeNumber: str = Field(..., description="技师工号") + asrText: str = Field(..., description="原始 ASR 文本") + sessionId: Optional[str] = Field(None, description="WebSocket 会话 ID") + deviceMac: Optional[str] = Field(None, description="设备 MAC 地址") + clientId: Optional[str] = Field(None, description="客户端 ID") + satisfaction: Optional[str] = Field(None, description="满意度") + storeId: Optional[str] = Field(None, description="门店 ID") + employeeId: Optional[str] = Field(None, description="员工 ID") + customerName: Optional[str] = Field(None, description="客户称呼/自报姓名") + phoneTail: Optional[str] = Field(None, description="手机号后四位") + + +class SaveRecordRequest(BaseModel): + """保存反馈记录请求 - 字段名与 H5 前端完全一致""" + model_config = ConfigDict(populate_by_name=True) + + storeId: Optional[str] = Field(default=None, description="门店 ID") + employeeId: Optional[str] = Field(default=None, description="员工 ID") + sessionId: Optional[str] = Field(default=None, description="会话 ID") + deviceMac: Optional[str] = Field(default=None, description="设备 MAC") + rawAsrText: Optional[str] = Field(default=None, description="原始 ASR 文本") + cleanedText: Optional[str] = Field(default=None, description="清洗后文本") + qaJson: Optional[str] = Field(default=None, description="QA JSON") + reviewLong: Optional[str] = Field(default=None, description="标准点评") + reviewShort: Optional[str] = Field(default=None, description="精简短评") + satisfaction: Optional[str] = Field(default=None, description="满意度") + customerName: Optional[str] = Field(default=None, description="客户称呼/自报姓名") + phoneTail: Optional[str] = Field(default=None, description="手机号后四位") + + +class PublicAppointmentActionRequest(BaseModel): + """公开预约取消/改约请求""" + storeCode: str + customerPhone: str + appointmentId: Optional[str] = None + employeeId: Optional[str] = None + startAt: Optional[str] = None + durationMinutes: int = 60 + reason: Optional[str] = None + + +class PublicAppointmentBookRequest(BaseModel): + """公开预约提交请求""" + storeCode: str + employeeId: str + startAt: str + durationMinutes: int = 60 + customerName: Optional[str] = None + customerPhone: str + memberProductId: Optional[str] = None + productId: Optional[str] = None + serviceName: Optional[str] = None + notes: Optional[str] = None + + +def _appointment_notify(session: Session, store_id: str, title: str, content: str, appointment_id: Optional[str] = None): + session.add(AdminNotificationModel( + id=generate_id(), + store_id=store_id, + title=title, + content=content, + notification_type="appointment", + target_route="crm:appointments", + target_id=appointment_id, + )) + + +class DeviceInitRequest(BaseModel): + """设备初始化请求 - 兼容 H5 前端两种传参方式""" + model_config = ConfigDict(populate_by_name=True) + + storeId: Optional[str] = Field(default=None, description="门店 ID (H5 旧版)") + employeeId: Optional[str] = Field(default=None, description="员工 ID (H5 旧版)") + storeCode: Optional[str] = Field(default=None, description="门店编码 (新版)") + deviceMac: Optional[str] = Field(default=None, description="设备 MAC") + + # 兼容 Pydantic V2:至少提供 storeId 或 storeCode 之一 + # 不设 required,在 endpoint 中手动校验 + + +# ---- Endpoints ---- + +@router.get("/store/{store_code}") +async def get_store_by_code( + store_code: str, + session: Session = Depends(get_session), +): + """根据门店编码获取门店信息(扫码入口)""" + service = StoreService(session) + try: + store = await service.get_by_store_code(store_code) + return { + "code": 0, + "msg": "success", + "data": { + "id": store.id, + "storeCode": store.store_code, + "storeName": store.store_name, + "manager": store.manager, + "shareholders": store.shareholders, + "agentId": store.agent_id, + }, + } + except StoreNotFoundError as e: + return {"code": 404, "msg": e.message, "data": None} + + +@router.get("/employees/{store_id}") +async def get_employees_by_store( + store_id: str, + session: Session = Depends(get_session), +): + """获取门店下所有员工""" + service = EmployeeService(session) + employees = await service.list_by_store_id(store_id, status=1) + return { + "code": 0, + "msg": "success", + "data": [ + { + "id": e.id, + "name": e.name, + "number": e.number, + "employeeType": e.employee_type, + } + for e in employees + ], + } + + +@router.get("/appointment/bootstrap") +async def public_appointment_bootstrap( + storeCode: str, + date: Optional[str] = None, + durationMinutes: int = 60, + session: Session = Depends(get_session), +): + """公开预约页初始化:门店、技师、当天空闲档期一次返回。""" + store_service = StoreService(session) + try: + store = await store_service.get_by_store_code(storeCode) + except StoreNotFoundError as e: + return {"code": 404, "msg": e.message, "data": None} + + day = date or datetime.now().date().isoformat() + appointment_service = AppointmentService(session) + availability = await appointment_service.availability(store.id, day, None, durationMinutes) + employees = await EmployeeService(session).list_by_store_id(store.id, status=1) + return { + "code": 0, + "msg": "success", + "data": { + "serverTime": datetime.now().isoformat(sep=" ", timespec="seconds"), + "date": day, + "durationMinutes": durationMinutes, + "store": { + "id": store.id, + "storeCode": store.store_code, + "storeName": store.store_name, + "manager": store.manager, + }, + "employees": [ + {"id": e.id, "name": e.name, "number": e.number, "employeeType": e.employee_type} + for e in employees + ], + "availability": availability, + }, + } + + +@router.get("/appointment/availability") +async def public_appointment_availability( + storeCode: str, + date: str, + employeeId: Optional[str] = None, + durationMinutes: int = 60, + session: Session = Depends(get_session), +): + """公开查询预约空档。""" + try: + store = await StoreService(session).get_by_store_code(storeCode) + except StoreNotFoundError as e: + return {"code": 404, "msg": e.message, "data": None} + data = await AppointmentService(session).availability(store.id, date, employeeId, durationMinutes) + return {"code": 0, "msg": "success", "data": data} + + +@router.get("/appointment/member-products") +async def public_appointment_member_products( + storeCode: str, + phone: str, + session: Session = Depends(get_session), +): + """根据手机号查询客户已购项目/套餐,用于预约选择项目。""" + try: + store = await StoreService(session).get_by_store_code(storeCode) + except StoreNotFoundError as e: + return {"code": 404, "msg": e.message, "data": None} + phone = (phone or "").strip() + if len(phone) < 7: + return {"code": 400, "msg": "请填写有效手机号", "data": None} + member = session.query(CrmMemberModel).filter( + CrmMemberModel.store_id == store.id, + CrmMemberModel.phone == phone, + CrmMemberModel.status == 1, + ).first() + if not member: + return {"code": 404, "msg": "未查询到该手机号的客户档案,请联系门店添加后再预约", "data": {"member": None, "products": []}} + + rows = session.query(CrmMemberProductModel).filter( + CrmMemberProductModel.store_id == store.id, + CrmMemberProductModel.member_id == member.id, + CrmMemberProductModel.status == 1, + ).order_by(CrmMemberProductModel.create_date.desc()).all() + products = [] + for p in rows: + product = session.query(CrmProductModel).filter(CrmProductModel.id == p.product_id).first() if p.product_id else None + products.append({ + "id": p.id, + "memberProductId": p.id, + "productId": p.product_id, + "productName": p.product_name, + "durationMinutes": product.duration_minutes if product else 60, + "balanceCount": p.balance_count or 0, + "balanceAmount": float(p.balance_amount or 0), + "validEnd": str(p.valid_end) if p.valid_end else None, + }) + return { + "code": 0, + "msg": "success", + "data": { + "member": {"id": member.id, "name": member.name, "phone": member.phone}, + "products": products, + }, + } + + +@router.post("/appointment/book") +async def public_appointment_book( + req: PublicAppointmentBookRequest, + session: Session = Depends(get_session), +): + """公开预约提交。提交前实时二次校验冲突,防止档期被抢占。""" + try: + store = await StoreService(session).get_by_store_code(req.storeCode) + except StoreNotFoundError as e: + return {"code": 404, "msg": e.message, "data": None} + + phone = (req.customerPhone or "").strip() + if not phone or len(phone) < 7: + return {"code": 400, "msg": "请填写有效手机号", "data": None} + + member = session.query(CrmMemberModel).filter( + CrmMemberModel.store_id == store.id, + CrmMemberModel.phone == phone, + CrmMemberModel.status == 1, + ).first() + if not member: + return {"code": 404, "msg": "未查询到该手机号的客户档案,请联系门店添加后再预约", "data": None} + + member_product = None + if req.memberProductId: + member_product = session.query(CrmMemberProductModel).filter( + CrmMemberProductModel.id == req.memberProductId, + CrmMemberProductModel.store_id == store.id, + CrmMemberProductModel.member_id == member.id, + CrmMemberProductModel.status == 1, + ).first() + if not member_product: + return {"code": 400, "msg": "所选项目不可用,请重新选择", "data": None} + + payload = { + "storeId": store.id, + "memberId": member.id, + "employeeId": req.employeeId, + "startAt": req.startAt, + "durationMinutes": req.durationMinutes, + "memberProductId": member_product.id if member_product else None, + "productId": req.productId or (member_product.product_id if member_product else None), + "productName": req.serviceName or (member_product.product_name if member_product else "预约服务"), + "source": "h5", + "status": "pending", + "customerNotes": req.notes, + } + try: + result = await AppointmentService(session).create_appointment(payload, "appointment_h5") + _appointment_notify( + session, + store.id, + "新的客户预约", + f"{member.name or member.phone} 预约了 {payload['productName']},时间 {result.get('startAt')}", + result.get("id"), + ) + session.commit() + return {"code": 0, "msg": "预约成功", "data": result} + except ValueError as e: + session.rollback() + return {"code": 409, "msg": str(e), "data": None} + except Exception as e: + session.rollback() + logger.error(f"公开预约失败: {e}") + return {"code": 500, "msg": f"预约失败: {e}", "data": None} + + +@router.get("/appointment/my") +async def public_my_appointments( + storeCode: str, + phone: str, + session: Session = Depends(get_session), +): + """按手机号查询客户未完成预约,用于取消/改约。""" + try: + store = await StoreService(session).get_by_store_code(storeCode) + except StoreNotFoundError as e: + return {"code": 404, "msg": e.message, "data": None} + member = session.query(CrmMemberModel).filter( + CrmMemberModel.store_id == store.id, + CrmMemberModel.phone == (phone or "").strip(), + CrmMemberModel.status == 1, + ).first() + if not member: + return {"code": 404, "msg": "未查询到该手机号的客户档案", "data": {"member": None, "appointments": []}} + rows = session.query(CrmAppointmentModel).filter( + CrmAppointmentModel.store_id == store.id, + CrmAppointmentModel.member_id == member.id, + CrmAppointmentModel.status.in_(["pending", "confirmed", "arrived"]), + CrmAppointmentModel.start_at >= datetime.now(), + ).order_by(CrmAppointmentModel.start_at.asc()).all() + service = AppointmentService(session) + return { + "code": 0, + "msg": "success", + "data": { + "member": {"id": member.id, "name": member.name, "phone": member.phone}, + "appointments": [service._appointment_to_dict(a) for a in rows], + }, + } + + +@router.post("/appointment/cancel") +async def public_cancel_appointment( + req: PublicAppointmentActionRequest, + session: Session = Depends(get_session), +): + """公开取消预约。""" + try: + store = await StoreService(session).get_by_store_code(req.storeCode) + except StoreNotFoundError as e: + return {"code": 404, "msg": e.message, "data": None} + member = session.query(CrmMemberModel).filter(CrmMemberModel.store_id == store.id, CrmMemberModel.phone == req.customerPhone).first() + if not member: + return {"code": 404, "msg": "未查询到该手机号的客户档案", "data": None} + query = session.query(CrmAppointmentModel).filter( + CrmAppointmentModel.store_id == store.id, + CrmAppointmentModel.member_id == member.id, + CrmAppointmentModel.status.in_(["pending", "confirmed", "arrived"]), + ) + if req.appointmentId: + query = query.filter(CrmAppointmentModel.id == req.appointmentId) + appointment = query.order_by(CrmAppointmentModel.start_at.asc()).first() + if not appointment: + return {"code": 404, "msg": "未找到可取消的预约", "data": None} + result = await AppointmentService(session).update_status(appointment.id, "cancelled", {"reason": req.reason or "客户H5取消"}, "appointment_h5") + _appointment_notify(session, store.id, "客户取消预约", f"{member.name or member.phone} 取消了 {appointment.start_at}", appointment.id) + session.commit() + return {"code": 0, "msg": "预约已取消", "data": result} + + +@router.post("/appointment/reschedule") +async def public_reschedule_appointment( + req: PublicAppointmentActionRequest, + session: Session = Depends(get_session), +): + """公开改约。提交前实时二次校验新时间。""" + if not req.startAt: + return {"code": 400, "msg": "请选择新的预约时间", "data": None} + try: + store = await StoreService(session).get_by_store_code(req.storeCode) + except StoreNotFoundError as e: + return {"code": 404, "msg": e.message, "data": None} + member = session.query(CrmMemberModel).filter(CrmMemberModel.store_id == store.id, CrmMemberModel.phone == req.customerPhone).first() + if not member: + return {"code": 404, "msg": "未查询到该手机号的客户档案", "data": None} + query = session.query(CrmAppointmentModel).filter( + CrmAppointmentModel.store_id == store.id, + CrmAppointmentModel.member_id == member.id, + CrmAppointmentModel.status.in_(["pending", "confirmed", "arrived"]), + ) + if req.appointmentId: + query = query.filter(CrmAppointmentModel.id == req.appointmentId) + appointment = query.order_by(CrmAppointmentModel.start_at.asc()).first() + if not appointment: + return {"code": 404, "msg": "未找到可改约的预约", "data": None} + + start_at = datetime.fromisoformat(req.startAt) + duration = req.durationMinutes or appointment.duration_minutes or 60 + end_at = start_at + timedelta(minutes=duration) + employee_id = req.employeeId or appointment.employee_id + checker = AppointmentService(session) + if start_at <= datetime.now(): + return {"code": 409, "msg": "不能改约到已经过去的时间", "data": None} + if checker._has_conflict(employee_id, start_at, end_at): + return {"code": 409, "msg": "该员工该时间段已有预约", "data": None} + + appointment.employee_id = employee_id + appointment.start_at = start_at + appointment.end_at = end_at + appointment.appointment_date = start_at.date() + appointment.duration_minutes = duration + appointment.update_date = datetime.now() + checker._log(appointment.id, "reschedule", None, checker._appointment_to_dict(appointment), "appointment_h5", req.reason or "客户H5改约") + _appointment_notify(session, store.id, "客户改约", f"{member.name or member.phone} 改约到 {start_at}", appointment.id) + session.commit() + session.refresh(appointment) + return {"code": 0, "msg": "改约成功", "data": checker._appointment_to_dict(appointment)} + + +@router.post("/process") +async def process_feedback( + req: ProcessFeedbackRequest, + session: Session = Depends(get_session), +): + """AI 处理反馈 - 3 步 LLM Pipeline""" + service = FeedbackService(session) + try: + result = await service.process_feedback( + store_name=req.storeName, + employee_number=req.employeeNumber, + asr_text=req.asrText, + session_id=req.sessionId, + device_mac=req.deviceMac, + satisfaction=req.satisfaction, + store_id=req.storeId, + employee_id=req.employeeId, + customer_name=req.customerName, + phone_tail=req.phoneTail, + ) + return {"code": 0, "msg": "success", "data": result} + except LLMProcessingError as e: + logger.error(f"AI 处理失败: {e}") + return {"code": 500, "msg": e.message, "data": None} + except Exception as e: + logger.error(f"处理反馈异常: {e}") + return {"code": 500, "msg": f"处理失败: {str(e)}", "data": None} + + +@router.post("/record") +async def save_record( + req: SaveRecordRequest, + session: Session = Depends(get_session), +): + """保存反馈记录 - H5 前端调用,字段名兼容""" + service = FeedbackService(session) + try: + # 将 camelCase 映射到 domain 层的 snake_case + record_data = { + "store_id": req.storeId or "", + "session_id": req.sessionId, + "employee_id": req.employeeId, + "device_mac": req.deviceMac, + "raw_asr_text": req.rawAsrText, + "cleaned_text": req.cleanedText, + "qa_json": req.qaJson, + "review_long": req.reviewLong, + "review_short": req.reviewShort, + "satisfaction": req.satisfaction, + "customer_name": req.customerName, + "phone_tail": req.phoneTail, + } + record = await service.save_record(record_data) + return { + "code": 0, + "msg": "success", + "data": {"id": record.id}, + } + except Exception as e: + logger.error(f"保存记录失败: {e}") + return {"code": 500, "msg": f"保存失败: {str(e)}", "data": None} + + +@router.post("/device-init") +async def device_init( + req: DeviceInitRequest, + session: Session = Depends(get_session), +): + """设备初始化 - 返回设备 MAC、OTA 信息、agentId、激活码 + + 流程: + 1. 查询门店信息,生成设备 MAC + 2. 服务端调用 Java OTA 获取激活码(设备未绑定时)或 WebSocket URL(已绑定时) + 3. 将 OTA 结果一并返回给 H5 + + 兼容两种调用方式: + 1. H5 旧版: {storeId, employeeId} + 2. 新版: {storeCode, deviceMac} + """ + service = StoreService(session) + + # 确定门店信息 + store = None + if req.storeCode: + try: + store = await service.get_by_store_code(req.storeCode) + except StoreNotFoundError: + return {"code": 404, "msg": f"门店不存在: {req.storeCode}", "data": None} + elif req.storeId: + try: + store = await service.get_by_id(req.storeId) + except StoreNotFoundError: + return {"code": 404, "msg": f"门店不存在: {req.storeId}", "data": None} + else: + return {"code": 400, "msg": "请提供 storeCode 或 storeId", "data": None} + + # 生成/使用 MAC 地址(必须符合标准 MAC 格式 XX:XX:XX:XX:XX:XX,Java OTA 会校验) + mac = req.deviceMac + if not mac: + code_part = store.store_code[-4:] + emp_part = (req.employeeId or "0001").replace("emp", "").zfill(2) + mac = f"FB:{code_part[:2]}:{code_part[2:4]}:{emp_part[:2]}:{code_part[:2]}:{emp_part[-2:]}" + + ws_port = settings.get("xiaozhi.ws_port", 18000) + + # 服务端调用 Java OTA,获取激活码或 WebSocket URL + ota_result = await _call_java_ota(mac) + + return { + "code": 0, + "msg": "success", + "data": { + "deviceMac": mac, + "agentId": store.agent_id, + "storeId": store.id, + "storeName": store.store_name, + "wsPort": ws_port, + "wsPath": "/xiaozhi/v1/voice", + # OTA 结果:包含 activation.code 或 websocket.url + "otaResult": ota_result, + }, + } + + +async def _call_java_ota(device_mac: str) -> Optional[dict]: + """服务端调用 Java OTA 端点,获取激活码或 WebSocket URL + + 这是关键:通过服务端调用避免浏览器 CORS 问题, + 并且由 Java 管理后台生成激活码(存储在 Redis 中), + 这样管理员在智控台输入激活码才能完成绑定。 + """ + manager_api_url = settings.get("xiaozhi.manager_api_url", "http://127.0.0.1:8002") + ota_url = f"{manager_api_url}/xiaozhi/ota/" + + ota_request_body = { + "version": 0, + "uuid": "", + "application": { + "name": "xiaozhi-feedback-h5", + "version": "1.0.0", + "compile_time": "2026-06-10 10:00:00", + "idf_version": "4.4.3", + "elf_sha256": "1234567890abcdef1234567890abcdef1234567890abcdef", + }, + "ota": {"label": "xiaozhi-feedback-h5"}, + "board": { + "type": "反馈H5", + "ssid": "xiaozhi-feedback-h5", + "rssi": 0, + "channel": 0, + "ip": "192.168.1.1", + "mac": device_mac, + }, + "flash_size": 0, + "minimum_free_heap_size": 0, + "mac_address": device_mac, + "chip_model_name": "", + "chip_info": {"model": 0, "cores": 0, "revision": 0, "features": 0}, + "partition_table": [{"label": "", "type": 0, "subtype": 0, "address": 0, "size": 0}], + } + + try: + async with httpx.AsyncClient(timeout=10.0) as client: + resp = await client.post( + ota_url, + headers={ + "Device-Id": device_mac, + "Client-Id": "feedback_client", + "Content-Type": "application/json", + }, + json=ota_request_body, + ) + if resp.status_code == 200: + result = resp.json() + logger.info(f"Java OTA 响应: mac={device_mac}, " + f"has_activation={bool(result.get('activation'))}, " + f"has_websocket={bool(result.get('websocket', {}).get('url'))}") + return result + else: + logger.warning(f"Java OTA 返回非200: status={resp.status_code}, body={resp.text[:200]}") + except httpx.ConnectError: + logger.error(f"Java OTA 连接失败: {ota_url},请确认管理后台 (port 8002) 是否运行") + except Exception as e: + logger.error(f"Java OTA 调用异常: {e}") + return None + + +# ---- OTA 代理 - 解决 H5 跨域问题 ---- + +async def _do_ota_proxy(path: str, request: Request): + """OTA 代理核心逻辑 - 转发到 Java 管理后台 + + H5 前端调用 /api/v1/public/ota/ → feedback-backend → Java 管理后台 + 解决浏览器跨域问题,同时确保激活码在 Java Redis 中正确生成。 + """ + # 优先使用 Java 管理后台 URL(激活码在此生成) + # 回退到 xiaozhi-server HTTP(仅独立模式可用) + manager_api_url = settings.get("xiaozhi.manager_api_url", "") + if manager_api_url: + target_url = f"{manager_api_url}/xiaozhi/ota/{path}" + else: + xiaozhi_http = settings.get("xiaozhi.http_url", "http://127.0.0.1:18003") + target_url = f"{xiaozhi_http}/xiaozhi/ota/{path}" + + # OPTIONS 预检直接放行 + if request.method == "OPTIONS": + return JSONResponse(content={}, status_code=200) + + # 转发请求 + try: + headers = dict(request.headers) + # 移除 hop-by-hop 头 + for h in ["host", "content-length", "transfer-encoding", "connection"]: + headers.pop(h, None) + + body = await request.body() + + async with httpx.AsyncClient(timeout=15.0) as client: + resp = await client.request( + method=request.method, + url=target_url, + headers=headers, + content=body if body else None, + params=dict(request.query_params), + ) + + # 透传响应 + content_type = resp.headers.get("content-type", "") + if content_type.startswith("application/json"): + return JSONResponse(content=resp.json(), status_code=resp.status_code) + else: + from fastapi.responses import Response + return Response(content=resp.content, status_code=resp.status_code, + media_type=content_type) + except Exception as e: + logger.error(f"OTA 代理失败: {e}") + return JSONResponse(content={"error": str(e)}, status_code=502) + + +# 两个路由:/ota/ 和 /ota/{sub_path},覆盖所有情况 +@router.api_route("/ota/", methods=["GET", "POST", "OPTIONS"]) +async def ota_proxy_root(request: Request): + """代理 /xiaozhi/ota/ 根路径""" + return await _do_ota_proxy("", request) + + +@router.api_route("/ota/{path:path}", methods=["GET", "POST", "OPTIONS"]) +async def ota_proxy_path(path: str, request: Request): + """代理 /xiaozhi/ota/{sub_path}""" + return await _do_ota_proxy(path, request) diff --git a/main/feedback-backend/app/interfaces/api/router.py b/main/feedback-backend/app/interfaces/api/router.py new file mode 100644 index 000000000..4607858f6 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/router.py @@ -0,0 +1,34 @@ +"""API 路由汇总""" + +from fastapi import APIRouter + +from .public_controller import router as public_router +from .store_controller import router as store_router +from .employee_controller import router as employee_router +from .feedback_controller import router as feedback_router +from .stats_controller import router as stats_router +from .agent_config_controller import router as agent_config_router +from .auth_controller import router as auth_router +from .crm_controller import router as crm_router +from .agent_chat_controller import router as agent_chat_router +from .appointment_controller import router as appointment_router +from .notification_controller import router as notification_router + +api_router = APIRouter(prefix="/api/v1") + +# 公开接口(无需认证) +api_router.include_router(public_router) + +# 认证接口 +api_router.include_router(auth_router) + +# 后台管理接口(需要认证) +api_router.include_router(store_router) +api_router.include_router(employee_router) +api_router.include_router(feedback_router) +api_router.include_router(stats_router) +api_router.include_router(agent_config_router) +api_router.include_router(crm_router) +api_router.include_router(agent_chat_router) +api_router.include_router(appointment_router) +api_router.include_router(notification_router) diff --git a/main/feedback-backend/app/interfaces/api/stats_controller.py b/main/feedback-backend/app/interfaces/api/stats_controller.py new file mode 100644 index 000000000..ba3be1ef7 --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/stats_controller.py @@ -0,0 +1,97 @@ +"""统计控制器 - 后台管理用""" + +from typing import Optional + +from fastapi import APIRouter, Depends, Query +from sqlalchemy.orm import Session + +from app.application.stats_service import StatsService +from app.infrastructure.persistence.database import get_session +from app.interfaces.api.auth import get_current_user, scoped_store_id + +router = APIRouter(prefix="/stats", tags=["统计分析"]) + + +@router.get("/overview") +async def get_overview( + store_id: Optional[str] = Query(None), + start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"), + end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """统计概览""" + service = StatsService(session) + result = await service.get_overview(scoped_store_id(current_user, store_id), start_date, end_date) + return {"code": 0, "msg": "success", "data": result} + + +@router.get("/daily") +async def get_daily_stats( + store_id: Optional[str] = Query(None), + start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"), + end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """按天统计""" + service = StatsService(session) + result = await service.get_daily_stats(scoped_store_id(current_user, store_id), start_date, end_date) + return {"code": 0, "msg": "success", "data": result} + + +@router.get("/employee-kpi") +async def get_employee_kpi( + store_id: Optional[str] = Query(None), + start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"), + end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """按员工统计好/中/差评 KPI""" + service = StatsService(session) + result = await service.get_employee_kpi(scoped_store_id(current_user, store_id), start_date, end_date) + return {"code": 0, "msg": "success", "data": result} + + +@router.get("/employee-records") +async def get_employee_records( + employee_id: str = Query(...), + satisfaction_group: Optional[str] = Query(None, description="good/middle/bad"), + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), + store_id: Optional[str] = Query(None), + start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"), + end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """查询某员工完整评价列表""" + service = StatsService(session) + result = await service.get_employee_records( + employee_id=employee_id, + store_id=scoped_store_id(current_user, store_id), + satisfaction_group=satisfaction_group, + start_date=start_date, + end_date=end_date, + page=page, + page_size=page_size, + ) + return {"code": 0, "msg": "success", "data": result} + + +@router.get("/by-store") +async def get_store_stats( + start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"), + end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"), + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """按门店统计""" + service = StatsService(session) + store_id = scoped_store_id(current_user) + if store_id: + result = await service.get_single_store_stats(store_id, start_date, end_date) + else: + result = await service.get_store_stats(start_date, end_date) + return {"code": 0, "msg": "success", "data": result} diff --git a/main/feedback-backend/app/interfaces/api/store_controller.py b/main/feedback-backend/app/interfaces/api/store_controller.py new file mode 100644 index 000000000..1d5b7687c --- /dev/null +++ b/main/feedback-backend/app/interfaces/api/store_controller.py @@ -0,0 +1,110 @@ +"""门店管理控制器 - 后台管理用,需要认证""" + +from typing import Optional + +from fastapi import APIRouter, Depends +from pydantic import BaseModel, Field +from sqlalchemy.orm import Session + +from app.application.store_service import StoreService +from app.infrastructure.persistence.database import get_session +from app.interfaces.api.auth import get_current_user, require_super_admin + +router = APIRouter(prefix="/store", tags=["门店管理"]) + + +class CreateStoreRequest(BaseModel): + store_code: str = Field(..., description="门店编码(6位数字)") + store_name: str = Field(..., description="门店名称") + manager: Optional[str] = Field(default=None, description="店长") + shareholders: Optional[str] = Field(default=None, description="股东") + agent_id: Optional[str] = Field(default=None, description="智能体ID") + + +class UpdateStoreRequest(BaseModel): + store_code: Optional[str] = Field(default=None, description="门店编码") + store_name: Optional[str] = Field(default=None, description="门店名称") + manager: Optional[str] = Field(default=None, description="店长") + shareholders: Optional[str] = Field(default=None, description="股东") + agent_id: Optional[str] = Field(default=None, description="智能体ID") + status: Optional[int] = Field(default=None, description="状态") + + +@router.get("/list") +async def list_stores( + page: int = 1, + page_size: int = 20, + store_name: Optional[str] = None, + status: Optional[int] = None, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """分页查询门店列表""" + require_super_admin(current_user) + service = StoreService(session) + result = await service.list_page(page, page_size, store_name, status) + return { + "code": 0, + "msg": "success", + "data": { + "list": [ + { + "id": s.id, + "storeCode": s.store_code, + "storeName": s.store_name, + "manager": s.manager, + "shareholders": s.shareholders, + "agentId": s.agent_id, + "status": s.status, + "createDate": str(s.create_date) if s.create_date else None, + } + for s in result["list"] + ], + "total": result["total"], + "page": result["page"], + "pageSize": result["page_size"], + }, + } + + +@router.post("") +async def create_store( + req: CreateStoreRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """创建门店""" + require_super_admin(current_user) + service = StoreService(session) + store = await service.create_store( + req.store_code, req.store_name, req.manager, req.shareholders, req.agent_id + ) + return {"code": 0, "msg": "success", "data": {"id": store.id}} + + +@router.put("/{store_id}") +async def update_store( + store_id: str, + req: UpdateStoreRequest, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """更新门店""" + require_super_admin(current_user) + service = StoreService(session) + kwargs = {k: v for k, v in req.model_dump().items() if v is not None} + store = await service.update_store(store_id, **kwargs) + return {"code": 0, "msg": "success", "data": {"id": store.id}} + + +@router.post("/delete") +async def delete_store( + store_id: str = None, + current_user: dict = Depends(get_current_user), + session: Session = Depends(get_session), +): + """删除门店""" + require_super_admin(current_user) + service = StoreService(session) + await service.delete_store(store_id) + return {"code": 0, "msg": "success"} diff --git a/main/feedback-backend/app/main.py b/main/feedback-backend/app/main.py new file mode 100644 index 000000000..c11de4330 --- /dev/null +++ b/main/feedback-backend/app/main.py @@ -0,0 +1,110 @@ +"""FastAPI 应用入口""" + +from contextlib import asynccontextmanager + +from fastapi import FastAPI, Request +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse +from fastapi.staticfiles import StaticFiles +from loguru import logger +from pathlib import Path + +from app.infrastructure.persistence.database import SessionFactory, init_database +from app.infrastructure.persistence.models import AdminUserModel +from app.interfaces.api.auth import init_default_admin +from app.interfaces.api.router import api_router +from app.shared.config import settings +from app.shared.exceptions import FeedbackBaseException + + +@asynccontextmanager +async def lifespan(app: FastAPI): + """应用生命周期:启动时初始化""" + logger.info("Feedback Backend starting...") + + # 初始化数据库表(开发模式;生产环境应使用 Alembic 迁移) + try: + init_database() + logger.info("Database tables initialized") + except Exception as e: + logger.warning(f"Database init failed (check DB connection): {e}") + + # 初始化默认管理员 + try: + session = SessionFactory() + init_default_admin(session) + session.close() + except Exception as e: + logger.warning(f"Admin init failed: {e}") + + logger.info(f"Feedback Backend ready - http://{settings.get('server.host', '0.0.0.0')}:{settings.get('server.port', 8009)}") + + yield + + logger.info("Feedback Backend shutdown") + + +def create_app() -> FastAPI: + """创建 FastAPI 应用""" + app = FastAPI( + title="反馈系统后端", + description="客户反馈系统独立后端服务 - DDD 架构", + version="1.0.0", + lifespan=lifespan, + ) + + # CORS 中间件 + cors_origins = settings.get("server.cors_origins", ["*"]) + app.add_middleware( + CORSMiddleware, + allow_origins=cors_origins, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + + # 信任代理头(Nginx 反向代理时需要) + from fastapi.middleware.trustedhost import TrustedHostMiddleware + trusted_hosts = settings.get("server.trusted_hosts", []) + if trusted_hosts: + app.add_middleware( + TrustedHostMiddleware, + allowed_hosts=trusted_hosts, + ) + + # 全局异常处理 + @app.exception_handler(FeedbackBaseException) + async def feedback_exception_handler(request: Request, exc: FeedbackBaseException): + return JSONResponse( + status_code=400, + content={"code": exc.code, "msg": exc.message, "data": None}, + ) + + # 注册 API 路由 + app.include_router(api_router) + + # 挂载 admin-ui 静态文件(如果存在) + admin_ui_dir = Path(__file__).resolve().parent.parent / "admin-ui" + if admin_ui_dir.exists(): + app.mount("/admin", StaticFiles(directory=str(admin_ui_dir), html=True), name="admin-ui") + + # 健康检查 + @app.get("/health") + async def health_check(): + return {"status": "ok", "service": "feedback-backend"} + + return app + + +app = create_app() + + +if __name__ == "__main__": + import uvicorn + + uvicorn.run( + "app.main:app", + host=settings.get("server.host", "0.0.0.0"), + port=settings.get("server.port", 8009), + reload=settings.get("server.debug", True), + ) diff --git a/main/feedback-backend/app/shared/__init__.py b/main/feedback-backend/app/shared/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/app/shared/config.py b/main/feedback-backend/app/shared/config.py new file mode 100644 index 000000000..9dbf8ec54 --- /dev/null +++ b/main/feedback-backend/app/shared/config.py @@ -0,0 +1,186 @@ +"""配置加载模块 - 从 config.yaml 读取配置,支持环境变量覆盖""" + +import os +from pathlib import Path +from typing import Any + +import yaml + + +class Settings: + """全局配置,只读访问""" + + _instance = None + _config: dict = {} + + def __new__(cls): + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + @classmethod + def load(cls, config_path: str | None = None) -> "Settings": + """加载配置文件,支持环境变量覆盖""" + instance = cls() + + # 默认配置路径 + if config_path is None: + base_dir = Path(__file__).resolve().parent.parent.parent # feedback-backend/ + config_path = str(base_dir / "config.yaml") + + # 读取主配置 + with open(config_path, "r", encoding="utf-8") as f: + instance._config = yaml.safe_load(f) or {} + + # 读取自定义覆盖配置 + custom_path = Path(config_path).parent / "data" / ".config.yaml" + if custom_path.exists(): + with open(custom_path, "r", encoding="utf-8") as f: + custom = yaml.safe_load(f) or {} + instance._config = _deep_merge(instance._config, custom) + + # 环境变量覆盖(FEEDBACK_ 前缀) + instance._apply_env_overrides() + + return instance + + def _apply_env_overrides(self): + """环境变量覆盖:FEEDBACK_DB_HOST -> database.host""" + env_map = { + "FEEDBACK_DB_HOST": ("database", "host"), + "FEEDBACK_DB_PORT": ("database", "port"), + "FEEDBACK_DB_USER": ("database", "username"), + "FEEDBACK_DB_PASSWORD": ("database", "password"), + "FEEDBACK_DB_NAME": ("database", "database"), + "FEEDBACK_SERVER_HOST": ("server", "host"), + "FEEDBACK_SERVER_PORT": ("server", "port"), + "FEEDBACK_LLM_PROVIDER": ("llm", "provider"), + "FEEDBACK_AUTH_SECRET": ("auth", "secret_key"), + "FEEDBACK_ADMIN_USER": ("admin", "username"), + "FEEDBACK_ADMIN_PASSWORD": ("admin", "password"), + "FEEDBACK_XIAOZHI_WS_URL": ("xiaozhi", "ws_url"), + "FEEDBACK_XIAOZHI_HTTP_URL": ("xiaozhi", "http_url"), + "FEEDBACK_XIAOZHI_MANAGER_API_URL": ("xiaozhi", "manager_api_url"), + } + for env_key, path in env_map.items(): + value = os.environ.get(env_key) + if value is not None: + _set_nested(self._config, path, value) + + provider = self.get("llm.provider", "openai") + llm_env_map = { + "FEEDBACK_LLM_API_KEY": "api_key", + "FEEDBACK_LLM_BASE_URL": "base_url", + "FEEDBACK_LLM_MODEL": "model", + } + for env_key, field in llm_env_map.items(): + value = os.environ.get(env_key) + if value is not None: + _set_nested(self._config, ("llm", provider, field), value) + + for provider_name in ("openai", "dashscope", "deepseek"): + prefix = f"FEEDBACK_{provider_name.upper()}" + for suffix, field in (("API_KEY", "api_key"), ("BASE_URL", "base_url"), ("MODEL", "model")): + value = os.environ.get(f"{prefix}_{suffix}") + if value is not None: + _set_nested(self._config, ("llm", provider_name, field), value) + + # ---- 便捷属性 ---- + + @property + def server(self) -> dict: + return self._config.get("server", {}) + + @property + def database(self) -> dict: + return self._config.get("database", {}) + + @property + def auth(self) -> dict: + return self._config.get("auth", {}) + + @property + def admin(self) -> dict: + return self._config.get("admin", {}) + + @property + def llm(self) -> dict: + return self._config.get("llm", {}) + + @property + def agent(self) -> dict: + return self._config.get("agent", {}) + + @property + def xiaozhi(self) -> dict: + return self._config.get("xiaozhi", {}) + + @property + def logging(self) -> dict: + return self._config.get("logging", {}) + + @property + def database_url(self) -> str: + """构建 SQLAlchemy 连接字符串""" + db = self.database + return ( + f"mysql+pymysql://{db['username']}:{db['password']}" + f"@{db['host']}:{db['port']}/{db['database']}" + f"?charset={db.get('charset', 'utf8mb4')}" + ) + + @property + def database_url_async(self) -> str: + """构建异步 SQLAlchemy 连接字符串""" + return self.database_url.replace("mysql+pymysql", "mysql+aiomysql") + + def get(self, key_path: str, default: Any = None) -> Any: + """点号路径访问:settings.get('server.port', 8009)""" + keys = key_path.split(".") + value = self._config + for key in keys: + if isinstance(value, dict): + value = value.get(key) + else: + return default + if value is None: + return default + return value + + +def _deep_merge(base: dict, override: dict) -> dict: + """递归合并字典,override 覆盖 base""" + result = base.copy() + for key, value in override.items(): + if key in result and isinstance(result[key], dict) and isinstance(value, dict): + result[key] = _deep_merge(result[key], value) + else: + result[key] = value + return result + + +def _set_nested(config: dict, path: tuple, value: str): + """设置嵌套字典值""" + current = config + for key in path[:-1]: + if key not in current or not isinstance(current[key], dict): + current[key] = {} + current = current[key] + # 类型转换:port 等数字字段 + current[path[-1]] = _auto_type(value) + + +def _auto_type(value: str): + """自动类型推断""" + if value.isdigit(): + return int(value) + if value.lower() in ("true", "false"): + return value.lower() == "true" + try: + return float(value) + except ValueError: + return value + + +# 全局单例 +settings = Settings.load() diff --git a/main/feedback-backend/app/shared/exceptions.py b/main/feedback-backend/app/shared/exceptions.py new file mode 100644 index 000000000..787fa0b94 --- /dev/null +++ b/main/feedback-backend/app/shared/exceptions.py @@ -0,0 +1,88 @@ +"""自定义异常体系""" + + +class FeedbackBaseException(Exception): + """反馈系统基础异常""" + + def __init__(self, message: str, code: str = "UNKNOWN_ERROR"): + self.message = message + self.code = code + super().__init__(message) + + +# ---- 领域异常 ---- + +class StoreNotFoundError(FeedbackBaseException): + """门店不存在""" + + def __init__(self, store_code: str): + super().__init__(f"门店不存在: {store_code}", "STORE_NOT_FOUND") + + +class EmployeeNotFoundError(FeedbackBaseException): + """员工不存在""" + + def __init__(self, employee_id: str): + super().__init__(f"员工不存在: {employee_id}", "EMPLOYEE_NOT_FOUND") + + +class AgentConfigNotFoundError(FeedbackBaseException): + """智能体配置不存在""" + + def __init__(self, agent_id: str): + super().__init__(f"智能体配置不存在: {agent_id}", "AGENT_CONFIG_NOT_FOUND") + + +# ---- 应用异常 ---- + +class LLMProcessingError(FeedbackBaseException): + """LLM 处理失败""" + + def __init__(self, detail: str): + super().__init__(f"AI 处理失败: {detail}", "LLM_PROCESSING_ERROR") + + +class PromptTemplateError(FeedbackBaseException): + """提示词模板错误""" + + def __init__(self, template_name: str, detail: str): + super().__init__(f"提示词模板 {template_name} 错误: {detail}", "PROMPT_TEMPLATE_ERROR") + + +class RecordSaveError(FeedbackBaseException): + """记录保存失败""" + + def __init__(self, detail: str): + super().__init__(f"记录保存失败: {detail}", "RECORD_SAVE_ERROR") + + +# ---- 基础设施异常 ---- + +class DatabaseConnectionError(FeedbackBaseException): + """数据库连接失败""" + + def __init__(self, detail: str): + super().__init__(f"数据库连接失败: {detail}", "DATABASE_CONNECTION_ERROR") + + +class AuthenticationError(FeedbackBaseException): + """认证失败""" + + def __init__(self, detail: str = "认证失败"): + super().__init__(detail, "AUTHENTICATION_ERROR") + + +class AuthorizationError(FeedbackBaseException): + """权限不足""" + + def __init__(self, detail: str = "权限不足"): + super().__init__(detail, "AUTHORIZATION_ERROR") + + +# ---- 验证异常 ---- + +class ValidationError(FeedbackBaseException): + """数据验证失败""" + + def __init__(self, detail: str): + super().__init__(detail, "VALIDATION_ERROR") diff --git a/main/feedback-backend/app/shared/mekai66.py b/main/feedback-backend/app/shared/mekai66.py new file mode 100644 index 000000000..fbafcd446 --- /dev/null +++ b/main/feedback-backend/app/shared/mekai66.py @@ -0,0 +1,74 @@ +"""麦凯66客户档案字段。 + +公开资料中的 Mackay 66 Customer Profile 常见版本会按客户个人、家庭、公司、 +兴趣、关系、业务往来等维度采集信息。这里结合美容养生门店做本地化字段。 +""" + +MEKAI66_FIELDS = [ + {"key": "name", "label": "姓名", "category": "基础信息"}, + {"key": "nickname", "label": "昵称/常用称呼", "category": "基础信息"}, + {"key": "gender", "label": "性别", "category": "基础信息"}, + {"key": "birthday", "label": "生日", "category": "基础信息"}, + {"key": "age", "label": "年龄", "category": "基础信息"}, + {"key": "hometown", "label": "籍贯/老家", "category": "基础信息"}, + {"key": "address", "label": "居住地址/小区", "category": "基础信息"}, + {"key": "phone", "label": "手机号", "category": "基础信息"}, + {"key": "wechat", "label": "微信号", "category": "基础信息"}, + {"key": "education", "label": "学历", "category": "基础信息"}, + {"key": "marital_status", "label": "婚姻状态", "category": "家庭关系"}, + {"key": "spouse_name", "label": "配偶姓名", "category": "家庭关系"}, + {"key": "spouse_job", "label": "配偶职业", "category": "家庭关系"}, + {"key": "children", "label": "子女情况", "category": "家庭关系"}, + {"key": "children_school", "label": "子女学校/年级", "category": "家庭关系"}, + {"key": "parents", "label": "父母情况", "category": "家庭关系"}, + {"key": "family_anniversary", "label": "家庭纪念日", "category": "家庭关系"}, + {"key": "family_focus", "label": "家庭关注点", "category": "家庭关系"}, + {"key": "pet", "label": "宠物", "category": "家庭关系"}, + {"key": "emergency_contact", "label": "紧急联系人", "category": "家庭关系"}, + {"key": "company", "label": "公司/单位", "category": "工作事业"}, + {"key": "industry", "label": "行业", "category": "工作事业"}, + {"key": "position", "label": "职位", "category": "工作事业"}, + {"key": "job_responsibility", "label": "工作职责", "category": "工作事业"}, + {"key": "income_level", "label": "收入水平", "category": "工作事业"}, + {"key": "work_pressure", "label": "工作压力", "category": "工作事业"}, + {"key": "work_schedule", "label": "作息/上下班时间", "category": "工作事业"}, + {"key": "business_needs", "label": "事业需求/目标", "category": "工作事业"}, + {"key": "decision_style", "label": "决策风格", "category": "工作事业"}, + {"key": "social_circle", "label": "社交圈", "category": "工作事业"}, + {"key": "hobbies", "label": "兴趣爱好", "category": "生活方式"}, + {"key": "sports", "label": "运动习惯", "category": "生活方式"}, + {"key": "travel", "label": "旅游偏好", "category": "生活方式"}, + {"key": "diet", "label": "饮食偏好", "category": "生活方式"}, + {"key": "tea_drink", "label": "茶饮偏好", "category": "生活方式"}, + {"key": "music", "label": "音乐偏好", "category": "生活方式"}, + {"key": "reading", "label": "阅读/学习偏好", "category": "生活方式"}, + {"key": "shopping", "label": "购物偏好", "category": "生活方式"}, + {"key": "brands", "label": "喜欢品牌", "category": "生活方式"}, + {"key": "taboo_topics", "label": "忌讳话题", "category": "生活方式"}, + {"key": "consumption_power", "label": "消费能力", "category": "消费习惯"}, + {"key": "consumption_frequency", "label": "消费频次", "category": "消费习惯"}, + {"key": "budget", "label": "预算区间", "category": "消费习惯"}, + {"key": "preferred_projects", "label": "偏好项目", "category": "消费习惯"}, + {"key": "disliked_projects", "label": "不喜欢项目", "category": "消费习惯"}, + {"key": "price_sensitivity", "label": "价格敏感度", "category": "消费习惯"}, + {"key": "promotion_preference", "label": "优惠偏好", "category": "消费习惯"}, + {"key": "referral_willingness", "label": "转介绍意愿", "category": "消费习惯"}, + {"key": "decision_factor", "label": "购买决策因素", "category": "消费习惯"}, + {"key": "loss_risk", "label": "流失风险点", "category": "消费习惯"}, + {"key": "skin_type", "label": "皮肤类型", "category": "健康美容"}, + {"key": "beauty_concerns", "label": "美容关注点", "category": "健康美容"}, + {"key": "body_discomfort", "label": "身体不适", "category": "健康美容"}, + {"key": "chronic_disease", "label": "慢性病/疾病史", "category": "健康美容"}, + {"key": "allergy", "label": "过敏史", "category": "健康美容"}, + {"key": "contraindication", "label": "护理禁忌", "category": "健康美容"}, + {"key": "sleep", "label": "睡眠情况", "category": "健康美容"}, + {"key": "menstruation", "label": "经期/备孕/孕产情况", "category": "健康美容"}, + {"key": "preferred_employee", "label": "偏好技师", "category": "服务偏好"}, + {"key": "service_strength", "label": "服务力度偏好", "category": "服务偏好"}, + {"key": "chat_preference", "label": "聊天偏好", "category": "服务偏好"}, + {"key": "room_preference", "label": "房间/环境偏好", "category": "服务偏好"}, + {"key": "temperature_preference", "label": "温度偏好", "category": "服务偏好"}, + {"key": "appointment_preference", "label": "预约时间偏好", "category": "服务偏好"}, + {"key": "last_important_event", "label": "最近重要事件", "category": "关系维护"}, + {"key": "next_followup", "label": "下次跟进重点", "category": "关系维护"}, +] diff --git a/main/feedback-backend/app/shared/utils.py b/main/feedback-backend/app/shared/utils.py new file mode 100644 index 000000000..82a5bf58b --- /dev/null +++ b/main/feedback-backend/app/shared/utils.py @@ -0,0 +1,74 @@ +"""共享工具函数""" + +import re +import uuid +from datetime import datetime +from typing import Any + + +def generate_id() -> str: + """生成 64 位字符串 ID(与 Java ASSIGN_ID 策略兼容)""" + return str(uuid.uuid4()).replace("-", "")[:64] + + +def now() -> datetime: + """获取当前时间""" + return datetime.now() + + +def is_valid_store_code(code: str) -> bool: + """验证门店编码:6 位数字""" + return bool(re.match(r"^\d{6}$", code)) + + +def sanitize_text(text: str) -> str: + """清理文本:去除首尾空白,压缩连续空白""" + if not text: + return "" + text = text.strip() + text = re.sub(r"\s+", " ", text) + return text + + +def parse_satisfaction(value: str) -> dict: + """解析满意度值,返回标准化的满意度信息""" + mapping = { + "very_satisfied": {"level": "very_satisfied", "text": "非常满意", "score": 4}, + "satisfied": {"level": "satisfied", "text": "满意", "score": 3}, + "unsatisfied": {"level": "unsatisfied", "text": "不满意", "score": 2}, + "very_bad": {"level": "very_bad", "text": "很差", "score": 1}, + } + return mapping.get(value, {"level": "unknown", "text": "未知", "score": 0}) + + +def should_generate_review(satisfaction: str) -> bool: + """是否应生成点评(仅满意时生成)""" + return satisfaction in ("very_satisfied", "satisfied") + + +def load_prompt_template(file_path: str) -> str: + """加载提示词模板文件""" + with open(file_path, "r", encoding="utf-8") as f: + return f.read() + + +def render_prompt(template: str, **kwargs) -> str: + """渲染提示词模板,支持 {{变量名}} 语法""" + result = template + for key, value in kwargs.items(): + result = result.replace("{{" + key + "}}", str(value)) + return result + + +def paginate(items: list, page: int = 1, page_size: int = 20) -> dict: + """通用分页""" + total = len(items) + start = (page - 1) * page_size + end = start + page_size + return { + "list": items[start:end], + "total": total, + "page": page, + "page_size": page_size, + "total_pages": (total + page_size - 1) // page_size if total > 0 else 0, + } diff --git a/main/feedback-backend/cli.py b/main/feedback-backend/cli.py new file mode 100644 index 000000000..7cb18bca3 --- /dev/null +++ b/main/feedback-backend/cli.py @@ -0,0 +1,834 @@ +#!/usr/bin/env python3 +"""Feedback/CRM CLI. + +面向人工和 AI Agent 的命令行入口,统一调用后台 HTTP API。 + +常用示例: + python cli.py login --username admin --password admin123 --raw-token + python cli.py --token crm overview + python cli.py --token crm member-list --keyword 1234 + python cli.py --token stats employee-kpi + python cli.py --token crm issue-fix --issue-id --result 已处理 + +环境变量: + FEEDBACK_API_BASE=http://127.0.0.1:8007/api/v1 + FEEDBACK_TOKEN= +""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.parse +import urllib.request + +DEFAULT_BASE_URL = os.environ.get("FEEDBACK_API_BASE", "http://127.0.0.1:8007/api/v1") +DEFAULT_TOKEN = os.environ.get("FEEDBACK_TOKEN", "") + + +# ---- HTTP / IO ---- + +def request(method, path, token="", data=None, params=None, base_url=DEFAULT_BASE_URL): + url = base_url.rstrip("/") + path + if params: + query = urllib.parse.urlencode({k: v for k, v in params.items() if v not in (None, "")}) + if query: + url += "?" + query + body = None + headers = {"Content-Type": "application/json"} + if token: + headers["Authorization"] = f"Bearer {token}" + if data is not None: + body = json.dumps(data, ensure_ascii=False).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=60) as resp: + text = resp.read().decode("utf-8") + return json.loads(text) if text else {} + except urllib.error.HTTPError as e: + text = e.read().decode("utf-8", errors="replace") + raise SystemExit(f"HTTP {e.code}: {text}") + except urllib.error.URLError as e: + raise SystemExit(f"请求失败: {e}") + + +def print_json(data): + print(json.dumps(data, ensure_ascii=False, indent=2)) + + +def require_token(args): + token = args.token or DEFAULT_TOKEN + if not token: + raise SystemExit("缺少 token:请传 --token 或设置 FEEDBACK_TOKEN,或先执行 login") + return token + + +def load_json_file(path): + if not path: + return {} + with open(path, "r", encoding="utf-8") as f: + return json.load(f) + + +def merge_payload(args, base=None): + payload = dict(base or {}) + payload.update(load_json_file(getattr(args, "json_file", ""))) + return {k: v for k, v in payload.items() if v not in (None, "", [])} + + +def split_list(value): + if not value: + return [] + return [x.strip() for x in value.replace(",", ",").split(",") if x.strip()] + + +# ---- Basic ---- + +def cmd_login(args): + data = request("POST", "/auth/login", data={"username": args.username, "password": args.password}, base_url=args.base_url) + if args.raw_token: + print(data.get("access_token", "")) + elif args.export: + print(f"$env:FEEDBACK_TOKEN='{data.get('access_token', '')}'") + else: + print_json(data) + + +def cmd_health(args): + base = args.base_url.rsplit("/api/v1", 1)[0] + print_json(request("GET", "/health", base_url=base)) + + +# ---- CRM ---- + +def cmd_crm_overview(args): + print_json(request("GET", "/crm/overview", token=require_token(args), base_url=args.base_url)) + + +def cmd_crm_mekai66(args): + print_json(request("GET", "/crm/mekai66-fields", token=require_token(args), base_url=args.base_url)) + + +def cmd_member_list(args): + print_json(request("GET", "/crm/member/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "keyword": args.keyword, "status": args.status, + })) + + +def cmd_member_detail(args): + print_json(request("GET", f"/crm/member/{args.member_id}", token=require_token(args), base_url=args.base_url)) + + +def cmd_member_create(args): + payload = merge_payload(args, { + "storeId": args.store_id, + "name": args.name, + "phone": args.phone, + "wechat": args.wechat, + "level": args.level, + "beautyConcerns": split_list(args.beauty), + "healthIssues": split_list(args.health), + "allergies": args.allergies, + "notes": args.notes, + }) + print_json(request("POST", "/crm/member", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_member_update(args): + payload = merge_payload(args, { + "name": args.name, + "phone": args.phone, + "wechat": args.wechat, + "level": args.level, + "beautyConcerns": split_list(args.beauty), + "healthIssues": split_list(args.health), + "allergies": args.allergies, + "notes": args.notes, + "status": args.status, + }) + print_json(request("PUT", f"/crm/member/{args.member_id}", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_visit_list(args): + print_json(request("GET", "/crm/visit/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "member_id": args.member_id, + })) + + +def cmd_visit_create(args): + payload = merge_payload(args, { + "storeId": args.store_id, + "memberId": args.member_id, + "employeeId": args.employee_id, + "arriveAt": args.arrive_at, + "leaveAt": args.leave_at, + "serviceItems": split_list(args.items), + "consumptionAmount": args.amount, + "satisfaction": args.satisfaction, + "notes": args.notes, + }) + print_json(request("POST", "/crm/visit", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_visit_update(args): + payload = merge_payload(args, { + "memberId": args.member_id, + "employeeId": args.employee_id, + "arriveAt": args.arrive_at, + "leaveAt": args.leave_at, + "serviceItems": split_list(args.items), + "consumptionAmount": args.amount, + "satisfaction": args.satisfaction, + "notes": args.notes, + }) + print_json(request("PUT", f"/crm/visit/{args.visit_id}", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_account_list(args): + print_json(request("GET", "/crm/account/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "member_id": args.member_id, "status": args.status, + })) + + +def cmd_account_create(args): + payload = merge_payload(args, { + "storeId": args.store_id, + "memberId": args.member_id, + "accountType": args.account_type, + "cardName": args.card_name, + "totalAmount": args.amount, + "totalCount": args.count, + "validStart": args.valid_start, + "validEnd": args.valid_end, + "notes": args.notes, + }) + print_json(request("POST", "/crm/account", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_account_consume(args): + payload = merge_payload(args, { + "amount": args.amount, + "countChange": args.count, + "visitId": args.visit_id, + "notes": args.notes, + }) + print_json(request("POST", f"/crm/account/{args.account_id}/consume", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_transactions(args): + print_json(request("GET", "/crm/account/transactions", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "account_id": args.account_id, "member_id": args.member_id, + })) + + +def cmd_body_status_list(args): + print_json(request("GET", "/crm/body-status/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "member_id": args.member_id, + })) + + +def cmd_body_status_create(args): + payload = merge_payload(args, { + "storeId": args.store_id, + "memberId": args.member_id, + "visitId": args.visit_id, + "memberProductId": args.member_product_id, + "weight": args.weight, + "waistline": args.waistline, + "painLevel": args.pain_level, + "sleepQuality": args.sleep_quality, + "skinStatus": args.skin_status, + "notes": args.notes, + }) + print_json(request("POST", "/crm/body-status", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_product_list(args): + print_json(request("GET", "/crm/product/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "keyword": args.keyword, "category": args.category, "status": args.status, + })) + + +def cmd_product_create(args): + payload = merge_payload(args, { + "storeId": args.store_id, + "productName": args.product_name, + "productType": args.product_type, + "category": args.category, + "price": args.price, + "defaultCount": args.default_count, + "description": args.description, + }) + print_json(request("POST", "/crm/product", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_member_product_list(args): + print_json(request("GET", "/crm/member-product/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "member_id": args.member_id, "status": args.status, + })) + + +def cmd_product_purchase(args): + payload = merge_payload(args, { + "storeId": args.store_id, + "memberId": args.member_id, + "productId": args.product_id, + "productName": args.product_name, + "totalCount": args.total_count, + "totalAmount": args.total_amount, + "validStart": args.valid_start, + "validEnd": args.valid_end, + "notes": args.notes, + }) + print_json(request("POST", "/crm/member-product/purchase", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_product_consume(args): + payload = merge_payload(args, { + "consumeCount": args.consume_count, + "consumeAmount": args.consume_amount, + "visitId": args.visit_id, + "notes": args.notes, + }) + print_json(request("POST", f"/crm/member-product/{args.member_product_id}/consume", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_product_consumes(args): + print_json(request("GET", "/crm/product-consume/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "member_id": args.member_id, "member_product_id": args.member_product_id, + })) + + +def cmd_card_close(args): + payload = merge_payload(args, { + "accountId": args.account_id, + "reason": args.reason, + "refundAmount": args.refund_amount, + "feedbackRecordId": args.feedback_id, + "assignedTo": args.assigned_to, + "handleNotes": args.notes, + }) + print_json(request("POST", "/crm/card-close", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_card_close_list(args): + print_json(request("GET", "/crm/card-close/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "member_id": args.member_id, + })) + + +def cmd_suggestion_list(args): + print_json(request("GET", "/crm/suggestion/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "status": args.status, + })) + + +def cmd_suggestion_create(args): + payload = merge_payload(args, { + "storeId": args.store_id, + "memberId": args.member_id, + "feedbackRecordId": args.feedback_id, + "content": args.content, + "category": args.category, + }) + print_json(request("POST", "/crm/suggestion", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_suggestion_status(args): + payload = merge_payload(args, { + "status": args.status, + "handleNotes": args.notes, + "rejectedReason": args.rejected_reason, + }) + print_json(request("POST", f"/crm/suggestion/{args.suggestion_id}/status", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_issue_list(args): + print_json(request("GET", "/crm/issue/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "status": args.status, + })) + + +def cmd_issue_create(args): + payload = merge_payload(args, { + "storeId": args.store_id, + "memberId": args.member_id, + "feedbackRecordId": args.feedback_id, + "cardCloseId": args.card_close_id, + "title": args.title, + "description": args.description, + "severity": args.severity, + "category": args.category, + "assignedTo": args.assigned_to, + "fixPlan": args.fix_plan, + "fixDeadline": args.fix_deadline, + }) + print_json(request("POST", "/crm/issue", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_issue_update(args): + payload = merge_payload(args, { + "title": args.title, + "description": args.description, + "severity": args.severity, + "category": args.category, + "status": args.status, + "assignedTo": args.assigned_to, + "fixPlan": args.fix_plan, + "fixResult": args.fix_result, + }) + print_json(request("PUT", f"/crm/issue/{args.issue_id}", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_issue_fix(args): + payload = merge_payload(args, {"status": "fixed", "fixResult": args.result, "fixPlan": args.plan}) + print_json(request("PUT", f"/crm/issue/{args.issue_id}", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_issue_close(args): + payload = merge_payload(args, {"status": "closed", "fixResult": args.result}) + print_json(request("PUT", f"/crm/issue/{args.issue_id}", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +def cmd_feedback_bind(args): + payload = merge_payload(args, { + "memberId": args.member_id, + "visitId": args.visit_id, + "cardCloseId": args.card_close_id, + }) + print_json(request("POST", f"/crm/feedback/{args.feedback_id}/bind", token=require_token(args), base_url=args.base_url, data={"data": payload})) + + +# ---- Feedback / Store / Employee / Stats ---- + +def cmd_record_list(args): + print_json(request("GET", "/record/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, + "page_size": args.page_size, + "store_id": args.store_id, + "employee_id": args.employee_id, + "satisfaction": args.satisfaction, + "start_date": args.start_date, + "end_date": args.end_date, + })) + + +def cmd_feedback_process(args): + payload = merge_payload(args, { + "storeName": args.store_name, + "employeeNumber": args.employee_number, + "asrText": args.text, + "sessionId": args.session_id, + "deviceMac": args.device_mac, + "satisfaction": args.satisfaction, + "storeId": args.store_id, + "employeeId": args.employee_id, + }) + print_json(request("POST", "/public/process", base_url=args.base_url, data=payload)) + + +def cmd_store_list(args): + print_json(request("GET", "/store/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "keyword": args.keyword, + })) + + +def cmd_employee_list(args): + print_json(request("GET", "/employee/list", token=require_token(args), base_url=args.base_url, params={ + "page": args.page, "page_size": args.page_size, "store_id": args.store_id, + })) + + +def cmd_employee_kpi(args): + print_json(request("GET", "/stats/employee-kpi", token=require_token(args), base_url=args.base_url, params={ + "start_date": args.start_date, "end_date": args.end_date, + })) + + +def cmd_employee_records(args): + print_json(request("GET", "/stats/employee-records", token=require_token(args), base_url=args.base_url, params={ + "employee_id": args.employee_id, + "satisfaction_group": args.group, + "page": args.page, + "page_size": args.page_size, + })) + + +def cmd_raw(args): + data = load_json_file(args.json_file) if args.json_file else None + print_json(request(args.method, args.path, token=(args.token or DEFAULT_TOKEN), data=data, base_url=args.base_url)) + + +# ---- Parser ---- + +def add_common(parser): + parser.add_argument("--base-url", default=DEFAULT_BASE_URL, help=f"API base URL,默认 {DEFAULT_BASE_URL}") + parser.add_argument("--token", default=DEFAULT_TOKEN, help="JWT token;也可用 FEEDBACK_TOKEN") + + +def add_json_file(parser): + parser.add_argument("--json-file", default="", help="从 JSON 文件读取 data,并覆盖/补充命令行参数") + + +def add_page(parser): + parser.add_argument("--page", type=int, default=1) + parser.add_argument("--page-size", type=int, default=20) + + +def build_parser(): + parser = argparse.ArgumentParser(description="Feedback/CRM CLI") + add_common(parser) + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("login", help="登录并输出 token") + p.add_argument("--username", required=True) + p.add_argument("--password", required=True) + p.add_argument("--raw-token", action="store_true", help="只输出 token,便于脚本使用") + p.add_argument("--export", action="store_true", help="输出 PowerShell 环境变量设置语句") + p.set_defaults(func=cmd_login) + + p = sub.add_parser("health", help="健康检查") + p.set_defaults(func=cmd_health) + + p = sub.add_parser("raw", help="原始 HTTP 调用,高级/AI 用") + p.add_argument("--method", default="GET", choices=["GET", "POST", "PUT", "DELETE"]) + p.add_argument("--path", required=True, help="例如 /crm/overview") + p.add_argument("--json-file", default="") + p.set_defaults(func=cmd_raw) + + crm = sub.add_parser("crm", help="CRM 命令") + crm_sub = crm.add_subparsers(dest="crm_command", required=True) + + p = crm_sub.add_parser("overview", help="CRM 看板") + p.set_defaults(func=cmd_crm_overview) + + p = crm_sub.add_parser("mekai66-fields", help="查看麦凯66字段") + p.set_defaults(func=cmd_crm_mekai66) + + p = crm_sub.add_parser("member-list", help="客户列表") + p.add_argument("--keyword", default="") + p.add_argument("--status", type=int) + add_page(p) + p.set_defaults(func=cmd_member_list) + + p = crm_sub.add_parser("member-detail", help="客户详情") + p.add_argument("--member-id", required=True) + p.set_defaults(func=cmd_member_detail) + + p = crm_sub.add_parser("member-create", help="创建客户") + add_json_file(p) + p.add_argument("--store-id", default="") + p.add_argument("--name", default="") + p.add_argument("--phone", default="") + p.add_argument("--wechat", default="") + p.add_argument("--level", default="") + p.add_argument("--beauty", default="", help="逗号分隔") + p.add_argument("--health", default="", help="逗号分隔") + p.add_argument("--allergies", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_member_create) + + p = crm_sub.add_parser("member-update", help="更新客户") + add_json_file(p) + p.add_argument("--member-id", required=True) + p.add_argument("--name", default="") + p.add_argument("--phone", default="") + p.add_argument("--wechat", default="") + p.add_argument("--level", default="") + p.add_argument("--beauty", default="") + p.add_argument("--health", default="") + p.add_argument("--allergies", default="") + p.add_argument("--notes", default="") + p.add_argument("--status", type=int) + p.set_defaults(func=cmd_member_update) + + p = crm_sub.add_parser("visit-list", help="到店记录列表") + p.add_argument("--member-id", default="") + add_page(p) + p.set_defaults(func=cmd_visit_list) + + p = crm_sub.add_parser("visit-create", help="创建到店记录") + add_json_file(p) + p.add_argument("--store-id", default="") + p.add_argument("--member-id", default="") + p.add_argument("--employee-id", default="") + p.add_argument("--arrive-at", default="") + p.add_argument("--leave-at", default="") + p.add_argument("--items", default="") + p.add_argument("--amount", default="0") + p.add_argument("--satisfaction", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_visit_create) + + p = crm_sub.add_parser("visit-update", help="更新到店记录") + add_json_file(p) + p.add_argument("--visit-id", required=True) + p.add_argument("--member-id", default="") + p.add_argument("--employee-id", default="") + p.add_argument("--arrive-at", default="") + p.add_argument("--leave-at", default="") + p.add_argument("--items", default="") + p.add_argument("--amount", default="") + p.add_argument("--satisfaction", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_visit_update) + + p = crm_sub.add_parser("account-list", help="账户列表") + p.add_argument("--member-id", default="") + p.add_argument("--status", type=int) + add_page(p) + p.set_defaults(func=cmd_account_list) + + p = crm_sub.add_parser("account-create", help="开卡/建账户") + add_json_file(p) + p.add_argument("--store-id", default="") + p.add_argument("--member-id", default="") + p.add_argument("--account-type", default="balance") + p.add_argument("--card-name", default="") + p.add_argument("--amount", default="0") + p.add_argument("--count", default="0") + p.add_argument("--valid-start", default="") + p.add_argument("--valid-end", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_account_create) + + p = crm_sub.add_parser("account-consume", help="账户消费") + add_json_file(p) + p.add_argument("--account-id", required=True) + p.add_argument("--amount", default="0") + p.add_argument("--count", default="0") + p.add_argument("--visit-id", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_account_consume) + + p = crm_sub.add_parser("transactions", help="账户流水") + p.add_argument("--account-id", default="") + p.add_argument("--member-id", default="") + add_page(p) + p.set_defaults(func=cmd_transactions) + + p = crm_sub.add_parser("body-status-list", help="身体变化记录") + p.add_argument("--member-id", default="") + add_page(p) + p.set_defaults(func=cmd_body_status_list) + + p = crm_sub.add_parser("body-status-create", help="创建身体变化记录") + add_json_file(p) + p.add_argument("--store-id", default="") + p.add_argument("--member-id", default="") + p.add_argument("--visit-id", default="") + p.add_argument("--member-product-id", default="") + p.add_argument("--weight", default="") + p.add_argument("--waistline", default="") + p.add_argument("--pain-level", default="") + p.add_argument("--sleep-quality", default="") + p.add_argument("--skin-status", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_body_status_create) + + p = crm_sub.add_parser("product-list", help="产品/套餐列表") + p.add_argument("--keyword", default="") + p.add_argument("--category", default="") + p.add_argument("--status", type=int) + add_page(p) + p.set_defaults(func=cmd_product_list) + + p = crm_sub.add_parser("product-create", help="创建产品/套餐") + add_json_file(p) + p.add_argument("--store-id", default="") + p.add_argument("--product-name", default="") + p.add_argument("--product-type", default="package") + p.add_argument("--category", default="") + p.add_argument("--price", default="0") + p.add_argument("--default-count", default="1") + p.add_argument("--description", default="") + p.set_defaults(func=cmd_product_create) + + p = crm_sub.add_parser("member-product-list", help="客户已购产品/套餐") + p.add_argument("--member-id", default="") + p.add_argument("--status", type=int) + add_page(p) + p.set_defaults(func=cmd_member_product_list) + + p = crm_sub.add_parser("product-purchase", help="客户购买产品/套餐") + add_json_file(p) + p.add_argument("--store-id", default="") + p.add_argument("--member-id", default="") + p.add_argument("--product-id", default="") + p.add_argument("--product-name", default="") + p.add_argument("--total-count", default="0") + p.add_argument("--total-amount", default="0") + p.add_argument("--valid-start", default="") + p.add_argument("--valid-end", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_product_purchase) + + p = crm_sub.add_parser("product-consume", help="消费客户产品/套餐") + add_json_file(p) + p.add_argument("--member-product-id", required=True) + p.add_argument("--consume-count", default="1") + p.add_argument("--consume-amount", default="0") + p.add_argument("--visit-id", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_product_consume) + + p = crm_sub.add_parser("product-consumes", help="产品/套餐消费记录") + p.add_argument("--member-id", default="") + p.add_argument("--member-product-id", default="") + add_page(p) + p.set_defaults(func=cmd_product_consumes) + + p = crm_sub.add_parser("card-close", help="销卡") + add_json_file(p) + p.add_argument("--account-id", default="") + p.add_argument("--reason", default="") + p.add_argument("--refund-amount", default="0") + p.add_argument("--feedback-id", default="") + p.add_argument("--assigned-to", default="") + p.add_argument("--notes", default="") + p.set_defaults(func=cmd_card_close) + + p = crm_sub.add_parser("card-close-list", help="销卡记录") + p.add_argument("--member-id", default="") + add_page(p) + p.set_defaults(func=cmd_card_close_list) + + p = crm_sub.add_parser("suggestion-list", help="建议列表") + p.add_argument("--status", default="") + add_page(p) + p.set_defaults(func=cmd_suggestion_list) + + p = crm_sub.add_parser("suggestion-create", help="创建建议") + add_json_file(p) + p.add_argument("--store-id", default="") + p.add_argument("--member-id", default="") + p.add_argument("--feedback-id", default="") + p.add_argument("--content", default="") + p.add_argument("--category", default="") + p.set_defaults(func=cmd_suggestion_create) + + p = crm_sub.add_parser("suggestion-status", help="更新建议状态") + add_json_file(p) + p.add_argument("--suggestion-id", required=True) + p.add_argument("--status", required=True, choices=["pending", "adopted", "rejected", "duplicate", "implemented"]) + p.add_argument("--notes", default="") + p.add_argument("--rejected-reason", default="") + p.set_defaults(func=cmd_suggestion_status) + + p = crm_sub.add_parser("issue-list", help="问题列表") + p.add_argument("--status", default="") + add_page(p) + p.set_defaults(func=cmd_issue_list) + + p = crm_sub.add_parser("issue-create", help="创建问题") + add_json_file(p) + p.add_argument("--store-id", default="") + p.add_argument("--member-id", default="") + p.add_argument("--feedback-id", default="") + p.add_argument("--card-close-id", default="") + p.add_argument("--title", default="") + p.add_argument("--description", default="") + p.add_argument("--severity", default="medium") + p.add_argument("--category", default="") + p.add_argument("--assigned-to", default="") + p.add_argument("--fix-plan", default="") + p.add_argument("--fix-deadline", default="") + p.set_defaults(func=cmd_issue_create) + + p = crm_sub.add_parser("issue-update", help="更新问题") + add_json_file(p) + p.add_argument("--issue-id", required=True) + p.add_argument("--title", default="") + p.add_argument("--description", default="") + p.add_argument("--severity", default="") + p.add_argument("--category", default="") + p.add_argument("--status", default="") + p.add_argument("--assigned-to", default="") + p.add_argument("--fix-plan", default="") + p.add_argument("--fix-result", default="") + p.set_defaults(func=cmd_issue_update) + + p = crm_sub.add_parser("issue-fix", help="标记问题已修复") + add_json_file(p) + p.add_argument("--issue-id", required=True) + p.add_argument("--plan", default="") + p.add_argument("--result", default="") + p.set_defaults(func=cmd_issue_fix) + + p = crm_sub.add_parser("issue-close", help="关闭问题") + add_json_file(p) + p.add_argument("--issue-id", required=True) + p.add_argument("--result", default="") + p.set_defaults(func=cmd_issue_close) + + p = crm_sub.add_parser("feedback-bind", help="绑定反馈到客户/到店/销卡") + add_json_file(p) + p.add_argument("--feedback-id", required=True) + p.add_argument("--member-id", default="") + p.add_argument("--visit-id", default="") + p.add_argument("--card-close-id", default="") + p.set_defaults(func=cmd_feedback_bind) + + feedback = sub.add_parser("feedback", help="反馈命令") + feedback_sub = feedback.add_subparsers(dest="feedback_command", required=True) + + p = feedback_sub.add_parser("record-list", help="反馈记录列表") + p.add_argument("--store-id", default="") + p.add_argument("--employee-id", default="") + p.add_argument("--satisfaction", default="") + p.add_argument("--start-date", default="") + p.add_argument("--end-date", default="") + add_page(p) + p.set_defaults(func=cmd_record_list) + + p = feedback_sub.add_parser("process", help="提交文本模拟客户反馈处理(会调用 LLM)") + add_json_file(p) + p.add_argument("--store-name", required=False, default="") + p.add_argument("--employee-number", required=False, default="") + p.add_argument("--text", required=False, default="") + p.add_argument("--session-id", default="") + p.add_argument("--device-mac", default="") + p.add_argument("--satisfaction", default="") + p.add_argument("--store-id", default="") + p.add_argument("--employee-id", default="") + p.set_defaults(func=cmd_feedback_process) + + admin = sub.add_parser("admin", help="门店/员工管理查询") + admin_sub = admin.add_subparsers(dest="admin_command", required=True) + + p = admin_sub.add_parser("store-list", help="门店列表") + p.add_argument("--keyword", default="") + add_page(p) + p.set_defaults(func=cmd_store_list) + + p = admin_sub.add_parser("employee-list", help="员工列表") + p.add_argument("--store-id", default="") + add_page(p) + p.set_defaults(func=cmd_employee_list) + + stats = sub.add_parser("stats", help="统计命令") + stats_sub = stats.add_subparsers(dest="stats_command", required=True) + + p = stats_sub.add_parser("employee-kpi", help="员工 KPI") + p.add_argument("--start-date", default="") + p.add_argument("--end-date", default="") + p.set_defaults(func=cmd_employee_kpi) + + p = stats_sub.add_parser("employee-records", help="员工评价明细") + p.add_argument("--employee-id", required=True) + p.add_argument("--group", choices=["", "good", "middle", "bad"], default="") + add_page(p) + p.set_defaults(func=cmd_employee_records) + + return parser + + +def main(argv=None): + parser = build_parser() + args = parser.parse_args(argv) + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/main/feedback-backend/config.yaml b/main/feedback-backend/config.yaml new file mode 100644 index 000000000..bff5b01da --- /dev/null +++ b/main/feedback-backend/config.yaml @@ -0,0 +1,89 @@ +# ============================================================ +# Feedback Backend 配置文件 +# ============================================================ + +server: + host: "0.0.0.0" + port: 8009 + debug: true + cors_origins: + - "*" + +database: + # 独立数据库 feedback_db,与 xiaozhi_esp32_server 解耦 + host: "127.0.0.1" + port: 13306 + username: "root" + password: "123456" + database: "feedback_db" + charset: "utf8mb4" + pool_size: 10 + max_overflow: 20 + pool_recycle: 3600 + +# JWT 认证配置(后台管理用) +auth: + secret_key: "feedback-backend-jwt-secret-change-in-production" + algorithm: "HS256" + access_token_expire_minutes: 1440 # 24 小时 + +# 默认管理员账号 +admin: + username: "admin" + password: "admin123" # 首次登录后请修改 + +# LLM 配置(AI 处理用) +llm: + # 默认 LLM 提供商: openai / dashscope / deepseek + provider: "deepseek" + openai: + api_key: "" + base_url: "https://api.openai.com/v1" + model: "gpt-4o-mini" + dashscope: + api_key: "" + model: "qwen-plus" + deepseek: + api_key: "" + base_url: "https://api.deepseek.com/v1" + model: "deepseek-chat" + +# 智能体对话配置 +agent: + # 默认对话轮次(问几个问题) + default_dialogue_rounds: 8 + # 默认提示词配置 + default_prompts: + asr_cleanup: "prompts/asr-cleanup.txt" + qa_structured: "prompts/qa-structured.txt" + review_generation: "prompts/review-generation.txt" + # 默认问题列表(可被 agent_config 覆盖) + default_questions: + - "请问您的技师工号是多少?" + - "您在这家店多久了?" + - "请问您做了什么项目?" + - "您是什么时间到店的?" + - "您之前身体哪里不舒服?" + - "您的问题解决了吗?" + - "您对这次服务满意吗?" + # 点评生成规则 + review: + long_min_length: 80 + long_max_length: 150 + short_min_length: 30 + short_max_length: 60 + +# xiaozhi-server 连接配置(WebSocket 语音对话) +xiaozhi: + ws_url: "ws://127.0.0.1:18000/xiaozhi/v1/voice" + ws_port: 18000 + http_url: "http://127.0.0.1:18003" + # Java 管理后台 API(OTA 激活码生成) + manager_api_url: "http://127.0.0.1:8002" + +# 日志配置 +logging: + level: "INFO" + format: "{time:YYYY-MM-DD HH:mm:ss} | {level} | {name}:{line} | {message}" + rotation: "10 MB" + retention: "7 days" diff --git a/main/feedback-backend/migrations/env.py b/main/feedback-backend/migrations/env.py new file mode 100644 index 000000000..29ed6d7dd --- /dev/null +++ b/main/feedback-backend/migrations/env.py @@ -0,0 +1,61 @@ +"""Alembic 环境配置""" + +from logging.config import fileConfig + +from alembic import context +from sqlalchemy import engine_from_config, pool + +from app.infrastructure.persistence.database import Base +from app.infrastructure.persistence.models import ( # noqa: F401 - 确保所有 model 被导入 + StoreModel, + EmployeeModel, + FeedbackRecordModel, + AgentConfigModel, + AdminUserModel, +) +from app.shared.config import settings + +config = context.config + +# 使用 settings 中的数据库 URL 覆盖 alembic.ini 中的配置 +config.set_main_option("sqlalchemy.url", settings.database_url) + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def run_migrations_offline() -> None: + """离线模式 - 生成 SQL 脚本""" + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """在线模式 - 直接执行迁移""" + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + ) + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/main/feedback-backend/migrations/script.py.mako b/main/feedback-backend/migrations/script.py.mako new file mode 100644 index 000000000..958df8735 --- /dev/null +++ b/main/feedback-backend/migrations/script.py.mako @@ -0,0 +1,25 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/main/feedback-backend/prompts/asr-cleanup.txt b/main/feedback-backend/prompts/asr-cleanup.txt new file mode 100644 index 000000000..5778c2ff8 --- /dev/null +++ b/main/feedback-backend/prompts/asr-cleanup.txt @@ -0,0 +1,17 @@ +你是一位专业的语音文本清洗专家。你的任务是对语音识别(ASR)产生的文本进行清洗和规整,去除语音交互中的填充词、重复、自我纠正等口语化表达,保留用户想要表达的完整内容。 + +门店:{{门店名称}} +技师工号:{{技师工号}} + +用户全部语音原话: +{{用户全部语音原话}} + +清洗规则: +1. 去除语气词:嗯、啊、呃、那个、就是、然后等无意义的填充词 +2. 去除重复表达:将重复的词语或句子保留一次 +3. 修正口误:用户自我纠正时,以最终表达为准 +4. 保留完整语义:不要删除任何有实质内容的词语 +5. 保持自然流畅:清洗后的文本应当像书面表达一样流畅 +6. 不添加内容:不要补充用户没有说到的内容 + +请直接输出清洗后的文本,不要任何解释。 \ No newline at end of file diff --git a/main/feedback-backend/prompts/qa-structured.txt b/main/feedback-backend/prompts/qa-structured.txt new file mode 100644 index 000000000..781dfa2f8 --- /dev/null +++ b/main/feedback-backend/prompts/qa-structured.txt @@ -0,0 +1,42 @@ +你是一位专业的客户反馈分析师。你的任务是根据客户在门店的消费反馈,提取结构化的问答信息。 + +门店:{{门店名称}} +技师编号:{{技师编号}} +消费项目:{{消费项目}} + +以下是客户规整后的反馈文本: +{{规整后ASR文本}} + +请按照以下10个问题提取信息,如果客户没有提及某个问题,对应回答填"未提及": + +Q1: 技师工号是多少? +A1: + +Q2: 客户来这家店消费多久了?(注意:这是问客户本人的消费时长,不是技师的工作年限) +A2: + +Q3: 客户做了什么项目/服务? +A3: + +Q4: 客户什么时间到店的? +A4: + +Q5: 客户之前身体哪里不舒服? +A5: + +Q6: 客户的问题是否解决了? +A6: + +Q7: 客户对这次服务满意吗? +A7: + +Q8: 客户怎么称呼? +A8: + +Q9: 客户手机号后四位是多少? +A9: + +Q10: 客户有什么建议? +A10: + +请严格按照上述格式输出,每个问答占一行。答案必须取自客户本人的陈述,严禁张冠李戴。 diff --git a/main/feedback-backend/prompts/review-generation.txt b/main/feedback-backend/prompts/review-generation.txt new file mode 100644 index 000000000..d9cccaf73 --- /dev/null +++ b/main/feedback-backend/prompts/review-generation.txt @@ -0,0 +1,36 @@ +你是一位专业的点评撰写专家。你的任务是根据客户的消费反馈,撰写真实、自然、有说服力的消费点评。 + +【重要:角色归属规则】 +你必须严格区分"客户"和"技师"的信息: +- "来店X年/X个月"是【客户】的消费时长,不是技师的工作年限 +- "几号技师"指的是为【客户】服务的技师编号 +- "做的XX项目"是【客户】消费的项目 +- "身体不舒服/XX症状"是【客户】本人的身体状况 +- 严禁将客户的属性张冠李戴到技师身上 + +门店:{{门店名称}} +技师编号:{{技师编号}} +消费项目:{{消费项目}} +到店时长:{{到店时长}} +到店时间:{{到店时间}} +身体不舒服症状:{{身体不舒服症状}} +问题是否解决:{{问题是否解决}} +满意程度:{{满意程度}} + +点评撰写规则: +1. 内容必须真实反映客户的实际体验,不得编造 +2. 语气自然,像普通消费者写的,不要太官方 +3. 可以适当用一些口语化表达,增加真实感 +4. 不提及任何医疗相关声明 +5. 不包含建议或改进意见 +6. 只写正面内容,突出满意的地方 +7. 可以提到具体的技师、项目、感受 +8. 严格按照上面QA结构化数据中的信息写,不要混淆客户和技师的属性 + +请严格按照以下格式输出,不要输出任何其他内容: + +【标准版点评】 +(80-150字,适合大众点评发布,从客户第一人称角度写,直接写点评内容,不要带标题) + +【精简短评】 +(30-60字,适合美团等平台快速评价,从客户第一人称角度写,直接写点评内容) diff --git a/main/feedback-backend/requirements.txt b/main/feedback-backend/requirements.txt new file mode 100644 index 000000000..efc160c01 --- /dev/null +++ b/main/feedback-backend/requirements.txt @@ -0,0 +1,27 @@ +# FastAPI +fastapi==0.115.12 +uvicorn[standard]==0.34.3 +pydantic==2.11.4 +pydantic-settings==2.9.1 + +# Database +sqlalchemy==2.0.41 +alembic==1.16.1 +pymysql==1.1.1 +cryptography==45.0.4 + +# LLM +openai==2.8.1 + +# Utils +pyyaml==6.0.2 +loguru==0.7.3 +httpx==0.28.1 + +# Auth +python-jose[cryptography]==3.4.0 +passlib[bcrypt]==1.7.4 +bcrypt==4.0.1 + +# Validation +email-validator==2.2.0 diff --git a/main/feedback-backend/skills/feedback-crm/SKILL.md b/main/feedback-backend/skills/feedback-crm/SKILL.md new file mode 100644 index 000000000..0091f84b8 --- /dev/null +++ b/main/feedback-backend/skills/feedback-crm/SKILL.md @@ -0,0 +1,119 @@ +--- +name: feedback-crm +description: 通过 CLI 管理反馈系统、CRM、员工KPI、建议和问题修复。适合 AI Agent 调用后台系统能力。 +--- + +# Feedback CRM Skill + +该 skill 将后台系统能力收敛到 `cli.py`,AI Agent 应优先通过 CLI 调用系统,而不是直接操作数据库。 + +## 环境变量 + +```bash +export FEEDBACK_API_BASE="https://feedback-admin.new123.vip/api/v1" +export FEEDBACK_TOKEN="" +``` + +获取 token: + +```bash +python main/feedback-backend/cli.py --base-url "$FEEDBACK_API_BASE" login --username admin --password admin123 --raw-token +``` + +## 常用能力 + +### 健康检查 + +```bash +python main/feedback-backend/cli.py health +``` + +### 查 CRM 概览 + +```bash +python main/feedback-backend/cli.py crm overview +``` + +### 查客户 + +```bash +python main/feedback-backend/cli.py crm member-list --keyword 1234 +python main/feedback-backend/cli.py crm member-detail --member-id +``` + +### 创建/更新客户 + +```bash +python main/feedback-backend/cli.py crm member-create --name 张女士 --phone 13800001234 --health 肩颈酸痛 +python main/feedback-backend/cli.py crm member-update --member-id --level VIP +``` + +复杂客户档案用 JSON: + +```bash +python main/feedback-backend/cli.py crm member-create --json-file member.json +``` + +### 到店记录 + +```bash +python main/feedback-backend/cli.py crm visit-list --member-id +python main/feedback-backend/cli.py crm visit-create --member-id --employee-id --arrive-at 2026-06-20T10:00:00 --items 肩颈调理 +``` + +### 账户/卡/流水 + +```bash +python main/feedback-backend/cli.py crm account-list --member-id +python main/feedback-backend/cli.py crm account-create --member-id --card-name 肩颈10次卡 --account-type count --amount 1000 --count 10 +python main/feedback-backend/cli.py crm account-consume --account-id --count 1 --notes 消费1次 +python main/feedback-backend/cli.py crm transactions --member-id +``` + +### 销卡 + +```bash +python main/feedback-backend/cli.py crm card-close --account-id --reason 服务不满意要求退款 --refund-amount 100 --assigned-to 店长 +python main/feedback-backend/cli.py crm card-close-list --member-id +``` + +### 建议管理 + +```bash +python main/feedback-backend/cli.py crm suggestion-list --status pending +python main/feedback-backend/cli.py crm suggestion-create --content 希望提前开空调 --category environment +python main/feedback-backend/cli.py crm suggestion-status --suggestion-id --status adopted --notes 服务前30分钟开空调 +``` + +### 问题修复 + +```bash +python main/feedback-backend/cli.py crm issue-list --status identified +python main/feedback-backend/cli.py crm issue-create --title 房间温度偏低 --severity medium --assigned-to 店长 +python main/feedback-backend/cli.py crm issue-fix --issue-id --result 已增加毛毯并提前开空调 +python main/feedback-backend/cli.py crm issue-close --issue-id --result 店长复核通过 +``` + +### 反馈和 KPI + +```bash +python main/feedback-backend/cli.py feedback record-list --employee-id --satisfaction very_bad +python main/feedback-backend/cli.py stats employee-kpi +python main/feedback-backend/cli.py stats employee-records --employee-id --group bad +``` + +### 模拟反馈处理 + +会调用 LLM,谨慎使用: + +```bash +python main/feedback-backend/cli.py feedback process --store-name 腰妍美容养生馆 --employee-number 1 --text "手机号后四位1234,今天肩颈调理,房间有点冷,希望提前开空调" --satisfaction satisfied --store-id store001 --employee-id emp001 +``` + +## 操作原则 + +1. 只读查询可直接执行。 +2. 创建/更新/销卡/修复等写操作应返回结果给用户确认。 +3. 不直接删数据;如需删除,先询问用户并走后台 API。 +4. 复杂 payload 优先使用 `--json-file`,便于审计。 +5. 不绕过权限,使用当前用户 token 调用 API。 diff --git a/main/feedback-backend/start.py b/main/feedback-backend/start.py new file mode 100644 index 000000000..95dfc4b27 --- /dev/null +++ b/main/feedback-backend/start.py @@ -0,0 +1,34 @@ +"""启动脚本 - 方便快速启动服务""" + +import sys +import os + +# 将项目根目录加入 Python 路径 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import uvicorn +from app.shared.config import settings + + +def main(): + host = settings.get("server.host", "0.0.0.0") + port = settings.get("server.port", 8009) + debug = settings.get("server.debug", True) + + print(f"Feedback Backend starting...") + print(f" URL: http://{host}:{port}") + print(f" Docs: http://{host}:{port}/docs") + print(f" Admin: http://{host}:{port}/admin") + print(f" Debug: {'ON' if debug else 'OFF'}") + + uvicorn.run( + "app.main:app", + host=host, + port=port, + reload=debug, + log_level="info", + ) + + +if __name__ == "__main__": + main() diff --git a/main/feedback-backend/tests/__init__.py b/main/feedback-backend/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/feedback-backend/tests/test_crm_story.py b/main/feedback-backend/tests/test_crm_story.py new file mode 100644 index 000000000..94b6ba11d --- /dev/null +++ b/main/feedback-backend/tests/test_crm_story.py @@ -0,0 +1,287 @@ +"""CRM 用户故事自动化测试。 + +用户故事: +店长希望客户完成语音反馈后,系统能按手机号后四位识别客户,自动把反馈、到店、 +满意度、建议、问题修复、账户消费流水串起来,并在统计概览中按员工展示好评、 +中评、差评 KPI;同时客户档案支持麦凯66字段,方便门店持续经营客户关系。 +""" + +import asyncio +import unittest +from datetime import datetime + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import StaticPool + +from app.application.crm_service import CrmService +from app.application.feedback_service import FeedbackService +from app.application.stats_service import StatsService +from app.infrastructure.persistence.database import Base +from app.infrastructure.persistence.models import ( + CrmIssueModel, + CrmMemberModel, + CrmSuggestionModel, + CrmVisitModel, + EmployeeModel, + FeedbackRecordModel, + StoreModel, +) +from app.shared.mekai66 import MEKAI66_FIELDS +from app.shared.utils import generate_id + + +class CrmStoryTest(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + self.engine = create_engine( + "sqlite://", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + Base.metadata.create_all(self.engine) + self.Session = sessionmaker(bind=self.engine) + self.session = self.Session() + self.crm = CrmService(self.session) + self.stats = StatsService(self.session) + self.feedback = FeedbackService(self.session) + self.store = StoreModel(id="store001", store_code="558744", store_name="测试门店", status=1) + self.emp = EmployeeModel(id="emp001", name="小王", number=1, store_id="store001", status=1) + self.session.add_all([self.store, self.emp]) + self.session.commit() + + async def asyncTearDown(self): + self.session.close() + self.engine.dispose() + + async def _member(self): + return await self.crm.create_member({ + "store_id": "store001", + "name": "张女士", + "phone": "13800001234", + "beautyConcerns": ["皮肤干燥"], + "healthIssues": ["肩颈酸痛"], + "mekaiTags": {"nickname": "张姐", "preferred_employee": "小王"}, + }, "tester") + + async def _account_with_visit(self): + member = await self._member() + visit = await self.crm.create_visit({ + "store_id": "store001", + "memberId": member["id"], + "employeeId": "emp001", + "arriveAt": "2026-06-18T10:00:00", + "serviceItems": ["肩颈调理"], + }, "tester") + account = await self.crm.create_account({ + "store_id": "store001", + "memberId": member["id"], + "cardName": "肩颈10次卡", + "accountType": "count", + "totalAmount": 1000, + "totalCount": 10, + }, "tester") + return member, visit, account + + def _record(self, satisfaction="satisfied", employee_id="emp001", member_id=None): + record = FeedbackRecordModel( + id=generate_id(), store_id="store001", employee_id=employee_id, + member_id=member_id, satisfaction=satisfaction, review_long="测试评价", + cleaned_text="客户反馈房间有点冷,手机号后四位1234", create_date=datetime.now(), + ) + self.session.add(record) + self.session.commit() + return record + + async def test_01_mekai66_has_exactly_66_fields(self): + self.assertEqual(66, len(MEKAI66_FIELDS)) + + async def test_02_mekai66_keys_are_unique(self): + keys = [f["key"] for f in MEKAI66_FIELDS] + self.assertEqual(len(keys), len(set(keys))) + + async def test_03_create_member_with_mekai66(self): + member = await self._member() + self.assertEqual("张女士", member["name"]) + self.assertEqual("张姐", member["mekaiTags"]["nickname"]) + + async def test_04_search_member_by_phone(self): + await self._member() + result = await self.crm.list_members(store_id="store001", keyword="1234") + self.assertEqual(1, result["total"]) + + async def test_05_update_member_health_profile(self): + member = await self._member() + updated = await self.crm.update_member(member["id"], {"healthIssues": ["腰背酸痛"]}, "store001", "tester") + self.assertIn("腰背酸痛", updated["healthIssues"]) + + async def test_06_create_visit_calculates_duration(self): + member = await self._member() + visit = await self.crm.create_visit({"store_id": "store001", "memberId": member["id"], "arriveAt": "2026-06-18T10:00:00", "leaveAt": "2026-06-18T11:30:00"}, "tester") + self.assertEqual(90, visit["durationMinutes"]) + + async def test_07_visit_returns_member_name(self): + member, visit, _ = await self._account_with_visit() + self.assertEqual(member["name"], visit["memberName"]) + + async def test_08_visit_updates_member_stats(self): + member, _, _ = await self._account_with_visit() + detail = await self.crm.get_member(member["id"], "store001") + self.assertEqual(1, detail["totalVisits"]) + + async def test_09_create_account_creates_recharge_transaction(self): + member, _, account = await self._account_with_visit() + txs = await self.crm.list_account_transactions(member_id=member["id"]) + self.assertEqual(1, txs["total"]) + self.assertEqual("recharge", txs["list"][0]["transactionType"]) + + async def test_10_consume_account_decreases_count(self): + _, _, account = await self._account_with_visit() + consumed = await self.crm.consume_account(account["id"], {"countChange": 1}, "store001", "tester") + self.assertEqual(9, consumed["balanceCount"]) + + async def test_11_consume_account_creates_consume_transaction(self): + member, _, account = await self._account_with_visit() + await self.crm.consume_account(account["id"], {"countChange": 1, "notes": "消费1次"}, "store001", "tester") + txs = await self.crm.list_account_transactions(member_id=member["id"]) + self.assertEqual(2, txs["total"]) + self.assertEqual("consume", txs["list"][0]["transactionType"]) + + async def test_12_consume_without_visit_links_latest_visit(self): + _, visit, account = await self._account_with_visit() + await self.crm.consume_account(account["id"], {"amount": 88, "countChange": 1}, "store001", "tester") + txs = await self.crm.list_account_transactions(account_id=account["id"]) + consume = [t for t in txs["list"] if t["transactionType"] == "consume"][0] + self.assertEqual(visit["id"], consume["relatedVisitId"]) + + async def test_13_consume_syncs_visit_amount(self): + member, _, account = await self._account_with_visit() + await self.crm.consume_account(account["id"], {"amount": 88, "countChange": 1}, "store001", "tester") + detail = await self.crm.get_member(member["id"], "store001") + self.assertEqual(88.0, detail["visits"][0]["consumptionAmount"]) + + async def test_14_create_suggestion(self): + member = await self._member() + suggestion = await self.crm.create_suggestion({"store_id": "store001", "memberId": member["id"], "content": "房间有点冷"}, "tester") + self.assertEqual("pending", suggestion["status"]) + + async def test_15_duplicate_suggestion_increments_frequency(self): + await self.crm.create_suggestion({"store_id": "store001", "content": "房间有点冷"}, "tester") + suggestion = await self.crm.create_suggestion({"store_id": "store001", "content": "房间有点冷"}, "tester") + self.assertEqual(2, suggestion["frequency"]) + + async def test_16_adopt_suggestion_with_notes(self): + suggestion = await self.crm.create_suggestion({"store_id": "store001", "content": "提前开空调"}, "tester") + adopted = await self.crm.update_suggestion_status(suggestion["id"], "adopted", {"handleNotes": "服务前30分钟开空调"}, "store001", "tester") + self.assertEqual("adopted", adopted["status"]) + self.assertEqual("服务前30分钟开空调", adopted["handleNotes"]) + + async def test_17_create_issue(self): + issue = await self.crm.create_issue({"store_id": "store001", "title": "房间温度偏低"}, "tester") + self.assertEqual("identified", issue["status"]) + + async def test_18_update_issue_to_fixed_sets_fixed_time(self): + issue = await self.crm.create_issue({"store_id": "store001", "title": "房间温度偏低"}, "tester") + fixed = await self.crm.update_issue(issue["id"], {"status": "fixed", "fixResult": "已加毛毯"}, "store001", "tester") + self.assertEqual("fixed", fixed["status"]) + self.assertIsNotNone(fixed["fixedAt"]) + + async def test_19_close_card_marks_account_closed(self): + _, _, account = await self._account_with_visit() + close = await self.crm.close_card({"accountId": account["id"], "reason": "搬家", "refundAmount": 100}, "store001", "tester") + self.assertEqual("done", close["status"]) + accounts = await self.crm.list_accounts(store_id="store001", status=0) + self.assertEqual(1, accounts["total"]) + + async def test_20_close_card_bad_reason_does_not_auto_create_issue(self): + _, _, account = await self._account_with_visit() + await self.crm.close_card({"accountId": account["id"], "reason": "服务不满意,要求退款", "refundAmount": 100}, "store001", "tester") + issues = await self.crm.list_issues(store_id="store001") + self.assertEqual(0, issues["total"]) + + async def test_21_bind_feedback_to_member_and_visit(self): + member, visit, _ = await self._account_with_visit() + record = self._record() + bound = await self.crm.bind_feedback(record.id, {"memberId": member["id"], "visitId": visit["id"]}, "store001") + self.assertEqual(member["id"], bound["memberId"]) + self.assertEqual(visit["id"], bound["visitId"]) + + async def test_22_employee_kpi_groups_good_middle_bad(self): + self._record("very_satisfied") + self._record("satisfied") + self._record("unsatisfied") + self._record("very_bad") + kpi = await self.stats.get_employee_kpi("store001") + self.assertEqual(2, kpi[0]["good"]) + self.assertEqual(1, kpi[0]["middle"]) + self.assertEqual(1, kpi[0]["bad"]) + + async def test_23_employee_records_filter_bad(self): + self._record("very_satisfied") + self._record("very_bad") + records = await self.stats.get_employee_records("emp001", "store001", "bad") + self.assertEqual(1, records["total"]) + self.assertEqual("very_bad", records["list"][0]["satisfaction"]) + + async def test_24_phone_tail_extraction(self): + self.assertEqual("1234", self.feedback._extract_phone_tail("我的手机号后四位是1234")) + + async def test_25_auto_link_feedback_finds_member_by_tail(self): + member = await self._member() + record = self._record("satisfied") + qa = "Q3: 客户做了什么项目/服务? A3: 肩颈调理\nQ4: 客户什么时间到店的? A4: 10点30\nQ5: 客户之前身体哪里不舒服? A5: 睡眠不好\nQ8: 客户有什么建议? A8: 希望提前开空调\nQ9: 客户手机号后四位是多少? A9: 1234" + entity = await self.feedback.record_repo.get_by_id(record.id) + self.feedback._auto_link_feedback_to_crm(entity, record.cleaned_text, qa, "satisfied") + updated = self.session.query(FeedbackRecordModel).filter(FeedbackRecordModel.id == record.id).first() + self.assertEqual(member["id"], updated.member_id) + + async def test_26_auto_link_feedback_creates_visit(self): + await self._member() + record = self._record("satisfied") + entity = await self.feedback.record_repo.get_by_id(record.id) + qa = "Q3: 客户做了什么项目/服务? A3: 肩颈调理\nQ4: 客户什么时间到店的? A4: 10点30\nQ9: 客户手机号后四位是多少? A9: 1234" + self.feedback._auto_link_feedback_to_crm(entity, record.cleaned_text, qa, "satisfied") + self.assertEqual(1, self.session.query(CrmVisitModel).count()) + + async def test_27_auto_link_feedback_creates_suggestion(self): + await self._member() + record = self._record("satisfied") + entity = await self.feedback.record_repo.get_by_id(record.id) + qa = "Q8: 客户有什么建议? A8: 希望提前开空调\nQ9: 客户手机号后四位是多少? A9: 1234" + self.feedback._auto_link_feedback_to_crm(entity, record.cleaned_text, qa, "satisfied") + self.assertEqual(1, self.session.query(CrmSuggestionModel).count()) + + async def test_28_auto_link_feedback_no_longer_creates_issue_for_bad_feedback(self): + await self._member() + record = self._record("very_bad") + entity = await self.feedback.record_repo.get_by_id(record.id) + qa = "Q9: 客户手机号后四位是多少? A9: 1234" + self.feedback._auto_link_feedback_to_crm(entity, "客户很差,要求退款", qa, "very_bad") + self.assertEqual(0, self.session.query(CrmIssueModel).count()) + + async def test_29_member_detail_aggregates_related_data(self): + member, _, account = await self._account_with_visit() + await self.crm.consume_account(account["id"], {"countChange": 1}, "store001", "tester") + await self.crm.create_suggestion({"store_id": "store001", "memberId": member["id"], "content": "建议"}, "tester") + await self.crm.create_issue({"store_id": "store001", "memberId": member["id"], "title": "问题"}, "tester") + detail = await self.crm.get_member(member["id"], "store001") + self.assertTrue(detail["visits"]) + self.assertTrue(detail["accounts"]) + self.assertTrue(detail["transactions"]) + self.assertTrue(detail["suggestions"]) + self.assertTrue(detail["issues"]) + + async def test_30_crm_overview_counts_all_modules(self): + member, _, account = await self._account_with_visit() + await self.crm.create_suggestion({"store_id": "store001", "memberId": member["id"], "content": "建议"}, "tester") + await self.crm.create_issue({"store_id": "store001", "memberId": member["id"], "title": "问题"}, "tester") + await self.crm.close_card({"accountId": account["id"], "reason": "搬家"}, "store001", "tester") + overview = await self.crm.get_overview("store001") + self.assertEqual(1, overview["members"]) + self.assertEqual(1, overview["visits"]) + self.assertEqual(1, overview["cardCloses"]) + self.assertEqual(1, overview["pendingSuggestions"]) + self.assertEqual(1, overview["openIssues"]) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/main/feedback-h5/.dockerignore b/main/feedback-h5/.dockerignore new file mode 100644 index 000000000..cc4d8ebfa --- /dev/null +++ b/main/feedback-h5/.dockerignore @@ -0,0 +1,8 @@ +__pycache__/ +*.pyc +.git/ +.gitignore +.env +*.log +debug.js +test_*.py diff --git a/main/feedback-h5/Dockerfile b/main/feedback-h5/Dockerfile new file mode 100644 index 000000000..3a6186d38 --- /dev/null +++ b/main/feedback-h5/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.10-slim + +WORKDIR /app + +# 配置 pip 镜像(国内加速) +RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ + +# 安装 aiohttp(start.py 唯一依赖) +RUN pip install --no-cache-dir aiohttp==3.11.10 + +# 复制 H5 全部文件(静态资源 + start.py) +COPY . . + +# 暴露端口 +EXPOSE 8007 + +# 启动 H5 服务器 + 反向代理 +CMD ["python", "start.py"] diff --git a/main/feedback-h5/README.md b/main/feedback-h5/README.md new file mode 100644 index 000000000..64c48e662 --- /dev/null +++ b/main/feedback-h5/README.md @@ -0,0 +1,116 @@ +# 客户反馈系统 - 使用指南 + +## 系统架构 +- **MySQL**: 3张表(feedback_store, feedback_employee, feedback_record) +- **Java manager-api** (8002): 门店/员工/记录 CRUD(注意:Java代码需重建镜像才生效,当前H5使用mock数据降级) +- **Python xiaozhi-server** (18000/18003): WebSocket语音对话 + `/feedback/process` AI处理接口 +- **H5前端** (8007): 客户使用页面,含Live2D数字人 + +## 当前已部署 +✅ MySQL 表已建好 +✅ 测试数据已插入(门店码: **558744**) +✅ Python feedback_handler 已挂载到容器并生效 +✅ H5 已运行在 8007 端口 + +## 完整测试流程 + +### 第一步:访问H5页面 +浏览器打开:`http://127.0.0.1:8007/#/home?code=558744` + +应该看到: +- 自动识别门店"康悦养生店" +- 展示3名员工卡片(1号张三-店长、2号李四-优秀、3号王五-实习) + +### 第二步:选择员工 → 开始反馈 +点击任意员工 → 点击"开始语音反馈" → 跳转到语音对话页 + +### 第三步:智能体绑定(首次) +H5 会显示**6位验证码**(如:544341) + +**管理员操作**: +1. 打开智控台 `http://localhost:8002` +2. 进入"智能体管理" → 新增智能体 +3. 输入6位验证码 → 绑定设备 +4. 配置该智能体的: + - LLM(如 DeepSeek) + - ASR(如 FunASR) + - TTS(如 EdgeTTS) + - 系统提示词(7个固定问题引导逻辑,见下方) + +### 第四步:再次拨号 → 开始对话 +绑定后再次访问H5 → 自动连接 → Live2D数字人开始按7个问题提问 + +### 第五步:对话结束 → AI 处理 +对话结束(WebSocket断开)后,H5 自动调用 `/feedback/process`: +- 第1步:ASR 文本规整 +- 第2步:QA 结构化 +- 第3步:生成美团/大众点评好评 + +### 第六步:复制好评 + 跳转 +- 点击"复制好评" → 自动 TTS 播报"已复制" +- 点击"打开大众点评/美团" → 唤起APP或网页版 + +--- + +## 智能体提示词模板 + +在智控台创建智能体时填入: + +``` +你是一位客户服务回访助手,名叫小智。你的任务是按照顺序依次向客户提出以下7个问题,每次只问一个问题,等待客户回答后再问下一个: + +1. 您来店里多久了? +2. 今天做的什么项目? +3. 您是几点过来做项目的? +4. 您来之前觉得哪里不舒服呢? +5. 本次服务解决您的问题了么? +6. 您对本次服务满意么? +7. 您对我们有什么好的建议么? + +规则: +- 严格按顺序提问,不可跳过或打乱顺序 +- 每次只问一个问题,等客户回答后再问下一个 +- 客户回答后简单回应(如"好的,了解了"),然后自然过渡到下一个问题 +- 如果客户没听清,重复当前问题 +- 不要询问客户怎么称呼、手机号、手机尾号或手机号后四位,这些信息会在对话结束后的表单中填写 +- 不要偏离这7个问题去聊其他话题 +- 7个问题全部回答完毕后,感谢客户并说"您的反馈我们已记录,感谢您的参与!再见" +``` + +--- + +## 启动/停止 + +### 启动 H5 +```bash +cd main/feedback-h5 +python start.py +``` + +### 重启 Python 服务(修改 feedback_handler.py 后) +```bash +docker restart xiaozhi-esp32-server +``` + +### 查看 Python 日志 +```bash +docker logs xiaozhi-esp32-server --tail 50 +``` + +--- + +## 待解决问题 + +### Java API 未生效 +当前 Java manager-api 容器使用预构建镜像(`ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest`),新增的 `/feedback/*` REST API 不在镜像里。 + +**临时方案**:H5 的 `api.js` 已加入 mock 数据降级(门店 558744 + 3名员工),可以走通完整流程。 + +**长期方案**:重新构建 Java Docker 镜像,将本地 `main/manager-api/src/main/java/xiaozhi/modules/feedback/` 模块和 `ShiroConfig.java` 编译进去。 + +### 数据库测试数据 +当前已插入: +- 门店:`store001`, code=`558744`, 名称=`康悦养生店`, 绑定智能体=`5c6595d3c74843149364bec51b160126` +- 员工:emp001/张三/1号/店长, emp002/李四/2号/优秀, emp003/王五/3号/实习 + +注意:`agent_id` 当前绑定的是已存在的"human"智能体。如需新建反馈专用智能体,需通过智控台创建并更新 `feedback_store.agent_id`。 diff --git a/main/feedback-h5/css/style.css b/main/feedback-h5/css/style.css new file mode 100644 index 000000000..60a1ef3cd --- /dev/null +++ b/main/feedback-h5/css/style.css @@ -0,0 +1,1188 @@ +/* 客户反馈H5 - 全屏沉浸式 + 现代简约风格 */ + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +html, body { + height: 100%; + overflow-x: hidden; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Microsoft YaHei', sans-serif; + background: #f5f5f5; + color: #333; + -webkit-font-smoothing: antialiased; +} + +.app-container { + max-width: 480px; + margin: 0 auto; + min-height: 100vh; + background: #fff; + position: relative; +} + +.page { + padding: 20px; + min-height: 100vh; +} + +/* ==================== 通用按钮 ==================== */ +.btn-primary { + height: 48px; + padding: 0 20px; + background: linear-gradient(135deg, #4CAF50, #45a049); + color: #fff; + border: none; + border-radius: 12px; + font-size: 16px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s; +} + +.btn-primary:disabled { + background: #ccc; + cursor: not-allowed; +} + +.btn-primary:active { + transform: scale(0.98); +} + +.btn-secondary { + height: 48px; + padding: 0 20px; + background: #fff; + color: #666; + border: 1.5px solid #e0e0e0; + border-radius: 12px; + font-size: 16px; + cursor: pointer; +} + +.btn-large { + width: 100%; + margin-top: 12px; +} + +/* ==================== 首页 ==================== */ +.home-page { + padding-top: 40px; +} + +.page-header { + text-align: center; + margin-bottom: 24px; +} + +.page-header h1 { + font-size: 24px; + color: #1a1a1a; + margin-bottom: 8px; +} + +.subtitle { + color: #999; + font-size: 14px; +} + +.store-input-section { + margin-bottom: 24px; +} + +.store-input-section label { + display: block; + font-size: 14px; + color: #666; + margin-bottom: 8px; +} + +.code-input-group { + display: flex; + gap: 12px; +} + +.code-input-group input { + flex: 1; + height: 48px; + border: 2px solid #e0e0e0; + border-radius: 12px; + padding: 0 16px; + font-size: 20px; + text-align: center; + letter-spacing: 8px; + outline: none; + transition: border-color 0.2s; +} + +.code-input-group input:focus { + border-color: #4CAF50; +} + +.store-card { + background: linear-gradient(135deg, #4CAF50, #45a049); + color: #fff; + border-radius: 16px; + padding: 20px; + margin-bottom: 20px; +} + +.store-card h2 { + font-size: 20px; + margin-bottom: 8px; +} + +.store-code { + font-size: 13px; + opacity: 0.85; +} + +.employee-section h3 { + font-size: 16px; + color: #333; + margin-bottom: 12px; +} + +.employee-list { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 10px; + margin-bottom: 20px; +} + +.employee-card { + display: flex; + align-items: center; + gap: 8px; + padding: 12px; + border: 2px solid #e0e0e0; + border-radius: 12px; + cursor: pointer; + transition: all 0.2s; +} + +.employee-card.selected { + border-color: #4CAF50; + background: #E8F5E9; +} + +.emp-number { + font-size: 18px; + font-weight: bold; + color: #4CAF50; + min-width: 36px; +} + +.emp-name { + font-size: 14px; + flex: 1; +} + +.emp-type { + font-size: 11px; + padding: 2px 6px; + border-radius: 4px; + color: #fff; +} + +.type-manager { background: #FF9800; } +.type-excellent { background: #2196F3; } +.type-intern { background: #9E9E9E; } + +.btn-start { + width: 100%; + height: 52px; + background: linear-gradient(135deg, #4CAF50, #45a049); + color: #fff; + border: none; + border-radius: 16px; + font-size: 18px; + font-weight: bold; + cursor: pointer; +} + +.btn-start:disabled { + background: #ccc; + cursor: not-allowed; +} + +.error-message { + text-align: center; + color: #f44336; + padding: 12px; + background: #FFEBEE; + border-radius: 8px; + font-size: 14px; +} + +/* ==================== 全屏语音对话页 ==================== */ +.voice-fullscreen { + position: fixed; + top: 0; + left: 50%; + transform: translateX(-50%); + width: 100%; + max-width: 480px; + height: 100vh; + overflow: hidden; + /* 渐变背景作为数字人后面的衬底 */ + background: + radial-gradient(circle at 50% 30%, #FFE5E5 0%, transparent 60%), + linear-gradient(180deg, #FFB6C1 0%, #FFC8DD 30%, #BDE0FE 70%, #A2D2FF 100%); +} + +/* Live2D 全屏 canvas */ +.live2d-fullscreen { + position: absolute !important; + top: 0; + left: 0; + width: 100% !important; + height: 100% !important; + z-index: 1; +} + +.model-loading-overlay { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + color: #fff; + font-size: 14px; + background: rgba(0, 0, 0, 0.5); + padding: 12px 24px; + border-radius: 24px; + z-index: 5; + backdrop-filter: blur(8px); +} + +/* ==================== 准备页(覆盖在数字人上方) ==================== */ +.prepare-overlay { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 100; + display: flex; + align-items: center; + justify-content: center; + padding: 24px; + background: + radial-gradient(circle at 50% 30%, rgba(255, 229, 229, 0.95) 0%, rgba(189, 224, 254, 0.95) 100%); + backdrop-filter: blur(10px); + transition: opacity 0.5s ease; + animation: prepareIn 0.3s ease; +} + +@keyframes prepareIn { + from { opacity: 0; } + to { opacity: 1; } +} + +.prepare-overlay.fading-out { + opacity: 0; + pointer-events: none; +} + +.prepare-card { + width: 100%; + max-width: 360px; + background: #fff; + border-radius: 24px; + padding: 32px 24px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12); + text-align: center; +} + +.prepare-emoji { + font-size: 56px; + margin-bottom: 8px; + animation: emojiPulse 1.5s ease infinite; +} + +@keyframes emojiPulse { + 0%, 100% { transform: scale(1); } + 50% { transform: scale(1.1); } +} + +.prepare-title { + font-size: 20px; + font-weight: 600; + color: #1a1a1a; + margin-bottom: 6px; +} + +.prepare-subtitle { + font-size: 13px; + color: #888; + margin-bottom: 24px; +} + +.prepare-progress { + width: 100%; + height: 8px; + background: #f0f0f0; + border-radius: 8px; + overflow: hidden; + margin-bottom: 8px; +} + +.prepare-progress-bar { + height: 100%; + width: 0%; + background: linear-gradient(90deg, #4CAF50, #81C784); + border-radius: 8px; + transition: width 0.4s ease; + box-shadow: 0 0 8px rgba(76, 175, 80, 0.4); +} + +.prepare-percent { + font-size: 13px; + color: #4CAF50; + font-weight: 600; + margin-bottom: 20px; +} + +.prepare-steps { + text-align: left; + margin-bottom: 16px; +} + +.prepare-step { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + margin-bottom: 6px; + border-radius: 10px; + background: #fafafa; + font-size: 13px; + color: #666; + transition: all 0.3s ease; +} + +.prepare-step.done { + background: #E8F5E9; + color: #2E7D32; +} + +.prepare-step .step-icon { + font-size: 16px; + flex-shrink: 0; +} + +.prepare-tip { + font-size: 12px; + color: #999; + margin-top: 4px; +} + +/* 准备页 - 错误状态 */ +.prepare-card.prepare-error { + text-align: center; +} + +.prepare-error-reason { + font-size: 14px; + color: #d32f2f; + background: #FFEBEE; + padding: 10px 14px; + border-radius: 10px; + margin: 12px 0; + line-height: 1.5; +} + +.prepare-error-tip { + font-size: 13px; + color: #666; + background: #FFF8E1; + padding: 12px 14px; + border-radius: 10px; + text-align: left; + line-height: 1.7; + margin-bottom: 16px; +} + +.prepare-error-actions { + display: flex; + flex-direction: column; + gap: 8px; +} + +/* 顶部状态栏 - 半透明叠加 */ +.voice-status-overlay { + position: absolute; + top: 0; + left: 0; + right: 0; + padding: env(safe-area-inset-top, 12px) 16px 12px; + background: linear-gradient(180deg, rgba(0, 0, 0, 0.3), transparent); + text-align: center; + z-index: 10; +} + +.voice-status-text { + color: #fff; + font-size: 14px; + font-weight: 500; + text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5); +} + +/* 中下部聊天弹幕 - 半透明气泡叠加在数字人上 */ +.chat-stream-overlay { + position: absolute; + bottom: 130px; + left: 12px; + right: 12px; + max-height: 40vh; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 8px; + z-index: 10; + pointer-events: none; + /* 顶部渐变遮罩 */ + -webkit-mask-image: linear-gradient(180deg, transparent 0%, black 20%); + mask-image: linear-gradient(180deg, transparent 0%, black 20%); +} + +.chat-stream-overlay::-webkit-scrollbar { + display: none; +} + +.chat-bubble { + max-width: 75%; + padding: 10px 14px; + border-radius: 18px; + font-size: 14px; + line-height: 1.5; + word-break: break-word; + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); + pointer-events: auto; + animation: bubbleIn 0.3s ease-out; +} + +@keyframes bubbleIn { + from { opacity: 0; transform: translateY(10px); } + to { opacity: 1; transform: translateY(0); } +} + +.chat-bubble.ai { + background: rgba(255, 255, 255, 0.85); + color: #1565C0; + align-self: flex-start; + border-bottom-left-radius: 4px; +} + +.chat-bubble.user { + background: rgba(76, 175, 80, 0.92); + color: #fff; + align-self: flex-end; + border-bottom-right-radius: 4px; +} + +/* 底部控制 - 玻璃拟态浮层 */ +.voice-controls-overlay { + position: absolute; + bottom: 0; + left: 0; + right: 0; + padding: 16px 20px calc(20px + env(safe-area-inset-bottom, 0px)); + display: flex; + align-items: center; + justify-content: center; + gap: 12px; + z-index: 10; + background: linear-gradient(0deg, rgba(0, 0, 0, 0.25), transparent); +} + +.ctrl-btn-round { + width: 56px; + height: 56px; + border-radius: 50%; + border: none; + background: rgba(255, 255, 255, 0.9); + backdrop-filter: blur(12px); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); + transition: all 0.2s; +} + +.ctrl-btn-round.muted { + background: rgba(150, 150, 150, 0.85); +} + +.ctrl-btn-round:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.ctrl-btn-round .ctrl-icon { + font-size: 22px; +} + +.ctrl-btn-main { + flex: 1; + max-width: 200px; + height: 56px; + border-radius: 28px; + border: none; + color: #fff; + font-size: 16px; + font-weight: 600; + cursor: pointer; + box-shadow: 0 4px 16px rgba(76, 175, 80, 0.4); + transition: all 0.2s; +} + +.ctrl-btn-main.primary-end { + background: linear-gradient(135deg, #4CAF50, #45a049); +} + +.ctrl-btn-main:disabled { + background: #ccc; + box-shadow: none; + cursor: not-allowed; +} + +.ctrl-btn-main:active { + transform: scale(0.97); +} + +/* ==================== 满意度选择弹窗 ==================== */ +.modal-overlay { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.6); + z-index: 100; + display: flex; + align-items: center; + justify-content: center; + padding: 20px; + animation: fadeIn 0.2s; +} + +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +.modal-card { + background: #fff; + border-radius: 20px; + padding: 24px; + max-width: 400px; + width: 100%; + animation: slideUp 0.3s; +} + +@keyframes slideUp { + from { transform: translateY(20px); opacity: 0; } + to { transform: translateY(0); opacity: 1; } +} + +.satisfaction-modal h2 { + text-align: center; + font-size: 18px; + color: #1a1a1a; + margin-bottom: 6px; +} + +.modal-subtitle { + text-align: center; + color: #999; + font-size: 13px; + margin-bottom: 20px; +} + +.satisfaction-options { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 10px; + margin-bottom: 16px; +} + +.sat-option { + border: 2px solid #e0e0e0; + background: #fafafa; + border-radius: 14px; + padding: 16px 8px; + cursor: pointer; + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + transition: all 0.2s; +} + +.sat-option:active { + transform: scale(0.96); +} + +.sat-very-satisfied:hover { border-color: #FF6B6B; background: #FFF0F0; } +.sat-satisfied:hover { border-color: #4CAF50; background: #E8F5E9; } +.sat-unsatisfied:hover { border-color: #FF9800; background: #FFF3E0; } +.sat-very-bad:hover { border-color: #757575; background: #F5F5F5; } + +.sat-emoji { + font-size: 36px; +} + +.sat-label { + font-size: 14px; + color: #333; + font-weight: 500; +} + +.modal-cancel-btn { + width: 100%; + height: 44px; + background: transparent; + border: none; + color: #999; + font-size: 14px; + cursor: pointer; +} + +.identity-modal { + text-align: left; +} + +.identity-modal .form-input { + width: 100%; + height: 46px; + border: 1.5px solid #e0e0e0; + border-radius: 12px; + padding: 0 14px; + font-size: 16px; + outline: none; + background: #fafafa; +} + +.identity-modal .form-input:focus { + border-color: #4CAF50; + background: #fff; +} + +.identity-hint { + margin: 4px 0 10px; + padding: 10px 12px; + border-radius: 10px; + background: #F1F8E9; + color: #4CAF50; + font-size: 12px; + line-height: 1.5; +} + +.login-error { + min-height: 18px; + color: #E53935; + font-size: 13px; + text-align: center; +} + +/* ==================== 激活码弹窗 ==================== */ +.activation-modal h2 { + text-align: center; + font-size: 20px; + color: #1a1a1a; + margin-bottom: 4px; +} + +.activation-code-display { + text-align: center; + font-size: 42px; + font-weight: 800; + color: #4CAF50; + letter-spacing: 8px; + padding: 16px 0; + background: linear-gradient(135deg, #e8f5e9, #c8e6c9); + border-radius: 12px; + margin: 16px 0; + user-select: all; +} + +.activation-hint { + background: #f5f5f5; + border-radius: 10px; + padding: 14px 16px; + margin-bottom: 16px; +} + +.activation-hint p { + font-size: 13px; + font-weight: 600; + color: #666; + margin-bottom: 6px; +} + +.activation-hint ol { + padding-left: 18px; + font-size: 12px; + color: #888; + line-height: 1.8; +} + +.activation-hint a { + color: #4CAF50; + text-decoration: underline; +} + +/* ==================== 结果页 ==================== */ +.result-page { + padding-top: 40px; +} + +.processing-view { + text-align: center; + padding: 60px 20px; +} + +.processing-icon { + font-size: 56px; + animation: floaty 2s ease-in-out infinite; + margin-bottom: 16px; +} + +@keyframes floaty { + 0%, 100% { transform: translateY(0); } + 50% { transform: translateY(-8px); } +} + +.processing-title { + font-size: 20px; + color: #1a1a1a; + margin-bottom: 8px; +} + +.processing-subtitle { + font-size: 14px; + color: #999; + margin-bottom: 32px; +} + +.processing-loader { + display: flex; + justify-content: center; + gap: 8px; + margin-bottom: 20px; +} + +.loader-dot { + width: 10px; + height: 10px; + background: #4CAF50; + border-radius: 50%; + animation: dotBounce 1.4s ease-in-out infinite both; +} + +.loader-dot:nth-child(1) { animation-delay: -0.32s; } +.loader-dot:nth-child(2) { animation-delay: -0.16s; } + +@keyframes dotBounce { + 0%, 80%, 100% { transform: scale(0); } + 40% { transform: scale(1); } +} + +.processing-status { + font-size: 13px; + color: #4CAF50; +} + +/* 结果内容(满意) */ +.result-content-clean { + padding: 20px 0; +} + +.result-header { + text-align: center; + margin-bottom: 24px; +} + +.result-emoji { + font-size: 56px; + margin-bottom: 12px; +} + +.result-header h2 { + font-size: 20px; + color: #1a1a1a; + margin-bottom: 6px; +} + +.result-header p { + font-size: 14px; + color: #999; +} + +.review-card { + background: #FFF8E1; + border-radius: 16px; + padding: 16px; + margin-bottom: 20px; +} + +.review-tabs { + display: flex; + gap: 8px; + margin-bottom: 12px; +} + +.tab-btn { + flex: 1; + padding: 8px; + border: 2px solid #e0e0e0; + border-radius: 8px; + background: #fff; + cursor: pointer; + font-size: 13px; + transition: all 0.2s; +} + +.tab-btn.active { + border-color: #FF9800; + color: #F57C00; + background: #FFE0B2; + font-weight: 600; +} + +.review-text-box { + display: none; + background: #fff; + border-radius: 10px; + padding: 14px; + font-size: 14px; + line-height: 1.7; + color: #333; + white-space: pre-wrap; +} + +.review-text-box.active { + display: block; +} + +.btn-publish { + background: linear-gradient(135deg, #FF6B6B, #FF8E53); + box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3); +} + +/* ==================== 一键复制 + 平台按钮 ==================== */ +.review-actions { + margin-bottom: 16px; +} + +.btn-copy-review { + width: 100%; + height: 48px; + background: linear-gradient(135deg, #4CAF50, #45a049); + color: #fff; + border: none; + border-radius: 12px; + font-size: 16px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s; +} + +.btn-copy-review:active { + transform: scale(0.98); +} + +.btn-copy-review.copied { + background: linear-gradient(135deg, #66BB6A, #4CAF50); +} + +.btn-copy-short { + background: linear-gradient(135deg, #42A5F5, #1E88E5); +} + +.btn-copy-short.copied { + background: linear-gradient(135deg, #64B5F6, #42A5F5); +} + +.manual-copy-overlay { + position: fixed; + inset: 0; + background: rgba(0,0,0,0.45); + z-index: 9999; + display: flex; + align-items: flex-end; + justify-content: center; +} + +.manual-copy-card { + width: 100%; + max-width: 520px; + background: #fff; + border-radius: 20px 20px 0 0; + padding: 20px; + box-shadow: 0 -12px 40px rgba(0,0,0,0.18); +} + +.manual-copy-card h3 { + font-size: 18px; + margin-bottom: 8px; +} + +.manual-copy-card p { + color: #666; + font-size: 14px; + line-height: 1.6; + margin-bottom: 12px; +} + +.manual-copy-card textarea { + width: 100%; + min-height: 180px; + border: 1.5px solid #4CAF50; + border-radius: 12px; + padding: 12px; + font-size: 15px; + line-height: 1.7; + color: #333; + background: #F8FFF8; + user-select: text; + -webkit-user-select: text; +} + +.platform-section { + background: #f9f9f9; + border-radius: 14px; + padding: 16px; + margin-bottom: 12px; +} + +.platform-section h3 { + font-size: 15px; + color: #333; + margin-bottom: 4px; +} + +.platform-hint { + font-size: 12px; + color: #999; + margin-bottom: 12px; +} + +.platform-buttons-inline { + display: flex; + gap: 10px; +} + +.platform-buttons-inline .btn-platform { + flex: 1; + height: 44px; + border: 2px solid #e0e0e0; + border-radius: 10px; + background: #fff; + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; +} + +.platform-buttons-inline .btn-dianping { + color: #FF6B35; + border-color: #FF6B35; +} + +.platform-buttons-inline .btn-dianping:active { + background: #FFF3E0; +} + +.platform-buttons-inline .btn-meituan { + color: #FFB300; + border-color: #FFB300; +} + +.platform-buttons-inline .btn-meituan:active { + background: #FFF8E1; +} + +/* 结果内容(不满意) */ +.unsatisfied-header h2 { + color: #444; +} + +.feedback-saved-card { + background: #F5F5F5; + border-radius: 14px; + padding: 16px; + display: flex; + align-items: center; + gap: 14px; + margin-bottom: 24px; +} + +.saved-icon { + width: 40px; + height: 40px; + border-radius: 50%; + background: #4CAF50; + color: #fff; + display: flex; + align-items: center; + justify-content: center; + font-size: 20px; + font-weight: bold; + flex-shrink: 0; +} + +.saved-title { + font-size: 15px; + color: #1a1a1a; + font-weight: 600; + margin-bottom: 2px; +} + +.saved-subtitle { + font-size: 13px; + color: #999; +} + +/* ==================== 发布好评页 ==================== */ +.publish-page { + padding-top: 20px; +} + +.review-box { + background: #FFF8E1; + border-radius: 16px; + padding: 20px; + margin-bottom: 24px; +} + +.review-box h3 { + font-size: 16px; + margin-bottom: 12px; + color: #F57C00; +} + +.review-content { + background: #fff; + border-radius: 12px; + padding: 14px; + font-size: 14px; + line-height: 1.6; + margin-bottom: 12px; +} + +.platform-buttons h3 { + font-size: 16px; + margin-bottom: 12px; +} + +.btn-platform { + width: 100%; + height: 52px; + border: none; + border-radius: 12px; + font-size: 16px; + font-weight: bold; + cursor: pointer; + margin-bottom: 10px; +} + +.btn-dianping { background: #FF6600; color: #fff; } +.btn-meituan { background: #FFD100; color: #333; } + +.btn-complete { + width: 100%; + height: 48px; + background: #e0e0e0; + color: #666; + border: none; + border-radius: 12px; + font-size: 16px; + cursor: pointer; + margin-top: 20px; +} + +/* ==================== 完成页 ==================== */ +.complete-page { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + min-height: 100vh; + text-align: center; + padding: 20px; +} + +.complete-content { + margin-bottom: 40px; +} + +.complete-icon { + font-size: 64px; + margin-bottom: 20px; + animation: bounce 1s infinite; +} + +@keyframes bounce { + 0%, 100% { transform: translateY(0); } + 50% { transform: translateY(-10px); } +} + +.complete-content h1 { + font-size: 24px; + margin-bottom: 12px; +} + +.complete-content p { + color: #999; + font-size: 14px; + margin-bottom: 4px; +} + +/* ==================== 客户预约页 ==================== */ +.appointment-page { padding: 0; background: #f6f8fb; } +.appointment-hero { padding: 28px 20px 22px; background: linear-gradient(135deg, #16A34A, #22C55E); color: #fff; border-radius: 0 0 26px 26px; box-shadow: 0 12px 30px rgba(34,197,94,.22); } +.appointment-kicker { display: inline-flex; padding: 4px 10px; border-radius: 999px; background: rgba(255,255,255,.18); font-size: 12px; margin-bottom: 10px; } +.appointment-hero h1 { font-size: 24px; margin-bottom: 8px; } +.appointment-hero p { font-size: 14px; opacity: .9; line-height: 1.6; } +.apt-card { margin: 14px 14px 0; background: #fff; border-radius: 18px; padding: 16px; box-shadow: 0 8px 28px rgba(15,23,42,.06); } +.apt-card-title { font-size: 16px; font-weight: 800; color: #111827; margin-bottom: 12px; } +.apt-employee-list { display: grid; grid-template-columns: repeat(2, minmax(0,1fr)); gap: 10px; } +.apt-employee { min-height: 64px; padding: 10px; border: 1.5px solid #E5E7EB; border-radius: 14px; background: #fff; display: flex; flex-direction: column; align-items: flex-start; justify-content: center; gap: 4px; color: #374151; } +.apt-employee span { color: #16A34A; font-size: 13px; font-weight: 800; } +.apt-employee strong { font-size: 15px; } +.apt-employee.selected { border-color: #22C55E; background: #F0FDF4; box-shadow: 0 8px 20px rgba(34,197,94,.12); } +.apt-slot-list { display: grid; grid-template-columns: repeat(3, minmax(0,1fr)); gap: 10px; } +.apt-slot { padding: 10px 6px; border: 1.5px solid #E5E7EB; border-radius: 14px; background: #fff; color: #111827; font-size: 14px; font-weight: 800; } +.apt-slot small { display: block; margin-top: 4px; color: #9CA3AF; font-size: 11px; font-weight: 500; } +.apt-slot.selected { border-color: #22C55E; background: #ECFDF5; color: #047857; } +.apt-muted { color: #9CA3AF; font-size: 14px; padding: 10px 0; } +.apt-form-grid { display: grid; grid-template-columns: 1fr auto; gap: 10px; } +.apt-input { width: 100%; height: 46px; border: 1.5px solid #E5E7EB; border-radius: 13px; padding: 0 13px; outline: none; font-size: 15px; } +.apt-member-info { margin-top: 10px; padding: 10px 12px; border-radius: 12px; background: #F0FDF4; color: #047857; font-size: 14px; font-weight: 700; } +.apt-product-list { display: grid; gap: 10px; margin-top: 12px; } +.apt-product { width: 100%; text-align: left; padding: 12px; border: 1.5px solid #E5E7EB; border-radius: 14px; background: #fff; color: #374151; } +.apt-product strong { display: block; font-size: 15px; color: #111827; margin-bottom: 4px; } +.apt-product span, .apt-product small { display: block; color: #6B7280; font-size: 12px; line-height: 1.5; } +.apt-product.selected { border-color: #22C55E; background: #ECFDF5; box-shadow: 0 8px 20px rgba(34,197,94,.12); } +.apt-input:focus { border-color: #22C55E; box-shadow: 0 0 0 3px rgba(34,197,94,.12); } +.apt-confirm-text { margin: 12px 0; padding: 12px; background: #F8FAFC; border: 1px solid #E5E7EB; border-radius: 12px; color: #374151; font-size: 14px; line-height: 1.6; } +.apt-voice-panel { margin: 14px; padding: 16px; border-radius: 18px; background: linear-gradient(135deg, #EEF2FF, #F8FAFC); border: 1px solid #E0E7FF; } +.apt-ai-text { min-height: 54px; color: #374151; font-size: 14px; line-height: 1.7; margin-bottom: 12px; } +.apt-listen-status { padding: 10px 12px; border-radius: 12px; background: rgba(79,70,229,.08); color: #4F46E5; font-size: 13px; font-weight: 700; text-align: center; } +.apt-start-voice-btn { width: 100%; height: 48px; border: none; border-radius: 14px; color: #fff; background: linear-gradient(135deg, #4F46E5, #6366F1); font-size: 16px; font-weight: 800; margin-bottom: 10px; } +.apt-voice-btn { width: 100%; height: 48px; border: none; border-radius: 14px; color: #fff; background: linear-gradient(135deg, #4F46E5, #6366F1); font-size: 16px; font-weight: 800; } +@media (max-width: 380px) { + .apt-employee-list { grid-template-columns: 1fr; } + .apt-slot-list { grid-template-columns: repeat(2, minmax(0,1fr)); } + .apt-form-grid { grid-template-columns: 1fr; } +} diff --git a/main/feedback-h5/index.html b/main/feedback-h5/index.html new file mode 100644 index 000000000..55fbb37bc --- /dev/null +++ b/main/feedback-h5/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + 服务反馈 + + + + +
      + +
      + + + + + + + + + + + + + + + + + diff --git a/main/feedback-h5/js/api.js b/main/feedback-h5/js/api.js new file mode 100644 index 000000000..5e03543e3 --- /dev/null +++ b/main/feedback-h5/js/api.js @@ -0,0 +1,263 @@ +// 反馈系统 API 调用模块 +// API 走相对路径(同源请求,不会有 CORS 和混合内容问题) +// +// 架构(FRP 单端口模式): +// 外网 https://feedback.new123.vip +// → FRP 隧道 → 本地 8007 (start.py) +// ├─ /api/v1/* → 反代到 127.0.0.1:8009 (feedback-backend) +// ├─ /xiaozhi/* → 反代到 127.0.0.1:8002 (Java) +// └─ / → H5 静态文件 +// +// 本地开发时(端口 8007 直连)和生产环境(FRP+域名)使用同一套相对路径配置 + +const FEEDBACK_API_BASE = window.location.origin + '/api/v1'; + +// WebSocket 走 OTA 返回的地址(带 token),由 connectVoice 处理 +// 生产环境如果 WebSocket 也要走 FRP,需要 OTA 返回 wss://feedback.new123.vip/ws/ 这种地址 +const WS_BASE = (window.location.protocol === 'https:' ? 'wss:' : 'ws:') + + '//' + window.location.host + '/ws'; + +export { FEEDBACK_API_BASE, WS_BASE }; + +export const FeedbackAPI = { + // 通过6位码查询门店信息 + async getStoreByCode(storeCode) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/store/${storeCode}`); + const data = await res.json(); + if (data.code === 0) { + return { success: true, data: data.data }; + } + return { success: false, message: data.msg || '门店查询失败' }; + } catch (e) { + console.error('门店查询失败:', e); + return { success: false, message: '门店不存在或网络错误' }; + } + }, + + // 获取门店下的员工列表 + async getEmployees(storeId) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/employees/${storeId}`); + const data = await res.json(); + if (data.code === 0) { + return { success: true, data: data.data || [] }; + } + return { success: false, message: data.msg || '获取员工列表失败' }; + } catch (e) { + console.error('员工列表查询失败:', e); + return { success: false, message: '网络错误' }; + } + }, + + // 初始化设备绑定 - 返回 deviceMac、otaUrl、agentId、otaResult + async deviceInit(storeId, employeeId) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/device-init`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ storeId, employeeId }) + }); + const data = await res.json(); + if (data.code === 0) { + return { success: true, data: data.data }; + } + throw new Error(data.msg); + } catch (e) { + console.error('设备初始化失败:', e); + // fallback: 前端自己生成 MAC(注意:没有 otaResult,需要在语音页重新获取) + let mac = localStorage.getItem('feedback_device_mac'); + if (!mac) { + const hex = '0123456789ABCDEF'; + mac = 'FB'; + for (let i = 0; i < 5; i++) { + mac += ':' + hex.charAt(Math.floor(Math.random()*16)) + hex.charAt(Math.floor(Math.random()*16)); + } + localStorage.setItem('feedback_device_mac', mac); + } + return { + success: true, + data: { + deviceMac: mac, + // 没有 otaResult,connectVoice 会在语音页重新调用 OTA + } + }; + } + }, + + // 保存反馈记录 → feedback-backend + async saveRecord(recordData) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/record`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(recordData) + }); + const data = await res.json(); + return { success: data.code === 0 }; + } catch (e) { + console.error('保存记录失败:', e); + return { success: false }; + } + }, + + // 调用反馈AI处理 → feedback-backend(3步 LLM Pipeline) + async processFeedback(processData) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/process`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(processData) + }); + const data = await res.json(); + if (data.code === 0 && data.data && data.data.success) { + return { success: true, data: data.data }; + } + return { success: false, message: (data.data && data.data.message) || data.msg || 'AI处理失败' }; + } catch (e) { + console.error('AI处理连接失败:', e); + return { success: false, message: 'AI处理服务连接失败' }; + } + }, + + // 预约页初始化:门店、技师、当天空档 + async appointmentBootstrap(storeCode, date, durationMinutes = 60) { + try { + const params = new URLSearchParams({ storeCode, durationMinutes: String(durationMinutes) }); + if (date) params.set('date', date); + const res = await fetch(`${FEEDBACK_API_BASE}/public/appointment/bootstrap?${params.toString()}`); + const data = await res.json(); + return { success: data.code === 0, data: data.data, message: data.msg }; + } catch (e) { + console.error('预约初始化失败:', e); + return { success: false, message: '预约初始化失败' }; + } + }, + + // 查询预约空档 + async getAppointmentAvailability(storeCode, date, employeeId, durationMinutes = 60) { + try { + const params = new URLSearchParams({ storeCode, date, durationMinutes: String(durationMinutes) }); + if (employeeId) params.set('employeeId', employeeId); + const res = await fetch(`${FEEDBACK_API_BASE}/public/appointment/availability?${params.toString()}`); + const data = await res.json(); + return { success: data.code === 0, data: data.data, message: data.msg }; + } catch (e) { + console.error('查询预约空档失败:', e); + return { success: false, message: '查询预约空档失败' }; + } + }, + + // 根据手机号查询客户可预约项目 + async getAppointmentMemberProducts(storeCode, phone) { + try { + const params = new URLSearchParams({ storeCode, phone }); + const res = await fetch(`${FEEDBACK_API_BASE}/public/appointment/member-products?${params.toString()}`); + const data = await res.json(); + return { success: data.code === 0, data: data.data, message: data.msg, code: data.code }; + } catch (e) { + console.error('查询客户项目失败:', e); + return { success: false, message: '查询客户项目失败' }; + } + }, + + // 查询我的未完成预约 + async getMyAppointments(storeCode, phone) { + try { + const params = new URLSearchParams({ storeCode, phone }); + const res = await fetch(`${FEEDBACK_API_BASE}/public/appointment/my?${params.toString()}`); + const data = await res.json(); + return { success: data.code === 0, data: data.data, message: data.msg, code: data.code }; + } catch (e) { + console.error('查询我的预约失败:', e); + return { success: false, message: '查询我的预约失败' }; + } + }, + + async cancelAppointmentPublic(payload) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/appointment/cancel`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) + }); + const data = await res.json(); + return { success: data.code === 0, data: data.data, message: data.msg, code: data.code }; + } catch (e) { + console.error('取消预约失败:', e); + return { success: false, message: '取消预约失败' }; + } + }, + + async rescheduleAppointmentPublic(payload) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/appointment/reschedule`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) + }); + const data = await res.json(); + return { success: data.code === 0, data: data.data, message: data.msg, code: data.code }; + } catch (e) { + console.error('改约失败:', e); + return { success: false, message: '改约失败' }; + } + }, + + + // 提交预约(后端会实时二次校验冲突) + async bookAppointment(payload) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/appointment/book`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + const data = await res.json(); + return { success: data.code === 0, data: data.data, message: data.msg, code: data.code }; + } catch (e) { + console.error('提交预约失败:', e); + return { success: false, message: '提交预约失败' }; + } + }, + + // OTA连接 - 通过 feedback-backend 代理转发到 Java manager-api(避免浏览器 CORS) + async connectOTA(deviceMac, clientId) { + try { + const res = await fetch(`${FEEDBACK_API_BASE}/public/ota/`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Device-Id': deviceMac, + 'Client-Id': clientId || 'feedback_client' + }, + body: JSON.stringify({ + version: 0, + uuid: '', + application: { + name: 'xiaozhi-feedback-h5', + version: '1.0.0', + compile_time: '2026-06-10 10:00:00', + idf_version: '4.4.3', + elf_sha256: '1234567890abcdef1234567890abcdef1234567890abcdef' + }, + ota: { label: 'xiaozhi-feedback-h5' }, + board: { + type: '反馈H5', + ssid: 'xiaozhi-feedback-h5', + rssi: 0, + channel: 0, + ip: '192.168.1.1', + mac: deviceMac + }, + flash_size: 0, + minimum_free_heap_size: 0, + mac_address: deviceMac, + chip_model_name: '', + chip_info: { model: 0, cores: 0, revision: 0, features: 0 }, + partition_table: [{ label: '', type: 0, subtype: 0, address: 0, size: 0 }] + }) + }); + return await res.json(); + } catch (e) { + console.error('OTA连接失败:', e); + return null; + } + } +}; diff --git a/main/feedback-h5/js/app.js b/main/feedback-h5/js/app.js new file mode 100644 index 000000000..5922a1523 --- /dev/null +++ b/main/feedback-h5/js/app.js @@ -0,0 +1,2002 @@ +// 主应用模块 - SPA路由 + 状态管理 + 页面视图 + +import { FeedbackAPI, WS_BASE } from './api.js'; +import { copyToClipboard, showManualCopySheet, isMobile, speak, openDianping, openMeituan, getEmployeeTypeLabel } from './utils.js'; +import { getAudioPlayer } from './audio-player.js'; +import { getAudioRecorder, checkMicrophoneAvailability } from './audio-recorder.js'; +import { checkOpusLoaded } from './opus-codec.js'; + +// 等待 Opus 库异步初始化完成 +async function waitForOpusReady(maxWait = 5000) { + const start = Date.now(); + while (Date.now() - start < maxWait) { + if (typeof Module !== 'undefined') { + // Module.instance 是工厂函数返回的实例 + const inst = (typeof Module.instance !== 'undefined') ? Module.instance : Module; + if (typeof inst._opus_decoder_get_size === 'function' && + typeof inst._opus_encoder_get_size === 'function') { + window.ModuleInstance = inst; + console.log('[Opus] 库初始化完成'); + return true; + } + } + await new Promise(r => setTimeout(r, 100)); + } + console.warn('[Opus] 库初始化超时'); + return false; +} + +// 启动时初始化 Opus +waitForOpusReady().then(() => checkOpusLoaded()); + +// 应用状态 +const appState = { + currentPage: 'home', + storeCode: '', + storeInfo: null, + employees: [], + selectedEmployee: null, + deviceMac: '', + sessionId: '', + chatMessages: [], + customerName: '', + phoneTail: '', + customerIdentity: null, + feedbackResult: null, + ws: null, + otaResult: null, + live2dManager: null, + audioPlayer: null, + audioRecorder: null, + isRemoteSpeaking: false, + appointment: null, +}; + +// 暴露给 Live2D 使用 +window.chatApp = appState; + +// 从URL参数读取store code +function getUrlParams() { + const hash = window.location.hash || '#/home'; + const [path, query] = hash.substring(2).split('?'); + const params = {}; + if (query) { + query.split('&').forEach(p => { + const [k, v] = p.split('='); + params[k] = decodeURIComponent(v); + }); + } + return { path, params }; +} + +function navigate(page) { + window.location.hash = `#/${page}`; +} + +// 页面渲染入口 +function render() { + const { path, params } = getUrlParams(); + const app = document.getElementById('app'); + + switch (path) { + case 'home': + appState.storeCode = params.code || ''; + renderHome(app); + break; + case 'appointment': + appState.storeCode = params.storeCode || params.code || ''; + renderAppointment(app); + break; + case 'voice': + renderVoice(app); + break; + case 'result': + renderResult(app); + break; + case 'publish': + renderPublish(app); + break; + case 'complete': + renderComplete(app); + break; + default: + renderHome(app); + } +} + +// ==================== 客户预约页 ==================== +function todayISO() { + const d = new Date(); + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +function appointmentSpeak(text) { + try { + if ('speechSynthesis' in window) { + window.speechSynthesis.cancel(); + const u = new SpeechSynthesisUtterance(text); + u.lang = 'zh-CN'; + u.rate = 1; + window.speechSynthesis.speak(u); + } + } catch (e) {} +} + +function showVoiceUnlockHint(message = '手机浏览器需要点一下才能开启麦克风和语音播报') { + const btn = document.getElementById('aptStartVoiceBtn'); + const status = document.getElementById('aptListenStatus'); + if (btn) btn.style.display = 'block'; + if (status) status.textContent = message; +} + +function hideVoiceUnlockHint() { + const btn = document.getElementById('aptStartVoiceBtn'); + if (btn) btn.style.display = 'none'; +} + +function unlockAppointmentVoice() { + const state = appState.appointment; + if (!state || state.completed) return; + state.voiceUnlocked = true; + hideVoiceUnlockHint(); + try { + // 用一次空播报解锁移动端 TTS;部分浏览器需要用户手势触发。 + if ('speechSynthesis' in window) { + window.speechSynthesis.cancel(); + const u = new SpeechSynthesisUtterance(''); + u.lang = 'zh-CN'; + window.speechSynthesis.speak(u); + } + } catch (e) {} + startAppointmentAutoListen(); +} + +function renderAppointment(container) { + container.innerHTML = ` +
      +
      +
      智能预约
      +

      正在加载门店...

      +

      我会先读取今天所有技师排期,为您快速预约

      +
      + + +
      `; + initAppointmentPage(); +} + +async function initAppointmentPage() { + const err = document.getElementById('aptError'); + if (!appState.storeCode) { + err.textContent = '缺少门店编码,请确认预约链接是否正确'; + err.style.display = 'block'; + return; + } + const result = await FeedbackAPI.appointmentBootstrap(appState.storeCode, todayISO(), 60); + if (!result.success) { + err.textContent = result.message || '预约初始化失败'; + err.style.display = 'block'; + return; + } + const data = result.data; + appState.appointment = { + store: data.store, + date: data.date, + durationMinutes: data.durationMinutes || 60, + employees: data.employees || [], + availability: data.availability || { slots: [] }, + selectedEmployee: null, + selectedSlot: null, + member: null, + products: [], + selectedProduct: null, + recognition: null, + listening: false, + completed: false, + voiceUnlocked: false, + intent: 'book', + myAppointments: [], + selectedExistingAppointment: null, + }; + document.getElementById('aptStoreName').textContent = data.store.storeName; + document.getElementById('aptSubtitle').textContent = `今天可预约技师 ${appState.appointment.employees.length} 位,已为您提前加载空闲时间`; + document.getElementById('aptMain').style.display = 'block'; + renderAppointmentEmployees(); + const names = appState.appointment.employees.map(e => `${e.number}号技师${e.name}`).join('、'); + setAppointmentAiText(`您好,今天可以预约的技师有:${names}。请问您想预约哪位技师?`, true); + setTimeout(startAppointmentAutoListen, 800); + document.getElementById('aptSubmitBtn').addEventListener('click', submitAppointment); + document.getElementById('aptVoicePanel').addEventListener('click', unlockAppointmentVoice); + document.getElementById('aptStartVoiceBtn').addEventListener('click', unlockAppointmentVoice); + document.addEventListener('click', unlockAppointmentVoice, { once: true }); + document.getElementById('aptLookupBtn').addEventListener('click', lookupAppointmentProductsFromInput); + document.getElementById('aptPhone').addEventListener('input', (e) => { + const phone = (e.target.value || '').replace(/\D/g, ''); + if (phone.length >= 11) lookupAppointmentProducts(phone); + }); +} + +function renderAppointmentEmployees() { + const list = document.getElementById('aptEmployees'); + const state = appState.appointment; + list.innerHTML = state.employees.map(e => ` + `).join(''); + list.querySelectorAll('.apt-employee').forEach(btn => { + btn.addEventListener('click', () => selectAppointmentEmployee(btn.dataset.id)); + }); +} + +function selectAppointmentEmployee(employeeId) { + const state = appState.appointment; + state.selectedEmployee = state.employees.find(e => e.id === employeeId); + state.selectedSlot = null; + renderAppointmentEmployees(); + renderAppointmentSlots(); + const slots = getAvailableSlotsForEmployee(employeeId).slice(0, 5); + const text = slots.length + ? `${state.selectedEmployee.name}今天可以预约:${slots.map(s => formatSlotText(s.start)).join('、')}。您想约哪个时间?` + : `${state.selectedEmployee.name}今天暂时没有可预约时间,请选择其他技师。`; + setAppointmentAiText(text, true); + updateAppointmentConfirm(); +} + +function getAvailableSlotsForEmployee(employeeId) { + return (appState.appointment?.availability?.slots || []) + .filter(s => s.employeeId === employeeId && s.available); +} + +function renderAppointmentSlots() { + const state = appState.appointment; + const box = document.getElementById('aptSlots'); + if (!state.selectedEmployee) { + box.innerHTML = '
      请先选择技师
      '; + return; + } + const slots = getAvailableSlotsForEmployee(state.selectedEmployee.id); + if (slots.length === 0) { + box.innerHTML = '
      该技师今天暂无空闲,请选择其他技师
      '; + return; + } + box.innerHTML = slots.map(s => ` + `).join(''); + box.querySelectorAll('.apt-slot').forEach(btn => { + btn.addEventListener('click', () => { + state.selectedSlot = { start: btn.dataset.start, end: btn.dataset.end }; + renderAppointmentSlots(); + updateAppointmentConfirm(); + setAppointmentAiText(`好的,我帮您确认一下:${state.selectedEmployee.name},${formatDateZh(state.date)}${formatSlotText(state.selectedSlot.start)}。请直接说或输入手机号,我帮您查询项目后确认预约。`, true); + }); + }); +} + +async function lookupAppointmentProductsFromInput() { + const phone = (document.getElementById('aptPhone')?.value || '').replace(/\D/g, ''); + if (!phone || phone.length < 7) { + alert('请先输入手机号'); + return; + } + await lookupAppointmentProducts(phone); +} + +async function lookupAppointmentProducts(phone) { + const state = appState.appointment; + if (!state || state._lastLookupPhone === phone) return; + state._lastLookupPhone = phone; + const box = document.getElementById('aptProducts'); + const memberInfo = document.getElementById('aptMemberInfo'); + box.innerHTML = '
      正在查询您的项目...
      '; + const result = await FeedbackAPI.getAppointmentMemberProducts(state.store.storeCode, phone); + if (!result.success) { + state.member = null; + state.products = []; + state.selectedProduct = null; + memberInfo.style.display = 'none'; + box.innerHTML = `
      ${result.message || '未查询到项目'}
      `; + setAppointmentAiText(result.message || '未查询到您的项目,请联系门店确认。', true); + updateAppointmentConfirm(); + return; + } + state.member = result.data.member; + state.products = result.data.products || []; + state.selectedProduct = null; + memberInfo.style.display = 'block'; + memberInfo.textContent = `已识别客户:${state.member?.name || '顾客'}(${phone})`; + renderAppointmentProducts(); + const productNames = state.products.map(p => p.productName).join('、'); + setAppointmentAiText(state.products.length ? `查到了您的项目:${productNames}。请选择本次要预约的项目。` : '已找到客户档案,但暂无可预约项目,请联系门店确认。', true); + updateAppointmentConfirm(); +} + +function renderAppointmentProducts() { + const state = appState.appointment; + const box = document.getElementById('aptProducts'); + if (!state.products.length) { + box.innerHTML = '
      暂无可预约项目
      '; + return; + } + box.innerHTML = state.products.map(p => ` + `).join(''); + box.querySelectorAll('.apt-product').forEach(btn => { + btn.addEventListener('click', () => { + state.selectedProduct = state.products.find(p => p.id === btn.dataset.id); + state.durationMinutes = state.selectedProduct?.durationMinutes || state.durationMinutes || 60; + renderAppointmentProducts(); + updateAppointmentConfirm(); + setAppointmentAiText(`已选择${state.selectedProduct.productName}。请确认技师、时间和项目无误后提交预约。`, true); + }); + }); +} + +async function lookupMyAppointments(phone) { + const state = appState.appointment; + if (!state) return; + const box = document.getElementById('aptExistingAppointments'); + box.style.display = 'grid'; + box.innerHTML = '
      正在查询您的预约...
      '; + const result = await FeedbackAPI.getMyAppointments(state.store.storeCode, phone); + if (!result.success) { + state.myAppointments = []; + state.selectedExistingAppointment = null; + box.innerHTML = `
      ${result.message || '未查询到预约'}
      `; + setAppointmentAiText(result.message || '未查询到可操作的预约。', true); + updateAppointmentConfirm(); + return; + } + state.member = result.data.member; + state.myAppointments = result.data.appointments || []; + state.selectedExistingAppointment = null; + renderMyAppointments(); + setAppointmentAiText(state.myAppointments.length ? '已查到您的预约,请选择要操作的预约。' : '没有查到未完成的预约。', true); + updateAppointmentConfirm(); +} + +function renderMyAppointments() { + const state = appState.appointment; + const box = document.getElementById('aptExistingAppointments'); + box.style.display = 'grid'; + if (!state.myAppointments.length) { + box.innerHTML = '
      暂无未完成预约
      '; + return; + } + box.innerHTML = state.myAppointments.map(a => ` + `).join(''); + box.querySelectorAll('.apt-product').forEach(btn => { + btn.addEventListener('click', () => { + state.selectedExistingAppointment = state.myAppointments.find(a => a.id === btn.dataset.id); + if (state.intent === 'reschedule' && state.selectedExistingAppointment?.employeeId) { + state.selectedEmployee = state.employees.find(e => e.id === state.selectedExistingAppointment.employeeId) || state.selectedEmployee; + renderAppointmentEmployees(); + renderAppointmentSlots(); + } + renderMyAppointments(); + if (state.intent === 'cancel') { + setAppointmentAiText('已选中预约。您说确认或点击确认按钮,我就帮您取消。', true); + } else if (state.intent === 'reschedule') { + setAppointmentAiText('已选中原预约。请重新选择技师和时间,然后确认改约。', true); + } + updateAppointmentConfirm(); + }); + }); +} + +function employeeNameById(id) { + return appState.appointment?.employees?.find(e => e.id === id)?.name || ''; +} + +function updateAppointmentConfirm() { + const state = appState.appointment; + const text = document.getElementById('aptConfirmText'); + const btn = document.getElementById('aptSubmitBtn'); + if (state.intent === 'cancel') { + if (!state.selectedExistingAppointment) { + text.textContent = '请选择要取消的预约'; + btn.disabled = true; + return; + } + text.textContent = `将取消:${formatAppointmentDateTime(state.selectedExistingAppointment.startAt)} · ${state.selectedExistingAppointment.productName || '预约服务'}`; + btn.textContent = '确认取消预约'; + btn.disabled = false; + return; + } + if (state.intent === 'reschedule') { + if (!state.selectedExistingAppointment || !state.selectedEmployee || !state.selectedSlot) { + text.textContent = '请选择原预约和新的技师/时间'; + btn.textContent = '确认改约'; + btn.disabled = true; + return; + } + text.textContent = `将改约到:${state.selectedEmployee.name} · ${formatDateZh(state.date)} ${state.selectedSlot.start}`; + btn.textContent = '确认改约'; + btn.disabled = false; + return; + } + if (!state?.selectedEmployee || !state?.selectedSlot || !state?.selectedProduct) { + text.textContent = '请选择技师、时间和项目'; + btn.textContent = '确认预约'; + btn.disabled = true; + return; + } + text.textContent = `已选择:${state.selectedEmployee.name} · ${formatDateZh(state.date)} ${state.selectedSlot.start} · ${state.selectedProduct.productName}`; + btn.textContent = '确认预约'; + btn.disabled = false; +} + +async function submitAppointment() { + const state = appState.appointment; + const phone = (document.getElementById('aptPhone').value || '').replace(/\D/g, ''); + if (!state?.selectedEmployee || !state?.selectedSlot || !state?.selectedProduct) return; + if (!phone || phone.length < 7) { alert('请填写有效手机号'); return; } + + const btn = document.getElementById('aptSubmitBtn'); + btn.disabled = true; + + if (state.intent === 'cancel') { + btn.textContent = '正在取消...'; + const result = await FeedbackAPI.cancelAppointmentPublic({ + storeCode: state.store.storeCode, + customerPhone: phone, + appointmentId: state.selectedExistingAppointment?.id, + reason: '客户H5取消', + }); + if (result.success) { + state.completed = true; + stopAppointmentListening(); + btn.textContent = '已取消'; + setAppointmentAiText('好的,您的预约已取消。', true); + } else { + btn.disabled = false; + btn.textContent = '确认取消预约'; + setAppointmentAiText(result.message || '取消失败,请稍后再试。', true); + } + return; + } + + if (state.intent === 'reschedule') { + btn.textContent = '正在实时确认新档期...'; + const startAt = `${state.date}T${state.selectedSlot.start}:00`; + const result = await FeedbackAPI.rescheduleAppointmentPublic({ + storeCode: state.store.storeCode, + customerPhone: phone, + appointmentId: state.selectedExistingAppointment?.id, + employeeId: state.selectedEmployee.id, + startAt, + durationMinutes: state.selectedExistingAppointment?.durationMinutes || state.durationMinutes, + reason: '客户H5改约', + }); + if (result.success) { + state.completed = true; + stopAppointmentListening(); + btn.textContent = '改约成功'; + setAppointmentAiText(`改约成功,新的时间是${formatDateZh(state.date)}${formatSlotText(state.selectedSlot.start)}。`, true); + } else if (result.code === 409) { + btn.disabled = false; + btn.textContent = '确认改约'; + await refreshAppointmentAvailability(); + setAppointmentAiText('不好意思,新时间刚刚被预约了,请重新选择其他时间。', true); + } else { + btn.disabled = false; + btn.textContent = '确认改约'; + setAppointmentAiText(result.message || '改约失败,请稍后再试。', true); + } + return; + } + + btn.textContent = '正在实时确认档期...'; + setAppointmentAiText('好的,正在为您预约,请稍后。我会实时确认这个时间是否还没有被别人预定。', true); + + const startAt = `${state.date}T${state.selectedSlot.start}:00`; + const result = await FeedbackAPI.bookAppointment({ + storeCode: state.store.storeCode, + employeeId: state.selectedEmployee.id, + startAt, + durationMinutes: state.selectedProduct.durationMinutes || state.durationMinutes, + customerName: state.member?.name || '', + customerPhone: phone, + memberProductId: state.selectedProduct.memberProductId, + productId: state.selectedProduct.productId, + serviceName: state.selectedProduct.productName || '预约服务', + notes: '客户H5预约', + }); + if (result.success) { + state.completed = true; + stopAppointmentListening(); + btn.textContent = '预约成功'; + setAppointmentAiText(`预约成功,已为您安排${state.selectedEmployee.name},时间是${formatDateZh(state.date)}${formatSlotText(state.selectedSlot.start)}。请您按时到店。`, true); + btn.disabled = true; + } else if (result.code === 409) { + btn.textContent = '确认预约'; + btn.disabled = false; + await refreshAppointmentAvailability(); + setAppointmentAiText(`不好意思,刚刚这个时间已经被其他顾客预约了。请您重新选择其他时间。`, true); + } else { + btn.textContent = '确认预约'; + btn.disabled = false; + setAppointmentAiText(result.message || '预约失败,请稍后再试', true); + } +} + +async function refreshAppointmentAvailability() { + const state = appState.appointment; + const result = await FeedbackAPI.getAppointmentAvailability(state.store.storeCode, state.date, null, state.durationMinutes); + if (result.success) { + state.availability = result.data; + state.selectedSlot = null; + renderAppointmentSlots(); + updateAppointmentConfirm(); + } +} + +function stopAppointmentListening() { + const state = appState.appointment; + if (!state) return; + try { + if (state.recognition) state.recognition.stop(); + } catch (e) {} + state.recognition = null; + state.listening = false; + const status = document.getElementById('aptListenStatus'); + if (status) status.textContent = '预约已完成,语音监听已关闭'; +} + +function startAppointmentAutoListen() { + const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; + const status = document.getElementById('aptListenStatus'); + if (!SpeechRecognition) { + if (status) status.textContent = '当前浏览器不支持自动语音识别,请手动输入手机号和选择项目'; + return; + } + const state = appState.appointment; + if (!state || state.completed || state.listening) return; + try { + const rec = new SpeechRecognition(); + rec.lang = 'zh-CN'; + rec.interimResults = false; + rec.continuous = false; + state.recognition = rec; + state.listening = true; + if (status) status.textContent = '正在聆听... 可直接说手机号、技师或时间'; + rec.onresult = e => { + const text = Array.from(e.results).map(r => r[0]?.transcript || '').join(''); + handleAppointmentUtterance(text); + }; + rec.onerror = e => { + if (e.error === 'not-allowed' || e.error === 'service-not-allowed') { + showVoiceUnlockHint('请点一下按钮并允许麦克风权限'); + } else { + if (status) status.textContent = '环境较嘈杂,我会继续听有效信息'; + } + }; + rec.onend = () => { + state.listening = false; + if (state.completed) { + if (status) status.textContent = '预约已完成,语音监听已关闭'; + return; + } + if (status) status.textContent = '继续聆听中...'; + if (window.location.hash.includes('/appointment')) { + setTimeout(startAppointmentAutoListen, 500); + } + }; + rec.start(); + } catch (e) { + state.listening = false; + showVoiceUnlockHint('请点一下按钮开始语音预约'); + } +} + +function enterAppointmentAction(intent) { + const state = appState.appointment; + if (!state) return; + state.intent = intent; + state.selectedExistingAppointment = null; + document.getElementById('aptProducts').innerHTML = '
      取消/改约无需选择项目,请先说手机号查询预约
      '; + document.getElementById('aptExistingAppointments').style.display = 'grid'; + document.getElementById('aptExistingAppointments').innerHTML = '
      请直接说或输入手机号,我帮您查询未完成预约
      '; + setAppointmentAiText(intent === 'cancel' ? '好的,我来帮您取消预约。请直接说您的手机号。' : '好的,我来帮您改约时间。请直接说您的手机号。', true); + updateAppointmentConfirm(); +} + +function handleAppointmentUtterance(text) { + const state = appState.appointment; + if (!state) return; + text = normalizeSpeechText(text); + if (!text) return; + const wantsCancel = /不能参加|不参加|不去了|取消|取消预约|来不了|不能去了/.test(text); + const wantsReschedule = /改约|改时间|换时间|改到|换到|重新约/.test(text); + if (wantsCancel) enterAppointmentAction('cancel'); + if (wantsReschedule) enterAppointmentAction('reschedule'); + const phone = matchPhone(text); + const emp = matchAppointmentEmployee(text); + const product = matchAppointmentProduct(text); + const slot = matchAppointmentSlot(text); + const confirmed = /确认|对的|可以|就这个|没问题|好的|好/.test(text); + if (!phone && !emp && !product && !slot && !confirmed && !wantsCancel && !wantsReschedule) { + const status = document.getElementById('aptListenStatus'); + if (status) status.textContent = '环境较嘈杂,已忽略无关声音,继续聆听...'; + return; + } + setAppointmentAiText(`您说:${text}`, false); + if (phone) { + const input = document.getElementById('aptPhone'); + if (input) input.value = phone; + if (state.intent === 'cancel' || state.intent === 'reschedule') { + lookupMyAppointments(phone); + } else { + lookupAppointmentProducts(phone); + } + } + if (emp) { + selectAppointmentEmployee(emp.id); + } + if (product) { + appState.appointment.selectedProduct = product; + appState.appointment.durationMinutes = product.durationMinutes || appState.appointment.durationMinutes || 60; + renderAppointmentProducts(); + updateAppointmentConfirm(); + setAppointmentAiText(`已选择${product.productName}。`, true); + } + if (slot && state.selectedEmployee) { + state.selectedSlot = slot; + renderAppointmentSlots(); + updateAppointmentConfirm(); + setAppointmentAiText(`好的,我帮您确认:${state.selectedEmployee.name},${formatDateZh(state.date)}${formatSlotText(slot.start)}。请直接说您的手机号,我帮您查询可预约项目。`, true); + return; + } + if (confirmed && state.selectedEmployee && state.selectedSlot && state.selectedProduct) { + submitAppointment(); + return; + } + if (!state.selectedEmployee) { + setAppointmentAiText('请告诉我想预约哪位技师,比如说:我要约2号技师。', true); + } else if (!state.selectedSlot) { + setAppointmentAiText('请告诉我想约几点,比如说:下午3点。', true); + } else if (!state.member) { + setAppointmentAiText('请直接说您的手机号,我帮您查询可预约项目。', true); + } else if (!state.selectedProduct) { + setAppointmentAiText('请从卡片中选择本次要预约的项目,或直接说项目名称。', true); + } +} + +function normalizeSpeechText(text) { + return String(text || '') + .replace(/幺/g, '一') + .replace(/零/g, '0') + .replace(/〇/g, '0') + .replace(/一/g, '1') + .replace(/二/g, '2') + .replace(/两/g, '2') + .replace(/三/g, '3') + .replace(/四/g, '4') + .replace(/五/g, '5') + .replace(/六/g, '6') + .replace(/七/g, '7') + .replace(/八/g, '8') + .replace(/九/g, '9') + .replace(/十1/g, '11') + .replace(/十2/g, '12') + .replace(/十/g, '10') + .trim(); +} + +function matchPhone(text) { + const normalized = normalizeSpeechText(text).replace(/[,,。\s\-]/g, ''); + const full = normalized.match(/1\d{10}/); + if (full) return full[0]; + const digits = normalized.replace(/\D/g, ''); + return digits.length >= 7 ? digits : ''; +} + +function matchAppointmentProduct(text) { + const state = appState.appointment; + if (!state?.products?.length) return null; + return state.products.find(p => text.includes(p.productName)) || null; +} + +function matchAppointmentEmployee(text) { + const state = appState.appointment; + if (!state) return null; + for (const e of state.employees) { + if (text.includes(e.name) || text.includes(`${e.number}号`) || text.includes(`${e.number} 号`)) return e; + } + return null; +} + +function matchAppointmentSlot(text) { + const state = appState.appointment; + if (!state?.selectedEmployee) return null; + const slots = getAvailableSlotsForEmployee(state.selectedEmployee.id); + const hourMatch = text.match(/(\d{1,2}|一|二|两|三|四|五|六|七|八|九|十|十一|十二)点/); + if (!hourMatch) return null; + const hour = chineseHourToNumber(hourMatch[1]); + const isPm = /下午|晚上/.test(text) || (hour >= 1 && hour <= 8 && !/上午|早上/.test(text)); + const h24 = isPm && hour < 12 ? hour + 12 : hour; + const minute = /半/.test(text) ? '30' : '00'; + const target = `${String(h24).padStart(2, '0')}:${minute}`; + return slots.find(s => s.start === target) || slots.find(s => s.start.startsWith(String(h24).padStart(2, '0'))); +} + +function chineseHourToNumber(v) { + const map = { '一':1, '二':2, '两':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '十':10, '十一':11, '十二':12 }; + return map[v] || parseInt(v, 10); +} + +function setAppointmentAiText(text, shouldSpeak = false) { + const el = document.getElementById('aptAiText'); + if (el) el.textContent = text; + if (shouldSpeak) appointmentSpeak(text); +} + +function formatAppointmentDateTime(value) { + if (!value) return '-'; + const s = String(value).replace('T', ' '); + return `${s.slice(0, 10)} ${s.slice(11, 16)}`; +} + +function formatSlotText(time) { + const [h, m] = time.split(':').map(Number); + const prefix = h < 12 ? '上午' : h < 18 ? '下午' : '晚上'; + const hour = h > 12 ? h - 12 : h; + return `${prefix}${hour}点${m === 30 ? '半' : ''}`; +} + +function formatDateZh(date) { + const today = todayISO(); + return date === today ? '今天' : date; +} + +// ==================== 首页 ==================== +async function renderHome(container) { + // 返回首页时清理 WebSocket 和音频资源 + if (appState.ws) { + try { appState.ws.close(); } catch (e) {} + appState.ws = null; + } + if (appState.audioRecorder?.isRecording) { + try { appState.audioRecorder.stop(); } catch (e) {} + } + appState.chatMessages = []; + appState.customerName = ''; + appState.phoneTail = ''; + appState.customerIdentity = null; + appState.sessionId = ''; + appState._otaResult = null; + + container.innerHTML = ` +
      + +
      + +
      + + +
      +
      + + +
      `; + + document.getElementById('queryStoreBtn').addEventListener('click', queryStore); + document.getElementById('storeCodeInput').addEventListener('keyup', (e) => { + if (e.key === 'Enter') queryStore(); + }); + document.getElementById('startFeedbackBtn').addEventListener('click', startFeedback); + + // 如果 URL 带了 code 参数,自动查询并隐藏输入框(用户体验:扫码进入即直奔员工选择) + if (appState.storeCode) { + document.getElementById('storeCodeInput').value = appState.storeCode; + appState._codeFromUrl = true; + queryStore(); + } else { + appState._codeFromUrl = false; + } +} + +async function queryStore() { + const codeInput = document.getElementById('storeCodeInput'); + const code = codeInput.value.trim(); + if (!code) return; + + const errEl = document.getElementById('errorMessage'); + errEl.style.display = 'none'; + + const result = await FeedbackAPI.getStoreByCode(code); + if (!result.success) { + errEl.textContent = result.message; + errEl.style.display = 'block'; + document.getElementById('storeInfoSection').style.display = 'none'; + return; + } + + appState.storeInfo = result.data; + appState.storeCode = code; + + if (!result.data.agentId) { + errEl.textContent = '门店配置中,请稍后再试'; + errEl.style.display = 'block'; + document.getElementById('storeInfoSection').style.display = 'none'; + return; + } + + document.getElementById('storeNameDisplay').textContent = result.data.storeName; + document.getElementById('storeCodeDisplay').textContent = `服务码: ${result.data.storeCode}`; + document.getElementById('storeInfoSection').style.display = 'block'; + + // 如果服务码是从 URL 参数带进来的,查询成功后直接隐藏输入框(扫码场景免输入) + if (appState._codeFromUrl) { + const inputSection = document.getElementById('storeInputSection'); + if (inputSection) inputSection.style.display = 'none'; + } + + // 【预加载】门店查询成功后立即后台预热 Live2D 资源(不等用户选员工) + // 这样用户在选员工的几秒内,4MB 的模型文件已经下载完了 + preloadVoicePageResources(); + + const empResult = await FeedbackAPI.getEmployees(result.data.id); + if (empResult.success) { + appState.employees = empResult.data || []; + renderEmployeeList(); + } +} + +function renderEmployeeList() { + const list = document.getElementById('employeeList'); + list.innerHTML = appState.employees.map(emp => { + const typeLabel = getEmployeeTypeLabel(emp.employeeType); + return ` +
      + ${emp.number}号 + ${emp.name} + ${typeLabel ? `${typeLabel}` : ''} +
      `; + }).join(''); + + list.querySelectorAll('.employee-card').forEach(card => { + card.addEventListener('click', () => { + list.querySelectorAll('.employee-card').forEach(c => c.classList.remove('selected')); + card.classList.add('selected'); + const empId = card.dataset.empId; + appState.selectedEmployee = appState.employees.find(e => e.id === empId); + document.getElementById('startFeedbackBtn').disabled = false; + + // 【预加载】用户选完员工后,后台静默预热 Live2D 资源 + 音频上下文 + // 等用户点击"开始语音反馈"时,文件已经在浏览器缓存里了 + preloadVoicePageResources(); + }); + }); +} + +// 预加载语音页所需资源(在 home 页静默执行) +let _preloadStarted = false; +async function preloadVoicePageResources() { + if (_preloadStarted) return; + _preloadStarted = true; + console.log('[preload] 开始预加载语音页资源...'); + + const modelName = localStorage.getItem('live2dModel') || 'hiyori_pro_zh'; + const modelFileMap = { + 'hiyori_pro_zh': 'hiyori_pro_t11', + 'natori_pro_zh': 'natori_pro_t06', + }; + const fileBase = modelFileMap[modelName] || 'hiyori_pro_t11'; + const basePath = `resources/${modelName}/runtime/${fileBase}`; + + // 预加载模型相关文件(让浏览器缓存住) + const filesToPreload = [ + `${basePath}.model3.json`, + `${basePath}.moc3`, + `${basePath}.physics3.json`, + `${basePath}.cdi3.json`, + `${basePath}.2048/texture_00.png`, + `${basePath}.2048/texture_01.png`, + ]; + + // 用 fetch 预加载(结果会进 HTTP 缓存,PIXI.Live2D 后续加载会命中缓存) + const t0 = performance.now(); + await Promise.all(filesToPreload.map(url => + fetch(url, { cache: 'force-cache' }) + .then(r => r.blob()) + .catch(e => console.warn(`[preload] ${url} 失败:`, e.message)) + )); + console.log(`[preload] Live2D 资源预加载完成,耗时 ${Math.round(performance.now() - t0)}ms`); + + // 预初始化音频上下文(消除浏览器策略导致的首次启动延迟) + try { + const { getAudioPlayer } = await import('./audio-player.js'); + const player = getAudioPlayer(); + player.start(); + console.log('[preload] 音频播放器已预热'); + } catch (e) { + console.warn('[preload] 音频预热失败:', e.message); + } +} + +async function startFeedback() { + if (!appState.storeInfo || !appState.selectedEmployee) return; + + const btn = document.getElementById('startFeedbackBtn'); + btn.textContent = '准备中...'; + btn.disabled = true; + + // 检查麦克风 + const micOk = await checkMicrophoneAvailability(); + if (!micOk) { + btn.textContent = '开始语音反馈'; + btn.disabled = false; + alert('无法访问麦克风,请允许麦克风权限后重试'); + return; + } + + const initResult = await FeedbackAPI.deviceInit( + appState.storeInfo.id, + appState.selectedEmployee.id + ); + + if (!initResult.success) { + btn.textContent = '开始语音反馈'; + btn.disabled = false; + alert(initResult.message || '设备初始化失败'); + return; + } + + appState.deviceMac = initResult.data.deviceMac; + appState._deviceInitResult = initResult.data; + + // 检查 device_init 返回的 OTA 结果 + const otaResult = initResult.data.otaResult; + console.log('[startFeedback] deviceInit 返回 otaResult:', otaResult ? '有' : '无', + otaResult ? `activation=${!!otaResult.activation} websocket=${!!otaResult.websocket?.url}` : ''); + + if (otaResult && otaResult.activation && otaResult.activation.code) { + // 设备未绑定 → 显示激活码,等待管理员绑定 + appState._otaResult = otaResult; + showActivationCode(otaResult.activation.code, otaResult.websocket, btn, initResult.data.agentId); + return; + } + + if (otaResult && otaResult.websocket && otaResult.websocket.url) { + // 设备已绑定 → 直接连接 + appState._otaResult = otaResult; + navigate('voice'); + return; + } + + // OTA 未返回有效结果(Java 可能未运行),需要在语音页重新获取 + appState._otaResult = null; + console.warn('[startFeedback] device-init 未获取到 OTA 结果,将在语音页重试'); + navigate('voice'); +} + +// 显示激活码弹窗 +function showActivationCode(code, wsInfo, startBtn, agentId) { + // 生成带 agentId 的管理后台链接,方便管理员直接跳转 + const adminUrl = agentId + ? `http://localhost:8002/#/device-management?agentId=${agentId}` + : 'http://localhost:8002'; + + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` +
      `; + document.body.appendChild(overlay); + + document.getElementById('retryConnectBtn').addEventListener('click', async () => { + document.body.removeChild(overlay); + const btn2 = document.getElementById('startFeedbackBtn'); + if (btn2) { + btn2.textContent = '连接中...'; + btn2.disabled = true; + } + + // 重新调用 OTA 检查绑定状态 + const otaResult = await FeedbackAPI.connectOTA(appState.deviceMac, 'feedback_client'); + if (otaResult && otaResult.websocket && otaResult.websocket.url) { + // 绑定成功! + appState._otaResult = otaResult; + navigate('voice'); + } else if (otaResult && otaResult.activation && otaResult.activation.code) { + // 仍然未绑定,重新显示激活码 + showActivationCode(otaResult.activation.code, otaResult.websocket, btn2, agentId); + } else { + alert('连接失败,请检查管理后台是否正常运行'); + if (btn2) { + btn2.textContent = '开始语音反馈'; + btn2.disabled = false; + } + } + }); + + document.getElementById('activationCancelBtn').addEventListener('click', () => { + document.body.removeChild(overlay); + startBtn.textContent = '开始语音反馈'; + startBtn.disabled = false; + }); +} + +// ==================== 语音对话页 ==================== +function renderVoice(container) { + // 安全检查:必须先有门店信息和设备MAC(防止直接访问 #/voice URL) + if (!appState.storeInfo || !appState.deviceMac) { + console.warn('[renderVoice] 缺少必要状态,返回首页'); + navigate('home'); + return; + } + + // 清理之前的 Live2D 实例,防止 WebGL 上下文累积 + if (appState.live2dManager) { + try { + appState.live2dManager.destroy(); + } catch (e) { /* 忽略清理异常 */ } + appState.live2dManager = null; + } + + container.innerHTML = ` +
      + +
      +
      +
      ✨
      +

      智能助手准备中

      +

      请稍候,马上为您开启对话

      + +
      +
      +
      +
      0%
      + +
      +
      + ⏳ + 加载数字人形象 +
      +
      + ⏳ + 建立语音通道 +
      +
      + ⏳ + AI 准备开口 +
      +
      + +

      💡 即将开始与您的服务体验对话

      +
      +
      + + + + + +
      + 连接中... +
      + + +
      + + +
      + + +
      +
      `; + + // 重置准备状态 + appState._prepareState = { + live2dReady: false, + wsReady: false, + aiReady: false, + dismissed: false, + }; + + // 兜底:30 秒后无论如何强制淡出准备页(防止 AI 长时间不响应卡住) + // 注意:如果 WS 连接失败,showPrepareError 会先把准备页变成错误诊断页 + setTimeout(() => { + if (appState._prepareState && !appState._prepareState.dismissed) { + // 如果 WS 都没通,已经被错误诊断接管,不淡出 + if (!appState._prepareState.wsReady) { + console.warn('[prepareOverlay] 30秒超时但 WS 未就绪,保留页面让用户看错误'); + return; + } + console.warn('[prepareOverlay] 30秒兜底超时,强制淡出准备页'); + dismissPrepareOverlay(); + } + }, 30000); + + initLive2D(); + connectVoice(); +} + +// 更新准备进度 +function updatePrepareProgress() { + const state = appState._prepareState; + if (!state || state.dismissed) return; + + const steps = [ + { key: 'live2dReady', id: 'step-live2d' }, + { key: 'wsReady', id: 'step-ws' }, + { key: 'aiReady', id: 'step-ai' }, + ]; + let completed = 0; + steps.forEach(s => { + const el = document.getElementById(s.id); + if (!el) return; + const icon = el.querySelector('.step-icon'); + if (state[s.key]) { + completed++; + el.classList.add('done'); + if (icon) icon.textContent = '✅'; + } + }); + + const percent = Math.round((completed / steps.length) * 100); + const bar = document.getElementById('prepareProgressBar'); + const pct = document.getElementById('preparePercent'); + if (bar) bar.style.width = percent + '%'; + if (pct) pct.textContent = percent + '%'; + + // 全部就绪 → 淡出准备页 + if (state.live2dReady && state.wsReady && state.aiReady) { + dismissPrepareOverlay(); + } +} + +// 淡出准备页 +function dismissPrepareOverlay() { + const state = appState._prepareState; + if (!state || state.dismissed) return; + state.dismissed = true; + + const overlay = document.getElementById('prepareOverlay'); + if (overlay) { + overlay.classList.add('fading-out'); + setTimeout(() => { + if (overlay.parentNode) overlay.parentNode.removeChild(overlay); + }, 500); + } +} + +// 在准备页上显示连接错误诊断(不淡出) +function showPrepareError(code, reason) { + const state = appState._prepareState; + if (!state || state.dismissed) return; + + const overlay = document.getElementById('prepareOverlay'); + if (!overlay) return; + + // 1006: TLS/连接异常关闭(多半是 Nginx WS 没配 Upgrade 头) + // 1011: 服务端内部错误 + // 1015: TLS 失败 + let errorTitle = '连接失败'; + let errorReason = ''; + let errorTip = ''; + + if (code === 1006) { + errorTitle = '语音通道无法建立'; + errorReason = '后端 WebSocket 连接被中断(code 1006)'; + errorTip = '可能原因:\n• 反向代理(Nginx/FRP)未配置 WebSocket 升级头\n• xiaozhi-server 未运行或不可达\n• 域名 SSL 证书问题\n请联系管理员检查 Nginx 配置'; + } else if (code === 1011) { + errorTitle = '服务端错误'; + errorReason = `服务端拒绝连接 (code ${code}): ${reason || '未知原因'}`; + errorTip = '请稍后重试,或联系管理员'; + } else if (code === 1015) { + errorTitle = 'TLS 握手失败'; + errorReason = `加密连接建立失败 (code ${code})`; + errorTip = '请检查域名 SSL 证书是否有效'; + } else { + errorReason = `连接关闭 (code ${code})${reason ? ': ' + reason : ''}`; + errorTip = '请检查网络连接后重试'; + } + + overlay.innerHTML = ` +
      +
      ⚠️
      +

      ${errorTitle}

      +

      ${errorReason}

      +
      ${errorTip.replace(/\n/g, '
      ')}
      +
      + + +
      +
      `; +} + +async function initLive2D() { + try { + if (typeof Live2DManager === 'undefined') { + console.warn('Live2DManager未加载'); + return; + } + const manager = new Live2DManager(); + await manager.initializeLive2D(); + appState.live2dManager = manager; + // 让Live2D可以访问到 + if (window.chatApp) { + window.chatApp.live2dManager = manager; + } + // 标记 Live2D 加载完成,更新准备进度 + if (appState._prepareState) { + appState._prepareState.live2dReady = true; + updatePrepareProgress(); + } + } catch (e) { + console.error('Live2D初始化失败:', e); + // 即使 Live2D 加载失败,也标记完成(不要卡住进度条) + if (appState._prepareState) { + appState._prepareState.live2dReady = true; + updatePrepareProgress(); + } + } +} + +async function connectVoice() { + const statusEl = document.getElementById('voiceStatus'); + const muteBtn = document.getElementById('muteBtn'); + const endCallBtn = document.getElementById('endCallBtn'); + appState.chatMessages = []; + appState._autoEndTriggered = false; + + statusEl.textContent = '正在连接...'; + + // 启动音频播放系统 + appState.audioPlayer = getAudioPlayer(); + appState.audioPlayer.start(); + + // 初始化录音器 + appState.audioRecorder = getAudioRecorder(); + + // 优先使用 device_init 返回的 OTA 结果,避免重复请求 + let otaResult = appState._otaResult; + console.log('[connectVoice] 使用缓存的 OTA 结果:', otaResult ? '有' : '无'); + if (!otaResult || !otaResult.websocket || !otaResult.websocket.url) { + // 通过 feedback-backend 代理调用 OTA(避免 CORS) + console.log('[connectVoice] 重新调用 OTA 代理...'); + otaResult = await FeedbackAPI.connectOTA(appState.deviceMac, 'feedback_client'); + console.log('[connectVoice] OTA 代理返回:', otaResult ? JSON.stringify(otaResult).substring(0, 200) : 'null'); + } + + if (!otaResult || !otaResult.websocket || !otaResult.websocket.url) { + statusEl.textContent = '连接失败,请重试'; + console.error('[connectVoice] 无法获取 WebSocket URL'); + return; + } + + // 未绑定,显示验证码(兜底:正常流程已在 startFeedback 中处理) + if (otaResult.activation && otaResult.activation.code) { + statusEl.innerHTML = `
      +
      请管理员在智控台输入以下验证码绑定智能体:
      +
      ${otaResult.activation.code}
      + +
      `; + return; + } + + appState.otaResult = otaResult; + statusEl.textContent = '正在连接语音服务...'; + + // 构建 WebSocket URL + // OTA 返回的 URL 通常是 ws://127.0.0.1:18000/...(内部地址) + // 如果当前页面是通过外网域名访问的,需要替换为 wss://域名/ws/(走 FRP 隧道) + let wsUrlStr = otaResult.websocket.url; + const isExternalAccess = !['127.0.0.1', 'localhost', '0.0.0.0'].includes(window.location.hostname); + const isLocalWsUrl = wsUrlStr.includes('127.0.0.1') || wsUrlStr.includes('localhost'); + + if (isExternalAccess && isLocalWsUrl) { + // 外网访问 + OTA 返回内部地址 → 改用同源 WebSocket(需要 FRP/Nginx 配置 /ws/ 路径) + wsUrlStr = WS_BASE + '/'; + console.log('[connectVoice] 外网模式,使用同源 WS:', wsUrlStr); + } + + let wsUrl = new URL(wsUrlStr); + if (otaResult.websocket.token) { + wsUrl.searchParams.append('authorization', 'Bearer ' + otaResult.websocket.token); + } + // 同时通过 URL 参数传递 device-id 和 client-id(WebSocket 协议要求) + wsUrl.searchParams.append('device-id', appState.deviceMac); + wsUrl.searchParams.append('client-id', 'feedback_client'); + + const finalWsUrl = wsUrl.toString(); + console.log('[connectVoice] WebSocket URL:', finalWsUrl); + + try { + const ws = new WebSocket(finalWsUrl); + ws.binaryType = 'arraybuffer'; + appState.ws = ws; + appState.audioRecorder.setWebSocket(ws); + + ws.onopen = () => { + console.log('[connectVoice] WebSocket 已连接'); + statusEl.textContent = '已连接'; + ws.send(JSON.stringify({ + type: 'hello', + device_id: appState.deviceMac, + device_name: appState.storeInfo?.storeName || '反馈H5', + device_mac: appState.deviceMac, + token: otaResult.websocket?.token, + features: { mcp: false, emoji: false } + })); + }; + + ws.onmessage = async (event) => { + if (typeof event.data === 'string') { + try { + const msg = JSON.parse(event.data); + console.log('[connectVoice] WS 收到文本消息:', msg.type, msg.text || ''); + handleWSTextMessage(msg); + } catch (e) { + console.warn('非JSON消息:', event.data); + } + } else { + const opusData = new Uint8Array(event.data); + appState.audioPlayer.enqueueAudioData(opusData); + } + }; + + ws.onclose = (event) => { + console.log('[connectVoice] WebSocket 关闭: code=', event.code, 'reason=', event.reason); + // 如果还没建立过对话(没有 session_id),说明连接提前断了 + if (!appState.sessionId) { + statusEl.textContent = `连接断开 (${event.code}),请重试`; + console.error('[connectVoice] WebSocket 在建立对话前就关闭了'); + // 在准备页上显示明确的错误诊断 + showPrepareError(event.code, event.reason); + return; // 不触发 processAfterConversation + } + statusEl.textContent = '对话已结束,正在生成结果...'; + muteBtn.disabled = true; + endCallBtn.disabled = true; + // 停止录音 + if (appState.audioRecorder?.isRecording) { + appState.audioRecorder.stop(); + } + // 触发AI处理(如果用户选了满意度,传过去;否则不传) + const sat = appState._pendingSatisfaction || ''; + appState._pendingSatisfaction = ''; + setTimeout(() => processAfterConversation(sat), 500); + }; + + ws.onerror = (event) => { + console.error('[connectVoice] WebSocket 错误:', event); + statusEl.textContent = '连接错误,请检查网络'; + }; + + // 静音按钮 - 切换是否发送音频 + let isMuted = false; + muteBtn.addEventListener('click', () => { + isMuted = !isMuted; + if (isMuted) { + // 暂停录音 + if (appState.audioRecorder?.isRecording) { + appState.audioRecorder.stop(); + } + muteBtn.classList.add('muted'); + muteBtn.querySelector('.mute-icon').textContent = '🔇'; + muteBtn.querySelector('.mute-text').textContent = '已静音'; + } else { + // 恢复录音 + startContinuousRecording(); + muteBtn.classList.remove('muted'); + muteBtn.querySelector('.mute-icon').textContent = '🎤'; + muteBtn.querySelector('.mute-text').textContent = '监听中'; + } + }); + + // 结束反馈按钮 - 弹出满意度选择 + endCallBtn.addEventListener('click', () => { + showSatisfactionDialog(); + }); + + } catch (e) { + statusEl.textContent = '连接失败: ' + e.message; + } +} + +// 开始持续录音(自动模式 - 由服务端VAD自动判断说话边界) +async function startContinuousRecording() { + if (!appState.ws || appState.ws.readyState !== WebSocket.OPEN) return; + if (appState.audioRecorder?.isRecording) return; + + // 发送 listen start (auto模式 - 服务端VAD自动判断) + appState.ws.send(JSON.stringify({ + session_id: appState.sessionId, + type: 'listen', + state: 'start', + mode: 'auto' + })); + // 开始录音(持续发送音频流) + await appState.audioRecorder.start(); +} + +function handleWSTextMessage(msg) { + const statusEl = document.getElementById('voiceStatus'); + const chatStream = document.getElementById('chatStream'); + const muteBtn = document.getElementById('muteBtn'); + const endCallBtn = document.getElementById('endCallBtn'); + + if (msg.type === 'hello' && msg.session_id) { + appState.sessionId = msg.session_id; + statusEl.textContent = '对话中(请直接说话)'; + if (muteBtn) muteBtn.disabled = false; + if (endCallBtn) endCallBtn.disabled = false; + + // 标记 WebSocket 通道就绪(hello 握手完成) + if (appState._prepareState) { + appState._prepareState.wsReady = true; + updatePrepareProgress(); + } + + // 触发AI开始第一个问题 + if (appState.ws && appState.ws.readyState === WebSocket.OPEN) { + appState.ws.send(JSON.stringify({ + session_id: msg.session_id, + type: 'listen', + state: 'detect', + text: '你好' + })); + } + // 自动启动持续录音(auto模式 - 服务端VAD) + setTimeout(() => startContinuousRecording(), 300); + } else if (msg.type === 'stt' && msg.text) { + addChatBubble(chatStream, msg.text, true); + appState.chatMessages.push({ role: 'user', text: msg.text }); + updateCustomerIdentityFromText(msg.text); + } else if (msg.type === 'llm' && msg.text) { + const textWithoutEmoji = msg.text.replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '').trim(); + if (textWithoutEmoji) { + addChatBubble(chatStream, msg.text, false); + appState.chatMessages.push({ role: 'ai', text: msg.text }); + } + } else if (msg.type === 'tts') { + if (msg.state === 'start') { + statusEl.textContent = 'AI说话中...'; + appState.isRemoteSpeaking = true; + // 【关键】AI 开始说第一句话 → 标记准备完成,淡出加载页 + if (appState._prepareState && !appState._prepareState.aiReady) { + appState._prepareState.aiReady = true; + updatePrepareProgress(); + } + if (appState.live2dManager) { + appState.live2dManager.startTalking?.(); + } + } else if (msg.state === 'sentence_start' && msg.text) { + const last = appState.chatMessages[appState.chatMessages.length - 1]; + if (!last || last.role !== 'ai' || last.text !== msg.text) { + addChatBubble(chatStream, msg.text, false); + appState.chatMessages.push({ role: 'ai', text: msg.text }); + } + // 【优化1】检测 AI 说再见 → 自动弹出满意度选择 + checkAutoEndConversation(msg.text); + } else if (msg.state === 'stop') { + statusEl.textContent = '请直接说话...'; + appState.isRemoteSpeaking = false; + if (appState.live2dManager) { + setTimeout(() => { + appState.live2dManager.stopTalking?.(); + }, 500); + } + } + } +} + +// 【优化1】检测 AI 说再见 → 自动弹出满意度选择(无需用户手动点击结束按钮) +function checkAutoEndConversation(text) { + if (appState._autoEndTriggered) return; // 防止重复触发 + + const goodbyeKeywords = ['再见', '拜拜', '祝您', '祝您生活愉快', '感谢您的反馈', + '感谢您的配合', '期待您下次', '谢谢您的反馈', '感谢您的参与', + '我们的服务到此结束', '本次反馈已结束', '那就先到这里']; + + const isGoodbye = goodbyeKeywords.some(kw => text.includes(kw)); + if (isGoodbye) { + console.log('[autoEnd] 检测到告别语,自动弹出满意度选择'); + appState._autoEndTriggered = true; + // 等 TTS 播完后再弹窗(延迟一点让用户听完) + setTimeout(() => { + if (appState.ws && appState.ws.readyState === WebSocket.OPEN) { + showSatisfactionDialog(); + } + }, 1500); + } +} + +function addChatBubble(container, text, isUser) { + const bubble = document.createElement('div'); + bubble.className = `chat-bubble ${isUser ? 'user' : 'ai'}`; + bubble.textContent = text; + container.appendChild(bubble); + container.scrollTop = container.scrollHeight; +} + +function normalizePhoneTail(value) { + const digits = String(value || '').replace(/\D/g, ''); + return digits.length >= 4 ? digits.slice(-4) : ''; +} + +function formLine(label, controlHtml) { + return `
      ${controlHtml}
      `; +} + +function updateCustomerIdentityFromText(text) { + const raw = String(text || ''); + const phoneTail = normalizePhoneTail(raw); + if (phoneTail) appState.phoneTail = phoneTail; + + const namePatterns = [ + /(?:我叫|我是|叫我)([一-龥A-Za-z]{1,12})/, + /(?:称呼|叫)(?:我)?[::,,\s]*([一-龥A-Za-z]{1,12})/, + ]; + for (const pattern of namePatterns) { + const match = raw.match(pattern); + if (match && match[1] && !/^\d+$/.test(match[1])) { + appState.customerName = match[1].slice(0, 12); + break; + } + } +} + +async function ensureCustomerIdentity() { + return new Promise((resolve) => { + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + document.body.appendChild(overlay); + const nameInput = document.getElementById('identityName'); + const phoneInput = document.getElementById('identityPhoneTail'); + phoneInput?.addEventListener('input', (e) => { + e.target.value = String(e.target.value || '').replace(/\D/g, '').slice(0, 4); + }); + setTimeout(() => (nameInput || phoneInput)?.focus(), 50); + document.getElementById('identityConfirmBtn').addEventListener('click', () => { + const name = nameInput?.value.trim() || ''; + const tail = normalizePhoneTail(phoneInput?.value || ''); + if (!name) { + document.getElementById('identityError').textContent = '请填写称呼'; + nameInput?.focus(); + return; + } + if (tail.length !== 4) { + document.getElementById('identityError').textContent = '请填写手机号后四位'; + phoneInput?.focus(); + return; + } + appState.customerName = name; + appState.phoneTail = tail; + document.body.removeChild(overlay); + resolve(true); + }); + }); +} + +async function processAfterConversation(satisfaction) { + if (appState.chatMessages.length === 0) { + // 对话没产生任何消息,显示重试按钮而非静默跳回 + const statusEl = document.getElementById('voiceStatus'); + if (statusEl) { + statusEl.innerHTML = `
      +
      对话未能建立,请重试
      + +
      `; + } + return; + } + + const allText = appState.chatMessages.map(m => `${m.role === 'user' ? '客户' : 'AI'}: ${m.text}`).join('\n'); + + // 保存满意度供后续使用 + appState.satisfaction = satisfaction; + + // 【重要】无论 AI 处理是否成功,先保存原始对话记录(防丢失) + FeedbackAPI.saveRecord({ + storeId: appState.storeInfo?.id, + employeeId: appState.selectedEmployee?.id, + sessionId: appState.sessionId, + deviceMac: appState.deviceMac, + rawAsrText: allText, + customerName: appState.customerName, + phoneTail: appState.phoneTail, + satisfaction: satisfaction, + }); + + navigate('result'); + + const result = await FeedbackAPI.processFeedback({ + sessionId: appState.sessionId, + deviceMac: appState.deviceMac, + clientId: 'feedback_client', + storeName: appState.storeInfo?.storeName || '', + employeeNumber: String(appState.selectedEmployee?.number || ''), + asrText: allText, + customerName: appState.customerName, + phoneTail: appState.phoneTail, + satisfaction: satisfaction + }); + + if (result.success) { + appState.feedbackResult = result.data; + renderFeedbackResult(); + // AI 处理成功后,更新记录(补全清洗文本/QA/点评) + FeedbackAPI.saveRecord({ + storeId: appState.storeInfo?.id, + employeeId: appState.selectedEmployee?.id, + sessionId: appState.sessionId, + deviceMac: appState.deviceMac, + rawAsrText: allText, + cleanedText: result.data.cleaned_text, + qaJson: result.data.qa_result, + reviewLong: result.data.review_long, + reviewShort: result.data.review_short, + customerName: appState.customerName, + phoneTail: appState.phoneTail, + satisfaction: result.data.satisfaction, + }); + } else { + const statusEl = document.getElementById('processStatus'); + if (statusEl) statusEl.textContent = '处理失败: ' + (result.message || ''); + // 即使 AI 处理失败,也渲染不满意的结果页(原始记录已保存) + appState.feedbackResult = { + should_publish: false, + satisfaction: satisfaction, + }; + renderFeedbackResult(); + } +} + +// 显示满意度选择弹窗 +function showSatisfactionDialog() { + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay'; + overlay.innerHTML = ` + `; + document.body.appendChild(overlay); + + overlay.querySelectorAll('.sat-option').forEach(btn => { + btn.addEventListener('click', async () => { + const satisfaction = btn.dataset.value; + const ok = await ensureCustomerIdentity(); + if (!ok) return; + document.body.removeChild(overlay); + // 关闭WebSocket,进入处理流程 + if (appState.audioRecorder?.isRecording) { + appState.audioRecorder.stop(); + } + if (appState.ws && appState.ws.readyState === WebSocket.OPEN) { + // 把 satisfaction 暂存,等 onclose 触发时使用 + appState._pendingSatisfaction = satisfaction; + appState.ws.close(); + } else { + processAfterConversation(satisfaction); + } + }); + }); + + document.getElementById('satCancelBtn').addEventListener('click', () => { + document.body.removeChild(overlay); + }); +} + +// ==================== 结果页 ==================== +function renderResult(container) { + const sat = appState.satisfaction; + const willPublish = sat === 'very_satisfied' || sat === 'satisfied'; + + container.innerHTML = ` +
      +
      +
      ✨
      +

      ${willPublish ? '正在为您生成大众点评好评' : '正在记录您的反馈'}

      +

      ${willPublish ? '请您稍等片刻...' : '感谢您的真实反馈'}

      +
      +
      +
      +
      +
      +
      AI正在分析对话内容...
      +
      + + +
      `; +} + +function renderFeedbackResult() { + const data = appState.feedbackResult; + const sat = appState.satisfaction; + const processingView = document.getElementById('processingView'); + const contentEl = document.getElementById('resultContent'); + + if (processingView) processingView.style.display = 'none'; + if (!contentEl) return; + + contentEl.style.display = 'block'; + + // 情况1: 满意/非常满意 - 展示好评话术 + 一键复制 + 平台跳转 + if (data.should_publish && data.review_long) { + const storeName = appState.storeInfo?.storeName || ''; + contentEl.innerHTML = ` +
      +
      ${sat === 'very_satisfied' ? '🤩' : '😊'}
      +

      感谢您的好评

      +

      已为您生成大众点评好评话术

      +
      +
      +
      + + +
      +
      ${escapeHtml(data.review_long)}
      +
      ${escapeHtml(data.review_short || '')}
      +
      +
      + + +
      +
      +

      一键发布到平台

      +

      点击下方按钮打开APP,粘贴刚才复制的点评即可

      +
      + + +
      +
      + `; + + // Tab 切换逻辑 + document.querySelectorAll('.tab-btn').forEach(btn => { + btn.addEventListener('click', () => { + document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); + document.querySelectorAll('.review-text-box').forEach(t => t.classList.remove('active')); + btn.classList.add('active'); + const tab = btn.dataset.tab; + const isLong = tab === 'long'; + document.getElementById(isLong ? 'reviewLong' : 'reviewShort').classList.add('active'); + // 切换复制按钮 + document.getElementById('copyLongBtn').style.display = isLong ? '' : 'none'; + document.getElementById('copyShortBtn').style.display = isLong ? 'none' : ''; + }); + }); + + // 一键复制(标准版) + document.getElementById('copyLongBtn').addEventListener('click', async () => { + const ok = await copyToClipboard(data.review_long || ''); + const btn = document.getElementById('copyLongBtn'); + if (ok) { + btn.textContent = '✅ 已复制到剪贴板'; + btn.classList.add('copied'); + speak('好评已复制,请打开大众点评粘贴发布'); + if (isMobile()) showManualCopySheet(data.review_long || ''); + } else { + btn.textContent = '请长按文字手动复制'; + showManualCopySheet(data.review_long || ''); + } + setTimeout(() => { btn.textContent = '📋 复制标准版好评'; btn.classList.remove('copied'); }, 3000); + }); + + // 一键复制(精简版) + document.getElementById('copyShortBtn').addEventListener('click', async () => { + const ok = await copyToClipboard(data.review_short || ''); + const btn = document.getElementById('copyShortBtn'); + if (ok) { + btn.textContent = '✅ 已复制到剪贴板'; + btn.classList.add('copied'); + speak('好评已复制,请打开美团粘贴发布'); + if (isMobile()) showManualCopySheet(data.review_short || ''); + } else { + btn.textContent = '请长按文字手动复制'; + showManualCopySheet(data.review_short || ''); + } + setTimeout(() => { btn.textContent = '📋 复制精简版好评'; btn.classList.remove('copied'); }, 3000); + }); + + // 平台跳转 + document.getElementById('openDianpingBtn').addEventListener('click', () => openDianping(storeName)); + document.getElementById('openMeituanBtn').addEventListener('click', () => openMeituan(storeName)); + document.getElementById('completeBtn2').addEventListener('click', () => navigate('complete')); + } else { + // 情况2: 不满意/非常糟糕 - 致歉 + 引导 + const isVeryBad = sat === 'very_bad'; + contentEl.innerHTML = ` +
      +
      ${isVeryBad ? '🙏' : '😔'}
      +

      ${isVeryBad ? '非常抱歉给您带来不好的体验' : '感谢您的真实反馈'}

      +

      ${isVeryBad ? '门店管理团队会尽快与您联系处理' : '您的意见我们已记录,会持续改进'}

      +
      + + `; + + document.getElementById('completeBtn').addEventListener('click', () => navigate('complete')); + } +} + +function escapeHtml(s) { + if (!s) return ''; + return String(s) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +// ==================== 发布好评页 ==================== +function renderPublish(container) { + const data = appState.feedbackResult || {}; + container.innerHTML = ` +
      + +
      +

      好评话术

      +
      ${data.review_long || ''}
      + +
      +
      +

      跳转评价平台

      + + +
      + +
      `; + + document.getElementById('copyReviewBtn').addEventListener('click', async () => { + const text = data.review_long || ''; + const ok = await copyToClipboard(text); + if (ok) { + document.getElementById('copyReviewBtn').textContent = '✅ 已复制'; + speak('好评话术已复制成功,请直接粘贴发布,感谢您的支持!'); + if (isMobile()) showManualCopySheet(text); + } else { + showManualCopySheet(text); + } + }); + + const storeName = appState.storeInfo?.storeName || ''; + document.getElementById('openDianpingBtn').addEventListener('click', () => openDianping(storeName)); + document.getElementById('openMeituanBtn').addEventListener('click', () => openMeituan(storeName)); + document.getElementById('completeBtn').addEventListener('click', () => navigate('complete')); +} + +// ==================== 完成页 ==================== +function renderComplete(container) { + container.innerHTML = ` +
      +
      +
      🎉
      +

      感谢您的反馈!

      +

      您的意见对我们非常重要

      +

      祝您生活愉快!

      +
      + +
      `; + + document.getElementById('retryBtn').addEventListener('click', () => { + appState.selectedEmployee = null; + appState.chatMessages = []; + appState.feedbackResult = null; + appState.sessionId = ''; + appState._otaResult = null; + if (appState.ws) { + try { appState.ws.close(); } catch (e) {} + appState.ws = null; + } + // 清理 Live2D 实例 + if (appState.live2dManager) { + try { appState.live2dManager.destroy(); } catch (e) {} + appState.live2dManager = null; + } + navigate('home'); + }); +} + +// ==================== 初始化 ==================== +window.addEventListener('hashchange', render); +window.addEventListener('load', render); diff --git a/main/feedback-h5/js/audio-player.js b/main/feedback-h5/js/audio-player.js new file mode 100644 index 000000000..d86f9ec10 --- /dev/null +++ b/main/feedback-h5/js/audio-player.js @@ -0,0 +1,303 @@ +// 音频播放模块 +import BlockingQueue from './blocking-queue.js'; +import { log } from './logger.js'; +import { createStreamingContext } from './stream-context.js'; + +// 音频播放器类 +export class AudioPlayer { + constructor() { + // 音频参数 + this.SAMPLE_RATE = 16000; + this.CHANNELS = 1; + this.FRAME_SIZE = 960; + this.MIN_AUDIO_DURATION = 0.12; + + // 状态 + this.audioContext = null; + this.opusDecoder = null; + this.streamingContext = null; + this.queue = new BlockingQueue(); + this.isPlaying = false; + } + + // 获取或创建AudioContext + getAudioContext() { + if (!this.audioContext) { + this.audioContext = new (window.AudioContext || window.webkitAudioContext)({ + sampleRate: this.SAMPLE_RATE, + latencyHint: 'interactive' + }); + log('创建音频上下文,采样率: ' + this.SAMPLE_RATE + 'Hz', 'debug'); + } + return this.audioContext; + } + + // 初始化Opus解码器 + async initOpusDecoder() { + if (this.opusDecoder) return this.opusDecoder; + + try { + if (typeof window.ModuleInstance === 'undefined') { + // libopus.js 实际导出在 Module.instance + if (typeof Module !== 'undefined' && typeof Module.instance !== 'undefined' && + typeof Module.instance._opus_decoder_get_size === 'function') { + window.ModuleInstance = Module.instance; + log('使用 Module.instance 作为 ModuleInstance', 'info'); + } else if (typeof Module !== 'undefined' && + typeof Module._opus_decoder_get_size === 'function') { + window.ModuleInstance = Module; + log('使用全局Module作为ModuleInstance', 'info'); + } else { + throw new Error('Opus库未加载,ModuleInstance和Module对象都不存在'); + } + } + + const mod = window.ModuleInstance; + + this.opusDecoder = { + channels: this.CHANNELS, + rate: this.SAMPLE_RATE, + frameSize: this.FRAME_SIZE, + module: mod, + decoderPtr: null, + + init: function () { + if (this.decoderPtr) return true; + + const decoderSize = mod._opus_decoder_get_size(this.channels); + log(`Opus解码器大小: ${decoderSize}字节`, 'debug'); + + this.decoderPtr = mod._malloc(decoderSize); + if (!this.decoderPtr) { + throw new Error("无法分配解码器内存"); + } + + const err = mod._opus_decoder_init( + this.decoderPtr, + this.rate, + this.channels + ); + + if (err < 0) { + this.destroy(); + throw new Error(`Opus解码器初始化失败: ${err}`); + } + + log("Opus解码器初始化成功", 'success'); + return true; + }, + + decode: function (opusData) { + if (!this.decoderPtr) { + if (!this.init()) { + throw new Error("解码器未初始化且无法初始化"); + } + } + + try { + const mod = this.module; + + const opusPtr = mod._malloc(opusData.length); + mod.HEAPU8.set(opusData, opusPtr); + + const pcmPtr = mod._malloc(this.frameSize * 2); + + const decodedSamples = mod._opus_decode( + this.decoderPtr, + opusPtr, + opusData.length, + pcmPtr, + this.frameSize, + 0 + ); + + if (decodedSamples < 0) { + mod._free(opusPtr); + mod._free(pcmPtr); + throw new Error(`Opus解码失败: ${decodedSamples}`); + } + + const decodedData = new Int16Array(decodedSamples); + for (let i = 0; i < decodedSamples; i++) { + decodedData[i] = mod.HEAP16[(pcmPtr >> 1) + i]; + } + + mod._free(opusPtr); + mod._free(pcmPtr); + + return decodedData; + } catch (error) { + log(`Opus解码错误: ${error.message}`, 'error'); + return new Int16Array(0); + } + }, + + destroy: function () { + if (this.decoderPtr) { + this.module._free(this.decoderPtr); + this.decoderPtr = null; + } + } + }; + + if (!this.opusDecoder.init()) { + throw new Error("Opus解码器初始化失败"); + } + + return this.opusDecoder; + + } catch (error) { + log(`Opus解码器初始化失败: ${error.message}`, 'error'); + this.opusDecoder = null; + throw error; + } + } + + // 启动音频缓冲 + async startAudioBuffering() { + log("开始音频缓冲...", 'info'); + + this.initOpusDecoder().catch(error => { + log(`预初始化Opus解码器失败: ${error.message}`, 'warning'); + }); + + const timeout = 400; + while (true) { + const packets = await this.queue.dequeue( + 6, + timeout, + (count) => { + log(`缓冲超时,当前缓冲包数: ${count},开始播放`, 'info'); + } + ); + if (packets.length) { + log(`已缓冲 ${packets.length} 个音频包,开始播放`, 'info'); + this.streamingContext.pushAudioBuffer(packets); + } + + while (true) { + const data = await this.queue.dequeue(99, 30); + if (data.length) { + this.streamingContext.pushAudioBuffer(data); + } else { + break; + } + } + } + } + + // 播放已缓冲的音频 + async playBufferedAudio() { + try { + this.audioContext = this.getAudioContext(); + + if (!this.opusDecoder) { + log('初始化Opus解码器...', 'info'); + try { + this.opusDecoder = await this.initOpusDecoder(); + if (!this.opusDecoder) { + throw new Error('解码器初始化失败'); + } + log('Opus解码器初始化成功', 'success'); + } catch (error) { + log('Opus解码器初始化失败: ' + error.message, 'error'); + this.isPlaying = false; + return; + } + } + + if (!this.streamingContext) { + this.streamingContext = createStreamingContext( + this.opusDecoder, + this.audioContext, + this.SAMPLE_RATE, + this.CHANNELS, + this.MIN_AUDIO_DURATION + ); + } + + this.streamingContext.decodeOpusFrames(); + this.streamingContext.startPlaying(); + + } catch (error) { + log(`播放已缓冲的音频出错: ${error.message}`, 'error'); + this.isPlaying = false; + this.streamingContext = null; + } + } + + // 添加音频数据到队列 + enqueueAudioData(opusData) { + if (opusData.length > 0) { + this.queue.enqueue(opusData); + } else { + log('收到空音频数据帧,可能是结束标志', 'warning'); + if (this.isPlaying && this.streamingContext) { + this.streamingContext.endOfStream = true; + } + } + } + + // 预加载解码器 + async preload() { + log('预加载Opus解码器...', 'info'); + try { + await this.initOpusDecoder(); + log('Opus解码器预加载成功', 'success'); + } catch (error) { + log(`Opus解码器预加载失败: ${error.message},将在需要时重试`, 'warning'); + } + } + + // 启动播放系统 + async start() { + await this.preload(); + this.playBufferedAudio(); + this.startAudioBuffering(); + } + + // 获取音频包统计信息 + getAudioStats() { + if (!this.streamingContext) { + return { + pendingDecode: 0, + pendingPlay: 0, + totalPending: 0 + }; + } + + const pendingDecode = this.streamingContext.getPendingDecodeCount(); + const pendingPlay = this.streamingContext.getPendingPlayCount(); + + return { + pendingDecode, // 待解码包数 + pendingPlay, // 待播放包数 + totalPending: pendingDecode + pendingPlay // 总待处理包数 + }; + } + + // 清空所有音频缓冲并停止播放 + clearAllAudio() { + log('AudioPlayer: 清空所有音频', 'info'); + + // 清空接收队列(使用clear方法保持对象引用) + this.queue.clear(); + + // 清空流上下文的所有缓冲 + if (this.streamingContext) { + this.streamingContext.clearAllBuffers(); + } + + log('AudioPlayer: 音频已清空', 'success'); + } +} + +// 创建单例 +let audioPlayerInstance = null; + +export function getAudioPlayer() { + if (!audioPlayerInstance) { + audioPlayerInstance = new AudioPlayer(); + } + return audioPlayerInstance; +} diff --git a/main/feedback-h5/js/audio-recorder.js b/main/feedback-h5/js/audio-recorder.js new file mode 100644 index 000000000..6f701c75d --- /dev/null +++ b/main/feedback-h5/js/audio-recorder.js @@ -0,0 +1,394 @@ +// Audio recording module +import { log } from './logger.js'; +import { initOpusEncoder } from './opus-codec.js'; +import { getAudioPlayer } from './audio-player.js'; + +// Audio recorder class +export class AudioRecorder { + constructor() { + this.isRecording = false; + this.audioContext = null; + this.analyser = null; + this.audioProcessor = null; + this.audioProcessorType = null; + this.audioSource = null; + this.opusEncoder = null; + this.pcmDataBuffer = new Int16Array(); + this.audioBuffers = []; + this.totalAudioSize = 0; + this.visualizationRequest = null; + this.recordingTimer = null; + this.websocket = null; + // Callback functions + this.onRecordingStart = null; + this.onRecordingStop = null; + this.onVisualizerUpdate = null; + } + + // Set WebSocket instance + setWebSocket(ws) { + this.websocket = ws; + } + + // Get AudioContext instance + getAudioContext() { + return getAudioPlayer().getAudioContext(); + } + + // Initialize encoder + initEncoder() { + if (!this.opusEncoder) { + this.opusEncoder = initOpusEncoder(); + } + return this.opusEncoder; + } + + // PCM processor code + getAudioProcessorCode() { + return ` + class AudioRecorderProcessor extends AudioWorkletProcessor { + constructor() { + super(); + this.buffers = []; + this.frameSize = 960; + this.buffer = new Int16Array(this.frameSize); + this.bufferIndex = 0; + this.isRecording = false; + this.port.onmessage = (event) => { + if (event.data.command === 'start') { + this.isRecording = true; + this.port.postMessage({ type: 'status', status: 'started' }); + } else if (event.data.command === 'stop') { + this.isRecording = false; + if (this.bufferIndex > 0) { + const finalBuffer = this.buffer.slice(0, this.bufferIndex); + this.port.postMessage({ type: 'buffer', buffer: finalBuffer }); + this.bufferIndex = 0; + } + this.port.postMessage({ type: 'status', status: 'stopped' }); + } + }; + } + process(inputs, outputs, parameters) { + if (!this.isRecording) return true; + const input = inputs[0][0]; + if (!input) return true; + for (let i = 0; i < input.length; i++) { + if (this.bufferIndex >= this.frameSize) { + this.port.postMessage({ type: 'buffer', buffer: this.buffer.slice(0) }); + this.bufferIndex = 0; + } + this.buffer[this.bufferIndex++] = Math.max(-32768, Math.min(32767, Math.floor(input[i] * 32767))); + } + return true; + } + } + registerProcessor('audio-recorder-processor', AudioRecorderProcessor); + `; + } + + // Create audio processor + async createAudioProcessor() { + this.audioContext = this.getAudioContext(); + try { + if (this.audioContext.audioWorklet) { + // 避免重复注册同名 worklet + if (!this.audioContext._workletRegistered) { + const blob = new Blob([this.getAudioProcessorCode()], { type: 'application/javascript' }); + const url = URL.createObjectURL(blob); + try { + await this.audioContext.audioWorklet.addModule(url); + } catch (regErr) { + if (!String(regErr).includes('already registered')) { + throw regErr; + } + } + URL.revokeObjectURL(url); + this.audioContext._workletRegistered = true; + } + const audioProcessor = new AudioWorkletNode(this.audioContext, 'audio-recorder-processor'); + audioProcessor.port.onmessage = (event) => { + if (event.data.type === 'buffer') { + this.processPCMBuffer(event.data.buffer); + } + }; + log('使用AudioWorklet处理音频', 'success'); + const silent = this.audioContext.createGain(); + silent.gain.value = 0; + audioProcessor.connect(silent); + silent.connect(this.audioContext.destination); + return { node: audioProcessor, type: 'worklet' }; + } else { + log('AudioWorklet不可用,使用ScriptProcessorNode作为后备方案', 'warning'); + return this.createScriptProcessor(); + } + } catch (error) { + log(`创建音频处理器失败: ${error.message},尝试后备方案`, 'error'); + return this.createScriptProcessor(); + } + } + + // Create ScriptProcessor as fallback + createScriptProcessor() { + try { + const frameSize = 4096; + const scriptProcessor = this.audioContext.createScriptProcessor(frameSize, 1, 1); + scriptProcessor.onaudioprocess = (event) => { + if (!this.isRecording) return; + const input = event.inputBuffer.getChannelData(0); + const buffer = new Int16Array(input.length); + for (let i = 0; i < input.length; i++) { + buffer[i] = Math.max(-32768, Math.min(32767, Math.floor(input[i] * 32767))); + } + this.processPCMBuffer(buffer); + }; + const silent = this.audioContext.createGain(); + silent.gain.value = 0; + scriptProcessor.connect(silent); + silent.connect(this.audioContext.destination); + log('使用ScriptProcessorNode作为后备方案成功', 'warning'); + return { node: scriptProcessor, type: 'processor' }; + } catch (fallbackError) { + log(`后备方案也失败: ${fallbackError.message}`, 'error'); + return null; + } + } + + // Process PCM buffer data + processPCMBuffer(buffer) { + if (!this.isRecording) return; + const newBuffer = new Int16Array(this.pcmDataBuffer.length + buffer.length); + newBuffer.set(this.pcmDataBuffer); + newBuffer.set(buffer, this.pcmDataBuffer.length); + this.pcmDataBuffer = newBuffer; + const samplesPerFrame = 960; + while (this.pcmDataBuffer.length >= samplesPerFrame) { + const frameData = this.pcmDataBuffer.slice(0, samplesPerFrame); + this.pcmDataBuffer = this.pcmDataBuffer.slice(samplesPerFrame); + this.encodeAndSendOpus(frameData); + } + } + + // Encode and send Opus data + encodeAndSendOpus(pcmData = null) { + if (!this.opusEncoder) { + log('Opus编码器未初始化', 'error'); + return; + } + try { + if (pcmData) { + const opusData = this.opusEncoder.encode(pcmData); + if (opusData && opusData.length > 0) { + this.audioBuffers.push(opusData.buffer); + this.totalAudioSize += opusData.length; + if (this.websocket && this.websocket.readyState === WebSocket.OPEN) { + try { + this.websocket.send(opusData.buffer); + } catch (error) { + log(`WebSocket发送错误: ${error.message}`, 'error'); + } + } + } else { + log('Opus编码失败,未返回有效数据', 'error'); + } + } else { + if (this.pcmDataBuffer.length > 0) { + const samplesPerFrame = 960; + if (this.pcmDataBuffer.length < samplesPerFrame) { + const paddedBuffer = new Int16Array(samplesPerFrame); + paddedBuffer.set(this.pcmDataBuffer); + this.encodeAndSendOpus(paddedBuffer); + } else { + this.encodeAndSendOpus(this.pcmDataBuffer.slice(0, samplesPerFrame)); + } + this.pcmDataBuffer = new Int16Array(0); + } + } + } catch (error) { + log(`Opus编码错误: ${error.message}`, 'error'); + } + } + + // Start recording + async start() { + if (this.isRecording) return false; + try { + if (!this.initEncoder()) { + log('无法开始录音: Opus编码器初始化失败', 'error'); + return false; + } + log('请至少录制1-2秒音频以确保收集足够的数据', 'info'); + const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, sampleRate: 16000, channelCount: 1 } }); + this.audioContext = this.getAudioContext(); + if (this.audioContext.state === 'suspended') { + await this.audioContext.resume(); + } + const processorResult = await this.createAudioProcessor(); + if (!processorResult) { + log('无法创建音频处理器', 'error'); + return false; + } + this.audioProcessor = processorResult.node; + this.audioProcessorType = processorResult.type; + this.audioSource = this.audioContext.createMediaStreamSource(stream); + this.analyser = this.audioContext.createAnalyser(); + this.analyser.fftSize = 2048; + this.audioSource.connect(this.analyser); + this.audioSource.connect(this.audioProcessor); + this.pcmDataBuffer = new Int16Array(); + this.audioBuffers = []; + this.totalAudioSize = 0; + this.isRecording = true; + if (this.audioProcessorType === 'worklet' && this.audioProcessor.port) { + this.audioProcessor.port.postMessage({ command: 'start' }); + } + // Send listening start message + if (this.websocket && this.websocket.readyState === WebSocket.OPEN) { + log(`已发送录音开始消息`, 'info'); + } else { + log('WebSocket未连接,无法发送开始消息', 'error'); + return false; + } + // Start visualization + if (this.onVisualizerUpdate) { + const dataArray = new Uint8Array(this.analyser.frequencyBinCount); + this.startVisualization(dataArray); + } + // Immediately notify recording start, update button state + if (this.onRecordingStart) { + this.onRecordingStart(0); + } + // Start recording timer + let recordingSeconds = 0; + this.recordingTimer = setInterval(() => { + recordingSeconds += 0.1; + if (this.onRecordingStart) { + this.onRecordingStart(recordingSeconds); + } + }, 100); + log('已开始PCM直接录音', 'success'); + return true; + } catch (error) { + log(`直接录音启动错误: ${error.message}`, 'error'); + this.isRecording = false; + return false; + } + } + + // Start visualization + startVisualization(dataArray) { + const draw = () => { + this.visualizationRequest = requestAnimationFrame(() => draw()); + if (!this.isRecording) return; + this.analyser.getByteFrequencyData(dataArray); + if (this.onVisualizerUpdate) { + this.onVisualizerUpdate(dataArray); + } + }; + draw(); + } + + // Stop recording + stop() { + if (!this.isRecording) return false; + try { + this.isRecording = false; + if (this.audioProcessor) { + if (this.audioProcessorType === 'worklet' && this.audioProcessor.port) { + this.audioProcessor.port.postMessage({ command: 'stop' }); + } + this.audioProcessor.disconnect(); + this.audioProcessor = null; + } + if (this.audioSource) { + this.audioSource.disconnect(); + this.audioSource = null; + } + if (this.visualizationRequest) { + cancelAnimationFrame(this.visualizationRequest); + this.visualizationRequest = null; + } + if (this.recordingTimer) { + clearInterval(this.recordingTimer); + this.recordingTimer = null; + } + // Encode and send remaining data + this.encodeAndSendOpus(); + // Send end signal + if (this.websocket && this.websocket.readyState === WebSocket.OPEN) { + const emptyOpusFrame = new Uint8Array(0); + this.websocket.send(emptyOpusFrame); + log('已发送录音停止信号', 'info'); + } + if (this.onRecordingStop) { + this.onRecordingStop(); + } + log('已停止PCM直接录音', 'success'); + return true; + } catch (error) { + log(`直接录音停止错误: ${error.message}`, 'error'); + return false; + } + } + + // Get analyser + getAnalyser() { + return this.analyser; + } +} + +// Create singleton instance +let audioRecorderInstance = null; + +export function getAudioRecorder() { + if (!audioRecorderInstance) { + audioRecorderInstance = new AudioRecorder(); + } + return audioRecorderInstance; +} + +/** + * Check if microphone is available + * @returns {Promise} Returns true if available, false if not available + */ +export async function checkMicrophoneAvailability() { + // Check if browser supports getUserMedia API + if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { + log('浏览器不支持getUserMedia API', 'warning'); + return false; + } + try { + // Try to access microphone + const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, sampleRate: 16000, channelCount: 1 } }); + // Immediately stop all tracks to release microphone + stream.getTracks().forEach(track => track.stop()); + log('麦克风可用性检查成功', 'success'); + return true; + } catch (error) { + log(`麦克风不可用: ${error.message}`, 'warning'); + return false; + } +} + +/** + * Check if it is HTTP non-localhost access + * @returns {boolean} Returns true if it is HTTP non-localhost access + */ +export function isHttpNonLocalhost() { + const protocol = window.location.protocol; + const hostname = window.location.hostname; + // Check if it is HTTP protocol + if (protocol !== 'http:') { + return false; + } + // localhost and 127.0.0.1 can use microphone + if (hostname === 'localhost' || hostname === '127.0.0.1') { + return false; + } + // Private IP addresses can also use microphone (browser allows) + if (hostname.startsWith('192.168.') || hostname.startsWith('10.') || hostname.startsWith('172.')) { + return false; + } + // Other HTTP access is considered non-localhost + return true; +} diff --git a/main/feedback-h5/js/blocking-queue.js b/main/feedback-h5/js/blocking-queue.js new file mode 100644 index 000000000..738a3e75b --- /dev/null +++ b/main/feedback-h5/js/blocking-queue.js @@ -0,0 +1,103 @@ +export default class BlockingQueue { + #items = []; + #waiters = []; // {resolve, reject, min, timer, onTimeout} + + /* 空队列一次性闸门 */ + #emptyPromise = null; + #emptyResolve = null; + + /* 生产者:把数据塞进去 */ + enqueue(item, ...restItems) { + if (restItems.length === 0) { + this.#items.push(item); + } + // 如果有额外参数,批量处理所有项 + else { + const items = [item, ...restItems].filter(i => i); + if (items.length === 0) return; + this.#items.push(...items); + } + // 若有空队列闸门,一次性放行所有等待者 + if (this.#emptyResolve) { + this.#emptyResolve(); + this.#emptyResolve = null; + this.#emptyPromise = null; + } + + // 唤醒所有正在等的 waiter + this.#wakeWaiters(); + } + + /* 消费者:min 条或 timeout ms 先到谁 */ + async dequeue(min = 1, timeout = Infinity, onTimeout = null) { + // 1. 若空,等第一次数据到达(所有调用共享同一个 promise) + if (this.#items.length === 0) { + await this.#waitForFirstItem(); + } + + // 立即满足 + if (this.#items.length >= min) { + return this.#flush(); + } + + // 需要等待 + return new Promise((resolve, reject) => { + let timer = null; + const waiter = { resolve, reject, min, onTimeout, timer }; + + // 超时逻辑 + if (Number.isFinite(timeout)) { + waiter.timer = setTimeout(() => { + this.#removeWaiter(waiter); + if (onTimeout) onTimeout(this.#items.length); + resolve(this.#flush()); + }, timeout); + } + + this.#waiters.push(waiter); + }); + } + + /* 空队列闸门生成器 */ + #waitForFirstItem() { + if (!this.#emptyPromise) { + this.#emptyPromise = new Promise(r => (this.#emptyResolve = r)); + } + return this.#emptyPromise; + } + + /* 内部:每次数据变动后,检查哪些 waiter 已满足 */ + #wakeWaiters() { + for (let i = this.#waiters.length - 1; i >= 0; i--) { + const w = this.#waiters[i]; + if (this.#items.length >= w.min) { + this.#removeWaiter(w); + w.resolve(this.#flush()); + } + } + } + + #removeWaiter(waiter) { + const idx = this.#waiters.indexOf(waiter); + if (idx !== -1) { + this.#waiters.splice(idx, 1); + if (waiter.timer) clearTimeout(waiter.timer); + } + } + + #flush() { + const snapshot = [...this.#items]; + this.#items.length = 0; + return snapshot; + } + + /* 当前缓存长度(不含等待者) */ + get length() { + return this.#items.length; + } + + /* 清空队列(保持对象引用,不影响等待者) */ + clear() { + this.#items.length = 0; + } +} \ No newline at end of file diff --git a/main/feedback-h5/js/live2d-manager.js b/main/feedback-h5/js/live2d-manager.js new file mode 100644 index 000000000..8fd360a25 --- /dev/null +++ b/main/feedback-h5/js/live2d-manager.js @@ -0,0 +1,861 @@ +/** + * Live2D 管理器 + * 负责 Live2D 模型的初始化、嘴部动画控制等功能 + */ +class Live2DManager { + constructor() { + this.live2dApp = null; + this.live2dModel = null; + this.isTalking = false; + this.mouthAnimationId = null; + this.mouthParam = 'ParamMouthOpenY'; + this.audioContext = null; + this.analyser = null; + this.dataArray = null; + this.lastEmotionActionTime = null; + this.currentModelName = null; + + // 模型特定配置 + this.modelConfig = { + 'hiyori_pro_zh': { + mouthParam: 'ParamMouthOpenY', + mouthAmplitude: 1.0, + mouthThresholds: { low: 0.3, high: 0.7 }, + motionMap: { + 'FlickUp': 'FlickUp', + 'FlickDown': 'FlickDown', + 'Tap': 'Tap', + 'Tap@Body': 'Tap@Body', + 'Flick': 'Flick', + 'Flick@Body': 'Flick@Body' + } + }, + 'natori_pro_zh': { + mouthParam: 'ParamMouthOpenY', + mouthAmplitude: 1.0, + mouthThresholds: { low: 0.1, high: 0.4 }, + mouthFormParam: 'ParamMouthForm', + mouthFormAmplitude: 1.0, + mouthForm2Param: 'ParamMouthForm2', + mouthForm2Amplitude: 0.8, + motionMap: { + 'FlickUp': 'FlickUp', + 'FlickDown': 'Flick@Body', + 'Tap': 'Tap', + 'Tap@Body': 'Tap@Head', + 'Flick': 'Tap', + 'Flick@Body': 'Flick@Body' + } + } + }; + + // 情绪到动作的映射 + this.emotionToActionMap = { + 'happy': 'FlickUp', // 开心-向上轻扫动作 + 'laughing': 'FlickUp', // 大笑-向上轻扫动作 + 'funny': 'FlickUp', // 搞笑-向上轻扫动作 + 'sad': 'FlickDown', // 伤心-向下轻扫动作 + 'crying': 'FlickDown', // 哭泣-向下轻扫动作 + 'angry': 'Tap@Body', // 生气-身体点击动作 + 'surprised': 'Tap', // 惊讶-点击动作 + 'neutral': 'Flick', // 平常-轻扫动作 + 'default': 'Flick@Body' // 默认-身体轻扫动作 + }; + + // 单/双击判定配置与状态 + this._lastClickTime = 0; + this._lastClickPos = { x: 0, y: 0 }; + this._singleClickTimer = null; + this._doubleClickMs = 280; // 双击时间阈值(ms) + this._doubleClickDist = 16; // 双击允许的最大位移(px) + // 滑动判定 + this._pointerDown = false; + this._downPos = { x: 0, y: 0 }; + this._downTime = 0; + this._downArea = 'Body'; + this._movedBeyondClick = false; + this._swipeMinDist = 24; // 触发滑动的最小距离 + } + + /** + * 初始化 Live2D + */ + async initializeLive2D() { + try { + const canvas = document.getElementById('live2d-stage'); + + // 清理之前的 PIXI 应用(防止 WebGL 上下文累积) + if (this.live2dApp) { + try { + this.live2dApp.destroy(true, { children: true, texture: true }); + } catch (e) { /* 忽略清理异常 */ } + this.live2dApp = null; + this.live2dModel = null; + } + + // 供内部使用 + window.PIXI = PIXI; + + // 使用 canvas 容器尺寸(适配 max-width:480 的 H5 容器) + const canvasContainer = canvas.parentElement; + const containerW = canvasContainer ? canvasContainer.clientWidth : window.innerWidth; + const containerH = canvasContainer ? canvasContainer.clientHeight : window.innerHeight; + + // 限制 resolution 最大为 2,避免高分屏 WebGL 纹理溢出 + const resolution = Math.min(window.devicePixelRatio || 1, 2); + + this.live2dApp = new PIXI.Application({ + view: canvas, + height: containerH, + width: containerW, + resolution: resolution, + autoDensity: true, + antialias: false, + backgroundAlpha: 0, + }); + + // 加载 Live2D 模型 - 动态检测当前目录,适配不同环境 + // 获取当前HTML文件所在的目录路径 + const currentPath = window.location.pathname; + const lastSlashIndex = currentPath.lastIndexOf('/'); + const basePath = currentPath.substring(0, lastSlashIndex + 1); + + // 从 localStorage 读取上次选择的模型,如果没有则使用默认 + const savedModelName = localStorage.getItem('live2dModel') || 'hiyori_pro_zh'; + const modelFileMap = { + 'hiyori_pro_zh': 'hiyori_pro_t11.model3.json', + 'natori_pro_zh': 'natori_pro_t06.model3.json' + }; + const modelFileName = modelFileMap[savedModelName] || 'hiyori_pro_t11.model3.json'; + const modelPath = basePath + 'resources/' + savedModelName + '/runtime/' + modelFileName; + + this.live2dModel = await PIXI.live2d.Live2DModel.from(modelPath); + this.live2dApp.stage.addChild(this.live2dModel); + + // 保存当前模型名称 + this.currentModelName = savedModelName; + + // 更新下拉框显示 + const modelSelect = document.getElementById('live2dModelSelect'); + if (modelSelect) { + modelSelect.value = savedModelName; + } + + // 设置模型特定的嘴部参数名 + if (this.modelConfig[savedModelName]) { + this.mouthParam = this.modelConfig[savedModelName].mouthParam || 'ParamMouthOpenY'; + } + + // 设置模型属性 - 全屏放大居中显示 + this.live2dModel.scale.set(0.5); + this.live2dModel.x = (containerW - this.live2dModel.width) * 0.5; + this.live2dModel.y = (containerH - this.live2dModel.height) * 0.1; + + // 启用交互并监听点击命中(头部/身体等) + + this.live2dModel.interactive = true; + + + this.live2dModel.on('doublehit', (args) => { + const area = Array.isArray(args) ? args[0] : args; + + // 触发双击动作 + if (area === 'Body') { + this.motion('Flick@Body'); + } else if (area === 'Head' || area === 'Face') { + this.motion('Flick'); + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'doublehit', area }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + + }); + + this.live2dModel.on('singlehit', (args) => { + const area = Array.isArray(args) ? args[0] : args; + + // 触发单击动作 + if (area === 'Body') { + this.motion('Tap@Body'); + } else if (area === 'Head' || area === 'Face') { + this.motion('Tap'); + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'singlehit', area }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + + }); + + this.live2dModel.on('swipe', (args) => { + const area = Array.isArray(args) ? args[0] : args; + const dir = Array.isArray(args) ? args[1] : undefined; + + // 触发滑动动作 + if (area === 'Body') { + if (dir === 'up') { + this.motion('FlickUp'); + } else if (dir === 'down') { + this.motion('FlickDown'); + } + } else if (area === 'Head' || area === 'Face') { + if (dir === 'up') { + this.motion('FlickUp'); + } else if (dir === 'down') { + this.motion('FlickDown'); + } + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'swipe', area, dir }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + + }); + + // 兜底:自定义"头部/身体"命中区域 + 单/双击/滑动区分 + this.live2dModel.on('pointerdown', (event) => { + try { + const global = event.data.global; + const bounds = this.live2dModel.getBounds(); + // 仅在点击落在模型可见范围内时判定 + if (!bounds || !bounds.contains(global.x, global.y)) return; + + const relX = (global.x - bounds.x) / (bounds.width || 1); + const relY = (global.y - bounds.y) / (bounds.height || 1); + let area = ''; + // 经验阈值:模型可见矩形的上部 20% 视为"头部"区域 + if (relX >= 0.4 && relX <= 0.6) { + if (relY <= 0.15) { + area = 'Head'; + } else if (relY <= 0.23) { + area = 'Face'; + } else { + area = 'Body'; + } + } + if (area === '') { + return; + } + + // 记录按下状态用于滑动判定 + this._pointerDown = true; + this._downPos = { x: global.x, y: global.y }; + this._downTime = performance.now(); + this._downArea = area; + this._movedBeyondClick = false; + + const now = performance.now(); + const dt = now - (this._lastClickTime || 0); + const dx = global.x - (this._lastClickPos?.x || 0); + const dy = global.y - (this._lastClickPos?.y || 0); + const dist = Math.hypot(dx, dy); + + // 命中确认:仅当点击在模型上时做单/双击判断 + if (this._lastClickTime && dt <= this._doubleClickMs && dist <= this._doubleClickDist) { + // 判定为双击:取消待触发的单击事件 + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + if (typeof this.live2dModel.emit === 'function') { + this.live2dModel.emit('doublehit', [area]); + } + this._lastClickTime = 0; + this._pointerDown = false; // 双击完成,重置状态 + return; + } + + // 可能是单击:记录并延迟确认 + this._lastClickTime = now; + this._lastClickPos = { x: global.x, y: global.y }; + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + this._singleClickTimer = setTimeout(() => { + // 若在等待期间发生了移动超过阈值,则不再当作单击 + if (!this._movedBeyondClick && typeof this.live2dModel.emit === 'function') { + this.live2dModel.emit('singlehit', [area]); + } + this._singleClickTimer = null; + this._lastClickTime = 0; + }, this._doubleClickMs); + } catch (e) { + // 忽略自定义命中判断中的异常,避免影响主流程 + } + }); + + // 指针移动:用于判定是否从"点击"升级为"滑动" + this.live2dModel.on('pointermove', (event) => { + try { + if (!this._pointerDown) return; + const global = event.data.global; + const dx = global.x - this._downPos.x; + const dy = global.y - this._downPos.y; + const dist = Math.hypot(dx, dy); + + // 使用 _doubleClickDist 作为点击/滑动的判定阈值 + if (dist > this._doubleClickDist) { + this._movedBeyondClick = true; + // 若已超出点击阈值,取消可能的单击触发 + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + this._lastClickTime = 0; + } + } catch (e) { + // 忽略移动判定中的异常 + } + }); + + // 指针抬起:确认是否为滑动 + const handlePointerUp = (event) => { + try { + if (!this._pointerDown) return; + const global = (event && event.data && event.data.global) ? event.data.global : { x: this._downPos.x, y: this._downPos.y }; + const dx = global.x - this._downPos.x; + const dy = global.y - this._downPos.y; + const dist = Math.hypot(dx, dy); + + // 滑动:超过滑动最小距离则触发 swipe 事件(携带方向与区域) + if (this._movedBeyondClick && dist >= this._swipeMinDist) { + if (typeof this.live2dModel.emit === 'function') { + const dir = Math.abs(dx) >= Math.abs(dy) + ? (dx > 0 ? 'right' : 'left') + : (dy > 0 ? 'down' : 'up'); + this.live2dModel.emit('swipe', [this._downArea, dir]); + } + // 终止:不再让单击/双击触发 + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + this._lastClickTime = 0; + } + } catch (e) { + // 忽略抬起判定中的异常 + } + finally { + this._pointerDown = false; + this._movedBeyondClick = false; + } + }; + + this.live2dModel.on('pointerup', handlePointerUp); + this.live2dModel.on('pointerupoutside', handlePointerUp); + + // 添加窗口大小变化监听器,保持模型在Canvas中间和底部 + window.addEventListener('resize', () => { + if (this.live2dModel) { + // 使用窗口实际尺寸重新计算模型位置 + this.live2dModel.x = (window.innerWidth - this.live2dModel.width) * 0.5; + this.live2dModel.y = -50; + } + }); + + } catch (err) { + console.error('加载 Live2D 模型失败:', err); + } + } + + /** + * 初始化音频分析器 - 使用音频播放器的分析器节点 + */ + initializeAudioAnalyzer() { + try { + // 获取音频播放器实例 + const audioPlayer = window.chatApp?.audioPlayer; + if (!audioPlayer) { + console.warn('音频播放器未初始化,无法获取分析器节点'); + return false; + } + + // 获取音频播放器的音频上下文 + this.audioContext = audioPlayer.getAudioContext(); + if (!this.audioContext) { + console.warn('无法获取音频播放器的音频上下文'); + return false; + } + + // 创建分析器节点 + this.analyser = this.audioContext.createAnalyser(); + this.analyser.fftSize = 256; + this.dataArray = new Uint8Array(this.analyser.frequencyBinCount); + + return true; + } catch (error) { + console.error('初始化音频分析器失败:', error); + return false; + } + } + + /** + * 连接到音频播放器的输出节点 + */ + connectToAudioPlayer() { + try { + // 获取音频播放器的流上下文 + const audioPlayer = window.chatApp?.audioPlayer; + if (!audioPlayer || !audioPlayer.streamingContext) { + console.warn('音频播放器或流上下文未初始化'); + return false; + } + + // 获取音频播放器的流上下文 + const streamingContext = audioPlayer.streamingContext; + + // 获取分析器节点 + const analyser = streamingContext.getAnalyser(); + if (!analyser) { + console.warn('音频播放器尚未创建分析器节点,无法连接'); + return false; + } + + // 使用音频播放器的分析器节点 + this.analyser = analyser; + this.dataArray = new Uint8Array(this.analyser.frequencyBinCount); + return true; + } catch (error) { + console.error('连接到音频播放器失败:', error); + return false; + } + } + + /** + * 嘴部动画循环 + */ + animateMouth() { + if (!this.isTalking) return; + if (!this.live2dModel) return; + const internal = this.live2dModel && this.live2dModel.internalModel; + if (internal && internal.coreModel) { + const coreModel = internal.coreModel; + + let mouthOpenY = 0; + let mouthForm = 0; + let mouthForm2 = 0; + let average = 0; + + if (this.analyser && this.dataArray) { + this.analyser.getByteFrequencyData(this.dataArray); + average = this.dataArray.reduce((a, b) => a + b) / this.dataArray.length; + + const normalizedVolume = average / 255; + + // 获取模型特定的阈值 + let lowThreshold = 0.3; + let highThreshold = 0.7; + if (this.currentModelName && this.modelConfig[this.currentModelName]) { + lowThreshold = this.modelConfig[this.currentModelName].mouthThresholds?.low || 0.3; + highThreshold = this.modelConfig[this.currentModelName].mouthThresholds?.high || 0.7; + } + + // 使用模型特定的阈值进行映射 + let minOpenY = 0.1; + if (this.currentModelName && this.modelConfig[this.currentModelName]) { + minOpenY = this.modelConfig[this.currentModelName].mouthMinOpenY || 0.1; + } + + if (normalizedVolume < lowThreshold) { + mouthOpenY = minOpenY + Math.pow(normalizedVolume / lowThreshold, 1.5) * (0.4 - minOpenY); + } else if (normalizedVolume < highThreshold) { + mouthOpenY = 0.4 + (normalizedVolume - lowThreshold) / (highThreshold - lowThreshold) * 0.4; + } else { + mouthOpenY = 0.8 + Math.pow((normalizedVolume - highThreshold) / (1 - highThreshold), 1.2) * 0.2; + } + + // 应用模型特定的嘴部开合幅度 + let amplitudeMultiplier = 1.0; + let maxOpenY = 2.5; + if (this.currentModelName && this.modelConfig[this.currentModelName]) { + amplitudeMultiplier = this.modelConfig[this.currentModelName].mouthAmplitude; + maxOpenY = this.modelConfig[this.currentModelName].maxOpenY || 2.5; + } + mouthOpenY = mouthOpenY * amplitudeMultiplier; + mouthOpenY = Math.min(Math.max(mouthOpenY, 0), maxOpenY); + + // 计算嘴型参数(仅对支持嘴型变化的模型) + if (this.currentModelName && this.modelConfig[this.currentModelName]?.mouthFormParam) { + const config = this.modelConfig[this.currentModelName]; + const formAmplitude = config.mouthFormAmplitude || 0.5; + const form2Amplitude = config.mouthForm2Amplitude || 0; + + // 嘴型随音量变化: + // 低音量:嘴型偏"一"字(负值) + // 高音量:嘴型偏"o"字(正值) + // 音量=0时:嘴型=0(自然状态) + mouthForm = (normalizedVolume - 0.5) * 2 * formAmplitude; + mouthForm = Math.max(-formAmplitude, Math.min(formAmplitude, mouthForm)); + + // 第二嘴型参数(natori特有) + if (config.mouthForm2Param) { + mouthForm2 = (normalizedVolume - 0.3) * 2 * form2Amplitude; + mouthForm2 = Math.max(-form2Amplitude, Math.min(form2Amplitude, mouthForm2)); + } + } + + // 调试日志:每60帧输出一次(避免控制台刷屏) + if (!this._debugFrameCount) this._debugFrameCount = 0; + this._debugFrameCount++; + if (this._debugFrameCount % 60 === 1) { + console.log(`[Live2D] 模型: ${this.currentModelName || 'unknown'}, 音量: ${average?.toFixed(0)}, OpenY: ${mouthOpenY.toFixed(3)}`); + } + } + + // 设置嘴部开合参数 + coreModel.setParameterValueById(this.mouthParam, mouthOpenY); + + // 设置嘴型参数(仅对支持嘴型变化的模型) + if (this.currentModelName && this.modelConfig[this.currentModelName]?.mouthFormParam) { + const config = this.modelConfig[this.currentModelName]; + const formParam = config.mouthFormParam; + coreModel.setParameterValueById(formParam, mouthForm); + + // 设置第二嘴型参数(natori特有) + if (config.mouthForm2Param) { + coreModel.setParameterValueById(config.mouthForm2Param, mouthForm2); + } + } + + coreModel.update(); + } + this.mouthAnimationId = requestAnimationFrame(() => this.animateMouth()); + } + + /** + * 开始说话动画 + */ + startTalking() { + if (this.isTalking || !this.live2dModel) return; + + // 确保音频分析器已初始化 + if (!this.analyser) { + if (!this.initializeAudioAnalyzer()) { + console.warn('音频分析器初始化失败,将使用模拟动画'); + // 即使分析器初始化失败,也启动动画(使用模拟数据) + this.isTalking = true; + this.animateMouth(); + return; + } + } + + // 连接到音频播放器输出 + if (!this.connectToAudioPlayer()) { + console.warn('无法连接到音频播放器输出,将使用模拟动画'); + } + + this.isTalking = true; + this.animateMouth(); + } + + /** + * 停止说话动画 + */ + stopTalking() { + this.isTalking = false; + if (this.mouthAnimationId) { + cancelAnimationFrame(this.mouthAnimationId); + this.mouthAnimationId = null; + } + + // 重置嘴部参数 + if (this.live2dModel) { + const internal = this.live2dModel.internalModel; + if (internal && internal.coreModel) { + const coreModel = internal.coreModel; + coreModel.setParameterValueById(this.mouthParam, 0); + coreModel.update(); + } + } + } + + /** + * 基于情绪触发动作 + * @param {string} emotion - 情绪名称 + */ + triggerEmotionAction(emotion) { + if (!this.live2dModel) return; + + // 添加冷却时间控制,避免过于频繁触发 + const now = Date.now(); + if (this.lastEmotionActionTime && now - this.lastEmotionActionTime < 5000) { // 5秒冷却时间 + return; + } + + // 根据情绪获取对应的动作 + const action = this.emotionToActionMap[emotion] || this.emotionToActionMap['default']; + + // 触发动作并记录时间 + this.motion(action); + this.lastEmotionActionTime = now; + } + + + + /** + * 触发模型动作(Motion) + * @param {string} name - 动作分组名称,如 'TapBody'、'FlickUp'、'Idle' 等 + */ + motion(name) { + try { + if (!this.live2dModel) return; + + // 根据当前模型获取对应的动作名称 + let actualMotionName = name; + if (this.currentModelName && this.modelConfig[this.currentModelName]) { + const motionMap = this.modelConfig[this.currentModelName].motionMap; + actualMotionName = motionMap[name] || name; + } + + this.live2dModel.motion(actualMotionName); + } catch (error) { + console.error('触发动作失败:', error); + } + } + + /** + * 设置模型交互事件 + */ + setupModelInteractions() { + if (!this.live2dModel) return; + + this.live2dModel.interactive = true; + + this.live2dModel.on('doublehit', (args) => { + const area = Array.isArray(args) ? args[0] : args; + + if (area === 'Body') { + this.motion('Flick@Body'); + } else if (area === 'Head' || area === 'Face') { + this.motion('Flick'); + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'doublehit', area }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + }); + + this.live2dModel.on('singlehit', (args) => { + const area = Array.isArray(args) ? args[0] : args; + + if (area === 'Body') { + this.motion('Tap@Body'); + } else if (area === 'Head' || area === 'Face') { + this.motion('Tap'); + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'singlehit', area }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + }); + + this.live2dModel.on('swipe', (args) => { + const area = Array.isArray(args) ? args[0] : args; + const dir = Array.isArray(args) ? args[1] : undefined; + + if (area === 'Body') { + if (dir === 'up') { + this.motion('FlickUp'); + } else if (dir === 'down') { + this.motion('FlickDown'); + } + } + + const app = window.chatApp; + const payload = JSON.stringify({ type: 'live2d', event: 'swipe', area, dir }); + if (app && app.dataChannel && app.dataChannel.readyState === 'open') { + app.dataChannel.send(payload); + } + }); + + this.live2dModel.on('pointerdown', (event) => { + try { + const global = event.data.global; + const bounds = this.live2dModel.getBounds(); + if (!bounds || !bounds.contains(global.x, global.y)) return; + + const relX = (global.x - bounds.x) / (bounds.width || 1); + const relY = (global.y - bounds.y) / (bounds.height || 1); + let area = ''; + + if (relX >= 0.4 && relX <= 0.6) { + if (relY <= 0.15) { + area = 'Head'; + } else if (relY >= 0.7) { + area = 'Body'; + } + } + + if (!area) return; + + const now = Date.now(); + const dt = now - (this._lastClickTime || 0); + const dx = global.x - (this._lastClickPos?.x || 0); + const dy = global.y - (this._lastClickPos?.y || 0); + const dist = Math.hypot(dx, dy); + + if (this._lastClickTime && dt <= this._doubleClickMs && dist <= this._doubleClickDist) { + if (this._singleClickTimer) { + clearTimeout(this._singleClickTimer); + this._singleClickTimer = null; + } + + this.live2dModel.emit('doublehit', area); + this._lastClickTime = null; + this._lastClickPos = null; + } else { + this._lastClickTime = now; + this._lastClickPos = { x: global.x, y: global.y }; + + this._singleClickTimer = setTimeout(() => { + this._singleClickTimer = null; + this.live2dModel.emit('singlehit', area); + }, this._doubleClickMs); + } + } catch (e) { + console.warn('pointerdown 处理出错:', e); + } + }); + } + + /** + * 清理资源 + */ + destroy() { + this.stopTalking(); + + // 清理音频分析器 + if (this.audioContext) { + try { this.audioContext.close(); } catch (e) {} + this.audioContext = null; + } + this.analyser = null; + this.dataArray = null; + + // 清理 Live2D 模型 + if (this.live2dModel) { + try { + this.live2dModel.interactive = false; + this.live2dModel.removeAllListeners(); + if (this.live2dApp && this.live2dApp.stage) { + this.live2dApp.stage.removeChild(this.live2dModel); + } + if (typeof this.live2dModel.destroy === 'function') { + this.live2dModel.destroy(); + } + } catch (e) { /* 忽略清理异常 */ } + this.live2dModel = null; + } + + // 清理 PIXI 应用(释放 WebGL 上下文) + if (this.live2dApp) { + try { + this.live2dApp.destroy(true, { children: true, texture: true, baseTexture: true }); + } catch (e) { /* 忽略清理异常 */ } + this.live2dApp = null; + } + } + + /** + * 切换 Live2D 模型 + * @param {string} modelName - 模型目录名称,如 'hiyori_pro_zh'、'natori_pro_zh' + * @returns {Promise} - 切换是否成功 + */ + async switchModel(modelName) { + try { + // 获取模型文件名映射 + const modelFileMap = { + 'hiyori_pro_zh': 'hiyori_pro_t11.model3.json', + 'natori_pro_zh': 'natori_pro_t06.model3.json', + 'chitose': 'chitose.model3.json', + 'haru_greeter_pro_jp': 'haru_greeter_t05.model3.json' + }; + + const modelFileName = modelFileMap[modelName]; + if (!modelFileName) { + console.error('未知的模型名称:', modelName); + return false; + } + + // 获取基础路径 + const currentPath = window.location.pathname; + const lastSlashIndex = currentPath.lastIndexOf('/'); + const basePath = currentPath.substring(0, lastSlashIndex + 1); + const modelPath = basePath + 'resources/' + modelName + '/runtime/' + modelFileName; + + // 如果已存在模型,先移除 + if (this.live2dModel) { + this.live2dApp.stage.removeChild(this.live2dModel); + this.live2dModel.destroy(); + this.live2dModel = null; + } + + // 显示加载状态 + const app = window.chatApp; + if (app) { + app.setModelLoadingStatus(true); + } + + // 加载新模型 + this.live2dModel = await PIXI.live2d.Live2DModel.from(modelPath); + this.live2dApp.stage.addChild(this.live2dModel); + + // 设置模型属性 + this.live2dModel.scale.set(0.33); + this.live2dModel.x = (window.innerWidth - this.live2dModel.width) * 0.5; + this.live2dModel.y = -50; + + // 重新绑定交互事件 + this.setupModelInteractions(); + + // 隐藏加载状态 + if (app) { + app.setModelLoadingStatus(false); + } + + // 保存当前模型名称 + this.currentModelName = modelName; + + // 设置模型特定的嘴部参数名 + if (this.modelConfig[modelName]) { + this.mouthParam = this.modelConfig[modelName].mouthParam || 'ParamMouthOpenY'; + } + + // 保存到 localStorage + localStorage.setItem('live2dModel', modelName); + + // 更新下拉框显示 + const modelSelect = document.getElementById('live2dModelSelect'); + if (modelSelect) { + modelSelect.value = modelName; + } + + console.log('模型切换成功:', modelName); + return true; + } catch (error) { + console.error('切换模型失败:', error); + const app = window.chatApp; + if (app) { + app.setModelLoadingStatus(false); + } + return false; + } + } + + +} + +// 导出全局实例 +window.Live2DManager = Live2DManager; diff --git a/main/feedback-h5/js/logger.js b/main/feedback-h5/js/logger.js new file mode 100644 index 000000000..e7a9c6106 --- /dev/null +++ b/main/feedback-h5/js/logger.js @@ -0,0 +1,43 @@ +// 日志记录函数 +export function log(message, type = 'info') { + // 将消息按换行符分割成多行 + const lines = message.split('\n'); + const now = new Date(); + // const timestamp = `[${now.toLocaleTimeString()}] `; + const timestamp = `[${now.toLocaleTimeString()}.${now.getMilliseconds().toString().padStart(3, '0')}] `; + + // 检查是否存在日志容器 + const logContainer = document.getElementById('logContainer'); + if (!logContainer) { + // 如果日志容器不存在,只输出到控制台 + console.log(`[${type.toUpperCase()}] ${message}`); + return; + } + + // 为每一行创建日志条目 + lines.forEach((line, index) => { + const logEntry = document.createElement('div'); + logEntry.className = `log-entry log-${type}`; + // 如果是第一条日志,显示时间戳 + const prefix = index === 0 ? timestamp : ' '.repeat(timestamp.length); + logEntry.textContent = `${prefix}${line}`; + // logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`; + // logEntry.style 保留起始的空格 + logEntry.style.whiteSpace = 'pre'; + if (type === 'error') { + logEntry.style.color = 'red'; + } else if (type === 'debug') { + logEntry.style.color = 'gray'; + return; + } else if (type === 'warning') { + logEntry.style.color = 'orange'; + } else if (type === 'success') { + logEntry.style.color = 'green'; + } else { + logEntry.style.color = 'black'; + } + logContainer.appendChild(logEntry); + }); + + logContainer.scrollTop = logContainer.scrollHeight; +} \ No newline at end of file diff --git a/main/feedback-h5/js/opus-codec.js b/main/feedback-h5/js/opus-codec.js new file mode 100644 index 000000000..910e1481a --- /dev/null +++ b/main/feedback-h5/js/opus-codec.js @@ -0,0 +1,182 @@ +import { log } from './logger.js'; + + +// 检查Opus库是否已加载 +export function checkOpusLoaded() { + try { + // 检查Module是否存在(本地库导出的全局变量) + if (typeof Module === 'undefined') { + throw new Error('Opus库未加载,Module对象不存在'); + } + + // 尝试先使用Module.instance(libopus.js最后一行导出方式) + if (typeof Module.instance !== 'undefined' && typeof Module.instance._opus_decoder_get_size === 'function') { + // 使用Module.instance对象替换全局Module对象 + window.ModuleInstance = Module.instance; + log('Opus库加载成功(使用Module.instance)', 'success'); + + // 3秒后隐藏状态 + const statusElement = document.getElementById('scriptStatus'); + if (statusElement) statusElement.style.display = 'none'; + return; + } + + // 如果没有Module.instance,检查全局Module函数 + if (typeof Module._opus_decoder_get_size === 'function') { + window.ModuleInstance = Module; + log('Opus库加载成功(使用全局Module)', 'success'); + + // 3秒后隐藏状态 + const statusElement = document.getElementById('scriptStatus'); + if (statusElement) statusElement.style.display = 'none'; + return; + } + + throw new Error('Opus解码函数未找到,可能Module结构不正确'); + } catch (err) { + log(`Opus库加载失败,请检查libopus.js文件是否存在且正确: ${err.message}`, 'error'); + } +} + + +// 创建一个Opus编码器 +let opusEncoder = null; +export function initOpusEncoder() { + try { + if (opusEncoder) { + return opusEncoder; // 已经初始化过 + } + + if (!window.ModuleInstance) { + log('无法创建Opus编码器:ModuleInstance不可用', 'error'); + return; + } + + // 初始化一个Opus编码器 + const mod = window.ModuleInstance; + const sampleRate = 16000; // 16kHz采样率 + const channels = 1; // 单声道 + const application = 2048; // OPUS_APPLICATION_VOIP = 2048 + + // 创建编码器 + opusEncoder = { + channels: channels, + sampleRate: sampleRate, + frameSize: 960, // 60ms @ 16kHz = 60 * 16 = 960 samples + maxPacketSize: 4000, // 最大包大小 + module: mod, + + // 初始化编码器 + init: function () { + try { + // 获取编码器大小 + const encoderSize = mod._opus_encoder_get_size(this.channels); + log(`Opus编码器大小: ${encoderSize}字节`, 'info'); + + // 分配内存 + this.encoderPtr = mod._malloc(encoderSize); + if (!this.encoderPtr) { + throw new Error("无法分配编码器内存"); + } + + // 初始化编码器 + const err = mod._opus_encoder_init( + this.encoderPtr, + this.sampleRate, + this.channels, + application + ); + + if (err < 0) { + throw new Error(`Opus编码器初始化失败: ${err}`); + } + + // 设置位率 (16kbps) + mod._opus_encoder_ctl(this.encoderPtr, 4002, 16000); // OPUS_SET_BITRATE + + // 设置复杂度 (0-10, 越高质量越好但CPU使用越多) + mod._opus_encoder_ctl(this.encoderPtr, 4010, 5); // OPUS_SET_COMPLEXITY + + // 设置使用DTX (不传输静音帧) + mod._opus_encoder_ctl(this.encoderPtr, 4016, 1); // OPUS_SET_DTX + + log("Opus编码器初始化成功", 'success'); + return true; + } catch (error) { + if (this.encoderPtr) { + mod._free(this.encoderPtr); + this.encoderPtr = null; + } + log(`Opus编码器初始化失败: ${error.message}`, 'error'); + return false; + } + }, + + // 编码PCM数据为Opus + encode: function (pcmData) { + if (!this.encoderPtr) { + if (!this.init()) { + return null; + } + } + + try { + const mod = this.module; + + // 为PCM数据分配内存 + const pcmPtr = mod._malloc(pcmData.length * 2); // 2字节/int16 + + // 将PCM数据复制到HEAP + for (let i = 0; i < pcmData.length; i++) { + mod.HEAP16[(pcmPtr >> 1) + i] = pcmData[i]; + } + + // 为输出分配内存 + const outPtr = mod._malloc(this.maxPacketSize); + + // 进行编码 + const encodedLen = mod._opus_encode( + this.encoderPtr, + pcmPtr, + this.frameSize, + outPtr, + this.maxPacketSize + ); + + if (encodedLen < 0) { + throw new Error(`Opus编码失败: ${encodedLen}`); + } + + // 复制编码后的数据 + const opusData = new Uint8Array(encodedLen); + for (let i = 0; i < encodedLen; i++) { + opusData[i] = mod.HEAPU8[outPtr + i]; + } + + // 释放内存 + mod._free(pcmPtr); + mod._free(outPtr); + + return opusData; + } catch (error) { + log(`Opus编码出错: ${error.message}`, 'error'); + return null; + } + }, + + // 销毁编码器 + destroy: function () { + if (this.encoderPtr) { + this.module._free(this.encoderPtr); + this.encoderPtr = null; + } + } + }; + + opusEncoder.init(); + return opusEncoder; + } catch (error) { + log(`创建Opus编码器失败: ${error.message}`, 'error'); + return false; + } +} \ No newline at end of file diff --git a/main/feedback-h5/js/stream-context.js b/main/feedback-h5/js/stream-context.js new file mode 100644 index 000000000..9a9761f6a --- /dev/null +++ b/main/feedback-h5/js/stream-context.js @@ -0,0 +1,221 @@ +import BlockingQueue from './blocking-queue.js'; +import { log } from './logger.js'; + +// 音频流播放上下文类 +export class StreamingContext { + constructor(opusDecoder, audioContext, sampleRate, channels, minAudioDuration) { + this.opusDecoder = opusDecoder; + this.audioContext = audioContext; + + // 音频参数 + this.sampleRate = sampleRate; + this.channels = channels; + this.minAudioDuration = minAudioDuration; + + // 初始化队列和状态 + this.queue = []; // 已解码的PCM队列。正在播放 + this.activeQueue = new BlockingQueue(); // 已解码的PCM队列。准备播放 + this.pendingAudioBufferQueue = []; // 待处理的缓存队列 + this.audioBufferQueue = new BlockingQueue(); // 缓存队列 + this.playing = false; // 是否正在播放 + this.endOfStream = false; // 是否收到结束信号 + this.source = null; // 当前音频源 + this.totalSamples = 0; // 累积的总样本数 + this.lastPlayTime = 0; // 上次播放的时间戳 + this.scheduledEndTime = 0; // 已调度音频的结束时间 + + // 初始化分析器节点(供Live2D使用) + this.analyser = this.audioContext.createAnalyser(); + this.analyser.fftSize = 256; + } + + // 缓存音频数组 + pushAudioBuffer(item) { + this.audioBufferQueue.enqueue(...item); + } + + // 获取需要处理缓存队列,单线程:在audioBufferQueue一直更新的状态下不会出现安全问题 + async getPendingAudioBufferQueue() { + // 等待数据到达并获取 + const data = await this.audioBufferQueue.dequeue(); + // 赋值给待处理队列 + this.pendingAudioBufferQueue = data; + } + + // 获取正在播放已解码的PCM队列,单线程:在activeQueue一直更新的状态下不会出现安全问题 + async getQueue(minSamples) { + const num = minSamples - this.queue.length > 0 ? minSamples - this.queue.length : 1; + + // 等待数据并获取 + const tempArray = await this.activeQueue.dequeue(num); + this.queue.push(...tempArray); + } + + // 将Int16音频数据转换为Float32音频数据 + convertInt16ToFloat32(int16Data) { + const float32Data = new Float32Array(int16Data.length); + for (let i = 0; i < int16Data.length; i++) { + // 将[-32768,32767]范围转换为[-1,1],统一使用32768.0避免不对称失真 + float32Data[i] = int16Data[i] / 32768.0; + } + return float32Data; + } + + // 获取待解码包数 + getPendingDecodeCount() { + return this.audioBufferQueue.length + this.pendingAudioBufferQueue.length; + } + + // 获取待播放样本数(转换为包数,每包960样本) + getPendingPlayCount() { + // 计算已在队列中的样本 + const queuedSamples = this.activeQueue.length + this.queue.length; + + // 计算已调度但未播放的样本(在Web Audio缓冲区中) + let scheduledSamples = 0; + if (this.playing && this.scheduledEndTime) { + const currentTime = this.audioContext.currentTime; + const remainingTime = Math.max(0, this.scheduledEndTime - currentTime); + scheduledSamples = Math.floor(remainingTime * this.sampleRate); + } + + const totalSamples = queuedSamples + scheduledSamples; + return Math.ceil(totalSamples / 960); + } + + // 清空所有音频缓冲 + clearAllBuffers() { + log('清空所有音频缓冲', 'info'); + + // 清空所有队列(使用clear方法保持对象引用) + this.audioBufferQueue.clear(); + this.pendingAudioBufferQueue = []; + this.activeQueue.clear(); + this.queue = []; + + // 停止当前播放的音频源 + if (this.source) { + try { + this.source.stop(); + this.source.disconnect(); + } catch (e) { + // 忽略已经停止的错误 + } + this.source = null; + } + + // 重置状态 + this.playing = false; + this.scheduledEndTime = this.audioContext.currentTime; + this.totalSamples = 0; + + log('音频缓冲已清空', 'success'); + } + + // 获取分析器节点(供Live2D使用) + getAnalyser() { + return this.analyser; + } + + // 将Opus数据解码为PCM + async decodeOpusFrames() { + if (!this.opusDecoder) { + log('Opus解码器未初始化,无法解码', 'error'); + return; + } else { + log('Opus解码器启动', 'info'); + } + + while (true) { + let decodedSamples = []; + for (const frame of this.pendingAudioBufferQueue) { + try { + // 使用Opus解码器解码 + const frameData = this.opusDecoder.decode(frame); + if (frameData && frameData.length > 0) { + // 转换为Float32 + const floatData = this.convertInt16ToFloat32(frameData); + // 使用循环替代展开运算符 + for (let i = 0; i < floatData.length; i++) { + decodedSamples.push(floatData[i]); + } + } + } catch (error) { + log("Opus解码失败: " + error.message, 'error'); + } + } + + if (decodedSamples.length > 0) { + // 使用循环替代展开运算符 + for (let i = 0; i < decodedSamples.length; i++) { + this.activeQueue.enqueue(decodedSamples[i]); + } + this.totalSamples += decodedSamples.length; + } else { + log('没有成功解码的样本', 'warning'); + } + await this.getPendingAudioBufferQueue(); + } + } + + // 开始播放音频 + async startPlaying() { + this.scheduledEndTime = this.audioContext.currentTime; // 跟踪已调度音频的结束时间 + + while (true) { + // 初始缓冲:等待足够的样本再开始播放 + const minSamples = this.sampleRate * this.minAudioDuration * 2; + if (!this.playing && this.queue.length < minSamples) { + await this.getQueue(minSamples); + } + this.playing = true; + + // 持续播放队列中的音频,每次播放一个小块 + while (this.playing && this.queue.length > 0) { + // 每次播放120ms的音频(2个Opus包) + const playDuration = 0.12; + const targetSamples = Math.floor(this.sampleRate * playDuration); + const actualSamples = Math.min(this.queue.length, targetSamples); + + if (actualSamples === 0) break; + + const currentSamples = this.queue.splice(0, actualSamples); + const audioBuffer = this.audioContext.createBuffer(this.channels, currentSamples.length, this.sampleRate); + audioBuffer.copyToChannel(new Float32Array(currentSamples), 0); + + // 创建音频源 + this.source = this.audioContext.createBufferSource(); + this.source.buffer = audioBuffer; + + // 精确调度播放时间 + const currentTime = this.audioContext.currentTime; + const startTime = Math.max(this.scheduledEndTime, currentTime); + + // 连接到分析器和输出 + this.source.connect(this.analyser); + this.source.connect(this.audioContext.destination); + + log(`调度播放 ${currentSamples.length} 个样本,约 ${(currentSamples.length / this.sampleRate).toFixed(2)} 秒`, 'debug'); + this.source.start(startTime); + + // 更新下一个音频块的调度时间 + const duration = audioBuffer.duration; + this.scheduledEndTime = startTime + duration; + this.lastPlayTime = startTime; + + // 如果队列中数据不足,等待新数据 + if (this.queue.length < targetSamples) { + break; + } + } + + // 等待新数据 + await this.getQueue(minSamples); + } + } +} + +// 创建streamingContext实例的工厂函数 +export function createStreamingContext(opusDecoder, audioContext, sampleRate, channels, minAudioDuration) { + return new StreamingContext(opusDecoder, audioContext, sampleRate, channels, minAudioDuration); +} \ No newline at end of file diff --git a/main/feedback-h5/js/utils.js b/main/feedback-h5/js/utils.js new file mode 100644 index 000000000..c9dfdf4d4 --- /dev/null +++ b/main/feedback-h5/js/utils.js @@ -0,0 +1,180 @@ +// 工具函数模块 + +// 生成随机MAC地址 +export function generateRandomMac() { + const hexDigits = '0123456789ABCDEF'; + let mac = 'FB'; + for (let i = 0; i < 5; i++) { + mac += ':'; + for (let j = 0; j < 2; j++) { + mac += hexDigits.charAt(Math.floor(Math.random() * 16)); + } + } + return mac; +} + +// 复制文本到剪贴板(兼容手机浏览器/微信内置浏览器) +export async function copyToClipboard(text) { + const value = String(text || ''); + if (!value) return false; + + // 1. 标准 Clipboard API:必须在用户点击事件中调用,HTTPS 下成功率最高 + try { + if (navigator.clipboard && navigator.clipboard.writeText) { + await navigator.clipboard.writeText(value); + return true; + } + } catch (e) { + // 继续走降级方案 + } + + // 2. 移动端/旧浏览器降级:textarea + select + execCommand + const textArea = document.createElement('textarea'); + textArea.value = value; + textArea.setAttribute('readonly', 'readonly'); + textArea.style.position = 'fixed'; + textArea.style.top = '50%'; + textArea.style.left = '50%'; + textArea.style.width = '1px'; + textArea.style.height = '1px'; + textArea.style.opacity = '0.01'; + textArea.style.zIndex = '-1'; + document.body.appendChild(textArea); + + try { + textArea.focus({ preventScroll: true }); + textArea.select(); + textArea.setSelectionRange(0, value.length); + const ok = document.execCommand && document.execCommand('copy'); + document.body.removeChild(textArea); + return !!ok; + } catch (e) { + try { document.body.removeChild(textArea); } catch (_) {} + return false; + } +} + +export function showManualCopySheet(text) { + const old = document.getElementById('manualCopySheet'); + if (old) old.remove(); + const overlay = document.createElement('div'); + overlay.id = 'manualCopySheet'; + overlay.className = 'manual-copy-overlay'; + overlay.innerHTML = ` +
      +

      长按复制点评文字

      +

      当前浏览器限制了自动复制,请长按下方文本,使用手机系统菜单复制。

      + + +
      `; + document.body.appendChild(overlay); + const ta = document.getElementById('manualCopyText'); + setTimeout(() => { + try { + ta.focus(); + ta.select(); + ta.setSelectionRange(0, ta.value.length); + } catch (e) {} + }, 50); + document.getElementById('manualCopyClose').onclick = () => overlay.remove(); +} + +// TTS语音播报 +export function speak(text) { + try { + if ('speechSynthesis' in window) { + window.speechSynthesis.cancel(); + const utterance = new SpeechSynthesisUtterance(text); + utterance.lang = 'zh-CN'; + utterance.rate = 1.0; + utterance.pitch = 1.0; + window.speechSynthesis.speak(utterance); + return true; + } + } catch (e) { + // 忽略TTS错误 + } + return false; +} + +// 检测是否是移动端 +export function isMobile() { + return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); +} + +// 检测是否在微信内 +function isWechat() { + return /MicroMessenger/i.test(navigator.userAgent); +} + +// 智能跳转 - 先尝试唤起APP,失败则跳网页版 +function smartOpen(appUrl, webUrl, appName) { + // 微信浏览器拦截 deep link,直接跳网页提示 + if (isWechat()) { + alert(`微信内无法直接打开${appName},请点击右上角菜单 → "在浏览器中打开"`); + window.location.href = webUrl; + return; + } + + // PC 浏览器或非移动端 - 直接打开网页 + if (!isMobile()) { + window.open(webUrl, '_blank'); + return; + } + + // 移动端 - 用 iframe 唤起 APP,避免错误页面 + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + iframe.src = appUrl; + document.body.appendChild(iframe); + + // 监听页面是否真的离开了(说明 APP 唤起成功) + let appOpened = false; + const visibilityHandler = () => { + if (document.hidden) { + appOpened = true; + } + }; + document.addEventListener('visibilitychange', visibilityHandler); + + // 2.5秒后判断:如果页面没有变成 hidden,说明 APP 没打开,跳网页 + setTimeout(() => { + document.removeEventListener('visibilitychange', visibilityHandler); + if (iframe.parentNode) iframe.parentNode.removeChild(iframe); + + if (!appOpened && !document.hidden) { + // APP 没打开 - 跳网页 + window.location.href = webUrl; + } + }, 2500); +} + +// 打开大众点评 - 直接搜索门店 +export function openDianping(storeName) { + // 大众点评 URL Scheme(搜索关键词) + // 注意:iOS需要在白名单 LSApplicationQueriesSchemes + const appUrl = `dianping://search?keyword=${encodeURIComponent(storeName)}`; + const webUrl = `https://www.dianping.com/search/keyword/0/0_${encodeURIComponent(storeName)}`; + smartOpen(appUrl, webUrl, '大众点评'); +} + +// 打开美团 - 直接搜索门店 +export function openMeituan(storeName) { + // 美团 URL Scheme(搜索关键词) + const appUrl = `imeituan://www.meituan.com/search?q=${encodeURIComponent(storeName)}`; + const webUrl = `https://i.meituan.com/index/search?q=${encodeURIComponent(storeName)}`; + smartOpen(appUrl, webUrl, '美团'); +} + +// 员工类型标签 +export const EMPLOYEE_TYPE_MAP = { + 'manager': '店长', + 'excellent': '优秀', + 'intern': '实习', + 'normal': '' +}; + +// 获取员工类型标签 +export function getEmployeeTypeLabel(type) { + return EMPLOYEE_TYPE_MAP[type] || ''; +} diff --git a/main/feedback-h5/js/version.js b/main/feedback-h5/js/version.js new file mode 100644 index 000000000..0b33c0acd --- /dev/null +++ b/main/feedback-h5/js/version.js @@ -0,0 +1,33 @@ +/** + * 版本控制 + 缓存清除 + * + * 作用:每次部署后修改 VERSION 常量,浏览器会把所有 JS/CSS + * 当成新文件强制重新下载,彻底解决手机端缓存旧版代码的问题。 + * + * 工作原理: + * 1. 页面加载时,这个脚本最早执行(在 app.js 之前) + * 2. 找到所有