TH1/Unity/DOC/devmissiondoc/26_04/fix_shared_buffer.py

169 lines
6.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能替换 _sharedAroundBuf 为 RentAroundBuf/ReturnAroundBuf
"""
import re
import sys
from pathlib import Path
def process_skill_file(filepath):
"""处理单个技能文件"""
content = filepath.read_text(encoding='utf-8')
original = content
# 检查是否在注释块中
lines = content.split('\n')
result_lines = []
in_comment_block = False
modified = False
i = 0
while i < len(lines):
line = lines[i]
stripped = line.strip()
# 检查注释块开始/结束
if '/*' in stripped and '*/' not in stripped:
in_comment_block = True
elif '*/' in stripped:
in_comment_block = False
# 只处理非注释块中的 _sharedAroundBuf ??= new
if not in_comment_block and '_sharedAroundBuf ??= new List<GridData>();' in line:
# 找到这个 pattern:
# _sharedAroundBuf ??= new List<GridData>();
# _sharedAroundBuf.Clear();
# map...GetAroundGridData(..., _sharedAroundBuf);
# foreach..._sharedAroundBuf...
# 向前查找上下文(实际上这是连续的三行)
if i + 2 < len(lines):
# 检查后续几行是否匹配模式
next_lines = '\n'.join(lines[i:i+10])
if '_sharedAroundBuf.Clear()' in next_lines and 'GetAroundGridData' in next_lines:
# 这是一个 use 块,需要智能替换
print(f"Processing: {filepath.name} at line {i+1}")
# 找到完整的 block
block_start = i
block_end = find_block_end(lines, i)
# 提取 block 并转换
block = lines[block_start:block_end+1]
new_block = transform_block(block)
result_lines.extend(new_block)
i = block_end + 1
modified = True
continue
result_lines.append(line)
i += 1
if modified:
new_content = '\n'.join(result_lines)
filepath.write_text(new_content, encoding='utf-8')
print(f" ✓ Modified: {filepath.name}")
return True
else:
print(f" - No changes: {filepath.name}")
return False
def find_block_end(lines, start_idx):
"""找到 _sharedAroundBuf 使用块的结束位置"""
# 从 start_idx 开始,查找 foreach 或相关代码块
brace_count = 0
in_foreach = False
for i in range(start_idx, min(start_idx + 50, len(lines))):
line = lines[i]
# 检测 foreach 开始
if 'foreach' in line and '_sharedAroundBuf' in line:
in_foreach = True
brace_count += line.count('{') - line.count('}')
elif in_foreach:
brace_count += line.count('{') - line.count('}')
# 简单的启发式:检测 foreach 结束
if brace_count <= 0 and '{' in lines[start_idx:i+1].__str__():
# 还要考虑后续几行,可能有 return 或其他代码
# 找到下一个方法定义或空行作为结束
for j in range(i+1, min(i+10, len(lines))):
next_line = lines[j].strip()
if next_line == '' or next_line.startswith('//') or next_line.startswith('public') or next_line.startswith('private') or next_line.startswith('}'):
return i
return i
return min(start_idx + 20, len(lines)-1)
def transform_block(block):
"""转换代码块"""
block_str = '\n'.join(block)
# 检查是否有提前 return
has_early_return = re.search(r'return\s*;', block_str) is not None
has_return_in_foreach = re.search(r'foreach.*\{[^}]*return\s*;', block_str, re.DOTALL) is not None
# 简单替换前两行
result = []
skip_until = -1
aroundBuf_name = "aroundBuf"
for i, line in enumerate(block):
if i <= skip_until:
continue
if '_sharedAroundBuf ??= new List<GridData>();' in line:
result.append(line.replace('_sharedAroundBuf ??= new List<GridData>();', f'var {aroundBuf_name} = RentAroundBuf();'))
elif '_sharedAroundBuf.Clear();' in line and 'RentAroundBuf()' not in result[-1]:
# 如果上一行已经是 RentAroundBuf则跳过 Clear
if 'RentAroundBuf()' in result[-1]:
continue
result.append(line.replace('_sharedAroundBuf.Clear()', f'{aroundBuf_name}.Clear()'))
elif 'GetAroundGridData' in line and '_sharedAroundBuf' in line:
result.append(line.replace('_sharedAroundBuf', aroundBuf_name))
elif 'foreach' in line and '_sharedAroundBuf' in line:
result.append(line.replace('_sharedAroundBuf', aroundBuf_name))
elif '_sharedAroundBuf' in line:
result.append(line.replace('_sharedAroundBuf', aroundBuf_name))
elif 'return' in line.strip() and has_return_in_foreach:
# 在 return 前添加 ReturnAroundBuf
indent = len(line) - len(line.lstrip())
result.append(' ' * indent + 'ReturnAroundBuf();')
result.append(line)
else:
result.append(line)
# 在末尾添加 ReturnAroundBuf如果不存在
if 'ReturnAroundBuf()' not in '\n'.join(result):
# 找到合适的位置(块的最后一个有效语句)
last_idx = len(result) - 1
while last_idx >= 0 and result[last_idx].strip() in ['', '}', '//', '/*', '*/']:
last_idx -= 1
# 在最后一个 return/语句之前插入
result.insert(last_idx + 1, result[last_idx].replace(result[last_idx].strip(), 'ReturnAroundBuf();'))
return result
def main():
skill_dir = Path(r'C:\TH1\TH1\Unity\Assets\Scripts\TH1_Logic\Skill\AllSkill')
files = [f for f in skill_dir.glob('*.cs') if 'KomeijiFear' not in f.name and 'FearMaker' not in f.name and 'LuckSkill' not in f.name]
modified_count = 0
for filepath in files:
try:
if process_skill_file(filepath):
modified_count += 1
except Exception as e:
print(f" ✗ Error processing {filepath.name}: {e}")
print(f"\nTotal modified: {modified_count}/{len(files)}")
if __name__ == '__main__':
main()