Compare commits

..
Author SHA1 Message Date
DismissedLight 45f55f94cd part 2 2025-01-21 22:10:50 +08:00
DismissedLight d4aae4508a init test 2025-01-21 17:31:09 +08:00
1253 changed files with 75361 additions and 83322 deletions

No files matched your search

-27
View File
@@ -1,27 +0,0 @@
main:
# 自定义按钮可触发的事件
web_trigger_one:
- docker:
image: python:3.11
imports:
- https://cnb.cool/bettergi/secret/-/blob/main/env.yml
stages:
- name: 下载构建物并上传
script: |
cd .github/workflows
pip install -r requirements.txt
python github_download_and_cnb_upload.py --cnb-token $CNB_TOKEN --github-token $GITHUB_TOKEN
echo done!
api_trigger_one:
- docker:
image: python:3.11
imports:
- https://cnb.cool/bettergi/secret/-/blob/main/env.yml
stages:
- name: API触发上传
script: |
echo run id: $RUN_ID
cd .github/workflows
pip install -r requirements.txt
python github_download_and_cnb_upload.py --cnb-token $CNB_TOKEN --github-token $GITHUB_TOKEN --run-id $RUN_ID
echo api done!
-5
View File
@@ -1,5 +0,0 @@
branch:
- buttons:
- name: 触发上传
description: 上传测试版或者正式版
event: web_trigger_one
-452
View File
@@ -1,452 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CNB Release Uploader
依赖:
- requests
- tqdm
安装依赖:
pip install requests tqdm
"""
import os
import json
import requests
import time
import sys
import argparse
from typing import List, Dict, Optional
from pathlib import Path
from tqdm import tqdm
class CNBReleaseUploader:
def __init__(self, token: str, base_url: str = "https://api.cnb.cool"):
"""
初始化CNB Release上传器
Args:
token: 认证token
base_url: API基础URL
"""
self.token = token
self.base_url = base_url
self.headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
'User-Agent': 'CNB-Release-Uploader/1.0.0',
'Host': 'api.cnb.cool',
'Connection': 'keep-alive'
}
def create_release(self, project_path: str, release_data: Dict) -> Optional[Dict]:
"""
创建一个新的release
Args:
project_path: 项目路径 (例如: "bettergi/better-genshin-impact")
release_data: release数据
Returns:
创建的release信息或None
"""
url = f"{self.base_url}/{project_path}/-/releases"
# 打印请求信息
print("\n📋 请求头 (Headers):")
for key, value in self.headers.items():
print(f" {key}: {value}")
try:
response = requests.post(url, headers=self.headers, json=release_data)
response.raise_for_status()
release_info = response.json()
print(f"✅ Release创建成功: {release_info.get('name', 'N/A')}")
print(f" Release ID: {release_info.get('id', 'N/A')}")
print(f" Tag Name: {release_info.get('tag_name', 'N/A')}")
print(f" Created At: {release_info.get('created_at', 'N/A')}")
print(f" Is Latest: {release_info.get('is_latest', False)}")
return release_info
except requests.exceptions.RequestException as e:
print(f"❌ 创建release失败: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f" 状态码: {e.response.status_code}")
print(f" 响应内容: {e.response.text}")
return None
def get_asset_upload_url(self, project_path: str, release_id: str, asset_name: str,
file_size: int, overwrite: bool = True) -> Optional[Dict]:
"""
获取asset上传URL
Args:
project_path: 项目路径
release_id: release ID
asset_name: asset名称
file_size: 文件大小
overwrite: 是否覆盖现有文件
Returns:
包含upload_url等信息的字典或None
"""
url = f"{self.base_url}/{project_path}/-/releases/{release_id}/asset-upload-url"
data = {
"asset_name": asset_name,
"overwrite": overwrite,
"size": file_size
}
try:
response = requests.post(url, headers=self.headers, json=data)
response.raise_for_status()
upload_info = response.json()
print(f"✅ 获取上传URL成功")
return upload_info
except requests.exceptions.RequestException as e:
print(f"❌ 获取上传URL失败 ({asset_name}): {e}")
if hasattr(e, 'response') and e.response is not None:
print(f" 状态码: {e.response.status_code}")
print(f" 响应内容: {e.response.text}")
return None
def upload_asset(self, upload_url: str, file_path: str, show_progress: bool = True) -> bool:
"""
上传asset文件
Args:
upload_url: 上传URL
file_path: 本地文件路径
show_progress: 是否显示上传进度条
Returns:
是否上传成功
"""
if not os.path.exists(file_path):
print(f"❌ 文件不存在: {file_path}")
return False
upload_headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {self.token}',
}
file_size = os.path.getsize(file_path)
file_name = os.path.basename(file_path)
try:
with open(file_path, 'rb') as file:
if show_progress and file_size > 0:
# 创建进度条
progress_bar = tqdm(
total=file_size,
unit='B',
unit_scale=True,
unit_divisor=1024,
desc=f"📤 上传 {file_name}",
ncols=80,
bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]'
)
# 创建一个包装器来更新进度条
class ProgressFileWrapper:
def __init__(self, file_obj, progress_bar):
self.file_obj = file_obj
self.progress_bar = progress_bar
def read(self, size=-1):
data = self.file_obj.read(size)
if data:
self.progress_bar.update(len(data))
return data
def __getattr__(self, name):
return getattr(self.file_obj, name)
wrapped_file = ProgressFileWrapper(file, progress_bar)
response = requests.put(upload_url, headers=upload_headers, data=wrapped_file)
progress_bar.close()
else:
response = requests.put(upload_url, headers=upload_headers, data=file)
response.raise_for_status()
print(f"📤 上传到 {upload_url} 返回结果: {response.status_code}")
try:
response_data = response.json()
print(f" 响应内容 (JSON): {json.dumps(response_data, indent=2, ensure_ascii=False)}")
except (json.JSONDecodeError, ValueError):
print(f" 响应内容 (文本): {response.text}")
return True
except requests.exceptions.RequestException as e:
print(f"❌ 文件上传失败 ({os.path.basename(file_path)}): {e}")
if hasattr(e, 'response') and e.response is not None:
print(f" 响应状态码: {e.response.status_code}")
print(f" 响应内容: {e.response.text}")
return False
def verify_upload(self, verify_url: str) -> bool:
"""
验证上传是否成功
Args:
verify_url: 验证URL
Returns:
是否验证成功
"""
try:
response = requests.post(verify_url, headers=self.headers)
response.raise_for_status()
print(f"🔍 验证请求返回状态: {response.status_code}")
try:
response_data = response.json()
print(f" 响应内容 (JSON): {json.dumps(response_data, indent=2, ensure_ascii=False)}")
except (json.JSONDecodeError, ValueError):
print(f" 响应内容 (文本): {response.text}")
return True
except requests.exceptions.RequestException as e:
print(f"❌ 验证上传失败: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f" 验证状态码: {e.response.status_code}")
print(f" 验证响应内容: {e.response.text}")
return False
def upload_multiple_assets(self, project_path: str, release_id: str,
asset_files: List[str], overwrite: bool = True, show_progress: bool = True) -> List[bool]:
"""
上传多个assets
Args:
project_path: 项目路径
release_id: release ID
asset_files: asset文件路径列表
overwrite: 是否覆盖现有文件
show_progress: 是否显示进度条
Returns:
每个文件的上传结果列表
"""
results = []
print(f"\n📦 开始上传 {len(asset_files)} 个文件到release {release_id}...")
# 计算总文件大小用于整体进度显示
total_size = 0
valid_files = []
for file_path in asset_files:
if os.path.exists(file_path):
total_size += os.path.getsize(file_path)
valid_files.append(file_path)
if show_progress and valid_files:
print(f"📊 总计 {len(valid_files)} 个有效文件,总大小: {total_size / 1024 / 1024:.2f} MB")
print("" + "=" * 60)
for i, file_path in enumerate(asset_files, 1):
if not os.path.exists(file_path):
print(f"❌ [{i}/{len(asset_files)}] 跳过不存在的文件: {file_path}")
results.append(False)
continue
file_size = os.path.getsize(file_path)
asset_name = os.path.basename(file_path)
print(f"\n📁 [{i}/{len(asset_files)}] 处理文件: {asset_name}")
print(f" 文件大小: {file_size:,} bytes ({file_size / 1024 / 1024:.2f} MB)")
# 1. 获取上传URL
upload_info = self.get_asset_upload_url(
project_path, release_id, asset_name, file_size, overwrite
)
if not upload_info:
results.append(False)
continue
# 2. 上传文件
upload_success = self.upload_asset(upload_info['upload_url'], file_path, show_progress)
time.sleep(1)
# 3. 验证上传(如果有验证URL)
final_success = upload_success
if upload_success and 'verify_url' in upload_info:
verify_success = self.verify_upload(upload_info['verify_url'])
final_success = verify_success
if verify_success:
print(f"✅ 文件 {asset_name} 上传并验证成功")
else:
print(f"❌ 文件 {asset_name} 上传成功但验证失败")
elif upload_success:
print(f"✅ 文件 {asset_name} 上传成功(无需验证)")
results.append(final_success)
# 避免请求过快
if i < len(asset_files):
time.sleep(1)
return results
def load_config_from_json(json_input: str) -> Dict:
"""
从JSON字符串或文件路径加载配置
Args:
json_input: JSON字符串或JSON文件路径
Returns:
配置字典
"""
try:
# 首先尝试作为JSON字符串解析
config = json.loads(json_input)
print("✅ 从JSON字符串加载配置成功")
return config
except json.JSONDecodeError:
# 如果失败,尝试作为文件路径
try:
if os.path.exists(json_input):
with open(json_input, 'r', encoding='utf-8') as f:
config = json.load(f)
print(f"✅ 从文件 {json_input} 加载配置成功")
return config
else:
raise FileNotFoundError(f"配置文件不存在: {json_input}")
except Exception as e:
raise ValueError(f"无法解析JSON配置: {e}")
def validate_config(config: Dict) -> None:
"""
验证配置的必需字段
Args:
config: 配置字典
Raises:
ValueError: 如果配置无效
"""
required_fields = ['token', 'project_path', 'release_data']
for field in required_fields:
if field not in config:
raise ValueError(f"缺少必需字段: {field}")
# 验证release_data必需字段
release_required = ['tag_name', 'name']
for field in release_required:
if field not in config['release_data']:
raise ValueError(f"release_data缺少必需字段: {field}")
# 验证asset_files
if 'asset_files' in config and not isinstance(config['asset_files'], list):
raise ValueError("asset_files必须是数组")
def main():
parser = argparse.ArgumentParser(description='CNB Release Uploader - JSON配置版本')
parser.add_argument('config', help='JSON配置字符串或JSON配置文件路径')
parser.add_argument('--dry-run', action='store_true', help='只验证配置,不执行上传')
parser.add_argument('--no-progress', action='store_true', help='禁用上传进度条显示')
args = parser.parse_args()
try:
# 加载配置
print("🔧 加载配置...")
config = load_config_from_json(args.config)
# 验证配置
print("🔍 验证配置...")
validate_config(config)
# 打印配置信息
print("\n📋 配置信息:")
print(f" Token: {'*' * 20}")
print(f" 项目路径: {config['project_path']}")
print(f" Release名称: {config['release_data']['name']}")
print(f" Tag名称: {config['release_data']['tag_name']}")
print(f" Asset文件数量: {len(config.get('asset_files', []))}")
if args.dry_run:
print("\n🧪 Dry-run模式,配置验证通过,退出程序")
return 0
# 创建上传器实例
uploader = CNBReleaseUploader(
token=config['token'],
base_url=config.get('base_url', 'https://api.cnb.cool')
)
# 1. 创建release
print("\n🚀 开始创建release...")
release_info = uploader.create_release(config['project_path'], config['release_data'])
if not release_info:
print("❌ 创建release失败,退出程序")
return 1
release_id = release_info.get('id')
if not release_id:
print("❌ 无法获取release ID,退出程序")
return 1
# 2. 上传assets(如果有)
asset_files = config.get('asset_files', [])
if asset_files:
overwrite = config.get('overwrite', True)
show_progress = not args.no_progress # 默认显示进度条,除非指定 --no-progress
results = uploader.upload_multiple_assets(
config['project_path'], release_id, asset_files, overwrite, show_progress
)
# 3. 显示结果
print("\n" + "=" * 50)
print("📊 上传结果汇总:")
print("=" * 50)
success_count = sum(results)
total_count = len(results)
for i, (file_path, success) in enumerate(zip(asset_files, results)):
status = "✅ 成功" if success else "❌ 失败"
print(f" [{i + 1}] {status} - {os.path.basename(file_path)}")
print(f"\n🎉 完成! 成功上传 {success_count}/{total_count} 个文件")
if success_count == total_count:
print("🎊 所有文件都上传成功!")
return 0
elif success_count > 0:
print("⚠️ 部分文件上传成功,请检查失败的文件")
return 2
else:
print("💥 所有文件上传失败,请检查配置和网络")
return 1
else:
print("\n📦 没有指定asset文件,只创建了release")
return 0
except Exception as e:
print(f"❌ 程序执行失败: {e}")
return 1
if __name__ == "__main__":
exit_code = main()
sys.exit(exit_code)
-94
View File
@@ -1,94 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Better Genshin Impact Build Trigger Script
用于触发CNB构建的Python脚本
"""
import requests
import json
import sys
import argparse
def trigger_build(token, branch="main", event="api_trigger_one", runid=None):
"""
触发构建请求
Args:
token (str): 授权token
branch (str): 分支名称,默认为main
event (str): 事件类型,默认为api_trigger_one
runid (str): 运行ID,可选参数
Returns:
dict: API响应结果
"""
url = "https://api.cnb.cool/bettergi/better-genshin-impact/-/build/start"
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Host": "api.cnb.cool",
"Connection": "keep-alive"
}
data = {
"branch": branch,
"event": event
}
# 如果提供了runid,则添加到env中
if runid:
data["env"] = {
"RUN_ID": runid
}
try:
print(f"正在发起构建请求...")
print(f"URL: {url}")
print(f"请求体: {json.dumps(data, indent=2, ensure_ascii=False)}")
response = requests.post(url, headers=headers, json=data)
print(f"响应状态码: {response.status_code}")
if response.status_code == 200:
result = response.json()
print("构建触发成功!")
print(f"响应内容: {json.dumps(result, indent=2, ensure_ascii=False)}")
return result
else:
print(f"请求失败: {response.status_code}")
print(f"错误信息: {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"请求异常: {e}")
return None
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}")
print(f"响应内容: {response.text}")
return None
def main():
parser = argparse.ArgumentParser(description="触发Better Genshin Impact构建")
parser.add_argument("token", help="授权token")
parser.add_argument("--branch", default="main", help="分支名称 (默认: main)")
parser.add_argument("--event", default="api_trigger_one", help="事件类型 (默认: api_trigger_one)")
parser.add_argument("--runid", help="运行ID (可选)")
args = parser.parse_args()
if not args.token:
print("错误: 必须提供token参数")
sys.exit(1)
result = trigger_build(args.token, args.branch, args.event, args.runid)
if result is None:
sys.exit(1)
if __name__ == "__main__":
main()
@@ -1,507 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GitHub Actions 构建物下载和上传脚本
该脚本用于:
1. 从 GitHub Actions 下载最新的构建物 (BetterGI_7z 和 BetterGI_Install)
2. 解压构建物到本地
3. 调用 cnb_release.py 上传文件到 CNB
使用方法:
python github_download_and_cnb_upload.py --cnb-token YOUR_CNB_TOKEN [--github-token YOUR_GITHUB_TOKEN] [--run-id RUN_ID]
参数说明:
--cnb-token: CNB API Token (必需)
--github-token: GitHub Personal Access Token (可选,用于提高API限制)
--run-id: 指定 GitHub Actions 运行 ID (可选,默认获取最新运行)
依赖:
- requests: HTTP 请求库
- tqdm: 进度条显示库
安装依赖:pip install -r requirements.txt
"""
import os
import sys
import json
import requests
import zipfile
import tempfile
import shutil
import re
from pathlib import Path
from typing import List, Dict, Optional
from tqdm import tqdm
# 导入 CNBReleaseUploader
from cnb_release import CNBReleaseUploader
class GitHubActionsDownloader:
def __init__(self, token: Optional[str] = None):
"""
初始化 GitHub Actions 下载器
Args:
token: GitHub Personal Access Token (可选,用于提高API限制)
"""
self.token = token
self.headers = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'BetterGI-Downloader/1.0.0'
}
if token:
self.headers['Authorization'] = f'token {token}'
def get_latest_workflow_run(self, owner: str, repo: str, workflow_file: str) -> Optional[Dict]:
"""
获取最新的工作流运行
Args:
owner: 仓库所有者
repo: 仓库名称
workflow_file: 工作流文件名
Returns:
最新的工作流运行信息或None
"""
url = f'https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_file}/runs'
params = {
'status': 'completed',
'conclusion': 'success',
'per_page': 1
}
try:
response = requests.get(url, headers=self.headers, params=params)
response.raise_for_status()
data = response.json()
runs = data.get('workflow_runs', [])
if not runs:
print("❌ 没有找到成功完成的工作流运行")
return None
latest_run = runs[0]
print(f"✅ 找到最新的工作流运行:")
print(f" Run ID: {latest_run['id']}")
print(f" 创建时间: {latest_run['created_at']}")
print(f" 状态: {latest_run['status']} / {latest_run['conclusion']}")
print(f" 分支: {latest_run['head_branch']}")
return latest_run
except requests.exceptions.RequestException as e:
print(f"❌ 获取工作流运行失败: {e}")
return None
def get_artifacts(self, owner: str, repo: str, run_id: int) -> List[Dict]:
"""
获取指定运行的构建物列表
Args:
owner: 仓库所有者
repo: 仓库名称
run_id: 运行ID
Returns:
构建物列表
"""
url = f'https://api.github.com/repos/{owner}/{repo}/actions/runs/{run_id}/artifacts'
try:
response = requests.get(url, headers=self.headers)
response.raise_for_status()
data = response.json()
artifacts = data.get('artifacts', [])
print(f"📦 找到 {len(artifacts)} 个构建物:")
for artifact in artifacts:
print(f" - {artifact['name']} ({artifact['size_in_bytes']:,} bytes)")
return artifacts
except requests.exceptions.RequestException as e:
print(f"❌ 获取构建物列表失败: {e}")
return []
def download_artifact(self, owner: str, repo: str, artifact_id: int,
artifact_name: str, download_dir: str) -> Optional[str]:
"""
下载指定的构建物
Args:
owner: 仓库所有者
repo: 仓库名称
artifact_id: 构建物ID
artifact_name: 构建物名称
download_dir: 下载目录
Returns:
下载的文件路径或None
"""
url = f'https://api.github.com/repos/{owner}/{repo}/actions/artifacts/{artifact_id}/zip'
try:
print(f"📥 开始下载构建物: {artifact_name}")
response = requests.get(url, headers=self.headers, stream=True)
response.raise_for_status()
# 获取文件总大小
total_size = int(response.headers.get('content-length', 0))
# 保存到临时文件
zip_path = os.path.join(download_dir, f"{artifact_name}.zip")
# 使用 tqdm 创建进度条
chunk_size = 8192
with open(zip_path, 'wb') as f:
with tqdm(
total=total_size,
unit='B',
unit_scale=True,
unit_divisor=1024,
desc=f"下载 {artifact_name}",
ncols=80,
bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]'
) as pbar:
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
pbar.update(len(chunk))
print(f"✅ 下载完成: {zip_path}")
return zip_path
except requests.exceptions.RequestException as e:
print(f"❌ 下载构建物失败 ({artifact_name}): {e}")
return None
def extract_artifact(self, zip_path: str, extract_dir: str) -> List[str]:
"""
解压构建物
Args:
zip_path: ZIP文件路径
extract_dir: 解压目录
Returns:
解压出的文件列表
"""
extracted_files = []
try:
print(f"📂 解压构建物: {os.path.basename(zip_path)}")
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(extract_dir)
extracted_files = [os.path.join(extract_dir, name) for name in zip_ref.namelist()]
print(f"✅ 解压完成,共 {len(extracted_files)} 个文件")
for file_path in extracted_files:
if os.path.isfile(file_path):
size = os.path.getsize(file_path)
print(f" - {os.path.basename(file_path)} ({size:,} bytes)")
return extracted_files
except Exception as e:
print(f"❌ 解压失败: {e}")
return []
def extract_version_from_filename(filename: str) -> Optional[str]:
"""
从文件名中提取版本号
Args:
filename: 文件名
Returns:
版本号或None
"""
# 去除扩展名
import os
filename_without_ext = os.path.splitext(filename)[0]
# 匹配版本号模式,如 v1.2.3, 1.2.3-alpha.1 等
patterns = [
r'v?([0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)',
r'_v?([0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)',
]
for pattern in patterns:
match = re.search(pattern, filename_without_ext)
if match:
return match.group(1)
return None
def create_cnb_config(files: List[str], version: str, token: str) -> Dict:
"""
创建CNB上传配置
Args:
files: 要上传的文件列表
version: 版本号
token: CNB token
Returns:
CNB配置字典
"""
# 判断是否为预发布版本
is_prerelease = '-' in version
make_latest = "false" if is_prerelease else "true"
config = {
"token": token,
"project_path": "bettergi/better-genshin-impact",
"base_url": "https://api.cnb.cool",
"overwrite": True,
"release_data": {
"tag_name": f"v{version}",
"name": f"BetterGI v{version}",
"body": f"BetterGI v{version} 自动发布",
"draft": False,
"prerelease": is_prerelease,
"target_commitish": "main",
"make_latest": make_latest
},
"asset_files": files
}
return config
def main():
import argparse
# 解析命令行参数
parser = argparse.ArgumentParser(description='BetterGI 构建物下载和上传工具')
parser.add_argument('--run-id', type=str, help='指定 GitHub Actions 运行 ID,如果提供则不会获取最新运行')
parser.add_argument('--github-token', type=str, help='GitHub Personal Access Token')
parser.add_argument('--cnb-token', type=str, required=True, help='CNB API Token (必需)')
args = parser.parse_args()
print("🚀 BetterGI 构建物下载和上传工具")
print("=" * 50)
# 获取 token,优先使用命令行参数,其次使用环境变量
github_token = args.github_token or os.getenv('GITHUB_TOKEN')
cnb_token = args.cnb_token or os.getenv('CNB_TOKEN')
if not cnb_token:
print("❌ 错误: 请设置 CNB_TOKEN 环境变量")
return 1
if not github_token:
print("⚠️ 警告: 未设置 GITHUB_TOKEN,可能会遇到API限制")
# 确定运行 ID
if args.run_id:
print(f"\n🎯 使用指定的运行 ID: {args.run_id}")
run_id = args.run_id
else:
# 创建下载器来获取最新运行 ID
downloader = GitHubActionsDownloader(github_token)
print("\n🔍 查找最新的工作流运行...")
latest_run = downloader.get_latest_workflow_run('babalae', 'better-genshin-impact', 'publish.yml')
if not latest_run:
return 1
run_id = str(latest_run['id'])
# 使用当前目录下的固定目录,以action运行ID命名
work_dir = os.path.join(os.getcwd(), 'github_actions_cache', run_id)
download_dir = os.path.join(work_dir, 'downloads')
extract_dir = os.path.join(work_dir, 'extracted')
print(f"\n📁 使用工作目录: {work_dir}")
# 检查是否已存在解压后的文件
all_files = []
version = None
# 检查解压目录是否已存在且包含文件
if os.path.exists(extract_dir):
print("🔍 检查已存在的构建物...")
existing_files = []
# 预期的构建物名称
expected_artifacts = ['BetterGI_7z', 'BetterGI_Install']
for artifact_name in expected_artifacts:
artifact_extract_dir = os.path.join(extract_dir, artifact_name)
if os.path.exists(artifact_extract_dir):
for root, dirs, files in os.walk(artifact_extract_dir):
for file in files:
file_path = os.path.join(root, file)
existing_files.append(file_path)
# 尝试从文件名提取版本号
if not version:
filename = os.path.basename(file_path)
extracted_version = extract_version_from_filename(filename)
if extracted_version:
version = extracted_version
if existing_files and version:
print(f"✅ 发现已存在的构建物 ({len(existing_files)} 个文件),跳过下载")
print(f"📋 检测到版本号: {version}")
all_files = existing_files
else:
print("⚠️ 已存在目录但未找到有效文件,将重新下载")
# 如果没有找到已存在的文件,则进行下载和解压
if not all_files:
print("📥 需要下载构建物,正在获取构建物信息...")
# 如果还没有创建下载器,现在创建
if 'downloader' not in locals():
downloader = GitHubActionsDownloader(github_token)
# 获取构建物列表
print("\n📦 获取构建物列表...")
artifacts = downloader.get_artifacts('babalae', 'better-genshin-impact', int(run_id))
if not artifacts:
return 1
# 筛选需要的构建物
target_artifacts = []
for artifact in artifacts:
if artifact['name'] in ['BetterGI_7z', 'BetterGI_Install']:
target_artifacts.append(artifact)
if len(target_artifacts) != 2:
print(f"❌ 错误: 期望找到2个构建物,实际找到 {len(target_artifacts)} 个")
return 1
print("📥 开始下载和解压构建物...")
os.makedirs(download_dir, exist_ok=True)
os.makedirs(extract_dir, exist_ok=True)
for artifact in target_artifacts:
# 下载
zip_path = downloader.download_artifact(
'babalae', 'better-genshin-impact',
artifact['id'], artifact['name'], download_dir
)
if not zip_path:
continue
# 解压
artifact_extract_dir = os.path.join(extract_dir, artifact['name'])
os.makedirs(artifact_extract_dir, exist_ok=True)
extracted_files = downloader.extract_artifact(zip_path, artifact_extract_dir)
# 收集文件并提取版本号
for file_path in extracted_files:
if os.path.isfile(file_path):
all_files.append(file_path)
# 尝试从文件名提取版本号
if not version:
filename = os.path.basename(file_path)
extracted_version = extract_version_from_filename(filename)
if extracted_version:
version = extracted_version
print(f"📋 检测到版本号: {version}")
if not all_files:
print("❌ 错误: 没有找到可上传的文件")
return 1
if not version:
print("❌ 错误: 无法从文件名中提取版本号")
return 1
print(f"\n📋 准备上传 {len(all_files)} 个文件:")
for file_path in all_files:
size = os.path.getsize(file_path)
print(f" - {os.path.basename(file_path)} ({size:,} bytes)")
# 创建CNB配置
print("\n⚙️ 创建CNB配置...")
cnb_config = create_cnb_config(all_files, version, cnb_token)
# 保存配置文件
config_path = os.path.join(work_dir, 'cnb_config.json')
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(cnb_config, f, indent=2, ensure_ascii=False)
print(f"✅ 配置文件已保存: {config_path}")
# 直接调用 CNBReleaseUploader
print("\n🚀 开始上传到CNB...")
try:
# 创建 CNBReleaseUploader 实例
uploader = CNBReleaseUploader(
token=cnb_config['token'],
base_url=cnb_config.get('base_url', 'https://api.cnb.cool')
)
# 创建 release
print(f"📝 创建 release: {cnb_config['release_data']['name']}")
release_result = uploader.create_release(
project_path=cnb_config['project_path'],
release_data=cnb_config['release_data']
)
if not release_result:
print("❌ 创建 release 失败")
return 1
print(f"✅ Release 创建成功: {release_result['name']}")
# 上传文件
print(f"📤 开始上传 {len(cnb_config['asset_files'])} 个文件...")
upload_results = uploader.upload_multiple_assets(
project_path=cnb_config['project_path'],
release_id=release_result['id'],
asset_files=cnb_config['asset_files'],
overwrite=cnb_config.get('overwrite', True)
)
# 检查上传结果
success_count = sum(1 for result in upload_results if result)
total_count = len(upload_results)
print(f"\n📊 上传结果汇总:")
print(f" ✅ 成功: {success_count}/{total_count}")
if success_count < total_count:
print(f" ❌ 失败: {total_count - success_count}/{total_count}")
for i, result in enumerate(upload_results):
if not result:
file_name = os.path.basename(cnb_config['asset_files'][i])
print(f" - {file_name}: 上传失败")
if success_count == total_count:
print("\n🎉 所有文件上传完成!")
return 0
else:
print("\n❌ 部分文件上传失败")
return 1
except Exception as e:
print(f"❌ CNB上传失败: {e}")
return 1
if __name__ == '__main__':
try:
exit_code = main()
sys.exit(exit_code)
except KeyboardInterrupt:
print("\n⚠️ 用户中断操作")
sys.exit(1)
except Exception as e:
print(f"\n💥 程序异常: {e}")
sys.exit(1)
@@ -1,19 +0,0 @@
name: mirrorchyan_release_note
on:
workflow_dispatch:
release:
types: [edited, released]
jobs:
mirrorchyan_release_note:
runs-on: macos-latest
steps:
- id: uploading
uses: MirrorChyan/release-note-action@v1
with:
mirrorchyan_rid: BGI
upload_token: ${{ secrets.MirrorChyanUploadToken }}
github_token: ${{ secrets.GITHUB_TOKEN }}
@@ -1,88 +0,0 @@
name: mirrorchyan_uploading
on:
workflow_dispatch:
release:
types: [released]
jobs:
mirrorchyan:
runs-on: windows-latest
steps:
- name: 📥 Download release
uses: robinraju/[email protected]
with:
latest: true
fileName: "*"
- name: 📥 Download kachina-builder release
uses: robinraju/[email protected]
with:
repository: "YuehaiTeam/kachina-installer"
latest: true
fileName: "kachina-builder.exe"
- name: Embed Dotnet and VCRedist
shell: bash
run: |
# dotnet
VERSION_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/8.0/latest.version"
VERSION=$(curl -fsSL "$VERSION_URL" | tr -d '\r\n')
if [ -z "$VERSION" ]; then
echo "Cannot get the latest version from $VERSION_URL"
exit 1
fi
INSTALLER_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/${VERSION}/windowsdesktop-runtime-${VERSION}-win-x64.exe"
OUTPUT="windowsdesktop-runtime-${VERSION}-win-x64.exe"
echo "Downloading Windows Desktop Runtime version $VERSION from $INSTALLER_URL"
curl -fSL -o "$OUTPUT" "$INSTALLER_URL"
# vcredist
echo "Downloading VCRedist"
curl -fSL -o "vc_redist.x64.exe" "https://aka.ms/vs/17/release/vc_redist.x64.exe"
# embed
echo "Embedding runtimes"
./kachina-builder.exe append -o ./BetterGI.Install.*.exe -f "$OUTPUT" -n "Microsoft.DotNet.DesktopRuntime.8" -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
./kachina-builder.exe extract -i ./BetterGI.Install.*.exe -f ./metadata.json -n "\0META"
- name: Extract 7z and create zip
shell: bash
run: |
7z a -tzip BetterGI.Install.zip ./BetterGI.Install.*.exe -mx=1 -r -y
choco install wget --no-progress
7z x BetterGI_v*.7z -oun7z
mv ./metadata.json ./un7z/BetterGI/.metadata.json
cd un7z
7z a -tzip ../BetterGI.zip ./BetterGI -mx=5 -r -y
- name: Determine version number
id: get-version
shell: bash
run: |
if [ "${{ github.event_name }}" = "release" ]; then
echo "version=${{ github.event.release.tag_name }}" >> $GITHUB_OUTPUT
else
LATEST_TAG=$(curl -s -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
https://api.github.com/repos/${{ github.repository }}/releases/latest \
| jq -r '.tag_name')
echo "version=$LATEST_TAG" >> $GITHUB_OUTPUT
fi
- name: Upload Zip
uses: MirrorChyan/uploading-action@v1
with:
filetype: local
mirrorchyan_rid: BGI
filename: "BetterGI.zip"
version_name: ${{ steps.get-version.outputs.version }}
upload_token: ${{ secrets.MirrorChyanUploadToken }}
os: win
arch: x64
- name: Upload Exe
uses: MirrorChyan/uploading-action@v1
with:
filetype: local
mirrorchyan_rid: BGI
filename: "BetterGI.Install.zip"
version_name: ${{ steps.get-version.outputs.version }}
upload_token: ${{ secrets.MirrorChyanUploadToken }}
-596
View File
@@ -1,596 +0,0 @@
name: BetterGI Publish
run-name: "BetterGI ${{ inputs.version }}"
on:
workflow_dispatch:
inputs:
version:
description: 'BetterGI Version (eg: 0.35.1, 0.36.5-alpha.1)'
required: true
type: string
kachina-channel:
type: choice
description: 'Kachina Installer Channel'
required: true
default: 'release'
options:
- release
- dev
create-release:
type: boolean
description: '创建 GitHub Release 草稿'
required: true
default: false
upload-to-steambird:
type: boolean
description: '上传到 Steambird'
required: true
default: false
jobs:
# Add validation job to check version format
validate:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.set-version.outputs.version }}
steps:
- name: Set version from input or tag
id: set-version
run: |
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
# Validate manual input version format
if ! [[ "${{ github.event.inputs.version }}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then
echo "❌ 错误:版本格式必须符合语义化版本规范 (例如: 1.2.3, 1.2.3-alpha, 1.2.3+build.123)"
exit 1
fi
echo "version=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT
echo "✨ 手动触发构建,版本号:${{ github.event.inputs.version }}"
else
# Extract version from tag name (remove 'v' prefix)
VERSION=${GITHUB_REF#refs/tags/v}
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "🏷️ 从 tag 触发构建,版本号:${VERSION}"
fi
build_web_map_editor:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
repository: huiyadanli/bettergi-map
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm install
- run: npm run build:single
- uses: actions/upload-artifact@v4
with:
name: web_map_editor
path: dist/
build_web_scripts_list:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
repository: huiyadanli/bettergi-scripts-web
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm install
- run: npm run build:single
- uses: actions/upload-artifact@v4
with:
name: web_scripts_list
path: dist/
build_dist:
runs-on: windows-latest
needs: [validate, build_web_map_editor, build_web_scripts_list]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.x
- name: 更新 csproj 文件版本号
run: |
$version = '${{ needs.validate.outputs.version }}'
(Get-Content BetterGenshinImpact/BetterGenshinImpact.csproj) -replace '<Version>.*</Version>', "<Version>$version</Version>" | Set-Content BetterGenshinImpact/BetterGenshinImpact.csproj
- name: 自动提交更改
if: github.repository_owner == 'babalae'
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "Update version to ${{ needs.validate.outputs.version }}"
branch: main
file_pattern: BetterGenshinImpact/BetterGenshinImpact.csproj
- name: Cache NuGet packages
uses: actions/cache@v4
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/BetterGenshinImpact.csproj') }}
restore-keys: |
${{ runner.os }}-nuget-
- name: 🛠️ Build application
run: dotnet publish BetterGenshinImpact/BetterGenshinImpact.csproj -c Release -p:PublishProfile=FolderProfile -p:Version=${{ needs.validate.outputs.version }}
continue-on-error: true
- name: 🧹 Clear & Move Files
run: |
$sourceDir = ".\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64"
Get-ChildItem -Path $sourceDir -Recurse -Filter "*.lib" | Remove-Item -Force
Get-ChildItem -Path $sourceDir -Recurse -Filter "*ffmpeg*.dll" | Remove-Item -Force
Get-ChildItem -Path $sourceDir -Recurse -Filter "*.pdb" | Remove-Item -Force
New-Item -Path "dist/BetterGI" -ItemType Directory
xcopy "$sourceDir\*" ".\dist\BetterGI\" /E /H /I /Y
# 下载前面构建好的web内容
- uses: actions/download-artifact@v4
with:
name: web_map_editor
path: dist/BetterGI/Assets/Map/Editor
- uses: actions/download-artifact@v4
with:
name: web_scripts_list
path: dist/BetterGI/Assets/Web/ScriptRepo
# 下载构建 repo 的内容补充数据
- uses: actions/checkout@v4
with:
repository: babalae/bettergi-publish
path: publish
# - name: 🗜️ Extract Map
# run: |
# cd publish
# # Extract zst files
# Get-ChildItem -Filter *.zst | ForEach-Object {
# if ($_.PSIsContainer -eq $false) {
# $file = $_.Name
# $output_file = "..\dist\BetterGI\Assets\Map\$($file -replace '.zst$', '')"
# & zstd -d $file -o $output_file
# Write-Host "$file -> $output_file"
# }
# }
# # Extract zip files
# Get-ChildItem -Filter *.zip | ForEach-Object {
# if ($_.PSIsContainer -eq $false) {
# $file = $_.FullName
# $destination = "..\dist\BetterGI\Assets\Map"
# Expand-Archive -Path $file -DestinationPath $destination -Force
# Write-Host "$file -> $destination"
# }
# }
# 生成更新器
- name: 📥 Download kachina-builder release
if: ${{ github.event.inputs.kachina-channel == 'release' }}
uses: robinraju/[email protected]
with:
repository: "YuehaiTeam/kachina-installer"
latest: true
fileName: "kachina-builder.exe"
- name: 📥 Download kachina-builder dev
if: ${{ github.event.inputs.kachina-channel == 'dev' }}
uses: dawidd6/action-download-artifact@v8
with:
github_token: ${{secrets.GITHUB_TOKEN}}
repo: "YuehaiTeam/kachina-installer"
workflow: "build.yml"
name: artifact
branch: main
event: push
workflow_conclusion: success
- name: 📦 Gen Updater by kachina-builder
run: |
cd dist
..\kachina-builder.exe pack -c ..\Build\kachina.config.json -o BetterGI/BetterGI.update.exe
# 打包上传
- name: 📦 Generate archive
run: |
cd dist
7z a "BetterGI_v${{ needs.validate.outputs.version }}.7z" BetterGI -t7z -mx=5 -mf=BCJ2 -r -y
- uses: actions/upload-artifact@v4
with:
name: BetterGI_7z
path: dist/BetterGI_*.7z
build_installer:
runs-on: windows-latest
needs: [validate, build_dist]
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: BetterGI_7z
path: dist
- name: Unpack BetterGI_*.7z
run: |
cd dist
7z x "BetterGI_v${{ needs.validate.outputs.version }}.7z"
- name: 📥 Download kachina-builder release
if: ${{ github.event.inputs.kachina-channel == 'release' }}
uses: robinraju/[email protected]
with:
repository: "YuehaiTeam/kachina-installer"
latest: true
fileName: "kachina-builder.exe"
- name: 📥 Download kachina-builder dev
if: ${{ github.event.inputs.kachina-channel == 'dev' }}
uses: dawidd6/action-download-artifact@v8
with:
github_token: ${{secrets.GITHUB_TOKEN}}
repo: "YuehaiTeam/kachina-installer"
workflow: "build.yml"
name: artifact
branch: main
event: push
workflow_conclusion: success
- name: 📥 Download last release
uses: robinraju/[email protected]
with:
repository: "babalae/better-genshin-impact"
latest: true
fileName: "BetterGI_v*.7z"
out-file-path: 'last'
- name: 📥 Get 2nd and 3rd release
id: release_tags
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
$releasesUrl = "https://api.github.com/repos/babalae/better-genshin-impact/releases"
$headers = @{
"Authorization" = "Bearer $env:GITHUB_TOKEN"
"Accept" = "application/vnd.github.v3+json"
}
$releases = Invoke-RestMethod -Uri $releasesUrl -Headers $headers -Method Get
$validReleases = $releases |
Where-Object { -not $_.draft -and -not $_.prerelease } |
Sort-Object { [DateTime]$_.published_at } -Descending
if ($validReleases.Count -lt 3) {
Write-Error "至少需要 3 个正式 Release(当前找到 $($validReleases.Count) 个)"
exit 1
}
"second_release_tag=$($validReleases[1].tag_name)" | Out-File -FilePath $env:GITHUB_OUTPUT -Append
"third_release_tag=$($validReleases[2].tag_name)" | Out-File -FilePath $env:GITHUB_OUTPUT -Append
- name: 📥 Download 2nd last release
uses: robinraju/[email protected]
with:
repository: "babalae/better-genshin-impact"
tag: ${{ steps.release_tags.outputs.second_release_tag }}
fileName: "BetterGI_v*.7z"
out-file-path: '2nd'
- name: 📥 Download 3rd last release
uses: robinraju/[email protected]
with:
repository: "babalae/better-genshin-impact"
tag: ${{ steps.release_tags.outputs.third_release_tag }}
fileName: "BetterGI_v*.7z"
out-file-path: '3rd'
- name: Unpack releases
run: |
cd last
7z x "BetterGI*.7z" -otemp
if (Test-Path -Path ".\temp\BetterGI" -PathType Container) {
Move-Item -Path ".\temp\BetterGI" -Destination ".\BetterGI"
} else {
Rename-Item -Path ".\temp" -NewName ".\BetterGI"
}
cd ..
cd 2nd
7z x "BetterGI*.7z" -otemp
if (Test-Path -Path ".\temp\BetterGI" -PathType Container) {
Move-Item -Path ".\temp\BetterGI" -Destination ".\BetterGI"
} else {
Rename-Item -Path ".\temp" -NewName ".\BetterGI"
}
cd ..
cd 3rd
7z x "BetterGI*.7z" -otemp
if (Test-Path -Path ".\temp\BetterGI" -PathType Container) {
Move-Item -Path ".\temp\BetterGI" -Destination ".\BetterGI"
} else {
Rename-Item -Path ".\temp" -NewName ".\BetterGI"
}
cd ..
ls .\last
ls .\2nd
ls .\3rd
- name: 📦 Pack kachina-builder
run: |
cd dist
..\kachina-builder.exe gen -j 6 -i BetterGI -m metadata.json -o hashed -r babalae/bettergi -t ${{ needs.validate.outputs.version }} --diff-vers ..\last\BetterGI --diff-vers ..\2nd\BetterGI --diff-vers ..\3rd\BetterGI --diff-ignore *[.txt,.onnx] -u .\BetterGI\BetterGI.update.exe
..\kachina-builder.exe pack -c ../Build/kachina.config.json -m metadata.json -d hashed -o BetterGI.Install.${{ needs.validate.outputs.version }}.exe
- uses: actions/upload-artifact@v4
with:
name: BetterGI_Install
path: dist/BetterGI.Install.*.exe
- uses: actions/upload-artifact@v4
with:
name: BetterGI_OnlineInst
path: dist/BetterGI/BetterGI.update.exe
build_setup:
runs-on: windows-latest
needs: [validate, build_dist]
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: BetterGI_7z
path: dist
- name: Unpack BetterGI_*.7z & Repack
run: |
cd dist
7z x "BetterGI_v${{ needs.validate.outputs.version }}.7z"
cd BetterGI
7z a -t7z "..\..\publish.7z" *
- name: 📥 Download MicaSetup
uses: robinraju/[email protected]
with:
repository: "lemutec/MicaSetup"
latest: true
fileName: "MicaSetup_v*.7z"
- name: 📦 Pack MicaSetup
run: |
$archiveFiles = Get-ChildItem -Path . -Filter "MicaSetup_v*.7z"
foreach ($archive in $archiveFiles) {
& 7z x $archive.FullName
}
Copy-Item -Path "Build\micasetup.json" -Destination "."
Copy-Item -Path "Build\micasetup" -Destination "." -Recurse -Force
.\makemica.exe micasetup.json
ren BetterGI_Setup.exe BetterGI_Setup_v${{ needs.validate.outputs.version }}.exe
- uses: actions/upload-artifact@v4
with:
name: BetterGI_Setup
path: BetterGI_Setup*.exe
# 创建 GitHub Release
create_release:
if: github.event.inputs.create-release == 'true'
needs: [validate, build_dist, build_installer]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@v4
with:
path: artifacts
- name: Create Release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ needs.validate.outputs.version }}
name: BetterGI v${{ needs.validate.outputs.version }}
draft: true
prerelease: ${{ contains(needs.validate.outputs.version, '-') }}
fail_on_unmatched_files: true
files: |
artifacts/BetterGI_7z/*.7z
artifacts/BetterGI_Install/*.exe
mirrorchyan_uploading:
if: github.repository_owner == 'babalae' && contains(needs.validate.outputs.version, '-')
needs: [validate, build_dist, build_installer]
runs-on: windows-latest
steps:
- uses: actions/download-artifact@v4
with:
path: downloads
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: 📥 Download kachina-builder release
if: ${{ github.event.inputs.kachina-channel == 'release' }}
uses: robinraju/[email protected]
with:
repository: "YuehaiTeam/kachina-installer"
latest: true
fileName: "kachina-builder.exe"
- name: 📥 Download kachina-builder dev
if: ${{ github.event.inputs.kachina-channel == 'dev' }}
uses: dawidd6/action-download-artifact@v8
with:
github_token: ${{secrets.GITHUB_TOKEN}}
repo: "YuehaiTeam/kachina-installer"
workflow: "build.yml"
name: artifact
branch: main
event: push
workflow_conclusion: success
- name: Embed Dotnet and VCRedist
shell: bash
run: |
# dotnet
VERSION_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/8.0/latest.version"
VERSION=$(curl -fsSL "$VERSION_URL" | tr -d '\r\n')
if [ -z "$VERSION" ]; then
echo "Cannot get the latest version from $VERSION_URL"
exit 1
fi
INSTALLER_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/${VERSION}/windowsdesktop-runtime-${VERSION}-win-x64.exe"
OUTPUT="windowsdesktop-runtime-${VERSION}-win-x64.exe"
echo "Downloading Windows Desktop Runtime version $VERSION from $INSTALLER_URL"
curl -fSL -o "$OUTPUT" "$INSTALLER_URL"
# vcredist
echo "Downloading VCRedist"
curl -fSL -o "vc_redist.x64.exe" "https://aka.ms/vs/17/release/vc_redist.x64.exe"
# embed
echo "Embedding runtimes"
./kachina-builder.exe append -o ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f "$OUTPUT" -n "Microsoft.DotNet.DesktopRuntime.8" -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
./kachina-builder.exe extract -i ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f ./metadata.json -n "\0META"
- name: Extract 7z and create zip
shell: bash
run: |
choco install wget --no-progress
7z a -tzip BetterGI.Install.${{ needs.validate.outputs.version }}.zip ./downloads/BetterGI_Install/BetterGI.Install.${{ needs.validate.outputs.version }}.exe -mx=1 -r -y
cd downloads/BetterGI_7z
7z x BetterGI_v*.7z -oun7z
mv ../../metadata.json ./un7z/BetterGI/.metadata.json
cd un7z
7z a -tzip ../BetterGI.zip ./BetterGI -mx=5 -r -y
- name: Upload Zip
uses: MirrorChyan/uploading-action@v1
with:
filetype: local
mirrorchyan_rid: BGI
filename: "downloads/BetterGI_7z/BetterGI.zip"
version_name: ${{ needs.validate.outputs.version }}
upload_token: ${{ secrets.MirrorChyanUploadToken }}
os: win
arch: x64
- name: Upload Install.exe
uses: MirrorChyan/uploading-action@v1
with:
filetype: local
mirrorchyan_rid: BGI
filename: "BetterGI.Install.${{ needs.validate.outputs.version }}.zip"
version_name: ${{ needs.validate.outputs.version }}
upload_token: ${{ secrets.MirrorChyanUploadToken }}
cnb_uploading:
if: github.repository_owner == 'babalae' && false
needs: [validate, build_dist, build_installer]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r .github/workflows/requirements.txt
- uses: actions/download-artifact@v4
with:
path: artifacts
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Prepare files for upload
run: |
mkdir -p upload_files
# 只复制 7z 文件和 Install.exe 文件
find artifacts -name "*.7z" -exec cp {} upload_files/ \;
find artifacts -name "BetterGI.Install.*.exe" -exec cp {} upload_files/ \;
echo "📦 准备上传的文件:"
ls -la upload_files/
- name: Copy CNB uploader script
run: |
# 复制 CNB 上传脚本到当前目录
cp .github/workflows/cnb_release.py ./cnb_release.py
- name: Upload to CNB
env:
CNB_TOKEN: ${{ secrets.CNB_TOKEN }}
VERSION: ${{ needs.validate.outputs.version }}
run: |
# 生成文件列表数组
FILE_LIST=""
for file in upload_files/*; do
if [ -f "$file" ]; then
if [ -n "$FILE_LIST" ]; then
FILE_LIST="$FILE_LIST,"
fi
FILE_LIST="$FILE_LIST\"$file\""
fi
done
# 判断是否为预发布版本
if [[ "$VERSION" == *"-"* ]]; then
IS_PRERELEASE="true"
MAKE_LATEST="false"
else
IS_PRERELEASE="false"
MAKE_LATEST="true"
fi
# 创建 JSON 配置
cat > cnb_config.json << EOF
{
"token": "$CNB_TOKEN",
"project_path": "bettergi/better-genshin-impact",
"base_url": "https://api.cnb.cool",
"overwrite": true,
"release_data": {
"tag_name": "v$VERSION",
"name": "BetterGI v$VERSION",
"body": "BetterGI v$VERSION 自动发布",
"draft": false,
"prerelease": $IS_PRERELEASE,
"target_commitish": "main",
"make_latest": "$MAKE_LATEST"
},
"asset_files": [
$FILE_LIST
]
}
EOF
# 检查配置文件内容
echo "📋 CNB 配置内容:"
cat cnb_config.json
# 验证 JSON 格式
python -c "import json; print('✅ JSON 格式验证通过'); json.load(open('cnb_config.json'))"
# 执行上传
python cnb_release.py cnb_config.json
cnb_trigger:
if: github.repository_owner == 'babalae'
needs: [validate, build_dist, build_installer]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r .github/workflows/requirements.txt
- name: Trigger CNB Build
env:
CNB_TOKEN: ${{ secrets.CNB_TOKEN }}
run: |
python .github/workflows/cnb_trigger.py "$CNB_TOKEN" --runid ${{ github.run_id }}
upload_to_steambird:
if: ${{ inputs.upload-to-steambird && github.repository_owner == 'babalae' }}
needs: [validate, build_dist, build_installer]
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
with:
path: artifacts
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Prepare files for upload
run: |
mkdir -p upload_files
# 只复制 7z 文件和 Install.exe 文件
find artifacts -name "*.7z" -exec cp {} upload_files/ \;
find artifacts -name "BetterGI.Install.*.exe" -exec cp {} upload_files/ \;
echo "📦 准备上传的文件:"
ls -la upload_files/
- name: Upload to Steambird
env:
TUS_USER: "bgi"
TUS_PASS: ${{ secrets.TUS_PASS }}
run: |
wget https://uploads.steambird.pub/upload.sh
chmod +x upload.sh
./upload.sh https://uploads.steambird.pub/dav/bgi/ upload_files/BetterGI.Install.*.exe
-3
View File
@@ -1,3 +0,0 @@
# CNB Release Uploader 依赖
requests>=2.25.0
tqdm>=4.60.0
+1 -6
View File
@@ -24,14 +24,9 @@ bld/
Tmp/
/packages/
node_modules/
github_actions_cache/
*.zip
# Rider
.idea
.trae
.claude
CLAUDE.md
__pycache__/
_ReSharper.Caches/
+3 -3
View File
@@ -1,3 +1,3 @@
[submodule "Test/BetterGenshinImpact.UnitTest/Assets"]
path = Test/BetterGenshinImpact.UnitTest/Assets
url = https://github.com/huiyadanli/BetterGI.UnitTest.Assets.git
[submodule "BetterGenshinImpact/Script"]
path = BetterGenshinImpact/Script
url = https://github.com/babalae/bettergi-scripts.git
@@ -0,0 +1,19 @@
<Project Sdk="MSTest.Sdk/3.6.4">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UseVSTest>true</UseVSTest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BetterGenshinImpact.CombatScript\BetterGenshinImpact.CombatScript.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,52 @@
namespace BetterGenshinImpact.CombatScript.Test;
[TestClass]
public sealed class ScriptEmitTest
{
[TestMethod]
public void TestEmit()
{
ScriptUnit scriptUnit = new(
[
new CommentSymbol("测试注释"),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("钟离"), [new SpaceTriviaSymbol()], new(
[
new WalkSymbol(WalkDirection.Backward, [new DoubleSymbol(0.1)], [], new CommaTriviaSymbol()),
new SkillSymbol(true, [new HoldSymbol()], [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new WaitSymbol([new DoubleSymbol(0.3)], [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new WalkSymbol(WalkDirection.Forward, [new DoubleSymbol(0.1)], [new SpaceTriviaSymbol()], default),
])),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("芙宁娜"), [new SpaceTriviaSymbol()], new(
[
new SkillSymbol(true, [], new CommaTriviaSymbol()),
new BurstSymbol(true, [new SpaceTriviaSymbol()], default)
])),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("行秋"), [new SpaceTriviaSymbol()], new(
[
new SkillSymbol(true, [], new CommaTriviaSymbol()),
new BurstSymbol(true, [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new SkillSymbol(true, [new SpaceTriviaSymbol()], default),
])),
]);
Console.WriteLine(scriptUnit.Emit(new SymbolEmitter()));
}
[TestMethod]
public void TestParse()
{
ReadOnlySpan<char> raw = """
// 测试注释
钟离 s(0.1),e(hold),wait(0.3),w(0.1)
芙宁娜 e,q
行秋 e,q,e
""";
ScriptUnit scriptUnit = SymbolParser.Parse(raw);
Console.WriteLine(scriptUnit.Emit(new SymbolEmitter()));
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class AttackSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public AttackSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("attack", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public AttackSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("attack", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,24 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class AvatarInstructionListSymbol : BaseSymbol
{
public AvatarInstructionListSymbol(AvatarSymbol avatar, ImmutableArray<TriviaSymbol> triviaList, InstructionListSymbol instructionList)
{
Avatar = avatar;
TriviaList = triviaList;
InstructionList = instructionList;
}
public AvatarSymbol Avatar { get; }
public ImmutableArray<TriviaSymbol> TriviaList { get; }
public InstructionListSymbol InstructionList { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Avatar).Append(TriviaList).Append(InstructionList);
}
}
@@ -0,0 +1,16 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class AvatarSymbol : BaseSymbol
{
public AvatarSymbol(string name)
{
Name = name;
}
public string Name { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Name);
}
}
@@ -0,0 +1,6 @@
namespace BetterGenshinImpact.CombatScript;
public abstract class BaseSymbol : ISymbol
{
public abstract void Emit(ISymbolEmitter emitter);
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@@ -0,0 +1,25 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class BurstSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public BurstSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("burst", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0]);
IsAlias = isAlias;
}
public BurstSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("burst", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "q";
public bool IsAlias { get; }
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class ChargeSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public ChargeSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("charge", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public ChargeSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("charge", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,17 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class CommaTriviaSymbol : TriviaSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(',');
}
}
public sealed class SemicolonTriviaSymbol : TriviaSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(';');
}
}
@@ -0,0 +1,16 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class CommentSymbol : TriviaSymbol
{
public CommentSymbol(string comment)
{
Comment = comment;
}
public string Comment { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append("//").Append(Comment);
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class DashSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public DashSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("dash", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public DashSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("dash", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,16 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class DoubleSymbol : BaseSymbol, IParameterSymbol
{
public DoubleSymbol(double value)
{
Value = value;
}
public double Value { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Value);
}
}
@@ -0,0 +1,9 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class HoldSymbol : BaseSymbol, IParameterSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append("hold");
}
}
@@ -0,0 +1,8 @@
namespace BetterGenshinImpact.CombatScript;
public interface IInstructionSymbolHasAlias
{
public string AliasName { get; }
public bool IsAlias { get; }
}
@@ -0,0 +1,10 @@
using System;
namespace BetterGenshinImpact.CombatScript;
public interface IInstructionSymbolHasDuration
{
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,5 @@
namespace BetterGenshinImpact.CombatScript;
public interface IParameterSymbol : ISymbol
{
}
@@ -0,0 +1,6 @@
namespace BetterGenshinImpact.CombatScript;
public interface ISymbol
{
void Emit(ISymbolEmitter emitter);
}
@@ -0,0 +1,14 @@
namespace BetterGenshinImpact.CombatScript;
public interface ISymbolEmitter
{
string Emit();
ISymbolEmitter Append(char value);
ISymbolEmitter Append(char value, int repeatCount);
ISymbolEmitter Append(double value);
ISymbolEmitter Append(string value);
}
@@ -0,0 +1,18 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class InstructionListSymbol : BaseSymbol
{
public InstructionListSymbol(ImmutableArray<InstructionSymbol> instructions)
{
Instructions = instructions;
}
public ImmutableArray<InstructionSymbol> Instructions { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Instructions);
}
}
@@ -0,0 +1,59 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public abstract class InstructionSymbol : BaseSymbol
{
protected InstructionSymbol(string name, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
Name = name;
HasParameterList = false;
LeadingTriviaList = leadingTriviaList;
TailingTrivia = tailingTrivia;
}
protected InstructionSymbol(string name, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
Name = name;
HasParameterList = true;
ParameterList = parameterList;
LeadingTriviaList = leadingTriviaList;
TailingTrivia = tailingTrivia;
}
public string Name { get; }
public bool HasParameterList { get; }
public ImmutableArray<IParameterSymbol> ParameterList { get; }
public ImmutableArray<TriviaSymbol> LeadingTriviaList { get; }
public TriviaSymbol? TailingTrivia { get; set; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(LeadingTriviaList);
if (this is IInstructionSymbolHasAlias {IsAlias: true } hasAlias)
{
emitter.Append(hasAlias.AliasName);
}
else
{
emitter.Append(Name);
}
if (HasParameterList)
{
emitter.Append('(');
emitter.Append(ParameterList);
emitter.Append(')');
}
if (TailingTrivia is not null)
{
emitter.Append(TailingTrivia);
}
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Frozen;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public static class InstructionThrowHelper
{
public static void ThrowIfParameterListIsDefault(ImmutableArray<IParameterSymbol> parameterList)
{
if (parameterList.IsDefault)
{
throw new ArgumentException($"Parameter list can not be default.");
}
}
public static void ThrowIfParameterListCountNotCorrect(ImmutableArray<IParameterSymbol> parameterList, FrozenSet<int> allowedCounts)
{
if (!allowedCounts.Contains(parameterList.Length))
{
throw new ArgumentException($"Instruction parameter count not correct.");
}
}
public static void ThrowIfParameterAtIndexIsNot<T>(ImmutableArray<IParameterSymbol> parameterList, int index, out T symbol)
where T : IParameterSymbol
{
if (parameterList.Length <= index || parameterList[index] is not T result)
{
throw new ArgumentException($"Instruction's parameter at index {index} must be a {typeof(T).Name}.");
}
symbol = result;
}
}
@@ -0,0 +1,25 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class JumpSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public JumpSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("jump", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0]);
IsAlias = isAlias;
}
public JumpSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("jump", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "j";
public bool IsAlias { get; }
}
@@ -0,0 +1,28 @@
using System;
namespace BetterGenshinImpact.CombatScript;
public class LineBreakTriviaSymbol : TriviaSymbol
{
private readonly string lineBreak;
public LineBreakTriviaSymbol()
{
lineBreak = Environment.NewLine;
}
public LineBreakTriviaSymbol(string lineBreak)
{
if (lineBreak is not ("\r\n" or "\n" or "\r" or ";"))
{
throw new ArgumentException("Invalid line break.");
}
this.lineBreak = lineBreak;
}
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(lineBreak);
}
}
@@ -0,0 +1,23 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class ScriptUnit
{
public ScriptUnit(ImmutableArray<ISymbol> symbols)
{
Symbols = symbols;
}
public ImmutableArray<ISymbol> Symbols { get; }
public string Emit(ISymbolEmitter emitter)
{
foreach (ref readonly ISymbol symbol in Symbols.AsSpan())
{
symbol.Emit(emitter);
}
return emitter.Emit();
}
}
@@ -0,0 +1,30 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class SkillSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public SkillSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("skill", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out HoldSymbol _);
}
IsAlias = isAlias;
}
public SkillSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("skill", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "e";
public bool IsAlias { get; }
}
@@ -0,0 +1,21 @@
namespace BetterGenshinImpact.CombatScript;
public class SpaceTriviaSymbol : TriviaSymbol
{
private readonly int count;
public SpaceTriviaSymbol()
{
count = 1;
}
public SpaceTriviaSymbol(int count)
{
this.count = count;
}
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(' ', count);
}
}
@@ -0,0 +1,37 @@
using System.Text;
namespace BetterGenshinImpact.CombatScript;
public sealed class SymbolEmitter : ISymbolEmitter
{
private readonly StringBuilder builder = new();
public string Emit()
{
return builder.ToString();
}
public ISymbolEmitter Append(char value)
{
builder.Append(value);
return this;
}
public ISymbolEmitter Append(char value, int repeatCount)
{
builder.Append(value, repeatCount);
return this;
}
public ISymbolEmitter Append(double value)
{
builder.Append(value);
return this;
}
public ISymbolEmitter Append(string value)
{
builder.Append(value);
return this;
}
}
@@ -0,0 +1,23 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public static class SymbolEmitterExtensions
{
public static ISymbolEmitter Append(this ISymbolEmitter emitter, ISymbol symbol)
{
symbol.Emit(emitter);
return emitter;
}
public static ISymbolEmitter Append<TSymbol>(this ISymbolEmitter emitter, ImmutableArray<TSymbol> symbolList)
where TSymbol : ISymbol
{
foreach(ref readonly TSymbol symbol in symbolList.AsSpan())
{
symbol.Emit(emitter);
}
return emitter;
}
}
@@ -0,0 +1,193 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
namespace BetterGenshinImpact.CombatScript;
public static class SymbolParser
{
public static ScriptUnit Parse(ReadOnlySpan<char> raw)
{
ImmutableArray<ISymbol>.Builder symbols = ImmutableArray.CreateBuilder<ISymbol>();
ParseLines(raw, symbols);
return new(symbols.ToImmutable());
}
private static void ParseLines(ReadOnlySpan<char> raw, ImmutableArray<ISymbol>.Builder symbols)
{
bool skipNextRange = false;
ref readonly char end = ref raw[^1];
foreach(Range range in raw.SplitAny(['\r', '\n', ';']))
{
if (skipNextRange)
{
skipNextRange = false;
continue;
}
int offset = range.End.GetOffset(raw.Length);
if (offset >= raw.Length)
{
break;
}
ref readonly char peek = ref raw[offset];
LineBreakTriviaSymbol lineBreakTrivia;
if (peek is '\r')
{
if (Unsafe.IsAddressLessThan(in peek, in end) && Unsafe.Add(ref Unsafe.AsRef(in peek), 1) is '\n')
{
// It's a CRLF
lineBreakTrivia = new("\r\n");
skipNextRange = true;
}
else
{
// It's a CR
lineBreakTrivia = new("\r");
}
}
else if (peek is '\n')
{
// It's a LF
lineBreakTrivia = new("\n");
}
else if (peek is ';')
{
lineBreakTrivia = new(";");
}
else
{
throw new InvalidOperationException($"Failed to parse line break trivia at {range}.");
}
if (ParseLine(raw[range]) is { } symbol)
{
symbols.Add(symbol);
}
symbols.Add(lineBreakTrivia);
}
}
private static ISymbol? ParseLine(ReadOnlySpan<char> raw)
{
if (raw.IsEmpty)
{
return default;
}
if (raw.StartsWith("//"))
{
return new CommentSymbol(raw[2..].ToString());
}
int indexOfSpace = raw.IndexOf(' ');
ReadOnlySpan<char> avatarIdentifier = raw[..indexOfSpace];
AvatarSymbol avatarSymbol = new(avatarIdentifier.ToString());
ImmutableArray<TriviaSymbol> triviaList = ParseTriviaList(raw[indexOfSpace..], out int advanced);
InstructionListSymbol listSymbol = ParseInstructionList(raw[(indexOfSpace + advanced)..]);
return new AvatarInstructionListSymbol(avatarSymbol, triviaList, listSymbol);
}
private static InstructionListSymbol ParseInstructionList(ReadOnlySpan<char> raw)
{
ImmutableArray<InstructionSymbol>.Builder builder = ImmutableArray.CreateBuilder<InstructionSymbol>();
foreach (Range range in raw.Split(','))
{
ReadOnlySpan<char> current = raw[range];
ImmutableArray<TriviaSymbol> leadingTriviaList = ParseTriviaList(current, out int advanced);
if (ParseInstruction(current[advanced..], leadingTriviaList) is { } symbol)
{
builder.Add(symbol);
}
}
return new(builder.ToImmutable());
}
private static InstructionSymbol? ParseInstruction(ReadOnlySpan<char> raw, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
if (raw.IsEmpty)
{
return default;
}
switch (raw[0])
{
// attack|a
case 'a':
break;
// burst
case 'b':
return new BurstSymbol(false, [], leadingTriviaList, tailingTrivia);
break;
// charge
case 'c':
break;
// dash|d
case 'd':
break;
// jump|j
case 'j':
break;
// q
case 'q':
return new BurstSymbol(true, [], leadingTriviaList, tailingTrivia);
break;
// skill|s
case 's':
break;
// wait|walk|w
case 'w':
break;
}
return default;
}
// Handle ','&' '
private static ImmutableArray<TriviaSymbol> ParseTriviaList(ReadOnlySpan<char> raw, out int advanced)
{
advanced = 0;
if (raw.IsEmpty)
{
return ImmutableArray<TriviaSymbol>.Empty;
}
ImmutableArray<TriviaSymbol>.Builder builder = ImmutableArray.CreateBuilder<TriviaSymbol>();
int spaceCount = 0;
foreach (ref readonly char value in raw)
{
advanced++;
if (value is ' ')
{
spaceCount++;
}
else
{
if (spaceCount is not 0)
{
builder.Add(new SpaceTriviaSymbol(spaceCount));
spaceCount = 0;
}
if (value is ',')
{
builder.Add(new CommaTriviaSymbol());
}
else
{
break;
}
}
}
return builder.ToImmutable();
}
}
@@ -0,0 +1,5 @@
namespace BetterGenshinImpact.CombatScript;
public abstract class TriviaSymbol : BaseSymbol
{
}
@@ -0,0 +1,23 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class WaitSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public WaitSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("wait", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [1]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,9 @@
namespace BetterGenshinImpact.CombatScript;
public enum WalkDirection
{
Forward,
Backward,
Left,
Right
}
@@ -0,0 +1,70 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class WalkSymbol : InstructionSymbol, IInstructionSymbolHasAlias, IInstructionSymbolHasDuration, IParameterSymbol
{
public WalkSymbol(WalkDirection direction, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [1]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
Direction = direction;
IsAlias = true;
}
// Used for parameter
public WalkSymbol(WalkDirection direction, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", leadingTriviaList, tailingTrivia)
{
Direction = direction;
IsAlias = true;
}
public WalkSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [2]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out WalkSymbol directionAlias);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 1, out DoubleSymbol doubleSymbol);
Direction = directionAlias.Direction;
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
IsAlias = false;
}
public string AliasName
{
get
{
return Direction switch
{
WalkDirection.Forward => "w",
WalkDirection.Backward => "s",
WalkDirection.Left => "a",
WalkDirection.Right => "d",
_ => throw new ArgumentOutOfRangeException(),
};
}
}
public bool IsAlias { get; }
public WalkDirection Direction { get; }
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
File renamed without changes.
@@ -6,7 +6,6 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
@@ -14,7 +13,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\BetterGenshinImpact\BetterGenshinImpact.csproj" />
<ProjectReference Include="..\BetterGenshinImpact\BetterGenshinImpact.csproj" />
</ItemGroup>
</Project>
@@ -7,33 +7,34 @@ namespace BetterGenshinImpact.Test.Dataset;
public class AvatarClassifyGen
{
// 基础图像文件夹
private const string BaseDir = @"E:\HuiTask\更好的原神\侧面头像\源数据\AvatarIcon";
// 产出文件夹
private const string OutputDir = @"E:\HuiTask\更好的原神\侧面头像\dateset";
private const string BaseDir = @"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\分类器\";
// 背景图像文件夹
private static readonly string BackgroundDir = @"E:\HuiTask\更好的原神\侧面头像\background";
private static readonly string BackgroundDir = Path.Combine(BaseDir, "background");
private static readonly Random Rd = new Random();
public static readonly List<string> ImgNames = ["UI_AvatarIcon_Side_Aino.png","UI_AvatarIcon_Side_Flins.png", "UI_AvatarIcon_Side_Nefer.png", "UI_AvatarIcon_Side_Nefer.png", "UI_AvatarIcon_Side_Lauma.png"];
public static void GenAll()
{
// 读取基础图像
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
// 只用一个图像
List<string> sideImageFiles = [];
foreach (string imgName in ImgNames)
{
sideImageFiles.Add(Path.Combine(BaseDir, imgName));
}
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_HutaoCostumeWinter.png", SearchOption.TopDirectoryOnly).ToList();
List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Iansan.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles2);
List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Citlali.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles3);
List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Lanyan.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles4);
List<string> sideImageFiles5 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_XianglingCostumeWinter.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles5);
List<string> sideImageFiles6 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Mavuika.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles6);
// 生成训练集
GenTo(sideImageFiles, Path.Combine(OutputDir, @"dateset\train"), 200);
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\train"), 200);
// 生成测试集
GenTo(sideImageFiles, Path.Combine(OutputDir, @"dateset\test"), 40);
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\test"), 40);
// GenTo(new List<string> { sideImageFiles[1] }, Path.Combine(BaseDir, @"dateset\test"), 1);
}
@@ -71,14 +72,11 @@ public class AvatarClassifyGen
for (int i = 0; i < count; i++)
{
// 随机挑选一张背景图像
string backgroundImageFile = Path.Combine(BackgroundDir,
Directory.GetFiles(BackgroundDir, "*.png")[
Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
string backgroundImageFile = Path.Combine(BackgroundDir, Directory.GetFiles(BackgroundDir, "*.png")[Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
// 从背景图像中随机取一块 128x128 的区域
Mat backgroundImage = Cv2.ImRead(backgroundImageFile, ImreadModes.Color);
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128),
new Random().Next(backgroundImage.Height - 128), 128, 128);
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128), new Random().Next(backgroundImage.Height - 128), 128, 128);
Mat backgroundImageRegion = backgroundImage[backgroundRect];
// 随机平移、缩放保留区域
@@ -95,11 +93,9 @@ public class AvatarClassifyGen
// Cv2.ImShow("resizedSideImage", resizedSideImage);
var resizedMaskImage = new Mat();
// Cv2.Threshold(alphaChannel, alphaChannel, 200, 255, ThresholdTypes.Otsu);
Cv2.Resize(~alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0,
InterpolationFlags.Cubic);
Cv2.Resize(255 - alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
var resizedAlphaChannel = new Mat();
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0,
InterpolationFlags.Cubic);
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
// Cv2.ImShow("resizedMaskImage", resizedMaskImage);
// generatedImage[transformedRect] = resizedSideImage;
@@ -116,8 +112,7 @@ public class AvatarClassifyGen
int offsetY = Rd.Next(-ySpace, 0);
Debug.WriteLine($"{sideImageFileName} 缩放{scale}大于1 偏移 ({offsetX},{offsetY})");
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX,
(resizedSideImage.Height - 128) + offsetY, 128, 128);
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX, (resizedSideImage.Height - 128) + offsetY, 128, 128);
// result = new Mat();
// Cv2.BitwiseAnd(backgroundImageRegionClone, backgroundImageRegionClone, result, resizedMaskImage[roi]);
result = Mul(backgroundImageRegionClone, resizedAlphaChannel[roi]);
@@ -131,8 +126,7 @@ public class AvatarClassifyGen
int offsetY = Rd.Next(-ySpace, 0);
Debug.WriteLine($"{sideImageFileName} 缩放{scale}小于等于1 偏移 ({offsetX},{offsetY})");
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX,
(128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX, (128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
var res = new Mat();
// Cv2.BitwiseAnd(backgroundImageRegionClone[roi], backgroundImageRegionClone[roi], res, resizedMaskImage);
res = Mul(backgroundImageRegionClone[roi], resizedAlphaChannel);
@@ -152,12 +146,11 @@ public class AvatarClassifyGen
var channels = background.Split();
for (int i = 0; i < 3; i++)
{
Cv2.Multiply(channels[i], ~ alphaChannel, channels[i], 1 / 255.0);
Cv2.Multiply(channels[i], 255 - alphaChannel, channels[i], 1 / 255.0);
}
Mat result = new Mat();
Cv2.Merge(channels[..3], result);
return result;
}
}
}
}
@@ -7,35 +7,42 @@ namespace BetterGenshinImpact.Test.Dataset;
public class AvatarClassifyTransparentGen
{
// 基础图像文件夹
private const string BaseDir = @"E:\HuiTask\更好的原神\侧面头像\源数据\AvatarIcon";
// 产出文件夹
private const string OutputDir = @"E:\HuiTask\更好的原神\侧面头像\dateset";
private const string BaseDir = @"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\分类器\";
// 背景图像文件夹
private static readonly string BackgroundDir = @"E:\HuiTask\更好的原神\侧面头像\background";
private static readonly string BackgroundDir = Path.Combine(BaseDir, "background");
private static readonly Random Rd = new Random();
// 在类的开头添加一个新的常量
private const string SideSrcDir = "side_src";
private const string SideSrcTransportDir = "side_src_transport";
public static void GenAll()
{
List<string> sideImageFiles = [];
List<string> imgNames = AvatarClassifyGen.ImgNames;
foreach (string imgName in imgNames)
{
sideImageFiles.Add(Path.Combine(BaseDir, imgName));
}
var newList = AdjustTransparency(sideImageFiles, 0.5f);
// 调整透明度(可选,取消注释以启用)
AdjustTransparency(0.5f);
// 读取基础图像
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "*.png", SearchOption.TopDirectoryOnly).ToList();
// 只用一个图像
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "UI_AvatarIcon_Side_HutaoCostumeWinter.png", SearchOption.TopDirectoryOnly).ToList();
List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "UI_AvatarIcon_Side_Iansan.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles2);
List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "UI_AvatarIcon_Side_Citlali.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles3);
List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "UI_AvatarIcon_Side_Lanyan.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles4);
List<string> sideImageFiles5 = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "UI_AvatarIcon_Side_XianglingCostumeWinter.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles5);
List<string> sideImageFiles6 = Directory.GetFiles(Path.Combine(BaseDir, SideSrcTransportDir), "UI_AvatarIcon_Side_Mavuika.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles6);
// 生成训练集
GenTo(newList, Path.Combine(OutputDir, @"dateset\train"), 200);
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\train"), 200);
// 生成测试集
GenTo(newList, Path.Combine(OutputDir, @"dateset\test"), 40);
// GenTo(new List<string> { newList[1] }, Path.Combine(BaseDir, @"dateset\test"), 1);
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\test"), 40);
// GenTo(new List<string> { sideImageFiles[1] }, Path.Combine(BaseDir, @"dateset\test"), 1);
}
static void GenTo(List<string> sideImageFiles, string dataFolder, int count)
@@ -72,14 +79,11 @@ public class AvatarClassifyTransparentGen
for (int i = 0; i < count; i++)
{
// 随机挑选一张背景图像
string backgroundImageFile = Path.Combine(BackgroundDir,
Directory.GetFiles(BackgroundDir, "*.png")[
Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
string backgroundImageFile = Path.Combine(BackgroundDir, Directory.GetFiles(BackgroundDir, "*.png")[Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
// 从背景图像中随机取一块 128x128 的区域
Mat backgroundImage = Cv2.ImRead(backgroundImageFile, ImreadModes.Color);
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128),
new Random().Next(backgroundImage.Height - 128), 128, 128);
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128), new Random().Next(backgroundImage.Height - 128), 128, 128);
Mat backgroundImageRegion = backgroundImage[backgroundRect];
// 随机平移、缩放保留区域
@@ -96,11 +100,9 @@ public class AvatarClassifyTransparentGen
// Cv2.ImShow("resizedSideImage", resizedSideImage);
var resizedMaskImage = new Mat();
// Cv2.Threshold(alphaChannel, alphaChannel, 200, 255, ThresholdTypes.Otsu);
Cv2.Resize(~ alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0,
InterpolationFlags.Cubic);
Cv2.Resize(255 - alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
var resizedAlphaChannel = new Mat();
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0,
InterpolationFlags.Cubic);
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
// Cv2.ImShow("resizedMaskImage", resizedMaskImage);
// generatedImage[transformedRect] = resizedSideImage;
@@ -117,8 +119,7 @@ public class AvatarClassifyTransparentGen
int offsetY = Rd.Next(-ySpace, 0);
Debug.WriteLine($"{sideImageFileName} 缩放{scale}大于1 偏移 ({offsetX},{offsetY})");
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX,
(resizedSideImage.Height - 128) + offsetY, 128, 128);
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX, (resizedSideImage.Height - 128) + offsetY, 128, 128);
// result = new Mat();
// Cv2.BitwiseAnd(backgroundImageRegionClone, backgroundImageRegionClone, result, resizedMaskImage[roi]);
result = Mul(backgroundImageRegionClone, resizedAlphaChannel[roi]);
@@ -132,8 +133,7 @@ public class AvatarClassifyTransparentGen
int offsetY = Rd.Next(-ySpace, 0);
Debug.WriteLine($"{sideImageFileName} 缩放{scale}小于等于1 偏移 ({offsetX},{offsetY})");
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX,
(128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX, (128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
var res = new Mat();
// Cv2.BitwiseAnd(backgroundImageRegionClone[roi], backgroundImageRegionClone[roi], res, resizedMaskImage);
res = Mul(backgroundImageRegionClone[roi], resizedAlphaChannel);
@@ -153,9 +153,8 @@ public class AvatarClassifyTransparentGen
var channels = background.Split();
for (int i = 0; i < 3; i++)
{
Cv2.Multiply(channels[i], ~ alphaChannel, channels[i], 1 / 255.0);
Cv2.Multiply(channels[i], 255 - alphaChannel, channels[i], 1 / 255.0);
}
Mat result = new Mat();
Cv2.Merge(channels[..3], result);
return result;
@@ -163,19 +162,19 @@ public class AvatarClassifyTransparentGen
}
// 在类中添加以下新方法
public static List<string> AdjustTransparency(List<string> sideImageFiles, float targetAlpha = 0.5f)
public static void AdjustTransparency(float targetAlpha = 0.5f)
{
List<string> newSideImageFiles = [];
string sourcePath = Path.Combine(BaseDir, SideSrcDir);
string destinationPath = Path.Combine(BaseDir, SideSrcTransportDir);
string destinationPath = Path.Combine(OutputDir, SideSrcTransportDir);
Directory.CreateDirectory(destinationPath);
List<string> sideImageFiles = Directory.GetFiles(sourcePath, "*.png", SearchOption.TopDirectoryOnly).ToList();
foreach (string sideImageFile in sideImageFiles)
{
string fileName = Path.GetFileName(sideImageFile);
string destFile = Path.Combine(destinationPath, fileName);
newSideImageFiles.Add(destFile);
Mat image = Cv2.ImRead(sideImageFile, ImreadModes.Unchanged);
Mat[] channels = Cv2.Split(image);
@@ -198,6 +197,5 @@ public class AvatarClassifyTransparentGen
}
Console.WriteLine($"已完成透明度调整,结果保存在 {destinationPath}");
return newSideImageFiles;
}
}
}
@@ -0,0 +1,33 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
using System.IO;
namespace BetterGenshinImpact.Test.Simple.AllMap;
public class FeatureTransfer
{
private static string rootPath = Global.Absolute(@"User\Map\");
public static void Transfer()
{
var kp = LoadKeyPointArrayOld();
if (kp != null)
{
string kpPath = Path.Combine(rootPath, $"mainMap2048Block_SIFT.kp");
FileStorage fs = new(kpPath, FileStorage.Modes.Write);
fs.Write("kp", kp);
fs.Release();
}
}
public static KeyPoint[]? LoadKeyPointArrayOld()
{
string kpPath = Path.Combine(rootPath, "mainMap2048Block_SIFT.kp.old");
if (File.Exists(kpPath))
{
return ObjectUtils.Deserialize(File.ReadAllBytes(kpPath)) as KeyPoint[];
}
return null;
}
}
@@ -281,10 +281,10 @@ public class KeyPointMatchTest
writer.Write(image.Rows);
writer.Write(image.Cols);
int depth = image.Depth();
MatType type = image.Type();
int type = image.Type();
int channels = image.Channels();
writer.Write(depth);
writer.Write(type.Value);
writer.Write(type);
writer.Write(channels);
int sizeInBytes = (int)image.Step() * image.Rows;
writer.Write(sizeInBytes);
@@ -1,71 +1,16 @@
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using OpenCvSharp;
using OpenCvSharp.Features2D;
using OpenCvSharp.Internal.Vectors;
namespace BetterGenshinImpact.Test.Simple.AllMap;
/// <summary>
/// 运行完毕MapPuzzle就来运行这个
/// 每次地图更新都需要
/// </summary>
public class LargeSiftExtractor
{
private const int BLOCK_SIZE = 1024;
private const int OVERLAP_SIZE = BLOCK_SIZE * 3;
private readonly Feature2D _sift = SIFT.Create();
public static void Gen1024()
{
var rootPath = @"E:\HuiTask\更好的原神\地图匹配\拼图结果\6.0";
var mainMap2048BlockMat = new Mat($@"{rootPath}\map_2048.png", ImreadModes.Color);
// 缩小 2048/1024 = 2
var targetFilePath = $@"{rootPath}\1024_map.png";
// opencv 缩小
var mainMap1024BlockMat =
mainMap2048BlockMat.Resize(new Size(mainMap2048BlockMat.Width / 2, mainMap2048BlockMat.Height / 2));
// 转化为灰度图
mainMap1024BlockMat.SaveImage(targetFilePath);
Debug.WriteLine("done!");
}
public static void Gen256Sift()
{
Environment.SetEnvironmentVariable("OPENCV_IO_MAX_IMAGE_PIXELS", Math.Pow(2, 40).ToString("F0"));
var rootPath = @"E:\HuiTask\更好的原神\地图匹配\拼图结果\6.0";
// 缩小 2048/256 = 8
var targetFilePath = $@"{rootPath}\Teyvat_0_256.png";
if (!File.Exists(targetFilePath))
{
var mainMap2048BlockMat = new Mat($@"{rootPath}\map_2048.png", ImreadModes.Color);
// opencv 缩小
var mainMap256BlockMat =
mainMap2048BlockMat.Resize(new Size(mainMap2048BlockMat.Width / 8, mainMap2048BlockMat.Height / 8));
// 转化为灰度图
mainMap256BlockMat = mainMap256BlockMat.CvtColor(ColorConversionCodes.BGR2GRAY);
mainMap256BlockMat.SaveImage(targetFilePath);
}
FeatureMatcher featureMatcher = new(new Mat(targetFilePath, ImreadModes.Grayscale),
new FeatureStorage("Teyvat_0_256", rootPath));
Debug.WriteLine("done!");
}
public static void GenLargeSift()
{
Environment.SetEnvironmentVariable("OPENCV_IO_MAX_IMAGE_PIXELS", Math.Pow(2, 40).ToString("F0"));
var extractor = new LargeSiftExtractor();
extractor.ExtractAndSaveSift(@"E:\HuiTask\更好的原神\地图匹配\拼图结果\6.0\map_2048.png",
@"E:\HuiTask\更好的原神\地图匹配\拼图结果\6.0\");
}
public void ExtractAndSaveSift(string imagePath, string outputPath)
{
@@ -148,7 +93,7 @@ public class LargeSiftExtractor
// 找出中心区域关键点的索引
var centralKeypointIndices = new List<int>();
var centralKeypoints = new List<KeyPoint>();
for (int i = 0; i < kps.Length; i++)
{
if (kps[i].Pt.X >= BLOCK_SIZE && kps[i].Pt.X < BLOCK_SIZE * 2 &&
@@ -191,38 +136,15 @@ public class LargeSiftExtractor
}
}
// private void SaveFeaturesOld(List<KeyPoint> keypoints, Mat descriptors, string outputPath)
// {
// Debug.WriteLine($"保存 {keypoints.Count} 个关键点和描述符到 {outputPath}");
// using var fs1 = new FileStorage(Path.Combine(outputPath, "mainMap2048Block_SIFT.kp"), FileStorage.Modes.Write);
// fs1.Write("kp", keypoints.ToArray());
// fs1.Release();
// using var fs2 = new FileStorage(Path.Combine(outputPath, "mainMap2048Block_SIFT.mat"), FileStorage.Modes.Write);
// fs2.Write("desc", descriptors);
// fs2.Release();
// Debug.WriteLine("特征保存成功。");
// }
private void SaveFeatures(List<KeyPoint> keypoints, Mat descriptors, string outputPath)
{
Debug.WriteLine($"保存 {keypoints.Count} 个关键点和描述符到 {outputPath}");
SaveKeyPointArray2(keypoints.ToArray(), Path.Combine(outputPath, "Teyvat_0_2048_SIFT.kp.bin"));
SaveDescMat2(descriptors, Path.Combine(outputPath, "Teyvat_0_2048_SIFT.mat.png"));
using var fs1 = new FileStorage(Path.Combine(outputPath, "mainMap2048Block_SIFT.kp"), FileStorage.Modes.Write);
fs1.Write("kp", keypoints.ToArray());
fs1.Release();
using var fs2 = new FileStorage(Path.Combine(outputPath, "mainMap2048Block_SIFT.mat"), FileStorage.Modes.Write);
fs2.Write("desc", descriptors);
fs2.Release();
Debug.WriteLine("特征保存成功。");
}
public static void SaveDescMat2(Mat descMat, string outputPath)
{
descMat.SaveImage(outputPath);
}
public static unsafe void SaveKeyPointArray2(KeyPoint[] kpArray, string outputPath)
{
var kpVector = new VectorOfKeyPoint(kpArray);
var sizeOfKeyPoint = Marshal.SizeOf<KeyPoint>();
var kpSpan = new ReadOnlySpan<byte>((byte*)kpVector.ElemPtr, kpArray.Length * sizeOfKeyPoint);
using var fs = new FileStream(outputPath, FileMode.Create);
fs.Write(kpSpan);
}
}
@@ -27,27 +27,24 @@ public class MapPuzzle
public static void PutAll()
{
var folder = @"E:\HuiTask\更好的原神\地图匹配\拼图结果\6.0";
Directory.CreateDirectory(folder);
// 保存2048大图
var img2048 = Put(2048);
Cv2.ImWrite(@$"{folder}\map_2048.png", img2048);
// var img2048 = Put(2048);
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_2048.png", img2048);
// 保存1024
var img1024 = Put(1024);
Cv2.ImWrite(@$"{folder}\map_1024.png", img1024);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_1024.png", img1024);
// 保存256
var grayImage = new Mat();
Cv2.CvtColor(img2048.Resize(new Size(img2048.Width / 8, img2048.Height / 8), 0, 0, InterpolationFlags.Cubic), grayImage, ColorConversionCodes.BGR2GRAY);
Cv2.ImWrite(@$"{folder}\Teyvat_0_256.png", grayImage);
// var grayImage = new Mat();
// Cv2.CvtColor(img1024.Resize(new Size(img1024.Width / 4, img1024.Height / 4), 0, 0, InterpolationFlags.Cubic), grayImage, ColorConversionCodes.BGR2GRAY);
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_256.png", grayImage);
}
public static Mat Put(int block = 2048)
{
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\地图块素材\UI_Map_最新"; // 图片文件夹路径
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\UI_Map_5.2"; // 图片文件夹路径
string pattern = @"UI_MapBack_([-+]?\d+)_([-+]?\d+)(.*)";
var images = Directory.GetFiles(folderPath, "*.png", SearchOption.TopDirectoryOnly); // 获取所有图片文件路径
@@ -6,7 +6,6 @@ using System.Diagnostics;
using System.IO;
using System.Text.Json;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
namespace BetterGenshinImpact.Test.Simple.AllMap;
@@ -17,15 +16,15 @@ public class MapTeleportPointDraw
// var pList = LoadTeleportPoint(@"E:\HuiTask\更好的原神\地图匹配\地图点位\5.0");
// pList.AddRange(MapAssets.Instance.TpPositions);
var map = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\mainMap1024BlockColor.png");
DrawTeleportPoint(map, MapLazyAssets.Instance.ScenesDic[MapTypes.Teyvat.ToString()].Points);
DrawTeleportPoint(map, MapLazyAssets.Instance.TpPositions);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\传送点_1024_0.34.3.png", map);
}
public static void DrawTeleportPoint(Mat map, List<GiTpPosition> points)
public static void DrawTeleportPoint(Mat map, List<GiWorldPosition> points)
{
foreach (var point in points)
{
var p = TeyvatMapCoordinate.GameToMain1024(point.Position);
var p = MapCoordinate.GameToMain1024(point.Position);
Cv2.Circle(map, p, 4, Scalar.Red, 2);
// 写文字
Cv2.PutText(map, $"[{point.X:F2},{point.Y:F2}]", new Point(p.X + 10, p.Y + 5), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
@@ -61,7 +61,7 @@ internal class HsvTestWindow
Cv2.CreateTrackbar("High S", _windowDetectionName, ref _highS, MaxValue, on_high_S_thresh_trackbar);
Cv2.CreateTrackbar("Low V", _windowDetectionName, ref _lowV, MaxValue, on_low_V_thresh_trackbar);
Cv2.CreateTrackbar("High V", _windowDetectionName, ref _highV, MaxValue, on_high_V_thresh_trackbar);
var frame = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\Q识别\拼图\2.png", ImreadModes.Color);
var frame = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\bsz1.png", ImreadModes.Color);
Mat frameHsv = new Mat();
// Convert from BGR to HSV colorspace
Cv2.CvtColor(frame, frameHsv, ColorConversionCodes.BGR2HSV);
@@ -282,7 +282,7 @@ public class CharacterOrientationTest
if (contours.Length > 0)
{
Rect maxRect = default;
var maxRect = Rect.Empty;
var maxIndex = 0;
for (int i = 0; i < contours.Length; i++)
{
@@ -0,0 +1,37 @@
using System.Diagnostics;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using OpenCvSharp;
namespace BetterGenshinImpact.Test.Simple;
public class OcrTest
{
public static void TestYap()
{
Mat mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png", ImreadModes.Grayscale);
var text = TextInferenceFactory.Pick.Inference(PreProcessForInference(mat));
Debug.WriteLine(text);
Mat mat2 = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png", ImreadModes.Grayscale);
var text2 = OcrFactory.Paddle.Ocr(mat2);
Debug.WriteLine(text2);
}
private static Mat PreProcessForInference(Mat mat)
{
// Yap 已经改用灰度图了 https://github.com/Alex-Beng/Yap/commit/c2ad1e7b1442aaf2d80782a032e00876cd1c6c84
// 二值化
// Cv2.Threshold(mat, mat, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
//Cv2.AdaptiveThreshold(mat, mat, 255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary, 31, 3); // 效果不错 但是和模型不搭
//mat = OpenCvCommonHelper.Threshold(mat, Scalar.FromRgb(235, 235, 235), Scalar.FromRgb(255, 255, 255)); // 识别物品不太行
// 不知道为什么要强制拉伸到 221x32
mat = ResizeHelper.ResizeTo(mat, 221, 32);
// 填充到 384x32
var padded = new Mat(new Size(384, 32), MatType.CV_8UC1, Scalar.Black);
padded[new Rect(0, 0, mat.Width, mat.Height)] = mat;
//Cv2.ImWrite(Global.Absolute("padded.png"), padded);
return padded;
}
}
+49 -19
View File
@@ -9,13 +9,19 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.GameCapture", "Fi
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.HotkeyCapture", "Fischless.HotkeyCapture\Fischless.HotkeyCapture.csproj", "{08152E44-2564-46C5-B5B2-54DD43C01A79}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Test", "Test\BetterGenshinImpact.Test\BetterGenshinImpact.Test.csproj", "{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Deploy", "Deploy", "{458E1106-43A4-47E6-B11B-D243035D4C76}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicaSetup", "Build\MicaSetup\MicaSetup.csproj", "{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicaSetup.Uninst", "Build\MicaSetup\MicaSetup.Uninst.csproj", "{673344BC-B860-44AE-AD88-D33465BDE25B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Test", "BetterGenshinImpact.Test\BetterGenshinImpact.Test.csproj", "{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.WindowsInput", "Fischless.WindowsInput\Fischless.WindowsInput.csproj", "{9D00BC7A-9280-4AC9-8951-4502EDB71B76}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.CombatScript", "BetterGenshinImpact.CombatScript\BetterGenshinImpact.CombatScript.csproj", "{57C278F9-F62A-480A-B929-B0E5D8174194}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.UnitTest", "Test\BetterGenshinImpact.UnitTest\BetterGenshinImpact.UnitTest.csproj", "{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.CombatScript.Test", "BetterGenshinImpact.CombatScript.Test\BetterGenshinImpact.CombatScript.Test.csproj", "{09427DA8-665E-441A-A576-C11FBC6F9E5C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -49,14 +55,30 @@ Global
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|Any CPU.Build.0 = Release|x64
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|x64.ActiveCfg = Release|x64
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|x64.Build.0 = Release|x64
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|x64.ActiveCfg = Debug|x64
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|x64.Build.0 = Debug|x64
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Release|Any CPU.Build.0 = Release|Any CPU
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Release|x64.ActiveCfg = Release|x64
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Release|x64.Build.0 = Release|x64
{673344BC-B860-44AE-AD88-D33465BDE25B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{673344BC-B860-44AE-AD88-D33465BDE25B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{673344BC-B860-44AE-AD88-D33465BDE25B}.Debug|x64.ActiveCfg = Debug|x64
{673344BC-B860-44AE-AD88-D33465BDE25B}.Debug|x64.Build.0 = Debug|x64
{673344BC-B860-44AE-AD88-D33465BDE25B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{673344BC-B860-44AE-AD88-D33465BDE25B}.Release|Any CPU.Build.0 = Release|Any CPU
{673344BC-B860-44AE-AD88-D33465BDE25B}.Release|x64.ActiveCfg = Release|x64
{673344BC-B860-44AE-AD88-D33465BDE25B}.Release|x64.Build.0 = Release|x64
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|x64.ActiveCfg = Debug|x64
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|x64.Build.0 = Debug|x64
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|Any CPU.ActiveCfg = Release|x64
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|Any CPU.Build.0 = Release|x64
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|x64.ActiveCfg = Release|x64
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|x64.Build.0 = Release|x64
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|x64.ActiveCfg = Debug|Any CPU
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|x64.Build.0 = Debug|Any CPU
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|Any CPU.Build.0 = Release|Any CPU
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|x64.ActiveCfg = Release|Any CPU
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|x64.Build.0 = Release|Any CPU
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Debug|Any CPU.ActiveCfg = Debug|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Debug|Any CPU.Build.0 = Debug|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Debug|x64.ActiveCfg = Debug|x64
@@ -65,21 +87,29 @@ Global
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|Any CPU.Build.0 = Release|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.ActiveCfg = Release|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.Build.0 = Release|x64
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Debug|x64.ActiveCfg = Debug|x64
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Debug|x64.Build.0 = Debug|x64
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|Any CPU.ActiveCfg = Release|x64
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|Any CPU.Build.0 = Release|x64
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|x64.ActiveCfg = Release|x64
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|x64.Build.0 = Release|x64
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|Any CPU.Build.0 = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|x64.ActiveCfg = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|x64.Build.0 = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|Any CPU.ActiveCfg = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|Any CPU.Build.0 = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|x64.ActiveCfg = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|x64.Build.0 = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|x64.ActiveCfg = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|x64.Build.0 = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|Any CPU.Build.0 = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|x64.ActiveCfg = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE} = {02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98} = {02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15} = {458E1106-43A4-47E6-B11B-D243035D4C76}
{673344BC-B860-44AE-AD88-D33465BDE25B} = {458E1106-43A4-47E6-B11B-D243035D4C76}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {352D8B78-9DE3-4E58-985F-FADD22594DB4}
-7
View File
@@ -1,7 +0,0 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=chyan/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=enkanomiya/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=mirrorchan/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=onslaugh/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=serenitea/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=steambird/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
+2 -13
View File
@@ -1,7 +1,6 @@
<Application x:Class="BetterGenshinImpact.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:behavior="clr-namespace:BetterGenshinImpact.View.Behavior"
xmlns:bgivc="clr-namespace:BetterGenshinImpact.View.Converters"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vio="http://schemas.lepo.co/wpfui/2022/xaml/violeta">
@@ -12,24 +11,14 @@
<ui:ControlsDictionary />
<vio:ControlsDictionary />
<ResourceDictionary Source="/View/Controls/WpfUi/FaFontIconStyle.xaml" />
<ResourceDictionary Source="/View/Controls/Drawer/DrawerStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
<FontFamily x:Key="TextThemeFontFamily">/Resources/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
<FontFamily x:Key="DigitalThemeFontFamily">/Resources/Fonts/deluge-led.ttf#Deluge LED</FontFamily>
<FontFamily x:Key="TextThemeFontFamily">/Assets/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
<FontFamily x:Key="DigitalThemeFontFamily">/Assets/Fonts/deluge-led.ttf#Deluge LED</FontFamily>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
<bgivc:BooleanToEnableTextConverter x:Key="BooleanToEnableTextConverter" />
<bgivc:InverseBooleanConverter x:Key="InverseBooleanConverter" />
<bgivc:NotNullConverter x:Key="NotNullConverter" />
<bgivc:EnumToKVPConverter x:Key="EnumToKVPConverter" />
<bgivc:CultureInfoNameToKVPConverter x:Key="CultureInfoNameToKVPConverter" />
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type TextBox}">
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
</Style>
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type ui:TextBox}">
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
+26 -54
View File
@@ -1,15 +1,6 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Helpers.Win32;
using BetterGenshinImpact.Hutao;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.Service.Interface;
@@ -19,15 +10,22 @@ using BetterGenshinImpact.View;
using BetterGenshinImpact.View.Pages;
using BetterGenshinImpact.ViewModel;
using BetterGenshinImpact.ViewModel.Pages;
using BetterGenshinImpact.ViewModel.Pages.View;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.RichTextBox.Abstraction;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using BetterGenshinImpact.View.Pages.View;
using BetterGenshinImpact.ViewModel.Pages.OneDragon;
using BetterGenshinImpact.ViewModel.Pages.View;
using Wpf.Ui;
using Wpf.Ui.DependencyInjection;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact;
@@ -43,7 +41,10 @@ public partial class App : Application
.CheckIntegration()
.UseElevated()
.UseSingleInstance("BetterGI")
.ConfigureLogging(builder => { builder.ClearProviders(); })
.ConfigureLogging(builder =>
{
builder.ClearProviders();
})
.ConfigureServices(
(context, services) =>
{
@@ -60,33 +61,22 @@ public partial class App : Application
services.AddSingleton<IRichTextBox>(richTextBox);
var loggerConfiguration = new LoggerConfiguration()
.WriteTo.File(logFile,
outputTemplate:
"[{Timestamp:HH:mm:ss.fff}] [{Level:u3}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}",
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 31,
retainedFileTimeLimit: TimeSpan.FromDays(21))
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(path: logFile, outputTemplate: "[{Timestamp:HH:mm:ss.fff}] [{Level:u3}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}", rollingInterval: RollingInterval.Day)
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning);
if (all.MaskWindowConfig.MaskEnabled)
{
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
}
Log.Logger = loggerConfiguration.CreateLogger();
services.AddLogging(c => c.AddSerilog());
services.AddLocalization();
services.AddNavigationViewPageProvider();
// App Host
services.AddHostedService<ApplicationHostService>();
// Page resolver service
services.AddSingleton<INavigationService, NavigationService>();
services.AddSingleton<IPageService, PageService>();
services.AddSingleton<IUpdateService, UpdateService>();
// Service containing navigation, same as INavigationWindow... but without window
@@ -105,7 +95,7 @@ public partial class App : Application
services.AddView<CommonSettingsPage, CommonSettingsPageViewModel>();
services.AddView<TaskSettingsPage, TaskSettingsPageViewModel>();
services.AddView<HotKeyPage, HotKeyPageViewModel>();
services.AddView<NotificationSettingsPage, NotificationSettingsPageViewModel>();
// services.AddView<NotificationSettingsPage, NotificationSettingsPageViewModel>();
services.AddView<KeyMouseRecordPage, KeyMouseRecordPageViewModel>();
services.AddView<JsListPage, JsListViewModel>();
services.AddView<MapPathingPage, MapPathingViewModel>();
@@ -132,11 +122,6 @@ public partial class App : Application
services.AddSingleton<NotifierManager>();
services.AddSingleton<IScriptService, ScriptService>();
services.AddSingleton<HutaoNamedPipe>();
services.AddSingleton<BgiOnnxFactory>();
services.AddSingleton<OcrFactory>();
services.AddSingleton(TimeProvider.System);
services.AddSingleton<IServerTimeProvider, ServerTimeProvider>();
// Configuration
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
@@ -144,8 +129,6 @@ public partial class App : Application
)
.Build();
public static IServiceProvider ServiceProvider => _host.Services;
public static ILogger<T> GetLogger<T>()
{
return _host.Services.GetService<ILogger<T>>()!;
@@ -180,18 +163,14 @@ public partial class App : Application
try
{
// 分配控制台窗口以支持控制台输出
ConsoleHelper.AllocateConsole("BetterGI Console");
RegisterEvents();
await _host.StartAsync();
ServerTimeHelper.Initialize(_host.Services.GetRequiredService<IServerTimeProvider>());
await UrlProtocolHelper.RegisterAsync();
}
catch (Exception ex)
{
// DEBUG only, no overhead
Debug.WriteLine(ex);
ConsoleHelper.WriteError($"应用程序启动失败: {ex.Message}");
if (Debugger.IsAttached)
{
@@ -207,15 +186,8 @@ public partial class App : Application
{
base.OnExit(e);
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
TempManager.CleanUp();
await _host.StopAsync();
_host.Dispose();
// 释放控制台窗口
ConsoleHelper.FreeConsoleWindow();
}
/// <summary>
@@ -270,7 +242,7 @@ public partial class App : Application
}
//UI线程未捕获异常处理事件(UI主线程)
private static void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
private static void AppDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
try
{
@@ -303,16 +275,16 @@ public partial class App : Application
// Fallback.
System.Windows.Forms.MessageBox.Show(
$"""
程序异常:{e.Source}
--
{e.StackTrace}
--
{e.Message}
"""
程序异常:{e.Source}
--
{e.StackTrace}
--
{e.Message}
"""
);
}
// log
GetLogger<App>().LogDebug(e, "UnHandle Exception");
}
}
}
Binary file not shown.
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8" ?>
<SyntaxDefinition name="Json" extensions=".json" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<Color name="Bool" foreground="#569CD6" exampleText="true | false" />
<Color name="Number" foreground="#B5CEA8" exampleText="3.14" />
<Color name="String" foreground="#CE9178" exampleText="" />
<Color name="Null" foreground="#569CD6" exampleText="" />
<Color name="FieldName" foreground="#9CDCF0" />
<Color name="Punctuation1" foreground="#DA66BE" />
<Color name="Punctuation2" foreground="#FFD710" />
<Color name="Punctuation3" foreground="#FFFFFF" />
<RuleSet name="String">
<Span begin="\\" end="."/>
</RuleSet>
<RuleSet name="Object">
<Span color="FieldName" ruleSet="String">
<Begin>"</Begin>
<End>"</End>
</Span>
<Span color="FieldName" ruleSet="String">
<Begin>'</Begin>
<End>'</End>
</Span>
<Span color="Punctuation3" ruleSet="Expression">
<Begin>:</Begin>
</Span>
<Span color="Punctuation3">
<Begin>,</Begin>
</Span>
</RuleSet>
<RuleSet name="Array">
<Import ruleSet="Expression"/>
<Span color="Punctuation3">
<Begin>,</Begin>
</Span>
</RuleSet>
<RuleSet name="Expression">
<Keywords color="Bool" >
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Null" >
<Word>null</Word>
</Keywords>
<Span color="String" ruleSet="String">
<Begin>"</Begin>
<End>"</End>
</Span>
<Span color="String" ruleSet="String">
<Begin>'</Begin>
<End>'</End>
</Span>
<Span color="Punctuation1" ruleSet="Object" multiline="true">
<Begin>\{</Begin>
<End>\}</End>
</Span>
<Span color="Punctuation2" ruleSet="Array" multiline="true">
<Begin>\[</Begin>
<End>\]</End>
</Span>
<Rule color="Number">
\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?
</Rule>
</RuleSet>
<RuleSet>
<Import ruleSet="Expression"/>
</RuleSet>
</SyntaxDefinition>
Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

File renamed without changes.
Binary file not shown.
Loaded 100 of 1253 files, more files were not shown because too many files have changed in this diff. Show more