Initial public release
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
# Tables used by item annotations
|
||||
|
||||
| File | Contents | In the public repository? |
|
||||
|---|---|---|
|
||||
| `comments.tsv` | A one-line comment for each unique item, set item and runeword (rewritten entry by entry from the comments of a third-party mod) | **No.** It is an adaptation and the public repository does not ship it; without this table no comments are added, and the rest of the annotations work as usual |
|
||||
| `oldnames.tsv` | Old-translation table: changes some names back to the older Chinese translations that long-time players know | **No.** It is a complete set of someone else's translated names and the public repository does not ship it; without this table the "change back to old names" step is skipped automatically, and the rest of the annotations work as usual |
|
||||
|
||||
## Supplying your own old-translation table
|
||||
|
||||
Put an `oldnames.tsv` in this directory to enable it. Tab-separated, UTF-8, first line is the header (the column names are in Chinese; keep them as shown):
|
||||
|
||||
```
|
||||
文件 键 原文校验 旧译名
|
||||
item-names KhalimFlail 2717cc0f (the name you want instead)
|
||||
```
|
||||
|
||||
- `文件` (file): the name of the game string file, without `.json` (under `data/local/lng/strings/` in the game resources)
|
||||
- `键` (key): the `Key` of that entry in the file
|
||||
- `原文校验` (checksum of the original text): the first 8 hex digits of the SHA-1 of the entry's current Simplified Chinese text (UTF-8). Every entry is checked at build time, and a changed original (the game was updated) is reported as an error, so that nothing is replaced by mistake
|
||||
- `旧译名` (old name): the name to use instead; write a line break as `\n`
|
||||
|
||||
## Supplying your own comment table
|
||||
|
||||
Put a `comments.tsv` in this directory to enable it. Tab-separated, UTF-8, first line is the header; the columns are the ones read by `comments()` in `annot_strings.py`:
|
||||
|
||||
```
|
||||
文件 键 名字颜色 点评
|
||||
item-names (the Key of the string) unique (your one-line comment)
|
||||
```
|
||||
|
||||
- `文件` (file): `item-names` (unique and set items) or `item-runes` (runewords)
|
||||
- `键` (key): the `Key` of that string; a key in the table that cannot be found in the game's string tables is reported as an error
|
||||
- `名字颜色` (name color): `set` = set item (green); anything else is treated as unique (gold)
|
||||
- `点评` (comment): one line shown below the name. Skill names mentioned in it must be the names after the change back to old names (if you also supply the old-translation table)
|
||||
@@ -0,0 +1,34 @@
|
||||
# 物品注释用的表
|
||||
|
||||
| 文件 | 内容 | 进不进公开仓库 |
|
||||
|---|---|---|
|
||||
| `comments.tsv` | 暗金 / 套装 / 符文之语的一句点评(按一个第三方模组的点评逐条改写的) | **不进**。属于改编,公开仓库不带;没有这份表时不加点评,其余注释照常 |
|
||||
| `oldnames.tsv` | 旧译名对照表:把一部分名字换回老玩家熟悉的旧版中文译名 | **不进**。它是成套的他人译名,公开仓库不带;没有这份表时「换回旧译名」这一步自动不做,其余注释照常 |
|
||||
|
||||
## 自备旧译名对照表
|
||||
|
||||
放一份 `oldnames.tsv` 到本目录即启用。制表符分隔、UTF-8、首行是表头:
|
||||
|
||||
```
|
||||
文件 键 原文校验 旧译名
|
||||
item-names KhalimFlail 2717cc0f (你要换成的名字)
|
||||
```
|
||||
|
||||
- `文件`:游戏字符串文件名,不带 `.json`(在游戏资源的 `data/local/lng/strings/` 下)
|
||||
- `键`:该文件里那一条的 `Key`
|
||||
- `原文校验`:这一条现行简体中文原文(UTF-8)的 SHA-1 前 8 位十六进制——构建时逐条核对,原文变了(游戏换了版本)会报错,免得换错
|
||||
- `旧译名`:换成的名字;要换行写 `\n`
|
||||
|
||||
## 自备点评表
|
||||
|
||||
放一份 `comments.tsv` 到本目录即启用。制表符分隔、UTF-8、首行是表头;看 `annot_strings.py` 的 `comments()` 用到的列:
|
||||
|
||||
```
|
||||
文件 键 名字颜色 点评
|
||||
item-names (字符串的 Key) unique (你写的一句话)
|
||||
```
|
||||
|
||||
- `文件`:`item-names`(暗金、套装件)或 `item-runes`(符文之语)
|
||||
- `键`:该条字符串的 `Key`;表里的键在游戏字符串表里找不到会报错
|
||||
- `名字颜色`:`set` = 套装(绿),其余按暗金(金)
|
||||
- `点评`:显示在名字下面的一行。里面提到的技能名要用换回旧译名之后的名字(如果你同时带了旧译名对照表)
|
||||
@@ -0,0 +1,221 @@
|
||||
"""地上掉落名(筛选逻辑和规则复刻红叶;不抄红叶的字,信息一条不少,全从游戏表算,用我们自己的措辞)。
|
||||
红叶的「筛选」就是改名字(它什么都不藏):低价值消耗品缩短、值钱 / 要用的加色、加来源与用途、底材加档次与价值。逐类对应如下:
|
||||
药水:治疗 / 法力 1–5 级缩成 微 / 小 / 中 / 大 / 超 + 红 / 蓝(超级加色);复苏 小紫 / 大紫;解毒药水去「药水」。
|
||||
卷轴:回城、鉴定两种常掉的缩短;箭矢 / 弩矢缩成「箭」「弩矢」。
|
||||
宝石 / 骷髅:缩成「档-颜色」;碎裂 / 有瑕疵 / 标准三档加「合 N」= 这颗在魔盒里升级符文时合出第几号(cubemain.txt 的符文升级配方)。
|
||||
符文:现行名「中文 英文 #号」上色,24 号起加框线、27 号起多空行、28 号起框线加长(越值钱越显眼)。
|
||||
钥匙 / 首领器官 / 精华:来源首领由掉落表反查(treasureclassex.txt 逐层往上找,到 monstats / superuniques 的地狱掉落列),名字取字符串表;
|
||||
钥匙另标首领所在幕,任务物品(ua1–ua5)按 misc.txt 英文名里的 Act 号标幕。
|
||||
底材(武器 / 护甲):档次与轻中重由前面的「底材档次」步骤写好;这里加 ★(值得留的底材,名单与理由见 VALUE_BASES)、价值数字、顶级符文之语、
|
||||
职业标枪的魔法词缀上限、合成手套的标志属性(cubemain.txt 的手套合成配方)。
|
||||
名字一律取字符串表的现行值(已做过旧译名 / 符文序号)。游戏把多行名字倒着画(最后一行在最上面),所以「说明\\n名字」画出来是名字在上、说明在下。
|
||||
Ground drop names (the filter logic and rules replicate the Hongye community mod; its wording is not copied, no piece of information is left out, everything is computed from the game tables, in our own wording).
|
||||
Hongye's "filter" is just renaming (it hides nothing): low-value consumables are shortened, valuable / needed items get color, source and use are added, bases get tier and value. Category by category:
|
||||
Potions: healing / mana levels 1–5 are shortened to 「微 / 小 / 中 / 大 / 超」(minor / light / medium / greater / super) + 「红 / 蓝」(red / blue) (super gets color); rejuvenation becomes 「小紫 / 大紫」(small purple / large purple); antidote potion drops 「药水」(potion).
|
||||
Scrolls: the two commonly dropped ones, town portal and identify, are shortened; arrows / bolts are shortened to 「箭」(arrows) and 「弩矢」(bolts).
|
||||
Gems / skulls: shortened to "grade-color"; the chipped / flawed / standard grades get 「合 N」(combine N) = which rune number this one produces when upgrading runes in the Horadric Cube (rune upgrade recipes in cubemain.txt).
|
||||
Runes: the current name "Chinese English #number" is colored; frame lines from 24 on, extra blank lines from 27 on, longer frame lines from 28 on (the more valuable, the more conspicuous).
|
||||
Keys / boss organs / essences: the source boss is reverse-looked-up from the treasure classes (search upward level by level in treasureclassex.txt, up to the Hell drop columns of monstats / superuniques); names come from the string table;
|
||||
keys also get the act the boss is in, and quest items (ua1–ua5) get the act from the Act number in the English name in misc.txt.
|
||||
Bases (weapons / armor): tier and light/medium/heavy are written by the earlier "base tier" step; here we add ★ (base worth keeping; list and reasons in VALUE_BASES), the value number, top runewords,
|
||||
the magic affix cap for class javelins, and the signature property for crafted gloves (glove crafting recipes in cubemain.txt).
|
||||
Names always use the current value in the string table (old translated names / rune numbers already applied). The game draws multi-line names in reverse (last line on top), so "description\\\\\\
|
||||
name" is drawn with the name on top and the description below."""
|
||||
import math, re
|
||||
|
||||
FILES = ('item-names.json', 'item-runes.json', 'chinese-overlay.json') # 加载顺序:后加载的同键覆盖前面的 | Load order: a later-loaded file overrides earlier ones for the same key
|
||||
NAME_FILES = FILES + ('monsters.json', 'npcs.json')
|
||||
RED, BLUE, BLUE2, PURPLE, ORANGE, GREEN = 'ÿc1', 'ÿc3', 'ÿc5', 'ÿc;', 'ÿc8', 'ÿc2'
|
||||
SIZE = ('微', '小', '中', '大', '超') # 药水 1–5 级 | Potion levels 1–5
|
||||
SHORT = {'tsc': '回城', 'aqv': '箭', 'cqv': '弩矢', 'rvs': PURPLE + '小紫', 'rvl': PURPLE + '大紫'}
|
||||
STRIP = {'isc': '卷轴', 'yps': '药水'} # 常掉的低价值件:去掉后缀 | Commonly dropped low-value items: strip the suffix
|
||||
GEM_COLOR = {'gema': '紫', 'gemt': '黄', 'gems': '蓝', 'geme': '绿', 'gemr': '红', 'gemd': '钻', 'gemz': '骷髅'}
|
||||
GEM_GRADE = (('碎裂', ''), ('裂开', ''), ('', ''), ('无瑕', RED), ('完美', RED)) # 档:碎裂 / 有瑕疵 / 标准 / 无瑕 / 完美 | Grades: chipped / flawed / standard / flawless / perfect
|
||||
GEM_GRADE_CH = {'c': 0, 'f': 1, 's': 2, 'l': 3, 'z': 3, 'p': 4} # 宝石码第 2 字(gzv:紫宝石的无瑕用 z) | 2nd character of the gem code (gzv: amethyst uses z for flawless)
|
||||
SKULL_GRADE_CH = {'c': 0, 'f': 1, 'u': 2, 'l': 3, 'z': 4} # 骷髅码第 3 字(skl 无瑕、skz 完美) | 3rd character of the skull code (skl flawless, skz perfect)
|
||||
HIGH_RUNE = 24 # 从这一号起加上下框线(值钱的高级符文);27 号起上下多空两行、28 号起框线加长 | From this number on, add frame lines above and below (valuable high runes); from 27 on, two extra blank lines above and below; from 28 on, longer frame lines
|
||||
SOURCE_NOTE = {'pk1': '火炬钥匙', 'pk2': '火炬钥匙', 'pk3': '火炬钥匙', 'dhn': '地狱火炬材料', 'bey': '地狱火炬材料', 'mbr': '地狱火炬材料',
|
||||
'tes': '合成赦免勋章', 'ceh': '合成赦免勋章', 'bet': '合成赦免勋章', 'fed': '合成赦免勋章'}
|
||||
SOURCE_COLOR = {'pk1': RED, 'pk2': ORANGE, 'pk3': GREEN}
|
||||
BOSS_ACT = {'The Countess': 1, 'The Summoner': 2, 'Nihlathak Boss': 5} # 首领所在幕(地图事实) | Act the boss is in (map fact)
|
||||
# 值得留的底材(我们自己的判据,按用途分组):
|
||||
# 法珠(法师专用、可 4 孔、自带法术词缀);刺客高阶爪(3 孔做混沌 / 狂怒、或高技能魔法爪);头环(可出 +2 技能 / 3 孔);
|
||||
# 精英头盔里出顶级暗金 / 符文之语的三顶;4 孔精英身甲与力量需求最低的扩展身甲(做谜团 / 刚毅);6 孔女族长之矛;4 孔圣骑士皇家盾牌。
|
||||
# 「值」= 这件做卓越品质(+1 最大值后 ×1.15)时的上限;身甲做谜团不做无形,头盔 / 武器给佣兵用按无形(再 ×1.5)算。武器给伤害、护甲给防御。
|
||||
# Bases worth keeping (our own criteria, grouped by use):
|
||||
# orbs (sorceress-only, can have 4 sockets, come with spell automods); high-tier assassin claws (3 sockets for Chaos / Fury, or high-skill magic claws); circlets (can roll +2 skills / 3 sockets);
|
||||
# the three elite helms that yield top uniques / runewords; 4-socket elite body armor and the exceptional body armor with the lowest strength requirement (for Enigma / Fortitude); 6-socket Matriarchal Spear; 4-socket paladin Royal Shield.
|
||||
# "Value" = the cap when this piece is superior quality (+1 max, then ×1.15); body armor is for Enigma and not ethereal, helms / weapons are for the mercenary and computed as ethereal (a further ×1.5). Weapons give damage, armor gives defense.
|
||||
VALUE_BASES = {
|
||||
**{c: {} for c in ('ob1', 'ob2', 'ob3', 'ob4', 'ob5', 'ob6', 'ob7', 'ob8', 'ob9', 'oba', 'obb', 'obc', 'obd', 'obe', 'obf')},
|
||||
**{c: {} for c in ('9lw', '9tw', '7lw', '7tw', 'ci1', 'ci2', 'ci3', 'uhm', 'usk', 'utu', 'upl', 'uth', 'uul', 'uar', 'utp', 'amd', 'paa')},
|
||||
'xtp': {'value': 'range'},
|
||||
'urn': {'value': 'max', 'eth': True},
|
||||
}
|
||||
# 顶级符文之语:每件底材列出我们认为值得为它留底的几个(runes.txt 核过底材类型,能做才写)
|
||||
# Top runewords: for each base, list the few we consider worth keeping the base for (base types checked against runes.txt; only written if it can be made)
|
||||
TOP_RUNEWORDS = {'7wa': ('Oath', 'Death', 'Breath of the Dying')}
|
||||
WEAPON_VALUE = {'7wa': {'value': 'range', 'eth': True}}
|
||||
FRAMED = ('ci3',) # 头环里最高阶的权冠:可出 +2 技能 + 2 孔以上的顶级头环底 | The highest-tier circlet, the Diadem: a top circlet base that can roll +2 skills + 2 or more sockets
|
||||
CLASS_MAGIC = ('ama', 'amf') # 职业标枪里扩展 / 精英最高阶的两把:标出魔法件能出的最高技能与攻速 | The two highest-tier exceptional / elite class javelins: mark the highest skill and attack speed a magic one can roll
|
||||
CRAFT_GLOVE_MODS = {'crush': '压碎', 'mana-kill': '杀敌回蓝'} # 手套合成配方的标志属性里值得标的两种(鲜血 / 施法者合成) | The two signature properties of glove crafting recipes that are worth marking (Blood / Caster crafts)
|
||||
|
||||
|
||||
def _strings_get(s, key):
|
||||
v = [s.get(f, key) for f in NAME_FILES if s.has(f, key)]
|
||||
return v[-1] if v else None
|
||||
|
||||
|
||||
class Tables:
|
||||
"""一次性读好要用的游戏表。 | Read all the game tables that are needed, once."""
|
||||
def __init__(self, romfs):
|
||||
from annot_strings import excel
|
||||
self.misc = {r['code']: r for r in excel(romfs, 'misc.txt') if r.get('code')}
|
||||
self.weap = {r['code']: r for r in excel(romfs, 'weapons.txt') if r.get('code')}
|
||||
self.armor = {r['code']: r for r in excel(romfs, 'armor.txt') if r.get('code')}
|
||||
self.types = {r['Code']: r for r in excel(romfs, 'itemtypes.txt') if r.get('Code')}
|
||||
self.cube = excel(romfs, 'cubemain.txt')
|
||||
self.runes = {r['*Rune Name']: r for r in excel(romfs, 'runes.txt') if r.get('*Rune Name')}
|
||||
self.tc = excel(romfs, 'treasureclassex.txt')
|
||||
self.monstats = excel(romfs, 'monstats.txt'); self.superuniques = excel(romfs, 'superuniques.txt')
|
||||
self.automagic = excel(romfs, 'automagic.txt'); self.prefix = excel(romfs, 'magicprefix.txt'); self.suffix = excel(romfs, 'magicsuffix.txt')
|
||||
self.parents = {}
|
||||
for r in self.tc:
|
||||
for k in range(1, 11):
|
||||
i = r.get('Item%d' % k, '')
|
||||
if i: self.parents.setdefault(i, set()).add(r['Treasure Class'])
|
||||
|
||||
def ancestors(self, t):
|
||||
out, st = set(), [t]
|
||||
while st:
|
||||
x = st.pop()
|
||||
if x and x not in out:
|
||||
out.add(x); st += [self.types.get(x, {}).get('Equiv1', ''), self.types.get(x, {}).get('Equiv2', '')]
|
||||
return out
|
||||
|
||||
def gem_rune(self, code):
|
||||
"""这颗宝石在哪条符文升级配方里当辅料:返回合出的符文号。 | Which rune upgrade recipe uses this gem as the secondary ingredient: returns the number of the resulting rune."""
|
||||
for r in self.cube:
|
||||
ins = [(r.get('input %d' % k, '') or '').split(',')[0] for k in range(1, 8)]; out = r.get('output', '')
|
||||
if code in ins and re.fullmatch(r'r\d\d', out) and any(re.fullmatch(r'r\d\d', i) for i in ins): return int(out[1:])
|
||||
return None
|
||||
|
||||
def sources(self, code):
|
||||
"""掉这件的首领 [(表, 内部名, 名字键)](地狱难度):从直接列出它的掉落表逐层往上找,再找哪个超级独特怪 / 怪的地狱掉落表在里面。 | Bosses that drop this piece [(table, internal name, name key)] (Hell difficulty): starting from the treasure class that lists it directly, search upward level by level, then find which super unique / monster has its Hell treasure class in there."""
|
||||
seen, st = set(), [code]
|
||||
while st:
|
||||
for p in self.parents.get(st.pop(), ()):
|
||||
if p not in seen: seen.add(p); st.append(p)
|
||||
out = []
|
||||
for r in self.superuniques:
|
||||
if any(r.get(c) in seen for c in r if c.startswith('TC') and '(H)' in c): out.append(('su', r['Superunique'], r.get('Name')))
|
||||
if out: return out
|
||||
for r in self.monstats:
|
||||
if any(r.get(c) in seen for c in r if c.startswith('TreasureClass') and '(H)' in c): out.append(('mon', r.get('Id'), r.get('NameStr')))
|
||||
return out
|
||||
|
||||
def class_magic(self, code):
|
||||
"""职业物品魔法件能出的最高技能(自动词缀 + 前缀的技能页加成)与最高攻速(后缀)。 | Highest skill a magic class item can roll (skill-tab bonus from automod + prefix) and highest attack speed (suffix)."""
|
||||
a = self.ancestors(self.weap[code]['type'])
|
||||
def best(tab, mods, spawn):
|
||||
v = 0
|
||||
for r in tab:
|
||||
if spawn and r.get('spawnable') != '1': continue
|
||||
its = {r.get('itype%d' % k, '') for k in range(1, 8)}; ex = {r.get('etype%d' % k, '') for k in range(1, 6)}
|
||||
if not (its & a) or (ex & a): continue
|
||||
for k in range(1, 4):
|
||||
if r.get('mod%dcode' % k) in mods: v = max(v, int(r.get('mod%dmax' % k) or 0))
|
||||
return v
|
||||
return best(self.automagic, ('skilltab',), False) + best(self.prefix, ('skilltab',), True), best(self.suffix, ('swing1', 'swing2', 'swing3'), True)
|
||||
|
||||
def craft_glove(self, code):
|
||||
"""这双手套所在的一族(普 / 扩 / 精)是哪条手套合成配方的底材:返回配方标志属性里值得标的那一个(CRAFT_GLOVE_MODS)。 | Which glove crafting recipe the family (normal / exceptional / elite) of this pair of gloves is the base for: returns the one worth marking among the recipe's signature properties (CRAFT_GLOVE_MODS)."""
|
||||
r = self.armor[code]; fam = {r.get('normcode'), r.get('ubercode'), r.get('ultracode')}
|
||||
for c in self.cube:
|
||||
if (c.get('input 1', '') or '').split(',')[0] in fam:
|
||||
for k in range(1, 6):
|
||||
if c.get('mod %d' % k) in CRAFT_GLOVE_MODS: return CRAFT_GLOVE_MODS[c.get('mod %d' % k)]
|
||||
return None
|
||||
|
||||
|
||||
def _rune_line(code, name):
|
||||
m = re.fullmatch(r"(.+) ([A-Za-z']+) (#\d+)", name)
|
||||
if not m: return None
|
||||
i, txt = int(code[1:]), ORANGE + m.group(1) + ' ' + BLUE2 + m.group(2) + GREEN + m.group(3)
|
||||
if i < HIGH_RUNE: return txt
|
||||
bar, gap = ORANGE + '—' * (13 if i >= 28 else 9), '\n' * (4 if i >= 27 else 2)
|
||||
return bar + gap + txt + gap + bar
|
||||
|
||||
|
||||
def misc_rule(T, s, code, name):
|
||||
"""杂物类一个物品码的掉落名;None = 不改。 | Drop name for one miscellaneous item code; None = no change."""
|
||||
row = T.misc[code]; t = row.get('type', '')
|
||||
if code in SHORT: return SHORT[code]
|
||||
if code in STRIP and name.endswith(STRIP[code]): return name[:-len(STRIP[code])]
|
||||
if t in ('hpot', 'mpot') and code[-1:].isdigit():
|
||||
i = int(code[-1]) - 1; w = SIZE[i] + ('红' if t == 'hpot' else '蓝')
|
||||
return (RED if t == 'hpot' else BLUE) + w if i == 4 else w
|
||||
if t in GEM_COLOR:
|
||||
g = SKULL_GRADE_CH.get(code[2]) if t == 'gemz' else GEM_GRADE_CH.get(code[1])
|
||||
if g is None: return None
|
||||
word, color = GEM_GRADE[g]
|
||||
base = color + word + '-' + GEM_COLOR[t] if word else name
|
||||
n = T.gem_rune(code) if g <= 2 else None
|
||||
return base + (' (合%d)' % n if n else '')
|
||||
if t == 'rune' and re.fullmatch(r'r\d\d', code): return _rune_line(code, name)
|
||||
if code in SOURCE_NOTE:
|
||||
src = T.sources(code)
|
||||
if not src: raise SystemExit('annot_drop:%s 在掉落表里找不到来源首领' % code)
|
||||
who = '或'.join(dict.fromkeys(_strings_get(s, key) or key for _, _, key in src))
|
||||
act = next((BOSS_ACT[x[1]] for x in src if x[1] in BOSS_ACT), None)
|
||||
color = SOURCE_COLOR.get(code, GREEN)
|
||||
return color + '[' + who + ' · ' + SOURCE_NOTE[code] + ']\n' + color + name + (' 第%d幕' % act if act else '')
|
||||
m = re.search(r'Act ?(\d)', row.get('name', ''))
|
||||
if m and t == 'ques' and code.startswith('ua'): return '%s 第%s幕' % (name, m.group(1))
|
||||
return None
|
||||
|
||||
|
||||
def base_rule(T, s, code, name):
|
||||
"""武器 / 护甲一个物品码的掉落名(在底材档次之后);None = 不改。 | Drop name for one weapon / armor item code (after the base tier); None = no change."""
|
||||
parts = []
|
||||
w, a = T.weap.get(code), T.armor.get(code)
|
||||
if code in CLASS_MAGIC:
|
||||
sk, ias = T.class_magic(code); parts.append('魔法 技能+%d 攻速+%d' % (sk, ias))
|
||||
vb = VALUE_BASES.get(code) or WEAPON_VALUE.get(code)
|
||||
if vb and vb.get('value'):
|
||||
k = 1.5 if vb.get('eth') else 1.0
|
||||
if w:
|
||||
lo, hi = int(w['mindam'] or w['2handmindam']), int(w['maxdam'] or w['2handmaxdam'])
|
||||
parts.append('攻速 %s · 伤害 %d-%d' % (w.get('speed') or '0', lo, math.floor(math.ceil(hi * k) * 1.15)))
|
||||
else:
|
||||
lo, hi = int(a['minac']), int(a['maxac']); top = math.floor(math.floor((hi + 1) * k) * 1.15)
|
||||
parts.append(('防御 %d-%d' % (lo, top)) if vb['value'] == 'range' else '防御 %d' % top)
|
||||
if code in TOP_RUNEWORDS:
|
||||
names = []
|
||||
for rw in TOP_RUNEWORDS[code]:
|
||||
r = T.runes[rw]; its = {r.get('itype%d' % k, '') for k in range(1, 7)}
|
||||
if not (its & T.ancestors((w or a)['type'])): raise SystemExit('annot_drop:%s 做不了 %s' % (code, rw))
|
||||
nm = (_strings_get(s, r['Name']) or rw).split('\n')[-1] # 前面的注释步骤给符文之语名加了范围 / 点评行:只取名字那一行 | Earlier annotation steps added range / review lines to the runeword name: take only the name line
|
||||
names.append(re.sub(r'\u00ffc.', '', nm))
|
||||
parts.append('可做 ' + ' / '.join(names))
|
||||
glove = T.craft_glove(code) if a and a.get('type') == 'glov' else None
|
||||
out = name
|
||||
if code in VALUE_BASES: out = '★' + out
|
||||
if glove: out += ' 〈合成·%s〉' % glove
|
||||
if parts: out = '[' + ' · '.join(parts) + ']\n' + out
|
||||
if code in FRAMED: out = '—' * 7 + '\n' + out + '\n' + '—' * 7 # 最顶级的几件上下加框线 | Add frame lines above and below the few top-tier pieces
|
||||
return out if out != name else None
|
||||
|
||||
|
||||
def ann_drop(s, romfs):
|
||||
"""s = 已做完前面步骤的 Strings。返回改写条数。 | s = Strings with the earlier steps already applied. Returns the number of rewritten entries."""
|
||||
T = Tables(romfs); n = 0
|
||||
for tab, rule in ((T.misc, misc_rule), (T.weap, base_rule), (T.armor, base_rule)):
|
||||
for code, row in tab.items():
|
||||
key = row.get('namestr') or code
|
||||
cur = [s.get(f, key) for f in FILES if s.has(f, key)]
|
||||
if not cur: continue
|
||||
new = rule(T, s, code, cur[-1]) # 最后一份才是游戏里显示的 | The last one is what the game displays
|
||||
if new is None or new == cur[-1]: continue
|
||||
n += sum(s.set(f, key, lambda _t, v=new: v) for f in FILES)
|
||||
return n
|
||||
@@ -0,0 +1,117 @@
|
||||
"""给暗金、套装和符文之语名称加关键可变属性范围。 | Add key variable-property ranges to unique, set and runeword names."""
|
||||
ITEM_FILES = ('item-names.json', 'chinese-overlay.json')
|
||||
|
||||
|
||||
def _excel(romfs, name):
|
||||
from annot_strings import excel
|
||||
return excel(romfs, name)
|
||||
|
||||
|
||||
STAT_NAMES = {
|
||||
'abs-cold': '吸收冰伤', 'abs-cold%': '吸冰伤', 'abs-fire': '吸收火伤', 'abs-fire%': '吸火伤',
|
||||
'abs-ltng': '吸电伤', 'abs-ltng%': '吸电伤', 'abs-mag': '吸收魔伤', 'ac': '防御', 'ac%': '强防',
|
||||
'ac-miss': '防御', 'addxp': '经验', 'all-stats': '全属性', 'allskills': '全技能', 'ama': '亚马逊',
|
||||
'att': '命中', 'att%': '命中', 'att-demon': '对恶魔命中', 'att-skill': '命中技能', 'att-undead': '对亡灵命中',
|
||||
'aura': '光环', 'balance1': '打击恢复', 'balance2': '打击恢复', 'balance3': '打击恢复', 'block': '格挡',
|
||||
'bloody': '撕裂', 'cast1': '施法速度', 'cast2': '施法速度', 'cast3': '施法速度', 'cheap': '商店折扣',
|
||||
'cold-len': '冰冻时长', 'cold-max': '冰伤上限', 'cold-min': '冰伤下限', 'crush': '压碎打击',
|
||||
'death-skill': '死亡技能', 'demon-heal': '对恶魔回复', 'dex': '敏捷', 'dmg': '伤害', 'dmg%': '强伤',
|
||||
'dmg-cold': '冰伤', 'dmg-demon': '对恶魔伤', 'dmg-elem': '元素伤', 'dmg-fire': '火伤', 'dmg-ltng': '电伤',
|
||||
'dmg-mag': '魔伤', 'dmg-max': '伤害上限', 'dmg-min': '伤害下限', 'dmg-norm': '伤害', 'dmg-undead': '对亡灵伤',
|
||||
'dmg-pois': '毒伤', 'dru': '德鲁伊', 'dur': '耐久', 'enr': '精力', 'extra-cold': '冰伤加成',
|
||||
'extra-fire': '火伤加成', 'extra-ltng': '电伤加成', 'extra-mag': '魔伤加成', 'extra-pois': '毒伤加成',
|
||||
'fire-max': '火伤上限', 'fire-min': '火伤下限', 'freeze': '冻结', 'gold%': '金币', 'gethit-skill': '受击技能',
|
||||
'heal-kill': '击杀回复', 'hit-skill': '击中技能', 'hp': '生命', 'hp%': '生命', 'kill-skill': '击杀技能',
|
||||
'levelup-skill': '升级技能', 'lifesteal': '吸血', 'light': '照亮范围', 'light-thorns': '荆棘', 'ltng-max': '电伤上限',
|
||||
'mag%': '寻宝', 'mana': '法力', 'mana%': '法力', 'mana-kill': '击杀回蓝', 'manasteal': '吸蓝',
|
||||
'move1': '跑速', 'move2': '跑速', 'move3': '跑速', 'nec': '死灵法师', 'oskill': '技能',
|
||||
'pal': '圣骑士', 'pierce-cold': '冰抗穿透', 'pierce-fire': '火抗穿透', 'pierce-ltng': '电抗穿透',
|
||||
'pierce-mag': '魔抗穿透', 'pierce-pois': '毒抗穿透', 'randclassskill': '随机技能', 'red-dmg': '减伤',
|
||||
'red-dmg%': '减伤', 'red-mag': '魔法减伤', 'regen': '生命回复', 'regen-mana': '法力回复', 'res-all': '全抗',
|
||||
'res-cold': '冰抗', 'res-fire': '火抗', 'res-ltng': '电抗', 'res-mag': '魔抗', 'res-pois': '毒抗',
|
||||
'skill': '技能', 'skill-rand': '随机技能', 'skilltab': '技能页', 'sock': '孔', 'sor': '女巫', 'stam': '耐力',
|
||||
'str': '力量', 'swing1': '攻速', 'swing2': '攻速', 'swing3': '攻速', 'thorns': '荆棘', 'vit': '体力',
|
||||
'charged': '技能', '*charged': '技能',
|
||||
}
|
||||
|
||||
# 只有「min..max 里随机取一个值」的属性才是可变范围:看 properties.txt 的 func1。
|
||||
# 1 / 2 / 5 / 6 / 7 / 8 / 10 / 14 / 22 = 随机取值(数值、伤害下限 / 上限 / 百分比、速度、技能页、孔数、单个技能等级);
|
||||
# 15 = min 给下限属性、max 给上限属性(如「冰伤 15-45」是固定的伤害区间);11 / 19 = 触发 / 充能(几率或次数 + 技能等级);17 / 18 = 按等级 / 按时间。这些都不写。
|
||||
# Only properties that "pick a random value within min..max" are variable ranges: look at func1 in properties.txt.
|
||||
# 1 / 2 / 5 / 6 / 7 / 8 / 10 / 14 / 22 = random value (number, damage min / max / percent, speed, skill tab, socket count, single skill level);
|
||||
# 15 = min goes to the minimum property and max to the maximum property (e.g. 「冰伤 15-45」(cold damage 15-45) is a fixed damage range); 11 / 19 = proc / charges (chance or count + skill level); 17 / 18 = per level / per time. None of these are written.
|
||||
RANDOM_FUNCS = {'1', '2', '5', '6', '7', '8', '10', '14', '22'}
|
||||
SKILL_CODES = {'skill', 'oskill', 'aura', 'skilltab', 'charged', '*charged', 'hit-skill', 'gethit-skill',
|
||||
'kill-skill', 'death-skill', 'levelup-skill', 'att-skill', 'skill-rand'}
|
||||
|
||||
|
||||
def _skill_names(s, romfs):
|
||||
names = {}
|
||||
for row in _excel(romfs, 'skills.txt'):
|
||||
skill_id = row.get('*Id', '').strip()
|
||||
skill = row.get('skill', '').strip()
|
||||
if skill_id and skill:
|
||||
value = s.get('skills.json', 'skillname' + skill_id)
|
||||
names[skill] = value if value and len(value) <= 4 else '技能'
|
||||
return names
|
||||
|
||||
|
||||
def _label(code, param, skills):
|
||||
label = STAT_NAMES.get(code, STAT_NAMES.get(code.lstrip('*')))
|
||||
if code in SKILL_CODES or code.lstrip('*') in SKILL_CODES:
|
||||
if param:
|
||||
return skills.get(param, '技能') + '+'
|
||||
return '技能'
|
||||
return label or code
|
||||
|
||||
|
||||
def _range_line(rows, code_prefix, min_prefix, max_prefix, slots, skills, props):
|
||||
parts = []
|
||||
for i in slots:
|
||||
code = rows.get(code_prefix.format(i), '').strip()
|
||||
if not code:
|
||||
continue
|
||||
minimum = rows.get(min_prefix.format(i), '').strip()
|
||||
maximum = rows.get(max_prefix.format(i), '').strip()
|
||||
if props.get(code.lstrip('*'), {}).get('func1') not in RANDOM_FUNCS or minimum == maximum or not minimum or not maximum:
|
||||
continue
|
||||
label = _label(code, rows.get(('par' + str(i)) if code_prefix.startswith('prop') else ('T1Param' + str(i)), '').strip(), skills)
|
||||
suffix = '%' if '%' in code else ''
|
||||
prefix = '+' if code == 'ac' else ''
|
||||
parts.append('%s%s%s-%s%s' % (label, prefix, minimum, maximum, suffix))
|
||||
if len(parts) == 3:
|
||||
break
|
||||
return '/'.join(parts)
|
||||
|
||||
|
||||
def _annotate(s, key, line, color, files=ITEM_FILES):
|
||||
"""名字下方加灰色范围行。串里的颜色码从写下处一直生效到被下一个码改掉(只在前面加 ÿc5 时名字也变灰),
|
||||
所以名字行前补回它本来的颜色:暗金 / 符文之语 ÿc4、套装 ÿc2。
|
||||
Add a gray range line below the name. A color code in the string stays in effect from where it is written until the next code changes it (adding only ÿc5 in front would turn the name gray too),
|
||||
so the name line gets its original color restored in front: unique / runeword ÿc4, set ÿc2."""
|
||||
if not line:
|
||||
return 0
|
||||
def add(text):
|
||||
return text if text.startswith('\u00ffc5[') else '\u00ffc5[%s]\n%s%s' % (line, color, text)
|
||||
n = 0
|
||||
for filename in files:
|
||||
n += s.set(filename, key, add)
|
||||
return n
|
||||
|
||||
|
||||
def ann_ranges(s, romfs):
|
||||
"""按表中原顺序给可变属性加范围,返回改写条数。 | Add ranges to variable properties in the table's original order; returns the number of rewritten entries."""
|
||||
skills = _skill_names(s, romfs)
|
||||
props = {r['code']: r for r in _excel(romfs, 'properties.txt') if r.get('code')}
|
||||
changed = 0
|
||||
for row in _excel(romfs, 'uniqueitems.txt'):
|
||||
if row.get('disabled') == '1' or row.get('spawnable') != '1':
|
||||
continue
|
||||
changed += _annotate(s, row.get('index', ''), _range_line(row, 'prop{}', 'min{}', 'max{}', range(1, 13), skills, props), '\u00ffc4')
|
||||
for row in _excel(romfs, 'setitems.txt'):
|
||||
changed += _annotate(s, row.get('index', ''), _range_line(row, 'prop{}', 'min{}', 'max{}', range(1, 9), skills, props), '\u00ffc2')
|
||||
for row in _excel(romfs, 'runes.txt'):
|
||||
if row.get('complete') != '1':
|
||||
continue
|
||||
changed += _annotate(s, row.get('Name', ''), _range_line(row, 'T1Code{}', 'T1Min{}', 'T1Max{}', range(1, 8), skills, props), '\u00ffc4', ('item-runes.json', 'chinese-overlay.json'))
|
||||
return changed
|
||||
@@ -0,0 +1,267 @@
|
||||
#!/usr/bin/env python3
|
||||
"""物品 / 符文 / 区域 / 怪物 / 神殿的注释与旧译名(注释要、旧译名整体换回、不加英文缩写)。
|
||||
做法 = RomFS 覆盖层换字符串文件(与 touch_strings 同一套机制),只改 zhCN 一列、按键名定位、原文不符即报错。
|
||||
注释的数字一律从我们 3.3 包里的 excel 表算(不拷红叶的表);旧译名表 annot/oldnames.tsv 是从红叶 mod 的名字部分抽出、
|
||||
逐条与 3.3 原文对过的。
|
||||
Annotations and old translated names for items / runes / areas / monsters / shrines (annotations wanted, old translated names restored wholesale, no English abbreviations added).
|
||||
Method = replace the string files via the RomFS overlay (same mechanism as touch_strings); only the zhCN column is changed, located by key name, and an error is raised if the source text does not match.
|
||||
Annotation numbers are always computed from the excel tables in our 3.3 package (the Hongye community mod's tables are not copied); the old-name table annot/oldnames.tsv was extracted from the name part of the Hongye mod and
|
||||
checked entry by entry against the 3.3 source text."""
|
||||
import csv, hashlib, io, os, re, sys
|
||||
import touch_layout
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
STR = '/lng/strings/'
|
||||
|
||||
|
||||
class Strings:
|
||||
"""字符串文件的按键改写:保留原文件排版,只换 zhCN 的值。 | Per-key rewrite of a strings file: keep the original file's formatting and replace only the zhCN value."""
|
||||
def __init__(self, romfs, repl):
|
||||
self.romfs, self.repl, self.text, self.path, self.dirty = romfs, repl, {}, {}, set()
|
||||
|
||||
def _load(self, name):
|
||||
if name in self.text: return
|
||||
path, text = touch_layout.read_layout(self.romfs, None, suffix=STR + name)
|
||||
prev = self.repl.get(path.lower()) # 前面的步骤(touch_strings)已经换过这份就在它的结果上改 | If an earlier step (touch_strings) has already replaced this file, modify on top of its result
|
||||
if prev: text = open(prev, encoding='utf-8-sig').read()
|
||||
self.text[name], self.path[name] = text, path
|
||||
|
||||
def _iter(self, name, key):
|
||||
self._load(name)
|
||||
return list(re.finditer(r'"Key":\s*"%s",.*?"zhCN":\s*("(?:[^"\\]|\\.)*")' % re.escape(key.replace('"', '\\"')), self.text[name], re.S))
|
||||
|
||||
def has(self, name, key): return bool(self._iter(name, key))
|
||||
|
||||
def keys(self, name):
|
||||
self._load(name)
|
||||
return re.findall(r'"Key":\s*"((?:[^"\\]|\\.)*)"', self.text[name])
|
||||
|
||||
def get(self, name, key):
|
||||
import json
|
||||
m = self._iter(name, key)
|
||||
return json.loads(m[0].group(1)) if m else None
|
||||
|
||||
def get_lang(self, name, key, lang):
|
||||
"""同一条目里别的语言列(如 enUS)。 | Other language columns in the same entry (e.g. enUS)."""
|
||||
import json
|
||||
self._load(name)
|
||||
m = re.search(r'"Key":\s*"%s",.*?"%s":\s*("(?:[^"\\]|\\.)*")' % (re.escape(key), lang), self.text[name], re.S)
|
||||
return json.loads(m.group(1)) if m else None
|
||||
|
||||
def set(self, name, key, fn):
|
||||
"""fn(原文) → 新文;同一文件里同键多处一起改。返回改了几处。 | fn(original text) → new text; multiple occurrences of the same key in one file are changed together. Returns the number of changes."""
|
||||
import json
|
||||
ms = self._iter(name, key)
|
||||
t = self.text[name]
|
||||
for m in reversed(ms):
|
||||
t = t[:m.start(1)] + json.dumps(fn(json.loads(m.group(1))), ensure_ascii=False) + t[m.end(1):]
|
||||
if ms: self.text[name] = t; self.dirty.add(name)
|
||||
return len(ms)
|
||||
|
||||
def write(self, outdir):
|
||||
out = {}
|
||||
for name in sorted(self.dirty):
|
||||
o = os.path.join(outdir, 'annot_' + name)
|
||||
open(o, 'w', encoding='utf-8-sig', newline='').write(self.text[name]); out[self.path[name].lower()] = o
|
||||
return out
|
||||
|
||||
|
||||
def excel(romfs, name):
|
||||
_, text = touch_layout.read_layout(romfs, None, suffix='/global/excel/' + name)
|
||||
return list(csv.DictReader(io.StringIO(text), delimiter='\t'))
|
||||
|
||||
|
||||
# 物品名的键可能同时出现在 chinese-overlay.json(它后加载、同键覆盖),两处都改
|
||||
# An item name key may also appear in chinese-overlay.json (it loads later and overrides the same key); change both places
|
||||
ITEM_FILES = ('item-names.json', 'chinese-overlay.json')
|
||||
|
||||
|
||||
def text_hash(t):
|
||||
"""原文校验:游戏现行文字的 SHA-1 前 8 位(表里不存原文,只存这个,防原包换版本后照旧改)。 | Source-text check: first 8 characters of the SHA-1 of the game's current text (the table does not store the source text, only this, to prevent applying the same change after the original package changes version)."""
|
||||
return hashlib.sha1(t.encode('utf-8')).hexdigest()[:8]
|
||||
|
||||
|
||||
OLDNAMES = os.path.join(HERE, 'annot', 'oldnames.tsv')
|
||||
def old_rows():
|
||||
"""旧译名对照表的各行。表可以没有:公开仓库不带这份表(它是成套的他人译名),没有时「换回旧译名」这一步什么都不做,
|
||||
注释、点评、符文序号等其余步骤照常。自备一份放到 annot/oldnames.tsv 即启用,格式见该目录下的 README。
|
||||
Rows of the old-name table. The table may be absent: the public repository does not carry it (it is a complete set of someone else's translated names); without it the "switch back to old translated names" step does nothing,
|
||||
and the other steps (annotations, comments, rune numbers, etc.) run as usual. Put your own copy at annot/oldnames.tsv to enable it; for the format see the README in that directory."""
|
||||
if not os.path.isfile(OLDNAMES):
|
||||
if not getattr(old_rows, 'said', 0): old_rows.said = 1; print('annot_strings:没有旧译名对照表 %s,不换旧译名(其余注释照常)' % OLDNAMES, file=sys.stderr)
|
||||
return []
|
||||
return list(csv.DictReader(open(OLDNAMES, encoding='utf-8'), delimiter='\t'))
|
||||
|
||||
|
||||
def old_names(s):
|
||||
n = 0
|
||||
for row in old_rows():
|
||||
f, k = row['文件'] + '.json', row['键']
|
||||
new = row['旧译名'].replace('\\n', '\n')
|
||||
cur = s.get(f, k)
|
||||
if cur is None: raise SystemExit('annot_strings:%s 里没有键 %s' % (f, k))
|
||||
if text_hash(cur) != row['原文校验']: raise SystemExit('annot_strings:%s / %s 的原文变了(校验 %s,现行「%s」)——原包换了版本,核过再改表' % (f, k, row['原文校验'], cur))
|
||||
n += s.set(f, k, lambda _: new)
|
||||
return n
|
||||
|
||||
|
||||
def rune_numbers(s):
|
||||
"""符文名 = 中文短名 + 原版英文名 + 序号:r30 → 「贝 Ber #30」。背包说明与地上标签都用这个键;
|
||||
中文取符文之语配方里的短名 rNNL(已换旧译),英文取 rNNL 的 enUS 列。
|
||||
Rune name = Chinese short name + the original game's English name + number: r30 → 「贝 Ber #30」(Chinese short name, Ber, #30). The inventory description and the ground label both use this key;
|
||||
the Chinese comes from the short name rNNL in the runeword recipe (old translation already restored), the English from the enUS column of rNNL."""
|
||||
n = 0
|
||||
for i in range(1, 34):
|
||||
zh, en = s.get('item-runes.json', 'r%02dL' % i), s.get_lang('item-runes.json', 'r%02dL' % i, 'enUS')
|
||||
if not zh or not en or not re.fullmatch(r"[A-Za-z']+", en): raise SystemExit('annot_strings:r%02dL 的中 / 英短名不对:%r %r' % (i, zh, en))
|
||||
n += s.set('item-runes.json', 'r%02d' % i, lambda _, i=i, zh=zh, en=en: '%s %s #%d' % (zh, en, i))
|
||||
# 配方短名也带序号:rNNL 只被 gems.txt 的 letter 列引用,用在符文之语装备说明框的配方行,
|
||||
# 游戏把各符文短名直接拼进一对引号(实测「'奈夫提尔'」),所以序号后留一个空格分隔:「'乔#31 伊斯特#24 贝#30 '」
|
||||
# Recipe short names also carry the number: rNNL is referenced only by the letter column of gems.txt and is used in the recipe line of the runeword item tooltip;
|
||||
# the game concatenates the rune short names directly inside one pair of quotes (measured: 「'奈夫提尔'」('NefTir')), so one space is left after the number as a separator: 「'乔#31 伊斯特#24 贝#30 '」('Jah#31 Ist#24 Ber#30 ')
|
||||
n += s.set('item-runes.json', 'r%02dL' % i, lambda _, i=i, zh=zh: '%s#%d ' % (zh, i))
|
||||
return n
|
||||
|
||||
|
||||
def is_shield(code, types):
|
||||
seen = set()
|
||||
while code and code not in seen:
|
||||
if code == 'shld': return True
|
||||
seen.add(code); code = types.get(code, {}).get('Equiv1', '')
|
||||
return False
|
||||
|
||||
|
||||
def base_tiers(s, romfs):
|
||||
"""底材名后标档次:普 / 扩 / 精 = 该行 code 等于同行 normcode / ubercode / ultracode;
|
||||
身甲与盾类再标轻 / 中 / 重 = armor.txt 的 speed 列 0 / 5 / 10(跑步减速档)。例「神圣铠甲[精·中]」。
|
||||
Mark the tier after the base name: 「普 / 扩 / 精」(normal / exceptional / elite) = the row's code equals the same row's normcode / ubercode / ultracode;
|
||||
body armor and shields additionally get 「轻 / 中 / 重」(light / medium / heavy) = 0 / 5 / 10 in the speed column of armor.txt (run slowdown tier). Example: 「神圣铠甲[精·中]」(Sacred Armor [elite, medium])."""
|
||||
types = {r['Code']: r for r in excel(romfs, 'itemtypes.txt') if r.get('Code')}
|
||||
n = 0
|
||||
for tab in ('weapons.txt', 'armor.txt'):
|
||||
for r in excel(romfs, tab):
|
||||
c = r.get('code')
|
||||
if not c or r.get('spawnable') != '1' or r.get('quest') not in ('', '0') or r.get('type') == 'tpot': continue
|
||||
tier = '普' if c == r['normcode'] else '扩' if c == r['ubercode'] else '精' if c == r['ultracode'] else None
|
||||
if not tier: continue
|
||||
if tab == 'armor.txt' and (r['type'] == 'tors' or is_shield(r['type'], types)):
|
||||
tier += '·' + {'0': '轻', '5': '中', '10': '重'}[r['speed']]
|
||||
key = r['namestr'] or c
|
||||
for f in ITEM_FILES:
|
||||
n += s.set(f, key, lambda t, tier=tier: '%s[%s]' % (t, tier))
|
||||
return n
|
||||
|
||||
|
||||
def comments(s):
|
||||
"""暗金 / 套装 / 符文之语的一句点评(我们自己写的,按红叶点评的意思逐条重写、字面不照搬)。绿色一行,显示在名字下面、范围行上面:
|
||||
串 = [范围行\n]ÿc2点评\n<名字色>名字(游戏把多行名字倒着画,最后一行在最上面)。
|
||||
核对:点评里不许出现「已换回旧译名的技能」的 3.3 现行名(点评用换回后的名字),有就报错。
|
||||
A one-sentence review for uniques / sets / runewords (written by ourselves, rewritten entry by entry after the meaning of the Hongye community mod's reviews, wording not copied). One green line, shown below the name and above the range line:
|
||||
string = [range line\\
|
||||
]ÿc2review\\
|
||||
<name color>name (the game draws multi-line names in reverse, last line on top).
|
||||
Check: a review must not contain the 3.3 current name of "a skill already switched back to its old translated name" (reviews use the restored names); raise an error if it does."""
|
||||
renamed, orig = {}, Strings(s.romfs, s.repl) # orig:没改过的那份,取技能现行名 | orig: the unmodified copy, used to get the skills' current names
|
||||
for row in old_rows():
|
||||
if row['文件'] == 'skills' and row['键'].lower().startswith('skillname'):
|
||||
cur = orig.get('skills.json', row['键'])
|
||||
if cur and cur != row['旧译名']: renamed[cur] = row['旧译名']
|
||||
kept = {s.get('skills.json', k) for k in s.keys('skills.json') if k.lower().startswith('skillname')} # 换名后仍在用的名字(两个技能同名、只改了一个,如「专注」)不算错 | A name still in use after the rename (two skills shared a name and only one was changed, e.g. 「专注」(Concentration)) is not an error
|
||||
renamed = {a: b for a, b in renamed.items() if a not in kept}
|
||||
n = 0
|
||||
cp = os.path.join(HERE, 'annot', 'comments.tsv')
|
||||
if not os.path.isfile(cp): # 点评表可以没有(公开仓库不带:它是照别人的点评逐条改写的):没有就不加点评,其余注释照常。自备格式见 annot/README.md | the comments table may be absent (the public repository does not carry it: it was rewritten entry by entry from someone else's comments): without it no comments are added, and the other annotations are produced as usual. For the format of your own copy see annot/README.md
|
||||
print('annot_strings:没有点评表 %s,不加点评(其余注释照常)' % cp, file=sys.stderr); return 0
|
||||
for row in csv.DictReader(open(cp, encoding='utf-8'), delimiter='\t'):
|
||||
c, color = row['点评'], '\u00ffc2' if row['名字颜色'] == 'set' else '\u00ffc4'
|
||||
bad = [a for a in renamed if a in c and renamed[a] not in c]
|
||||
if bad: raise SystemExit('annot_strings:%s 的点评「%s」里有 3.3 现行技能名 %s(应写旧译名 %s)' % (row['键'], c, bad, [renamed[a] for a in bad]))
|
||||
def add(t, c=c, color=color):
|
||||
if '\n' in t: head, name = t.rsplit('\n', 1); return '%s\n\u00ffc2%s\n%s' % (head, c, name)
|
||||
return '\u00ffc2%s\n%s%s' % (c, color, t)
|
||||
files = ('item-runes.json', 'chinese-overlay.json') if row['文件'] == 'item-runes' else ITEM_FILES
|
||||
k = sum(s.set(f, row['键'], add) for f in files)
|
||||
if not k: raise SystemExit('annot_strings:点评的键 %s 在字符串表里没有' % row['键'])
|
||||
n += k
|
||||
return n
|
||||
|
||||
|
||||
def apply_all(s, romfs):
|
||||
"""全部步骤按次序做在同一个 Strings 上;返回 {步骤: 改了几处}。旧译名在前(后面的注释挂在换回后的名字上);
|
||||
掉落名最后(杂物类按规则表缩短 / 加色 / 加说明,在旧译名与符文序号之后)。
|
||||
All steps are applied in order to the same Strings; returns {step: number of changes}. Old translated names come first (later annotations attach to the restored names);
|
||||
drop names come last (miscellaneous items are shortened / colored / given descriptions by the rule table, after old translated names and rune numbers)."""
|
||||
from annot_ranges import ann_ranges
|
||||
from annot_world import ann_levels, ann_shrines
|
||||
from annot_drop import ann_drop
|
||||
return {'旧译名': old_names(s), '可变范围': ann_ranges(s, romfs), '点评': comments(s), '符文序号': rune_numbers(s), '底材档次': base_tiers(s, romfs),
|
||||
'区域等级': ann_levels(s, romfs), '神殿效果': ann_shrines(s, romfs),
|
||||
'掉落名': ann_drop(s, romfs)}
|
||||
|
||||
|
||||
# 普通文字框(TextBoxWidget)不认颜色码:游戏加载时把 ÿc 换成私用区字符 U+E07E,文字框原样画成「*5」、换行画成空格
|
||||
# (真机上编年史列表所见)。说明框(TooltipsPanel)、聊天(ChatListWidget)认。所以除了写进字符串表的注释版,再出一份「文字框版」:
|
||||
# 同一条流水线只做改名类步骤(旧译名、符文序号、底材档次、区域等级),不做装饰类步骤(可变范围行、点评行、神殿效果行、掉落名的缩写 / 颜色 / 说明行)。
|
||||
# 两份逐键对照,凡注释版带颜色码且与文字框版不同的,记一行「注释版 → 文字框版」(都换成运行时的 U+E07E 写法)。
|
||||
# 宿主在文字框写字入口(观测门 14,dm_textbox.c)只按这张表整串 / 子串替换:原版自带的串不在表里、一个字节都不动;注释开关关掉时没有这张表
|
||||
# Ordinary text boxes (TextBoxWidget) do not understand color codes: at load time the game replaces ÿc with the private-use character U+E07E, and the text box draws it verbatim as "*5" and draws newlines as spaces
|
||||
# (as seen in the chronicle list on a real device). The tooltip box (TooltipsPanel) and chat (ChatListWidget) do understand them. So besides the annotated version written into the string table, a "text-box version" is also produced:
|
||||
# the same pipeline does only the renaming steps (old translated names, rune numbers, base tiers, area levels) and not the decorative steps (variable range lines, review lines, shrine effect lines, and the abbreviations / colors / description lines of drop names).
|
||||
# The two are compared key by key; wherever the annotated version has color codes and differs from the text-box version, one line "annotated version → text-box version" is recorded (both converted to the runtime U+E07E form).
|
||||
# At the text-box write entry (observation gate 14, dm_textbox.c) the host only does whole-string / substring replacement by this table: the original game's own strings are not in the table and not a single byte of them is touched; when the annotation switch is off this table does not exist
|
||||
TEXTBOX_TABLE = 'dm_textbox_plain.tsv'
|
||||
TEXTBOX_STEPS = ('旧译名', '符文序号', '底材档次', '区域等级')
|
||||
_last_table = None
|
||||
|
||||
|
||||
def apply_textbox(s, romfs):
|
||||
from annot_world import ann_levels
|
||||
steps = {'旧译名': lambda: old_names(s), '符文序号': lambda: rune_numbers(s), '底材档次': lambda: base_tiers(s, romfs), '区域等级': lambda: ann_levels(s, romfs)}
|
||||
return {k: steps[k]() for k in TEXTBOX_STEPS}
|
||||
|
||||
|
||||
def textbox_table(full, plain):
|
||||
"""full / plain:同一组文件、同一组键的两份 Strings。返回 {运行时注释版: 运行时文字框版};同一注释版对到两种文字框版 = 生成器自相矛盾,报错。 | full / plain: two Strings over the same set of files and the same set of keys. Returns {runtime annotated version: runtime text-box version}; the same annotated version mapping to two different text-box versions = the generator contradicts itself, raise an error."""
|
||||
rt = lambda t: t.replace('\u00ffc', '\ue07e')
|
||||
# 同一个键在几份表里都有时,后加载的覆盖前面的(同 annot_drop:最后一份才是游戏里显示的):先按加载顺序取每个键的生效值
|
||||
# When the same key exists in several tables, the later-loaded one overrides the earlier ones (same as annot_drop: the last one is what the game displays): first take each key's effective value in load order
|
||||
from annot_drop import FILES as LOAD_ORDER
|
||||
order = [n for n in LOAD_ORDER if n in full.dirty] + sorted(n for n in full.dirty if n not in LOAD_ORDER)
|
||||
eff = {}
|
||||
for name in order:
|
||||
for key in full.keys(name):
|
||||
a, b = full.get(name, key), plain.get(name, key)
|
||||
if a is not None and b is not None: eff[(name if name not in LOAD_ORDER else '*', key)] = (a, b)
|
||||
tab, src = {}, {}
|
||||
for k, (a, b) in eff.items():
|
||||
if 'ÿc' not in a or a == b: continue
|
||||
ra, rb = rt(a), rt(b)
|
||||
if tab.get(ra, rb) != rb: raise SystemExit('annot_strings:注释版 %r 对到两种文字框版 %r(%s)/ %r(%s)' % (a, tab[ra], src[ra], rb, k))
|
||||
tab[ra] = rb; src[ra] = k
|
||||
return tab
|
||||
|
||||
|
||||
def write_textbox_table(dst):
|
||||
"""gen_romfs_overlay 写完带本特性的变体后调:把最近一次 build 算出的对照表写进变体目录(一行一条,键与值里的 \\ / 换行 / 制表转义)。 | Called by gen_romfs_overlay after it writes a variant with this feature: writes the mapping table computed by the most recent build into the variant directory (one entry per line; \\\\ / newline / tab in keys and values are escaped)."""
|
||||
if _last_table is None: raise SystemExit('annot_strings:还没 build 就写文字框对照表')
|
||||
esc = lambda t: t.replace('\\', '\\\\').replace('\n', '\\n').replace('\t', '\\t')
|
||||
with open(os.path.join(dst, TEXTBOX_TABLE), 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write('# 注释版\t文字框版(annot_strings.py 生成,宿主 dm_textbox.c 读)\n')
|
||||
for a in sorted(_last_table): f.write('%s\t%s\n' % (esc(a), esc(_last_table[a])))
|
||||
return len(_last_table)
|
||||
|
||||
|
||||
def build(romfs, outdir, repl):
|
||||
"""repl:前面步骤已换的 {包内逻辑路径: 本地文件}。返回 ({包内逻辑路径: 本地文件}, {步骤: 改了几处})。 | repl: {in-package logical path: local file} already replaced by earlier steps. Returns ({in-package logical path: local file}, {step: number of changes})."""
|
||||
global _last_table
|
||||
s = Strings(romfs, repl)
|
||||
stat = apply_all(s, romfs)
|
||||
p = Strings(romfs, repl); apply_textbox(p, romfs)
|
||||
_last_table = textbox_table(s, p); stat['文字框对照'] = len(_last_table)
|
||||
return s.write(outdir), stat
|
||||
|
||||
if __name__ == '__main__': # 单独跑:python3 annot_strings.py <RomFS> <输出目录> → 打印统计 | Standalone run: python3 annot_strings.py <RomFS> <output dir> → prints statistics
|
||||
import sys
|
||||
os.makedirs(sys.argv[2], exist_ok=True)
|
||||
r, st = build(sys.argv[1], sys.argv[2], {})
|
||||
print(st); [print(k, '→', v) for k, v in r.items()]
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""区域、怪物、神殿名称注释。 | Annotations for area, monster and shrine names."""
|
||||
from collections import defaultdict
|
||||
|
||||
def _number(row, key):
|
||||
value = row.get(key, '')
|
||||
return int(value or 0)
|
||||
|
||||
|
||||
def _groups(rows, key, fields):
|
||||
groups = defaultdict(list)
|
||||
for row in rows:
|
||||
if row.get(key):
|
||||
groups[row[key]].append(tuple(row.get(field, '') for field in fields))
|
||||
return groups
|
||||
|
||||
|
||||
def ann_levels(s, romfs):
|
||||
from annot_strings import excel
|
||||
|
||||
fields = ('MonLvlEx', 'MonLvlEx(N)', 'MonLvlEx(H)')
|
||||
groups = _groups(excel(romfs, 'levels.txt'), 'LevelName', fields)
|
||||
skipped = []
|
||||
changed = 0
|
||||
for key, values in groups.items():
|
||||
unique = set(values)
|
||||
if len(unique) > 1:
|
||||
skipped.append(key)
|
||||
continue
|
||||
levels = tuple(_number(dict(zip(fields, values[0])), field) for field in fields)
|
||||
if levels == (0, 0, 0):
|
||||
continue
|
||||
changed += s.set('levels.json', key, lambda text, levels=levels: '%s[%d/%d/%d]' % (text, *levels))
|
||||
if skipped:
|
||||
print('ann_levels:同键多值,跳过:%s' % '、'.join(sorted(skipped)))
|
||||
return changed
|
||||
|
||||
|
||||
def _duration(row):
|
||||
frames = _number(row, 'Duration in frames')
|
||||
return '%d 秒' % (frames // 25) if frames else ''
|
||||
|
||||
|
||||
def _reset(row):
|
||||
value = row.get('reset time in minutes', '')
|
||||
return '刷新时间 %s 分钟' % value if value else '不会刷新'
|
||||
|
||||
|
||||
def _shrine_effect(row):
|
||||
code = row['Code']
|
||||
arg0, arg1 = row.get('Arg0', ''), row.get('Arg1', '')
|
||||
duration, reset = _duration(row), _reset(row)
|
||||
if code == '1':
|
||||
effect = '生命和法力全满'
|
||||
elif code == '2':
|
||||
effect = '生命全满'
|
||||
elif code == '3':
|
||||
effect = '法力全满'
|
||||
elif code == '4':
|
||||
effect = '用当前生命的 %s%% 恢复法力,最多 %s' % (arg0, arg1)
|
||||
elif code == '5':
|
||||
effect = '用当前法力的 %s%% 恢复生命,最多 %s' % (arg0, arg1)
|
||||
elif code == '6':
|
||||
effect = '+%s%% 防御' % arg0
|
||||
elif code == '7':
|
||||
effect = '+%s%% 准确率,+%s%% 伤害' % (arg0, arg1)
|
||||
elif code in ('8', '9', '10', '11'):
|
||||
effect = '+%s%% %s' % (arg0, {'8': '抗火', '9': '抗冰', '10': '抗电', '11': '抗毒'}[code])
|
||||
elif code == '12':
|
||||
effect = '+%s 所有技能' % arg0
|
||||
elif code == '13':
|
||||
effect = '+%s%% 法力重生' % arg0
|
||||
elif code == '14':
|
||||
effect = '无限耐力'
|
||||
elif code == '15':
|
||||
effect = '经验+%s%%' % arg0
|
||||
elif code == '16':
|
||||
effect = '颠倒角色名称'
|
||||
elif code == '17':
|
||||
effect = '生成一个回家的传送门'
|
||||
elif code == '18':
|
||||
effect = '随机把背包中的一颗宝石提升一级;没有宝石则生成一颗最低级宝石'
|
||||
elif code == '19':
|
||||
effect = '爆发火焰,使周围所有单位失去 %s%% 生命' % arg0
|
||||
elif code == '20':
|
||||
effect = '使最近的怪物升级为精英或冠军怪'
|
||||
elif code == '21':
|
||||
effect = '获得 %s-%s 个爆炸药剂,并使周围产生爆炸' % (arg0, arg1)
|
||||
elif code == '22':
|
||||
effect = '获得 %s-%s 个窒息气体药剂,并在周围产生毒雾' % (arg0, arg1)
|
||||
else:
|
||||
effect = row['*Effect']
|
||||
details = [effect]
|
||||
if reset:
|
||||
details.append(reset)
|
||||
if duration:
|
||||
details.append('持续 %s' % duration)
|
||||
return ','.join(details)
|
||||
|
||||
|
||||
def ann_shrines(s, romfs):
|
||||
from annot_strings import excel
|
||||
|
||||
changed = 0
|
||||
for row in excel(romfs, 'shrines.txt'):
|
||||
key = row.get('StringName')
|
||||
if not key or key == 'ShrId0' or '(Not Used)' in row.get('*Effect', ''): # 表里标了不用的(生命 / 法力交换、颠倒名字)游戏不生成,不加 | Those marked unused in the table (life / mana exchange, reversed names) are not generated by the game; not added
|
||||
continue
|
||||
effect = _shrine_effect(row)
|
||||
changed += s.set('shrines.json', key, lambda text, effect=effect: 'ÿc5%s\nÿc0%s' % (effect, text))
|
||||
return changed
|
||||
@@ -0,0 +1,17 @@
|
||||
# App Store Connect API 密钥口径(TestFlight 用)。只放编号,不放密钥:
|
||||
# ~/.appstoreconnect/dm.env:ASC_KEY_ID=… ASC_ISSUER=… ASC_APP_ID=…(App 的数字编号)
|
||||
# 密钥文件:~/.appstoreconnect/private_keys/AuthKey_<ASC_KEY_ID>.p8(600;altool 缺省也在这里找)
|
||||
# asc_auth:有密钥就把 xcodebuild 的 API 认证参数放进数组 ASC_AUTH,没有就留空(开发机照旧用本地描述文件)
|
||||
# App Store Connect API key conventions (for TestFlight). Only IDs go here, not the key:
|
||||
# ~/.appstoreconnect/dm.env: ASC_KEY_ID=... ASC_ISSUER=... ASC_APP_ID=... (the App's numeric ID)
|
||||
# Key file: ~/.appstoreconnect/private_keys/AuthKey_<ASC_KEY_ID>.p8 (600; altool also looks here by default)
|
||||
# asc_auth: if a key exists, put the xcodebuild API authentication arguments into the array ASC_AUTH; otherwise leave it empty (development machines keep using local provisioning profiles)
|
||||
ASC_ENV=${DM_ASC_ENV:-$HOME/.appstoreconnect/dm.env}
|
||||
asc_auth() {
|
||||
ASC_AUTH=()
|
||||
[ -f "$ASC_ENV" ] || return 0
|
||||
source "$ASC_ENV"
|
||||
ASC_KEY=$HOME/.appstoreconnect/private_keys/AuthKey_${ASC_KEY_ID}.p8
|
||||
[ -f "$ASC_KEY" ] || { echo "🔴 缺 API 密钥文件 $ASC_KEY"; return 1; }
|
||||
ASC_AUTH=(-authenticationKeyPath "$ASC_KEY" -authenticationKeyID "$ASC_KEY_ID" -authenticationKeyIssuerID "$ASC_ISSUER")
|
||||
}
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""给资源直接下载(Sources/asset_dl.m)出下载站目录:asset_manifest.py <资源文件夹(含 data/)> <下载站里的 assets 目录>
|
||||
生成 <assets>/manifest.json(每个文件的名字、字节数、SHA-256;.holes 区段表当普通文件一起列)并把 <assets>/data 软链到资源正本(不拷第二份)。
|
||||
校验值按(字节数, 修改时刻)缓存在 <assets> 旁的 .asset_sha.json,资源没变时重出清单不重算 4 GB。
|
||||
Produce the download-site directory for direct asset download (Sources/asset_dl.m): asset_manifest.py <asset folder (containing data/)> <assets directory in the download site>
|
||||
Generates <assets>/manifest.json (each file's name, byte count, SHA-256; the .holes extent table is listed as an ordinary file) and symlinks <assets>/data to the master copy of the assets (no second copy).
|
||||
Checksums are cached by (byte count, modification time) in .asset_sha.json next to <assets>, so regenerating the manifest when the assets are unchanged does not recompute 4 GB."""
|
||||
import hashlib, json, os, sys
|
||||
src, out = os.path.realpath(os.path.join(sys.argv[1], "data")), sys.argv[2]
|
||||
os.makedirs(out, exist_ok=True)
|
||||
cache_p = os.path.join(os.path.dirname(os.path.abspath(out)), ".asset_sha.json")
|
||||
try: cache = json.load(open(cache_p))
|
||||
except Exception: cache = {}
|
||||
files, total = [], 0
|
||||
for nm in sorted(os.listdir(src)):
|
||||
p = os.path.join(src, nm)
|
||||
if nm.startswith(".") or not os.path.isfile(p): continue
|
||||
st = os.stat(p); key = f"{p}|{st.st_size}|{st.st_mtime_ns}"
|
||||
if key not in cache:
|
||||
h = hashlib.sha256()
|
||||
with open(p, "rb") as f:
|
||||
while b := f.read(1 << 22): h.update(b)
|
||||
cache[key] = h.hexdigest()
|
||||
files.append({"name": nm, "size": st.st_size, "sha256": cache[key]}); total += st.st_size
|
||||
json.dump({k: v for k, v in cache.items() if k.split("|")[0].startswith(src)}, open(cache_p, "w"))
|
||||
json.dump({"version": 1, "total": total, "files": files}, open(os.path.join(out, "manifest.json"), "w"), indent=0)
|
||||
link = os.path.join(out, "data")
|
||||
if os.path.islink(link): os.unlink(link)
|
||||
os.symlink(src, link)
|
||||
print(f"清单 {len(files)} 个文件共 {total} 字节 → {out}/manifest.json;data → {src}")
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!/bin/bash
|
||||
# 真机启动时间线(DM_BOOTPROF ⓪–⑥ 分段):冷启动 1 局(重装后首启:代码页冷;RomFS 可能仍在系统文件缓存里——真冷要重启手机,不做)+ 热启动 N 局。
|
||||
# 用法:[DM_OUT=产物] dm/ios/tools/bootprof.sh [热局数=3] 或 --metal-cold [局数=3]
|
||||
# Real-device boot timeline (DM_BOOTPROF segments ⓪–⑥): 1 cold-start run (first launch after reinstall: code pages cold; the RomFS may still be in the system file cache - truly cold needs a phone reboot, not done) + N warm-start runs.
|
||||
# Usage: [DM_OUT=build output] dm/ios/tools/bootprof.sh [warm runs=3] or --metal-cold [runs=3]
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
METAL_COLD=0
|
||||
if [ "${1:-}" = "--metal-cold" ]; then METAL_COLD=1; N=${2:-3}; else N=${1:-3}; fi
|
||||
source tools/local_env.sh && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}; RUN_ROOT=${DM_ROOT:-$HOME/dm-work}/run/ios; R=$RUN_ROOT/bootprof; mkdir -p $R; rm -f $R/*.log
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
INGAME_KEYS='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame' # 同 smoke.sh | Same as smoke.sh
|
||||
if [ "$METAL_COLD" -eq 1 ]; then
|
||||
case "$N" in ''|*[!0-9]*|0) t "🔴 局数必须是正整数"; exit 1;; esac
|
||||
fi
|
||||
source tools/devlock.sh
|
||||
devlock_acquire "bootprof"
|
||||
trap devlock_release EXIT
|
||||
./run.sh build > $R/build.log 2>&1 || { t "🔴 构建失败"; tail -5 $R/build.log; exit 1; }
|
||||
./run.sh install >> $R/build.log 2>&1 || { t "🔴 装机失败"; tail -5 $R/build.log; exit 1; }
|
||||
if [ "$METAL_COLD" -eq 1 ]; then
|
||||
for kind in cold hot; do
|
||||
for k in $(seq 1 $N); do
|
||||
name=${kind}${k}; cold_env=()
|
||||
[ "$kind" = cold ] && cold_env=(DEVICECTL_CHILD_DM_METAL_COLD=1)
|
||||
# 冷 / 热都按冒烟同一键序进局(标准存档新副本),量「进局读取」= ToGame → 读取画面撤下(冷缓存下预热编管线会不会拉长读取)
|
||||
# Cold / warm both enter the run with the same key sequence as the smoke test (fresh copy of the standard save), measuring "run-entry loading" = ToGame → loading screen removed (whether warm-up pipeline compilation under a cold cache lengthens loading)
|
||||
env -u DEVICECTL_CHILD_DM_METAL_COLD "${cold_env[@]}" DEVICECTL_CHILD_DM_SAVE_FRESH=warlock DEVICECTL_CHILD_DM_KEYS="$INGAME_KEYS" DEVICECTL_CHILD_DM_UIMSG=1 DEVICECTL_CHILD_DM_BOOTPROF=1 DEVICECTL_CHILD_DM_WATCH=40 ./run.sh boot 60 > $R/$name.run 2>&1 || { t "🔴 $name 启动失败"; exit 1; }
|
||||
cp $RUN_ROOT/out/boot.txt $R/$name.log || { t "🔴 $name 日志读取失败"; exit 1; }
|
||||
grep -q "⑥" $R/$name.log || t "🔴 $name 没出分段表(看 $R/$name.log)"
|
||||
done
|
||||
done
|
||||
else
|
||||
for k in $(seq 0 $N); do
|
||||
name=hot$k; [ $k = 0 ] && name=cold
|
||||
DEVICECTL_CHILD_DM_SAVE_FRESH=1 DEVICECTL_CHILD_DM_UIMSG=1 DEVICECTL_CHILD_DM_BOOTPROF=1 DEVICECTL_CHILD_DM_WATCH=8 ./run.sh boot 40 > $R/$name.run 2>&1
|
||||
cp $RUN_ROOT/out/boot.txt $R/$name.log
|
||||
grep -q "⑥" $R/$name.log || t "🔴 $name 没出分段表(看 $R/$name.log)"
|
||||
done
|
||||
fi
|
||||
python3 - $R $N $METAL_COLD <<'PY'
|
||||
import sys, re, statistics
|
||||
R, N, metal_flag = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
|
||||
metal_cold = metal_flag == 1
|
||||
names = ([f'cold{k}' for k in range(1, N + 1)] + [f'hot{k}' for k in range(1, N + 1)]) if metal_cold else ['cold'] + [f'hot{k}' for k in range(1, N + 1)]
|
||||
seg = {}
|
||||
metal = {}
|
||||
cleared = set()
|
||||
errors = []
|
||||
togame = {}; ingame = {}
|
||||
for n in names:
|
||||
for l in open(f'{R}/{n}.log', errors='replace'):
|
||||
m = re.match(r'\[dm\] ([⓪①②③④⑤⑥]b?) (.+?)\s{2,}([\d.]+)\s+([\d.]+)', l)
|
||||
if m: seg.setdefault((m[1], m[2].strip()), {})[n] = (float(m[3]), float(m[4]))
|
||||
m = re.search(r'METALCACHE 现存 (\d+) 个 (\d+) 字节', l) # 每个目标目录一行,按局加总(只取最后一行会把旧位置的 0 当成全量,热局误报 0)
|
||||
if m and n not in cleared: f0, b0 = metal.get(n, (0, 0)); metal[n] = (f0 + int(m[1]), b0 + int(m[2]))
|
||||
m = re.search(r'METALCACHE 已清 (\d+) 个 (\d+) 字节 → 现存 (\d+) 个', l)
|
||||
if m:
|
||||
metal[n] = (int(m[1]), int(m[2]))
|
||||
if int(m[3]) == 0: cleared.add(n)
|
||||
else: errors.append(f'{n} 清后文件数 {m[3]} 越线(要求 0)')
|
||||
if metal_cold and 'METALCACHE 【红】' in l: errors.append(f'{n}: {l.strip()}')
|
||||
m = re.search(r'UIMSG \[([\d.]+)s\] FrontEndNavigation ToGame', l)
|
||||
if m and n not in togame: togame[n] = float(m[1])
|
||||
m = re.search(r'UIMSG \[([\d.]+)s\] PanelManager (?:UnloadPanel|ClosePanel) LoadScreenPanel', l)
|
||||
if m and n in togame and n not in ingame: ingame[n] = float(m[1]) - togame[n]
|
||||
print('段 | ' + ' | '.join(names) + '(各段用时 s,括号内累计)')
|
||||
for (k, name), v in seg.items():
|
||||
print(f'{k} {name} | ' + ' | '.join(f'{v[n][0]:.3f}({v[n][1]:.3f})' if n in v else '—' for n in names))
|
||||
for n in names:
|
||||
tot = max((v[n][1] for v in seg.values() if n in v), default=0)
|
||||
d4 = next((v[n][0] for (k, _), v in seg.items() if k == '④' and n in v), 0); d5 = next((v[n][0] for (k, _), v in seg.items() if k == '⑤' and n in v), 0)
|
||||
print(f'{n}:到 Ribbon {tot:.3f} s;④ {d4:.3f} s({d4 / tot * 100 if tot else 0:.0f}%)⑤ {d5:.3f} s({d5 / tot * 100 if tot else 0:.0f}%)')
|
||||
if metal_cold:
|
||||
for n in names:
|
||||
present = {k for (k, _), values in seg.items() if n in values}
|
||||
missing = set('⓪①②③④⑤⑥') - present
|
||||
if missing: errors.append(f'{n} 缺分段:{"".join(sorted(missing))}')
|
||||
if n not in metal: errors.append(f'{n} 缺 METALCACHE 读数')
|
||||
else: print(f'{n} METALCACHE 删前/启动前:{metal[n][0]} 个 {metal[n][1]} 字节')
|
||||
if n.startswith('cold') and n not in cleared: errors.append(f'{n} 未确认清零')
|
||||
if n not in ingame: errors.append(f'{n} 缺进局读取读数(ToGame / 读取画面撤下)')
|
||||
else: print(f'{n} 进局读取(ToGame → 读取画面撤下){ingame[n]:.2f} s')
|
||||
if errors:
|
||||
for error in errors: print(f'🔴 {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
for kind in ('cold', 'hot'):
|
||||
group = [n for n in names if n.startswith(kind)]
|
||||
totals = [max((v[n][1] for v in seg.values() if n in v), default=0) for n in group]
|
||||
print(f'{kind} 进局读取中位数:{statistics.median([ingame[n] for n in group]):.2f} s')
|
||||
print(f'{kind} 中位数({len(group)}/{N} 局):总用时 {statistics.median(totals):.3f} s;METALCACHE 删前/启动前 {statistics.median([metal[n][0] for n in group]):g} 个 {statistics.median([metal[n][1] for n in group]):g} 字节')
|
||||
for (key, label), values in seg.items():
|
||||
duration = [values[n][0] for n in group if n in values]
|
||||
cumulative = [values[n][1] for n in group if n in values]
|
||||
if len(duration) != N:
|
||||
print(f'🔴 {kind} {key} 分段覆盖 {len(duration)}/{N}', file=sys.stderr); sys.exit(1)
|
||||
print(f'{kind} {key} {label} 中位数:{statistics.median(duration):.3f}({statistics.median(cumulative):.3f})')
|
||||
PY
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
# 选角页回归(Mac 上的 iOS 包,真实触点路径):四行各「点一次 → 再点两次 → 进入游戏」,核进的是该行的角色、期间没有发 CharacterSelect:SelectCharacter。
|
||||
# 来由:换成键鼠版选角页后,再点已高亮的行会发「确认选择」、列表收起重开后高亮换了人,「进入游戏」进错角色。
|
||||
# 认角色用进局后读到的等级:标准存档 save_ref_warlock 里四个角色等级各不相同(列表顺序 joe 76 / Warlock 1 / joebao 9 / 法师 88);换存档要改 WANT。
|
||||
# 用法:charsel_retap.sh <结果目录>。先跑过 smoke_mac.sh(要有包好的 .iosdd_mac/DmMacSmoke.app)。全过返回 0。
|
||||
# Character select page regression (iOS app on Mac, real touch point path): for each of the four rows, "tap once → tap twice more → enter game", check that the character entered is that row's and that no CharacterSelect:SelectCharacter was sent in between.
|
||||
# Background: after switching to the keyboard-and-mouse character select page, tapping an already highlighted row again sends 「确认选择」(confirm selection), the list collapses and reopens with the highlight on someone else, and 「进入游戏」(Play) enters the wrong character.
|
||||
# Characters are identified by the level read after entering the run: the four characters in the standard save save_ref_warlock all have different levels (list order joe 76 / Warlock 1 / joebao 9 / 「法师」(Mage) 88); change WANT when changing the save.
|
||||
# Usage: charsel_retap.sh <result dir>. Run smoke_mac.sh first (the packaged .iosdd_mac/DmMacSmoke.app must exist). Returns 0 if all pass.
|
||||
set -u
|
||||
OUT=${1:?用法:charsel_retap.sh <结果目录>}; TOOLS=$(cd "$(dirname "$0")" && pwd); mkdir -p "$OUT"; WANT=(76 1 9 88); YS=(47 92 128 165); bad=0
|
||||
for r in 0 1 2 3; do y=${YS[$r]}
|
||||
printf '4.0 down 0 803,%s\n4.1 up 0\n5.8 down 0 803,%s\n5.9 up 0\n7.6 down 0 803,%s\n7.7 up 0\n10.0 down 0 478,395\n10.1 up 0\n12.0 down 0 478,163\n12.1 up 0\n' $y $y $y > "$OUT/t$r.txt"
|
||||
E2E_REF=956x440 E2E_KEYS='B@OpenPanel:NoSuchPanelEver' E2E_ENV='{"DM_TOUCH_SCRIPT_START":"menu","DM_FE_AUTO":"1"}' bash "$TOOLS/touch_e2e_mac.sh" "$OUT/t$r.txt" "$OUT/r$r" 26 > "$OUT/r$r.out" 2>&1
|
||||
sel=$(LC_ALL=C grep -a -c 'UIMSG.*CharacterSelect SelectCharacter' "$OUT/r$r/boot.txt" 2>/dev/null); lv=$(LC_ALL=C grep -a 'dm_hud' "$OUT/r$r/boot.txt" 2>/dev/null | LC_ALL=C grep -a -o 'Lv [0-9]*' | awk '$2>0{print $2; exit}')
|
||||
if [ "${sel:-1}" = 0 ] && [ "${lv:-}" = "${WANT[$r]}" ]; then echo "第 $((r+1)) 行 OK:进局等级 ${lv},SelectCharacter 0 条"; else echo "【红】第 $((r+1)) 行:进局等级「${lv:-没进局}」(应为 ${WANT[$r]}),SelectCharacter ${sel:-?} 条"; bad=1; fi
|
||||
done
|
||||
[ $bad = 0 ] && echo "CHARSEL-RETAP OK 4/4" || echo "CHARSEL-RETAP RED"; exit $bad
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
# 原版衍生物不入库(凡由原版表或图生成的都不进仓库,构建时从玩家自己的游戏文件生成,见 dm/README.md「从你的游戏文件生成资源」):
|
||||
# ① git 里不许再出现这些生成物(被人手动加回来就红);② 本机有游戏文件时把底部 UI v4 实际生成一遍,跑不通就红(生成链最长的一条)。
|
||||
# 用法:check_hud_gen.sh 退出 0 = 通过或跳过 ②,1 = 有生成物入库 / 生成失败
|
||||
# Derivatives of the original game are not checked in (anything generated from the original game's tables or images stays out of the repository and is generated at build time from the player's own game files, see dm/README.md 「从你的游戏文件生成资源」(Generate assets from your game files)):
|
||||
# ① these generated files must not reappear in git (fails if someone manually adds them back); ② when the local machine has game files, actually generate bottom UI v4 once, and fail if that fails (the longest generation chain).
|
||||
# Usage: check_hud_gen.sh exit 0 = passed or ② skipped, 1 = generated files checked in / generation failed
|
||||
set -uo pipefail
|
||||
I="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"; W="$(cd "$I/../.." && pwd)"
|
||||
BAD=$(git -C "$W" ls-files -- dm/ios/NativeHUD/v4 dm/ios/NativeHUD/mapgoal dm/ios/NativeHUD/widestash dm/ios/NativeHUD/pouch dm/ios/NativeHUD/touch/fe_rightpanel.* \
|
||||
'dm/ios/Sources/TouchArt/dm_native_*' dm/ios/Sources/dm_touch_native_art.c dm/host/dm_vault_tab.h dm/host/dm_hud_exp.h dm/host/dm_bright_levels.inc dm/ios/tools/touchrectv1_HUDPanelHD.json dm/ios/tools/native_art/skills.txt dm/ios/tools/native_art/skilldesc.txt)
|
||||
[ -z "$BAD" ] || { echo "HUDGEN 红:原版衍生的生成物进了仓库(应该构建时从游戏文件生成):"; echo "$BAD" | sed 's/^/ /'; exit 1; }
|
||||
R=${DM_ROMFS_SRC:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/RomFS}
|
||||
[ -f "$R/data/build_manifest.psv" ] || { echo "HUDGEN OK(入库检查);生成检查跳过:这台机器没有游戏文件 $R"; exit 0; }
|
||||
T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
|
||||
python3 "$I/tools/native_art/generate.py" "$R" > "$T.art.log" 2>&1 || { echo "HUDGEN 红:技能图集生成不通(底栏要用它)"; tail -3 "$T.art.log"; exit 1; } # 底栏的技能图标取自技能图集(Sources/TouchArt,git 忽略);干净的树里没有,先生成 | The bottom bar's skill icons come from the skill atlas (Sources/TouchArt, git-ignored); a clean tree has none, so generate it first
|
||||
python3 "$I/tools/gen_hud_v4.py" "$R" "$T" > "$T.log" 2>&1 || { echo "HUDGEN 红:gen_hud_v4.py 跑不通"; tail -3 "$T.log"; exit 1; }
|
||||
n=$(find "$T" -type f | wc -l | tr -d ' '); [ "$n" -ge 79 ] || { echo "HUDGEN 红:底部 UI v4 只生成了 $n 个文件(应 79)"; exit 1; }
|
||||
echo "HUDGEN OK:生成物没有入库;底部 UI v4 从游戏文件生成 $n 个文件$(grep -q '^没找到 PC' "$T.log" && echo '(Switch 素材放大版)')"
|
||||
@@ -0,0 +1,40 @@
|
||||
# 本机起 iOS 包的总闸:不许连真实 iCloud。被 smoke_mac.sh、touch_e2e_mac.sh、uireg/run_mac.sh source。
|
||||
# 为什么要有:iCloud 同步只按路径认「真存档」(DM_SAVE == Documents/save,cloud_ios.m 的 dm_cloud_boot)。开发机登着真实账号时,
|
||||
# Mac 上跑的 iOS 包就是那个账号的又一台设备——测试存档换到这个路径、或者测试局改了这个路径下的角色,都会被传进真实云端。
|
||||
# 做法:每一局都带 DM_TEST_ICLOUD_OFF=1(cloud_ios.m:整个不同步);跑完再核启动日志,出现任何同步动作就报红。
|
||||
# 不用「指到一次性本地目录」的办法:那会让本来不同步的测试存档开始同步,同一脚本里前一个实例传上去的角色会被后一个空存档实例下载回来。
|
||||
# cloud_guard_env <Documents 目录> [调用方已带的环境,空格分隔的 K=V]
|
||||
# 设好 CG_ENV(要加给 open 的那一条 K=V;调用方自己指了本地云端目录——iCloud 用例——时为空)。返回非零 = 这一局不许起(已打印红字)。
|
||||
# cloud_guard_check <启动日志> 本该不同步的局出现了同步动作 → 返回非零并打印红字
|
||||
# cloud_guard_clean <Documents 目录> 留给调用方收尾时调(现在没有要清的东西)
|
||||
# 真要测真实 iCloud:DM_REAL_ICLOUD=1 且 DM_REAL_ICLOUD_CONFIRM=写入真实云端 两个都给才放开,放开时每局打印红字提醒。
|
||||
# Master gate for launching the iOS app on this Mac: connecting to real iCloud is not allowed. Sourced by smoke_mac.sh, touch_e2e_mac.sh and uireg/run_mac.sh.
|
||||
# Why it exists: iCloud sync recognizes the "real save" by path only (DM_SAVE == Documents/save, dm_cloud_boot in cloud_ios.m). When the development machine is signed in to a real account,
|
||||
# the iOS app running on the Mac is one more device of that account -- a test save swapped into this path, or a test run modifying a character under this path, gets uploaded to the real cloud.
|
||||
# What it does: every run carries DM_TEST_ICLOUD_OFF=1 (cloud_ios.m: no sync at all); after the run the launch log is checked, and any sync action is reported as a failure.
|
||||
# The "point it at a one-off local directory" approach is not used: that would make test saves that otherwise do not sync start syncing, and a character uploaded by an earlier instance in the same script would be downloaded back by a later empty-save instance.
|
||||
# cloud_guard_env <Documents directory> [environment the caller already carries, space-separated K=V]
|
||||
# Sets CG_ENV (the K=V to add to open; empty when the caller specified a local cloud directory itself -- iCloud cases). Non-zero return = this run must not start (red text already printed).
|
||||
# cloud_guard_check <launch log> a sync action appeared in a run that should not sync → returns non-zero and prints red text
|
||||
# cloud_guard_clean <Documents directory> for the caller to call at wrap-up (currently there is nothing to clean)
|
||||
# To really test real iCloud: it is opened up only when both DM_REAL_ICLOUD=1 and DM_REAL_ICLOUD_CONFIRM=写入真实云端 are given, and when opened up a red reminder is printed for every run.
|
||||
CG_ENV=; CG_REAL=; CG_LOCAL=
|
||||
cloud_guard_env() {
|
||||
CG_ENV=; CG_REAL=; CG_LOCAL=
|
||||
if [ "${DM_REAL_ICLOUD:-}" = 1 ]; then
|
||||
[ "${DM_REAL_ICLOUD_CONFIRM:-}" = "写入真实云端" ] || { echo "【红】DM_REAL_ICLOUD=1 还要同时给 DM_REAL_ICLOUD_CONFIRM=写入真实云端 才放开;这一局不起" >&2; return 1; }
|
||||
echo "【红】本局连的是真实 iCloud(DM_REAL_ICLOUD=1):Documents/save 里的改动会同步到这个账号的所有设备" >&2; CG_REAL=1; return 0
|
||||
fi
|
||||
case " ${2:-} " in
|
||||
*" DM_TEST_ICLOUD_SUB="*) echo "【红】DM_TEST_ICLOUD_SUB 走的是真实 iCloud 容器,没有显式放开(DM_REAL_ICLOUD)不许带;这一局不起" >&2; return 1;;
|
||||
*" DM_TEST_ICLOUD_DIR="*|*" DM_TEST_ICLOUD_ROOT="*) CG_LOCAL=1; return 0;; # 调用方自己指了本地目录(iCloud 用例) | The caller specified a local directory itself (iCloud cases)
|
||||
esac
|
||||
CG_ENV="DM_TEST_ICLOUD_OFF=1"
|
||||
}
|
||||
cloud_guard_check() {
|
||||
[ "$CG_REAL" = 1 ] || [ "$CG_LOCAL" = 1 ] && return 0 # 显式放开的、调用方自己指了本地目录的:不核 | Explicitly opened up, or the caller specified a local directory itself: not checked
|
||||
local bad; bad=$(LC_ALL=C grep -a -E 'iCloud 同步:(启动 |.* 上传(|.* 下载(|.*记删除标记)' "$1" 2>/dev/null | head -1)
|
||||
[ -z "$bad" ] && return 0
|
||||
echo "【红】这一局本该不同步,却出现了 iCloud 同步动作:$(echo "$bad" | cut -c1-160)。可能已写进真实云端,立刻停下报告,别再起局" >&2; return 1
|
||||
}
|
||||
cloud_guard_clean() { return 0; }
|
||||
@@ -0,0 +1,58 @@
|
||||
# 测试机电量闸(测试 iPhone 01:46 没电关机、断到 09:26——插在 Mac 上供电跟不上,屏幕常亮 10 小时电量一路掉到 1%)。
|
||||
# 用法:source 本文件后 devbattery_gate || exit 1(真机局取设备锁之前调)。读法:ideviceinfo 电池域(USB 不通再走网络 -n)。
|
||||
# 电量 < 30%:落暂停标记 $DM_ROOT/run/ios/device_low_battery、记【红】、记进 $DM_ROOT/run/ios/device_alert.txt,拒绝开跑(返回 1),之后所有真机局都拒绝;
|
||||
# 有暂停标记时电量 ≥ 60% 才撤标记放行(充电中途 30%–60% 一律拒绝,免得刚过线又跑没电);
|
||||
# 插着电却没在充、且电量低于 90% 才记【红】提醒(供电跟不上),但不拦——系统在高电量下会自己停充(全天停在 99–100%、「充电=0」,旧判据「低于 100%」整下午误报);读不到电量记【红】并拒绝(多半设备已离线)。
|
||||
# 放行时把「电量 N%(充电 / 未充电,电源 有 / 无)」写进 DEVBATTERY_LINE,调用方记进表头 / 日志;每次读数追加到 $DM_ROOT/run/ios/battery.log。
|
||||
# 测试开关:DEVBATTERY_FAKE="<电量> <充电 0/1> <电源 0/1>" 不读设备,直接用这组数(单测 devbattery_test.sh 用)。
|
||||
# Battery gate for the test device (the test iPhone ran out of power and shut down at 01:46 and stayed offline until 09:26: power from the Mac it was
|
||||
# plugged into could not keep up, and with the screen always on for 10 hours the charge fell all the way to 1%).
|
||||
# Usage: after sourcing this file, devbattery_gate || exit 1 (call it before taking the device lock for a real-device run). How it reads: the
|
||||
# ideviceinfo battery domain (falls back to network -n if USB is unavailable).
|
||||
# Charge < 30%: drops the pause marker $DM_ROOT/run/ios/device_low_battery, logs [RED], records it in $DM_ROOT/run/ios/device_alert.txt, and refuses
|
||||
# to start (returns 1); every real-device run after that is refused too;
|
||||
# with the pause marker present, the marker is removed and runs are allowed only at charge ≥ 60% (30%–60% in the middle of charging is always refused,
|
||||
# so a run does not drain the device again right after crossing the line);
|
||||
# plugged in but not charging, and charge below 90%: only then log [RED] as a warning (power cannot keep up), without blocking. The system stops
|
||||
# charging by itself at high charge (sitting at 99–100% all day with "charging=0"; the old criterion "below 100%" raised false alarms all afternoon).
|
||||
# If the charge cannot be read, log [RED] and refuse (most likely the device is offline).
|
||||
# When a run is allowed, "charge N% (charging / not charging, power present / absent)" is written into DEVBATTERY_LINE for the caller to put in the
|
||||
# table header / log; every reading is appended to $DM_ROOT/run/ios/battery.log.
|
||||
# Test switch: DEVBATTERY_FAKE="<charge> <charging 0/1> <power 0/1>" does not read the device and uses these values directly (used by the unit test
|
||||
# devbattery_test.sh).
|
||||
DEVBATTERY_LOW=${DEVBATTERY_LOW:-30}; DEVBATTERY_RESUME=${DEVBATTERY_RESUME:-60}
|
||||
DEVBATTERY_DIR=${DEVBATTERY_DIR:-${DM_ROOT:-$HOME/dm-work}/run/ios}
|
||||
devbattery_read() { # 输出「电量 充电 电源」三个数(0/1),读不到返回 1 | Outputs three numbers "battery level, charging, power source" (0/1); returns 1 if they cannot be read
|
||||
if [ -n "${DEVBATTERY_FAKE:-}" ]; then echo "$DEVBATTERY_FAKE"; return 0; fi
|
||||
local u=${DM_IOS_UDID:-} out
|
||||
[ -n "$u" ] || { source "$(dirname "${BASH_SOURCE[0]}")/local_env.sh" 2>/dev/null; u=${DM_IOS_UDID:-}; } # 调用方没 source 本机配置时自己取 | Fetch it ourselves when the caller has not sourced the local configuration
|
||||
[ -n "$u" ] || return 2 # 没配 UDID(与「读不到」分开报) | UDID not configured (reported separately from "unreadable")
|
||||
out=$(timeout 20 ideviceinfo -u "$u" -q com.apple.mobile.battery 2>/dev/null) || out=$(timeout 20 ideviceinfo -n -u "$u" -q com.apple.mobile.battery 2>/dev/null) || return 1
|
||||
awk '/^BatteryCurrentCapacity:/{p=$2} /^BatteryIsCharging:/{c=($2=="true")} /^ExternalConnected:/{e=($2=="true")} /^FullyCharged:/{f=($2=="true")} END{ if (p=="") exit 1; print p, c+0, e+0, f+0 }' <<<"$out"
|
||||
}
|
||||
devbattery_gate() {
|
||||
mkdir -p "$DEVBATTERY_DIR"; local flag=$DEVBATTERY_DIR/device_low_battery log=$DEVBATTERY_DIR/battery.log r p c e f now; now=$(date '+%m-%d %H:%M:%S')
|
||||
r=$(devbattery_read); local rc=$?
|
||||
if [ $rc = 2 ]; then
|
||||
echo "$now 没配 UDID" >> "$log"; DEVBATTERY_LINE="电量 没配 UDID"
|
||||
echo "【红】没配测试机 UDID(本机配置 ~/.config/dm-ios/local.env 的 DM_IOS_UDID 为空),读不了电量,这局不跑" >&2; devbattery_notify "没配测试机 UDID,真机局已拒绝"; return 1; fi
|
||||
if [ $rc != 0 ]; then
|
||||
echo "$now 读不到" >> "$log"; DEVBATTERY_LINE="电量 读不到"
|
||||
echo "【红】测试机电量读不到(ideviceinfo 不通,设备多半离线或没电关机),这局不跑" >&2; devbattery_notify "测试机电量读不到,真机局已拒绝"; return 1; fi
|
||||
read -r p c e f <<<"$r"; f=${f:-0}
|
||||
DEVBATTERY_LINE="电量 ${p}%($([ "$c" = 1 ] && echo 充电 || echo 未充电),电源 $([ "$e" = 1 ] && echo 有 || echo 无))"
|
||||
echo "$now $p% 充电=$c 电源=$e 充满=$f" >> "$log"
|
||||
if [ -f "$flag" ]; then
|
||||
if [ "$p" -ge "$DEVBATTERY_RESUME" ]; then rm -f "$flag"; echo "测试机电量回到 ${p}%(≥ ${DEVBATTERY_RESUME}%),撤掉暂停标记,真机局放行" >&2
|
||||
else echo "【红】测试机电量暂停中:现 ${p}%,充到 ${DEVBATTERY_RESUME}% 才放行(标记 $flag:$(head -1 "$flag"))" >&2; return 1; fi
|
||||
elif [ "$p" -lt "$DEVBATTERY_LOW" ]; then
|
||||
echo "$now 电量 ${p}% 充电=$c 电源=$e" > "$flag"
|
||||
echo "【红】测试机电量 ${p}% 低于 ${DEVBATTERY_LOW}%:暂停全部真机局,充到 ${DEVBATTERY_RESUME}% 再放行(标记 $flag)" >&2
|
||||
devbattery_notify "测试机电量 ${p}%,真机局已暂停,充到 ${DEVBATTERY_RESUME}% 放行"; return 1
|
||||
fi
|
||||
[ "$e" = 1 ] && [ "$c" = 0 ] && [ "$f" = 0 ] && [ "$p" -lt "${DEVBATTERY_NOCHARGE:-90}" ] && echo "【红】测试机插着电源却没在充(${p}%):供电跟不上,局照跑,请换充电头 / 线" >&2
|
||||
return 0
|
||||
}
|
||||
devbattery_notify() { # 记进 battery.log 与 device_alert.txt(巡检读这个文件;不用系统通知:osascript 首次会弹权限框) | Record into battery.log and device_alert.txt (the patrol reads this file; system notifications are not used: osascript pops a permission dialog the first time)
|
||||
echo "$(date '+%m-%d %H:%M:%S') 通知:$1" | tee -a "$DEVBATTERY_DIR/battery.log" >> "$DEVBATTERY_DIR/device_alert.txt"
|
||||
}
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# devbattery.sh 单测:假读数(DEVBATTERY_FAKE)+ 临时目录,不碰设备。期望值按规则手算:< 30 拒并落标记、标记在时 < 60 拒、≥ 60 撤标记放行、读不到拒
|
||||
# Unit test for devbattery.sh: fake readings (DEVBATTERY_FAKE) + temporary directory, no device touched. Expected values are computed by hand from the rules: < 30 refuse and drop the marker; with the marker present, < 60 refuse; ≥ 60 remove the marker and pass; unreadable refuse
|
||||
cd "$(dirname "$0")"; T=$(mktemp -d); export DEVBATTERY_DIR=$T; # 单测一律写临时目录,不碰 $DM_ROOT/run/ios 的真日志与告警 | Unit tests always write to a temporary directory and never touch the real logs and alerts in $DM_ROOT/run/ios
|
||||
source ./devbattery.sh; bad=0
|
||||
ck() { local want=$1 got; shift; DEVBATTERY_FAKE="$*" devbattery_gate 2>/dev/null; got=$?; [ "$got" = "$want" ] && echo "通 $* → $got" || { echo "不通 $* → $got(期望 $want)"; bad=1; }; }
|
||||
ck 0 80 0 1 1 # 80%:放行 | 80%: pass
|
||||
ck 1 25 1 1 0 # 25%:拒,落标记 | 25%: refuse, drop the marker
|
||||
[ -f $T/device_low_battery ] && echo "通 低电落标记" || { echo "不通 低电没落标记"; bad=1; }
|
||||
ck 1 45 1 1 0 # 标记在、45%:拒 | Marker present, 45%: refuse
|
||||
ck 0 60 1 1 0 # 60%:撤标记放行 | 60%: remove the marker and pass
|
||||
[ ! -f $T/device_low_battery ] && echo "通 撤标记" || { echo "不通 标记没撤"; bad=1; }
|
||||
ck 0 45 1 1 0 # 没标记、45%:放行 | No marker, 45%: pass
|
||||
out=$(DEVBATTERY_FAKE="50 0 1 0" devbattery_gate 2>&1); case "$out" in *供电跟不上*) echo "通 插电不充记红";; *) echo "不通 插电不充没记红"; bad=1;; esac
|
||||
out=$(DEVBATTERY_FAKE="99 0 1 0" devbattery_gate 2>&1); case "$out" in *供电跟不上*) echo "不通 99% 停充被当成供电跟不上"; bad=1;; *) echo "通 99% 停充不记红";; esac
|
||||
DEVBATTERY_FAKE= DM_IOS_UDID=00000000-0000000000000000 devbattery_gate 2>/dev/null && { echo "不通 读不到却放行"; bad=1; } || echo "通 读不到拒"
|
||||
grep -q '读不到' $T/battery.log && echo "通 读不到记「读不到」" || { echo "不通 读不到没记对"; bad=1; }
|
||||
DEVBATTERY_FAKE= DM_IOS_UDID= DM_LOCAL_ENV=/dev/null HOME=$T devbattery_gate 2>/dev/null && { echo "不通 没配 UDID 却放行"; bad=1; } || echo "通 没配 UDID 拒"
|
||||
grep -q '没配 UDID' $T/battery.log && echo "通 没配 UDID 记「没配 UDID」" || { echo "不通 没配 UDID 没分开记"; bad=1; }
|
||||
grep -q 通知 $T/device_alert.txt && echo "通 告警文件有记录" || { echo "不通 告警文件没记录"; bad=1; }
|
||||
# devlock 接入:device.lock 目录取锁前过闸——电量够直接取到;电量低等满上限退出 4、不取锁
|
||||
# devlock integration: go through the gate before taking the device.lock directory lock - with enough battery the lock is taken directly; with low battery it waits out the full limit, exits 4 and does not take the lock
|
||||
L=$T/device.lock; export DEVBATTERY_DIR=$T
|
||||
DM_DEVBATTERY=1 DEVBATTERY_FAKE="80 0 1 0" DM_DEVLOCK_DIR=$L bash -c 'source ./devlock.sh; devlock_acquire 单测 2>/dev/null; [ -d "$DEVLOCK_DIR" ] && devlock_release' && echo "通 devlock 电量够取到锁" || { echo "不通 devlock 电量够没取到"; bad=1; }
|
||||
DM_DEVBATTERY=1 DEVBATTERY_FAKE="10 0 1 0" DM_DEVBATTERY_WAIT_S=2 DM_DEVBATTERY_POLL_S=1 DM_DEVLOCK_DIR=$L bash -c 'source ./devlock.sh; devlock_acquire 单测 2>/dev/null; echo 不该走到这' >/dev/null; r=$?
|
||||
[ $r = 4 ] && [ ! -d $L ] && echo "通 devlock 电量低退出 4 且没取锁" || { echo "不通 devlock 电量低 → $r"; bad=1; }
|
||||
rm -rf "$T"; [ $bad = 0 ] && echo "devbattery 单测全过" || { echo "devbattery 单测有不通"; exit 1; }
|
||||
Executable
+229
@@ -0,0 +1,229 @@
|
||||
#!/bin/bash
|
||||
|
||||
DEVLOCK_DIR=${DM_DEVLOCK_DIR:-${DM_ROOT:-$HOME/dm-work}/run/ios/device.lock}
|
||||
DEVLOCK_DEPTH=${DEVLOCK_DEPTH:-0}
|
||||
DEVLOCK_QUEUE=${DM_DEVLOCK_QUEUE:-${DEVLOCK_DIR%.lock}.queue} # 拿号排队(抢锁无序,后到的可能先拿,曾饿 20 分钟) | Queue with tickets (lock grabbing is unordered; a later arrival may get it first, and one once starved for 20 minutes)
|
||||
DEVLOCK_TICKET=
|
||||
# 持锁上限(曾有手写脚本用 devicectl copy from 轮询日志,申报约 100 秒、实占 17 分钟,后面排队的各等 13–15 分钟;以前只要持有者活着就一直等)。
|
||||
# devlock_acquire <owner> [上限秒],或环境变量 DM_DEVLOCK_MAX_S;都没给时设备锁按类别取缺省:冒烟 / 合入 / 一般真机局 600 秒(冒烟台账 1338 次用时 p99 385 秒),
|
||||
# 测量(DM_DEVLOCK_CLASS=measure)1200 秒。别的锁目录(mini 的 macsmoke 锁、自测的临时锁)没有缺省、不设上限,显式给了才管。
|
||||
# 拿到锁后持锁者这一侧起看门狗:超过上限仍持锁 = 记【红】(owner、已持有秒数)→ 向持锁进程及其全部子孙(devicectl、iproxy、sleep…)发 TERM,5 秒后还在的 KILL → 释放锁。
|
||||
# 只动持锁者自己的进程树(看门狗自己除外),不碰别人。可重入(嵌套 acquire / 子进程沿用 DM_DEVLOCK_HELD)不另起看门狗、不改上限
|
||||
# Lock hold limit (a hand-written script once polled logs with devicectl copy from, declared about 100 seconds and actually held 17 minutes, and those queued behind each waited 13–15 minutes; previously, as long as the holder was alive everyone just kept waiting).
|
||||
# devlock_acquire <owner> [limit seconds], or the environment variable DM_DEVLOCK_MAX_S; when neither is given, the device lock takes a default by class: smoke test / merge / ordinary real-device run 600 seconds (p99 duration over 1338 smoke test ledger entries is 385 seconds),
|
||||
# measurement (DM_DEVLOCK_CLASS=measure) 1200 seconds. Other lock directories (the second Mac's macsmoke lock, temporary locks of self-tests) have no default and no limit; they are enforced only when one is given explicitly.
|
||||
# After the lock is obtained, a watchdog starts on the holder's side: still holding past the limit = log 【红】(red) (owner, seconds held) → send TERM to the holding process and all its descendants (devicectl, iproxy, sleep...), KILL those still alive after 5 seconds → release the lock.
|
||||
# Only the holder's own process tree is touched (except the watchdog itself), nobody else's. Reentrant cases (nested acquire / child processes inheriting DM_DEVLOCK_HELD) start no extra watchdog and do not change the limit
|
||||
DEVLOCK_WD_PID=
|
||||
DEVLOCK_WD_LOG=${DM_DEVLOCK_WD_LOG:-${DM_ROOT:-$HOME/dm-work}/run/ios/devlock_watchdog.log}
|
||||
devlock_default_max() {
|
||||
[ "$DEVLOCK_DIR" = "${DM_ROOT:-$HOME/dm-work}/run/ios/device.lock" ] || { echo 0; return; }
|
||||
[ "${DM_DEVLOCK_CLASS:-}" = measure ] && echo 1200 || echo 600
|
||||
}
|
||||
# 某进程的全部子孙(不含自己),子孙先于祖先列出
|
||||
# All descendants of a process (excluding itself), descendants listed before ancestors
|
||||
devlock_descendants() {
|
||||
local root=$1 kids k
|
||||
kids=$(ps -axo pid=,ppid= 2>/dev/null | awk -v p="$root" '$2==p{print $1}')
|
||||
for k in $kids; do devlock_descendants "$k"; echo "$k"; done
|
||||
}
|
||||
devlock_watchdog() { # 在后台跑:$1 持锁 pid,$2 其启动时刻,$3 上限秒,$4 owner | Runs in the background: $1 holder pid, $2 its start time, $3 limit in seconds, $4 owner
|
||||
local holder=$1 lst=$2 max=$3 owner=$4 me=${BASHPID:-$$} now started held victims v
|
||||
trap '' HUP
|
||||
while sleep 2; do
|
||||
[ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" = "$holder" ] || exit 0 # 已放锁 / 锁被换主 | Lock already released / lock changed owner
|
||||
[ "$(cat "$DEVLOCK_DIR/lstart" 2>/dev/null)" = "$lst" ] || exit 0
|
||||
kill -0 "$holder" 2>/dev/null || exit 0
|
||||
started=$(cat "$DEVLOCK_DIR/started" 2>/dev/null || echo 0); now=$(date +%s); held=$((now - started))
|
||||
[ "$held" -ge "$max" ] || continue
|
||||
local msg="【红】设备锁看门狗:持有者「$owner」(pid $holder)已持有 ${held} 秒,超过上限 ${max} 秒 → 终止持锁进程树、释放锁"
|
||||
echo "$msg" >&2; mkdir -p "$(dirname "$DEVLOCK_WD_LOG")"; echo "$(date '+%F %T') $msg(锁 $DEVLOCK_DIR)" >> "$DEVLOCK_WD_LOG"
|
||||
victims=$(devlock_descendants "$holder" | grep -v -x -e "$me" $(devlock_descendants "$me" | sed 's/^/-e /'))
|
||||
for v in $victims "$holder"; do kill -TERM "$v" 2>/dev/null; done
|
||||
sleep 5
|
||||
for v in $victims "$holder"; do kill -0 "$v" 2>/dev/null && kill -KILL "$v" 2>/dev/null; done
|
||||
[ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" = "$holder" ] && rm -rf "$DEVLOCK_DIR"
|
||||
exit 0
|
||||
done
|
||||
}
|
||||
|
||||
# 取号:<类别>_<到达纳秒>_<pid>,名字按(类别, 到达先后)排序;持号进程已死的号作废。
|
||||
# 类别(排队超过五分钟都太久):0 = 冒烟 / 合入(缺省),1 = 测量(DM_DEVLOCK_CLASS=measure)。
|
||||
# 冒烟 / 合入的号排在所有测量号前面,先到先得只在同类内部——任何冒烟最多等正在持锁的那一轮测量(测量单轮持锁 ≤ 4 分钟)。
|
||||
# 旧版脚本取的号(<到达纳秒>_<pid>,无类别)按字节序落在两类之间,新旧混用期间不乱序。
|
||||
# Take a ticket: <class>_<arrival nanoseconds>_<pid>; names sort by (class, arrival order); a ticket whose holding process is dead is void.
|
||||
# Classes (queuing for more than five minutes is too long in any case): 0 = smoke test / merge (default), 1 = measurement (DM_DEVLOCK_CLASS=measure).
|
||||
# Smoke test / merge tickets rank ahead of all measurement tickets, and first-come-first-served applies only within a class - any smoke test waits at most for the measurement round currently holding the lock (a single measurement round holds the lock ≤ 4 minutes).
|
||||
# Tickets taken by old scripts (<arrival nanoseconds>_<pid>, no class) fall between the two classes in byte order, so the order is not scrambled while old and new are mixed.
|
||||
devlock_ticket_take() {
|
||||
mkdir -p "$DEVLOCK_QUEUE"
|
||||
local cls=0; [ "${DM_DEVLOCK_CLASS:-}" = measure ] && cls=1
|
||||
DEVLOCK_TICKET="$DEVLOCK_QUEUE/${cls}_$(python3 -c 'import time;print(time.time_ns())')_$$"
|
||||
mkdir "$DEVLOCK_TICKET"; printf "%s\n" "${1:-unknown}" > "$DEVLOCK_TICKET/owner"
|
||||
}
|
||||
devlock_ticket_drop() { [ -n "$DEVLOCK_TICKET" ] && rm -rf "$DEVLOCK_TICKET"; DEVLOCK_TICKET=; }
|
||||
# 前面还有几个存活的号(顺手清掉死号);标准输出:个数<TAB>下一个的 owner
|
||||
# How many live tickets are ahead (dead tickets are cleaned up along the way); stdout: count<TAB>owner of the next one
|
||||
devlock_ahead() {
|
||||
local d n=0 first="" mine; mine=$(basename "$DEVLOCK_TICKET")
|
||||
# 调用处写的是 IFS=$'\t' read … < <(devlock_ahead):那个临时 IFS 会带进本函数,下面的 $(ls) 就不按换行拆——队列里有 ≥2 个号时
|
||||
# 每个人都把整张队列当成「排在前面的一个号」,全体永远等(曾有四个任务互等 11–20 分钟,锁本身没人持有)。这里钉回缺省。
|
||||
# The call site is written as IFS=$'\t' read ... < <(devlock_ahead): that temporary IFS carries into this function, so the $(ls) below is not split on newlines - with ≥2 tickets in the queue
|
||||
# everyone takes the whole queue as "one ticket ahead" and all wait forever (four tasks once waited on each other for 11–20 minutes while nobody held the lock). Pin it back to the default here.
|
||||
local IFS=$' \t\n'
|
||||
for d in $(ls "$DEVLOCK_QUEUE" 2>/dev/null | LC_ALL=C sort); do
|
||||
kill -0 "${d##*_}" 2>/dev/null || { rm -rf "$DEVLOCK_QUEUE/$d"; continue; }
|
||||
[ "$d" != "$mine" ] || break # 已按字节序排好:排在自己前面的都算(不用 [ \< ],它按区域设置比较) | Already sorted in byte order: everything ranked before our own counts (do not use [ \< ], which compares by locale)
|
||||
n=$((n + 1)); [ -n "$first" ] || first=$(cat "$DEVLOCK_QUEUE/$d/owner" 2>/dev/null)
|
||||
done
|
||||
printf "%s\t%s\n" "$n" "$first"
|
||||
}
|
||||
|
||||
# 进程启动时刻(判锁的持有者还在不在、防 pid 复用)。ps -o lstart 的字符串跟语言环境走:中文环境是「四 10月/ 8 18:51:58 2026」,
|
||||
# C / 英文环境是「Thu Oct 8 18:51:58 2026」。取锁方与抢锁方环境不同时,活着的持有者永远对不上、被当无主锁拆掉,两边同时用手机
|
||||
# (两路真机局曾因此撞车)。写入一律 LC_ALL=C;比对时按锁里那条记录的格式取(记录含非 ASCII = 中文环境写的)
|
||||
# Process start time (to judge whether the lock holder is still there, guards against pid reuse). The ps -o lstart string follows the locale: in a Chinese locale it is 「四 10月/ 8 18:51:58 2026」,
|
||||
# in a C / English locale it is "Thu Oct 8 18:51:58 2026". When the lock taker and the lock grabber have different locales, a live holder never matches and is torn down as an ownerless lock, and both sides use the phone at once
|
||||
# (two real-device runs once collided because of this). Writes always use LC_ALL=C; comparison uses the format of the record in the lock (a record containing non-ASCII = written in a Chinese locale)
|
||||
devlock_lstart() { # $1 pid,$2 参照串(缺省 = C 格式) | $1 pid, $2 reference string (default = C format)
|
||||
local loc=C; printf %s "${2:-}" | LC_ALL=C grep -q '[^ -~]' && loc=zh_CN.UTF-8
|
||||
# 进程已不在时 ps 返回非零:这里一律回 0、只打空串——调用方开着 set -e + pipefail(touch_e2e.sh)时,$(devlock_lstart 死pid) 的赋值会让整个脚本当场静默退出,
|
||||
# 走不到「持有者已死 → 收回锁」那个分支(实例:j 局留下死锁后 k pk sb rf2 pg2 vt1 六局 0 秒退、日志只有电量闸一行)
|
||||
# ps returns non-zero when the process is gone: here always return 0 and print only an empty string - when the caller has set -e + pipefail (touch_e2e.sh), the assignment $(devlock_lstart <dead pid>) would make the whole script exit silently on the spot,
|
||||
# never reaching the "holder is dead → reclaim the lock" branch (instance: after run j left a dead lock, the six runs k pk sb rf2 pg2 vt1 exited at 0 seconds with only the battery gate line in the log)
|
||||
LC_ALL=$loc ps -o lstart= -p "$1" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' || true
|
||||
}
|
||||
devlock_is_descendant() {
|
||||
local child=$1 ancestor=$2 parent depth=0
|
||||
while [ "$depth" -lt 64 ]; do
|
||||
[ "$child" = "$ancestor" ] && return 0
|
||||
parent=$(ps -o ppid= -p "$child" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
|
||||
[ -n "$parent" ] || return 1
|
||||
[ "$parent" = "$child" ] && return 1
|
||||
child=$parent
|
||||
depth=$((depth + 1))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# 取锁必须响亮:里面任何一步意外失败、或走完了锁却不在自己(或可重入的祖先)手里,都打【红】并返回非零——set -e 的调用方随之退出,不许静默退。
|
||||
# 函数体放在 || 的左边执行,调用方的 set -e 在里面不生效:没开 set -e 的调用方(冒烟、合入)一直是这样跑的,两种调用方从此同一条路径
|
||||
# Taking the lock must be loud: if any step inside fails unexpectedly, or it finishes with the lock not held by itself (or a reentrant ancestor), print 【红】(red) and return non-zero - a set -e caller then exits; silent exit is not allowed.
|
||||
# The function body runs on the left side of ||, so the caller's set -e has no effect inside: callers without set -e (smoke test, merge) have always run this way, and from now on both kinds of caller take the same path
|
||||
devlock_acquire() {
|
||||
local rc=0; _devlock_acquire "$@" || rc=$?
|
||||
if [ "$rc" = 0 ] && [ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" != "${DM_DEVLOCK_HELD:-}" ]; then rc=97; fi
|
||||
[ "$rc" = 0 ] && return 0
|
||||
echo "【红】设备锁:${1:-unknown} 没取到锁(返回 $rc;锁 $DEVLOCK_DIR 现在的持有者「$(cat "$DEVLOCK_DIR/owner" 2>/dev/null || echo 无)」pid $(cat "$DEVLOCK_DIR/pid" 2>/dev/null || echo 无))" >&2
|
||||
return "$rc"
|
||||
}
|
||||
_devlock_acquire() {
|
||||
local owner=${1:-unknown} max=${2:-${DM_DEVLOCK_MAX_S:-}} held_lstart pid lock_owner started now held lock_lstart self_lstart lock_pid_lstart current_pid last_notice=0 lock_max over_notice=0
|
||||
[ -n "$max" ] || max=$(devlock_default_max)
|
||||
mkdir -p "$(dirname "$DEVLOCK_DIR")" 2>/dev/null && [ -w "$(dirname "$DEVLOCK_DIR")" ] || return 98 # 锁的父目录建不出 / 写不了:下面的抢锁循环会空转,直接报失败 | The lock's parent directory cannot be created / written: the lock-grabbing loop below would spin, so report failure directly
|
||||
current_pid=${BASHPID:-$$}
|
||||
self_lstart=$(devlock_lstart $$)
|
||||
if [ -n "${DM_DEVLOCK_HELD:-}" ] && [ -f "$DEVLOCK_DIR/pid" ] &&
|
||||
[ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" = "$DM_DEVLOCK_HELD" ] &&
|
||||
# 比的是「持锁进程 DM_DEVLOCK_HELD」现在的启动时刻与锁内记录是否一致(防 pid 复用),不是当前进程自己的——
|
||||
# 比自己的会让持锁者的子进程(启动时刻必然不同)判不可复用、排队等自己的父进程,死锁
|
||||
# What is compared is whether the current start time of the "lock-holding process DM_DEVLOCK_HELD" matches the record inside the lock (guards against pid reuse), not that of the current process itself -
|
||||
# comparing its own would make a child of the holder (whose start time necessarily differs) be judged non-reentrant and queue up waiting for its own parent: deadlock
|
||||
held_lstart=$(devlock_lstart "$DM_DEVLOCK_HELD" "$(cat "$DEVLOCK_DIR/lstart" 2>/dev/null)") &&
|
||||
[ -n "$held_lstart" ] &&
|
||||
[ "$held_lstart" = "$(cat "$DEVLOCK_DIR/lstart" 2>/dev/null)" ] &&
|
||||
kill -0 "$DM_DEVLOCK_HELD" 2>/dev/null &&
|
||||
devlock_is_descendant "$current_pid" "$DM_DEVLOCK_HELD"; then
|
||||
DEVLOCK_DEPTH=$((DEVLOCK_DEPTH + 1))
|
||||
return 0
|
||||
fi
|
||||
# 电量闸:取真机锁 device.lock 前过 devbattery.sh——低于 30% 暂停、充到 60% 放行;拒绝时每分钟重读,
|
||||
# 一直不放行等满 DM_DEVBATTERY_WAIT_S(缺省 3600)秒就记【红】退出调用脚本(退出码 4)。只管真机锁 $DM_ROOT/run/ios/device.lock(单测的临时锁目录不过闸);DM_DEVBATTERY=0 跳过、=1 强制过闸
|
||||
# Battery gate: before taking the real-device lock device.lock, go through devbattery.sh - below 30% pause, charged to 60% pass; when refused, re-read every minute,
|
||||
# and if it never passes after waiting the full DM_DEVBATTERY_WAIT_S (default 3600) seconds, log 【红】(red) and exit the calling script (exit code 4). Applies only to the real-device lock $DM_ROOT/run/ios/device.lock (temporary lock directories of unit tests do not go through the gate); DM_DEVBATTERY=0 skips, =1 forces the gate
|
||||
if { [ "$DEVLOCK_DIR" = "${DM_ROOT:-$HOME/dm-work}/run/ios/device.lock" ] && [ "${DM_DEVBATTERY:-1}" != 0 ]; } || [ "${DM_DEVBATTERY:-}" = 1 ]; then
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/devbattery.sh"
|
||||
local bw0=$SECONDS bwmax=${DM_DEVBATTERY_WAIT_S:-3600}
|
||||
until devbattery_gate; do
|
||||
[ $((SECONDS - bw0)) -ge "$bwmax" ] && { echo "【红】电量闸等了 $((SECONDS - bw0)) 秒仍不放行(${DEVBATTERY_LINE:-}),$owner 不取锁、退出" >&2; exit 4; }
|
||||
sleep "${DM_DEVBATTERY_POLL_S:-60}"
|
||||
done
|
||||
echo "电量闸放行:${DEVBATTERY_LINE:-}($owner)" >&2
|
||||
fi
|
||||
devlock_ticket_take "$owner"
|
||||
local ahead first q_notice=0
|
||||
while :; do
|
||||
IFS=$'\t' read -r ahead first < <(devlock_ahead)
|
||||
[ "$ahead" = 0 ] && break
|
||||
now=$(date +%s); [ $((now - q_notice)) -ge 30 ] && { echo "排队等设备锁:前面还有 $ahead 个(下一个:${first:-?})" >&2; q_notice=$now; }
|
||||
sleep 1
|
||||
done
|
||||
while :; do
|
||||
# 每次抢锁前重看队列:等锁期间来了更优先的号(冒烟 / 合入排在测量前)就让它先抢
|
||||
# Re-check the queue before every lock attempt: if a higher-priority ticket arrived while waiting (smoke test / merge rank ahead of measurement), let it grab first
|
||||
IFS=$'\t' read -r ahead first < <(devlock_ahead)
|
||||
if [ "$ahead" != 0 ]; then sleep 1; continue; fi
|
||||
mkdir "$DEVLOCK_DIR" 2>/dev/null && break
|
||||
pid=$(cat "$DEVLOCK_DIR/pid" 2>/dev/null || true)
|
||||
lock_owner=$(cat "$DEVLOCK_DIR/owner" 2>/dev/null || echo unknown)
|
||||
started=$(cat "$DEVLOCK_DIR/started" 2>/dev/null || date +%s)
|
||||
lock_lstart=$(cat "$DEVLOCK_DIR/lstart" 2>/dev/null || true)
|
||||
now=$(date +%s)
|
||||
held=$((now - started))
|
||||
lock_pid_lstart=$(devlock_lstart "$pid" "$lock_lstart")
|
||||
# 旧格式锁(只有 pid / owner、没有 lstart 文件,如旧版 ios_smoke.sh 或手写的 mkdir 锁):pid 活着就尊重,不判陈旧
|
||||
# Old-format lock (only pid / owner, no lstart file, e.g. an old ios_smoke.sh or a hand-written mkdir lock): if the pid is alive, respect it and do not judge it stale
|
||||
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null && { [ ! -f "$DEVLOCK_DIR/lstart" ] || [ "$lock_pid_lstart" = "$lock_lstart" ]; }; then
|
||||
lock_max=$(cat "$DEVLOCK_DIR/max" 2>/dev/null || echo 0)
|
||||
if [ "$last_notice" -eq 0 ] || [ $((now - last_notice)) -ge 30 ]; then
|
||||
if [ "${lock_max:-0}" -gt 0 ]; then echo "等待设备锁:持有者 ${lock_owner},已持有 ${held} 秒 / 上限 ${lock_max} 秒" >&2
|
||||
else echo "等待设备锁:持有者 ${lock_owner},已持有 ${held} 秒(未申报上限)" >&2; fi
|
||||
last_notice=$now
|
||||
fi
|
||||
# 超过上限 30 秒还没放(持锁者的看门狗也没管用):记红,但不碰别人的进程
|
||||
# Still not released 30 seconds past the limit (the holder's watchdog did not work either): log a failure line, but do not touch other people's processes
|
||||
if [ "${lock_max:-0}" -gt 0 ] && [ "$held" -gt $((lock_max + 30)) ] && [ $((now - over_notice)) -ge 60 ]; then
|
||||
echo "【红】设备锁:持有者 ${lock_owner}(pid $pid)已持有 ${held} 秒,超过上限 ${lock_max} 秒仍未释放(看门狗没起作用),不代为终止,请找持有者" >&2
|
||||
mkdir -p "$(dirname "$DEVLOCK_WD_LOG")"; echo "$(date '+%F %T') 等锁方:持有者「${lock_owner}」pid $pid 已持有 ${held} 秒、上限 ${lock_max} 秒仍未释放(锁 $DEVLOCK_DIR)" >> "$DEVLOCK_WD_LOG"
|
||||
over_notice=$now
|
||||
fi
|
||||
sleep 1
|
||||
elif [ -z "$pid" ] && [ $((now - $(stat -f %m "$DEVLOCK_DIR" 2>/dev/null || echo 0))) -lt 10 ]; then
|
||||
sleep 1 # 别人刚 mkdir、还没写 pid:正在创建,不是陈旧锁 | Someone else just did mkdir and has not written the pid yet: it is being created, not a stale lock
|
||||
else
|
||||
rm -rf "$DEVLOCK_DIR"
|
||||
fi
|
||||
done
|
||||
printf "%s\n" "$$" > "$DEVLOCK_DIR/pid"
|
||||
printf "%s\n" "$owner" > "$DEVLOCK_DIR/owner"
|
||||
date +%s > "$DEVLOCK_DIR/started"
|
||||
printf "%s\n" "$self_lstart" > "$DEVLOCK_DIR/lstart"
|
||||
printf "%s\n" "${max:-0}" > "$DEVLOCK_DIR/max"
|
||||
export DM_DEVLOCK_HELD=$$
|
||||
devlock_ticket_drop
|
||||
DEVLOCK_DEPTH=1
|
||||
if [ "${max:-0}" -gt 0 ]; then
|
||||
devlock_watchdog "$$" "$self_lstart" "$max" "$owner" </dev/null >/dev/null &
|
||||
DEVLOCK_WD_PID=$!; disown "$DEVLOCK_WD_PID" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
devlock_release() {
|
||||
[ "$DEVLOCK_DEPTH" -gt 0 ] || return 0
|
||||
if [ "$DEVLOCK_DEPTH" -gt 1 ]; then
|
||||
DEVLOCK_DEPTH=$((DEVLOCK_DEPTH - 1))
|
||||
return 0
|
||||
fi
|
||||
# 看门狗连同它正在 sleep 的子进程一起收掉(KILL:它的 stdout / stderr 可能连着调用方的管道,拖着不退会让 `… | tail` 多等)
|
||||
# 先记下它的子进程、先杀看门狗本身再杀子进程:反过来的话看门狗会替被杀的 sleep 打一行「Killed: 9」到调用方的输出里
|
||||
# 每一步都带 || true:看门狗正好在两次 sleep 之间(没有子进程)时 pgrep 返回 1,set -e 的调用方在 EXIT 钩子里跑到这就当场退出、走不到下面删锁,
|
||||
# 留下一把持有者已死的锁(j 局出现过;离线复现:持锁 2 秒放锁,退出码 1、锁目录还在)
|
||||
# Reap the watchdog together with the child it is currently sleeping in (KILL: its stdout / stderr may be attached to the caller's pipe, and lingering would make `... | tail` wait longer)
|
||||
# Record its children first, then kill the watchdog itself before the children: the other way round, the watchdog would print a line "Killed: 9" for the killed sleep into the caller's output
|
||||
# Every step carries || true: when the watchdog happens to be between two sleeps (no child), pgrep returns 1, and a set -e caller running this in its EXIT hook would exit on the spot and never reach the lock removal below,
|
||||
# leaving a lock whose holder is dead (seen in run j; offline reproduction: hold the lock 2 seconds then release, exit code 1, lock directory still there)
|
||||
if [ -n "$DEVLOCK_WD_PID" ]; then local wk; wk=$(pgrep -P "$DEVLOCK_WD_PID" 2>/dev/null) || true; kill -KILL "$DEVLOCK_WD_PID" 2>/dev/null || true; [ -z "$wk" ] || kill -KILL $wk 2>/dev/null || true; DEVLOCK_WD_PID=; fi
|
||||
[ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" = "$$" ] || return 0
|
||||
rm -rf "$DEVLOCK_DIR"
|
||||
DEVLOCK_DEPTH=0
|
||||
}
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
# devlock.sh 跨语言环境自测(不碰手机):ps -o lstart 的字符串跟语言环境走,持有者与抢锁者环境不同时,活着的持有者不能被当无主锁拆掉。
|
||||
# 三格:① 中文环境持锁、C 环境来抢 → 等持有者放锁;② 修正前在中文环境写的旧锁(lstart 是中文串)、持有者活着 → 等;③ 持有者已死 → 收回。
|
||||
# Cross-locale self-test for devlock.sh (does not touch the phone): the ps -o lstart string follows the locale; when holder and grabber have different locales, a live holder must not be torn down as an ownerless lock.
|
||||
# Three cells: ① Chinese-locale holder, C-locale grabber → wait for the holder to release; ② an old lock written in a Chinese locale before the fix (lstart is a Chinese string), holder alive → wait; ③ holder dead → reclaim.
|
||||
set -u; H=$(cd "$(dirname "$0")" && pwd); T=$(mktemp -d); export DM_DEVLOCK_DIR=$T/device.lock DM_DEVLOCK_QUEUE=$T/device.queue; bad=0
|
||||
ok(){ echo " ✓ $1"; }; no(){ echo " 🔴 $1"; bad=1; }
|
||||
# ① 中文环境持锁 4 秒,1 秒后 C 环境来抢:抢到的时刻必须在持有者放锁之后
|
||||
# ① A Chinese-locale process holds the lock for 4 seconds and a C-locale one comes to grab 1 second later: the moment it gets the lock must be after the holder releases
|
||||
( unset DM_DEVLOCK_HELD; export LC_ALL=zh_CN.UTF-8; source $H/devlock.sh; devlock_acquire 甲 2>/dev/null; sleep 4; date +%s > $T/a_rel; devlock_release ) &
|
||||
sleep 1
|
||||
( unset DM_DEVLOCK_HELD; export LC_ALL=C; source $H/devlock.sh; devlock_acquire 乙 2>/dev/null; date +%s > $T/b_got; devlock_release )
|
||||
wait; [ "$(cat $T/b_got)" -ge "$(cat $T/a_rel)" ] && ok "① 中文环境持锁时 C 环境的等到放锁才拿到" || no "① C 环境的在中文环境持有者还活着时拿到了锁"
|
||||
# ② 旧锁:持有者活着、lstart 是中文环境写的串(修正前的写法),C 环境来抢 → 不能拆
|
||||
# ② Old lock: holder alive, lstart is a string written in a Chinese locale (the pre-fix way), a C-locale process comes to grab → must not be torn down
|
||||
sleep 30 & P=$!; mkdir -p $DM_DEVLOCK_DIR; echo $P > $DM_DEVLOCK_DIR/pid; echo 旧锁 > $DM_DEVLOCK_DIR/owner; date +%s > $DM_DEVLOCK_DIR/started
|
||||
LC_ALL=zh_CN.UTF-8 ps -o lstart= -p $P | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' > $DM_DEVLOCK_DIR/lstart
|
||||
( sleep 3; date +%s > $T/p_kill; kill $P ) &
|
||||
( unset DM_DEVLOCK_HELD; export LC_ALL=C; source $H/devlock.sh; devlock_acquire 丙 2>/dev/null; date +%s > $T/c_got; devlock_release )
|
||||
wait; [ "$(cat $T/c_got)" -ge "$(cat $T/p_kill)" ] && ok "② 中文串旧锁的持有者活着时没被拆,死了才收回" || no "② 中文串旧锁在持有者活着时被拆了"
|
||||
# ③ 持有者已死(pid 不在)→ 立即收回
|
||||
# ③ Holder is dead (pid gone) → reclaim immediately
|
||||
mkdir -p $DM_DEVLOCK_DIR; echo 999999 > $DM_DEVLOCK_DIR/pid; echo 死锁 > $DM_DEVLOCK_DIR/owner; echo "Thu Jan 1 00:00:00 2026" > $DM_DEVLOCK_DIR/lstart
|
||||
t0=$(date +%s); ( unset DM_DEVLOCK_HELD; source $H/devlock.sh; devlock_acquire 丁 2>/dev/null; devlock_release ); [ $(( $(date +%s) - t0 )) -le 3 ] && ok "③ 死持有者的锁 3 秒内收回" || no "③ 死持有者的锁没及时收回"
|
||||
rm -rf $T; [ $bad = 0 ] && echo "devlock_locale_test 通过 3/3" || { echo "🔴 devlock_locale_test 有不过的"; exit 1; }
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
export DM_DEVBATTERY=0 DEVBATTERY_DIR=$(mktemp -d) # 锁单测不过电量闸、不写真电量日志(一次挂住的锁单测往真告警文件写了 18 条「读不到」) | Lock unit tests do not go through the battery gate and do not write the real battery log (a hung lock unit test once wrote 18 「读不到」(unreadable) entries into the real alert file)
|
||||
# devlock.sh 持锁上限自测(不碰手机,用临时锁目录):
|
||||
# 1. 故意不放锁的持锁者(上限 6 秒,里面挂 sleep 子孙)→ 到点被自己的看门狗终止、子孙清干净、锁释放;排在后面的号随后拿到锁
|
||||
# 2. 正常持锁 3 秒就放(上限 6 秒)→ 不被终止,看门狗随之退出
|
||||
# 3. 嵌套 acquire(同进程两层 + 子进程沿用)→ 不另起看门狗、不误杀,上限到点前放锁
|
||||
# Lock hold limit self-test for devlock.sh (does not touch the phone, uses a temporary lock directory):
|
||||
# 1. A holder that deliberately does not release (limit 6 seconds, with sleep descendants hanging inside) → terminated on time by its own watchdog, descendants cleaned up, lock released; the ticket queued behind then gets the lock
|
||||
# 2. A normal hold released after 3 seconds (limit 6 seconds) → not terminated, and the watchdog exits along with it
|
||||
# 3. Nested acquire (two levels in the same process + inherited by a child process) → no extra watchdog, no wrongful kill, lock released before the limit is reached
|
||||
set -u; H=$(cd "$(dirname "$0")" && pwd); T=$(mktemp -d); export DM_DEVLOCK_DIR=$T/device.lock DM_DEVLOCK_QUEUE=$T/device.queue DM_DEVLOCK_WD_LOG=$T/wd.log
|
||||
fail=0; ok(){ echo " 通:$*"; }; bad(){ echo " 🔴 不通:$*"; fail=1; }
|
||||
echo "1. 不放锁的持锁者"
|
||||
# 持锁者用独立的 bash 进程(devlock 按 $$ 认持锁者:子 shell 的 $$ 是外层脚本,那样看门狗会把整个自测连根终止)
|
||||
# The holder uses a separate bash process (devlock identifies the holder by $$: a subshell's $$ is the outer script, in which case the watchdog would terminate the whole self-test, root and all)
|
||||
bash -c 'source $0/devlock.sh; devlock_acquire 赖着不走 6; sleep 300 & echo $! > $1/kid; sleep 300; echo 不该走到这 > $1/h1.reach' $H $T 2>>$T/h1.err & H1=$!
|
||||
sleep 1; bash -c 'unset DM_DEVLOCK_HELD; source $0/devlock.sh; t0=$(date +%s); devlock_acquire 后面排队的 2>>$1/w.err; echo $(( $(date +%s) - t0 )) > $1/wait; devlock_release' $H $T & W=$!
|
||||
wait $W; waited=$(cat $T/wait); sleep 1
|
||||
kill -0 $H1 2>/dev/null && bad "持锁者没被终止" || ok "持锁者被终止"
|
||||
kill -0 "$(cat $T/kid)" 2>/dev/null && { bad "子孙 sleep 还活着"; kill "$(cat $T/kid)"; } || ok "子孙清干净"
|
||||
[ ! -e $T/h1.reach ] && ok "持锁者没继续往下跑" || bad "持锁者继续往下跑了"
|
||||
[ "$waited" -ge 4 ] && [ "$waited" -le 10 ] && ok "后面的号等了 ${waited} 秒(上限 6 秒)就拿到锁" || bad "后面的号等了 ${waited} 秒"
|
||||
grep -q '【红】设备锁看门狗:持有者「赖着不走」' $T/h1.err && grep -q '已持有' $T/wd.log && ok "记了红:$(head -1 $T/wd.log | cut -c1-80)…" || bad "没记红"
|
||||
grep -q '上限 6 秒' $T/w.err && ok "等锁方提示带上限:$(grep -m1 上限 $T/w.err)" || bad "等锁方提示没有上限:$(cat $T/w.err)"
|
||||
[ ! -d $DM_DEVLOCK_DIR ] && ok "锁目录已清" || bad "锁目录还在"
|
||||
echo "2. 正常持锁 3 秒"
|
||||
bash -c 'source $0/devlock.sh; devlock_acquire 正常 6 2>/dev/null; sleep 3; devlock_release; sleep 6; echo 活着 > $1/h2.alive' $H $T; [ -e $T/h2.alive ] && ok "放锁后进程照常走完,没被杀" || bad "被误杀"
|
||||
echo "3. 嵌套"
|
||||
bash -c 'source $0/devlock.sh; devlock_acquire 外层 8 2>/dev/null; devlock_acquire 内层 2 2>/dev/null; bash -c "source $0/devlock.sh; devlock_acquire 子进程 2 2>/dev/null; sleep 4; devlock_release"; sleep 2; devlock_release; devlock_release; echo 走完 > $1/h3.done' $H $T
|
||||
[ -e $T/h3.done ] && ok "嵌套 6 秒(内层上限 2 秒不生效,外层 8 秒)没被误杀" || bad "嵌套被误杀"
|
||||
[ ! -d $DM_DEVLOCK_DIR ] && ok "锁已释放" || bad "锁没释放"
|
||||
echo "4. set -e 的调用方(touch_e2e.sh 的写法):持锁几秒后靠 EXIT 钩子放锁,锁必须放掉"
|
||||
for hold in 0 1 2 3; do
|
||||
bash -c 'set -euo pipefail; source $0/devlock.sh; devlock_acquire "钩子放锁 $2" 60 2>/dev/null; trap devlock_release EXIT; sleep $2' $H $T $hold; rc=$?
|
||||
[ $rc = 0 ] && [ ! -d $DM_DEVLOCK_DIR ] && ok "持锁 $hold 秒:退出码 0、锁已放" || { bad "持锁 $hold 秒:退出码 $rc、锁目录$([ -d $DM_DEVLOCK_DIR ] && echo 还在 || echo 已放)"; rm -rf $DM_DEVLOCK_DIR; }
|
||||
done
|
||||
echo "5. 持有者已死的锁:set -e 的后来者要收回并拿到"
|
||||
mkdir $DM_DEVLOCK_DIR; echo 999999 > $DM_DEVLOCK_DIR/pid; echo 死掉的持有者 > $DM_DEVLOCK_DIR/owner; date +%s > $DM_DEVLOCK_DIR/started; echo "Sun Oct 11 01:06:01 2026" > $DM_DEVLOCK_DIR/lstart; echo 600 > $DM_DEVLOCK_DIR/max
|
||||
bash -c 'set -euo pipefail; unset DM_DEVLOCK_HELD; source $0/devlock.sh; devlock_acquire 后来者 60 2>$1/s5.err; trap devlock_release EXIT; cat $DM_DEVLOCK_DIR/owner > $1/s5.owner' $H $T; rc=$?
|
||||
[ $rc = 0 ] && [ "$(cat $T/s5.owner 2>/dev/null)" = 后来者 ] && ok "死锁被收回,后来者拿到锁" || bad "退出码 $rc,锁内 owner「$(cat $DM_DEVLOCK_DIR/owner 2>/dev/null)」,输出:$(cat $T/s5.err)"
|
||||
[ ! -d $DM_DEVLOCK_DIR ] && ok "后来者退出后锁已放" || { bad "后来者退出后锁还在"; rm -rf $DM_DEVLOCK_DIR; }
|
||||
echo "6. 取不到锁要响亮:锁目录建不出来(父目录是个文件)→ 打【红】+ 非零退出"
|
||||
: > $T/notdir; DM_DEVLOCK_DIR=$T/notdir/device.lock DM_DEVLOCK_QUEUE=$T/q6 bash -c 'set -euo pipefail; unset DM_DEVLOCK_HELD; source $0/devlock.sh; devlock_acquire 取不到的 5 2>$1/s6.err; echo 不该走到这 > $1/s6.reach' $H $T & P6=$!
|
||||
( sleep 8; kill -KILL $P6 2>/dev/null ) & K6=$!; wait $P6 2>/dev/null; rc=$?; kill $K6 2>/dev/null
|
||||
[ $rc != 0 ] && [ $rc != 137 ] && grep -q '【红】设备锁:取不到的 没取到锁' $T/s6.err && [ ! -e $T/s6.reach ] && ok "退出码 $rc:$(grep -m1 【红】 $T/s6.err | cut -c1-60)…" || bad "退出码 $rc(137 = 挂住被本测试杀掉),输出:$(head -2 $T/s6.err)"
|
||||
rm -rf $T; [ $fail = 0 ] && echo "devlock_max_test 通过" || { echo "🔴 devlock_max_test 有不通"; exit 1; }
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/bash
|
||||
export DM_DEVBATTERY=0 DEVBATTERY_DIR=$(mktemp -d) # 锁单测不过电量闸、不写真电量日志(一次挂住的锁单测往真告警文件写了 18 条「读不到」) | Lock unit tests do not go through the battery gate and do not write the real battery log (a hung lock unit test once wrote 18 「读不到」(unreadable) entries into the real alert file)
|
||||
# devlock.sh 排队次序自测(不碰手机):持锁者在跑时,先到的测量号、后到的冒烟号、再后到的旧版无类别号——放锁后的拿锁次序应为 冒烟 → 旧版 → 测量。
|
||||
# Queue-order self-test for devlock.sh (does not touch the phone): while a holder is running, a measurement ticket arrives first, then a smoke test ticket, then an old-style classless ticket - after release the lock should be obtained in the order smoke test → old-style → measurement.
|
||||
set -u; H=$(cd "$(dirname "$0")" && pwd); T=$(mktemp -d); export DM_DEVLOCK_DIR=$T/device.lock DM_DEVLOCK_QUEUE=$T/device.queue
|
||||
w(){ ( unset DM_DEVLOCK_HELD; [ "$2" = measure ] && export DM_DEVLOCK_CLASS=measure; source $H/devlock.sh; devlock_acquire "$1" 2>/dev/null; echo "$1" >> $T/order; sleep 0.3; devlock_release ) & }
|
||||
( source $H/devlock.sh; devlock_acquire 持锁者 2>/dev/null; sleep 4; devlock_release ) &
|
||||
sleep 1; w 测量 measure; sleep 0.5; w 冒烟 smoke; sleep 0.5
|
||||
( mkdir -p $DM_DEVLOCK_QUEUE; sleep 30 & P=$!; K=$DM_DEVLOCK_QUEUE/$(python3 -c 'import time;print(time.time_ns())')_$P; mkdir $K; echo 旧版 > $K/owner
|
||||
until [ "$(ls $DM_DEVLOCK_QUEUE | LC_ALL=C sort | head -1 | sed 's/.*_//')" = $P ] && [ ! -d $DM_DEVLOCK_DIR ]; do sleep 0.1; done; echo 旧版 >> $T/order; kill $P; rm -rf $DM_DEVLOCK_QUEUE/*_$P ) &
|
||||
wait; got=$(tr '\n' ' ' < $T/order); rm -rf $T
|
||||
[ "$got" = "冒烟 旧版 测量 " ] && echo "devlock_test 通过:$got" || { echo "🔴 devlock_test 次序不对:期望「冒烟 旧版 测量」,实际「$got」"; exit 1; }
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""我们自己加的界面文字的中英表(英文版):唯一来源 dm/i18n/ui_text.tsv(键 / 中文 / English / 用在哪)。
|
||||
做法 = 把每一行作为新条目追加进原版字符串表 ui.json(RomFS 覆盖层,与 touch_strings 同一套机制):zhCN / zhTW 列 = 中文(繁体玩家读简体比读英文顺),其余 11 种语言列 = English。
|
||||
这样布局里写「@键」、宿主用原版取串 main+0x7f5630 取,语言切换由原版自己重装字符串表完成(SetLanguage,r34 起不剪),不用我们另跟语言。
|
||||
Chinese-English string table for the UI text we added ourselves (English version): single source dm/i18n/ui_text.tsv (key / Chinese / English / where used).
|
||||
Approach = append each row as a new entry to the original string table ui.json (RomFS overlay, same mechanism as touch_strings): zhCN / zhTW columns = Chinese (Traditional Chinese players read Simplified more easily than English), the other 11 language columns = English.
|
||||
This way layouts write "@key", the host fetches through the original string lookup at main+0x7f5630, and language switching is done by the original game reloading its string tables itself (SetLanguage, no longer patched out as of r34), so we do not have to follow the language separately."""
|
||||
import csv, json, os, re
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
TABLE = os.path.join(HERE, '..', '..', 'i18n', 'ui_text.tsv')
|
||||
LANGS = ('enUS', 'zhTW', 'deDE', 'esES', 'frFR', 'itIT', 'koKR', 'plPL', 'esMX', 'jaJP', 'ptBR', 'ruRU', 'zhCN') # 原版条目的列序 | column order of the original entries
|
||||
ID0 = 300000 # 原版全部字符串表最大 id 251780;我们的条目从这里起按表序编号 | the largest id across all original string tables is 251780; our entries are numbered from here in table order
|
||||
|
||||
PROPER = '老机型补充包|D2R Mobile Resources|D2R Mobile' # 英文里唯一许可的中文:App 显示名与资源文件夹名(玩家在桌面 /「文件」里看到的就是这几个字,改名另案,见盘点待定 6、7) | the only Chinese allowed in English text: the App display name and the asset folder name (these are the very characters the player sees on the home screen / in "Files"; renaming is a separate matter, see open items 6 and 7 of the inventory)
|
||||
FMT = re.compile(r'%[-+ #0-9.]*(?:ll|l|h|z)?[a-zA-Z@%]') # printf / strftime / NSString 占位符:中英两列必须同序同类(运行时拿英文串当格式串用) | printf / strftime / NSString placeholders: the Chinese and English columns must match in order and type (at run time the English string is used as a format string)
|
||||
|
||||
# 英文字数闸(进行中页「This Rift will be lost」被截断出框,靠人眼看图没拦住):大秘境面板 / 秘境提示各栏的英文上限(字符数,占位符按 3 个字符算)。
|
||||
# 数是按 Mac 截图量出来的每栏像素宽 ÷ 该栏字号下英文每字符平均宽度、再留一个字符余量——是按字数的近似,不是按字形逐个量宽;
|
||||
# 全是窄字母(i、l、1)的串实际更短,全是宽字母(M、W)的会更长,所以新词进表后仍要出图看一眼
|
||||
# English length gate (on the in-progress page "This Rift will be lost" was truncated and ran out of its box, and looking at screenshots by eye did not
|
||||
# catch it): English limits for each field of the Greater Rift panel / Rift messages (in characters, with a placeholder counted as 3 characters).
|
||||
# The numbers are each field's pixel width measured from Mac screenshots ÷ the average English character width at that field's font size, less one
|
||||
# character of margin. This is an approximation by character count, not a glyph-by-glyph width measurement;
|
||||
# a string made of narrow letters only (i, l, 1) is actually shorter and one made of wide letters only (M, W) is longer, so new wording added to the
|
||||
# table still needs a look at a screenshot
|
||||
EN_LIMITS = (
|
||||
(r'dmRiftSay(?!Prefix).*', 31),
|
||||
(r'dmRiftPtsGot', 62), (r'dmRiftPtsHeld', 33), # 通关点数两句:第一句中文就占两行(提示框自动换行),英文同样两行、不缩写;第二句一行 # 系统提示:前缀「Rift 」6 个字符 + 正文,提示框一行约 37 个字符 | the two clear-points sentences: the first already takes two lines in Chinese (the message box wraps automatically), so English is likewise two lines, unabbreviated; the second is one line # system messages: the prefix "Rift " is 6 characters plus the body, and one message box line holds about 37 characters
|
||||
(r'dmRift(Range|Best|Str|Lvl|Time)', 13), # 左栏「标签 + 值」的标签(英文专用小字号控件,值最长 7 个字符) | labels of the left column's "label + value" rows (English-only small-font widget; values are at most 7 characters)
|
||||
(r'dmRiftGam(Uni|Set)', 8), (r'dmRiftGamAfterEn', 17),
|
||||
(r'dmRift(SelT|InfT|GamT|TitleRun|TitleDone|TitleLate)', 16), # 左栏小标题(中号字,栏宽约 160 像素) | left column small headings (medium font, column about 160 pixels wide)
|
||||
(r'dmRift(GuardDown|NextOpen|Saved|RetryOpen|NotCounted)', 16), # 已完成页那三行(整行,中号字) | the three lines on the completed page (full lines, medium font)
|
||||
(r'dmRiftCap.*', 20), # 按钮上方的说明(英文专用小字号控件) | caption above the buttons (English-only small-font widget)
|
||||
(r'dmRiftBtn.*', 12), # 按钮上的字 | text on the buttons
|
||||
(r'dmRiftMsItem\d+', 15), (r'dmRiftMsSub\d+', 19), (r'dmRiftMsTier\d+', 4), (r'dmRiftMs(Got|Next|No)', 7), (r'dmRiftMsT', 12), (r'dmRiftMsNEn', 38),
|
||||
(r'dmRiftHud(Title)', 4), (r'dmRiftHud(Done|Late|Guard)', 18), (r'dmRiftHud(Next|Same|Kill|Goal)', 26),
|
||||
(r'dmKbRiftUnlock', 9), (r'dmKbRift(Best|Total)', 16),
|
||||
)
|
||||
# 键只许字母数字:布局里「@键」的解析遇到 _ 就断(@dmCustom_auto_mana 显示成「丢失字符串_auto_mana」,Mac 上的 iOS 包实测)
|
||||
# Keys may contain only letters and digits: parsing of "@key" in layouts stops at _ (@dmCustom_auto_mana is displayed as "<missing string>_auto_mana",
|
||||
# measured on the iOS app on Mac)
|
||||
def rows():
|
||||
out = []
|
||||
with open(TABLE, encoding='utf-8') as f:
|
||||
for r in csv.DictReader(f, delimiter='\t'):
|
||||
k, zh, en = r['键'], r['中文'].replace('\\n', '\n'), r['English'].replace('\\n', '\n')
|
||||
if not re.fullmatch(r'dm[A-Za-z0-9]+', k) or not zh or not en: raise SystemExit('dm_i18n:表里这一行不对:%r' % r)
|
||||
if re.search(r'[ -鿿-]', re.sub(PROPER, '', en)): raise SystemExit('dm_i18n:%s 的英文里有中文字符:%r' % (k, en))
|
||||
if FMT.findall(zh) != FMT.findall(en): raise SystemExit('dm_i18n:%s 的中英占位符不一致:%s / %s' % (k, FMT.findall(zh), FMT.findall(en)))
|
||||
lim = next((n for pat, n in EN_LIMITS if re.fullmatch(pat, k)), None) # 英文字数闸(见 EN_LIMITS) | English length gate (see EN_LIMITS)
|
||||
if lim is not None and len(FMT.sub('000', en).split('\n')[0]) > lim: raise SystemExit('dm_i18n:%s 的英文「%s」%d 个字符,超过这一栏的上限 %d(会顶框 / 被截断;压短,或给这一栏做英文专用的小字号控件后再改上限)' % (k, en, len(FMT.sub('000', en)), lim))
|
||||
out.append((k, zh, en))
|
||||
ks = [k for k, _, _ in out]
|
||||
if len(set(ks)) != len(ks): raise SystemExit('dm_i18n:键重复:%s' % sorted({k for k in ks if ks.count(k) > 1}))
|
||||
return out
|
||||
|
||||
def build(romfs, outdir, repl):
|
||||
"""repl:前面步骤已换的 {包内逻辑路径: 本地文件}。返回 ({包内逻辑路径: 本地文件}, 条数)。 | repl: {logical path in the package: local file} already replaced by earlier steps. Returns ({logical path in the package: local file}, entry count)."""
|
||||
import touch_layout # 用时再导:touch_layout 自己在模块层要读本表(自定义页行数),顶层互导会半初始化 | imported at use time: touch_layout itself reads this table at module level (row count of the Custom page), and a top-level mutual import would leave it half-initialized
|
||||
path, text = touch_layout.read_layout(romfs, None, suffix='/lng/strings/ui.json')
|
||||
prev = repl.get(path.lower())
|
||||
if prev: text = open(prev, encoding='utf-8-sig').read()
|
||||
have = set(re.findall(r'"Key":\s*"((?:[^"\\]|\\.)*)"', text))
|
||||
rs = rows()
|
||||
clash = [k for k, _, _ in rs if k in have]
|
||||
if clash: raise SystemExit('dm_i18n:键和原版重名:%s' % clash)
|
||||
add = [{'id': ID0 + i, 'Key': k, **{l: (zh if l in ('zhCN', 'zhTW') else en) for l in LANGS}} for i, (k, zh, en) in enumerate(rs)]
|
||||
end = text.rstrip().rindex(']')
|
||||
body = ',\n'.join(' ' + json.dumps(e, ensure_ascii=False) for e in add)
|
||||
text = text[:end].rstrip() + ',\n' + body + '\n' + text[end:]
|
||||
json.loads(text) # 拼完还是合法 JSON | still valid JSON after assembly
|
||||
o = os.path.join(outdir, 'i18n_ui.json'); open(o, 'w', encoding='utf-8-sig', newline='').write(text)
|
||||
return {path.lower(): o}, len(add)
|
||||
|
||||
def header():
|
||||
"""dm/host/dm_i18n_tab.h 的内容(游戏外画的字用的编译期表)。 | Contents of dm/host/dm_i18n_tab.h (the compile-time table for text drawn outside the game)."""
|
||||
c = lambda s: json.dumps(s, ensure_ascii=False) # JSON 串的转义在 C 里同样成立(\n \" \\) | JSON string escapes are equally valid in C (newline, double quote, backslash)
|
||||
out = ['// 生成文件,勿手改:python3 dm/ios/tools/dm_i18n.py --header > dm/host/dm_i18n_tab.h(表 dm/i18n/ui_text.tsv)', '#pragma once',
|
||||
'static const struct { const char *k, *zh, *en; } k_dm_i18n[] = {']
|
||||
out += [' { %s, %s, %s },' % (c(k), c(zh), c(en)) for k, zh, en in rows()]
|
||||
return '\n'.join(out + ['};', ''])
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
if sys.argv[1:] == ['--header']: sys.stdout.write(header())
|
||||
elif sys.argv[1:] == ['--check']: # 单测:表与入库的头文件一致 | unit test: the table matches the checked-in header file
|
||||
h = os.path.join(HERE, '..', '..', 'host', 'dm_i18n_tab.h')
|
||||
if open(h, encoding='utf-8').read() != header(): raise SystemExit('dm_i18n:dm/host/dm_i18n_tab.h 过期,重跑 python3 dm/ios/tools/dm_i18n.py --header > dm/host/dm_i18n_tab.h')
|
||||
print('dm_i18n OK %d 条' % len(rows()))
|
||||
else: raise SystemExit('用法:dm_i18n.py --header | --check')
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
# 高价值掉落的光(第二批):覆盖层里给物品的「地面模型定义」json 出两档带光变体,
|
||||
# 由宿主在「地上物品取模型路径」那一刻按规则改指过去(dm/host/dm_dropfilter.c,剪口 svc #0x87 落在 main+0x8fa590)。
|
||||
# 变体常驻覆盖层(不进开关组合份数):开关、档位、筛选都由宿主运行时决定,没被改指的变体游戏不会去读。
|
||||
# 变体 = 原模型定义 + 一个原版特效实体:一档 = 原版赫拉迪克光(白色竖光柱),二档 = 原版迪亚波罗光柱(橙色斜光束)。
|
||||
# 不加贴图、不加着色器、不放大模型、不加爆闪 / 头顶感叹号。路径:data/hd/items/<类别>/zswg/<档>__<模型名,/ 换成 __>.json(新增路径,casc_overlay「+」)。
|
||||
# 覆盖哪些模型:items.json / uniques.json / sets.json 指向的、在武器 / 盔甲两类下的全部模型(暗金 / 套装可以是任何底材),
|
||||
# 加上杂项里会发光的几类(符文、戒指、项链、护身符、钥匙、任务道具)。原版表里指向包里不存在模型的条目跳过(宿主改指前不核存在性:
|
||||
# 那些条目原本就画不出来)。
|
||||
# Light on high-value drops (second batch): in the overlay, produce two tiers of lit variants of the items' "ground model definition" json,
|
||||
# and the host redirects to them by rule at the moment of "ground item fetches its model path" (dm/host/dm_dropfilter.c, cut svc #0x87 lands at main+0x8fa590).
|
||||
# Variants live permanently in the overlay (not counted in the number of switch-combination copies): switch, tier and filter are all decided by the host at run time, and the game never reads a variant that is not redirected to.
|
||||
# Variant = original model definition + one effect entity from the original game: tier 1 = the original game's Horadric light (white vertical light shaft), tier 2 = the original game's Diablo light shaft (orange slanted beam).
|
||||
# No textures added, no shaders added, no model enlargement, no flash burst / overhead exclamation mark. Path: data/hd/items/<category>/zswg/<tier>__<model name, / replaced by __>.json (new path, casc_overlay "+").
|
||||
# Which models are covered: all models pointed to by items.json / uniques.json / sets.json under the weapon / armor categories (uniques / sets can be any base),
|
||||
# plus the few glowing kinds among misc (runes, rings, amulets, charms, keys, quest items). Entries in the original tables that point to models missing from the package are skipped (the host does not check existence before redirecting:
|
||||
# those entries could not be drawn in the first place).
|
||||
import hashlib, json, os, sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import touch_layout
|
||||
|
||||
GLOW = 'data/hd/vfx/particles/overlays/object/horadric_light/fx_horadric_light.particles' # 一档 | Tier 1
|
||||
SHAFT = 'data/hd/vfx/particles/missiles/diablo_light_shaft/fx_diablo_light_shaft.particles' # 二档 | Tier 2
|
||||
TIERS = {'1': GLOW, '2': SHAFT}
|
||||
ROOTS = ('weapon', 'armor', 'misc')
|
||||
MISC_LIT = ('rune/', 'ring/', 'amulet/', 'charm/', 'key/', 'quest/')
|
||||
|
||||
def add_light(text, fx, name):
|
||||
"""地面模型定义 → 挂上特效的新文本。实体 id 由文件名定(同一输入同一输出)。 | Ground model definition → new text with the effect attached. The entity id is determined by the file name (same input, same output)."""
|
||||
d = json.loads(text); assert d.get('type') == 'UnitDefinition', name
|
||||
deps = d['dependencies'].setdefault('particles', [])
|
||||
if not any(p.get('path', '').lower() == fx for p in deps): deps.append({'path': fx})
|
||||
eid = int.from_bytes(hashlib.md5(('droplight:' + name).encode()).digest()[:4], 'little') | 1
|
||||
d['entities'].append({'type': 'Entity', 'name': 'droplight', 'id': eid, 'components': [
|
||||
{'type': 'TransformDefinitionComponent', 'name': 'component_transform_droplight', 'position': {'x': 0.0, 'y': 0.0, 'z': 0.0},
|
||||
'orientation': {'x': 0.0, 'y': 0.0, 'z': 0.0, 'w': 1.0}, 'scale': {'x': 1.0, 'y': 1.0, 'z': 1.0}, 'inheritOnlyPosition': False},
|
||||
{'type': 'VfxDefinitionComponent', 'name': 'component_vfx_droplight', 'filename': fx, 'hardKillOnDestroy': False}]})
|
||||
return json.dumps(d, separators=(',', ':'))
|
||||
|
||||
def variant_path(root, asset, tier):
|
||||
"""宿主改写规则的离线一份(两边必须一致):data/hd/items/<root>/<asset>.json → data/hd/items/<root>/zswg/<tier>__<asset 里 / 换 __>.json | Offline copy of the host's rewrite rule (the two sides must match): data/hd/items/<root>/<asset>.json → data/hd/items/<root>/zswg/<tier>__<asset with / replaced by __>.json"""
|
||||
return f'data/hd/items/{root}/zswg/{tier}__' + asset.lower().replace('/', '__') + '.json'
|
||||
|
||||
def build(romfs, outdir, repl):
|
||||
"""返回 ({逻辑路径: 文件}(新增路径带「+」前缀), 统计)。repl 里已有同一原模型时在那份上叠加。 | Returns ({logical path: file} (new paths carry a "+" prefix), statistics). If repl already has the same original model, layer on top of that copy."""
|
||||
manifest = set()
|
||||
for line in open(os.path.join(romfs, 'data', 'build_manifest.psv'), encoding='utf-8'):
|
||||
f = line.rstrip('\n').split('|')
|
||||
if len(f) >= 11 and not line.startswith('#'): manifest.add(f[9].split(':', 1)[-1].lower())
|
||||
assets = set()
|
||||
for table in ('items.json', 'uniques.json', 'sets.json'):
|
||||
for row in json.loads(touch_layout.read_layout(romfs, None, suffix='/hd/items/' + table)[1]):
|
||||
(_, v), = row.items()
|
||||
assets.update(x.lower() for x in ([v['asset']] if 'asset' in v else [v[k] for k in ('normal', 'uber', 'ultra')]))
|
||||
out, skipped = {}, 0
|
||||
for asset in sorted(assets):
|
||||
root = next((r for r in ROOTS if f'data/hd/items/{r}/{asset}.json' in manifest), None)
|
||||
if root is None: skipped += 1; continue
|
||||
if root == 'misc' and not asset.startswith(MISC_LIT): continue
|
||||
src = f'data/hd/items/{root}/{asset}.json'
|
||||
text = open(repl[src], encoding='utf-8').read() if src in repl else touch_layout.read_layout(romfs, None, suffix='/' + src.split('/', 1)[1])[1]
|
||||
for tier, fx in TIERS.items():
|
||||
dst = variant_path(root, asset, tier)
|
||||
o = os.path.join(outdir, 'droplight_' + dst.replace('/', '_')); open(o, 'w').write(add_light(text, fx, dst)); out['+' + dst] = o
|
||||
return out, f'掉落光变体:{len(out) // 2} 个模型 × 2 档(原表指向不存在模型、跳过 {skipped} 个)'
|
||||
|
||||
if __name__ == '__main__': # 试验:drop_light.py <RomFS> <输出目录> → 只含本模块改动的 repl.tsv(casc_overlay.py 直接吃) | Trial: drop_light.py <RomFS> <output dir> → a repl.tsv containing only this module's changes (consumed directly by casc_overlay.py)
|
||||
romfs, out = sys.argv[1:3]; os.makedirs(out, exist_ok=True)
|
||||
r, stat = build(romfs, out, {})
|
||||
with open(os.path.join(out, 'repl.tsv'), 'w') as f:
|
||||
for k, v in r.items(): f.write(f'{k}\t{v}\n')
|
||||
print(stat)
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
# 「重场面」触点脚本:亡者大殿二层(第二幕,区域号 57,levels.txt 怪物密度最高一档 2200,Lv76 角色 joe 的存档自带这个小站)。真机 touch_e2e.sh / Mac touch_e2e_mac.sh 通用。
|
||||
# 用法:gen_heavy.py <总秒数> [到达后开始秒=17] > 脚本.txt,配套环境见同目录 heavy.env.sh(小站回放 + 键序传送 + 起局人数档 8)。
|
||||
# 动作:先推摇杆离开小站(站在小站上按攻击键是「再开小站页」),之后摇杆每 4 秒左右换向来回走(边走边拉怪),攻击键每 0.5 秒点一下。
|
||||
# 证据:perf.txt 场景列「区域57」、e2e_state.jsonl 的怪物表计数、boot.txt 的「每帧绘制」。
|
||||
# "Heavy scene" touch point script: Halls of the Dead Level 2 (Act 2, area number 57, the highest monster density tier 2200 in levels.txt, the save of the Lv76 character joe already has this waypoint). Works for both real device touch_e2e.sh / Mac touch_e2e_mac.sh.
|
||||
# Usage: gen_heavy.py <total seconds> [start second after arrival=17] > script.txt, the matching environment is in heavy.env.sh in the same directory (waypoint replay + key-sequence teleport + run-start /players setting 8).
|
||||
# Actions: first push the stick to leave the waypoint (pressing the attack key while standing on the waypoint is "open the waypoint page again"), after that the stick changes direction about every 4 seconds, walking back and forth (pulling monsters while walking), and the attack key is tapped every 0.5 seconds.
|
||||
# Evidence: 「区域57」(area 57) in the scene column of perf.txt, the monster table count in e2e_state.jsonl, 「每帧绘制」(draws per frame) in boot.txt.
|
||||
import sys
|
||||
total = float(sys.argv[1]); t0 = float(sys.argv[2]) if len(sys.argv) > 2 else 17.0
|
||||
ev = [(t0, "down 0 @joy"), (t0 + 0.1, "move 0 @joy+40,0")]
|
||||
t = t0 + 2.0; left = True
|
||||
while t < total - 1.0:
|
||||
ev.append((t, f"move 0 @joy+{-40 if left else 40},0")); left = not left; t += 4.0
|
||||
ev.append((total - 0.5, "up 0"))
|
||||
t = t0 + 2.2
|
||||
while t < total - 1.0:
|
||||
ev.append((t, "down 1 @main")); ev.append((t + 0.15, "up 1")); t += 0.5
|
||||
for t, s in sorted(ev, key=lambda e: e[0]): print(f"{t:.2f} {s}")
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
# 生成「进野外后向左走 + 连续攻击」的触点脚本(真机 touch_e2e.sh / Mac touch_e2e_mac.sh 通用,只用 @名字 目标,不依赖屏幕尺寸)。
|
||||
# 用法:gen_wild.py <总秒数> [起始秒=18] > 脚本.txt;配 PREFIX=<wild_prefix_original_warlock>/c2s.jsonl(前缀回放约 16 s 把角色带到营地门外、区域 2 鲜血荒地)。
|
||||
# 摇杆(触点 0)全程向左推满;攻击键(触点 1)每 0.6 秒点一下(按 0.15 秒)。证据:perf.txt 场景列的区域号 / 坐标在变,dm_hud 行的经验 ‰ 在涨。
|
||||
# 出处:在 Mac 上试出的走法(进鲜血荒地打到沉沦魔,经验 0 → 108‰)。
|
||||
# Generates the touch point script for "walk left after entering the wilderness + continuous attack" (works for both real device touch_e2e.sh / Mac touch_e2e_mac.sh, uses only @name targets, independent of screen size).
|
||||
# Usage: gen_wild.py <total seconds> [start second=18] > script.txt; pair with PREFIX=<wild_prefix_original_warlock>/c2s.jsonl (the prefix replay takes about 16 s to bring the character outside the camp gate, area 2 Blood Moor).
|
||||
# The stick (touch point 0) is pushed fully left the whole time; the attack key (touch point 1) is tapped every 0.6 seconds (held 0.15 seconds). Evidence: the area number / coordinates in the scene column of perf.txt are changing, and the experience ‰ on the dm_hud line is rising.
|
||||
# Source: a route worked out by trial on Mac (entering the Blood Moor and fighting Fallen, experience 0 → 108‰).
|
||||
import sys
|
||||
total = float(sys.argv[1]); t0 = float(sys.argv[2]) if len(sys.argv) > 2 else 18.0
|
||||
print(f"{t0:.2f} down 0 @joy"); print(f"{t0 + 0.1:.2f} move 0 @joy+-40,0")
|
||||
t = t0 + 0.5
|
||||
while t < total - 1.0:
|
||||
print(f"{t:.2f} down 1 @main"); print(f"{t + 0.15:.2f} up 1"); t += 0.6
|
||||
print(f"{total - 0.5:.2f} up 0")
|
||||
@@ -0,0 +1,5 @@
|
||||
# 重场面起局环境(source 后再调 touch_e2e.sh / touch_e2e_mac.sh):小站回放把 joe 带到营地小站 → 拍 135 开小站页 → ZR 切第二幕 → 下 ×3 → A 传到亡者大殿二层;起局人数档 8(怪更耐打,场面不会越打越轻)
|
||||
# Heavy scene run-start environment (source it, then call touch_e2e.sh / touch_e2e_mac.sh): the waypoint replay brings joe to the camp waypoint → at tick 135 open the waypoint page → ZR switches to Act 2 → down ×3 → A teleports to Halls of the Dead Level 2; run-start /players setting 8 (monsters take more hits, so the scene does not get lighter as the fight goes on)
|
||||
export PREFIX=${DM_ROOT:-$HOME/dm-work}/data/switch/truth_runs/wp1/c2s_to_E.jsonl
|
||||
export E2E_KEYS='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,MSG:CharacterSelect:LoadCharacter:0@OpenPanel:CharacterSelectPanel%1>FrontEndNavigation:ToGame,A@DM:Tick:135#>OpenPanel:WaypointsPanelExpansion,ZR@OpenPanel:WaypointsPanelExpansion%1,DOWN@%0.5,DOWN@%0.5,DOWN@%0.5,A@%0.6'
|
||||
export E2E_ENV='{"DM_FIXED_TIME":"1790000000","DM_PLAYERS":"8"}'
|
||||
@@ -0,0 +1,50 @@
|
||||
# 帧对拍:iPhone 截帧 vs Mac 截帧,遮罩外逐位全等才算过。
|
||||
# 遮罩 = Mac 自身两次运行有差异的区域(按墙钟推进的动画等非确定区,自动取)∪ --rect 给的固定矩形。
|
||||
# 自动区按 16×16 块取:块内有任一自身差异像素即整块遮掉,再外扩 1 块——动画区里两次 Mac 碰巧相同的像素
|
||||
# 照样随机变(实测逐像素遮罩漏掉 365 个),所以遮的是区域不是像素。
|
||||
# 用法:frame_cmp.py <mac_a.png> <mac_b.png> <ios.png> [--rect x0,y0,x1,y1 ...] [--mask-out mask.png]
|
||||
# 退出码 0 = 遮罩外全等;1 = 有差(打印差异区)。整块动画区两次 Mac 恰好全同时会漏遮 → 报红而不是放过。
|
||||
# Frame comparison: iPhone captured frame vs Mac captured frame; passes only if bit-identical outside the mask.
|
||||
# Mask = regions that differ between two runs of Mac itself (non-deterministic regions such as wall-clock-driven animation, taken automatically) ∪ fixed rectangles given by --rect.
|
||||
# The automatic region is taken in 16×16 tiles: a tile with any self-difference pixel is masked entirely, then grown by 1 tile - pixels inside an animated region that happened to match between the two Mac runs
|
||||
# still vary randomly (measured: a per-pixel mask missed 365), so what is masked is regions, not pixels.
|
||||
# Usage: frame_cmp.py <mac_a.png> <mac_b.png> <ios.png> [--rect x0,y0,x1,y1 ...] [--mask-out mask.png]
|
||||
# Exit code 0 = identical outside the mask; 1 = differences (prints the differing regions). If an entire animated region happens to be fully identical between the two Mac runs it will be under-masked → reports a failure rather than letting it through.
|
||||
import argparse, sys
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('mac_a'); ap.add_argument('mac_b'); ap.add_argument('ios')
|
||||
ap.add_argument('--rect', action='append', default=[], help='x0,y0,x1,y1(含端点)')
|
||||
ap.add_argument('--mask-out')
|
||||
o = ap.parse_args()
|
||||
paths, mask_out = (o.mac_a, o.mac_b, o.ios), o.mask_out
|
||||
rects = [tuple(map(int, r.split(','))) for r in o.rect]
|
||||
a, b, c = (np.asarray(Image.open(p).convert('RGBA')).astype(np.int16) for p in paths)
|
||||
if not (a.shape == b.shape == c.shape): sys.exit(f'【红】尺寸不一:{a.shape} {b.shape} {c.shape}')
|
||||
H, W = a.shape[:2]
|
||||
T = 16
|
||||
self_px = np.abs(a - b).max(axis=2) > 0 # Mac 自身非确定像素 | Mac's own non-deterministic pixels
|
||||
th, tw = (H + T - 1) // T, (W + T - 1) // T
|
||||
tiles = np.zeros((th, tw), bool)
|
||||
ys, xs = np.nonzero(self_px); tiles[ys // T, xs // T] = True
|
||||
grown = tiles.copy() # 外扩 1 块 | Grow by 1 tile
|
||||
for dy in (-1, 0, 1):
|
||||
for dx in (-1, 0, 1):
|
||||
grown |= np.pad(tiles, 1)[1 + dy:1 + dy + th, 1 + dx:1 + dx + tw]
|
||||
mask = np.kron(grown, np.ones((T, T), bool))[:H, :W]
|
||||
auto_n = int(mask.sum())
|
||||
for x0, y0, x1, y1 in rects: mask[y0:y1 + 1, x0:x1 + 1] = True
|
||||
diff = np.abs(c - a).max(axis=2)
|
||||
bad = (diff > 0) & ~mask
|
||||
inside = int(((diff > 0) & mask).sum())
|
||||
print(f'尺寸 {W}×{H};Mac 自身差异 {int(self_px.sum())} 像素 → 自动遮罩 {int(grown.sum())} 块 {auto_n} 像素;矩形 {len(rects)} 个;遮罩合计占 {mask.sum() / mask.size:.2%}')
|
||||
if not self_px.any(): print('【警告】Mac 两次无自身差异:按墙钟变化的区域没暴露出来,遮罩可能不全,下方的红可能是误报')
|
||||
print(f'遮罩外:比对 {int((~mask).sum())} 像素,不同 {int(bad.sum())};遮罩内不同 {inside}(不计)')
|
||||
if mask_out: Image.fromarray((mask * 255).astype(np.uint8)).save(mask_out)
|
||||
if bad.any():
|
||||
ys, xs = np.nonzero(bad)
|
||||
print(f'【红】遮罩外有差:x {xs.min()}–{xs.max()} y {ys.min()}–{ys.max()},最大分量差 {int(diff[bad].max())}')
|
||||
sys.exit(1)
|
||||
print('全过:遮罩外逐位全等')
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
# 真机 vs Mac 第 N 帧逐像素对拍(每次 main 更新后跑):Mac 截两次(取自身非确定区作遮罩)→ 真机截一次 → frame_cmp.py。
|
||||
# 用法:dm/ios/tools/frame_cmp.sh [帧号=300] [--rect x0,y0,x1,y1 ...] 产物与日志在 $DM_ROOT/run/ios/cmp/(每次清空重来)
|
||||
# 退出码 0 = 遮罩外逐位全等且屏幕级三项全过。宽屏产物对拍:DM_GAME_RES=宽x高 让 Mac 按同分辨率出图(front_mac.m)。Mac 截到图即停该进程(按自记 pid);真机按看门狗 DM_WATCH 收尾。
|
||||
# 帧号与时间:两端出图节拍同为 60 Hz、游戏出图间隔 2(约 30 帧/秒,窗口与无窗口一致),第 N 帧约在 N/30 秒;
|
||||
# 缺省 300(约 10 秒)落在选角页稳态(r5 起打开即选角,约 2.4 秒到主菜单)。
|
||||
# Per-pixel comparison of frame N, real device vs Mac (run after every main update): Mac captures twice (its own non-deterministic regions become the mask) → the real device captures once → frame_cmp.py.
|
||||
# Usage: dm/ios/tools/frame_cmp.sh [frame=300] [--rect x0,y0,x1,y1 ...] Build output and logs are in $DM_ROOT/run/ios/cmp/ (cleared and redone every time)
|
||||
# Exit code 0 = bit-identical outside the mask and all three screen-level checks pass. Widescreen build output comparison: DM_GAME_RES=WxH makes Mac output frames at the same resolution (front_mac.m). The Mac process is stopped as soon as its image is captured (by the self-recorded pid); the real device is wound up by the watchdog DM_WATCH.
|
||||
# Frame number and time: both ends present frames at a 60 Hz cadence with a game present interval of 2 (about 30 frames/second, the same with and without a window), so frame N is at about N/30 seconds;
|
||||
# the default 300 (about 10 seconds) lands in the steady state of the character select page (since r5 it opens straight to character select, about 2.4 seconds to the main menu).
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
N=300; case "${1:-}" in [0-9]*) N=$1; shift ;; esac
|
||||
OUT=${DM_OUT:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/3.3.94012-r10}
|
||||
C=${DM_ROOT:-$HOME/dm-work}/run/ios/cmp; rm -rf "$C"; mkdir -p "$C"
|
||||
source tools/local_env.sh && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
|
||||
SAVE_REF=${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref/0000000000000001/0 # 标准存档:每局拷新副本(两端起始状态一致) | Standard save: a fresh copy per run (same starting state on both ends)
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
|
||||
# 前置:真机 RomFS 完整(46 个文件)。缺了游戏会在 nnMain 早退,症状只是「没截到帧」,在这里直接报根因
|
||||
# Precondition: the real device's RomFS is complete (46 files). If any is missing the game exits early in nnMain and the only symptom is "no frame captured"; report the root cause directly here
|
||||
xcrun devicectl device info files --device $D --domain-type appDataContainer --domain-identifier $B --subdirectory Documents/romfs/data --json-output "$C/romfs_ls.json" > /dev/null 2>&1
|
||||
nf=$(python3 -c "import json; d=json.load(open('$C/romfs_ls.json')); print(sum(not f['resources']['isDirectory'] for f in d['result']['files']))" 2>/dev/null)
|
||||
[ "${nf:-0}" = 46 ] || { t "🔴 真机 Documents/romfs/data 文件数 ${nf:-0} ≠ 46:RomFS 不全,先推送(见 dm/ios/README.md 推送一节)"; exit 1; }
|
||||
make -s -C ../host || { t "🔴 Mac 宿主编译失败"; exit 1; }
|
||||
# Mac 两次:第二次压到后台 QoS(能效核)跑慢,使到第 N 帧时墙钟不同,按墙钟推进的动画才会在两次间露出差异
|
||||
# (两次全速连跑到第 300 帧同为 1–3 秒,动画相位相同、自身差异 0;慢跑 3/3 次露出约 6,600 像素)
|
||||
# Mac twice: the second run is pushed to background QoS (efficiency cores) to run slow, so the wall clock at frame N differs and wall-clock-driven animation shows differences between the two runs
|
||||
# (two back-to-back full-speed runs both reach frame 300 in 1–3 seconds, with the same animation phase and 0 self-difference; the slow run exposed about 6,600 pixels in 3/3 tries)
|
||||
for k in a b; do
|
||||
POL=""; [ $k = b ] && POL="taskpolicy -c background"
|
||||
rm -rf "$C/save_$k"; cp -R "$SAVE_REF" "$C/save_$k" && chmod -R u+w "$C/save_$k" || { t "🔴 拷标准存档失败"; exit 1; }
|
||||
DM_SAVE="$C/save_$k" DM_NVN_SHOT="$N:$C/mac_$k.png" DM_WATCH=120 $POL ../host/dmhost "$OUT" main sdk > "$C/mac_$k.log" 2>&1 & pid=$!
|
||||
s=$SECONDS
|
||||
until grep -q "截图.*$C/mac_$k.png" "$C/mac_$k.log" 2>/dev/null; do
|
||||
kill -0 $pid 2>/dev/null || { t "🔴 Mac 第 $k 次在截到第 $N 帧前退出"; tail -3 "$C/mac_$k.log"; exit 1; }
|
||||
[ $((SECONDS - s)) -gt 120 ] && { kill $pid; t "🔴 Mac 第 $k 次 120 秒未到第 $N 帧"; exit 1; }
|
||||
sleep 1
|
||||
done
|
||||
kill $pid 2>/dev/null; wait $pid 2>/dev/null
|
||||
t "Mac 第 $k 次截到($((SECONDS - s)) 秒)"
|
||||
done
|
||||
|
||||
./run.sh build > "$C/ios_build.log" 2>&1 || { t "🔴 真机构建失败"; tail -5 "$C/ios_build.log"; exit 1; }
|
||||
./run.sh install >> "$C/ios_build.log" 2>&1 || { t "🔴 真机装机失败"; tail -5 "$C/ios_build.log"; exit 1; }
|
||||
# 真机存档:App 自己把 Documents/save 换成资源里的 save_ref 新副本(DM_SAVE_FRESH)。勿用 devicectl --remove-existing-content:它会清掉整个 Documents
|
||||
# Real-device save: the App itself replaces Documents/save with a fresh copy of save_ref from its resources (DM_SAVE_FRESH). Do not use devicectl --remove-existing-content: it wipes the entire Documents
|
||||
DEVICECTL_CHILD_DM_SAVE_FRESH=1 DEVICECTL_CHILD_DM_NVN_SHOT="$N:cmp_$N.png" DEVICECTL_CHILD_DM_SCREEN_SHOT="$((N / 30 + 3)):screen.png" DEVICECTL_CHILD_DM_WATCH=${DM_IOS_WATCH:-45} ./run.sh boot 120 > "$C/ios_run.log" 2>&1
|
||||
cp "${DM_ROOT:-$HOME/dm-work}/run/ios/out/boot.txt" "$C/ios.log" 2>/dev/null
|
||||
grep -q "截图.*cmp_$N.png 成功" "$C/ios.log" || { t "🔴 真机没截到第 $N 帧(看 $C/ios.log;可加大 DM_IOS_WATCH)"; exit 1; }
|
||||
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B \
|
||||
--source "Documents/cmp_$N.png" --destination "$C/ios.png" > /dev/null 2>&1 || { t "🔴 拉回真机截图失败"; exit 1; }
|
||||
t "真机截到并拉回"
|
||||
# 屏幕级截图(整个窗口:方向、黑边、实际显示):在第 N 帧之后约 3 秒截;三项自动核见 screen_check.py(DM_SCREEN_WANT=full | 16:9,缺省 full)
|
||||
# Screen-level screenshot (the whole window: orientation, black bars, what is actually displayed): taken about 3 seconds after frame N; for the three automatic checks see screen_check.py (DM_SCREEN_WANT=full | 16:9, default full)
|
||||
for f in screen.png screen.png.txt; do
|
||||
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source "Documents/$f" --destination "$C/$f" > /dev/null 2>&1 || { t "🔴 拉回屏幕级截图 $f 失败"; exit 1; }
|
||||
done
|
||||
python3 tools/screen_check.py "$C/screen.png" "$C/screen.png.txt" "$C/ios.log" --want "${DM_SCREEN_WANT:-full}"; SC=$?
|
||||
|
||||
python3 tools/frame_cmp.py "$C/mac_a.png" "$C/mac_b.png" "$C/ios.png" --mask-out "$C/mask.png" "$@"; FC=$?
|
||||
exit $(( FC || SC ))
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
# iOS 全屏验收(屏幕级截图):② 不拉伸、④ 游戏输出分辨率 = 前端给的值;①(铺满无黑边)见 screen_check.py --want full。
|
||||
# 全屏不留安全区(界面按游戏原样铺满,不为灵动岛 / 圆角往里收)→ ③ 只出参考数据与叠线图,不判红。
|
||||
# 用法:fullscreen_check.py <页 sel|cls|game> <screen.png> <screen.png.txt> <boot.log> [16:9 负对照屏幕截图.png]
|
||||
# ② 不拉伸:(a) 出图横纵缩放差(闭式,三页);(b) 局内页 HUD 中段对 16:9 负对照截图的横纵缩放比(图像);均 ≤ 1%
|
||||
# ③(参考,不判):选角页左侧菜单面板左缘对安全区左边距;三页都出叠了安全区框线的图 <screen>_安全区.png
|
||||
# ④ 日志「前端给游戏的输出分辨率 主机 WxH」== 「WindowInitialize 交换链 … 首张 WxH」
|
||||
# iOS full-screen acceptance (screen-level screenshots): ② no stretching, ④ game output resolution = the value given by the front end; for ① (fills the screen with no black bars) see screen_check.py --want full.
|
||||
# Full screen keeps no safe area (the UI fills the screen exactly as the game draws it, not inset for the Dynamic Island / rounded corners) → ③ only produces reference data and an overlaid-line image, and never fails anything.
|
||||
# Usage: fullscreen_check.py <page sel|cls|game> <screen.png> <screen.png.txt> <boot.log> [16:9 negative-control screenshot.png]
|
||||
# ② No stretching: (a) difference between horizontal and vertical output scale (closed form, three pages); (b) on the in-run page, horizontal/vertical scale ratio of the HUD middle section against the 16:9 negative-control screenshot (image); both ≤ 1%
|
||||
# ③ (reference, not judged): left edge of the left menu panel on the character select page versus the safe-area left margin; all three pages produce an image with the safe-area frame lines overlaid, <screen>_安全区.png
|
||||
# ④ Log 「前端给游戏的输出分辨率 主机 WxH」(output resolution the front end gives the game, console WxH) == 「WindowInitialize 交换链 … 首张 WxH」(WindowInitialize swapchain ... first image WxH)
|
||||
import sys, re
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw
|
||||
from scipy import ndimage
|
||||
|
||||
page, png, meta, log = sys.argv[1:5]; ref = sys.argv[5] if len(sys.argv) > 5 else None # ref = 16:9 负对照的屏幕截图(同页) | ref = screenshot of the 16:9 negative control (same page)
|
||||
img = np.asarray(Image.open(png).convert('RGB')).astype(int); H, W = img.shape[:2]
|
||||
M = {l.split('\t')[0]: l.split('\t')[1:] for l in open(meta).read().splitlines() if '\t' in l}
|
||||
scale = float(M['scale'][0]); top, left, bottom, right = (float(x) * scale for x in M['safe_pt']) # 像素 | Pixels
|
||||
L = open(log, errors='replace').read(); bad = 0
|
||||
def res(ok, msg):
|
||||
global bad; print(('过 ' if ok else '【红】') + msg); bad += not ok
|
||||
|
||||
def ed(a): return np.abs(np.diff(a, axis=1))[:-1, :] + np.abs(np.diff(a, axis=0))[:, :-1]
|
||||
# ② 不拉伸,两道:(a) 闭式:游戏画面 WxH 对出图视口的横纵缩放之差(日志「出图视口 … (游戏画面 WxH)」);
|
||||
# (b) 图像:16:9 负对照屏幕截图(DM_GAME_RES=1600x900,同页同高度)的 HUD 中段作模板,在本截图上搜横 / 纵缩放,横纵比差 ≤ 1%。
|
||||
# (HUD 球不用:底部被 HUD 框遮住、液面与动画干扰,真值上也量不出正圆;人为横拉 2% 时本法测得 1.0226)
|
||||
# ② No stretching, two checks: (a) closed form: the difference between the horizontal and vertical scale of the game picture WxH to the output viewport (log 「出图视口 … (游戏画面 WxH)」(output viewport ... (game picture WxH)));
|
||||
# (b) image: use the middle section of the HUD from the 16:9 negative-control screenshot (DM_GAME_RES=1600x900, same page, same height) as a template and search for the horizontal / vertical scale on this screenshot; aspect difference ≤ 1%.
|
||||
# (the HUD orbs are not used: the bottom is covered by the HUD frame, the liquid surface and animation interfere, and even on ground truth a perfect circle cannot be measured; with an artificial 2% horizontal stretch this method measured 1.0226)
|
||||
vp = re.findall(r'出图视口 (\d+),(\d+) (\d+)x(\d+) / 画布 \d+x\d+(游戏画面 (\d+)x(\d+))', L)
|
||||
if vp:
|
||||
_, _, vw, vh, gw, gh = map(int, vp[-1]); d = (vw / gw) / (vh / gh) - 1
|
||||
res(abs(d) <= 0.01, f'② (a) 出图横纵缩放:{vw}/{gw} 对 {vh}/{gh},横纵比差 {d * 100:+.2f}%(判据 ≤ 1%)')
|
||||
else: res(False, '② (a) 日志里没有「出图视口」行')
|
||||
if page == 'game' and ref:
|
||||
F = np.asarray(Image.open(png).convert('L')).astype(float); N = np.asarray(Image.open(ref).convert('L')).astype(float); Hn, Wn = N.shape
|
||||
tpl = N[int(Hn * 0.87):Hn, Wn // 2 - 420:Wn // 2 + 420]; best = (-1,)
|
||||
for sx in np.arange(0.985, 1.0151, 0.0025):
|
||||
for sy in np.arange(0.985, 1.0151, 0.0025):
|
||||
t = np.asarray(Image.fromarray(tpl).resize((int(round(tpl.shape[1] * sx)), int(round(tpl.shape[0] * sy))), Image.BILINEAR)).astype(float)
|
||||
te = ed(t); te = (te - te.mean()) / (te.std() + 1e-9); th, tw = te.shape
|
||||
for dy in range(-6, 7, 2):
|
||||
for dx in range(-12, 13, 2):
|
||||
yy, xx = H - th - 1 + dy, W // 2 - tw // 2 + dx
|
||||
if yy < 0 or yy + th + 1 > H: continue
|
||||
f = ed(F[yy:yy + th + 1, xx:xx + tw + 1]); f = (f - f.mean()) / (f.std() + 1e-9); c = float((f * te).mean())
|
||||
if c > best[0]: best = (c, sx, sy)
|
||||
c, sx, sy = best
|
||||
res(c > 0.8 and abs(sx / sy - 1) <= 0.01, f'② (b) HUD 中段对 16:9 负对照:横 {sx:.4f} 纵 {sy:.4f},横纵比差 {(sx / sy - 1) * 100:+.2f}%(相关 {c:.3f},步长 0.25%,判据 ≤ 1%)')
|
||||
elif page == 'game': print(' ② (b) 没给 16:9 负对照截图,跳过图像核对')
|
||||
# ③
|
||||
if page == 'sel':
|
||||
lum = img.mean(axis=2); sat = img.max(axis=2) - img.min(axis=2)
|
||||
band = (lum > 95) & (sat < 40); band[: int(H * 0.1)] = False; band[int(H * 0.9):] = False
|
||||
frac = band.mean(axis=0); cols = np.nonzero(frac[: W // 3] > 0.35)[0]
|
||||
if cols.size: print(f' ③(参考)左侧菜单左缘 x={cols[0]} px({cols[0] / scale:.1f} pt),安全区左边距 {left:.0f} px({left / scale:.1f} pt)')
|
||||
else: print(' ③(参考)没找到左侧菜单面板')
|
||||
o = Image.open(png).convert('RGB'); d = ImageDraw.Draw(o)
|
||||
d.rectangle((left, top, W - 1 - right, H - 1 - bottom), outline=(255, 0, 255), width=4); o.save(png.replace('.png', '_安全区.png'))
|
||||
print(f' ③ 安全区(像素)上 {top:.0f} 左 {left:.0f} 下 {bottom:.0f} 右 {right:.0f};叠线图 {png.replace(".png", "_安全区.png")}')
|
||||
# ④
|
||||
f = re.search(r'前端给游戏的输出分辨率 主机 (\d+)x(\d+)', L); w = re.search(r'WindowInitialize 交换链 \d+ 张 间隔 \d+ 首张 (\d+)x(\d+)', L)
|
||||
res(bool(f and w and f.groups() == w.groups()), f'④ 前端给 {f.groups() if f else "?"},游戏交换链 {w.groups() if w else "?"}')
|
||||
sys.exit(1 if bad else 0)
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""从玩家自己的游戏文件生成 App 用的原版衍生资源(仓库里不放原版的图和字,见 dm/README.md「从你的游戏文件生成资源」)。run.sh build 先跑这里。
|
||||
输入:Switch 版 3.3.94012 的 Update/RomFS(参数或环境变量 DM_ROMFS_SRC);可选 PC 版 D2R 的解包目录(DM_PC_DATA,底栏出原版 2 倍图用,没有就用 Switch 素材放大)。
|
||||
产物(不进 git):
|
||||
Gen/assets/NativeHUD/{widestash, pouch, touch, mapgoal, v4} 加宽储藏箱 / 编年史盖板 / 百宝囊框 / 选角右侧面板 / 小地图终点 / 底部 UI v4
|
||||
Sources/TouchArt/dm_native_*.png、Sources/dm_touch_native_art.c 原版技能图集与技能索引(生成在原位置,dm/ios/.gitignore 忽略)
|
||||
宿主的三张表(dm_vault_tab.h、dm_hud_exp.h、dm_bright_levels.inc)由 dm/host/Makefile 生成。
|
||||
用法:gen_assets.py [<原版 RomFS(Update)>]
|
||||
输入没变就不重出(指纹 = 游戏文件清单 + dm/ios/tools 下全部文件 + PC 素材开关;写在产物根目录 .stamp);同一棵树里同时只许一个进程在生成(锁目录 .gen_lock)——
|
||||
accept 里 iOS 构建与功能用例并行,后者读产物、前者原先每次重写产物,读到一半被删过(base.png 找不到)。gen_romfs_overlay.py 开头也调 ensure()。
|
||||
Generate the assets derived from the original game that the App uses, from the player's own game files (the repository holds none of the original game's images or text, see dm/README.md 「从你的游戏文件生成资源」(Generate assets from your game files)). run.sh build runs this first.
|
||||
Input: Update/RomFS of Switch version 3.3.94012 (argument or environment variable DM_ROMFS_SRC); optionally the unpacked directory of PC D2R (DM_PC_DATA, used to produce the original game's 2x art for the bottom bar; without it, Switch art is upscaled).
|
||||
Build output (not in git):
|
||||
Gen/assets/NativeHUD/{widestash, pouch, touch, mapgoal, v4} widened stash / chronicle cover plate / pouch frame / character select right panel / minimap goal / bottom UI v4
|
||||
Sources/TouchArt/dm_native_*.png, Sources/dm_touch_native_art.c the original game's skill atlas and skill index (generated in place, ignored by dm/ios/.gitignore)
|
||||
The host's three tables (dm_vault_tab.h, dm_hud_exp.h, dm_bright_levels.inc) are generated by dm/host/Makefile.
|
||||
Usage: gen_assets.py [<original game RomFS (Update)>]
|
||||
Nothing is regenerated when the input is unchanged (fingerprint = game file list + all files under dm/ios/tools + the PC art switch; written to .stamp in the build output root); only one process may generate at a time in the same tree (lock directory .gen_lock) --
|
||||
in accept the iOS build and the functional cases run in parallel; the latter read the build output while the former used to rewrite it every time, and files were deleted mid-read (base.png not found). The start of gen_romfs_overlay.py also calls ensure()."""
|
||||
import hashlib, os, shutil, subprocess, sys, time
|
||||
import gen_paths
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
STEPS = [('加宽储藏箱', ['gen_widestash_art.py', '{R}']), ('编年史盖板', ['gen_vault_cover.py']), ('百宝囊框', ['gen_pouch_art.py', '{R}']),
|
||||
('选角右侧面板', ['gen_fe_rightpanel.py', '{R}']), ('小地图终点', ['gen_map_goal_art.py', '{R}']), ('佣兵面板底图', ['gen_merc_art.py', '{R}']),
|
||||
('技能图集与索引', ['native_art/generate.py', '{R}']), ('底部 UI v4', ['gen_hud_v4.py', '{R}'])]
|
||||
|
||||
|
||||
def stamp(R):
|
||||
h = hashlib.sha256(open(os.path.join(R, 'data', 'build_manifest.psv'), 'rb').read())
|
||||
for d, ds, fs in sorted(os.walk(HERE)):
|
||||
ds[:] = sorted(x for x in ds if x != '__pycache__')
|
||||
for f in sorted(fs): h.update(os.path.relpath(os.path.join(d, f), HERE).encode()); h.update(open(os.path.join(d, f), 'rb').read())
|
||||
pc = os.environ.get('DM_PC_DATA') or os.path.join(DM_ROOT, 'data/assets-src/raw')
|
||||
h.update(('%s|%s|%s' % (pc, os.path.isdir(pc), os.environ.get('DM_REQUIRE_PC_ART', ''))).encode())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def ensure(R):
|
||||
"""产物齐、指纹没变就直接返回;否则拿锁生成。返回 True = 这次重出了。 | If the build output is complete and the fingerprint unchanged, return directly; otherwise take the lock and generate. Returns True = regenerated this time."""
|
||||
root = gen_paths.gen_dir(); st = os.path.join(root, '.stamp'); lock = os.path.join(root, '.gen_lock')
|
||||
outs = [os.path.join(root, 'NativeHUD', 'v4', 'base.png'), os.path.join(HERE, '..', 'Sources', 'TouchArt', 'dm_native_skill_0.png'), os.path.join(HERE, '..', 'Sources', 'dm_touch_native_art.c')]
|
||||
want = stamp(R); fresh = lambda: all(map(os.path.isfile, outs)) and os.path.isfile(st) and open(st).read() == want
|
||||
if fresh(): return False
|
||||
t0 = time.time()
|
||||
while True:
|
||||
try: os.mkdir(lock); break
|
||||
except FileExistsError:
|
||||
try: pid = int(open(os.path.join(lock, 'pid')).read())
|
||||
except (OSError, ValueError): pid = 0
|
||||
if pid:
|
||||
try: os.kill(pid, 0)
|
||||
except ProcessLookupError: shutil.rmtree(lock, ignore_errors=True); continue # 持锁进程已经不在:接管 | The lock-holding process is gone: take over
|
||||
if time.time() - t0 > 600: sys.exit('🔴 gen_assets:等别的进程生成等了 10 分钟(锁 %s,pid %s)' % (lock, pid))
|
||||
time.sleep(0.5)
|
||||
try:
|
||||
open(os.path.join(lock, 'pid'), 'w').write(str(os.getpid()))
|
||||
if fresh(): return False # 等锁期间别人已经生成好了 | Someone else already generated it while we waited for the lock
|
||||
if os.path.exists(st): os.remove(st)
|
||||
run_steps(R); open(st, 'w').write(want); return True
|
||||
finally: shutil.rmtree(lock, ignore_errors=True)
|
||||
|
||||
|
||||
def run_steps(R):
|
||||
for name, cmd in STEPS:
|
||||
t0 = time.time(); r = subprocess.run([sys.executable] + [os.path.join(HERE, c) if i == 0 else c.replace('{R}', R) for i, c in enumerate(cmd)],
|
||||
capture_output=True, text=True)
|
||||
if r.returncode: sys.exit('🔴 生成「%s」失败:\n%s%s' % (name, r.stdout[-1500:], r.stderr[-1500:]))
|
||||
tip = [l for l in r.stdout.splitlines() if l.startswith(('没找到', '底栏素材'))]
|
||||
print('%s:%.1f 秒%s' % (name, time.time() - t0, ('(' + tip[0] + ')') if tip else ''))
|
||||
|
||||
|
||||
def main():
|
||||
R = sys.argv[1] if len(sys.argv) > 1 else os.environ.get('DM_ROMFS_SRC') or os.path.join(DM_ROOT, 'data/switch/3.3.94012/Update/RomFS')
|
||||
if not os.path.isfile(os.path.join(R, 'data', 'build_manifest.psv')):
|
||||
sys.exit('🔴 没找到游戏文件:%s/data/build_manifest.psv。把 Switch 版 3.3.94012 的 Update/RomFS 放到这里,或用环境变量 DM_ROMFS_SRC 指过去'
|
||||
'(见 dm/README.md「从你的游戏文件生成资源」)' % R)
|
||||
if not ensure(R): print('原版衍生资源:输入没变,沿用 %s' % gen_paths.gen_dir())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,42 @@
|
||||
# 从 dm/host/Makefile 实际展开的编译命令(make -n -B dmhost)取宿主的源文件 / 头文件路径 / 框架,生成 iOS 工程的构建输入,
|
||||
# 不手抄列表:Makefile 一改,iOS 下次构建自动跟上。
|
||||
# Gen/src/<扁平名> 源文件符号链接(排除 main.c 与 front_mac.m;main.c 另链到 Gen/main/main.c,以 -Dmain=dm_main 编)
|
||||
# stdout xcconfig 行:HEADER_SEARCH_PATHS(-I 目录 + 每个源文件所在目录,保证相对 include 照常解析)、
|
||||
# OTHER_CFLAGS(-D)、框架(Cocoa 换成 UIKit 侧已有,跳过)
|
||||
# 用法:gen_build.py <dm/host 目录> <Gen 目录>
|
||||
# Take the host's source files / header paths / frameworks from the actually expanded compile commands of dm/host/Makefile (make -n -B dmhost) and generate the iOS project's build inputs,
|
||||
# without hand-copying lists: when the Makefile changes, the next iOS build follows automatically.
|
||||
# Gen/src/<flat name> symlinks to source files (excluding main.c and front_mac.m; main.c is linked separately to Gen/main/main.c and compiled with -Dmain=dm_main)
|
||||
# stdout xcconfig lines: HEADER_SEARCH_PATHS (-I directories + the directory of every source file, so relative includes resolve as usual),
|
||||
# OTHER_CFLAGS (-D), frameworks (Cocoa is replaced by what the UIKit side already has, skipped)
|
||||
# Usage: gen_build.py <dm/host dir> <Gen dir>
|
||||
import os, shlex, subprocess, sys
|
||||
host, gen = os.path.abspath(sys.argv[1]), os.path.abspath(sys.argv[2])
|
||||
cmd = subprocess.run(['make', '-s', '-n', '-B', '-C', host, 'dmhost'], capture_output=True, text=True, check=True).stdout
|
||||
toks = shlex.split(next(l for l in cmd.splitlines() if l.lstrip().startswith('clang')))
|
||||
srcs, incs, defs, fws = [], [], [], []
|
||||
i = 0
|
||||
while i < len(toks):
|
||||
t = toks[i]
|
||||
if t == '-framework': fws.append(toks[i + 1]); i += 2; continue
|
||||
if t.startswith('-I'): incs.append(os.path.normpath(os.path.join(host, t[2:])))
|
||||
elif t.startswith('-D'): defs.append(t)
|
||||
elif t.endswith(('.c', '.m', '.S')): srcs.append(os.path.normpath(os.path.join(host, t)))
|
||||
i += 1
|
||||
assert srcs, '编译命令里没有源文件'
|
||||
dup = sorted({s for s in srcs if srcs.count(s) > 1})
|
||||
if dup: sys.exit('编译命令里源文件重复(Makefile 显式列与通配重叠?):' + ' '.join(dup))
|
||||
os.makedirs(f'{gen}/src'); os.makedirs(f'{gen}/main')
|
||||
dirs = []
|
||||
for s in srcs:
|
||||
d = os.path.dirname(s)
|
||||
if d not in dirs: dirs.append(d)
|
||||
b = os.path.basename(s)
|
||||
if os.path.splitext(b)[0].endswith('_mac'): continue # Mac 专用源按 _mac 命名约定不进 iOS(front_mac.m 由 front_ios.m 实现 front.h;touch_mac.c 是 Mac 触点脚本) | Mac-only sources are kept out of iOS by the _mac naming convention (for front_mac.m, front_ios.m implements front.h; touch_mac.c is the Mac touch point script)
|
||||
if os.path.dirname(s) == os.path.normpath(os.path.join(host, '../ios/Sources')): continue # 宿主借用的 iOS 源(如触屏模块)iOS 工程本身已编,再收一份会重复链接 | iOS sources borrowed by the host (e.g. the touch module) are already compiled by the iOS project itself; collecting another copy would link them twice
|
||||
if s == os.path.join(host, 'main.c'): os.symlink(s, f'{gen}/main/main.c'); continue
|
||||
flat = os.path.relpath(s, os.path.dirname(host)).replace('/', '__') # 不同目录同名文件不冲突 | Same-named files in different directories do not collide
|
||||
os.symlink(s, f'{gen}/src/{flat}')
|
||||
print('HEADER_SEARCH_PATHS = $(inherited) ' + ' '.join(f'"{d}"' for d in incs + dirs))
|
||||
print('OTHER_CFLAGS = $(inherited) ' + ' '.join(defs))
|
||||
print('DM_FRAMEWORKS = ' + ' '.join(f'-framework {f}' for f in fws if f != 'Cocoa'))
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
# 局内面板外框右上角的关闭按钮图(凹槽石面原样透出,上面嵌一个贴满凹槽的旧金色 X)。产出 NativeHUD/touch/close.png,由 gen_romfs_overlay.py 写进借用路径。
|
||||
# 用法:python3 dm/ios/tools/gen_close_btn.py 尺寸:凹槽在 2868×1320 下 33.5×45.5 像素;界面贴图 1 像素 = 2 布局单位 = 1.394 屏幕像素 → 24×33,底透明
|
||||
# Close button image for the top-right corner of the in-run panel frame (the groove's stone surface shows through unchanged, with an old-gold X inlaid on it that fills the groove). Produces NativeHUD/touch/close.png, written into the borrowed path by gen_romfs_overlay.py.
|
||||
# Usage: python3 dm/ios/tools/gen_close_btn.py Size: the groove is 33.5×45.5 pixels at 2868×1320; 1 UI texture pixel = 2 layout units = 1.394 screen pixels → 24×33, transparent background
|
||||
import os
|
||||
from PIL import Image, ImageDraw, ImageFilter, ImageChops
|
||||
W, H, S = 24, 33, 16
|
||||
def strokes(r, wd, off=(0, 0)):
|
||||
m = Image.new('L', (W * S, H * S), 0); d = ImageDraw.Draw(m); cx, cy = W * S / 2 + off[0] * S, H * S / 2 + off[1] * S
|
||||
hw, hh = 8.3 * r / 6.2, 13.2 * r / 6.2; cx += 0.1 * S; cy += 0.4 * S # 贴满凹槽内框:半宽 8.1、半高 13.3(贴图像素),r = 6.2 时正好到角 | Fills the groove's inner frame: half-width 8.1, half-height 13.3 (texture pixels); reaches the corners exactly when r = 6.2
|
||||
for sx in (1, -1): d.line((cx - sx * hw * S, cy - hh * S, cx + sx * hw * S, cy + hh * S), fill=255, width=int(wd * S))
|
||||
return m
|
||||
im = Image.new('RGBA', (W * S, H * S), (0, 0, 0, 0))
|
||||
def lay(mask, col, a):
|
||||
global im; l = Image.new('RGBA', im.size, col + (0,)); l.putalpha(mask.point(lambda v: int(v * a))); im = Image.alpha_composite(im, l)
|
||||
# 旧金嵌条:暗描边 + 金色笔画 + 左上高光
|
||||
# Old-gold inlay: dark outline + gold strokes + top-left highlight
|
||||
lay(strokes(6.3, 5.0, (0.35, 0.45)), (8, 7, 6), 0.75); lay(strokes(6.2, 3.7), (150, 118, 62), 1.0); lay(strokes(6.0, 1.3, (-0.35, -0.35)), (226, 198, 132), 0.9)
|
||||
lay(strokes(6.0, 0.9, (0.5, 0.5)), (92, 68, 34), 0.8)
|
||||
im = im.resize((W, H), Image.LANCZOS); im.save(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'NativeHUD', 'touch', 'close.png'))
|
||||
@@ -0,0 +1,36 @@
|
||||
# 生成内嵌汇编:把改写后的模块映像编进可执行文件,代码只进 __TEXT 一个执行段(苹果 ITMS-90999:只许一个带执行权限的段)。
|
||||
# __TEXT,__dm<名>x0 原 text:[0, 圆整16K(TEXT_END))(含 ro 首页的一部分,只读)
|
||||
# __DM<名>W,__img RW 段:[圆整16K(TEXT_END), PATCH_OFF),ro 余部 + data + bss(重定位只落这里)
|
||||
# __TEXT,__dm<名>x1 补丁区:[PATCH_OFF, 圆整16K(文件尾))
|
||||
# 三块在可执行文件里不相邻;运行时由装载器(loader.c iOS 分支)保留一块连续地址,按原相对位置 vm_remap 回去(代码页共享已签名页,W 写时复制),
|
||||
# 所以运行时布局与原映像逐字节相同:原代码与 data 之间的 PC 相对寻址、补丁区的相对跳转、宿主按「基址 + 原偏移」的引用都不用动。
|
||||
# 用法:gen_embed.py <产物目录> <输出 .S> <模块名...>;链接参数打印到 stdout(W 段的 -segprot)
|
||||
# Generate the embedded assembly: compile the rewritten module image into the executable, with code going into the single executable segment __TEXT only (Apple ITMS-90999: only one segment with execute permission is allowed).
|
||||
# __TEXT,__dm<name>x0 original text: [0, round16K(TEXT_END)) (includes part of the first ro page, read-only)
|
||||
# __DM<name>W,__img RW segment: [round16K(TEXT_END), PATCH_OFF), rest of ro + data + bss (relocations land only here)
|
||||
# __TEXT,__dm<name>x1 patch area: [PATCH_OFF, round16K(end of file))
|
||||
# The three pieces are not adjacent in the executable; at run time the loader (loader.c iOS branch) reserves one contiguous address range and vm_remaps them back at their original relative positions (code pages share the signed pages, W is copy-on-write),
|
||||
# so the run-time layout is byte-identical to the original image: PC-relative addressing between original code and data, relative jumps in the patch area, and the host's "base + original offset" references all need no change.
|
||||
# Usage: gen_embed.py <build output dir> <output .S> <module name...>; link flags are printed to stdout (-segprot for the W segment)
|
||||
import os, sys
|
||||
out, dst, names = sys.argv[1], sys.argv[2], sys.argv[3:]
|
||||
PG = 0x4000
|
||||
def r16(x): return (x + PG - 1) & ~(PG - 1)
|
||||
asm = ['// 由 dm/ios/tools/gen_embed.py 生成,勿手改']
|
||||
flags = []
|
||||
for n in names:
|
||||
hdr = dict(l[2:].split() for l in open(f'{out}/{n}.fixups.tsv'))
|
||||
te, po = int(hdr['TEXT_END'], 16), int(hdr['PATCH_OFF'], 16)
|
||||
ko, ks = int(hdr['KEY_PAGE_OFF'], 16), int(hdr['KEY_PAGE_SIZE'], 16)
|
||||
bin_ = os.path.abspath(f'{out}/{n}.patched.bin'); sz = os.path.getsize(bin_)
|
||||
a, end = r16(te), r16(sz)
|
||||
assert po % PG == 0 and a <= ko and ko + ks <= po and ko % PG == 0 and ks == PG
|
||||
for sect, lo, hi in ((f'__TEXT,__dm{n}x0', 0, a), (f'__DM{n}W,__img', a, po), (f'__TEXT,__dm{n}x1', po, end)):
|
||||
assert all(len(x) <= 16 for x in sect.split(','))
|
||||
fill = min(hi, sz) - lo
|
||||
asm += [f' .section {sect}', ' .p2align 14', f' .incbin "{bin_}", {lo:#x}, {fill:#x}']
|
||||
if hi - lo > fill: asm.append(f' .space {hi - lo - fill:#x}')
|
||||
asm.append(' .p2align 14') # 节尾补到 16K:vm_remap 按整页取 | Pad the section end to 16K: vm_remap takes whole pages
|
||||
flags.append(f'-Wl,-segprot,__DM{n}W,rw,rw')
|
||||
open(dst, 'w').write('\n'.join(asm) + '\n')
|
||||
print(' '.join(flags))
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
# 选角页右侧面板底图(键鼠版选角页阉割后只留存档列表;去掉「转换角色」):原版 FrontEnd_RightPanel.sprite 底部两个槽 + 中间十字花,
|
||||
# 改成居中一个槽——按列从原图同一行段搬过来拼(x 112 起:原 52–109 的左槽、原 112–171 的槽中段、两列过渡、再接左槽),只动 y 980–1039 这一条。
|
||||
# 编成原包同款 DXT5 + 块线性(gen_widestash_art.bc3 / pack;原始 RGBA 的 v31 在 401×1080 上读出竖条花屏)。
|
||||
# 用法:gen_fe_rightpanel.py <原版 RomFS(Update)>(构建时跑,产物 Gen/assets/NativeHUD/touch/fe_rightpanel.sprite;gen_romfs_overlay.py 写进借用路径)
|
||||
# Base image for the right-hand panel of the character select page (the keyboard-and-mouse character select page trimmed down to just the save list; 「转换角色」(Convert Character) removed): the original FrontEnd_RightPanel.sprite has two slots at the bottom + a cross ornament in the middle,
|
||||
# changed to a single centered slot - assembled column by column from the same row band of the original image (starting at x 112: the left slot from original 52–109, the slot middle from original 112–171, a two-column transition, then the left slot again); only the strip y 980–1039 is touched.
|
||||
# Encoded as DXT5 + block-linear like the original package (gen_widestash_art.bc3 / pack; raw RGBA v31 reads back as vertical-stripe garbage at 401x1080).
|
||||
# Usage: gen_fe_rightpanel.py <original RomFS (Update)> (run at build time, output Gen/assets/NativeHUD/touch/fe_rightpanel.sprite; gen_romfs_overlay.py writes it into the borrowed path)
|
||||
import os, sys
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
|
||||
import romfs_art, gen_widestash_art as G
|
||||
from gen_paths import gen_dir
|
||||
|
||||
SRC = 'hd/global/ui/FrontEnd/HD/Final/FrontEnd_RightPanel.sprite'
|
||||
Y0, Y1 = 980, 1040
|
||||
COPY = ((112, 52, 58), (170, 112, 60), (230, 53, 1), (231, 52, 1), (232, 52, 58)) # (目标列, 来源列, 列数) | (destination column, source column, column count)
|
||||
|
||||
def main(romfs):
|
||||
b = romfs_art.read(romfs, SRC); o = np.array(romfs_art.sprite(romfs, SRC)); w, h = o.shape[1], o.shape[0]
|
||||
assert (w, h) == (401, 1080), (w, h)
|
||||
m = o.copy()
|
||||
for d, s, n in COPY: m[Y0:Y1, d:d + n] = o[Y0:Y1, s:s + n]
|
||||
p = os.path.join(gen_dir('NativeHUD', 'touch'), 'fe_rightpanel.sprite')
|
||||
open(p, 'wb').write(G.pack(G.lib(), b, G.bc3(Image.fromarray(m, 'RGBA')), w, h, w))
|
||||
print('fe_rightpanel:%d×%d → %s' % (w, h, p))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1])
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
# 宿主经验表 dm_hud_exp.h(底栏经验条用):由原版 data/global/excel/experience.txt 生成(各职业同值,取 Amazon 列)。构建时生成,不进仓库。
|
||||
# 用法:gen_hud_exp.py <原版 RomFS(Update)> > <输出 .h>
|
||||
# Host experience table dm_hud_exp.h (for the bottom bar experience bar): generated from the original game's data/global/excel/experience.txt (same values for every class; the Amazon column is used). Generated at build time, not committed to the repository.
|
||||
# Usage: gen_hud_exp.py <original game RomFS (Update)> > <output .h>
|
||||
import csv, io, os, sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import romfs_art
|
||||
|
||||
def main(romfs):
|
||||
rows = list(csv.DictReader(io.StringIO(romfs_art.read(romfs, 'global/excel/experience.txt').decode('utf-8')), delimiter='\t'))
|
||||
v = [int(r['Amazon']) for r in rows if r.get('Level', '').isdigit()][:100]
|
||||
if len(v) != 100: raise SystemExit('gen_hud_exp:experience.txt 只有 %d 级' % len(v))
|
||||
out = ['// 由原版 data/global/excel/experience.txt 生成(3.3.94012,各职业同值,取 Amazon 列):k_exp[L] = 升到 L+1 级所需总经验;L = 0..99',
|
||||
'#pragma once', '#include <stdint.h>', 'static const uint32_t k_exp[100] = {']
|
||||
for i in range(0, 100, 10): out.append(' ' + ', '.join(str(x) for x in v[i:i + 10]) + (',' if i < 90 else ''))
|
||||
out.append('};')
|
||||
sys.stdout.write('\n'.join(out) + '\n')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1])
|
||||
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
# 底部 UI v4 生成器(按 v4 效果图实装):产出 NativeHUD/v4/base.png(底图)与 hud.json(手柄 HUD 布局)。
|
||||
# 用法:python3 dm/ios/tools/gen_hud_v4.py <原版 RomFS(Update)> [输出目录] [试调 json] 构建时跑(tools/gen_assets.py),产物 Gen/assets/NativeHUD/v4,不进仓库。
|
||||
# 几何与素材在 hud_v4_design.py(效果图脚本搬进仓库的那部分):有 PC 版 D2R 文件(DM_PC_DATA)出原版 2 倍图,没有就用 Switch 素材放大。
|
||||
# 几何量全部取自效果图脚本(同一套数);底图(石条 + 七格 + 天使 / 恶魔,球心挖空透出原生球液)由 gen_romfs_overlay.py 构建时写进借用路径
|
||||
# (dm/data/casc_overlay/borrowed_paths.tsv)。血 / 蓝球、腰带、红方十字(LevelUpButton)、回城(SkillButton6,ZR 位)、经验条用原生部件,只改位置与缩放。
|
||||
# 布局以 touchrectv1 为底(= 原版手柄 HUD 布局 Controller/HUDPanelHD.json 套我们的补丁 touchrectv1_patch.json:根铺满全屏、部件锚底边中点;SkillButton1–5 已摆在右侧技能区,iOS 技能圈叠在其上)。
|
||||
# 实测(Mac 宿主):布局 1 单位 = 屏高/2160;v31 原始贴图 1 纹素 = 2 单位;rect.scale 按 0.1 取整生效(0.8182 按 0.8),位置须按取整后的值算。
|
||||
# Bottom UI v4 generator (implemented per the v4 mockup): outputs NativeHUD/v4/base.png (base image) and hud.json (controller HUD layout).
|
||||
# Usage: python3 dm/ios/tools/gen_hud_v4.py <original game RomFS (Update)> [output dir] [tuning json] Run at build time (tools/gen_assets.py); build output Gen/assets/NativeHUD/v4, not committed to the repo.
|
||||
# Geometry and assets are in hud_v4_design.py (the part of the mockup script moved into the repo): with PC D2R files (DM_PC_DATA) it produces the original 2× images, otherwise it upscales the Switch assets.
|
||||
# All geometry values come from the mockup script (same set of numbers); the base image (stone strip + seven slots + angel / demon, orb centers cut out to show the native orb liquid) is written into the borrowed path by gen_romfs_overlay.py at build time
|
||||
# (dm/data/casc_overlay/borrowed_paths.tsv). The life / mana orbs, belt, red square cross (LevelUpButton), town portal (SkillButton6, ZR position) and experience bar use native widgets, with only position and scale changed.
|
||||
# The layout is based on touchrectv1 (= the original game's controller HUD layout Controller/HUDPanelHD.json with our patch touchrectv1_patch.json applied: root fills the full screen, widgets anchored at the bottom-edge midpoint; SkillButton1–5 are already placed in the right-side skill area with the iOS skill circles stacked on top).
|
||||
# Measured (Mac host): 1 layout unit = screen height/2160; v31 raw texture 1 texel = 2 units; rect.scale takes effect rounded to 0.1 (0.8182 acts as 0.8), so positions must be computed from the rounded value.
|
||||
import json, re, sys, os
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
HERE=os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0,HERE)
|
||||
import romfs_art, hud_v4_design, layout_patch
|
||||
from gen_paths import gen_dir
|
||||
ROMFS=sys.argv[1]; OUT=sys.argv[2] if len(sys.argv)>2 else gen_dir('NativeHUD','v4') # 试调时可指定输出目录 | The output directory can be specified when tuning
|
||||
os.makedirs(OUT,exist_ok=True); SRC=hud_v4_design.Source(ROMFS)
|
||||
def load(var='C'): return hud_v4_design.load(SRC, var)
|
||||
# 试调量(腰带三项按手机实拍校正:原版小药水贴图在格内偏右下,以手机常见的小药水居中为准;其余 Mac 截图逐像素量出):腰带位移 / 格距、经验条位移、数值文字位移与字号
|
||||
# Tuning values (the three belt items are corrected from real phone captures: the original game's small potion texture sits toward the lower right within the slot, so the small potion commonly seen on the phone is taken as centered; the rest are measured pixel by pixel from Mac screenshots): belt offset / slot pitch, experience bar offset, value text offset and font size
|
||||
T=dict(bx=6.5,by=5,bpx=25,bs=1.6,ex=-7,ey=-15,txt=43,tx=-238,ts=1.4) # bs:腰带缩放(药水对效果图 78 像素图标) | bs: belt scale (potions matched to the mockup's 78-pixel icons)
|
||||
if len(sys.argv)>3: T.update(json.loads(sys.argv[3])) # 试调:覆盖上面的量 | Tuning: overrides the values above
|
||||
g=load('C'); W,H=g['W'],g['H']; U=H/2160; RX0,RY0=-1473,-417
|
||||
ux=lambda px:(px-W/2)/U-RX0; uy=lambda py:(py-H)/U-RY0
|
||||
BASE='PANEL/HUD_02/BugBTN' # 借用路径,见登记表 | Borrowed path, see the registry
|
||||
# ---- 底图 ----
|
||||
# ---- Base image ----
|
||||
cv=Image.new('RGBA',(W,H))
|
||||
# 效果图的暗衬只为遮掉效果图上清理旧底栏的接缝;实机没有旧底栏,不要(还会压暗数值文字)
|
||||
# The mockup's dark backing exists only to hide the seam left on the mockup from cleaning out the old bottom bar; the real device has no old bottom bar, so drop it (it would also darken the value text)
|
||||
cv.alpha_composite(g['bar'],(g['BAR_X0']-g['EXT'],H-g['BH']))
|
||||
for x0,y0,_,_ in g['slots']: cv.alpha_composite(g['slot'],(x0,y0))
|
||||
# (六格:回城书格去掉,十字挪到第 5 格。)以下为七格时的说明——第 5 格回城书、第 6 格红方十字(原版 LevelUpButton 第 0 帧)照效果图烘进底图:触屏回城走原生绑定序列、不是 ZR 位上的技能,ZR 位图标代表不了回城;
|
||||
# 原生 LevelUpButton 没有未分配点数时不显示;这里要的是外观一直是红方十字、有点数时照原版亮起(原生按钮叠在上面亮)
|
||||
# 十字按钮两态——有未分配的技能点 / 属性点或新任务待读时红色,否则默认色。默认色 = 原图红底换成与其余六格内框同一路的暗底,
|
||||
# 金边与金十字不动;底图烘默认态,红色态由前端按 HUD 读数换图(DmTouchOverlay drawV4)
|
||||
# (Six slots: the Tome of Town Portal slot is removed, the cross moves to slot 5.) The following describes the seven-slot version -- slot 5 Tome of Town Portal and slot 6 red square cross (frame 0 of the original game's LevelUpButton) are baked into the base image per the mockup: touchscreen town portal goes through the native binding sequence, not a skill on the ZR position, so the ZR position icon cannot represent town portal;
|
||||
# the native LevelUpButton is not shown when there are no unassigned points; what we want here is an appearance that is always a red square cross, lighting up as in the original game when points are available (the native button lights up stacked on top)
|
||||
# The cross button has two states -- red when there are unassigned skill points / attribute points or a new quest waiting to be read, otherwise the default color. Default color = the original image's red background replaced with the same kind of dark background as the inner frames of the other six slots,
|
||||
# gold border and gold cross untouched; the base image bakes the default state, and the red state is swapped in by the front end according to HUD readings (DmTouchOverlay drawV4)
|
||||
def dflt(im):
|
||||
a_=np.asarray(im.convert('RGBA')).astype(float); r,gc,b=a_[...,0],a_[...,1],a_[...,2]; red=(r>14)&(((r>gc*1.3)&(gc-b<0.17*r))|(r>gc*1.7)); l=r*0.5+gc*0.3+b*0.2 # 红:绿蓝接近;金:绿明显高于蓝(十字的暗金边不能当红底换掉) | Red: green and blue close; gold: green clearly higher than blue (the cross's dark gold border must not be replaced as red background)
|
||||
hh,ww=red.shape; inner=np.zeros_like(red); inner[round(hh*0.12):round(hh*0.88),round(ww*0.12):round(ww*0.88)]=True; red&=inner # 只换金边以内的红底(金边暗部也偏红,不能动) | Only replace the red background inside the gold border (the dark parts of the gold border are also reddish and must not be touched)
|
||||
for ch,k in ((0,0.42),(1,0.40),(2,0.38)): a_[...,ch]=np.where(red,l*k+6,a_[...,ch])
|
||||
return Image.fromarray(a_.round().clip(0,255).astype('uint8'),'RGBA')
|
||||
g['layer']=Image.new('RGBA',(W,H)); g['fit'](dflt(g['lvl']),5,'十字(默认态)'); cv.alpha_composite(g['layer']) # 六格:回城不在底栏(改为右侧技能钮上方的圆钮,前端画),十字在第 5 格 | Six slots: town portal is not in the bottom bar (now a round button above the right-side skill buttons, drawn by the front end), the cross is in slot 5
|
||||
yy,xx=np.mgrid[0:H,0:W]; ball=np.zeros((H,W),bool)
|
||||
for c in (g['LBC'],g['RBC']): ball|=(xx-c[0])**2+(yy-c[1])**2<(g['BR']-2)**2
|
||||
# UIKit 原生分辨率版分层合成:石条 / 格子在球位挖空(石条两端伸进球下,不挖会盖黑半个球),再叠雕像——雕像带 PC 前面板在球上的半透明玻璃层(高光、边缘压暗、划痕)
|
||||
# UIKit native-resolution version, layered compositing: the stone strip / slots are cut out at the orb positions (the strip's ends extend under the orbs; without cutting they would black out half an orb), then the statues are overlaid -- the statues carry the PC front panel's semi-transparent glass layer over the orb (highlights, darkened edges, scratches)
|
||||
g_=np.array(cv); g_[...,3][ball]=0; cvg=Image.fromarray(g_)
|
||||
L,R=g['L'],g['R']
|
||||
for im_ in (cv,cvg): im_.alpha_composite(L,(g['LX'],H-L.height)); im_.alpha_composite(R,(g['RX'],H-R.height))
|
||||
a=np.array(cv); a_glass=np.array(cvg)
|
||||
a[...,3][ball]=0 # 游戏版底图球心整个挖空(含玻璃层):原生球在底图下层;玻璃层由 UIKit 原生分辨率版盖上,免得叠两层 | In the game version of the base image the orb center is cut out entirely (including the glass layer): the native orb is in the layer below the base image; the glass layer is laid on by the UIKit native-resolution version, to avoid stacking two layers
|
||||
cv=Image.fromarray(a); bx0,by0,bx1,by1=cv.getbbox(); spr=cv.crop((bx0,by0,bx1,by1))
|
||||
# 前端原生分辨率版(UIKit 直接贴效果图像素,不经游戏 1568×720 渲染与放大):腰带第 1–4 格内框挖空透出游戏画的药水;第 6 格整格留给 UIKit 红方十字按钮
|
||||
# Front-end native-resolution version (UIKit pastes the mockup pixels directly, bypassing the game's 1568×720 rendering and upscaling): the inner frames of belt slots 1–4 are cut out to show the potions drawn by the game; slot 6 is left entirely to the UIKit red square cross button
|
||||
full=a_glass # 不挖球心:玻璃层盖在游戏画的球液上(原先整个挖掉这层,球的光泽与细节差很远) | Do not cut out the orb center: the glass layer covers the orb liquid drawn by the game (previously this layer was cut out entirely, and the orb's gloss and detail were far off)
|
||||
for i in (1,2,3,4): x0,y0,_,_=g['slots'][i]; full[y0+g['IY0']:y0+g['IY1']+1, x0+g['IX0']:x0+g['IX1']+1, 3]=0
|
||||
x0,y0,x1,y1=g['slots'][5]; full[y0:y1,x0:x1,3]=0
|
||||
FULL=Image.fromarray(full).crop((bx0,by0,bx1,by1))
|
||||
# 按 1 纹素 = 2 单位重采样、布局缩放写 1.0:实测缩放字段取 0.8182 时底图窄 2.4%(≈ 按 0.8 生效),不依赖小数缩放
|
||||
# Resampled at 1 texel = 2 units with the layout scale written as 1.0: measured, with the scale field at 0.8182 the base image is 2.4% narrower (≈ takes effect as 0.8), so do not rely on fractional scaling
|
||||
spr=spr.resize((round(spr.width/(2*U)),round(spr.height/(2*U))),Image.LANCZOS)
|
||||
spr.save(f'{OUT}/base.png')
|
||||
# ---- 布局 ----
|
||||
# 以 touchrectv1(手机现行底栏布局:根铺满全屏、部件锚底边中点;六个原生技能键已摆在右侧技能区,iOS 技能圈叠在其上,须原样保留)为底,只重摆底栏部件
|
||||
# ---- Layout ----
|
||||
# Based on touchrectv1 (the current phone bottom bar layout: root fills the full screen, widgets anchored at the bottom-edge midpoint; the six native skill buttons are already placed in the right-side skill area with the iOS skill circles stacked on top, and must be kept as is), only the bottom bar widgets are rearranged
|
||||
j=layout_patch.apply(layout_patch.load_text(romfs_art.read(ROMFS,'global/ui/Layouts/Controller/HUDPanelHD.json').decode('utf-8-sig')),json.load(open(os.path.join(HERE,'touchrectv1_patch.json'),encoding='utf-8')))
|
||||
X=lambda px:(px-W/2)/U; Y=lambda py:(py-H)/U # 锚底边中点的部件坐标 | Widget coordinates anchored at the midpoint of the bottom edge
|
||||
j['children']=[c for c in j['children'] if c['name'] not in ('TouchBeltFrame','BeltPopupArrow','TouchHealthBallRing','TouchManaBallRing')] # v4 底图取代 | Replaced by the v4 base image
|
||||
by={c['name']:c for c in j['children']}
|
||||
def rect(n,**k):
|
||||
r=by[n]['fields'].setdefault('rect',{}); r.update({q:round(v,1) for q,v in k.items()}); by[n]['fields']['anchor']={'x':0.5,'y':1}
|
||||
by['Overlay']['fields']['filename']=BASE; by['Overlay']['fields'].pop('transparency',None)
|
||||
rect('Overlay',x=X(bx0),y=Y(by0)); by['Overlay']['fields']['rect'].pop('scale',None)
|
||||
q=lambda v: round(v,1) # 实测:布局 scale 字段按 0.1 取整生效,位置须按取整后的值算 | Measured: the layout scale field takes effect rounded to 0.1, so positions must be computed from the rounded value
|
||||
sb=q(2*g['BR']/(348*U)*T.get('ball',1.0)); ts=T.get('ts',1.4)
|
||||
for n,c in (('HealthBall',g['LBC']),('ManaBall',g['RBC'])):
|
||||
rect(n,x=X(c[0])-174*sb,y=Y(c[1])-175*sb,scale=sb); by[n]['fields']['rect'].pop('width',None); by[n]['fields']['rect'].update(width=348,height=350)
|
||||
vd=[k for k in by[n]['children'] if k['name']=='ValueDisplay'][0]['fields'] # 数值:球顶上方居中(效果图 YB 基线),底图在球之后画,原位置会被雕像盖住 | Values: centered above the orb top (mockup YB baseline); the base image is drawn after the orb, so the original position would be covered by the statue
|
||||
vd['rect']={'x':-6000,'y':0} # 原生数值文字挪出屏幕:改由前端按效果图字形原生分辨率画(gen 产出 life / mana 字形) | Native value text moved off screen: now drawn by the front end at native resolution with the mockup glyphs (gen outputs the life / mana glyphs)
|
||||
continue
|
||||
vd['rect']={'x':T.get('tx',-174),'y':round((Y(g['YB']-T.get('txt',30))-(Y(c[1])-175*sb))/sb,1),'width':348,'scale':ts}
|
||||
vd.setdefault('style',{})['alignment']={'h':'center'}
|
||||
s6=g['slots'][5]; sl=q(T.get('lvl',0.9)); lc=((s6[0]+s6[2])/2,(s6[1]+s6[3])/2)
|
||||
lx,ly=X(lc[0])-62*sl+T.get('lx',0),Y(lc[1])-60*sl; rect('LevelUpButton',x=lx,y=ly,scale=sl)
|
||||
rect('LevelUpFlourish',x=lx+(1179-1411)*sl,y=ly+(-1-265)*sl,scale=q(1.1*sl))
|
||||
s1=g['slots'][1]; rect('Belt',x=X(s1[0])+T.get('bx',0),y=Y(s1[1])+T.get('by',0),scale=q(T.get('bs',1.0)))
|
||||
by['Belt']['fields']['cellPadding']={'x':T.get('bpx',32),'y':T.get('bpy',68)}
|
||||
# 行距 15 → 68:多排腰带展开时(键鼠版「显示腰带」,腰带格上滑),上面几排是腰带控件自己从底排往上按行距排的,原行距下第一排的下半截被我们的底栏上沿
|
||||
# (经验条、「Lv · %」、生命 / 法力数值)压住。布局里没有「展开面板位置」这一项,能把它们抬过上沿的只有行距(排与排之间因此有缝);底排不受影响。
|
||||
# 真机 2868×1320 实量:第一排比底排高 165、排距 162(原 113 / 110)——dm_touch_controls.c 点上面几排的命中用的就是这两个数,改这里要一起改。
|
||||
# Row spacing 15 → 68: when the multi-row belt is expanded (the keyboard-and-mouse version's 「显示腰带」(Show Belt), swipe up on a belt slot), the upper rows are laid out by the belt widget itself from the bottom row upward at the row spacing; at the original spacing the lower half of the first row is covered by the top edge of our bottom bar
|
||||
# (experience bar, "Lv · %", life / mana values). The layout has no "expanded panel position" item; the only thing that can lift them above the top edge is the row spacing (hence the gaps between rows); the bottom row is unaffected.
|
||||
# Measured on a real device at 2868×1320: the first row is 165 above the bottom row, row pitch 162 (originally 113 / 110) -- dm_touch_controls.c uses exactly these two numbers for hit-testing the upper rows; change them together with this.
|
||||
by['Belt']['fields'].pop('cellOffsetInRow',None); by['Belt']['fields'].pop('itemOffsetInCell',None)
|
||||
[k for k in by['Belt']['children'] if k['name']=='HotkeyLabelTemplate'][0]['fields']['rect']={'x':-6000,'y':98} # 手柄方向键提示:触屏无意义且压住格框 | Controller d-pad hint: meaningless on a touchscreen and it overlaps the slot frame
|
||||
s5=g['slots'][5]; ss6=T.get('s6',1.0); rect('SkillButton6',x=X((s5[0]+s5[2])/2)-63*ss6+T.get('s6x',0),y=Y((s5[1]+s5[3])/2)-63*ss6+T.get('s6y',0),scale=ss6)
|
||||
# SkillButton6(ZR 位)实例保留供绑定读取,排在底图之前、由第 5 格底图盖住(显示的是 ZR 位绑定,不是回城)
|
||||
# SkillButton6 (ZR position) instance kept for reading bindings, ordered before the base image and covered by the slot 5 base image (what it shows is the ZR position binding, not town portal)
|
||||
kids=j['children']; sb6=next(c for c in kids if c['name']=='SkillButton6'); kids.remove(sb6); kids.insert(kids.index(by['Overlay']),sb6)
|
||||
es=q(T.get('exp',1.5)); rect('ExpBar',x=X(g['EX0'])+T.get('ex',0),y=Y(g['EY'])+T.get('ey',0),scale=es)
|
||||
# 原生 ExpBar 实例保留、排到底图之前被盖住:经验条(底槽 + 填充 + 20 等分刻度)与「Lv · %」由前端 UIKit 按效果图画(原生条与效果图几何对不上、也不带文字)
|
||||
# Native ExpBar instance kept, ordered before the base image so it is covered: the experience bar (trough + fill + 20 equal tick marks) and "Lv · %" are drawn by the front-end UIKit per the mockup (the native bar's geometry does not match the mockup, and it carries no text)
|
||||
eb=by['ExpBar']; kids.remove(eb); kids.insert(kids.index(by['Overlay']),eb)
|
||||
eb['fields']['rect']['y']=round(Y(g['slots'][1][1]+30),1) # 挪进石条区域(七格上沿之外底图盖不住,Mac 预览露出黄条) | Moved into the stone strip area (outside the top edge of the seven slots the base image cannot cover it, and the Mac preview shows a yellow bar)
|
||||
eb['fields']['rect']['x']=-6000 # 挪出屏幕(实例仍在)。靠底图盖是盖不住的:原生条放大 1.5 倍后比底栏还长,填充随经验伸长,过了约一半就从底图右端伸出去、 | Moved off screen (instance still exists). Covering it with the base image does not work: the native bar scaled 1.5× is longer than the bottom bar, the fill grows with experience, and past about halfway it sticks out of the base image's right end,
|
||||
# 横穿法力球——球里有法力时被液面挡住看不出,法力见底时就是球里一条黄线、一直伸到球右边外面(真机实例:2 级、经验 73%、法力 1/21)
|
||||
# Runs across the mana orb -- when the orb has mana it is hidden by the liquid surface and cannot be seen; when mana bottoms out it is a yellow line inside the orb extending all the way out past the orb's right side (real device instance: level 2, experience 73%, mana 1/21)
|
||||
# 原生技能键 1–5:实例保留(绑定读取),挪到第 5 格底图下藏住——右侧技能区由 iOS 画 PC 版圆形技能键,原生方框不再露在圆圈下
|
||||
# Native skill buttons 1–5: instances kept (bindings are read from them), moved under the slot 5 base image to hide them -- the right-side skill area has iOS draw PC-style round skill buttons, and the native square frames no longer show under the circles
|
||||
for n in ('SkillButton1','SkillButton2','SkillButton3','SkillButton4','SkillButton5'):
|
||||
w_=by[n]; kids.remove(w_); kids.insert(kids.index(by['Overlay']),w_); w_['fields']['rect']=dict(by['SkillButton6']['fields']['rect']); w_['fields']['anchor']={'x':0.5,'y':1}
|
||||
json.dump(j,open(f'{OUT}/hud.json','w'),ensure_ascii=False,indent=1)
|
||||
|
||||
# ---- 前端 UIKit 素材(hud_v4_ui/):几何(效果图像素,前端按 屏高/1320 换算、以屏宽中线对齐效果图 x=1434)、预渲染字形、难度数字、选择条格子 ----
|
||||
# ---- Front-end UIKit assets (hud_v4_ui/): geometry (mockup pixels; the front end converts by screen height/1320 and aligns the screen-width centerline to mockup x=1434), pre-rendered glyphs, difficulty digits, selection bar slots ----
|
||||
from PIL import ImageDraw, ImageFont
|
||||
UI=os.path.join(OUT,'hud_v4_ui'); os.makedirs(UI,exist_ok=True)
|
||||
for f in os.listdir(UI): os.remove(os.path.join(UI,f))
|
||||
font=g['num'](g['BADGE'])
|
||||
def glyphs(tag,fill,font=font,chars='0123456789Lv·% '): # 与效果图 shadow_text 同一字效:右下 2px 黑影(α170)+ 1px 深描边;每字一张,记字距与基线偏移 | Same text effect as the mockup's shadow_text: lower-right 2px black shadow (α170) + 1px dark outline; one image per character, recording advance and baseline offset
|
||||
m={}
|
||||
for ch in chars:
|
||||
pad=8; w=int(font.getlength(ch))+2*pad+4; asc,desc=font.getmetrics(); im=Image.new('RGBA',(w,asc+desc+2*pad+4)); d=ImageDraw.Draw(im)
|
||||
o=(pad,pad+asc)
|
||||
d.text((o[0]+2,o[1]+2),ch,font=font,fill=(0,0,0,170),anchor='ls'); d.text(o,ch,font=font,fill=fill,anchor='ls',stroke_width=1,stroke_fill=(10,8,6,255))
|
||||
bb=im.getbbox(); name=f'g_{tag}_{ord(ch):04x}.png'
|
||||
if bb: im.crop(bb).save(os.path.join(UI,name))
|
||||
m[ch]={'file':name if bb else None,'dx':(bb[0]-o[0]) if bb else 0,'dy':(bb[1]-o[1]) if bb else 0,'adv':font.getlength(ch)}
|
||||
return m
|
||||
ui={'ref':[W,H],'center_x':W/2,'slots':g['slots'],'inner':[g['IX0'],g['IY0'],g['IX1'],g['IY1']],
|
||||
'exp':{'x0':g['EX0'],'x1':g['EX1'],'y':g['EY'],'h':6,'track':[22,18,14],'edge':[70,58,40],'fill':[196,160,70],'ticks':20},
|
||||
'lv':{'x':(g['EX0']+g['EX1'])/2,'baseline':g['EY']-6,'glyphs':glyphs('lv',(205,185,140,255))},
|
||||
'badge':{'glyphs':glyphs('b',(235,235,235,255)),'dx':-3,'dy':-1}, # 右下内角锚点 = 格左上 + 内框右下 + (dx,dy),右对齐、基线 | Lower-right inner corner anchor = slot top-left + inner frame bottom-right + (dx,dy), right-aligned, baseline
|
||||
'pick':{'center_x':1390,'pitch':120,'y':1051.5},
|
||||
'vital':{'left_x':g['LBC'][0],'right_x':g['RBC'][0],'baseline':g['YB']}}
|
||||
font_v=SRC.font('blizzardglobal-v5_81.ttf',30)
|
||||
import re, dm_i18n # 生命 / 法力两行的字形:原有中文这一套 + 中英表 dmHudLife / dmHudMana 英文用到的字(英文版;字形不全 v4text 会空着) | glyphs for the life / mana rows: the existing Chinese set plus the characters used by the English of dmHudLife / dmHudMana in the Chinese-English string table (English version; with missing glyphs v4text would leave blanks)
|
||||
_vt={k:(z,e) for k,z,e in dm_i18n.rows()}; _vc='生命法力:/ 0123456789'
|
||||
_vc+=''.join(sorted({c for k in ('dmHudLife','dmHudMana') for c in dm_i18n.FMT.sub('',_vt[k][0]+_vt[k][1])}-set(_vc)))
|
||||
ui['vital']['glyphs']=glyphs('v',(235,235,235,255),font_v,_vc)
|
||||
g['slot'].save(os.path.join(UI,'slot.png'))
|
||||
FULL.save(os.path.join(UI,'base_full.png')); ui['base']={'x':bx0,'y':by0}
|
||||
lvlsheet=SRC.img('levelupbutton') # 原版 LevelUpButton 两帧(亮 / 按下),整格替换第 6 格 | The original game's LevelUpButton two frames (lit / pressed), replaces slot 6 entirely
|
||||
for fi in (0,1): # lvl_N = 红色态(有点可加 / 新任务),lvl_dN = 默认态;N = 0 常态 / 1 按住 | lvl_N = red state (points available to spend / new quest), lvl_dN = default state; N = 0 normal / 1 held
|
||||
fr=lvlsheet.crop((fi*124,0,fi*124+124,121)).resize((g['DM'],g['SH']),Image.LANCZOS); fr.save(os.path.join(UI,f'lvl_{fi}.png')); dflt(fr).save(os.path.join(UI,f'lvl_d{fi}.png'))
|
||||
for n in range(1,9): # 难度数字:效果图方案 C(Exocet + 原版标题金属字效),字高 = 安全区 78 × 85% | Difficulty digits: mockup option C (Exocet + the original game's title metal text effect), glyph height = safe area 78 × 85%
|
||||
im=g['prep'](g['metal'](str(n),220)); k=g['BOX']*0.85/im.height; im=im.resize((max(1,round(im.width*k)),round(im.height*k)),Image.LANCZOS)
|
||||
im.save(os.path.join(UI,f'diff_{n}.png'))
|
||||
# 技能剪影图集:官方技能图集(Sources/TouchArt/dm_native_skill_N.png,帧位置不变)只取银色剪影(高亮、低饱和;去掉锈铁方牌与四角铆钉),
|
||||
# 前端放进深色圆底 + 古铜圆环(同 PC 版圆形技能键的样式),不再把方形图标塞进圆圈
|
||||
# Skill silhouette atlas: from the official skill atlas (Sources/TouchArt/dm_native_skill_N.png, frame positions unchanged) take only the silver silhouette (bright, low saturation; drop the rusty iron square plate and the four corner rivets),
|
||||
# the front end puts it on a dark round base + bronze ring (same style as the PC version's round skill buttons), no longer stuffing a square icon into a circle
|
||||
ART=os.path.join(HERE,'..','Sources','TouchArt'); man=json.load(open(os.path.join(ART,'native_art_manifest.json')))
|
||||
for a_ in man['assets']:
|
||||
if not a_['asset'].startswith('dm_native_skill_'): continue
|
||||
im=np.asarray(Image.open(os.path.join(ART,a_['asset'])).convert('RGBA')).astype(float)/255
|
||||
mx=im[...,:3].max(-1); mn=im[...,:3].min(-1); sat=(mx-mn)/np.maximum(mx,1e-6)
|
||||
al=np.clip((mx-0.42)/0.18,0,1)*np.clip((0.32-sat)/0.12,0,1)*im[...,3]
|
||||
fw,pitch=a_['frame_width'],a_['frame_pitch']; Hh,Ww=al.shape; yy,xx=np.mgrid[0:Hh,0:Ww]
|
||||
al*=np.hypot((xx%pitch)-fw/2,yy-Hh/2)<fw*0.46
|
||||
Image.fromarray((np.dstack([im[...,:3],al])*255).astype('uint8')).save(os.path.join(UI,'sil_'+a_['asset']))
|
||||
# 技能键标签(PC 定稿演示图同款:主键「攻击」、其余 F1–F4 / 第二套 F5–F8),原版界面字体加粗米色 + 右下暗影,按效果图像素预渲染
|
||||
# Skill button labels (same as the final PC demo image: main button 「攻击」(Attack), the rest F1–F4 / second set F5–F8), the original game's UI font in bold beige + lower-right dark shadow, pre-rendered at mockup pixels
|
||||
lf=g['num'](34)
|
||||
for name,txt in [('main','攻击')]+[(f'f{n}',f'F{n}') for n in range(1,9)]:
|
||||
w=int(lf.getlength(txt))+16; im=Image.new('RGBA',(w,60)); d=ImageDraw.Draw(im)
|
||||
d.text((10,8),txt,font=lf,fill=(0,0,0,190),stroke_width=2,stroke_fill=(0,0,0,190)); d.text((8,6),txt,font=lf,fill=(226,206,160,255),stroke_width=1,stroke_fill=(30,22,12,255))
|
||||
im.crop(im.getbbox()).save(os.path.join(UI,f'lbl_{name}.png'))
|
||||
json.dump(ui,open(os.path.join(UI,'ui.json'),'w'),ensure_ascii=False,indent=1)
|
||||
print('NativeHUD/v4:底图',spr.size,'原点',round(X(bx0),1),round(Y(by0),1),'球缩放',sb)
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""小地图任务终点的素材(七个墓用任务日志的塔拉夏符号,其余终点用原版地图名牌,画面外贴边只写名字)。
|
||||
全部取自原版资源,不画原版没有的形状:
|
||||
· 塔拉夏符号 hd/global/ui/PANEL/Quest_Log/TalRashaSymbol.sprite(7 帧;第 N 帧 = 关卡 66+N 墓门门楣上刻的那个,宿主逐门截图对过 66/67/68/70)
|
||||
· 名牌下的灰十字 = 自动地图单位十字 hd/global/ui/AUTOMAP/Units.sprite 第 6 帧(白)按 50% 透明画(原版地图上 NPC 名字下就是这个灰十字)
|
||||
· 名牌 = 原版地图给 NPC / 物件标名的样式:深色半透明底 + 名字;人名浅金 (212,196,145)、物件白字(取自原版小地图截图);字体 hd/ui/fonts/BlizzardGlobal-V5_81.ttf
|
||||
· 名字 = 原版字符串(data/local/lng/strings/*.json 的 zhCN;英文版 label_<序号>_en.png 取 enUS);旧译名(自定义页「物品注释与旧译名」开着时游戏显示的名字)取 annot/oldnames.tsv
|
||||
产物(构建时生成,不进仓库):Gen/assets/NativeHUD/mapgoal/{sym_0..6.png, cross.png, label_<序号>.png, 旧译名不同的 label_<序号>_old.png, mapgoal.json}。
|
||||
用法:python3 dm/ios/tools/gen_map_goal_art.py <原版 RomFS(Update)> (读包与解贴图走 romfs_art.py)
|
||||
Assets for minimap quest goals (the seven tombs use the Tal Rasha symbols from the quest log, other goals use the original map name labels, and goals outside the view are pinned to the edge with the name only).
|
||||
Everything is taken from the original game's resources; no shape is drawn that the original game does not have:
|
||||
- Tal Rasha symbols hd/global/ui/PANEL/Quest_Log/TalRashaSymbol.sprite (7 frames; frame N = the one carved on the lintel of the tomb door of level 66+N, checked door by door against host screenshots for 66/67/68/70)
|
||||
- Gray cross under the label = the automap unit cross hd/global/ui/AUTOMAP/Units.sprite frame 6 (white) drawn at 50% opacity (on the original map this gray cross sits under NPC names)
|
||||
- Name label = the style the original map uses to name NPCs / objects: dark translucent backing + name; light gold (212,196,145) for people, white for objects (taken from screenshots of the original minimap); font hd/ui/fonts/BlizzardGlobal-V5_81.ttf
|
||||
- Names = original strings (zhCN from data/local/lng/strings/*.json; for the English version label_<index>_en.png takes enUS); legacy translated names (the names the game shows when "Item notes and legacy translated names" is on in the Custom page) come from annot/oldnames.tsv
|
||||
Outputs (generated at build time, not kept in the repository): Gen/assets/NativeHUD/mapgoal/{sym_0..6.png, cross.png, label_<index>.png, label_<index>_old.png where the legacy name differs, mapgoal.json}.
|
||||
Usage: python3 dm/ios/tools/gen_map_goal_art.py <original RomFS (Update)> (package reading and texture decoding go through romfs_art.py)"""
|
||||
import csv, json, os, struct, sys
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
import romfs_art
|
||||
from gen_paths import gen_dir
|
||||
OUT = gen_dir('NativeHUD', 'mapgoal'); ROMFS = None
|
||||
NPC, OBJ = (212, 196, 145), (255, 255, 255)
|
||||
# 名牌表:序号是宿主 dm_world.c 终点表里的「名牌号」,只许往后加、不许改序号
|
||||
# Label table: the index is the "label number" in the goal table of the host's dm_world.c; entries may only be appended, indices must not be changed
|
||||
LABELS = [
|
||||
('levels', "Tal Rasha's Tomb", OBJ), # 0 画面外的真墓(画面内用符号) | 0 The true tomb when off screen (on screen the symbol is used)
|
||||
('monsters', 'Bloodraven', NPC), # 1 血鸦 | 1 Blood Raven
|
||||
('objects', 'StoneAlpha', OBJ), # 2 凯恩之石(石柱) | 2 Cairn Stones (stone pillars)
|
||||
('objects', 'Inifuss', OBJ), # 3 因纽斯之树 | 3 Tree of Inifuss
|
||||
('monsters', 'The Countess', NPC), # 4 女伯爵 | 4 The Countess
|
||||
('item-names', 'hdm', OBJ), # 5 赫拉迪姆之锤 | 5 Horadric Malus
|
||||
('monsters', 'Radament', NPC), # 6
|
||||
('item-names', 'box', OBJ), # 7 赫拉迪姆魔盒 | 7 Horadric Cube
|
||||
('item-names', 'Staff of Kings', OBJ), # 8 列王之杖 | 8 Staff of Kings
|
||||
('objects', 'taintedsunaltar', OBJ), # 9 被污染的太阳祭坛 | 9 Tainted Sun Altar
|
||||
('monsters', 'The Summoner', NPC), # 10 召唤者 | 10 The Summoner
|
||||
('item-names', 'qey', OBJ), # 11 卡林姆的晶体 | 11 Khalim's Eye
|
||||
('item-names', 'qbr', OBJ), # 12 卡林姆的智慧 | 12 Khalim's Brain
|
||||
('item-names', 'qhr', OBJ), # 13 卡林姆的生命核心 | 13 Khalim's Heart
|
||||
('objects', 'compellingorb', OBJ), # 14 强迫之球 | 14 Compelling Orb
|
||||
('item-names', 'bbb', OBJ), # 15 兰姆·艾森之书 | 15 Lam Esen's Tome
|
||||
('levels', 'Ruined Temple', OBJ), # 16 市集里通往毁灭的神庙的入口 | 16 Entrance in the Bazaar leading to the Ruined Temple
|
||||
('monsters', 'Izual', NPC), # 17
|
||||
('objects', 'Hellforge', OBJ), # 18 地狱熔炉 | 18 Hellforge
|
||||
('item-names', 'Seal', OBJ), # 19 封印 | 19 Seal
|
||||
('monsters', 'Siege Boss', NPC), # 20 督军山克 | 20 Shenk the Overseer
|
||||
('objects', 'cagedwussie1', OBJ), # 21 笼子(野蛮人囚笼) | 21 Cage (barbarian prison cage)
|
||||
('npcs', 'Drehya', NPC), # 22 安雅 | 22 Anya
|
||||
('objects', 'orifice', OBJ), # 23 真墓里的法杖底座 | 23 Staff orifice in the true tomb
|
||||
('objects', 'gidbinn altar', OBJ), # 24 吉德宾祭坛 | 24 Gidbinn altar
|
||||
('monsters', 'Andariel', NPC), # 25 安达莉尔 | 25 Andariel
|
||||
('monsters', 'Duriel', NPC), # 26 督瑞尔 | 26 Duriel
|
||||
('monsters', 'Mephisto', NPC), # 27 墨菲斯托 | 27 Mephisto
|
||||
('monsters', 'Baal', NPC), # 28 巴尔(王座上) | 28 Baal (on the throne)
|
||||
('objects', 'ancientsaltar', OBJ), # 29 天坛(召出远古三人的祭坛) | 29 Altar of the Heavens (the altar that summons the three Ancients)
|
||||
('npcs', 'Nihlathak', NPC), # 30 尼拉塞克(按他的出生点物件定位) | 30 Nihlathak (located by his spawn point object)
|
||||
]
|
||||
TEXT_PX, PAD_X, PAD_Y, BOX_A = 48, 10, 6, 150 # 按 48 像素字出图,前端按屏高缩放(原版地图名牌字高约屏高的 1/53) | Rendered with 48-pixel text, the front end scales by screen height (the original game's map label glyph height is about 1/53 of screen height)
|
||||
|
||||
def sprite_png(path):
|
||||
b = romfs_art.read(ROMFS, path); assert b[:4] == b'SpA1'
|
||||
code, fw, w, h, frames = struct.unpack_from('<HHII4xH', b, 4); assert code == 0x3d, (path, code)
|
||||
return romfs_art.dxt5(b, w, h), fw, frames, w // frames
|
||||
|
||||
def strings(name):
|
||||
return {r['Key']: r for r in json.loads(romfs_art.read(ROMFS, 'local/lng/strings/%s.json' % name).decode('utf-8-sig'))}
|
||||
|
||||
def label(text, col, font):
|
||||
d0 = ImageDraw.Draw(Image.new('RGBA', (1, 1))); w = int(d0.textlength(text, font=font)) + 2 * PAD_X; h = TEXT_PX + 2 * PAD_Y
|
||||
im = Image.new('RGBA', (w, h), (0, 0, 0, BOX_A)); ImageDraw.Draw(im).text((w / 2, h / 2), text, font=font, fill=col + (255,), anchor='mm')
|
||||
return im
|
||||
|
||||
def main():
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
sym, fw, n, pitch = sprite_png('hd/global/ui/PANEL/Quest_Log/TalRashaSymbol.sprite'); assert n == 7
|
||||
for i in range(7): sym.crop((i * pitch, 0, i * pitch + fw, sym.height)).save(os.path.join(OUT, 'sym_%d.png' % i))
|
||||
units, ufw, un, upitch = sprite_png('hd/global/ui/AUTOMAP/Units.sprite'); assert un == 8
|
||||
cross = units.crop((6 * upitch, 0, 6 * upitch + ufw, units.height)); a = cross.split()[3].point(lambda v: v // 2); cross.putalpha(a); cross.save(os.path.join(OUT, 'cross.png'))
|
||||
font = ImageFont.truetype(romfs_art.font(ROMFS, 'BlizzardGlobal-V5_81.ttf'), TEXT_PX)
|
||||
oldp = os.path.join(HERE, 'annot', 'oldnames.tsv') # 旧译名对照表可以没有(公开仓库不带):没有就都用现行名 | the old-name table may be absent (the public repository does not carry it): without it the current names are used throughout
|
||||
old = {(r[0], r[1]): r[3] for r in csv.reader(open(oldp, encoding='utf-8'), delimiter='\t') if len(r) >= 4} if os.path.isfile(oldp) else {}
|
||||
cache, man = {}, []
|
||||
for i, (f, key, col) in enumerate(LABELS):
|
||||
if f not in cache: cache[f] = strings(f)
|
||||
zh = cache[f][key]['zhCN']; zo = old.get((f, key), zh)
|
||||
label(zh, col, font).save(os.path.join(OUT, 'label_%d.png' % i))
|
||||
if zo != zh: label(zo, col, font).save(os.path.join(OUT, 'label_%d_old.png' % i)) # 旧译名不同才出(前端没有 _old 就用 label_<序号>) | Only emitted when the old translated name differs (without _old the front end uses label_<index>)
|
||||
en = cache[f][key]['enUS']; label(en, col, font).save(os.path.join(OUT, 'label_%d_en.png' % i)) # 英文版:原版 enUS 名字,游戏语言不是简中时前端用它 | English version: the original enUS name, used by the front end when the game language is not Simplified Chinese
|
||||
man.append({'id': i, 'file': f, 'key': key, 'zhCN': zh, 'old': zo, 'enUS': en, 'color': list(col)})
|
||||
json.dump({'text_px': TEXT_PX, 'symbol_frames': 7, 'labels': man}, open(os.path.join(OUT, 'mapgoal.json'), 'w'), ensure_ascii=False, indent=1)
|
||||
print('mapgoal:符号 7 帧、十字 1、名牌 %d(旧译名不同的 %d)→ %s' % (len(man), sum(m['old'] != m['zhCN'] for m in man), OUT))
|
||||
|
||||
if __name__ == '__main__': ROMFS = sys.argv[1]; main()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
# 佣兵面板加装备位用的底图(构建时从玩家的游戏文件生成到 Gen/assets/NativeHUD/mercslots,不进仓库;merc_slots.py 只拷)。用法:gen_merc_art.py <原版 RomFS>
|
||||
# 原版佣兵面板底图(652×704,1 像素 = 2 布局单位)自带石纹和四个凹槽,石纹颗粒、凹槽边框都和玩家装备栏不是一套(玩家栏 = 手柄界面通用底板 MainPanelBG 第 1 帧右半的石纹
|
||||
# + 透明底的格子整图 InventoryBG)。直接把角色装备栏整块扣过来。所以名字条以上整块换成玩家栏那一套,逐像素原样拷、不重画不配色:
|
||||
# 石纹 = 通用底板第 1 帧里玩家栏装备区那一块(格子图在该帧里的左上角是 (814, 95),量自实跑截图并与布局数对过);
|
||||
# 格子 = 经典版格子图 InventoryBG_Classic 的装备十格(与资料片版逐格相同,只是武器格顶上没有 I / II 页签帽——佣兵没有武器切换),药水四格那一块不贴;
|
||||
# 位置 = 格子图左上角放在佣兵底图的 (DX, DY):这样佣兵底图边框以内正好落在通用底板的石纹区里(含两个上角的角花)。merc_slots.py 按同一个偏移把十个物品格摆到玩家栏的格位。
|
||||
# 面板四周 8 像素的边仍是佣兵原图的;名字条(原 y 312–422)整条下移 108;属性表五行各取一条 34 像素高的横带(原行距 47.5)依次排在名字条下面,表正好到底。
|
||||
# 重新编码成原包同款 DXT5(借 gen_widestash_art.py 的解码 / 编码 / 打包)
|
||||
# Base image for the extra equipment slots in the mercenary panel (generated at build time from the player's game files into Gen/assets/NativeHUD/mercslots, not in the repository; merc_slots.py only copies it). Usage: gen_merc_art.py <original RomFS>
|
||||
# The original mercenary panel base image (652×704, 1 pixel = 2 layout units) comes with its own stone texture and four recesses, and neither the stone grain nor the recess borders are of the same set as the player's equipment panel (player panel = the stone texture of the right half of frame 1 of the generic controller UI base panel MainPanelBG
|
||||
# + the whole grid image InventoryBG on a transparent background). The character's equipment panel block is taken over directly. So everything above the name strip is replaced with the player panel's set, copied pixel for pixel, with no redrawing and no recoloring:
|
||||
# Stone texture = the block of the player panel's equipment area in frame 1 of the generic base panel (the grid image's top-left corner in that frame is (814, 95), measured from an actual-run screenshot and checked against the layout numbers);
|
||||
# Cells = the ten equipment cells of the Classic grid image InventoryBG_Classic (cell for cell the same as the expansion version, only without the I / II tab caps on top of the weapon cells -- mercenaries have no weapon swap); the block of the four potion cells is not pasted;
|
||||
# Position = the grid image's top-left corner goes at (DX, DY) in the mercenary base image: this way the inside of the mercenary base image's border falls exactly within the stone texture area of the generic base panel (including the corner ornaments at the two top corners). merc_slots.py places the ten item cells at the player panel's cell positions with the same offset.
|
||||
# The 8-pixel border around the panel is still from the original mercenary image; the name strip (originally y 312–422) moves down as a whole by 108; each of the five stat table rows takes a 34-pixel-high horizontal band (original row pitch 47.5), placed one after another below the name strip, and the table reaches exactly to the bottom.
|
||||
# Re-encoded as DXT5, the same as in the original package (borrowing the decode / encode / pack code of gen_widestash_art.py)
|
||||
import os, struct, sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from PIL import Image
|
||||
import gen_widestash_art as GW
|
||||
|
||||
ART = __import__('gen_paths').gen_dir('NativeHUD', 'mercslots')
|
||||
DX, DY = 63, 11 # 格子图左上角在佣兵底图里的位置(像素) | Position (pixels) of the grid image's top-left corner in the mercenary base image
|
||||
INV_AT = (814, 95) # 格子图左上角在通用底板第 1 帧里的位置(像素) | Position (pixels) of the grid image's top-left corner in frame 1 of the generic base panel
|
||||
EQUIP_H, POTION = 392, (122, 345, 388) # 格子图里装备区的高;药水四格所在那块(x 起、y 起、x 止,到装备区底)不贴 | Height of the equipment area in the grid image; the block holding the four potion cells (x start, y start, x end, down to the bottom of the equipment area) is not pasted
|
||||
EDGE = 8 # 佣兵底图四周的面板边 | Panel border around the mercenary base image
|
||||
BAND = (312, 422) # 名字条在原图里的上下沿 | Top and bottom edges of the name strip in the original image
|
||||
BAND_Y, ROW_H, ROW_TOPS = 420, 34, (448, 495, 543, 590, 638) # 名字条新上沿;属性表每行取的横带高与原图里各行横带的上沿 | New top edge of the name strip; height of the horizontal band taken for each stat table row, and the top edges of the rows' bands in the original image
|
||||
|
||||
def main(romfs):
|
||||
L = GW.lib(); b = GW.orig(romfs, 'hirelinginventory/v2/hirelinginventorybg'); ver, fw, w, h = struct.unpack_from('<HHII', b, 4)
|
||||
assert b[:4] == b'SpA1' and ver == 61 and (fw, w, h) == (652, 652, 704), '佣兵面板底图不是 652×704(原版资源变了?)'
|
||||
src = GW.decode(L, b); inv = GW.decode(L, GW.orig(romfs, 'inventorypanel/v2/inventorybg_classic')); assert inv.size == (507, 700), '经典版格子图不是 507×700'
|
||||
mp = GW.decode(L, GW.orig(romfs, 'mainpanelbg')); assert mp.size == (2888, 881), '通用底板不是 2888×881'
|
||||
mp = mp.crop((mp.width // 2, 0, mp.width, mp.height)) # 第 1 帧(双面板) | Frame 1 (double panel)
|
||||
im = src.copy()
|
||||
sx, sy = INV_AT[0] - DX, INV_AT[1] - DY
|
||||
im.paste(mp.crop((sx + EDGE, sy + EDGE, sx + w - EDGE, sy + BAND_Y)).convert('RGBA'), (EDGE, EDGE)) # 石纹:边框以内、名字条以上 | Stone texture: inside the border, above the name strip
|
||||
for x0, x1 in ((0, EDGE), (w - EDGE, w)): im.paste(src.crop((x0, 100, x1, 100 + BAND_Y - BAND[0])), (x0, BAND[0])) # 左右面板边在原名字条那一段接着往下 | The left / right panel edges continue downward over the span of the original name strip
|
||||
for box in ((0, 0, inv.width, POTION[1]), (0, POTION[1], POTION[0], EQUIP_H), (POTION[2], POTION[1], inv.width, EQUIP_H)):
|
||||
fr = inv.crop(box); im.paste(fr, (DX + box[0], DY + box[1]), fr)
|
||||
im.paste(src.crop((0, BAND[0], w, BAND[1])), (0, BAND_Y)); y = BAND_Y + BAND[1] - BAND[0]
|
||||
for t in ROW_TOPS: im.paste(src.crop((0, t, w, t + ROW_H)), (0, y)); y += ROW_H
|
||||
if y < h: im.paste(src.crop((0, h - (h - y), w, h)), (0, y)) # 余下的贴原图最底下那几行(面板下边) | The rest is filled with the bottom-most rows of the original image (the panel's bottom edge)
|
||||
o = GW.pack(L, b, GW.bc3(im), w, h, w); open(os.path.join(ART, 'HirelingInventoryBG.sprite'), 'wb').write(o); im.save(os.path.join(ART, 'HirelingInventoryBG.png'))
|
||||
print('HirelingInventoryBG:%d×%d,%d 字节' % (w, h, len(o)))
|
||||
|
||||
if __name__ == '__main__': main(sys.argv[1])
|
||||
@@ -0,0 +1,12 @@
|
||||
"""构建时从游戏文件生成的资源放哪(仓库里不放原版衍生的图和字):环境变量 DM_GEN_ASSETS,缺省 dm/ios/Gen/assets(Gen/ 不进 git)。
|
||||
本模块不 import 别的工具模块(生成脚本与读取方互相 import,放这里免得循环)。
|
||||
Where resources generated at build time from the game files go (the repo holds no images or text derived from the original game): environment variable DM_GEN_ASSETS, default dm/ios/Gen/assets (Gen/ is not in git).
|
||||
This module does not import other tool modules (generator scripts and readers import each other; putting it here avoids cycles)."""
|
||||
import os
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def gen_dir(*sub):
|
||||
root = os.environ.get('DM_GEN_ASSETS') or os.path.join(HERE, '..', 'Gen', 'assets')
|
||||
p = os.path.normpath(os.path.join(root, *sub)); os.makedirs(p, exist_ok=True); return p
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
# 百宝囊框贴图(背包下方金币框左边一个同款框):从原版物品栏底图 InventoryBG_Classic(网格 + 金币框,507×700)
|
||||
# 裁金币框那一块(像素 x 152–352、y 628–692),左右各留 24 像素的框边、中间压窄到 140 像素宽,存成同格式精灵图 Gen/assets/NativeHUD/pouch/PouchBox.sprite(构建时生成,不进仓库)。
|
||||
# 底图里金币框外圈在 x 154–351、y 627–691(逐行量透明度)。用法:gen_pouch_art.py <原版 RomFS(Update)>(构建时跑;pouch_layout.py 只拷)
|
||||
# Pouch box texture (a matching box to the left of the gold box below the inventory): from the original game's inventory base image InventoryBG_Classic (grid + gold box, 507×700)
|
||||
# crop the gold box piece (pixels x 152–352, y 628–692), keep 24 pixels of box border on each side and squeeze the middle to 140 pixels wide, saved as a sprite of the same format Gen/assets/NativeHUD/pouch/PouchBox.sprite (generated at build time, not committed to the repo).
|
||||
# In the base image the gold box's outer ring is at x 154–351, y 627–691 (alpha measured row by row). Usage: gen_pouch_art.py <original game RomFS (Update)> (run at build time; pouch_layout.py only copies)
|
||||
import os, sys
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE); sys.path.insert(0, os.path.join(HERE, '..', '..', 'tools'))
|
||||
import gen_widestash_art as G, dmx
|
||||
from PIL import Image
|
||||
|
||||
W, CAP = 140, 24
|
||||
|
||||
def main():
|
||||
dmx.ROOT = os.path.join(sys.argv[1], 'data'); L = G.lib()
|
||||
src = dmx.get('data/hd/global/ui/controller/panel/inventorypanel/v2/inventorybg_classic.sprite'); im = G.decode(L, src)
|
||||
fr = im.crop((152, 628, 352, 692)); h = fr.height
|
||||
out = Image.new('RGBA', (W, h)); out.paste(fr.crop((0, 0, CAP, h)), (0, 0)); out.paste(fr.crop((fr.width - CAP, 0, fr.width, h)), (W - CAP, 0))
|
||||
out.paste(fr.crop((CAP, 0, fr.width - CAP, h)).resize((W - 2 * CAP, h), Image.LANCZOS), (CAP, 0))
|
||||
p = os.path.join(__import__('gen_paths').gen_dir('NativeHUD', 'pouch'), 'PouchBox.sprite'); open(p, 'wb').write(G.pack(L, src, G.bc3(out), W, h, W))
|
||||
print('PouchBox:%d×%d 像素(布局 %d×%d 单位)→ %s' % (W, h, 2 * W, 2 * h, p))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env python3
|
||||
# 构建时生成 App 内 RomFS 覆盖层(romfs_overlay/data/{.build.config, 新数据档}):底部 UI v4(NativeHUD/v4,见 gen_hud_v4.py)。
|
||||
# 用法:gen_romfs_overlay.py <原版 RomFS> <输出目录>。底图写进借用路径(dm/data/casc_overlay/borrowed_paths.tsv),布局替换手柄 HUDPanelHD.json;
|
||||
# 其余数据档仍由基底 RomFS 提供(App 启动按 DM_ROMFS_OVERLAY 先查本层),所以只拷新 .build.config 与本次新写的那一个数据档。
|
||||
# Generates the in-App RomFS overlay at build time (romfs_overlay/data/{.build.config, new data archive}): bottom UI v4 (NativeHUD/v4, see gen_hud_v4.py).
|
||||
# Usage: gen_romfs_overlay.py <original game RomFS> <output dir>. The base image is written into the borrowed path (dm/data/casc_overlay/borrowed_paths.tsv), the layout replaces the controller HUDPanelHD.json;
|
||||
# the other data archives are still supplied by the base RomFS (at launch the App checks this layer first via DM_ROMFS_OVERLAY), so only the new .build.config and the one data archive newly written this time are copied.
|
||||
import re
|
||||
import json, os, struct, subprocess, sys, tempfile, shutil
|
||||
from PIL import Image
|
||||
HERE=os.path.dirname(os.path.abspath(__file__)); V4=os.environ.get('DM_HUD_V4_DIR') or __import__('gen_paths').gen_dir('NativeHUD','v4') # 试调时可指向别的产物目录 | Can point to another build output directory when tuning
|
||||
romfs, out = sys.argv[1], sys.argv[2]
|
||||
sys.path.insert(0,HERE); import gen_assets; gen_assets.ensure(romfs) # 要读的生成资源(底栏 v4、选角右侧面板…)先确保齐全;输入没变不重出(gen_assets.py 文件头) | First make sure the generated resources to be read (bottom bar v4, character select right panel...) are complete; not regenerated if inputs are unchanged (gen_assets.py file header)
|
||||
REPL={'data/hd/global/ui/panel/hud_02/bugbtn.sprite':'base.sprite', # 借用路径(登记表「当前用途」= 底部 UI v4 底图) | Borrowed path (registry 「当前用途」(current use) = bottom UI v4 base image)
|
||||
'data/hd/global/ui/panel/hud_02/front_panel.sprite':'close.sprite', # 借用路径:局内面板外框右上角的关闭按钮图(NativeHUD/touch/close.png,gen_close_btn.py) | Borrowed path: the close button image at the top-right corner of the in-game panel outer frame (NativeHUD/touch/close.png, gen_close_btn.py)
|
||||
'data/global/ui/layouts/controller/hudpanelhd.json':os.path.join(V4,'hud.json')}
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
# 系统通知框(如改难度后的「游戏难度设为 N…」):左边 = 七格行最左格(难度格)左外沿,右边 = 最右格(红十字)右外沿,停留 5 秒;高度不动,纵向比原版上移 100 单位(原位 y=-500 压住底栏上方「Lv · 经验」那行)
|
||||
# (原版宽 1200 单位居中屏幕、停 10 秒)。几何从 hud_v4_ui/ui.json 的七格算,不手写:布局 1 单位 = 屏高/2160(gen_hud_v4.py 实测),框锚点在屏幕水平中心。
|
||||
# 落点按真机量(界面按游戏内部分辨率画,落到 2868 宽屏幕上约 1.8 px 一格取整):边框亮线两侧各有 1 px 暗边,宽度两边各放 1 px;
|
||||
# 中心再左移 1 单位才落到左亮线 x=973、右外沿 x=1807(= 七格外沿 973 / 1807)。四档实测
|
||||
# System notification box (e.g. 「游戏难度设为 N…」(Game difficulty set to N...) after changing difficulty): left edge = left outer edge of the leftmost slot of the seven-slot row (difficulty slot), right edge = right outer edge of the rightmost slot (red cross), stays 5 seconds; height unchanged, vertically moved up 100 units from the original game (the original position y=-500 covers the "Lv · experience" line above the bottom bar)
|
||||
# (the original game's is 1200 units wide, centered on screen, staying 10 seconds). Geometry is computed from the seven slots in hud_v4_ui/ui.json, not hand-written: 1 layout unit = screen height/2160 (measured in gen_hud_v4.py), the box anchor is at the horizontal center of the screen.
|
||||
# Placement is measured on a real device (the UI is drawn at the game's internal resolution, landing on the 2868-wide screen rounded at about 1.8 px per cell): the border's bright line has a 1 px dark edge on each side, so the width is extended 1 px on each side;
|
||||
# the center is then moved 1 more unit left to land on left bright line x=973, right outer edge x=1807 (= seven-slot outer edges 973 / 1807). Measured on four profiles
|
||||
ui=json.load(open(os.path.join(V4,'hud_v4_ui','ui.json'))); ref_w,ref_h=ui['ref']; k=2160/ref_h
|
||||
x0,x1=ui['slots'][0][0]-1,ui['slots'][-1][2]+1
|
||||
nw=round((x1-x0)*k); nx=round(((x0+x1)/2-ref_w/2)*k)-1
|
||||
# 系统提示框:整份自己写、不继承原版那份——原版带一个铺满的 Confirm 按钮(继承来的子控件删不掉),提示在屏上时它接住功能键和点击:
|
||||
# 按功能键 / 点它压着的地方都只是把提示关掉(面板开不了、下面的格子点不到)。触屏上提示到点自己消失,不要这个按钮
|
||||
# System notification: written entirely by ourselves, not inheriting the original game's one -- the original carries a full-cover Confirm button (an inherited child widget cannot be deleted), which catches the function key and taps while the notification is on screen:
|
||||
# pressing the function key / tapping where it covers only dismisses the notification (the panel cannot open, the cells beneath cannot be tapped). On a touchscreen the notification disappears by itself when its time is up, so this button is not wanted
|
||||
note={'type':'NotificationPanel','name':'NotificationPanel',
|
||||
'fields':{'priority':9002,'notificationSeconds':5.0,'transitionSeconds':0.8,'rect':{'x':nx,'y':-600,'width':nw,'height':244},'anchor':{'x':0.5,'y':1.0}},
|
||||
'children':[{'type':'NineTileImageWidget','name':'NotificationBorder',
|
||||
'fields':{'rect':{'x':0,'y':0,'width':nw,'height':244},'anchor':{'x':-0.5,'y':0.0},'filename':'PANEL/TooltipBorder/TooltipBorder','backgroundColor':[0.0,0.0,0.0,0.70],'tileScale':1},
|
||||
'children':[{'type':'TextBoxWidget','name':'Prompt','fields':{'fitToParent':True,'style':'$StyleNotification'}}]}]}
|
||||
json.dump(note,open(os.path.join(t,'notification.json'),'w'),indent=1)
|
||||
REPL['data/global/ui/layouts/controller/notificationpanelhd.json']=os.path.join(t,'notification.json')
|
||||
# 全触摸方案:前端与通用弹窗上的手柄键位提示挪出屏幕(按钮本身可点之后,字形就是错误信息);清单与做法见 touch_layout.py
|
||||
# Full-touch scheme: controller button hints on the front end and generic popups are moved off screen (once the buttons themselves are tappable, the glyphs are misinformation); list and method in touch_layout.py
|
||||
sys.path.insert(0,HERE); import touch_layout
|
||||
tl,ntl=touch_layout.build(romfs,t); REPL.update(tl)
|
||||
REPL.update(touch_layout.build_pcfront(romfs,t)) # 选角页改用键鼠版界面(盖掉上面 build 对这几份的改动) | Character select page switched to the keyboard-and-mouse UI (overrides the changes the build above made to these files)
|
||||
tp,ntp=touch_layout.build_present(romfs,t); REPL.update(tp) # 局内:页签条两端 L / R、人物页耐力行 | In-game: L / R at the two ends of the tab strip, stamina row on the character page
|
||||
ti,nti=touch_layout.build_ingame(romfs,t); REPL.update(ti) # 局内:各面板右上角的关闭按钮(同一落点、各发各的消息)与手柄版删掉的功能按钮(修理 / 翻页 / 高级属性 / 选项页应用·默认·放弃);要在 build_present 之后(同一文件以这份为准) | In-game: the close button at each panel's top-right corner (same position, each sending its own message) and the function buttons removed in the controller version (repair / page turn / advanced stats / options page apply·default·discard); must come after build_present (for the same file this copy wins)
|
||||
import merc_slots; REPL.update(merc_slots.build(romfs,t,REPL)) # 佣兵面板加六个装备位(底图 + 布局;要在 build_ingame 给它插关闭钮之后) | Add six equipment slots to the mercenary panel (base image + layout; must come after build_ingame has inserted the close button into it)
|
||||
REPL.update(touch_layout.build_cursor(romfs,t)) # 面板里的手柄光标圆环换成透明 | The controller cursor ring in panels replaced with a transparent one
|
||||
REPL.update(touch_layout.build_glyphs(romfs,t)) # 22 张手柄键图标换成透明 | 22 controller button icons replaced with transparent ones
|
||||
REPL.update(touch_layout.build_profile(romfs,t)) # 大字号 | Large font size
|
||||
import touch_strings; ts,nts=touch_strings.build(romfs,t); REPL.update(ts) # 排版用的串(大字号);手柄说法 → 触摸说法改由宿主按模式换(旁路表 touch_strings.tsv,见 emit) | Strings used for typesetting (large font size); controller wording → touch wording is now switched by the host according to mode (sidecar table touch_strings.tsv, see emit)
|
||||
TS=touch_strings.build_sidecar(romfs)
|
||||
import dm_i18n; si,nsi=dm_i18n.build(romfs,t,REPL); REPL.update(si) # 我们自己的界面文字(中英表 dm/i18n/ui_text.tsv)追加进原版 ui.json,布局写 @键、宿主按键取串 | our own UI text (Chinese-English string table dm/i18n/ui_text.tsv) is appended to the original ui.json; layouts write @key and the host looks strings up by key
|
||||
import drop_light; dl,dls=drop_light.build(romfs,t,REPL); REPL.update(dl) # 掉落光的带光模型变体(新增路径,常驻;宿主运行时按规则 / 开关改指,dm_dropfilter.c) | Lit model variants for drop lights (new paths, always present; the host repoints at runtime by rule / switch, dm_dropfilter.c)
|
||||
import pouch_layout; pl,pls=pouch_layout.build(romfs,t,REPL); REPL.update(pl) # 百宝囊框与「存放」按钮(物品栏,叠在触摸布局之后) | Pouch box and 「存放」(Deposit) button (inventory, stacked after the touch layout)
|
||||
import wide_stash; ws,wss=wide_stash.build(romfs,t,REPL); REPL.update(ws)
|
||||
# 手柄版布局:手柄模式读原版路径上的布局(触屏版挪进了触屏目录,见下面 TDIR)。我们的功能改动两种模式都要——符文之语清单、百宝囊框与「存放」、
|
||||
# 储藏箱 14 列(数据表已是 14 列,布局只有 10 列时第 11–14 列的物品看不到)与宽外框、编年史仓库页签——所以按同一套功能模块在原版布局上再出一份,放在原版路径;触屏改动不带
|
||||
# Controller layouts: controller mode reads the layouts at the original paths (the touch version was moved into the touch directories, see TDIR below). Our
|
||||
# feature changes are needed in both modes: the runeword list, the pouch frame and "Deposit",
|
||||
# the 14-column stash (the data table already has 14 columns; with a 10-column layout the items in columns 11 to 14 are invisible) with its wide frame,
|
||||
# and the Chronicle vault tab. So another copy is generated on top of the original layouts with the same set of feature modules and placed at the
|
||||
# original paths; touch changes are not included
|
||||
tpad=os.path.join(t,'pad'); os.makedirs(tpad); PR={}
|
||||
lp,lt=touch_layout.read_layout(romfs,pouch_layout.INV); o=os.path.join(tpad,'pad_inv.json'); open(o,'w',encoding='utf-8').write(touch_layout.pad_inv_rw(lt)); PR[lp.lower()]=o
|
||||
for rel,gd in (('controller/pauselayoutgardenhd.json',1),('controller/pauselayouthd.json',0)): # 手柄版暂停菜单:一键重开 / 切换难度 / 存放 / 分享诊断日志 | Controller pause menu: one-tap restart / change difficulty / Deposit / Share Diagnostics
|
||||
lp,lt=touch_layout.read_layout(romfs,rel); o=os.path.join(tpad,'pad_pause%d.json'%gd); open(o,'w',encoding='utf-8').write(touch_layout.pad_pause(lt,gd)); PR[lp.lower()]=o
|
||||
# 大秘境面板(借「消息记录」面板外壳,touch_layout._rift_panel):手柄版同一份。少了它手柄模式点秘境门开出来的是空的原版消息记录面板、进不了秘境;手柄键在 dm_rift_ui.c
|
||||
# Greater Rift panel (borrows the shell of the "Message Log" panel, touch_layout._rift_panel): the controller version uses the same one. Without it,
|
||||
# tapping the Rift portal in controller mode opens an empty original Message Log panel and the Rift cannot be entered; the controller keys are in
|
||||
# dm_rift_ui.c
|
||||
lp,lt=touch_layout.read_layout(romfs,'controller/messagelogpanelhd.json'); o=os.path.join(tpad,'pad_rift.json'); open(o,'w',encoding='utf-8').write(touch_layout._rift_panel(lt)[0]); PR[lp.lower()]=o
|
||||
PR.update(merc_slots.build_pad(romfs,tpad)) # 手柄版佣兵面板:同样加六个装备位 | Controller layout mercenary panel: likewise add six equipment slots
|
||||
PR.update(touch_layout.build_ingame(romfs,tpad,touch_layout.PAD_VENDOR,present=False)[0]) # 手柄版商人页:刷新货架钮 | Controller layout vendor page: the refresh shop stock button
|
||||
lp,lt=touch_layout.read_layout(romfs,'controller/console/mainmenupanelhd.json'); o=os.path.join(tpad,'pad_mainmenu.json'); open(o,'w',encoding='utf-8').write(touch_layout.pad_mainmenu(lt)); PR[lp.lower()]=o # 手柄版主菜单:构建号与新版本提示 | Controller layout main menu: build number and new version notice
|
||||
lp,lt=touch_layout.read_layout(romfs,'controller/console/mainmenubuttonribbonhd.json'); o=os.path.join(tpad,'pad_ribbon.json'); open(o,'w',encoding='utf-8').write(touch_layout.pad_ribbon(lt)); PR[lp.lower()]=o # 手柄版主菜单按钮栏:拿掉「电影动画」 | Controller layout main menu button ribbon: remove 「电影动画」(Cinematics)
|
||||
lp,lt=touch_layout.read_layout(romfs,'controller/hudmonsterhealthhd.json'); o=os.path.join(tpad,'pad_bosspct.json'); open(o,'w',encoding='utf-8').write(touch_layout.pad_boss_pct(lt)); PR[lp.lower()]=o # 手柄版怪物血条:加百分比 | Controller layout monster health bar: add the percentage
|
||||
lp,lt=touch_layout.read_layout(romfs,'controller/console/characteroptionspanelhd.json'); o=os.path.join(tpad,'pad_charopt.json'); open(o,'w',encoding='utf-8').write(touch_layout.pad_bliss(lt)); PR[lp.lower()]=o # 手柄版建角模式页:加「极乐世界」一行 | Controller-version character-creation mode page: add the "Elysium" row
|
||||
for rel,fn in (('controller/console/settingspanelhd.json',touch_layout.pad_settings),('controller/console/videooptionspanelhd.json',touch_layout.pad_custom_page)): # 手柄版选项页:「视频」页签换成「自定义」页 | Controller options page: the "Video" tab is replaced by the "Custom" page
|
||||
lp,lt=touch_layout.read_layout(romfs,rel); o=os.path.join(tpad,'pad_'+rel.replace('/','_')); open(o,'w',encoding='utf-8').write(fn(lt)); PR[lp.lower()]=o
|
||||
PR.update(pouch_layout.build(romfs,tpad,PR)[0]); PR.update(wide_stash.build(romfs,tpad,PR)[0]) # 储藏箱 10 → 14 列(编年史仓库第 1 步):表、底图、宽外框、布局;要在触摸布局之后(储藏箱 / 外框布局叠在那份上) | Stash 10 → 14 columns (chronicle vault step 1): table, base image, wide outer frame, layout; must come after the touch layout (the stash / outer frame layout stacks on that copy)
|
||||
cb=Image.open(os.path.join(HERE,'..','NativeHUD','touch','close.png')).convert('RGBA')
|
||||
open(os.path.join(t,'close.sprite'),'wb').write(b'SpA1'+struct.pack('<HHIIIIII',31,cb.width,cb.width,cb.height,0,1,0,0)+struct.pack('<II',cb.width*cb.height*4,4)+cb.tobytes())
|
||||
# 选角页右侧面板底图:去掉「转换角色」的槽与十字花、只留居中一个槽(原图解出后改的,同尺寸)
|
||||
# Character select page right panel base image: remove the 「转换角色」(Convert Character) slot and the cross ornament, leaving only one centered slot (modified after decoding the original image, same size)
|
||||
shutil.copy(os.path.join(__import__('gen_paths').gen_dir('NativeHUD','touch'),'fe_rightpanel.sprite'),os.path.join(t,'fe_rightpanel.sprite')) # 构建时由 gen_fe_rightpanel.py 从原图生成(DXT5 + 块线性);原始 RGBA 的 v31 在 401×1080 这个尺寸上游戏读出竖条花屏 | Generated at build time by gen_fe_rightpanel.py from the original image (DXT5 + block-linear); raw RGBA v31 at this 401×1080 size is read by the game as vertical-stripe garbage
|
||||
REPL['data/hd/global/ui/frontend/hd/final/frontend_rightpanel.sprite']='fe_rightpanel.sprite'
|
||||
im=Image.open(os.path.join(V4,'base.png')).convert('RGBA'); w,h=im.size
|
||||
# SpA1 v31 原始 RGBA:头 0x28 字节(版本 31、帧宽、宽、高、帧数 1、像素字节数),游戏实测可读
|
||||
# SpA1 v31 raw RGBA: 0x28-byte header (version 31, frame width, width, height, frame count 1, pixel byte count), measured to be readable by the game
|
||||
open(os.path.join(t,'base.sprite'),'wb').write(b'SpA1'+struct.pack('<HHIIIIII',31,w,w,h,0,1,0,0)+struct.pack('<II',w*h*4,4)+im.tobytes())
|
||||
# 老机型补充包(显卡不支持 BC 的机型):环境变量 DM_ASTC_PACK = 补充包目录(dm/tools/astc_pack.py + casc_overlay.py pack 的产物,含 pack_index.tsv / pack.json)。
|
||||
# 设了就再出一套 ASTC 版覆盖层(out_astc、out_astc_variants),索引里那 2.7 万张贴图指向补充包的数据档(内容不复制进 App);App 在不支持 BC 且补充包校验通过时挑这一套。
|
||||
# 没设 = 两个目录照建但为空(App 认为本包不带 ASTC 版)。
|
||||
# Legacy Device Pack (devices whose GPU does not support BC): environment variable DM_ASTC_PACK = Legacy Device Pack directory (build output of dm/tools/astc_pack.py + casc_overlay.py pack, containing pack_index.tsv / pack.json).
|
||||
# When set, an additional ASTC overlay set is produced (out_astc, out_astc_variants), in whose index those 27 thousand textures point to the Legacy Device Pack's data archive (contents are not copied into the App); the App picks this set when BC is unsupported and the Legacy Device Pack passes verification.
|
||||
# Not set = the two directories are still created but empty (the App takes it that this package carries no ASTC version).
|
||||
ASTC=os.environ.get('DM_ASTC_PACK','')
|
||||
# 触屏版布局放进自己的目录(手柄支持 P2):原版手柄布局 layouts/controller/ 原样保留,触屏改过的与没改的一并放到三个新目录,
|
||||
# 宿主按模式把原版拼路径用的三个前缀串改写成同长的新目录名(dm_padmode.c)再让游戏重载布局:
|
||||
# Controller/ → Xtouch_lay/、Controller/Console/ → Ztouch_console_lay/、Controller/Console/Switch/ → 0touch_console_switch_lay/
|
||||
# 新目录只能是 layouts 下一层、首字母不能与 layouts 现有子项相同(casc_overlay.py 新增路径的限制;layouts 下 a–y 与 _ 都用了)。
|
||||
# _profile*.json 按固定路径读、PC 专用子目录(pc/)Switch 不用,都留在原处。覆盖层根目录放标记文件 ctrl_touch:宿主见到它才改写前缀
|
||||
# Touch layouts go into their own directories (controller support P2): the original controller layouts layouts/controller/ are kept as is, and touch layouts,
|
||||
# both modified and unmodified, are all put into three new directories;
|
||||
# by mode, the host rewrites the three prefix strings the original uses to build paths into new directory names of the same length (dm_padmode.c) and
|
||||
# then makes the game reload its layouts:
|
||||
# Controller/ → Xtouch_lay/, Controller/Console/ → Ztouch_console_lay/, Controller/Console/Switch/ → 0touch_console_switch_lay/
|
||||
# A new directory must be exactly one level under layouts and its first character must differ from every existing child of layouts (limitation of new
|
||||
# paths in casc_overlay.py; a–y and _ under layouts are all taken).
|
||||
# _profile*.json is read from a fixed path and the PC-only subdirectory (pc/) is not used on Switch, so both stay where they are. The marker file
|
||||
# ctrl_touch is placed in the overlay root: the host rewrites the prefixes only when it sees it
|
||||
LAY='data/global/ui/layouts/'
|
||||
TDIR=[('controller/console/switch/','0touch_console_switch_lay/'),('controller/console/','ztouch_console_lay/'),('controller/','xtouch_lay/')]
|
||||
import romfs_art
|
||||
MAN={f[9].lower().split(':',1)[-1] for f in (l.rstrip('\n').split('|') for l in open(os.path.join(romfs,'data','build_manifest.psv'),encoding='utf-8')) if len(f)>=11}
|
||||
# 键位图标与手柄光标(touch_layout 换成透明的那几张)同样挪到新目录,宿主改写原版拼贴图路径的串(dm_padmode.c):
|
||||
# Controller/ControllerButtons/%s/%s → Ztouch_controller_buttons_ui/%s_%s(平台 / 名字之间的「/」换成「_」,只开一层目录)、Controller/Cursor/X → Xtouch_cursor_lay/X
|
||||
# Button icons and the controller cursor (the ones touch_layout replaces with transparent images) are likewise moved to new directories, and the host
|
||||
# rewrites the strings the original uses to build texture paths (dm_padmode.c):
|
||||
# Controller/ControllerButtons/%s/%s → Ztouch_controller_buttons_ui/%s_%s (the "/" between platform and name becomes "_", so only one directory level
|
||||
# is created), Controller/Cursor/X → Xtouch_cursor_lay/X
|
||||
UI='data/hd/global/ui/'
|
||||
def touch_path(k): # 原版路径 → 触屏目录里的路径;不归触屏目录管的返回 None | Original path → path in the touch directories; returns None for paths the touch directories do not cover
|
||||
if k.startswith(UI+'controller/controllerbuttons/'):
|
||||
r=k[len(UI+'controller/controllerbuttons/'):]; return UI+'ztouch_controller_buttons_ui/'+r.replace('/','_') if r.count('/')==1 else None
|
||||
if k.startswith(UI+'controller/cursor/') and '/' not in k[len(UI+'controller/cursor/'):]: return UI+'xtouch_cursor_lay/'+k[len(UI+'controller/cursor/'):]
|
||||
if not k.startswith(LAY) or '/_profile' in k: return None
|
||||
r=k[len(LAY):]
|
||||
for a,b in TDIR:
|
||||
if r.startswith(a): rest=r[len(a):]; return None if '/' in rest else LAY+b+rest
|
||||
return None
|
||||
ORIG=sorted(q for q in MAN if touch_path(q) and q.startswith(LAY)) # 布局要整套搬(重载时按目录找);贴图只搬换过的那几张,其余平台 / 贴图触屏模式用不到 | Layouts must be moved as a complete set (looked up by directory on reload); for textures only the replaced ones are moved, the other platforms / textures are not used in touch mode
|
||||
def to_touch(repl):
|
||||
r={}
|
||||
for k,v in repl.items(): tp=touch_path(k); r[tp or k]=v
|
||||
for q in ORIG:
|
||||
k=touch_path(q)
|
||||
if k not in r:
|
||||
o=os.path.join(t,'orig_'+q[len(LAY):].replace('/','__'))
|
||||
if not os.path.exists(o): open(o,'wb').write(romfs_art.read(romfs,q))
|
||||
r[k]=o
|
||||
return r
|
||||
# 两种模式本来就该共用的(我们自己的页,手柄 / 触屏同一份布局、宿主按模式摆):编年史三份
|
||||
# 还没分开的存量:两份字号档(开机只读一次)
|
||||
# Meant to be shared by both modes all along (our own pages, one layout for controller / touch, placed by the host according to mode): the three Chronicle ones
|
||||
# Existing stock not yet split: the two font size profiles (read only once at boot)
|
||||
SHARED_TODO=('chroniclebaselistpanelhd.json','chroniclepanelhd.json','controller/_profileconsolehd.json','controller/_profilehandheldhd.json','dropdownlistcontentshd.json')
|
||||
PADROOT=touch_layout.build_pad_root(romfs,tpad); PADROOT_KEYS={k[len(LAY):] for k in PADROOT} # 三份选项页:原路径放手柄那份,触屏那份挪到触屏这边 | The three options pages: the controller copy goes at the original path, the touch copy moves to the touch side
|
||||
UNSHARE=('confirmationmodalhd.json','dismissablemodalhd.json','helpbuttonpanelhd.json','npcdialogpanelhd.json','youdiedmodalhd.json') # 只该给触屏的:挪到触屏这边(见 emit) | Touch-only ones: moved to the touch side (see emit)
|
||||
PADLAY={k:v for k,v in PR.items() if touch_path(k)} # 手柄版只取布局(数据表、图与触屏版同一份) | The controller version takes only layouts (data tables and images are the same copy as the touch version)
|
||||
# 手柄专用清单:手柄模式下不是原版字节的布局就这几份,一份不许多、一份不许少(改上面某一行时把相邻一行整行替掉过,商人页的刷新钮就从包里掉了)
|
||||
# Controller-only list: these are the only layouts that are not original bytes in controller mode, not one more and not one fewer (once, when a line above was edited, the adjacent line was replaced whole, and the vendor page's refresh button dropped out of the package)
|
||||
PAD_PAGES=('controller/bankexpansionlayouthd.json','controller/console/characteroptionspanelhd.json','controller/console/mainmenubuttonribbonhd.json','controller/console/mainmenupanelhd.json','controller/console/settingspanelhd.json','controller/console/switch/playerinventoryexpansionlayouthd.json','controller/console/videooptionspanelhd.json',
|
||||
'controller/controlleroverlayhd.json','controller/hirelinginventorypanelhd.json','controller/hudmonsterhealthhd.json','controller/messagelogpanelhd.json','controller/pauselayoutgardenhd.json','controller/pauselayouthd.json','controller/vendorpanellayouthd.json')
|
||||
if sorted(k[len(LAY):] for k in PADLAY)!=sorted(PAD_PAGES): raise SystemExit('gen_romfs_overlay:手柄专用布局与清单 PAD_PAGES 不一致:多 %s,少 %s' % (sorted(set(k[len(LAY):] for k in PADLAY)-set(PAD_PAGES)), sorted(set(PAD_PAGES)-set(k[len(LAY):] for k in PADLAY))))
|
||||
def emit(repl, dst, tag, prebuilt=None): # repl → 覆盖层(新 .build.config + 一个新数据档)写到 dst/data | repl → overlay (a new .build.config + one new data archive) written to dst/data
|
||||
repl=to_touch(repl); repl.update(PADLAY)
|
||||
# 只该给触屏的根目录布局(不在 Controller/ 前缀下、原先两种模式共用一份改过的):改过的那份挪到触屏这边,原路径不再替换——手柄模式加载到原版字节。
|
||||
# 触屏目录里有页继承它的(basedOn 它的名字):放 1touchbase_lay/ 并把那些页的 basedOn 改指过去;没有页继承的(游戏直接按名字加载):放进触屏目录 xtouch_lay/,触屏模式先在那里找到
|
||||
# Root-directory layouts meant only for touch (not under the Controller/ prefix, previously one modified copy shared by both modes): the modified copy moves to the touch side and the original path is no longer replaced -- controller mode loads original bytes.
|
||||
# If pages in the touch directory inherit from it (basedOn its name): put it in 1touchbase_lay/ and repoint those pages' basedOn there; if no page inherits from it (the game loads it directly by name): put it in the touch directory xtouch_lay/, where touch mode finds it first
|
||||
for name in UNSHARE+tuple(sorted(PADROOT_KEYS)):
|
||||
k=LAY+name; mod=repl.pop(k); pat=re.compile(r'("basedOn"\s*:\s*")(%s)(")' % re.escape(name), re.I); inh=[]
|
||||
for tk,tv in list(repl.items()):
|
||||
if not any(tk.startswith(LAY+d) for _,d in TDIR): continue
|
||||
try: txt=open(os.path.join(t,tv),encoding='utf-8').read()
|
||||
except UnicodeDecodeError: continue
|
||||
if pat.search(txt): inh.append((tk,txt))
|
||||
if inh:
|
||||
repl[LAY+'1touchbase_lay/'+name]=mod
|
||||
for tk,txt in inh:
|
||||
o=os.path.join(t,tag+'unshare_'+tk[len(LAY):].replace('/','__')); open(o,'w',encoding='utf-8').write(pat.sub(lambda m: m.group(1)+'1touchbase_lay/'+m.group(2)+m.group(3), txt)); repl[tk]=o
|
||||
else: assert LAY+'xtouch_lay/'+name not in repl, name; repl[LAY+'xtouch_lay/'+name]=mod
|
||||
if name in PADROOT_KEYS: repl[LAY+name]=PADROOT[LAY+name] # 原路径换成手柄那份(触屏模式已不读原路径这一份) | The original path gets the controller copy (touch mode no longer reads the copy at the original path)
|
||||
print('按模式分开:%s → %s(继承它的触屏页 %d 个;0 = 触屏模式直接按名字加载)' % (name, '1touchbase_lay/' if inh else 'xtouch_lay/', len(inh)))
|
||||
# 手柄模式 = 原版:手柄模式能加载到的布局(触屏三个目录之外的)要么是原版字节(不在替换表里),要么在手柄专用清单 PR 里。
|
||||
# SHARED_TODO 是还没按模式分开的存量(两种模式共用一份改过的),只许减不许加;新增共用布局在这里红
|
||||
# Controller mode = original: the layouts that controller mode can load (those outside the three touch directories) are either original bytes (not in the replacement table) or in the controller-only list PR.
|
||||
# SHARED_TODO is the existing stock not yet split by mode (both modes share one modified copy); it may only decrease, never increase; a newly added shared layout fails here
|
||||
shared=sorted(k[len(LAY):] for k in repl if k.startswith(LAY) and k in MAN and k not in PADLAY and k[len(LAY):] not in PADROOT_KEYS and not any(k.startswith(LAY+d) for _,d in TDIR))
|
||||
if shared!=sorted(SHARED_TODO): raise SystemExit('gen_romfs_overlay:两种模式共用的改过的布局与存量清单不一致(多出的要按模式分开:改过的放触屏目录 / 另起新名,原路径留原版):多 %s,少 %s' % (sorted(set(shared)-set(SHARED_TODO)), sorted(set(SHARED_TODO)-set(shared))))
|
||||
with open(os.path.join(t,tag+'repl.tsv'),'w') as f:
|
||||
for k,v in repl.items(): f.write(f'{"" if k in MAN else "+"}{k}\t{os.path.join(t,v)}\n') # 新增路径前加「+」(casc_overlay.py) | New paths are prefixed with "+" (casc_overlay.py)
|
||||
subprocess.run([sys.executable,os.path.join(HERE,'..','..','tools','casc_overlay.py'),romfs,os.path.join(t,tag+'ov'),os.path.join(t,tag+'repl.tsv')]+(['--prebuilt',prebuilt] if prebuilt else []),check=True,stdout=subprocess.DEVNULL)
|
||||
src=os.path.join(t,tag+'ov','data'); new=[n for n in os.listdir(src) if n.endswith('.data') and not os.path.islink(os.path.join(src,n))]
|
||||
assert len(new)==1, new
|
||||
shutil.rmtree(dst,ignore_errors=True); os.makedirs(os.path.join(dst,'data'))
|
||||
for n in ('.build.config',new[0]): shutil.copyfile(os.path.join(src,n),os.path.join(dst,'data',n))
|
||||
with open(os.path.join(dst,'touch_strings.tsv'),'w',encoding='utf-8') as f: # 键 \t 原文校验(SHA-1 前 8 位) \t 触摸说法(\\ \\n \\t 转义);宿主 dm_padmode.c 读 | key <TAB> source checksum (first 8 hex digits of SHA-1) <TAB> touch wording (backslash, newline and tab are escaped); read by the host's dm_padmode.c
|
||||
for k,o,v in TS: f.write('%s\t%s\t%s\n' % (k,o,v.replace('\\','\\\\').replace('\n','\\n').replace('\t','\\t')))
|
||||
open(os.path.join(dst,'ctrl_touch'),'w').write('触屏版布局在 layouts/xtouch_lay、ztouch_console_lay、0touch_console_switch_lay(dm_padmode.c 见到本文件才改写前缀)\n')
|
||||
return new[0], os.path.getsize(os.path.join(dst,'data',new[0]))
|
||||
n0,z0=emit(REPL,out,'')
|
||||
print(f'romfs_overlay:{n0} {z0} 字节,底图 {w}x{h};前端布局 {len(tl)} 个、挪走键位提示 {ntl} 处')
|
||||
for d in (out+'_astc',out+'_astc_variants'): shutil.rmtree(d,ignore_errors=True); os.makedirs(d)
|
||||
if ASTC:
|
||||
idx=os.path.join(ASTC,'pack_index.tsv'); assert os.path.isfile(idx) and os.path.isfile(os.path.join(ASTC,'pack.json')), 'DM_ASTC_PACK 目录里缺 pack_index.tsv / pack.json:'+ASTC
|
||||
na,za=emit(REPL,out+'_astc','astc_',idx); shutil.copyfile(os.path.join(ASTC,'pack.json'),os.path.join(out+'_astc','pack.json'))
|
||||
assert na==n0, f'ASTC 版覆盖层的新数据档 {na} 与 BC 版 {n0} 不同名(预取清单按名字找档)'
|
||||
print(f'romfs_overlay_astc:{na} {za} 字节(贴图指向补充包 {ASTC})')
|
||||
# 走覆盖层的自定义开关(按组合出全部 2^n 份,App 启动按 dm_custom_get 挑一份,重启生效;开关到第 4 个再换「拼表」方案)。
|
||||
# 每项 = (自定义页的键, 模块名):模块提供 build(romfs, 临时目录, 前面已换的 repl) → ({包内逻辑路径: 本地文件}, 统计),在传入的 repl 之上改(同一文件多个特性都改时自然叠加)。
|
||||
# out 本身 = 全关(宿主验收 / 触摸链用它);其余组合写到 out_variants/<键+键…>/data,各带 features.txt。
|
||||
# Custom page switches that go through the overlay (all 2^n copies are produced by combination; at launch the App picks one by dm_custom_get, effective after restart; switch to the "table-stitching" scheme once there is a 4th switch).
|
||||
# Each entry = (customization page key, module name): the module provides build(romfs, temp dir, the repl replaced so far) → ({logical path in package: local file}, stats), modifying on top of the passed-in repl (naturally stacking when several features change the same file).
|
||||
# out itself = all off (host acceptance / the touch chain use it); the other combinations are written to out_variants/<key+key...>/data, each with its features.txt.
|
||||
FEATURES=[('item_notes','annot_strings')] # 物品注释与旧译名;以后走覆盖层的开关在这里追加一项 | Item notes and old translated names; future switches that go through the overlay append an entry here
|
||||
import importlib, itertools
|
||||
shutil.rmtree(out+'_variants',ignore_errors=True)
|
||||
for r in range(1,len(FEATURES)+1):
|
||||
for combo in itertools.combinations(FEATURES,r):
|
||||
RS=dict(REPL); touched=set(); stats={}
|
||||
for key,mod in combo:
|
||||
ta,st=importlib.import_module(mod).build(romfs,t,RS); RS.update(ta); touched|=set(ta); stats[key]=st
|
||||
# 除特性文件外逐文件相同:没被本组合的特性改过的路径必须原样指向全关那份的文件
|
||||
# File-by-file identical except for feature files: paths not changed by this combination's features must point unchanged to the files of the all-off copy
|
||||
diff=[k for k in RS if k not in touched and RS[k]!=REPL.get(k)]
|
||||
if diff: raise SystemExit('gen_romfs_overlay:组合 %s 除特性文件外与全关那份不一致:%s' % ([k for k,_ in combo],diff))
|
||||
name='+'.join(k for k,_ in combo); dst=os.path.join(out+'_variants',name)
|
||||
n1,z1=emit(RS,dst,name+'_')
|
||||
for key,mod in combo: # 特性模块自带的旁路文件(不进 CASC 的,如物品注释的文字框对照表)写在变体目录根上,宿主按 DM_ROMFS_OVERLAY 找 | Sidecar files that feature modules bring along (those not in CASC, e.g. the item notes' text box mapping table) are written at the variant directory root; the host finds them via DM_ROMFS_OVERLAY
|
||||
m=importlib.import_module(mod)
|
||||
if hasattr(m,'write_textbox_table'): m.write_textbox_table(dst)
|
||||
with open(os.path.join(dst,'features.txt'),'w') as f: f.write('\n'.join(k for k,_ in combo)+'\n'+''.join(f'{p}\n' for p in sorted(touched)))
|
||||
print(f'romfs_overlay_variants/{name}:{n1} {z1} 字节;改了 {len(touched)} 个文件;{stats}')
|
||||
if ASTC: # 同一组合的 ASTC 版:索引另出,旁路文件(features.txt、文字框对照表…)照抄 | ASTC version of the same combination: the index is emitted separately, sidecar files (features.txt, text box mapping table...) are copied as is
|
||||
da=os.path.join(out+'_astc_variants',name); emit(RS,da,name+'_astc_',os.path.join(ASTC,'pack_index.tsv'))
|
||||
for f in os.listdir(dst):
|
||||
if f!='data': shutil.copyfile(os.path.join(dst,f),os.path.join(da,f))
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
# 珍宝匣(储藏箱里宝石 / 符文 / 材料三页合成的一页):格位几何 + 底图。
|
||||
# 底图不重画:角色页那块连续石面整块校色到高级仓库石面,石槽 / 合成格台座 / 石板横带 / 底带从原版三张高级仓库底图逐像素搬(石槽缩到 SCALE),外框是原版宝石页的边框。
|
||||
# 几何(slots)给布局用(wide_stash.py):物品码 → 槽控件在底图里的左上角与大小(像素,1 像素 = 2 布局单位)。原版按物品码认格位,换位置不换码。
|
||||
# 底图由 gen_widestash_art.py 调 build() 生成,顶替原版宝石页那张(构建产物,不进仓库)。
|
||||
# Trove (the gems / runes / materials pages of the stash merged into one page): slot geometry + background.
|
||||
# The background is not redrawn: the continuous stone face of the character page is color-matched as a whole to the advanced stash stone face; stone slots / crafting slot pedestal / stone slab band / bottom band are copied pixel by pixel from the three original advanced stash backgrounds (stone slots scaled to SCALE); the outer frame is the original gems page border.
|
||||
# The geometry (slots) is for the layout (wide_stash.py): item code → top-left and size of the slot widget in the background (pixels, 1 pixel = 2 layout units). The game identifies slots by item code; positions change, codes do not.
|
||||
# The background is generated by gen_widestash_art.py calling build() and replaces the original gems page image (a build product, not in the repo).
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw
|
||||
X0, X1 = 58, 594 # 原版高级仓库底图(652 宽)有内容的列范围,两侧是透明边 | column range with content in the original advanced stash background (652 wide); both sides are transparent margins
|
||||
W, H = 732, 649 # 珍宝匣底图:原内容 536 宽 + 196(与加宽后的个人页同宽,切页时外框不跳) | Trove background: original content width 536 + 196 (same width as the widened personal tab, so the frame does not jump when switching tabs)
|
||||
EXW = W - (X1 - X0); HALF = EXW // 2
|
||||
FR, FRR = 20, 26 # 外框厚:左 20、右 26(右框内沿多一道暗线) | outer frame thickness: left 20, right 26 (the right frame has an extra dark line on its inner edge)
|
||||
SCALE = 0.85 # 石槽与槽控件的缩放(原版槽芯 45 像素、槽控件 49 像素) | scale of stone slots and slot widgets (original slot core 45 px, slot widget 49 px)
|
||||
TOP = dict(dx=43, dy=43, y=28, gap=18) # 上排:宝石 7 列 + 石面间隔 + 符文 7 列,各 5 行 | top row: 7 gem columns + stone face gap + 7 rune columns, 5 rows each
|
||||
SHIFT = 36 # 合成格台座与底带中台比居中偏左多少:右边要放下材料的 5 列 | how far left of center the crafting slot pedestal and the bottom band's middle block sit: the right side must fit the 5 materials columns
|
||||
CONS = dict(dx=44, y=278) # 材料槽格距与第一行(双高格)上沿 | materials slot pitch and top edge of the first row (double-height cells)
|
||||
YM, YS, YB = 283, 462, 507 # 宝石页格子区下沿 / 材料页石板横带上沿 / 底带上沿 | bottom edge of the gems page grid area / top edge of the materials page stone slab band / top edge of the bottom band
|
||||
GEM_COLS = 'w g r y v b'.split(); GEM_ROWS = 'gc gf gs gl gp'.split() # 列 = 颜色,行 = 品级;下面两个例外码 | column = color, row = grade; two exception codes below
|
||||
GEM_ODD = {'glv': 'gzv'}; SKULL = 'skc skf sku skl skz'.split()
|
||||
MAT_L = ['pk1', 'pk2', 'pk3', 'dhn', 'bey', 'mbr', 'rvs', 'rvl'] # 左 3 列:双高 3 / 3 / 2 | left 3 columns: double-height 3 / 3 / 2
|
||||
MAT_R = ['ua1', 'ua2', 'ua3', 'ua4', 'ua5', 'xa1', 'xa2', 'xa3', 'xa4', 'xa5', 'toa', 'tes', 'ceh', 'bet', 'fed'] # 右 5 列:双高 5 / 5 / 5 | right 5 columns: double-height 5 / 5 / 5
|
||||
PED_X = 205 - X0 + HALF - SHIFT # 台座左沿(原版材料页台座 x 205–439) | left edge of the pedestal (original materials page pedestal x 205–439)
|
||||
|
||||
def geometry():
|
||||
"""返回 {物品码: (槽心 x, 槽心 y, 占几格高)},坐标是珍宝匣底图里的像素。 | Returns {item code: (slot center x, slot center y, height in cells)}, coordinates in pixels within the Trove background."""
|
||||
dm = 45 * SCALE; tw = 13 * TOP['dx'] + dm + TOP['gap']; x0 = FR + (W - FR - FRR - tw) / 2; g = {} # 在左右框之间居中(右框比左框厚 6) | centered between the left and right frames (the right frame is 6 thicker than the left)
|
||||
for r in range(5):
|
||||
for k in range(14):
|
||||
cx, cy = x0 + k * TOP['dx'] + dm / 2 + (TOP['gap'] if k >= 7 else 0), TOP['y'] + r * TOP['dy'] + dm / 2
|
||||
if k < 6: c = GEM_ROWS[r] + GEM_COLS[k]; g[GEM_ODD.get(c, c)] = (cx, cy, 1)
|
||||
elif k == 6: g[SKULL[r]] = (cx, cy, 1)
|
||||
elif r < 4: g['r%02d' % (r * 7 + k - 6)] = (cx, cy, 1)
|
||||
elif k - 7 < 5: g['r%02d' % (29 + k - 7)] = (cx + TOP['dx'], cy, 1) # 符文 33 个:前 4 行各 7,末行 5 个居中 | 33 runes: 7 in each of the first 4 rows, 5 centered in the last row
|
||||
def group(codes, counts, gx):
|
||||
i = 0
|
||||
for row, n in enumerate(counts):
|
||||
for k in range(n):
|
||||
cx = gx + k * CONS['dx'] + dm / 2
|
||||
cy = CONS['y'] + 95 * SCALE / 2 if row == 0 else CONS['y'] + 95 * SCALE + 6 + (row - 1) * CONS['dx'] + dm / 2
|
||||
g[codes[i]] = (cx, cy, 2 if row == 0 else 1); i += 1
|
||||
pl, pr = PED_X, PED_X + 234
|
||||
group(MAT_L, (3, 3, 2), FR + (pl - FR - (2 * CONS['dx'] + dm)) / 2); group(MAT_R, (5, 5, 5), pr + (W - FRR - pr - (4 * CONS['dx'] + dm)) / 2)
|
||||
return g
|
||||
|
||||
def slots():
|
||||
"""布局用:{物品码: (x, y, 宽, 高)},槽控件矩形,单位 = 布局单位,原点 = 原版 652 宽底图的左上角(原版槽控件 98 × 98 / 98 × 196)。 | For the layout: {item code: (x, y, width, height)}, slot widget rects, in layout units, origin = top-left of the original 652-wide background (original slot widgets are 98 × 98 / 98 × 196)."""
|
||||
out = {}
|
||||
for code, (cx, cy, hgt) in geometry().items():
|
||||
w = round(98 * SCALE); h = w if hgt == 1 else round(196 * SCALE); wp, hp = 49 * SCALE, 49 * SCALE * hgt
|
||||
out[code] = (round((cx - wp / 2 - (HALF - X0)) * 2), round((cy - hp / 2) * 2) + 102, w, h) # 珍宝匣底图贴在加宽画布的 x = X0,原版 652 图贴在 x = HALF:横坐标差 HALF − X0 | the Trove background is pasted at x = X0 on the widened canvas, the original 652 image at x = HALF: x offset HALF − X0
|
||||
return out
|
||||
|
||||
def _stats(im, boxes):
|
||||
a = np.concatenate([np.asarray(im.crop(b).convert('RGB'), dtype=np.float64).reshape(-1, 3) for b in boxes]); return a.mean(0), a.std(0)
|
||||
def _stone(csh, w, h, target, ox=90, oy=190):
|
||||
src = np.asarray(csh.crop((ox, oy, ox + w, oy + h)).convert('RGB'), dtype=np.float64); m, s = src.reshape(-1, 3).mean(0), src.reshape(-1, 3).std(0)
|
||||
return Image.fromarray(np.clip((src - m) / s * target[1] + target[0], 0, 255).astype(np.uint8)).convert('RGBA')
|
||||
def _feather(sz, n=2):
|
||||
w, h = sz; a = np.ones((h, w))
|
||||
for i in range(n): v = (i + 1) / (n + 1); a[i, :] = np.minimum(a[i, :], v); a[h - 1 - i, :] = np.minimum(a[h - 1 - i, :], v); a[:, i] = np.minimum(a[:, i], v); a[:, w - 1 - i] = np.minimum(a[:, w - 1 - i], v)
|
||||
return Image.fromarray((a * 255).astype(np.uint8))
|
||||
def _slot(src, x, y, w=45, h=45, pad=4): # 槽芯外 2 像素是边框线,再外 2 像素羽化进石面(边框线不参与羽化) | 2 px outside the slot core is the border line, 2 more px outside feather into the stone face (the border line is not feathered)
|
||||
t = src.crop((x - pad, y - pad, x + w + pad, y + h + pad)); return t.resize((round(t.width * SCALE), round(t.height * SCALE)), Image.LANCZOS)
|
||||
def _paste(dst, t, cx, cy): dst.paste(t, (round(cx - t.width / 2), round(cy - t.height / 2)), _feather(t.size))
|
||||
def _mirror_fill(dst, strip, x, y, w):
|
||||
k = 0; px = x
|
||||
while px < x + w:
|
||||
p = strip if k % 2 == 0 else strip.transpose(Image.FLIP_LEFT_RIGHT); p = p.crop((0, 0, min(p.width, x + w - px), p.height)); dst.paste(p, (px, y)); px += p.width; k += 1
|
||||
|
||||
def build(gems, runes, cons, csh):
|
||||
"""四张原版图(宝石页、符文页、材料页底图,角色页底图;RGBA)→ 珍宝匣底图(W × H,RGBA)。 | Four original images (gems page, runes page, materials page backgrounds, character page background; RGBA) → Trove background (W × H, RGBA)."""
|
||||
assert gems.size == runes.size == cons.size == (652, 649) and csh.size == (1369, 706), '原版底图尺寸不是原样(原版资源变了?)'
|
||||
out = Image.new('RGBA', (W, H)); g = gems.crop((X0, 0, X1, H)); c = cons.crop((X0, 0, X1, H)); gw = g.width
|
||||
tgt = _stats(gems, [(165, 31, 178, 276), (226, 31, 239, 276), (287, 31, 300, 276)]) # 目标石面:宝石页槽与槽之间的三条竖缝 | target stone face: the three vertical gaps between slots on the gems page
|
||||
out.paste(g.crop((0, 0, FR, H)), (0, 0)); out.paste(g.crop((gw - FRR, 0, gw, H)), (W - FRR, 0))
|
||||
st = _stone(csh, W - 2 * FR + 6, H, tgt); out.paste(st.crop((0, 0, st.width, YS - 14)), (FR - 3, 14))
|
||||
out.paste(g.crop((0, 0, FR - 3, YS)), (0, 0)); out.paste(g.crop((gw - FRR + 3, 0, gw, YS)), (W - FRR + 3, 0)); _mirror_fill(out, g.crop((FR, 0, gw - FRR, 15)), FR, 0, W - FR - FRR)
|
||||
# 下半照原版材料页:石板横带、底带各自「左块贴左框、右块贴右框、中块放在居中偏左 SHIFT」,中块两侧空出来的按各段材质补
|
||||
# The lower half follows the original materials page: for the stone slab band and the bottom band each, "left block against the left frame, right block against the right frame, middle block SHIFT left of center"; the gaps beside the middle block are filled with each segment's own texture
|
||||
def widen(y0, y1, xl, xr, mode):
|
||||
band = c.crop((0, y0, gw, y1)); h = y1 - y0; nx = xl + HALF - SHIFT; left, mid, right = band.crop((0, 0, xl, h)), band.crop((xl, 0, xr, h)), band.crop((xr, 0, gw, h))
|
||||
def fill(x, w, edge, flip):
|
||||
if w <= 0: return
|
||||
if mode == 'tile': # 细密刻纹的石板:取紧邻的一段原样接着铺(不镜像) | finely engraved stone slab: continue with an adjacent segment as is (not mirrored)
|
||||
src = edge.crop((edge.width - 70, 0, edge.width - 6, h)) if not flip else edge.crop((6, 0, 70, h)); blk = Image.new('RGBA', (w, h)); px = 0
|
||||
while px < w: blk.paste(src, (px if not flip else w - px - src.width, 0)); px += src.width
|
||||
else: # 暗石面:角色页石面校到底带最下面那条暗石(横贯全宽、没有花饰)的均值与起伏;金线那几行横向接过去 | dark stone face: the character page stone face matched to the mean and variation of the bottom band's lowest dark stone strip (full width, no ornament); the gold-line rows are continued across
|
||||
tg = _stats(band, [(30, h - 16, gw - 30, h - 4)]); blk = _stone(csh, w, h, tg, ox=300 + x, oy=420); col = np.asarray(edge.convert('RGB'))[:, -3 if not flip else 2].astype(int); d = ImageDraw.Draw(blk)
|
||||
for yy in range(h):
|
||||
r_, g_, b_ = col[yy]
|
||||
if r_ - b_ > 22 and r_ > 60: d.line([(0, yy), (w, yy)], fill=(int(r_), int(g_), int(b_), 255))
|
||||
out.paste(blk, (x, y0))
|
||||
fill(xl, nx - xl, left, False); fill(nx + (xr - xl), W - (gw - xr) - nx - (xr - xl), right, True)
|
||||
out.paste(left, (0, y0)); out.paste(mid, (nx, y0)); out.paste(right, (W - (gw - xr), y0))
|
||||
ped = cons.crop((205, 264, 439, YS + 3)); out.paste(ped, (PED_X, 264), _feather(ped.size, 1)) # 台座先贴,石板横带后贴盖住它的下沿(接缝落在横带自己的上边线上) | paste the pedestal first, then the stone slab band over its lower edge (the seam falls on the band's own top line)
|
||||
widen(YS, YB, 205 - X0, 439 - X0, 'tile'); widen(YB, H, 226 - X0, 421 - X0, 'dark')
|
||||
gs, rs, tall, one = _slot(gems, 117, 31), _slot(runes, 93, 51), _slot(cons, 87, 49, 45, 95), _slot(cons, 87, 154)
|
||||
for code, (cx, cy, hgt) in geometry().items():
|
||||
_paste(out, tall if hgt == 2 else gs if code[0] in 'gs' else rs if code[0] == 'r' and code[1:].isdigit() else one, cx, cy)
|
||||
return out
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
# 编年史页底部盖板贴图(不要大黑块,用原版底板那一段):从宽个人页底图 StashPanelBGPersonal_wide.sprite(gen_widestash_art.py 生成)
|
||||
# 裁格子下面整条(两边的环饰 + 中间的石面),存成同格式精灵图(构建时生成,不进仓库)。
|
||||
# 为什么整条:第六页没有自己的底图(背景图表不能加第 6 项,见 wide_stash.py),游戏照画上一页的底图——个人页、共享页(多一个页码框)、
|
||||
# 宝石 / 材料 / 符文页(魔盒凹槽)各不相同,再加上嵌入魔盒容器的「转化」「提取」两颗钮、原版的翻页箭头。整条盖住才和从哪页切来无关。
|
||||
# (去掉翻页按钮下面那个原版黑框,按钮下移放大居中):改用个人页那张(没有页码框),并把中间的金币框抹成石面——
|
||||
# 金币框左右两侧各有一段同一行的平石面,左半取左段的镜像、右半取右段的镜像(同行取样,明暗走向一致),正中 16 像素交叉淡入。
|
||||
# 翻页箭头和页码是我们自己的控件(wide_stash.py 的 TouchV_PgL / PgR / Page),画在盖板上面;原版箭头被盖板压住,不再挖洞。
|
||||
# 底图在面板里摆在 (-2, 100)、1 像素 = 2 布局单位(BankExpansionLayoutHD.json 的 background;宿主截图按金币框对位核过)。
|
||||
# 用法:gen_vault_cover.py(构建时在 gen_widestash_art.py 之后跑,产物 Gen/assets/NativeHUD/widestash/VaultBottom.sprite;wide_stash.py 只拷)
|
||||
# Texture for the bottom cover of the Chronicle page (no big black block; use that stretch of the original base panel): from the wide personal page base image StashPanelBGPersonal_wide.sprite (generated by gen_widestash_art.py)
|
||||
# crop the whole strip below the grid (the ring ornaments on both sides + the stone face in the middle) and save it as a sprite of the same format (generated at build time, not in the repository).
|
||||
# Why the whole strip: the sixth page has no base image of its own (a 6th entry cannot be added to the background image table, see wide_stash.py), so the game draws the previous page's base image -- the personal page, the shared pages (with an extra page number box), and
|
||||
# the gem / material / rune pages (Horadric Cube recess) all differ, and on top of that come the two buttons 「转化」(Transmute) and 「提取」(Withdraw) embedded in the Horadric Cube container and the original page arrows. Only covering the whole strip makes it independent of which page one switched from.
|
||||
# (Remove the original black box under the page buttons; move the buttons down, enlarge and center them): use the personal page's image instead (it has no page number box), and erase the gold box in the middle into stone face --
|
||||
# on each side of the gold box there is a stretch of flat stone in the same rows; the left half takes the mirror image of the left stretch and the right half the mirror image of the right stretch (sampled from the same rows, so the shading runs the same way), cross-faded over the center 16 pixels.
|
||||
# The page arrows and page number are our own widgets (TouchV_PgL / PgR / Page in wide_stash.py), drawn on top of the cover; the original arrows are covered by it, and holes are no longer cut.
|
||||
# The base image sits at (-2, 100) in the panel, 1 pixel = 2 layout units (background in BankExpansionLayoutHD.json; checked by aligning on the gold box in a host screenshot).
|
||||
# Usage: gen_vault_cover.py (run at build time after gen_widestash_art.py; output Gen/assets/NativeHUD/widestash/VaultBottom.sprite; wide_stash.py only copies it)
|
||||
import os, sys
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
|
||||
import gen_widestash_art as G
|
||||
|
||||
ART = __import__('gen_paths').gen_dir('NativeHUD', 'widestash')
|
||||
BG_X, BG_Y = -2, 100
|
||||
TOP = 516 # 底图像素行:格子下沿金线(第 508 行上下)以下、4 的倍数(DXT 块);wide_stash.py 的 TouchV_Cover 摆在 (BG_X, BG_Y + 2 * TOP) | Base image pixel row: below the gold line at the grid's lower edge (around row 508), a multiple of 4 (DXT blocks); wide_stash.py's TouchV_Cover is placed at (BG_X, BG_Y + 2 * TOP)
|
||||
BOX = (322, 576, 524, 644) # 金币框(含边框外一圈)在底图里的像素范围 x0, y0, x1, y1;两侧平石面各宽 101:x 221–322 与 524–625 | Pixel range x0, y0, x1, y1 of the gold box (including one ring outside its border) in the base image; the flat stone on each side is 101 wide: x 221–322 and 524–625
|
||||
|
||||
def main():
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
L = G.lib(); src = open(os.path.join(ART, 'StashPanelBGPersonal_wide.sprite'), 'rb').read(); im = G.decode(L, src)
|
||||
w, h = im.size; eh = h - TOP; eh += -eh % 4
|
||||
a = np.asarray(im).astype(np.float32).copy(); x0, y0, x1, y1 = BOX; mid = (x0 + x1) // 2; n = mid - x0
|
||||
# 抹掉之前先核:框里确实是金币框(中间暗、上沿有一条亮边),两侧是平石面——底图变了就退,不瞎抹
|
||||
# Check before erasing: the box really contains the gold box (dark in the middle, a bright edge along the top) and both sides are flat stone -- if the base image has changed, back out rather than erase blindly
|
||||
g = a[..., :3].sum(axis=2)
|
||||
if not (g[608, x0 + 20:x1 - 20].mean() < 75 and g[608, x0 - 60:x0 - 10].mean() > 85): raise SystemExit('gen_vault_cover:个人页底图里金币框不在预期位置(原版资源变了?)')
|
||||
left = a[y0:y1, x0 - n:x0][:, ::-1]; right = a[y0:y1, x1:x1 + (x1 - mid)][:, ::-1]
|
||||
a[y0:y1, x0:mid] = left; a[y0:y1, mid:x1] = right
|
||||
for k in range(16): # 正中接缝:左右两段各自延伸过中线 8 像素再交叉淡入 | Center seam: the left and right segments each extend 8 pixels past the center line and are then cross-faded
|
||||
t = (k + .5) / 16; xl = mid - 8 + k; a[y0:y1, xl] = (1 - t) * a[y0:y1, x0 - 1 - (xl - x0)] + t * a[y0:y1, x1 + (x1 - 1 - xl)]
|
||||
im = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8), 'RGBA')
|
||||
crop = im.crop((0, TOP, w, TOP + eh)) # 超出底图的几行是透明的 | The rows beyond the base image are transparent
|
||||
open(os.path.join(ART, 'VaultBottom.sprite'), 'wb').write(G.pack(L, src, G.bc3(crop), w, eh, w)); crop.save(os.path.join(ART, 'VaultBottom.png'))
|
||||
print('VaultBottom:底图第 %d–%d 行,%d×%d,面板单位 (%d,%d)' % (TOP, TOP + eh, w, eh, BG_X, BG_Y + 2 * TOP))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
# 编年史仓库(第 3 步)的固定表:哪些暗金 / 套装件有格子、各在哪个部位、档次、物品图路径、套装分组与次序。
|
||||
# 用法:gen_vault_table.py <原版 RomFS(Update)> [<Base RomFS>] > dm/host/dm_vault_tab.h(构建时由 dm/host/Makefile 生成,不进仓库;游戏版本换了产物有变就要复核部位件数)
|
||||
# 来源全是游戏自己的表:excel/UniqueItems.txt、SetItems.txt、Sets.txt、armor / weapons / misc.txt、ItemTypes.txt;hd/items/uniques.json、sets.json、items.json(物品图 asset)。
|
||||
# 收哪些:玩家可能拿到的都给一格——disabled 空、spawnable 不是 0、有底子。比原版编年史多收它不收的(disableChronicle:碎裂护身符、巨型珠宝、督军的荣耀等,
|
||||
# 都能掉 / 能做出来),否则这些存不进来(页面结构原按编年史算 403 + 140)。
|
||||
# 名字不在这里:宿主运行时按 index 列(字符串键)走游戏的取本地化串 main+0x7f5630。
|
||||
# Fixed table for the chronicle vault (step 3): which unique / set pieces have a cell, which slot each is in, tier, item image path, set grouping and order.
|
||||
# Usage: gen_vault_table.py <original game RomFS (Update)> [<Base RomFS>] > dm/host/dm_vault_tab.h (generated at build time by dm/host/Makefile, not committed to the repo; if the game version changes and the build output differs, the per-slot piece counts must be rechecked)
|
||||
# Sources are all the game's own tables: excel/UniqueItems.txt, SetItems.txt, Sets.txt, armor / weapons / misc.txt, ItemTypes.txt; hd/items/uniques.json, sets.json, items.json (item image asset).
|
||||
# What is included: everything a player might obtain gets a cell -- disabled empty, spawnable not 0, has a base item. It includes more than the original game's chronicle, taking what that one leaves out (disableChronicle: Sunder Charms, Colossal Jewels, Warlord's Glory, etc.,
|
||||
# all of which can drop / can be crafted), otherwise these could not be stored (the page structure was originally computed from the chronicle's 403 + 140).
|
||||
# Names are not here: at runtime the host goes by the index column (string key) through the game's localized-string lookup main+0x7f5630.
|
||||
import json, os, re, sys
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'tools'))
|
||||
import dmx
|
||||
|
||||
PARTS = ['头盔', '盔甲', '盾牌与手套', '鞋子与腰带', '首饰', '剑与匕首', '斧与爪', '锤与棍', '长柄与矛', '弓弩', '法杖与法器']
|
||||
# 部位按底子的物品类型往上找(ItemTypes Equiv1 / Equiv2)第一个命中的类型码;顺序 = 判定优先级
|
||||
# 死灵头(head,原版归盾)按设计放头盔页;术士法典(grim,原版归盾)放法杖与法器页;权杖(scep,原版归法杖类 rod)放锤与棍页
|
||||
# The slot is found by walking up from the base item's item type (ItemTypes Equiv1 / Equiv2) to the first matching type code; order = decision priority
|
||||
# Necromancer heads (head, classed as shields in the original game) go on the helm page per the design; warlock grimoires (grim, classed as shields in the original game) go on the staves and implements page; scepters (scep, classed under the staff-like rod in the original game) go on the hammers and clubs page
|
||||
PART_OF = [('helm', 0), ('head', 0), ('tors', 1), ('grim', 10), ('shld', 2), ('glov', 2), ('boot', 3), ('belt', 3),
|
||||
('ring', 4), ('amul', 4), ('jewl', 4), ('char', 4), ('swor', 5), ('knif', 5), ('axe', 6), ('h2h', 6), ('scep', 7), ('staf', 10), ('wand', 10), ('orb', 10), ('blun', 7),
|
||||
('pole', 8), ('spea', 8), ('jave', 8), ('miss', 9)]
|
||||
|
||||
def txt(name):
|
||||
raw = dmx.get('data/global/excel/%s.txt' % name).decode('utf-8', 'replace').splitlines()
|
||||
head = raw[0].split('\t'); return [dict(zip(head, l.split('\t'))) for l in raw[1:] if l.strip()]
|
||||
def js(name):
|
||||
out = {}
|
||||
for d in json.loads(dmx.get('data/hd/items/%s.json' % name).decode('utf-8')):
|
||||
for k, v in d.items(): out[k] = v
|
||||
return out
|
||||
|
||||
def main():
|
||||
dmx.ROOT = os.path.join(sys.argv[1], 'data')
|
||||
sprites = set()
|
||||
for root in sys.argv[1:]:
|
||||
for line in open(os.path.join(root, 'data', 'build_manifest.psv'), encoding='utf-8'):
|
||||
p = line.split('|')[9].lower() if line.count('|') >= 10 else ''
|
||||
m = re.match(r'data:data/hd/global/ui/(items/.*)\.sprite$', p)
|
||||
if m: sprites.add(m.group(1))
|
||||
types = {r['Code']: (r['Equiv1'], r['Equiv2']) for r in txt('ItemTypes') if r.get('Code')}
|
||||
base = {} # 码 → (类别目录, 类型, 档次, 物品等级) | Code → (category directory, type, tier, item level)
|
||||
for cat, f in (('armor', 'armor'), ('weapon', 'weapons'), ('misc', 'misc')):
|
||||
for r in txt(f):
|
||||
c = r.get('code', '')
|
||||
if not c: continue
|
||||
tier = 2 if c == r.get('ultracode') else 1 if c == r.get('ubercode') else 0
|
||||
base[c] = (cat, r.get('type', ''), tier, int(r.get('level') or 0))
|
||||
def part(code):
|
||||
seen, todo = set(), [base[code][1]]
|
||||
while todo:
|
||||
t = todo.pop(0)
|
||||
if not t or t in seen: continue
|
||||
seen.add(t); todo += list(types.get(t, ('', '')))
|
||||
for t, p in PART_OF:
|
||||
if t in seen: return p
|
||||
raise SystemExit('gen_vault_table:底子 %s 的类型 %s 归不进任何部位' % (code, base[code][1]))
|
||||
uj, sj, ij = js('uniques'), js('sets'), js('items')
|
||||
def icon(key, code, j):
|
||||
cat = base[code][0]
|
||||
for a in ((j.get(re.sub(r'[^a-z0-9]+', '_', key.lower().replace("'", '')).strip('_')) or {}).get('normal'), (ij.get(code) or {}).get('asset')):
|
||||
if a and 'items/%s/%s' % (cat, a.lower()) in sprites: return 'Items/%s/%s' % (cat, a)
|
||||
raise SystemExit('gen_vault_table:%s(%s)找不到物品图' % (key, code))
|
||||
ok = lambda r: r.get('spawnable') != '0' and not r.get('disabled')
|
||||
rows = []
|
||||
for r in txt('UniqueItems'):
|
||||
c = r.get('code', '')
|
||||
if not ok(r) or c not in base: continue
|
||||
rows.append((1, part(c), base[c][2], int(r['*ID']), int(r.get('lvl') or 0), r['index'], icon(r['index'], c, uj), -1))
|
||||
sets = [r['index'] for r in txt('Sets') if r.get('index')]
|
||||
for r in txt('SetItems'):
|
||||
c = r.get('item', '')
|
||||
if not ok(r) or c not in base or r['set'] not in sets: continue
|
||||
rows.append((0, part(c), base[c][2], int(r['*ID']), int(r.get('lvl') or 0), r['index'], icon(r['index'], c, sj), sets.index(r['set'])))
|
||||
# 暗金:部位 → 档次 → 物品等级 → 行号(设计「页内排序:普通 → 扩展 → 精英,同档按物品等级」);套装:按 Sets.txt 次序,套内按 SetItems 行号
|
||||
# Uniques: slot → tier → item level → row number (design: "in-page order: normal → exceptional → elite, same tier by item level"); sets: in Sets.txt order, within a set by SetItems row number
|
||||
rows.sort(key=lambda t: (t[0], t[1], t[2], t[4], t[3]) if t[0] == 1 else (t[0], t[7], t[3]))
|
||||
used = [s for i, s in enumerate(sets) if any(t[0] == 0 and t[7] == i for t in rows)]
|
||||
q = lambda s: '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
|
||||
print('// 生成文件,勿手改:dm/ios/tools/gen_vault_table.py <原版 RomFS>(编年史仓库固定表,见该脚本头注释)')
|
||||
print('// 部位:' + '、'.join('%d %s %d 件' % (i, p, sum(1 for t in rows if t[0] == 1 and t[1] == i)) for i, p in enumerate(PARTS)))
|
||||
print('// 暗金 %d 件、套装 %d 套 %d 件' % (sum(1 for t in rows if t[0] == 1), len(used), sum(1 for t in rows if t[0] == 0)))
|
||||
print('#define VT_NPART %d' % len(PARTS))
|
||||
print('static const char *const vt_part_name[VT_NPART] = { %s };' % ', '.join(q(p) for p in PARTS))
|
||||
print('typedef struct { uint8_t kind, part, tier; uint16_t row, lvl; int16_t set; const char *key, *icon; } vt_row; // kind 1 暗金 / 0 套装件;row = 表行号(物品数据 +0x34);set = 套装序号(暗金 −1)')
|
||||
print('static const vt_row vt_rows[] = {')
|
||||
for t in rows:
|
||||
set_ix = used.index(sets[t[7]]) if t[0] == 0 else -1
|
||||
print(' { %d, %d, %d, %d, %d, %d, %s, %s },' % (t[0], t[1], t[2], t[3], t[4], set_ix, q(t[5]), q(t[6])))
|
||||
print('};')
|
||||
print('#define VT_NROW (int)(sizeof vt_rows / sizeof vt_rows[0])')
|
||||
print('static const char *const vt_set_key[] = { %s }; // 套装名的字符串键(Sets.txt index),次序 = 原版' % ', '.join(q(s) for s in used))
|
||||
print('#define VT_NSET (int)(sizeof vt_set_key / sizeof vt_set_key[0])')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
# 储藏箱加宽用的贴图(构建时从玩家的游戏文件生成到 Gen/assets/NativeHUD/widestash,不进仓库;wide_stash.py 只拷)。用法:gen_widestash_art.py <原版 RomFS>
|
||||
# 全部做成原包同款 SpA1 v61 = DXT5 + 块线性。不用原始 RGBA(v31):1640×881 的 v31 游戏读出来有成排花点、切两张后大片花屏
|
||||
# (本机宿主实测;选角页 401×1080 同类问题),而且显存是 DXT5 的 4 倍。
|
||||
# ① 宽外框 MainPanelBG_Wide:取原包外框(两帧横排,第 1 帧 = 双面板)第 1 帧,在左半标题框中间(帧内 x 348,4 像素对齐)
|
||||
# 把 152..348 这 196 像素的压缩块再拼一份 = 左半宽 196 像素(392 布局单位)。只搬原图压缩块,不重新编码。
|
||||
# ② 储藏箱底图(个人 / 共享 / 通用):解原图 → 格子区插 4 列、下段两侧花饰之间那整块右移 2 列居中、空出的两段补石纹 → 重新编码;
|
||||
# 宝石 / 材料 / 符文三页:原图两侧本就透明,左右各补 98 像素透明。编码按块取主轴两端为端点:原图本来就是 DXT5,块对齐处基本还原。
|
||||
# Textures for stash widening (generated at build time from the player's game files into Gen/assets/NativeHUD/widestash, not committed to the repo; wide_stash.py only copies). Usage: gen_widestash_art.py <original game RomFS>
|
||||
# All made in the original package's SpA1 v61 format = DXT5 + block-linear. Raw RGBA (v31) is not used: a 1640×881 v31 is read by the game with rows of garbage dots, and with large areas of garbage after splitting into two images
|
||||
# (measured on the local host; same kind of problem as the 401×1080 character select page), and it takes 4 times the video memory of DXT5.
|
||||
# ① Wide outer frame MainPanelBG_Wide: take frame 1 of the original package's outer frame (two frames side by side, frame 1 = dual panel), and in the middle of the left half's title box (x 348 within the frame, 4-pixel aligned)
|
||||
# splice in one more copy of the compressed blocks of the 196 pixels 152..348 = left half 196 pixels wider (392 layout units). Only the original compressed blocks are moved, no re-encoding.
|
||||
# ② Stash base images (personal / shared / generic): decode the original → insert 4 columns in the grid area, shift the whole block between the two side ornaments in the lower section right 2 columns to center it, fill the two vacated segments with stone texture → re-encode;
|
||||
# the gem / material / rune pages: the original images are already transparent on both sides, so 98 transparent pixels are added on each side. Encoding takes the two ends of each block's principal axis as endpoints: the originals are already DXT5, so block-aligned areas are essentially restored.
|
||||
import ctypes as C, io, os, struct, subprocess, sys, tempfile
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); DM = os.path.join(HERE, '..', '..'); ART = __import__('gen_paths').gen_dir('NativeHUD', 'widestash')
|
||||
sys.path.insert(0, HERE); import touch_layout
|
||||
X0, EX = 348, 196 # 宽外框插入点与插入宽度(像素,都是 4 的倍数) | Wide outer frame insertion point and insertion width (pixels, both multiples of 4)
|
||||
BG = {'StashPanelBG': 'stash/v2/stashpanelbg', 'StashPanelBGPersonal': 'stash/v2/stashpanelbgpersonal', 'StashPanelBGShared': 'stash/v2/stashpanelbgshared'}
|
||||
ADV = {'AdvancedStash_Gems_Console': 'stash/v2/additionalstash/advancedstash_gems_console',
|
||||
'AdvancedStash_Consumables_Console': 'stash/v2/additionalstash/advancedstash_consumables_console',
|
||||
'AdvancedStash_Runes_Console': 'stash/v2/additionalstash/advancedstash_runes_console'}
|
||||
# 底图加宽参数(像素,按原图列亮度 / 目测量):cut = 格子区插列处;yb = 格子区下沿(下段起点);mid = 两侧花饰之间那整块(金币框,共享页另有翻页底板)的左右边
|
||||
# Base image widening parameters (pixels, measured from the original image's column brightness / by eye): cut = column insertion point in the grid area; yb = lower edge of the grid area (start of the lower section); mid = left and right edges of the whole block between the two side ornaments (gold box; the shared page also has a page-turn base plate)
|
||||
SPEC = {'StashPanelBG': dict(cut=133, yb=525, mid=(214, 438)), 'StashPanelBGPersonal': dict(cut=129, yb=515, mid=(216, 428)), 'StashPanelBGShared': dict(cut=129, yb=515, mid=(216, 428))}
|
||||
|
||||
class Desc(C.Structure): _fields_ = [('target', C.c_int), ('format', C.c_int), ('flags', C.c_int), ('samples', C.c_int), ('width', C.c_uint32), ('height', C.c_uint32),
|
||||
('depth', C.c_uint32), ('levels', C.c_uint32), ('stride', C.c_uint32), ('pkg_block_h', C.c_int)]
|
||||
class Layout(C.Structure): _fields_ = [('size', C.c_uint64), ('layer_size', C.c_uint64), ('align', C.c_uint32), ('layers', C.c_uint32), ('bpb', C.c_uint32), ('tileH', C.c_uint), ('tileD', C.c_uint)]
|
||||
|
||||
def lib():
|
||||
t = tempfile.mkdtemp(); p = os.path.join(t, 'bl.dll' if os.name == 'nt' else 'bl.dylib')
|
||||
win = ['-Wl,/EXPORT:nvn_tex_layout', '-Wl,/EXPORT:nvn_deswizzle', '-Wl,/EXPORT:nvn_swizzle'] if os.name == 'nt' else ['-fPIC'] # 同 romfs_art.py | same as romfs_art.py
|
||||
subprocess.run(['clang', '-O2', '-shared', *win, '-I' + os.path.join(DM, 'gfx', 'nvn'), '-I' + os.path.join(DM, 'gfx', 'tex'), '-o', p,
|
||||
os.path.join(DM, 'gfx', 'tex', 'nvn_deswizzle.c'), os.path.join(DM, 'gfx', 'nvn', 'nvn_tex.c')], check=True)
|
||||
L = C.CDLL(p); L.nvn_tex_layout.argtypes = [C.POINTER(Desc), C.POINTER(Layout)]
|
||||
L.nvn_deswizzle.argtypes = [C.POINTER(Desc), C.c_uint, C.c_uint, C.c_void_p, C.c_void_p, C.c_size_t]
|
||||
L.nvn_swizzle.argtypes = [C.POINTER(Desc), C.c_uint, C.c_uint, C.c_void_p, C.c_size_t, C.c_void_p]
|
||||
return L
|
||||
|
||||
def orig(romfs, rel):
|
||||
for line in open(os.path.join(romfs, 'data', 'build_manifest.psv'), encoding='utf-8'):
|
||||
f = line.rstrip('\n').split('|')
|
||||
if len(f) >= 11 and f[9].lower().endswith('/ui/controller/panel/' + rel + '.sprite'): return touch_layout._read_entry(romfs, f)
|
||||
raise SystemExit('gen_widestash_art:包里没有 ' + rel)
|
||||
|
||||
def desc(b, w, h): return Desc(1, 0x44, 0, 0, w, h, 1, 1, 0, b[23] + 1) # 0x44 = DXT5;块高参数取原图头第 23 字节(同解码处) | 0x44 = DXT5; the block height parameter is taken from byte 23 of the original image's header (same as at the decode site)
|
||||
|
||||
def pack(L, hdr0, lin, w, h, fw, frames=1):
|
||||
"""线性 DXT5 块 → 块线性,套原图头(改显示宽、宽、帧数、数据字节数)。 | Linear DXT5 blocks → block-linear, with the original image's header attached (display width, width, frame count, data byte count changed)."""
|
||||
d = desc(hdr0, w, h); lay = Layout(); L.nvn_tex_layout(C.byref(d), C.byref(lay)); dst = C.create_string_buffer(lay.size); src = C.create_string_buffer(lin, len(lin))
|
||||
assert L.nvn_swizzle(C.byref(d), 0, 0, src, (w + 3) // 4 * 16, dst) == 0
|
||||
hdr = bytearray(hdr0[:40]); struct.pack_into('<HI', hdr, 6, fw, w); struct.pack_into('<I', hdr, 12, h); struct.pack_into('<H', hdr, 20, frames); struct.pack_into('<I', hdr, 0x20, lay.size)
|
||||
return bytes(hdr) + dst.raw
|
||||
|
||||
def bc3(img):
|
||||
"""RGBA → 线性 DXT5 块(行优先)。颜色:块内像素投到主轴上取两端;透明度:最大 / 最小 8 级。 | RGBA → linear DXT5 blocks (row-major). Color: pixels in the block are projected onto the principal axis and the two ends taken; alpha: max / min, 8 levels."""
|
||||
a = np.asarray(img.convert('RGBA'), dtype=np.float64); h, w = a.shape[:2]; H, W = (h + 3) // 4 * 4, (w + 3) // 4 * 4
|
||||
p = np.zeros((H, W, 4)); p[:h, :w] = a; p[h:, :] = p[h - 1:h, :] if h < H else 0; p[:, w:] = p[:, w - 1:w] if w < W else 0
|
||||
blk = p.reshape(H // 4, 4, W // 4, 4, 4).transpose(0, 2, 1, 3, 4).reshape(-1, 16, 4); rgb, al = blk[:, :, :3], blk[:, :, 3]
|
||||
mu = rgb.mean(1, keepdims=True); c = rgb - mu; cov = np.einsum('npi,npj->nij', c, c); v = np.ones((len(blk), 3))
|
||||
for _ in range(8): v = np.einsum('nij,nj->ni', cov, v); v /= np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-9)
|
||||
t = np.einsum('npi,ni->np', c, v); e0 = rgb[np.arange(len(blk)), t.argmax(1)]; e1 = rgb[np.arange(len(blk)), t.argmin(1)]
|
||||
def q565(e): r, g, b_ = (np.round(e[:, 0] * 31 / 255).astype(int), np.round(e[:, 1] * 63 / 255).astype(int), np.round(e[:, 2] * 31 / 255).astype(int)); return r << 11 | g << 5 | b_
|
||||
def un565(c_): return np.stack([(c_ >> 11 & 31) * 255 / 31, (c_ >> 5 & 63) * 255 / 63, (c_ & 31) * 255 / 31], 1)
|
||||
c0, c1 = q565(e0), q565(e1); dm = c0 < c1; c0, c1 = np.where(dm, c1, c0), np.where(dm, c0, c1)
|
||||
p0, p1 = un565(c0), un565(c1); pal = np.stack([p0, p1, (2 * p0 + p1) / 3, (p0 + 2 * p1) / 3], 1)
|
||||
ci = ((rgb[:, :, None, :] - pal[:, None, :, :]) ** 2).sum(-1).argmin(2); ci[c0 == c1] = 0
|
||||
a0, a1 = al.max(1).round().astype(int), al.min(1).round().astype(int)
|
||||
ap = np.stack([a0, a1] + [((7 - k) * a0 + k * a1) / 7 for k in range(1, 7)], 1); ai = np.abs(al[:, :, None] - ap[:, None, :]).argmin(2); ai[a0 == a1] = 0
|
||||
out = bytearray()
|
||||
for n in range(len(blk)):
|
||||
ab = sum(int(ai[n, k]) << (3 * k) for k in range(16)); cb = sum(int(ci[n, k]) << (2 * k) for k in range(16))
|
||||
out += struct.pack('<BB', a0[n], a1[n]) + ab.to_bytes(6, 'little') + struct.pack('<HHI', c0[n], c1[n], cb)
|
||||
return bytes(out)
|
||||
|
||||
def decode(L, b):
|
||||
"""原包 v61 精灵图 → RGBA(解块线性后套 DDS 头交给 PIL 解 DXT5)。 | Original package v61 sprite → RGBA (after un-block-linearizing, a DDS header is attached and PIL decodes the DXT5)."""
|
||||
w, h = struct.unpack_from('<II', b, 8); d = desc(b, w, h); pitch = (w + 3) // 4 * 16; lin = C.create_string_buffer(pitch * ((h + 3) // 4)); src = C.create_string_buffer(b[40:], len(b) - 40)
|
||||
assert L.nvn_deswizzle(C.byref(d), 0, 0, src, lin, pitch) == 0
|
||||
hdr = [124, 0x81007, h, w, len(lin), 0, 1] + [0] * 11 + [32, 4, struct.unpack('<I', b'DXT5')[0], 0, 0, 0, 0, 0] + [0x1000, 0, 0, 0, 0]
|
||||
return Image.open(io.BytesIO(b'DDS ' + struct.pack('<31I', *hdr) + lin.raw)).convert('RGBA')
|
||||
|
||||
def widen_bg(im, stone_src, cut, yb, mid):
|
||||
w, h = im.size; out = Image.new('RGBA', (w + EX, h)); L_, R_ = mid; H = EX // 2
|
||||
top = im.crop((0, 0, w, yb)); out.paste(top.crop((0, 0, cut + EX, yb)), (0, 0)); out.paste(top.crop((cut, 0, w, yb)), (cut + EX, 0)) # 格子区:插进 4 列(复制左边 4 列格子) | Grid area: insert 4 columns (duplicating the left 4 columns of cells)
|
||||
B = im.crop((0, yb, w, h)); bh = h - yb
|
||||
out.paste(B.crop((0, 0, L_, bh)), (0, yb)); out.paste(B.crop((R_, 0, w, bh)), (R_ + EX, yb)); out.paste(B.crop((L_, 0, R_, bh)), (L_ + H, yb)) # 左花饰不动、右花饰右移 4 列、中间整块右移 2 列 | Left ornament unchanged, right ornament shifted right 4 columns, the whole middle block shifted right 2 columns
|
||||
col = Image.new('RGBA', (H, bh)); y = 0; k = 0
|
||||
while y < bh: p = stone_src if k % 2 == 0 else stone_src.transpose(Image.FLIP_TOP_BOTTOM); col.paste(p, (0, y)); y += p.height; k += 1 # 上下交替翻转铺,接缝处镜像连续 | Tiled with alternating vertical flips, mirror-continuous at the seams
|
||||
out.paste(col, (L_, yb)); out.paste(col, (R_ + H, yb)); return out
|
||||
|
||||
def main(romfs):
|
||||
L = lib()
|
||||
b = orig(romfs, 'mainpanelbg'); ver, fw, w, h = struct.unpack_from('<HHII', b, 4)
|
||||
assert b[:4] == b'SpA1' and ver == 61 and (fw, w, h, struct.unpack_from('<H', b, 20)[0]) == (1440, 2888, 881, 2)
|
||||
d = desc(b, w, h); bw, bh = w // 4, (h + 3) // 4; lin = C.create_string_buffer(bw * 16 * bh); src = C.create_string_buffer(b[40:], len(b) - 40)
|
||||
assert L.nvn_deswizzle(C.byref(d), 0, 0, src, lin, bw * 16) == 0
|
||||
f1 = w // 2 // 4; rows = []
|
||||
for y in range(bh):
|
||||
fr = lin.raw[y * bw * 16:(y + 1) * bw * 16][f1 * 16:]
|
||||
rows.append(fr[:X0 // 4 * 16] + fr[(X0 - EX) // 4 * 16:X0 // 4 * 16] + fr[X0 // 4 * 16:])
|
||||
W = w // 2 + EX; o = pack(L, b, b''.join(rows), W, h, fw + EX) # 显示宽 = 原帧显示宽 + 插入宽 | Display width = original frame display width + inserted width
|
||||
open(os.path.join(ART, 'MainPanelBG_Wide.sprite'), 'wb').write(o); print('MainPanelBG_Wide:%d×%d,%d 字节' % (W, h, len(o)))
|
||||
imgs = {n: decode(L, orig(romfs, rel)) for n, rel in {**BG, **ADV}.items()}
|
||||
stone = imgs['StashPanelBGPersonal'].crop((248, 515 + 18, 248 + EX // 2, 515 + 62)) # 补空用的石纹:个人页金币框正上方第 18–62 行(避开格子区下沿暗线与金币框) | Stone texture used for filling gaps: rows 18–62 directly above the personal page's gold box (avoiding the dark line at the grid area's lower edge and the gold box)
|
||||
for n, rel in {**BG, **ADV}.items():
|
||||
b = orig(romfs, rel); assert struct.unpack_from('<HHII', b, 4)[:3] == (61, 652, 652), n # 原图都是 652 宽 | The original images are all 652 wide
|
||||
if n in BG: im = widen_bg(imgs[n], stone, **SPEC[n])
|
||||
elif n == 'AdvancedStash_Gems_Console': # 宝石页这张顶替成珍宝匣底图(宝石 / 符文 / 材料三页合一,gen_trove_art.py):内容 732 宽,两侧各留原版那 58 像素透明边 | the gems page image is replaced by the Trove background (gems / runes / materials merged into one page, gen_trove_art.py): content 732 wide, keeping the original 58 px transparent margin on each side
|
||||
import gen_trove_art as T
|
||||
im = Image.new('RGBA', (652 + EX, imgs[n].height)); im.paste(T.build(imgs['AdvancedStash_Gems_Console'], imgs['AdvancedStash_Runes_Console'], imgs['AdvancedStash_Consumables_Console'], decode(L, orig(romfs, 'charactersheet/v2/charactersheet_bg'))), (T.X0, 0))
|
||||
else: im = Image.new('RGBA', (652 + EX, imgs[n].height)); im.paste(imgs[n], (EX // 2, 0))
|
||||
ww, hh = im.size; o = pack(L, b, bc3(im), ww, hh, ww); open(os.path.join(ART, n + '_wide.sprite'), 'wb').write(o); print('%s:%d×%d,%d 字节' % (n, ww, hh, len(o)))
|
||||
|
||||
if __name__ == '__main__': main(sys.argv[1])
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
# 真机选角页 GPU 读数:第一局全屏逐帧 @gpu_ms(DM_NVN_TSV)取第 600–700 帧均值 / p95;第二局 16:9 串行化逐通道(DM_NVN_PASSGPU + DM_NVN_PASSGPU_SERIAL=1),供按通道号对照。
|
||||
# 用法:DM_OUT=<产物> dm/ios/tools/gpu_read.sh 产物:$DM_ROOT/run/ios/gpu/(frames_full.tsv、passgpu_serial_16x9.tsv、日志)
|
||||
# Real device character select page GPU readings: run 1, full-screen per-frame @gpu_ms (DM_NVN_TSV), mean / p95 over frames 600–700; run 2, 16:9 serialized per-pass (DM_NVN_PASSGPU + DM_NVN_PASSGPU_SERIAL=1), for cross-reference by pass number.
|
||||
# Usage: DM_OUT=<build output> dm/ios/tools/gpu_read.sh Output: $DM_ROOT/run/ios/gpu/ (frames_full.tsv, passgpu_serial_16x9.tsv, logs)
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
source tools/local_env.sh && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}; R=${DM_ROOT:-$HOME/dm-work}/run/ios/gpu; RUN=$(date +%H%M%S); mkdir -p $R
|
||||
./run.sh build > $R/build.log 2>&1 || { echo "🔴 构建失败"; tail -5 $R/build.log; exit 1; }
|
||||
./run.sh install >> $R/build.log 2>&1 || { echo "🔴 装机失败"; tail -5 $R/build.log; exit 1; }
|
||||
pull(){ xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source "Documents/$1" --destination "$R/$2" > /dev/null 2>&1 || echo "🔴 拉 $1 失败"; }
|
||||
DEVICECTL_CHILD_DM_SAVE_FRESH=1 DEVICECTL_CHILD_DM_NVN_TSV=frames_$RUN.tsv DEVICECTL_CHILD_DM_WATCH=20 ./run.sh boot 60 > $R/full.run 2>&1
|
||||
pull frames_$RUN.tsv frames_full.tsv; cp ${DM_ROOT:-$HOME/dm-work}/run/ios/out/boot.txt $R/full.log
|
||||
DEVICECTL_CHILD_DM_SAVE_FRESH=1 DEVICECTL_CHILD_DM_GAME_RES=1600x900 DEVICECTL_CHILD_DM_NVN_PASSGPU=passgpu_$RUN.tsv DEVICECTL_CHILD_DM_NVN_PASSGPU_SERIAL=1 DEVICECTL_CHILD_DM_WATCH=20 ./run.sh boot 60 > $R/serial.run 2>&1
|
||||
pull passgpu_$RUN.tsv passgpu_serial_16x9.tsv; cp ${DM_ROOT:-$HOME/dm-work}/run/ios/out/boot.txt $R/serial.log
|
||||
python3 - $R <<'PY'
|
||||
import sys
|
||||
R = sys.argv[1]
|
||||
g = sorted(float(l.split('\t')[2]) for l in open(f'{R}/frames_full.tsv') if '\t@gpu_ms\t' in l and 600 <= int(l.split('\t')[0]) <= 700)
|
||||
print(f'全屏 第 600–700 帧 GPU:{len(g)} 帧,均值 {sum(g) / len(g):.2f} ms,p95 {g[int(len(g) * 0.95)]:.2f} ms' if g else '🔴 没有 @gpu_ms 行')
|
||||
PY
|
||||
grep -h "【红】" $R/full.log $R/serial.log | grep -v 贴图号 | sort -u | head -5
|
||||
wc -l < $R/passgpu_serial_16x9.tsv
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
# 发热归因 A / B(各 N 秒,缺省 300):B = -mode blank(最小 Metal 60 帧清屏中灰,屏幕与显示链本身);A = 我们的 App 停在选角页(boot,标准存档)。
|
||||
# 每 10 秒一行 DM_HEAT(温控、CPU%、出图帧率、GPU 毫秒均值 / p95、亮度、最高刷新)+ DM_THRCPU 按线程 CPU;A 另开 DM_NVN_TSV 逐帧计时。用法:dm/ios/tools/heat_ab.sh [秒=300](先 run.sh build,再 run.sh install)
|
||||
# Heat attribution A / B (N seconds each, default 300): B = -mode blank (minimal Metal clearing the screen to mid-gray at 60 fps: the screen and the display chain themselves); A = our App sitting on the character select page (boot, standard save).
|
||||
# One DM_HEAT line every 10 seconds (thermal state, CPU%, output frame rate, GPU ms mean / p95, brightness, max refresh rate) + DM_THRCPU per-thread CPU; A additionally enables DM_NVN_TSV per-frame timing. Usage: dm/ios/tools/heat_ab.sh [seconds=300] (first run.sh build, then run.sh install)
|
||||
set -u
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/local_env.sh" && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
S=${1:-300}; D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}; R=${DM_ROOT:-$HOME/dm-work}/run/ios/heat; RUN=$(date +%H%M%S); mkdir -p $R
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
pid(){ xcrun devicectl device info processes --device $D 2>/dev/null | grep "DmIOS.app/DmIOS" | awk '{print $1}'; }
|
||||
for g in B A; do
|
||||
m=boot; [ $g = B ] && m=blank
|
||||
DEVICECTL_CHILD_DM_HEAT="heat_${g}_$RUN.tsv,10" DEVICECTL_CHILD_DM_THRCPU="thr_${g}_$RUN.tsv,10" DEVICECTL_CHILD_DM_NVN_TSV="frames_${g}_$RUN.tsv" DEVICECTL_CHILD_DM_SAVE_FRESH=1 DEVICECTL_CHILD_DM_WATCH=$((S + 20)) \
|
||||
xcrun devicectl device process launch --device $D --terminate-existing $B -mode $m > $R/launch_$g.log 2>&1 || { t "🔴 $g 启动失败"; exit 1; }
|
||||
t "$g($m)开始 $S 秒"; sleep $S
|
||||
p=$(pid); [ -n "$p" ] && xcrun devicectl device process terminate --device $D --pid $p > /dev/null 2>&1; sleep 3
|
||||
[ -z "$(pid)" ] || t "🔴 $g 停不掉"
|
||||
for f in heat thr frames; do [ $g = B ] && [ $f = frames ] && continue
|
||||
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source "Documents/${f}_${g}_$RUN.tsv" --destination $R/${f}_$g.tsv > /dev/null 2>&1 || t "🔴 拉 ${f}_$g 失败"; done
|
||||
t "$g 结束"
|
||||
done
|
||||
python3 - $R <<'PY'
|
||||
import sys, statistics as st
|
||||
R = sys.argv[1]
|
||||
for g, name in (('B', '空白负对照'), ('A', '我们的 App 选角页')):
|
||||
rows = [l.rstrip('\n').split('\t') for l in open(f'{R}/heat_{g}.tsv')][1:]
|
||||
rows = [r for r in rows if len(r) == 9]
|
||||
th = [int(r[1]) for r in rows]; cpu = [float(r[2]) for r in rows]; fps = [float(r[3]) for r in rows]
|
||||
ga = [float(r[4]) for r in rows if float(r[4]) >= 0]; gp = [float(r[5]) for r in rows if float(r[5]) >= 0]
|
||||
print(f'{g} {name}:{len(rows)} 行 / {rows[-1][0] if rows else 0} 秒;温控 起 {th[0] if th else "?"} 止 {th[-1] if th else "?"}(序列 {"".join(map(str, th))});'
|
||||
f'CPU% 中位 {st.median(cpu):.1f}({min(cpu):.1f}–{max(cpu):.1f});出图帧率 中位 {st.median(fps):.1f};'
|
||||
+ (f'GPU 每帧 均值中位 {st.median(ga):.2f} ms、p95 中位 {st.median(gp):.2f} ms;' if ga else 'GPU 无(空白模式不取);')
|
||||
+ f'亮度 {rows[0][7]};最高刷新 {rows[0][8]}')
|
||||
PY
|
||||
@@ -0,0 +1,153 @@
|
||||
"""底部 UI v4 的几何与素材(效果图脚本 make_bottom_ui_v4.py、六格版 make_bottom_ui_v4_6.py 搬进仓库:只留 gen_hud_v4.py 用到的几何量、石条 / 格子 / 雕像与字效,
|
||||
去掉效果图的演示底图、抠球液、存图与自检表)。几何全部由常量算出,与效果图同一套数。
|
||||
素材来源(构建时从玩家自己的游戏文件读,仓库里不放原版的图):
|
||||
② PC 版 D2R 的解包目录(环境变量 DM_PC_DATA,缺省 $DM_ROOT/data/assets-src/raw,下面是 hd/global/ui/...):原版 2 倍图(v31 原始 RGBA),出的图与现行逐字节一致;
|
||||
① 找不到 PC 版文件:用 Switch 版 RomFS 里的同名精灵图(半分辨率)放大到 PC 尺寸,会略糊。
|
||||
字体两种都从 RomFS 取(hd/ui/fonts,与 PC 版逐字节相同)。
|
||||
Geometry and assets of bottom UI v4 (the mockup script make_bottom_ui_v4.py and the six-slot version make_bottom_ui_v4_6.py moved into the repo: keeping only the geometry values, stone strip / slots / statues and text effects that gen_hud_v4.py uses,
|
||||
dropping the mockup's demo background, orb liquid cutout, image saving and self-check table). Geometry is computed entirely from constants, the same set of numbers as the mockup.
|
||||
Asset sources (read at build time from the player's own game files; the repo holds no images from the original game):
|
||||
② Unpacked directory of PC D2R (environment variable DM_PC_DATA, default $DM_ROOT/data/assets-src/raw, with hd/global/ui/... beneath it): the original 2× images (v31 raw RGBA); the resulting images are byte-identical to the current ones;
|
||||
① PC files not found: the same-named sprites in the Switch RomFS (half resolution) are upscaled to PC size, slightly blurry.
|
||||
In both cases the fonts are taken from the RomFS (hd/ui/fonts, byte-identical to the PC version)."""
|
||||
import os, struct
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
import numpy as np
|
||||
import romfs_art
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
|
||||
|
||||
# 素材:名字 → (包内路径, PC 版尺寸)
|
||||
# Assets: name → (path in package, PC size)
|
||||
ART = {'front_panel': ('hd/global/ui/PANEL/HUD_02/front_panel.sprite', (2822, 415)),
|
||||
'levelupbutton': ('hd/global/ui/Controller/HUD/LevelUpButton.sprite', (248, 121)),
|
||||
'greater_healing_potion': ('hd/global/ui/items/misc/potion/greater_healing_potion.sprite', (98, 98)),
|
||||
'healing_potion': ('hd/global/ui/items/misc/potion/healing_potion.sprite', (98, 98)),
|
||||
'greater_mana_potion': ('hd/global/ui/items/misc/potion/greater_mana_potion.sprite', (98, 98)),
|
||||
'rejuv_potion': ('hd/global/ui/items/misc/potion/rejuv_potion.sprite', (98, 98)),
|
||||
'perfect_skull': ('hd/global/ui/items/misc/gem/perfect_skull.sprite', (98, 98))}
|
||||
|
||||
|
||||
class Source:
|
||||
"""取原版素材:有 PC 版文件用 PC 版 2 倍图,没有就用 Switch 版放大。 | Fetch the original game's assets: with PC files use the PC 2× images, otherwise upscale the Switch version."""
|
||||
def __init__(self, romfs, pc=None):
|
||||
self.romfs = romfs
|
||||
pc = pc or os.environ.get('DM_PC_DATA') or os.path.join(DM_ROOT, 'data/assets-src/raw')
|
||||
self.pc = pc if all(os.path.isfile(os.path.join(pc, p)) for p, _ in ART.values()) else None
|
||||
if not self.pc and os.environ.get('DM_REQUIRE_PC_ART') == '1': # 我们自己出包的机器在本机配置里设这一项:底栏不许悄悄变糊 | The machines we build our own packages on set this item in the local config: the bottom bar must not silently get blurry
|
||||
raise SystemExit('🔴 DM_REQUIRE_PC_ART=1 但没找到 PC 版 D2R 文件(DM_PC_DATA=%s,要有 hd/global/ui/... 下的原始 .sprite):正式包的底栏会变糊,不出' % pc)
|
||||
if not self.pc: print('没找到 PC 版文件(DM_PC_DATA=%s),底栏用 Switch 素材放大,会略糊' % pc)
|
||||
else: print('底栏素材:PC 版 2 倍原图(%s)' % self.pc)
|
||||
|
||||
def img(self, name):
|
||||
path, size = ART[name]
|
||||
if self.pc:
|
||||
b = open(os.path.join(self.pc, path), 'rb').read(); ver, fw, w, h = struct.unpack_from('<HHII', b, 4)
|
||||
assert b[:4] == b'SpA1' and ver == 31 and (w, h) == size, (path, ver, w, h)
|
||||
return Image.frombytes('RGBA', (w, h), b[40:40 + w * h * 4])
|
||||
return romfs_art.sprite(self.romfs, path).resize(size, Image.LANCZOS)
|
||||
|
||||
def font(self, name, size): return ImageFont.truetype(romfs_art.font(self.romfs, name), size)
|
||||
|
||||
|
||||
def load(src, VAR='C'):
|
||||
"""算出 v4 的几何与素材,返回一个命名空间字典(gen_hud_v4.py 用其中的 bar / slot / slots / L / R / 球心 / 经验条 / 文字基线 / fit / metal …)。 | Computes v4's geometry and assets, returns a namespace dict (gen_hud_v4.py uses its bar / slot / slots / L / R / orb centers / experience bar / text baseline / fit / metal ...)."""
|
||||
fp = src.img('front_panel'); lvl = src.img('levelupbutton').crop((0, 0, 124, 121))
|
||||
W, H = 2868, 1320
|
||||
# ---- 规格(px;1pt = 3px)----
|
||||
# ---- Spec (px; 1pt = 3px) ----
|
||||
K = 156 / 348 # front_panel 设计单位 → px(球径 348 单位 = 52pt) | front_panel design units → px (orb diameter 348 units = 52pt)
|
||||
P, DM = 120, 114 # 格距 40pt、格宽 38pt(格间 6px) | Slot pitch 40pt, slot width 38pt (6px between slots)
|
||||
TILE = (1673, 277, 1792, 391) # 原版格图只取金框本体(外沿实测 x3–121、y15–128) | From the original game's slot image take only the gold frame itself (outer edge measured x3–121, y15–128)
|
||||
SH = round(DM * (TILE[3] - TILE[1]) / (TILE[2] - TILE[0]))
|
||||
B = 12; EXT = 60; BH = 156 # 条边 4pt、两端伸进球下 20pt、条高 = 球径 | Strip border 4pt, both ends extend 20pt under the orbs, strip height = orb diameter
|
||||
XC = 1390 # 两球中线 | Centerline between the two orbs
|
||||
N = 6; SLOTS_W = N * DM + (N - 1) * (P - DM) # 六格(回城挪到右侧技能钮上方的圆钮,底栏去掉回城格;原七格 834) | Six slots (town portal moved to the round button above the right-side skill buttons, the town portal slot removed from the bottom bar; originally seven slots, 834)
|
||||
SX0 = XC - SLOTS_W // 2; SY0 = H - BH + (BH - SH) // 2
|
||||
BAR_X0 = SX0 - B; BAR_X1 = SX0 + SLOTS_W + B
|
||||
SAFE = 0.09 # 图标安全边距(内框每边 9%) | Icon safe margin (9% of the inner frame on each side)
|
||||
BADGE = 26 # 角标字号(瓶数 / 张数 / Lv) | Badge font size (bottle count / scroll count / Lv)
|
||||
out = Image.new('RGBA', (W, H)) # 效果图的演示底图不要:几何只用到文字度量与雕像透明度,不读底图像素 | The mockup's demo background is dropped: geometry only uses text metrics and statue alpha, and reads no background pixels
|
||||
# ---- 石条 + 七格(同一格图逐像素复制)----
|
||||
# ---- Stone strip + seven slots (the same slot image copied pixel for pixel) ----
|
||||
STONE = (690, 330, 1170, 388); EDGE = (690, 276, 1170, 288) # front_panel 左侧长凹槽:暗石内壁(二维纹理)+ 灰石边带;平铺不拉伸,不含任何石饰 | front_panel's long left groove: dark stone inner wall (2D texture) + gray stone edge band; tiled without stretching, containing no stone ornaments
|
||||
BW_ = BAR_X1 - BAR_X0 + 2 * EXT; bar = Image.new('RGBA', (BW_, BH))
|
||||
tile = fp.crop(STONE); edge = fp.crop(EDGE)
|
||||
for yy in range(0, BH, tile.height):
|
||||
for xx in range(0, BW_, tile.width): bar.alpha_composite(tile if (xx // tile.width) % 2 == 0 else tile.transpose(Image.FLIP_LEFT_RIGHT), (xx, yy))
|
||||
for xx in range(0, BW_, edge.width):
|
||||
bar.alpha_composite(edge, (xx, 0)); bar.alpha_composite(edge.transpose(Image.FLIP_TOP_BOTTOM), (xx, BH - edge.height))
|
||||
ImageDraw.Draw(bar).rectangle((0, 0, bar.width - 1, bar.height - 1), outline=(40, 33, 24, 255), width=3)
|
||||
slot = fp.crop(TILE).resize((DM, SH), Image.LANCZOS)
|
||||
ta = np.array(slot).astype(int); gold = (ta[..., 0] > 90) & (ta[..., 0] - ta[..., 2] > 40)
|
||||
def inner(line): # 从两端向里:先遇金、再出金的位置 = 金框内沿 | From both ends inward: the position where gold is first met and then left = inner edge of the gold frame
|
||||
def scan(seq):
|
||||
i = 0
|
||||
while i < len(seq) and not seq[i]: i += 1
|
||||
while i < len(seq) and seq[i]: i += 1
|
||||
while i + 3 < len(seq) and any(seq[i:i + 3]): i += 1 # 金框有斑驳暗点:连续 3 像素非金才算出框 | The gold frame has mottled dark spots: only 3 consecutive non-gold pixels count as leaving the frame
|
||||
return i
|
||||
return scan(line), len(line) - 1 - scan(line[::-1])
|
||||
INNER = (2, 107, 7, 101) # 金框内沿(PC 原图量出):Switch 半分辨率放大后金色阈值找不准,兜底版直接用这组;PC 版照量并核对 | Inner edge of the gold frame (measured from the PC original image): after upscaling the Switch half-resolution image the gold threshold cannot locate it accurately, so the fallback version uses this set directly; the PC version still measures and cross-checks
|
||||
if src.pc:
|
||||
IX0, IX1 = inner(list(gold[SH // 2])); IY0, IY1 = inner(list(gold[:, DM // 2]))
|
||||
assert (IX0, IX1, IY0, IY1) == INNER, ('金框内沿和记录的不一致,改 INNER', IX0, IX1, IY0, IY1)
|
||||
else: IX0, IX1, IY0, IY1 = INNER
|
||||
IW, IH = IX1 - IX0 + 1, IY1 - IY0 + 1; BOX = round(min(IW, IH) * (1 - 2 * SAFE))
|
||||
slots = [(SX0 + i * P, SY0, SX0 + i * P + DM, SY0 + SH) for i in range(N)]
|
||||
# ---- 图标:按不透明外接框统一缩放进安全区,外接框中心对内框中心 ----
|
||||
# ---- Icons: uniformly scaled into the safe area by opaque bounding box, bounding box center aligned to inner frame center ----
|
||||
ns = {}
|
||||
def prep(im):
|
||||
a = np.array(im)[..., 3]; ys, xs = np.where(a > 24); return im.crop((xs.min(), ys.min(), xs.max() + 1, ys.max() + 1))
|
||||
def fit(im, i, name, text=False):
|
||||
# 规则:缩放系数 = min(78/最大边, 基准几何平均边长/本图几何平均边长);文字类按字高 = 78×85%
|
||||
# Rule: scale factor = min(78/longest side, reference geometric-mean side length/this image's geometric-mean side length); text items use glyph height = 78×85%
|
||||
im = prep(im); w, h = im.size
|
||||
k = BOX * 0.85 / h if text else min(BOX / max(w, h), ns['REF_G'] / ((w * h) ** 0.5))
|
||||
im = im.resize((max(1, round(w * k)), max(1, round(h * k))), Image.LANCZOS)
|
||||
cx = slots[i][0] + IX0 + IW / 2; cy = slots[i][1] + IY0 + IH / 2
|
||||
ns['layer'].alpha_composite(im, (round(cx - im.width / 2), round(cy - im.height / 2)))
|
||||
pc = src.img
|
||||
exo = lambda s: src.font('exocetblizzardot-medium.otf', s)
|
||||
num = lambda s: src.font('blizzardglobal-v5_81.ttf', s) # 角标与 Lv:原版界面字体等高数字 | Badge and Lv: lining figures in the original game's UI font
|
||||
def metal(t, size): # 原版标题字效:暗金竖向渐变 + 细深描边 + 轻斜面(左上高光、右下暗影) | The original game's title text effect: dark gold vertical gradient + thin dark outline + light bevel (upper-left highlight, lower-right shadow)
|
||||
f = exo(size); pad = size // 4; W0, H0 = size * len(t) + 2 * pad, size * 2
|
||||
m = Image.new('L', (W0, H0)); ImageDraw.Draw(m).text((pad, pad), t, font=f, fill=255)
|
||||
a = np.array(m).astype(float) / 255; ys = np.where(a.max(1) > 0)[0]; y0, y1 = ys.min(), ys.max()
|
||||
g = np.zeros((H0, W0, 3)); top = np.array([236, 206, 140]); bot = np.array([120, 84, 36])
|
||||
for y in range(H0): t_ = min(1, max(0, (y - y0) / max(1, y1 - y0))); g[y, :] = top * (1 - t_) + bot * t_
|
||||
hi = np.roll(np.roll(a, -2, 0), -2, 1); sh = np.roll(np.roll(a, 3, 0), 3, 1)
|
||||
rgb = g * a[..., None]; rgb += np.clip(a - hi, 0, 1)[..., None] * np.array([255, 240, 200]) * 0.6; rgb *= (1 - 0.45 * np.clip(a - sh, 0, 1))[..., None]
|
||||
ol = np.array(m.filter(ImageFilter.MaxFilter(5))).astype(float) / 255
|
||||
out_ = np.zeros((H0, W0, 4)); out_[..., :3] = rgb + (1 - a)[..., None] * np.array([28, 18, 8]); out_[..., 3] = np.maximum(a, ol) * 255
|
||||
return Image.fromarray(np.clip(out_, 0, 255).astype('uint8'), 'RGBA')
|
||||
_r = prep(pc('greater_healing_potion')); _k = BOX / max(_r.size); ns['REF_G'] = ((_r.width * _k) * (_r.height * _k)) ** 0.5
|
||||
# ---- 两侧雕像(PC 定稿原图,按 K 缩放),球心 = 定稿布局 HealthBall(260,65)+174 / ManaBall(24,65)+174 ----
|
||||
# ---- Statues on both sides (final PC original images, scaled by K), orb center = final layout HealthBall(260,65)+174 / ManaBall(24,65)+174 ----
|
||||
L = fp.crop((0, 0, 610, 415)); R = fp.crop((2210, 0, 2822, 415))
|
||||
L = L.resize((round(L.width * K), round(L.height * K)), Image.LANCZOS); R = R.resize((round(R.width * K), round(R.height * K)), Image.LANCZOS)
|
||||
BR = round(174 * K) # 球半径 78 | Orb radius 78
|
||||
LX = BAR_X0 + 6 - round(608 * K); RX = BAR_X1 - 6 - round(24 * K)
|
||||
LBC = (LX + round(434 * K), H - L.height + round(239 * K)); RBC = (RX + round(198 * K), H - R.height + round(239 * K))
|
||||
# ---- 经验条:两端对齐七格外沿 ----
|
||||
# ---- Experience bar: both ends aligned to the outer edges of the seven slots ----
|
||||
EX0, EX1 = slots[0][0], slots[-1][2]; EY = H - BH - 12
|
||||
# ---- 生命 / 法力:小一号,紧贴球顶(基线:不压雕像、与经验条留 ≥6)----
|
||||
# ---- Life / mana: one size smaller, tight against the orb top (baseline: not overlapping the statue, leaving ≥6 from the experience bar) ----
|
||||
d = ImageDraw.Draw(out); fz = src.font('blizzardglobal-v5_81.ttf', 30)
|
||||
statue = np.zeros((H, W), bool)
|
||||
for im_, x_ in ((L, LX), (R, RX)): statue[H - im_.height:H, x_:x_ + im_.width] |= np.array(im_)[..., 3] > 24
|
||||
TXT = [(LBC, '生命: 55 / 55'), (RBC, '法力: 20 / 20')]; GAP = 6
|
||||
def tbox(c, t, yb): x0, y0, x1, y1 = d.textbbox((c[0], yb), t, font=fz, anchor='mb', stroke_width=1); return x0, y0, x1 + 2, y1 + 2 # 含投影 | Includes the drop shadow
|
||||
def ok_at(yb):
|
||||
for c, t in TXT:
|
||||
x0, y0, x1, y1 = tbox(c, t, yb)
|
||||
if statue[y0:y1, x0:x1].any(): return False
|
||||
if x1 > EX0 - GAP and x0 < EX1 + GAP and y1 > EY - GAP: return False
|
||||
return True
|
||||
YB = LBC[1] - BR - 4
|
||||
while not ok_at(YB): YB -= 1
|
||||
ns.update(W=W, H=H, DM=DM, SH=SH, EXT=EXT, BH=BH, BAR_X0=BAR_X0, BADGE=BADGE, BOX=BOX, IX0=IX0, IX1=IX1, IY0=IY0, IY1=IY1,
|
||||
bar=bar, slot=slot, slots=slots, L=L, R=R, LX=LX, RX=RX, LBC=LBC, RBC=RBC, BR=BR, EX0=EX0, EX1=EX1, EY=EY, YB=YB,
|
||||
lvl=lvl, prep=prep, fit=fit, pc=pc, num=num, metal=metal, layer=Image.new('RGBA', (W, H)))
|
||||
return ns
|
||||
@@ -0,0 +1,403 @@
|
||||
#!/usr/bin/env python3
|
||||
"""冻结UI/HID收据的独立只读配对;协议通过不等于物理触摸通过。 | Independent read-only pairing of frozen UI/HID receipts; the protocol passing does not mean physical touch passes."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
STATE = ("buttons", "lx", "ly", "rx", "ry")
|
||||
PHASES = {"began", "moved", "ended", "cancelled"}
|
||||
SOURCES = {"uitouch", "layout", "navigation", "focus_cancel", "screenshot", "bindings", "portal_sequence"}
|
||||
UI_INTS = {"eventseq", "receiptseq", "event_first_seq", "event_last_seq",
|
||||
"mono_ns", "publish_end_ns", "slot", *STATE}
|
||||
HID_INTS = {"read_start_ns", "time_ns", "sampling", "id", "style",
|
||||
"attributes", "script_mask", *STATE}
|
||||
|
||||
|
||||
class TraceError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def integer(value):
|
||||
if isinstance(value, bool):
|
||||
raise TraceError("boolean_not_integer")
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, str) and re.fullmatch(r"-?(?:0[xX][0-9a-fA-F]+|[0-9]+)", value):
|
||||
try:
|
||||
return int(value, 16) if "x" in value.lower() else int(value, 10)
|
||||
except ValueError:
|
||||
pass
|
||||
raise TraceError("bad_integer")
|
||||
|
||||
|
||||
def normalize(records, keys):
|
||||
out = []
|
||||
for src in records:
|
||||
row = dict(src)
|
||||
for key in keys & row.keys():
|
||||
row[key] = integer(row[key])
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
def require(row, fields):
|
||||
missing = set(fields) - row.keys()
|
||||
if missing:
|
||||
raise TraceError("missing_fields:" + ",".join(sorted(missing)))
|
||||
|
||||
|
||||
def validate_state(row):
|
||||
# 校验实际Npad ABI类型,而不是新增±32767生产阈值。
|
||||
# Validates the actual Npad ABI type, rather than adding a new ±32767 production threshold.
|
||||
if not 0 <= row["buttons"] < 2**64:
|
||||
raise TraceError("unsigned_range")
|
||||
if any(not -(2**31) <= row[k] < 2**31 for k in ("lx", "ly", "rx", "ry")):
|
||||
raise TraceError("int32_range")
|
||||
|
||||
|
||||
PORTAL_FIELDS = {"portal_request", "portal_binding", "portal_scene", "portal_phase",
|
||||
"portal_pending", "modifier_publish_end_ns", "feedback_group_start_ns",
|
||||
"feedback_captured_ns", "feedback_secondary", "feedback_seen",
|
||||
"feedback_identity_scope"}
|
||||
PORTAL_UNSIGNED = PORTAL_FIELDS - {"portal_phase", "portal_pending", "feedback_secondary",
|
||||
"feedback_seen", "feedback_identity_scope"}
|
||||
|
||||
|
||||
def validate_portal(row, active, request):
|
||||
if row["source"] == "portal_sequence" or PORTAL_FIELDS & row.keys():
|
||||
require(row, PORTAL_FIELDS)
|
||||
else:
|
||||
if request:
|
||||
raise TraceError("portal_fields_missing_during_request")
|
||||
return None
|
||||
if any(not 0 <= row[k] < 2**64 for k in PORTAL_UNSIGNED):
|
||||
raise TraceError("portal_unsigned_range")
|
||||
if (row["portal_phase"] not in {0, 1, 2} or row["portal_pending"] not in {0, 1} or
|
||||
row["feedback_secondary"] not in {0, 1} or not 0 <= row["feedback_seen"] <= 63 or
|
||||
row["feedback_identity_scope"] not in {0, 1, 2}):
|
||||
raise TraceError("portal_field_range")
|
||||
if row["source"] == "portal_sequence":
|
||||
if (not request or request["acked"] or not active or row["mode"] != "game" or
|
||||
row["portal_phase"] != 2 or row["portal_pending"] != 0):
|
||||
raise TraceError("portal_request_not_pending")
|
||||
modifier = request["modifier"]
|
||||
if not any(t in active and active[t] >= 0 for t in request["touches"]):
|
||||
raise TraceError("portal_touch_not_active")
|
||||
if any(row[k] != modifier[k] for k in ("portal_request", "portal_binding", "portal_scene",
|
||||
"modifier_publish_end_ns")):
|
||||
raise TraceError("portal_request_identity")
|
||||
if row["feedback_secondary"] != 1 or row["feedback_seen"] != 63 or row["feedback_identity_scope"] not in {1, 2}:
|
||||
raise TraceError("portal_feedback_identity")
|
||||
if not (modifier["publish_end_ns"] < row["feedback_group_start_ns"] <=
|
||||
row["feedback_captured_ns"] < row["mono_ns"] and
|
||||
row["mono_ns"] - row["feedback_captured_ns"] <= 250_000_000):
|
||||
raise TraceError("portal_feedback_time")
|
||||
# 最小两阶段原SDK位序;仅承认原facet A/B/X/Y/R/ZR的一个新增边沿。
|
||||
# Minimal two-phase original SDK bit order; only one newly added edge of the original facets A/B/X/Y/R/ZR is accepted.
|
||||
edge = row["buttons"] & ~modifier["buttons"]
|
||||
if not row["buttons"] & 256 or edge not in {1, 2, 4, 8, 128, 512}:
|
||||
raise TraceError("portal_action_edge")
|
||||
row["_portal_modifier_receipt"] = modifier["receiptseq"]
|
||||
request["acked"] = True
|
||||
return request
|
||||
if row["portal_phase"] == 1:
|
||||
if (row["portal_pending"] != 1 or row["mode"] != "game" or not active or
|
||||
not row["buttons"] & 256 or not all(row[k] for k in ("portal_request", "portal_binding", "portal_scene"))):
|
||||
raise TraceError("portal_modifier_publication")
|
||||
same = request and all(row[k] == request["modifier"][k] for k in
|
||||
("portal_request", "portal_binding", "portal_scene"))
|
||||
if same:
|
||||
if request["acked"] or row["modifier_publish_end_ns"] != request["modifier"]["publish_end_ns"]:
|
||||
raise TraceError("portal_modifier_publication")
|
||||
return request
|
||||
if (row["source"] != "uitouch" or row["phase"] != "began" or
|
||||
row["modifier_publish_end_ns"] != row["publish_end_ns"]):
|
||||
raise TraceError("portal_modifier_publication")
|
||||
return {"modifier": row, "acked": False,
|
||||
"touches": {e["touch"] for e in row["_touch_group"] if e["phase"] == "began" and e["slot"] >= 0}}
|
||||
if row["portal_pending"]:
|
||||
raise TraceError("portal_request_not_pending")
|
||||
if row["portal_phase"] == 0:
|
||||
return None
|
||||
# normal Portal无需ZL/ACK;已ACK请求的普通持有发布保留其关联。
|
||||
# normal Portal needs no ZL/ACK; the ordinary hold publish of an already ACKed request keeps its association.
|
||||
if request and all(row[k] == request["modifier"][k] for k in
|
||||
("portal_request", "portal_binding", "portal_scene")):
|
||||
if not request["acked"]:
|
||||
raise TraceError("portal_action_without_ack")
|
||||
return request
|
||||
return None
|
||||
|
||||
|
||||
def validate_ui(records):
|
||||
records = normalize(records, UI_INTS | PORTAL_FIELDS)
|
||||
events = []
|
||||
outputs = []
|
||||
active = {}
|
||||
pending = []
|
||||
event_no = receipt_no = published = last_time = end_time = 0
|
||||
lifecycle_reasons = set()
|
||||
portal_request = None
|
||||
portal_epoch = 0
|
||||
for row in records:
|
||||
require(row, ("stage", "eventseq", "mono_ns", "source", "phase", "mode", *STATE))
|
||||
validate_state(row)
|
||||
if row["source"] not in SOURCES or row["mode"] not in {"game", "navigation"}:
|
||||
raise TraceError("bad_source_or_mode")
|
||||
if row["mono_ns"] <= 0 or row["mono_ns"] < max(last_time, end_time):
|
||||
raise TraceError("ui_time_regression")
|
||||
last_time = row["mono_ns"]
|
||||
if row["stage"] == "event":
|
||||
require(row, ("slot", "touch", "x", "y", "touch_timestamp_s"))
|
||||
if row["source"] != "uitouch" or row["phase"] not in PHASES:
|
||||
raise TraceError("bad_event_source_phase")
|
||||
if row["eventseq"] != event_no + 1:
|
||||
raise TraceError("event_sequence_gap")
|
||||
if not -1 <= row["slot"] < 16:
|
||||
raise TraceError("bad_slot")
|
||||
for key in ("x", "y", "touch_timestamp_s"):
|
||||
if not math.isfinite(float(row[key])):
|
||||
raise TraceError("nonfinite_touch")
|
||||
if float(row["touch_timestamp_s"]) < 0:
|
||||
raise TraceError("negative_touch_timestamp")
|
||||
touch = row["touch"]
|
||||
if row["phase"] == "began":
|
||||
if touch in active:
|
||||
lifecycle_reasons.add("duplicate_begin")
|
||||
if row["slot"] >= 0 and row["slot"] in active.values():
|
||||
raise TraceError("slot_conflict")
|
||||
active[touch] = row["slot"]
|
||||
else:
|
||||
if touch not in active:
|
||||
lifecycle_reasons.add("lifecycle_orphan")
|
||||
elif active[touch] != row["slot"]:
|
||||
raise TraceError("slot_transition")
|
||||
if row["phase"] in {"ended", "cancelled"}:
|
||||
active.pop(touch, None)
|
||||
event_no += 1
|
||||
pending.append(row)
|
||||
events.append(row)
|
||||
elif row["stage"] == "output":
|
||||
require(row, ("receiptseq", "event_first_seq", "event_last_seq", "publish_end_ns"))
|
||||
if row["receiptseq"] != receipt_no + 1 or row["eventseq"] != event_no:
|
||||
raise TraceError("output_sequence_gap")
|
||||
first = published + 1 if event_no > published else 0
|
||||
if row["event_first_seq"] != first or row["event_last_seq"] != event_no:
|
||||
raise TraceError("event_group_not_closed")
|
||||
if pending and (row["source"] != "uitouch" or
|
||||
any(e["phase"] != row["phase"] for e in pending)):
|
||||
raise TraceError("event_group_source_phase")
|
||||
if (row["source"] == "uitouch") != (row["phase"] in PHASES):
|
||||
raise TraceError("bad_output_phase")
|
||||
if row["publish_end_ns"] < row["mono_ns"]:
|
||||
raise TraceError("reversed_publication")
|
||||
row["_touch_group"] = list(pending)
|
||||
row["_release"] = bool(pending) and not active and row["phase"] in {"ended", "cancelled"}
|
||||
row["_blank_claim"] = any(e.get("blank") is True for e in pending)
|
||||
portal_request = validate_portal(row, active, portal_request)
|
||||
if "portal_request" in row:
|
||||
if row["portal_request"] < portal_epoch:
|
||||
raise TraceError("portal_request_regression")
|
||||
portal_epoch = row["portal_request"]
|
||||
outputs.append(row)
|
||||
if row["source"] in {"layout", "focus_cancel"}:
|
||||
# 控件取消/清槽不代表物理触点已结束;后续无归属点slot=-1仍按touch身份闭合。
|
||||
# A widget cancel / slot clear does not mean the physical touch point has ended; a subsequent unowned point with slot=-1 is still closed under the touch identity.
|
||||
active = {touch: -1 for touch in active}
|
||||
pending.clear()
|
||||
receipt_no += 1
|
||||
published = event_no
|
||||
end_time = row["publish_end_ns"]
|
||||
else:
|
||||
raise TraceError("bad_ui_stage")
|
||||
if pending:
|
||||
lifecycle_reasons.add("unpublished_events")
|
||||
if active:
|
||||
lifecycle_reasons.add("lifecycle_unclosed")
|
||||
if not records:
|
||||
raise TraceError("empty_ui_trace")
|
||||
return events, outputs, lifecycle_reasons
|
||||
|
||||
|
||||
def validate_hid(records):
|
||||
records = normalize(records, HID_INTS)
|
||||
rows = []
|
||||
seen = set()
|
||||
reasons = set()
|
||||
for row in records:
|
||||
if row.get("event") == "limit_reached":
|
||||
reasons.add("limit_reached")
|
||||
continue
|
||||
if row.get("event") != "npad_return":
|
||||
raise TraceError("bad_hid_event")
|
||||
require(row, HID_INTS)
|
||||
validate_state(row)
|
||||
if row["read_start_ns"] < 0 or row["time_ns"] < row["read_start_ns"]:
|
||||
raise TraceError("reversed_read")
|
||||
if not 0 < row["sampling"] < 2**63:
|
||||
raise TraceError("bad_sampling")
|
||||
if any(not 0 <= row[k] < 2**32 for k in ("id", "style", "attributes")):
|
||||
raise TraceError("unsigned_range")
|
||||
if any(not 0 <= row[k] < 2**64 for k in ("buttons", "script_mask", "read_start_ns", "time_ns")):
|
||||
raise TraceError("unsigned_range")
|
||||
identity = (row["id"], row["style"], row["sampling"])
|
||||
if identity in seen:
|
||||
reasons.add("sampling_not_forward")
|
||||
seen.add(identity)
|
||||
rows.append(row)
|
||||
rows.sort(key=lambda r: (r["time_ns"], r["read_start_ns"]))
|
||||
last = {}
|
||||
for row in rows:
|
||||
key = (row["id"], row["style"])
|
||||
if key in last and row["sampling"] <= last[key]:
|
||||
reasons.add("sampling_not_forward")
|
||||
last[key] = row["sampling"]
|
||||
return rows, reasons
|
||||
|
||||
|
||||
def connected(row):
|
||||
return bool(row["attributes"] & 1) and (
|
||||
(row["id"] == 0 and row["style"] == 1) or
|
||||
(row["id"] == 32 and row["style"] == 2))
|
||||
|
||||
|
||||
def analyze(ui, hid, domain="synthetic"):
|
||||
result = {"domain": domain, "physical_pass_claimed": False,
|
||||
"release_received": False, "blank_activity_received": False,
|
||||
"combo_received": False, "portal_combo_pairs": 0}
|
||||
try:
|
||||
events, outputs, reasons = validate_ui(ui)
|
||||
result.update(ui_events=len(events), ui_outputs=len(outputs))
|
||||
if domain == "device" and any(o["source"] == "portal_sequence" and o["feedback_identity_scope"] != 1 for o in outputs):
|
||||
raise TraceError("synthetic_identity_on_device")
|
||||
if hid is None:
|
||||
result.update(status="pair_not_executed", reasons=sorted(reasons | {"missing_hid_stream"}),
|
||||
ui_lifecycle_closed=not reasons, pairs=[])
|
||||
return result
|
||||
reads, h_reasons = validate_hid(hid)
|
||||
reasons.update(h_reasons)
|
||||
pairs = []
|
||||
touch_pairs = 0
|
||||
matched_reads = {}
|
||||
for i, output in enumerate(outputs):
|
||||
upper = outputs[i + 1]["mono_ns"] if i + 1 < len(outputs) else None
|
||||
lo = output["publish_end_ns"]
|
||||
stable = [r for r in reads if r["read_start_ns"] > lo and
|
||||
(upper is None or r["time_ns"] < upper)]
|
||||
overlaps = [r for r in reads if
|
||||
r["time_ns"] >= output["mono_ns"] and
|
||||
(upper is None or r["read_start_ns"] < upper) and
|
||||
any(r["read_start_ns"] <= o["publish_end_ns"] and
|
||||
r["time_ns"] >= o["mono_ns"] for o in outputs)]
|
||||
candidates = [r for r in stable if connected(r) and r["script_mask"] == 0]
|
||||
matched = [r for r in candidates if all(r[k] == output[k] for k in STATE)]
|
||||
is_touch = output["source"] == "uitouch" and bool(output["_touch_group"])
|
||||
pair = {"receiptseq": output["receiptseq"], "source": output["source"],
|
||||
"event_group": [output["event_first_seq"], output["event_last_seq"]],
|
||||
"matched_sampling": [r["sampling"] for r in matched],
|
||||
"status": "matched" if matched else "not_sampled"}
|
||||
is_combo = output["source"] == "portal_sequence"
|
||||
if (is_touch or is_combo) and not matched:
|
||||
reasons.add("missing_combo_receipt" if is_combo else "missing_receipt")
|
||||
if overlaps:
|
||||
reasons.add("concurrent_undetermined")
|
||||
pair["status"] = "concurrent_undetermined"
|
||||
elif stable and not any(connected(r) for r in stable):
|
||||
reasons.add("invalid_controller")
|
||||
pair["status"] = "invalid_controller"
|
||||
elif any(connected(r) and r["script_mask"] for r in stable):
|
||||
reasons.add("script_confounded")
|
||||
pair["status"] = "script_confounded"
|
||||
elif candidates:
|
||||
reasons.add("returned_state_mismatch")
|
||||
pair["status"] = "state_mismatch"
|
||||
matched_reads[output["receiptseq"]] = matched
|
||||
if is_combo:
|
||||
modifier_reads = matched_reads.get(output["_portal_modifier_receipt"], [])
|
||||
before_feedback = [r for r in modifier_reads
|
||||
if r["time_ns"] < output["feedback_group_start_ns"]]
|
||||
modifier_received = bool(before_feedback)
|
||||
pair["modifier_before_feedback_sampling"] = [r["sampling"] for r in before_feedback]
|
||||
pair["modifier_receiptseq"] = output["_portal_modifier_receipt"]
|
||||
pair["combo_received"] = bool(matched) and modifier_received
|
||||
if not modifier_received:
|
||||
reasons.add("modifier_not_before_feedback" if modifier_reads else "missing_modifier_receipt")
|
||||
if pair["combo_received"]:
|
||||
result["combo_received"] = True
|
||||
result["portal_combo_pairs"] += 1
|
||||
neutral = all(output[k] == 0 for k in STATE)
|
||||
if output["_release"] and not neutral:
|
||||
reasons.add("release_not_neutral")
|
||||
if output["_blank_claim"] and output["buttons"] & 1:
|
||||
reasons.add("blank_unwanted_A")
|
||||
if matched and is_touch:
|
||||
touch_pairs += 1
|
||||
if output["_release"] and neutral:
|
||||
result["release_received"] = True
|
||||
if output["_blank_claim"] and not (output["buttons"] & 1):
|
||||
result["blank_activity_received"] = True
|
||||
# 程序来源可匹配值,但不能算新真实触摸。
|
||||
# A program source may match values, but must not count as a new real touch.
|
||||
if not is_touch:
|
||||
pair["attribution"] = "output_only_not_new_touch"
|
||||
pairs.append(pair)
|
||||
if not touch_pairs:
|
||||
reasons.add("no_touch_pairs")
|
||||
result.update(hid_rows=len(reads), touch_output_pairs=touch_pairs,
|
||||
pairs=pairs, reasons=sorted(reasons),
|
||||
status="incomplete" if reasons else "protocol_pass",
|
||||
unknowns=["no physical case/game result established",
|
||||
"blank-area identity requires independent gesture plan",
|
||||
"feedback identity/group are UI declarations; native caller proof needs frozen source and original capture"])
|
||||
except (TraceError, ValueError, TypeError, KeyError) as error:
|
||||
result.update(status="invalid_trace", reasons=[str(error)], pairs=[])
|
||||
return result
|
||||
|
||||
|
||||
def load_ui(path):
|
||||
records = []
|
||||
for line in Path(path).read_text(errors="replace").splitlines():
|
||||
if "[touch-receipt]" in line:
|
||||
records.append(dict(re.findall(r"(\w+)=([^\s]+)", line)))
|
||||
return records
|
||||
|
||||
|
||||
def load_hid(path):
|
||||
return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--ui-log", required=True)
|
||||
parser.add_argument("--hid-log")
|
||||
parser.add_argument("--domain", choices=["synthetic", "fake", "simulator", "device"], required=True)
|
||||
parser.add_argument("--out")
|
||||
parser.add_argument("--blank-events", default="",
|
||||
help="由独立手势计划指定空白触点eventseq,逗号分隔;不从零输出猜空白区域")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
ui = load_ui(args.ui_log)
|
||||
blanks = {int(v) for v in args.blank_events.split(",") if v}
|
||||
observed = set()
|
||||
for row in ui:
|
||||
if row.get("stage") == "event" and int(row["eventseq"]) in blanks:
|
||||
row["blank"] = True
|
||||
observed.add(int(row["eventseq"]))
|
||||
if observed != blanks:
|
||||
raise TraceError("blank_plan_event_missing")
|
||||
data = analyze(ui, load_hid(args.hid_log) if args.hid_log else None, args.domain)
|
||||
data["blank_plan_events"] = sorted(blanks)
|
||||
except (OSError, ValueError) as error:
|
||||
data = {"status": "invalid_trace", "reasons": [str(error)],
|
||||
"domain": args.domain, "physical_pass_claimed": False}
|
||||
text = json.dumps(data, ensure_ascii=False, indent=2)
|
||||
if args.out:
|
||||
Path(args.out).write_text(text + "\n")
|
||||
print(text)
|
||||
return {"protocol_pass": 0, "pair_not_executed": 2}.get(data["status"], 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,12 @@
|
||||
# iOS 着色器出包链的唯一编译口径:任意来源的 MSL(PC 链 / 常数补丁 / 今后 Switch 原版经 Ryujinx 翻译)→ iphoneos metallib。
|
||||
# 编译参数只在这里定义一次;反射 json 的 chain.metal 记录由同一份参数生成,记录 == 实际。
|
||||
# The single compile standard for the iOS shader packaging chain: MSL from any source (PC chain / constant patches / in future, the Switch original translated via Ryujinx) → iphoneos metallib.
|
||||
# Compile parameters are defined only once, here; the chain.metal record in the reflection json is generated from the same parameters, record == actual.
|
||||
import subprocess
|
||||
METAL = ['xcrun', '-sdk', 'iphoneos', 'metal', '-c', '-mios-version-min=18.0'] # 与既有 iOS 着色器缓存一致 | Consistent with the existing iOS shader cache
|
||||
METALLIB = ['xcrun', '-sdk', 'iphoneos', 'metallib']
|
||||
RECORD = ' '.join(METAL) + '; ' + ' '.join(METALLIB) # 写进 json chain.metal | Written into json chain.metal
|
||||
|
||||
def compile(msl, air, lib):
|
||||
subprocess.run([*METAL, msl, '-o', air], check=True)
|
||||
subprocess.run([*METALLIB, air, '-o', lib], check=True)
|
||||
@@ -0,0 +1,19 @@
|
||||
# 本机起 iOS 包不被系统的「恢复窗口」弹框挡住。被 smoke_mac.sh、touch_e2e_mac.sh、uireg/run_mac.sh source。
|
||||
# 为什么要有:某一局在系统恢复窗口的阶段被杀,系统会记一笔;之后每次起这个包都先弹模态框「…unexpectedly quit while reopening windows… Reopen / Don't Reopen」,
|
||||
# 包停在后台(没有启动日志),所有线的本机局都起不来,看上去像锁屏。
|
||||
# 起包的 open 命令在 --args 后面带上 "${LG_ARGS[@]}"(-ApplePersistenceIgnoreState YES:这一次启动不恢复窗口、也不问)
|
||||
# launch_guard_pre <容器 Data 目录> 起包前调:删掉上次留下的窗口状态(没有就是空操作)
|
||||
# launch_guard_blocked <包名> <说明> 起包后等不到启动日志时调:红字报「起包被挡」并带上系统登记的应用状态,返回非零
|
||||
# Keeps launching the iOS app on this Mac from being blocked by the system's "restore windows" dialog. Sourced by smoke_mac.sh, touch_e2e_mac.sh and uireg/run_mac.sh.
|
||||
# Why it exists: if some run is killed during the system's window restoration phase, the system makes a note of it; from then on every launch of this package first shows the modal dialog "...unexpectedly quit while reopening windows... Reopen / Don't Reopen",
|
||||
# the package sits in the background (no launch log), nobody's local runs can start, and it looks like a locked screen.
|
||||
# The open command that launches the package carries "${LG_ARGS[@]}" after --args (-ApplePersistenceIgnoreState YES: this launch neither restores windows nor asks)
|
||||
# launch_guard_pre <container Data directory> call before launching: deletes the window state left from last time (a no-op if there is none)
|
||||
# launch_guard_blocked <bundle id> <description> call when no launch log appears after launching: reports 「起包被挡」(launch blocked) in red together with the application state registered by the system, and returns non-zero
|
||||
LG_ARGS=(-ApplePersistenceIgnoreState YES)
|
||||
launch_guard_pre() { local d="$1/Library/Saved Application State"; [ -d "$d" ] && find "$d" -maxdepth 1 -name '*.savedState' -exec rm -rf {} + 2>/dev/null; return 0; }
|
||||
launch_guard_blocked() {
|
||||
local st; st=$(lsappinfo info -only pid,applicationState,isHidden -app "$1" 2>/dev/null | tr '\n' ' ')
|
||||
echo "【红】起包被挡:$2,启动日志没出现。系统登记的应用状态:${st:-查不到(进程没起来)}。多半是桌面上有系统弹框压着(恢复窗口 / 权限 / 损坏提示),到这台机器的桌面看一眼;不是被测代码的问题" >&2
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
"""界面布局 JSON 的结构补丁:仓库里只放「我们在原版布局上改了什么」,构建时套到玩家游戏文件里的原版布局上(不放原版布局本身)。
|
||||
补丁格式(递归):
|
||||
{"value": X} 整个换成 X(类型变了、或叶子值变了)
|
||||
{"dict": {键: 子补丁 | null}, "order": [键…]} 字典:子补丁为 null = 原样;不在原版里的键给 {"value": …};order = 结果的键顺序(删掉的键不在里面)
|
||||
{"list": [{"base": i, "patch": 子补丁 | null} | {"value": X}, …]} 列表:按结果的顺序,逐项指明取原版第 i 项(再套子补丁)或新值
|
||||
列表项按控件名("name")对应原版,名字对不上再按位置。用法:
|
||||
layout_patch.py diff <原版 json> <我们的 json> > 补丁.json (开发期:改了布局后重出补丁)
|
||||
apply(原版对象, 补丁) → 我们的对象
|
||||
Structural patch for UI layout JSON: the repo holds only "what we changed on top of the original game's layout", applied at build time onto the original layout in the player's game files (the original layout itself is not stored).
|
||||
Patch format (recursive):
|
||||
{"value": X} replace the whole thing with X (type changed, or leaf value changed)
|
||||
{"dict": {key: sub-patch | null}, "order": [key...]} dict: sub-patch null = unchanged; keys not in the original are given as {"value": ...}; order = key order of the result (deleted keys are not in it)
|
||||
{"list": [{"base": i, "patch": sub-patch | null} | {"value": X}, ...]} list: in result order, each item states whether to take the original's item i (then apply the sub-patch) or a new value
|
||||
List items are matched to the original by widget name ("name"), falling back to position when names do not match. Usage:
|
||||
layout_patch.py diff <original json> <our json> > patch.json (during development: regenerate the patch after changing the layout)
|
||||
apply(original object, patch) → our object"""
|
||||
import json, re, sys
|
||||
|
||||
|
||||
def load_text(t):
|
||||
t = re.sub(r'//.*', '', t); t = re.sub(r',(\s*[}\]])', r'\1', t); return json.loads(t)
|
||||
|
||||
|
||||
def diff(a, b):
|
||||
if type(a) != type(b): return {'value': b}
|
||||
if isinstance(a, dict):
|
||||
sub = {k: (diff(a[k], b[k]) if k in a else {'value': b[k]}) for k in b}
|
||||
if all(v is None for v in sub.values()) and list(a) == list(b): return None
|
||||
return {'dict': {k: v for k, v in sub.items() if v is not None}, 'order': list(b)}
|
||||
if isinstance(a, list):
|
||||
names = {x.get('name'): i for i, x in enumerate(a) if isinstance(x, dict) and x.get('name')}
|
||||
spec, used, changed = [], set(), len(a) != len(b)
|
||||
for j, y in enumerate(b):
|
||||
i = names.get(y.get('name')) if isinstance(y, dict) and y.get('name') else None
|
||||
if i is None and j < len(a) and j not in used and not (isinstance(a[j], dict) and a[j].get('name')): i = j
|
||||
if i is None or i in used: spec.append({'value': y}); changed = True; continue
|
||||
used.add(i); p = diff(a[i], y); spec.append({'base': i, 'patch': p}); changed |= p is not None or i != j
|
||||
return {'list': spec} if changed else None
|
||||
return None if a == b else {'value': b}
|
||||
|
||||
|
||||
def apply(a, p):
|
||||
if p is None: return a
|
||||
if 'value' in p: return p['value']
|
||||
if 'dict' in p: return {k: apply(a.get(k), p['dict'].get(k)) if k in a else p['dict'][k]['value'] for k in p['order']}
|
||||
if 'list' in p: return [apply(a[s['base']], s['patch']) if 'base' in s else s['value'] for s in p['list']]
|
||||
raise ValueError('layout_patch:不认识的补丁 %r' % list(p))
|
||||
|
||||
|
||||
if __name__ == '__main__' and sys.argv[1:2] == ['diff']:
|
||||
a = load_text(open(sys.argv[2], encoding='utf-8-sig').read()); b = load_text(open(sys.argv[3], encoding='utf-8-sig').read())
|
||||
p = diff(a, b); assert apply(a, p) == b and json.dumps(apply(a, p)) == json.dumps(b)
|
||||
json.dump(p, sys.stdout, ensure_ascii=False, indent=1); sys.stdout.write('\n')
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
#!/bin/bash
|
||||
# 真机生命周期一轮(界面测试 TouchSmokeTests/LifecycleSmoke):进局 → 主屏键回桌面 30 秒 → 激活同一进程 → 再跑 20 秒,拉回 boot.txt 按日志判。
|
||||
# 用法:dm/ios/tools/lifecycle.sh。冒烟类,走设备锁;构建用本树 .iosdd_ui(不碰共享目录)。末行 LIFECYCLE OK|RED
|
||||
# One round of real device lifecycle (UI test TouchSmokeTests/LifecycleSmoke): enter the game → home button back to the home screen for 30 seconds → activate the same process → run 20 more seconds, pull back boot.txt and judge by the log.
|
||||
# Usage: dm/ios/tools/lifecycle.sh. Smoke-test class, goes through the device lock; the build uses this tree's .iosdd_ui (does not touch the shared directory). Last line LIFECYCLE OK|RED
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
source tools/local_env.sh && local_env_need DM_DEVICE DM_IOS_UDID || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
D=$DM_DEVICE; UDID=$DM_IOS_UDID; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
|
||||
TREE=$(git rev-parse --show-toplevel); DD=$TREE/.iosdd_ui; R=${DM_ROOT:-$HOME/dm-work}/run/ios/lifecycle/$(date +%m%d_%H%M%S)_$$; mkdir -p "$R"
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
MODE=${1:-ui}
|
||||
if [ "$MODE" = sim ]; then # 应用内模拟(DM_TEST_BG):不需要手机开界面自动化;验我们自己的全部逻辑,验不了系统侧(表面回收、系统是否续上节拍回调) | In-app simulation (DM_TEST_BG): does not need UI automation enabled on the phone; verifies all of our own logic, cannot verify the system side (surface reclamation, whether the system resumes the display-link callback)
|
||||
DM_IOS_DD="$TREE/.iosdd" bash run.sh build > "$R/build.log" 2>&1 || { t "🔴 构建失败"; grep -E "error:" "$R/build.log" | head -5; echo "LIFECYCLE RED"; exit 1; }
|
||||
source tools/devlock.sh; devlock_acquire "${SMOKE_OWNER:-未署名} 生命周期(应用内模拟)"; trap devlock_release EXIT
|
||||
pidof(){ timeout 30 xcrun devicectl device info processes --device $D 2>/dev/null | grep 'DmIOS.app/DmIOS' | awk '{print $1}' | tr '\n' ' '; }
|
||||
for p in $(pidof); do timeout 30 xcrun devicectl device process terminate --device $D --pid $p > /dev/null 2>&1; done; sleep 2
|
||||
DM_IOS_DD="$TREE/.iosdd" bash run.sh install > "$R/install.log" 2>&1 || { t "🔴 装机失败"; tail -3 "$R/install.log"; echo "LIFECYCLE RED"; exit 1; }
|
||||
KEYS='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame'
|
||||
t "拉起(进局后第 25 秒起模拟后台 30 秒)"
|
||||
DEVICECTL_CHILD_DM_SAVE_FRESH=warlock DEVICECTL_CHILD_DM_AUDIO=1 DEVICECTL_CHILD_DM_TEST_BG=25,30 DEVICECTL_CHILD_DM_UIMSG=1 DEVICECTL_CHILD_DM_KEYS="$KEYS" timeout -k 5 30 xcrun devicectl device process launch --device $D $B -mode boot > "$R/launch.txt" 2>&1
|
||||
sleep 78; P0=$(pidof); trc=0; [ -n "$P0" ] || trc=1
|
||||
elif [ "$MODE" = switcher ]; then # 多任务界面里划掉:LifecycleSmoke/testSwitcherKill 一局 + testReenter 一局,判划掉前捡进背包的 r30 在不在 | Swiped away in the app switcher: one run of LifecycleSmoke/testSwitcherKill + one run of testReenter, checking whether the r30 picked up into the inventory before the swipe is still there
|
||||
DM_GEN_ONLY=1 DM_IOS_DD="$DD" bash run.sh build > "$R/gen.log" 2>&1 || { t "🔴 生成失败"; tail -3 "$R/gen.log"; echo "LIFECYCLE RED"; exit 1; }
|
||||
source tools/asc_env.sh; asc_auth
|
||||
xcodebuild build-for-testing -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destination "platform=iOS,id=$UDID" -derivedDataPath "$DD" -allowProvisioningUpdates ${ASC_AUTH[@]+"${ASC_AUTH[@]}"} > "$R/build.log" 2>&1 \
|
||||
|| { t "🔴 构建失败"; grep -E "error:" "$R/build.log" | head -5; echo "LIFECYCLE RED"; exit 1; }
|
||||
source tools/devlock.sh; devlock_acquire "${SMOKE_OWNER:-未署名} 生命周期(多任务界面划掉)"; trap devlock_release EXIT
|
||||
pull(){ timeout 60 xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source "Documents/$1" --destination "$R/$2" > /dev/null 2>&1; }
|
||||
t "第 1 局:进局 → 捡 r30 → 多任务界面停 3 秒 → 结束进程"
|
||||
xcodebuild test-without-building -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destination "platform=iOS,id=$UDID" -derivedDataPath "$DD" -only-testing:TouchSmokeTests/LifecycleSmoke/testSwitcherKill > "$R/test1.log" 2>&1
|
||||
pull boot.txt kill_boot.txt || { t "🔴 拉第 1 局日志失败"; echo "LIFECYCLE RED"; exit 1; }
|
||||
t "第 2 局:重进同一角色、记物品表"
|
||||
xcodebuild test-without-building -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destination "platform=iOS,id=$UDID" -derivedDataPath "$DD" -only-testing:TouchSmokeTests/LifecycleSmoke/testReenter > "$R/test2.log" 2>&1
|
||||
pull boot.txt re_boot.txt; pull lc_state.jsonl re_state.jsonl
|
||||
devlock_release; trap - EXIT
|
||||
K="$R/kill_boot.txt"; grep -a "前端:scene\|前端:失活\|进后台等游戏存盘\|存档提交 #\|DM_TEST_GIVE" "$K" | sed 's#/[^ ]*/Documents/#Documents/#g' | cut -c1-160
|
||||
cls=$(grep -a "DM_TEST_GIVE:.*「r30」" "$K" | grep -o "物品类号 [0-9]*" | head -1 | grep -o "[0-9]*$")
|
||||
gt=$(grep -an "DM_TEST_GIVE:.*「r30」" "$K" | head -1 | cut -d: -f1); ct=$(grep -an "存档提交 #" "$K" | tail -1 | cut -d: -f1)
|
||||
have=$( [ -n "$cls" ] && [ -s "$R/re_state.jsonl" ] && tail -1 "$R/re_state.jsonl" | grep -c "\"cls\":$cls," || echo 0)
|
||||
echo "r30 物品类号 ${cls:-无};第 1 局最后一次存档提交在 r30 之后:$([ -n "$gt" ] && [ -n "$ct" ] && [ "$ct" -gt "$gt" ] && echo 是 || echo 否);第 2 局物品表里有它:$([ "${have:-0}" -gt 0 ] && echo 有 || echo 没有)"
|
||||
[ "${have:-0}" -gt 0 ] && echo "LIFECYCLE OK" || echo "LIFECYCLE RED"; exit 0
|
||||
else
|
||||
DM_GEN_ONLY=1 DM_IOS_DD="$DD" bash run.sh build > "$R/gen.log" 2>&1 || { t "🔴 生成失败"; tail -3 "$R/gen.log"; echo "LIFECYCLE RED"; exit 1; }
|
||||
source tools/asc_env.sh; asc_auth
|
||||
xcodebuild build-for-testing -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destination "platform=iOS,id=$UDID" -derivedDataPath "$DD" -allowProvisioningUpdates ${ASC_AUTH[@]+"${ASC_AUTH[@]}"} > "$R/build.log" 2>&1 \
|
||||
|| { t "🔴 构建失败"; grep -E "error:" "$R/build.log" | head -5; echo "LIFECYCLE RED"; exit 1; }
|
||||
source tools/devlock.sh; devlock_acquire "${SMOKE_OWNER:-未署名} 生命周期"; trap devlock_release EXIT
|
||||
t "跑界面测试(约 90 秒)"
|
||||
xcodebuild test-without-building -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destination "platform=iOS,id=$UDID" -derivedDataPath "$DD" -only-testing:TouchSmokeTests/LifecycleSmoke > "$R/test.log" 2>&1; trc=$?
|
||||
grep -E "Test Case.*(passed|failed)|error:|XCTAssert" "$R/test.log" | tail -4
|
||||
fi
|
||||
timeout 60 xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source Documents/boot.txt --destination "$R/boot.txt" > "$R/pull.log" 2>&1 || { t "🔴 拉 boot.txt 失败"; echo "LIFECYCLE RED"; exit 1; }
|
||||
L="$R/boot.txt"; bad=0
|
||||
chk(){ if [ "$2" = 1 ]; then echo "✓ $1"; else echo "✗ $1"; bad=1; fi; }
|
||||
bg=$(grep -n "前端:sceneDidEnterBackground" "$L" | head -1 | cut -d: -f1); fg=$(grep -n "前端:sceneWillEnterForeground" "$L" | tail -1 | cut -d: -f1)
|
||||
chk "同一份日志里先进后台、后回前台(进程没重开):行 ${bg:-无} → ${fg:-无}" $([ -n "$bg" ] && [ -n "$fg" ] && [ "$fg" -gt "$bg" ] && echo 1 || echo 0)
|
||||
chk "进后台时图形已挂起" $(grep -q "图形挂起:在途 GPU 工作已清空" "$L" && echo 1 || echo 0)
|
||||
cb=$(grep "前端:sceneDidEnterBackground" "$L" | head -1 | sed -E 's/.*客体时钟 ([0-9.]+) s.*/\1/'); cf=$(grep "前端:sceneWillEnterForeground" "$L" | tail -1 | sed -E 's/.*客体时钟 ([0-9.]+) s.*/\1/')
|
||||
chk "后台那段没算进游戏时间:客体时钟 进后台 ${cb:-无} s → 回前台 ${cf:-无} s(差 < 1 s)" $(python3 -c "print(1 if abs(float('${cf:-1e9}')-float('${cb:-0}'))<1.0 else 0)" 2>/dev/null || echo 0)
|
||||
ab=$(grep "前端:sceneWillEnterForeground" "$L" | tail -1 | sed -E 's/.*声卡回调累计 ([0-9]+).*/\1/'); ae=$(grep -o "声卡回调 [0-9]*\|音频回调 [0-9]*" "$L" | tail -1 | grep -o "[0-9]*$")
|
||||
post=$([ -n "$fg" ] && tail -n +"$fg" "$L" || true)
|
||||
chk "回前台后音频恢复行出现" $(echo "$post" | grep -q "audio 恢复" && echo 1 || echo 0)
|
||||
up=$(echo "$post" | grep "上屏 至帧" | tail -1); chk "回前台后仍在上屏:${up:-无上屏行}" $([ -n "$up" ] && echo 1 || echo 0)
|
||||
# 回前台后的上屏质量:从「回前台」这个事件之后量,不按帧号凑整的窗口量。
|
||||
# 原判据读最后一行「上屏 至帧 N」的掉帧数 ≤ 3:那一窗按帧号每 300 帧切一次,正好横跨进后台的那一刻——进后台时排着队没上屏的帧按规矩丢弃并记成掉帧,
|
||||
# 游戏在「进后台」到「图形挂起」之间还会再出几帧,赶上几帧算几帧,同一个包量出来不是 3 就是 5,和回前台后卡不卡无关。
|
||||
# 现在看三件事:① 回前台那一窗里真正上了屏的帧,间隔没有超过 25 ms 的(掉帧 − 丢弃 = 0);② 回前台后的完整显示节拍窗(每窗 300 个节拍)至少 2 个,
|
||||
# 空节拍与被丢弃的帧一个都不新增;③ 进后台那一刻丢弃的帧数只记录、给个上限(12,约半秒的量),防它失控。
|
||||
# Present quality after returning to the foreground: measured from the "returned to foreground" event onward, not in windows rounded by frame number.
|
||||
# The old criterion read the dropped-frame count ≤ 3 from the last "present, up to frame N" line: that window is cut every 300 frames by frame number
|
||||
# and happens to straddle the moment of entering the background. Frames queued but not yet presented at that moment are discarded by rule and counted as
|
||||
# dropped,
|
||||
# and the game still produces a few more frames between "entering background" and "graphics suspended", as many as it manages to, so the same build
|
||||
# measures either 3 or 5, which has nothing to do with whether it stutters after returning to the foreground.
|
||||
# Three things are checked now: ① among the frames actually presented in the return-to-foreground window, no interval exceeds 25 ms (dropped − discarded
|
||||
# = 0); ② at least 2 complete display-link windows after returning to the foreground (300 display-link ticks per window),
|
||||
# with not a single new empty display-link tick or discarded frame; ③ the number of frames discarded at the moment of entering the background is only recorded and
|
||||
# given an upper bound (12, about half a second's worth) to keep it from running away.
|
||||
lg=$(tail -n +"${fg:-1}" "$L" | python3 -c '
|
||||
import re, sys
|
||||
P = sys.stdin.read().split("\n")
|
||||
t = [tuple(map(int, m.groups())) for l in P for m in [re.search(r"显示节拍 至 (\d+):节拍 \d+、出图 \d+、空节拍 (\d+)、合并丢弃旧帧 (\d+)", l)] if m]
|
||||
u = [tuple(map(int, m.groups())) for l in P for m in [re.search(r"上屏 至帧 \d+:\d+ 帧,掉帧 (\d+)(丢弃 (\d+))", l)] if m]
|
||||
n = max(len(t) - 1, 0); de = t[-1][1] - t[0][1] if t else -1; dd = t[-1][2] - t[0][2] if t else -1
|
||||
print(u[-1][0] - u[-1][1] if u else -1, u[-1][1] if u else -1, n, de, dd)')
|
||||
set -- $lg
|
||||
chk "回前台那一窗上了屏的帧没有间隔超 25 ms 的:${1:-无读数} 帧" $([ "${1:--1}" = 0 ] && echo 1 || echo 0)
|
||||
chk "回前台后完整显示节拍窗 ≥ 2 个且空节拍、丢弃都不新增:${3:-0} 窗(每窗 300 节拍),空节拍 +${4:-?},丢弃 +${5:-?}" $([ "${3:-0}" -ge 2 ] && [ "${4:--1}" = 0 ] && [ "${5:--1}" = 0 ] && echo 1 || echo 0)
|
||||
chk "进后台那一刻丢弃的帧数在上限内(只防失控,≤ 12):${2:-无读数} 帧" $([ "${2:--1}" -ge 0 ] && [ "${2:-99}" -le 12 ] && echo 1 || echo 0)
|
||||
chk "回前台后 3D 比例没有因此降档" $(echo "$post" | grep -q "3D 渲染比例 0.7[02]" && echo 0 || echo 1)
|
||||
chk "红行 0(实得 $(grep -c '【红】' "$L"))" $(grep -q '【红】' "$L" && echo 0 || echo 1)
|
||||
chk "动作序列做完、进程还在(退出码 / 存活标志 $trc)" $([ "$trc" = 0 ] && echo 1 || echo 0)
|
||||
chk "模拟回前台后 2 秒声卡回调有增量:$(grep -o '测试回前台后 2 s 声卡回调 +[0-9]*' "$L" | tail -1)" $([ "$MODE" != sim ] || grep -qE '测试回前台后 2 s 声卡回调 \+[1-9]' "$L" && echo 1 || echo 0)
|
||||
[ "$MODE" = sim ] && for p in $(pidof); do timeout 30 xcrun devicectl device process terminate --device $D --pid $p > /dev/null 2>&1; done
|
||||
echo "日志 $R"; [ $bad = 0 ] && echo "LIFECYCLE OK" || echo "LIFECYCLE RED"; exit $bad
|
||||
@@ -0,0 +1,15 @@
|
||||
# 本机设备配置(不进仓)。被各脚本 source:按序找 $DM_LOCAL_ENV → dm/ios/local.env → ~/.config/dm-ios/local.env,读第一个存在的
|
||||
# (后一个位置供同一台机器上的多个工作树共用)。样例与各项含义见 dm/ios/local.env.example。
|
||||
# local_env_need <变量…>:缺哪项就报哪项并返回非零。
|
||||
# Local device configuration (not committed to the repo). Sourced by the scripts: looks in order at $DM_LOCAL_ENV → dm/ios/local.env → ~/.config/dm-ios/local.env and reads the first that exists
|
||||
# (the last location lets multiple worktrees on the same machine share it). For a sample and the meaning of each item see dm/ios/local.env.example.
|
||||
# local_env_need <variables...>: reports whichever items are missing and returns nonzero.
|
||||
_le_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
for _le_f in "${DM_LOCAL_ENV:-}" "$_le_dir/local.env" "$HOME/.config/dm-ios/local.env"; do
|
||||
[ -n "$_le_f" ] && [ -f "$_le_f" ] && { set -a; source "$_le_f"; set +a; DM_LOCAL_ENV_FILE=$_le_f; break; }
|
||||
done
|
||||
local_env_need() {
|
||||
local v miss=
|
||||
for v in "$@"; do [ -n "${!v:-}" ] || miss="$miss $v"; done
|
||||
[ -z "$miss" ] || { echo "🔴 缺本机配置:$miss(把 dm/ios/local.env.example 复制成 dm/ios/local.env 填好;本次读的是:${DM_LOCAL_ENV_FILE:-没找到配置文件})" >&2; return 1; }
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
#!/usr/bin/env python3
|
||||
"""真机冒烟的日志通道:经 iproxy(USB 端口映射,不经 devicectl)连 App 的测试日志端口 DM_LOG_PORT。
|
||||
|
||||
实测 devicectl --console 首行延迟约 76 s、被杀的会话还拖住下一条 devicectl 约 80 s;文件通道(copy from)同样卡。
|
||||
App 侧(dm/ios/Sources/main.m,只在 DM_LOG_PORT 开关下):连上先补发 boot.txt 已写内容,再逐行实时转发;收到 quit 优雅退出。
|
||||
|
||||
用法:
|
||||
logport.py alive <本地端口> 退出码 0 = App 在监听(连上即有数据),1 = 没有
|
||||
logport.py quit <本地端口> [上限秒=10] 让在监听的 App 退出,并按「端口不再有数据」确认已退;退出码 0 = 已无实例
|
||||
logport.py until <本地端口> <日志文件> <上限秒> <标记> 收日志到出现标记行为止(触摸玩家路径)
|
||||
logport.py player <本地端口> <日志文件> <主菜单上限秒> <进局秒> <暂停秒> 玩家路径(见 player())
|
||||
logport.py read <本地端口> <日志文件> <主菜单上限秒> <撤屏上限秒>
|
||||
读日志判三阶段,成功后发 quit 并确认退出。标准输出 shell 可 eval 的结果:
|
||||
result=0|1 stage=启动|主菜单|进局|撤屏 pk=0|1(本局见到已知 PK)tL= tM= tG= tS=(Unix 整秒)exited=0|1 lines=N
|
||||
Log channel for real device smoke tests: connects to the App's test log port DM_LOG_PORT via iproxy (USB port mapping, not through devicectl).
|
||||
Measured: devicectl --console has a first-line delay of about 76 s, and a killed session holds up the next devicectl for about 80 s; the file channel (copy from) stalls the same way.
|
||||
App side (dm/ios/Sources/main.m, only under the DM_LOG_PORT switch): on connect it first replays what has already been written to boot.txt, then forwards line by line in real time; on receiving quit it exits gracefully.
|
||||
Usage:
|
||||
logport.py alive <local port> exit code 0 = App is listening (data arrives on connect), 1 = not
|
||||
logport.py quit <local port> [limit seconds=10] make the listening App exit, and confirm it has exited by "no more data on the port"; exit code 0 = no instance left
|
||||
logport.py until <local port> <log file> <limit seconds> <marker> collect the log until the marker line appears (touch player path)
|
||||
logport.py player <local port> <log file> <main menu limit seconds> <enter-game seconds> <pause seconds> player path (see player())
|
||||
logport.py read <local port> <log file> <main menu limit seconds> <screen dismissal limit seconds>
|
||||
read the log and judge three stages, on success send quit and confirm exit. Stdout is a result the shell can eval:
|
||||
result=0|1 stage=启动|主菜单|进局|撤屏 (launch|main menu|enter game|screen dismissal) pk=0|1 (a known PK was seen this run) tL= tM= tG= tS= (Unix whole seconds) exited=0|1 lines=N
|
||||
"""
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
|
||||
PK = '占不到 pthread 键 507'
|
||||
|
||||
|
||||
def connect(port, wait=1.0):
|
||||
"""连 iproxy 本地端口;App 在监听时一连上就有补发数据。返回 (套接字, 首块数据) 或 (None, b'')。 | Connect to the iproxy local port; when the App is listening, replayed data arrives as soon as connected. Returns (socket, first chunk of data) or (None, b'')."""
|
||||
try:
|
||||
s = socket.create_connection(('127.0.0.1', port), timeout=1)
|
||||
except OSError:
|
||||
return None, b''
|
||||
s.settimeout(wait)
|
||||
try:
|
||||
d = s.recv(65536)
|
||||
except (socket.timeout, OSError):
|
||||
d = b''
|
||||
if not d:
|
||||
s.close()
|
||||
return None, b''
|
||||
return s, d
|
||||
|
||||
|
||||
def alive(port):
|
||||
s, _ = connect(port)
|
||||
if s:
|
||||
s.close()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
ACK = 'DM_LOG_PORT:收到 quit,退出'.encode()
|
||||
|
||||
|
||||
def quit_and_confirm(port, limit=10.0, sock=None, out=None):
|
||||
"""确认式退出:发 quit 后保持连接继续读,见到 App 的同步回执才算送达(2 s 没见到就重发,quit 幂等),
|
||||
再读到 App 关连接(进程退出)为止,最后按「端口不再有数据」确认已退。
|
||||
不可发完即关 / 半关:iproxy 2.1.1 客户端一 EOF 就拆整条 usbmux 连接,quit 可能随拆除丢失(冒烟残留进程的根因)。
|
||||
Confirmed exit: after sending quit keep the connection open and keep reading; delivery only counts once the App's synchronous acknowledgment is seen (resend if not seen within 2 s; quit is idempotent),
|
||||
then read until the App closes the connection (process exit), and finally confirm it has exited by "no more data on the port".
|
||||
Do not close / half-close right after sending: the iproxy 2.1.1 client tears down the whole usbmux connection upon EOF, and quit may be lost with the teardown (root cause of leftover smoke-test processes)."""
|
||||
end = time.time() + limit
|
||||
if sock is None:
|
||||
sock, _ = connect(port)
|
||||
if sock is None:
|
||||
return True
|
||||
tail = b''; acked = False; resend = 0.0
|
||||
try:
|
||||
while time.time() < end:
|
||||
if not acked and time.time() >= resend:
|
||||
sock.sendall(b'quit\n'); resend = time.time() + 2.0
|
||||
sock.settimeout(0.2)
|
||||
try:
|
||||
d = sock.recv(65536)
|
||||
except socket.timeout:
|
||||
continue
|
||||
if not d:
|
||||
break # App 关连接 = 进程在退 | App closed the connection = the process is exiting
|
||||
if out:
|
||||
out.write(d)
|
||||
tail = (tail + d)[-4096:]
|
||||
if ACK in tail:
|
||||
acked = True
|
||||
except OSError:
|
||||
pass
|
||||
sock.close()
|
||||
if out:
|
||||
out.flush()
|
||||
while time.time() < end:
|
||||
if not alive(port):
|
||||
return True
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def read(port, log, menu_limit, game_limit):
|
||||
t0 = time.time()
|
||||
out = open(log, 'ab')
|
||||
r = dict(result=1, stage='启动', pk=0, tL='', tM='', tG='', tS='', exited=0, lines=0)
|
||||
deadline = t0 + menu_limit
|
||||
sock = None
|
||||
buf = b''
|
||||
while time.time() < deadline and r['result']:
|
||||
if sock is None:
|
||||
sock, first = connect(port)
|
||||
if sock is None:
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
buf += first
|
||||
else:
|
||||
try:
|
||||
d = sock.recv(65536)
|
||||
except socket.timeout:
|
||||
d = None
|
||||
except OSError:
|
||||
d = b''
|
||||
if d == b'':
|
||||
sock.close()
|
||||
sock = None
|
||||
continue
|
||||
if d:
|
||||
buf += d
|
||||
while b'\n' in buf:
|
||||
raw, buf = buf.split(b'\n', 1)
|
||||
out.write(raw + b'\n')
|
||||
line = raw.decode(errors='replace')
|
||||
now = int(time.time()) # 绝对时刻(整秒),与 smoke.sh 的 tA=$(date +%s) 同口径 | Absolute time (whole seconds), same basis as smoke.sh's tA=$(date +%s)
|
||||
r['lines'] += 1
|
||||
if not r['tL']:
|
||||
r['tL'] = now
|
||||
if PK in line:
|
||||
r['pk'] = 1
|
||||
if not r['tM'] and 'MainMenuButtonRibbon' in line:
|
||||
r['tM'], r['stage'] = now, '进局'
|
||||
deadline = time.time() + game_limit
|
||||
if r['tM'] and not r['tG'] and 'FrontEndNavigation ToGame' in line:
|
||||
r['tG'], r['stage'] = now, '撤屏'
|
||||
if r['tG'] and not r['tS'] and 'UnloadPanel LoadScreenPanel' in line:
|
||||
r['tS'], r['result'] = now, 0
|
||||
break
|
||||
if r['tL'] and r['stage'] == '启动':
|
||||
r['stage'] = '主菜单'
|
||||
r['exited'] = int(quit_and_confirm(port, sock=sock, out=out))
|
||||
out.close()
|
||||
print(' '.join(f'{k}={v}' for k, v in r.items()))
|
||||
return r['result']
|
||||
|
||||
|
||||
def snapshot_hang(log):
|
||||
"""玩家路径红时留现场:对 App 进程取样(各线程调用栈)+ 记当时的前台应用,写到日志同目录的 player_sample_<pid>.txt / player_env.txt。
|
||||
三次「未打开暂停菜单」都是进局约 10 秒后不再出帧、主线程定时器照常,事后日志里读不出停在哪;重跑 10 局没复现。
|
||||
只留证据,不改红绿判定;取样失败不影响后续退出。
|
||||
When the player path fails, capture diagnostics: sample the App process (call stacks of each thread) + record the foreground app at that moment, written next to the log as player_sample_<pid>.txt / player_env.txt.
|
||||
All three 「未打开暂停菜单」(pause menu not opened) cases were: no more frames about 10 seconds after entering the game while the main thread timer ran as usual, and the log afterwards could not tell where it was stopped; 10 reruns did not reproduce it.
|
||||
Evidence only, the pass/fail verdict is not changed; a sampling failure does not affect the subsequent exit."""
|
||||
import os, subprocess
|
||||
d = os.path.dirname(os.path.abspath(log))
|
||||
try:
|
||||
ps = subprocess.run(['ps', '-axo', 'pid=,comm='], capture_output=True, text=True, timeout=5).stdout
|
||||
procs = [l.split(None, 1) for l in ps.splitlines() if l.rstrip().endswith('/Wrapper/DmIOS.app/DmIOS')] # 同机可能还有别的线的包在跑(另一个设备族),都取、各存各的 | Packages from other lines may also be running on the same machine (another device family); take them all, saving each separately
|
||||
pids = [p[0] for p in procs]
|
||||
env = [f"时刻 {time.strftime('%H:%M:%S')} 同名进程 {len(procs)} 个"] + [f" pid {p[0]} {p[1].strip()}" for p in procs]
|
||||
for cmd in ("lsappinfo info -only name $(lsappinfo front)", "pmset -g assertions | grep -i display | head -4"):
|
||||
env.append(subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5).stdout.strip())
|
||||
open(os.path.join(d, 'player_env.txt'), 'w').write('\n'.join(env) + '\n')
|
||||
for pid in pids: subprocess.run(['sample', pid, '2', '-file', os.path.join(d, f'player_sample_{pid}.txt')], capture_output=True, timeout=30)
|
||||
except Exception as e:
|
||||
try: open(os.path.join(d, 'player_env.txt'), 'a').write(f'留现场失败:{e}\n')
|
||||
except Exception: pass
|
||||
|
||||
|
||||
def player(port, log, menu_limit, game_s, pause_s):
|
||||
"""玩家路径:进局(读取画面撤下)后满 game_s 秒,由键序打开暂停菜单,再静置 pause_s 秒;期间日志口不断、无看门狗 / CRASH 行。
|
||||
标准输出:result=0|1 stage=启动|进局|暂停|静置 why=<原因> tS= tP= exited=0|1
|
||||
Player path: game_s seconds after entering the game (loading screen dismissed), the key sequence opens the pause menu, then idle for pause_s seconds; meanwhile the log port stays connected and there are no watchdog / CRASH lines.
|
||||
Stdout: result=0|1 stage=启动|进局|暂停|静置 (launch|enter game|pause|idle) why=<reason> tS= tP= exited=0|1"""
|
||||
t0 = time.time(); out = open(log, 'ab'); sock = None; buf = b''; tS = tP = None; why = ''
|
||||
end = t0 + menu_limit + game_s + 30
|
||||
while time.time() < end:
|
||||
if sock is None:
|
||||
sock, first = connect(port)
|
||||
if sock is None:
|
||||
if tS: why = '日志口断开(App 退出)'; break
|
||||
time.sleep(0.2); continue
|
||||
buf += first
|
||||
else:
|
||||
try: d = sock.recv(65536)
|
||||
except socket.timeout: d = None
|
||||
except OSError: d = b''
|
||||
if d == b'':
|
||||
why = '日志口断开(App 退出)'; sock.close(); sock = None; break
|
||||
if d: buf += d
|
||||
while b'\n' in buf:
|
||||
raw, buf = buf.split(b'\n', 1); out.write(raw + b'\n'); line = raw.decode(errors='replace')
|
||||
if '看门狗' in line or 'CRASH' in line: why = line.strip()[:80]
|
||||
if tS is None and 'UnloadPanel LoadScreenPanel' in line: tS = time.time()
|
||||
if tS and tP is None and 'OpenPanel PauseLayout' in line: tP = time.time(); end = tP + pause_s
|
||||
if why: break
|
||||
stage = '启动' if tS is None else '暂停' if tP is None else '静置'
|
||||
ok = not why and tP is not None and time.time() >= tP + pause_s - 0.5
|
||||
if not ok and not why: why = '未见读取画面撤下' if tS is None else '未打开暂停菜单' if tP is None else '静置未满'
|
||||
if not ok: # 红:发退出指令之前先留现场(进程还活着、还停在那里) | On failure: capture diagnostics before sending the quit command (the process is still alive and still stopped there)
|
||||
if sock is not None: # 让 App 自己把各客体线程的等待状态、寄存器、图形等待点打进日志(真机上取不了样,只有这一份);多收 3 秒把它写进 player.txt | Have the App itself print each guest thread's wait state, registers and graphics wait points into the log (sampling is not possible on a real device, this is the only copy); collect 3 more seconds so it gets written into player.txt
|
||||
try:
|
||||
sock.sendall(b'dump\n'); sock.settimeout(0.3); t1 = time.time() + 3.0
|
||||
while time.time() < t1:
|
||||
try: d = sock.recv(65536)
|
||||
except socket.timeout: continue
|
||||
if not d: break
|
||||
out.write(d)
|
||||
except OSError: pass
|
||||
snapshot_hang(log)
|
||||
exited = int(quit_and_confirm(port, sock=sock, out=out)); out.close()
|
||||
print(f"result={0 if ok else 1} stage={stage} why='{why}' tS={int(tS - t0) if tS else ''} tP={int(tP - t0) if tP else ''} exited={exited}")
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
def until(port, log, limit, marker):
|
||||
"""把日志收到文件,直到出现含 marker 的行或满 limit 秒,然后让 App 退出。标准输出:result=0|1 why=<原因> t=<秒> exited=0|1 | Collect the log to a file until a line containing marker appears or limit seconds elapse, then make the App exit. Stdout: result=0|1 why=<reason> t=<seconds> exited=0|1"""
|
||||
t0 = time.time(); out = open(log, 'ab'); sock = None; buf = b''; seen = False; why = ''
|
||||
while time.time() < t0 + limit and not seen and not why:
|
||||
if sock is None:
|
||||
sock, first = connect(port)
|
||||
if sock is None:
|
||||
time.sleep(0.2); continue
|
||||
buf += first
|
||||
else:
|
||||
try: d = sock.recv(65536)
|
||||
except socket.timeout: d = None
|
||||
except OSError: d = b''
|
||||
if d == b'':
|
||||
why = '日志口断开(App 退出)'; sock.close(); sock = None; break
|
||||
if d: buf += d
|
||||
while b'\n' in buf:
|
||||
raw, buf = buf.split(b'\n', 1); out.write(raw + b'\n'); line = raw.decode(errors='replace')
|
||||
if '看门狗' in line or 'CRASH' in line: why = line.strip()[:80]
|
||||
if marker in line: seen = True
|
||||
if not seen and not why: why = f'{int(limit)} 秒内没等到「{marker}」'
|
||||
exited = int(quit_and_confirm(port, sock=sock, out=out)); out.close()
|
||||
print(f"result={0 if seen and not why else 1} why='{why}' t={int(time.time() - t0)} exited={exited}")
|
||||
return 0 if seen and not why else 1
|
||||
|
||||
|
||||
def main(argv):
|
||||
cmd, port = argv[1], int(argv[2])
|
||||
if cmd == 'alive':
|
||||
return 0 if alive(port) else 1
|
||||
if cmd == 'quit':
|
||||
return 0 if quit_and_confirm(port, float(argv[3]) if len(argv) > 3 else 10.0) else 1
|
||||
if cmd == 'player':
|
||||
return player(port, argv[3], float(argv[4]), float(argv[5]), float(argv[6]))
|
||||
if cmd == 'until':
|
||||
return until(port, argv[3], float(argv[4]), argv[5])
|
||||
if cmd == 'read':
|
||||
return read(port, argv[3], float(argv[4]), float(argv[5]))
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main(sys.argv))
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/bin/bash
|
||||
# 生成冒烟用的标准存档:在这台 Mac 上把 iOS 包从空存档起一局,用触点脚本先后建两个角色、各进一次营地并保存退出,再把存档收成标准存档。
|
||||
# 之后出的 App 会带上它(run.sh build 从工作区拷),冒烟第一段「读档进局」就有档可读。存档只在你的工作区里,不进仓库。
|
||||
# 用法:make_fixture.sh 产物:$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0/
|
||||
# 前提:setup.sh 已跑完、dm/ios/local.env 填了 DM_TEAM_ID 与 DM_BUNDLE_ID。已有标准存档时不覆盖,要重做先删掉那个目录。
|
||||
# Generate the standard save used by the smoke test: on this Mac, start a game in the iOS app from an empty save, use a touch point script to create two characters one after the other, enter the camp once with each and save and exit, then collect the result as the standard save.
|
||||
# Apps built afterwards carry it (run.sh build copies it from the workspace), so the first smoke-test segment, "load a save and enter the game", has a save to load. The save stays in your workspace only and does not go into the repository.
|
||||
# Usage: make_fixture.sh Output: $DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0/
|
||||
# Prerequisites: setup.sh has finished, and dm/ios/local.env has DM_TEAM_ID and DM_BUNDLE_ID filled in. An existing standard save is not overwritten; to redo it, delete that directory first.
|
||||
set -u
|
||||
TOOLS=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); export DM_ROOT=${DM_ROOT:-$HOME/dm-work}
|
||||
source "$TOOLS/local_env.sh"; local_env_need DM_BUNDLE_ID || exit 1
|
||||
B=$DM_BUNDLE_ID; DST=$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0
|
||||
[ -d "$DST" ] && { echo "已有标准存档 $DST,不覆盖"; exit 0; }
|
||||
GAME=${SMOKE_MAC_ROMFS:-$DM_ROOT/data/switch/3.3.94012/Update/RomFS/data}
|
||||
[ -f "$GAME/.build.config" ] || { echo "✗ 没有游戏资源 $GAME"; exit 1; }
|
||||
W=$(SMOKE_MAC_PKG_ONLY=1 bash "$TOOLS/smoke_mac.sh" 1 2>&1 | sed -n 's/^SMOKE-MAC 只出包 //p' | tail -1)
|
||||
[ -d "$W" ] || { echo "✗ 没出成能在 Mac 上跑的包"; exit 1; }
|
||||
export DM_DEVLOCK_DIR=$DM_ROOT/run/ios/macsmoke.lock; source "$TOOLS/devlock.sh"; devlock_acquire "生成标准存档" 300 || exit 1; trap devlock_release EXIT
|
||||
pids() { ps -axo pid=,command= | awk '/\/Wrapper\/DmIOS\.app\/DmIOS/ {print $1}'; }
|
||||
[ -z "$(pids)" ] || { echo "✗ 这台 Mac 上已有游戏实例在跑(pid $(pids | tr '\n' ' ')),先结束它"; exit 1; }
|
||||
container() { local m; for m in "$HOME"/Library/Containers/*/.com.apple.containermanagerd.metadata.plist; do
|
||||
[ "$(/usr/libexec/PlistBuddy -c 'Print :MCMMetadataIdentifier' "$m" 2>/dev/null)" = "$B" ] && { echo "$(dirname "$m")/Data"; return 0; }; done; return 1; }
|
||||
C=$(container) || { open -n "$W" --args -mode boot; for _ in $(seq 1 30); do C=$(container) && break; sleep 0.5; done; for p in $(pids); do kill -TERM "$p"; done; sleep 1; }
|
||||
[ -n "${C:-}" ] || { echo "✗ 系统没有给 $B 建容器(包没签进这台 Mac?)"; exit 1; }
|
||||
rom="$C/Library/Application Support/romfs"
|
||||
[ -f "$rom/data/.build.config" ] || { mkdir -p "$rom" && cp -cR "$GAME" "$rom/data" || { echo "✗ 资源没放进容器"; exit 1; }; }
|
||||
port=$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1])"); LOG=$(mktemp)
|
||||
# 触点脚本:冒烟那份的前半(建角、进局、站定)→ 打开功能页、切到暂停页、点「保存并退出」(新角色要退回选角页才落盘)
|
||||
# → 在选角页再建第二个角色、同样保存退出。出两个角色是因为冒烟的缺省键序要点选角列表的第 2 行来选角色,只有一个角色时那一下没有反应。
|
||||
# Touch point script: the first half of the smoke test's script (create a character, enter the game, come to a stop) → open the function page, switch to the pause page, tap "Save and Exit" (a new character is written to disk only after returning to the character select page)
|
||||
# → create a second character on the character select page and save and exit the same way. Two characters are made because the smoke test's default key sequence taps row 2 of the character list to pick a character, and with only one character that tap does nothing.
|
||||
{ sed -n '1,/ pos$/p' "$TOOLS/smoke_touch.txt"
|
||||
printf '%s\n' '24.00 down 0 @menu' '24.12 up 0' '25.50 down 0 551,17' '25.62 up 0' '26.60 tap_ui Exit@PauseLayoutGarden 3' \
|
||||
'34.00 tap_ui CreateCharacter@CharacterSelectPanel 3' '36.50 down 0 488,209' '36.62 up 0' '37.30 down 0 433,189' '37.42 up 0' '40.00 down 0 334,343' '40.12 up 0' \
|
||||
'43.00 down 0 167,193' '43.12 up 0' '46.00 type Second' '47.00 alert ok' '55.00 pos' \
|
||||
'57.00 down 0 @menu' '57.12 up 0' '58.50 down 0 551,17' '58.62 up 0' '59.60 tap_ui Exit@PauseLayoutGarden 3' '67.00 note 存档完成'; } > "$C/Documents/fixture_touch.txt"
|
||||
caffeinate -u -t 3 > /dev/null 2>&1
|
||||
open -n "$W" --env DM_GAME_RES=2868x1320 --env DM_TEST_SAFE_L=62 --env DM_TEST_SAFE_R=62 --env DM_TOUCH_REF=667x375 --env DM_SAVE_FRESH=empty --env DM_LOG_PORT="$port" --env DM_UIMSG=1 \
|
||||
--env DM_TOUCH_SCRIPT=fixture_touch.txt --env DM_TOUCH_SCRIPT_START=menu --env DM_GAME_SEED=0x12345678 --env DM_FIXED_TIME=1790000000 --args -mode boot
|
||||
r=$(python3 "$TOOLS/logport.py" until "$port" "$LOG" 160 '[script] 全部') # 等触点脚本走完(建角、进局、保存并退出);之后让 App 自己退出 | Wait for the touch point script to finish (create a character, enter the game, save and exit); then let the App quit by itself
|
||||
for _ in $(seq 1 20); do [ -z "$(pids)" ] && break; sleep 0.5; done; for p in $(pids); do kill -TERM "$p"; done
|
||||
case "$r" in result=0*) ;; *) echo "✗ 没走到建角进局($r),日志 $LOG"; exit 1;; esac
|
||||
LC_ALL=C grep -a -q '【红】' "$LOG" && { echo "✗ 触点脚本有一步没走成:$(LC_ALL=C grep -a '【红】' "$LOG" | head -1 | cut -c1-120),日志 $LOG"; exit 1; }
|
||||
n=$(find "$C/Documents/save.test" -name '*.d2s' 2> /dev/null | wc -l | tr -d ' ')
|
||||
[ "$n" -ge 2 ] || { echo "✗ 存档目录里只有 $n 个角色文件(要 2 个),日志 $LOG"; exit 1; }
|
||||
mkdir -p "$DST" && cp -R "$C/Documents/save.test/." "$DST/" && chmod -R u+w "$DST" && echo "标准存档已生成:$DST($n 个角色)。重新出 App(run.sh build)后冒烟即可用"
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
# 佣兵加装备位(秘境最高通关 ≥ 10 层解锁):佣兵面板的装备区整块照玩家装备栏——十个物品格(原有四格 + 项链 / 手套 / 两戒指 / 腰带 / 鞋)的矩形 = 玩家物品栏布局里
|
||||
# 同名格的矩形平移一个固定偏移(格子图在两个面板里左上角之差)。底图由 gen_merc_art.py 生成(石纹和格子都从玩家栏的原图逐像素拷,名字条下移、属性表压行距),
|
||||
# 这里改布局:原四格挪到玩家栏的格位,加六个原版物品格控件(名字 = 部位、空位图照玩家物品栏面板),名字条 / 经验条 / 技能图标整体下移 216 单位,属性表五行按新行距重排;
|
||||
# 手柄光标的上下左右停靠照玩家物品栏接上。
|
||||
# 未解锁时六个格上各盖一块我们自己的暗红矩形 TouchMercLock_<部位>(原版「这个位置不可用」的颜色,如佣兵拿双手武器时的副手格),缺省在屏外,宿主(dm_rift_ui.c)按解锁状态挪。
|
||||
# 服务端放不放得进去由数据表(wide_stash.py 补佣兵行)和放置校验那道门(patch_nso.py 0x8d)决定,这里只管画面
|
||||
# Extra mercenary equipment slots (unlocked at highest rift level cleared ≥ 10): the equipment area of the mercenary panel follows the player's equipment panel as a whole -- the rectangles of the ten item cells (the original four + amulet / gloves / two rings / belt / boots) = the rectangles of the
|
||||
# same-named cells in the player inventory layout translated by a fixed offset (the difference between the grid image's top-left corners in the two panels). The base image is generated by gen_merc_art.py (stone texture and cells both copied pixel for pixel from the player panel's original images, name strip moved down, stat table row pitch compressed),
|
||||
# and the layout is changed here: the original four cells move to the player panel's cell positions, six original item cell widgets are added (name = body location, empty-slot image as in the player inventory panel), the name strip / experience bar / skill icons move down as a whole by 216 units, and the five stat table rows are re-laid at the new row pitch;
|
||||
# up / down / left / right controller cursor navigation is wired up following the player inventory.
|
||||
# When not unlocked each of the six cells is covered by our own dark red rectangle TouchMercLock_<body location> (the original game's color for "this slot is unavailable", such as the off-hand cell when the mercenary holds a two-handed weapon), off-screen by default and moved by the host (dm_rift_ui.c) according to the unlock state.
|
||||
# Whether the server lets an item in is decided by the data table (wide_stash.py adds the mercenary row) and the placement check gate (patch_nso.py 0x8d); this file only handles what is drawn
|
||||
import os, re, shutil, sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import touch_layout
|
||||
|
||||
PANEL = 'controller/hirelinginventorypanelhd.json'; PLAYER = 'controller/playerinventoryoriginallayouthd.json'
|
||||
BG = 'data/hd/global/ui/controller/panel/hirelinginventory/v2/hirelinginventorybg.sprite'
|
||||
SHIFT = 216 # 名字条下移(布局单位 = 底图 108 像素) | Name strip moved down (layout units = 108 pixels in the base image)
|
||||
ROWS = {902: 1064, 903: 1065, 905: 1067, 994: 1132, 993: 1131, 995: 1133, 1088: 1200, 1089: 1201, 1090: 1202, 1183: 1268, 1185: 1270, 1279: 1336} # 属性表各行:原 y → 新 y(底图里每行 34 像素) | Stat table rows: original y → new y (34 pixels per row in the base image)
|
||||
# 名字(上)、经验条(中)、「等级 N 佣兵类型」(下):原版两行字都贴各自矩形的下沿,中文字体下名字离经验条 13 像素、等级那行却几乎贴着条(原版佣兵面板本来如此,:
|
||||
# 错位不对称、压到经验条)。改成两行各放进一个 60 高的矩形、竖向居中,两个矩形关于经验条槽(底图里 y 956–972,中心 964)上下对称:{控件: (y, 高)}
|
||||
# Name (top), experience bar (middle), "Level N <mercenary type>" (bottom): in the original both text lines sit on the bottom edge of their own rectangles, so with the Chinese font the name is 13 pixels from the experience bar while the level line almost touches the bar (the original mercenary panel is like this to begin with:
|
||||
# misaligned and asymmetric, pressing on the experience bar). Changed to put each line in a 60-high rectangle, vertically centered, with the two rectangles symmetric above and below the experience bar groove (y 956–972 in the base image, center 964): {widget: (y, height)}
|
||||
ROWS_TXT = {'CharacterName': (884, 60), 'HireTypeText': (984, 60)}
|
||||
BAND = ('CharacterName', 'HireTypeText', 'XpProgress', 'NextLevelXP', 'CurrentXP', 'Skill0', 'Skill1', 'Skill2')
|
||||
STATS = ('HPTitle', 'HPStat', 'StrengthTitle', 'StrengthStat', 'DexTitle', 'DexStat', 'DamageTitle', 'Damage', 'ArmorClassTitle', 'ArmorClass',
|
||||
'FireResistanceTitle', 'FireText', 'ColdResistanceTitle', 'ColdText', 'LightningResistanceTitle', 'LightningText', 'PoisonResistanceTitle', 'PoisonText')
|
||||
NEW = ('neck', 'gloves', 'right_hand', 'belt', 'left_hand', 'feet')
|
||||
NAV = { # 手柄光标停靠(照玩家物品栏:上排 武器 / 头 / 项链 / 副手,下排 手套 / 右戒 / 腰带 / 左戒 / 鞋) | Controller cursor navigation (following the player inventory: top row weapon / head / amulet / off-hand, bottom row gloves / right ring / belt / left ring / boots)
|
||||
'head': {'left': 'right_arm', 'right': 'neck', 'down': 'torso'}, 'neck': {'left': 'head', 'right': 'left_arm', 'down': 'left_hand'},
|
||||
'torso': {'left': 'right_arm', 'right': 'left_arm', 'up': 'head', 'down': 'belt'}, 'right_arm': {'right': 'torso', 'down': 'gloves'},
|
||||
'left_arm': {'left': 'neck', 'up': 'head', 'down': 'feet'}, 'gloves': {'up': 'right_arm', 'right': 'right_hand'},
|
||||
'right_hand': {'left': 'gloves', 'right': 'belt', 'up': 'torso'}, 'belt': {'left': 'right_hand', 'right': 'left_hand', 'up': 'torso'},
|
||||
'left_hand': {'left': 'belt', 'right': 'feet', 'up': 'neck'}, 'feet': {'left': 'left_hand', 'up': 'left_arm'}}
|
||||
|
||||
def _block(text, name):
|
||||
m = re.search(r'\{\s*"type"\s*:\s*"\w+"\s*,\s*"name"\s*:\s*"%s"' % re.escape(name), text)
|
||||
if not m: raise SystemExit('merc_slots:布局里没有控件 ' + name)
|
||||
return m.start(), touch_layout._block_end(text, m.start()) + 1
|
||||
|
||||
def _set_y(text, name, fn):
|
||||
a, b = _block(text, name); blk = text[a:b]; r = re.compile(r'("rect"\s*:\s*\{\s*"x"\s*:\s*-?\d+\s*,\s*"y"\s*:\s*)(-?\d+)').search(blk)
|
||||
if not r: raise SystemExit('merc_slots:控件 %s 没有 rect 的 y' % name)
|
||||
return text[:a] + blk[:r.start(2)] + str(fn(int(r.group(2)))) + blk[r.end(2):] + text[b:]
|
||||
|
||||
def _nav(slot):
|
||||
rows = ['"%s": { "name": "slot_%s" }' % (d, t) for d, t in NAV[slot].items()]
|
||||
if slot in ('left_arm', 'feet'): rows.append('"right": { "panelBoundary": true }')
|
||||
return '"navigation": { ' + ', '.join(rows) + ' }'
|
||||
|
||||
INV_AT = (196, 43) # 格子图左上角在玩家物品栏面板里的位置(布局单位:面板 1408×1486、图锚在中心、rect −508, −700) | Position of the grid image's top-left corner in the player inventory panel (layout units: panel 1408×1486, image anchored at the center, rect −508, −700)
|
||||
ALL = ('head', 'torso', 'right_arm', 'left_arm') + NEW
|
||||
|
||||
def rects(player_text):
|
||||
"""十个格的布局矩形 {部位: (x, y, 宽, 高)} = 玩家物品栏里同名格的矩形平移到佣兵底图的格子图位置。 | Layout rectangles of the ten cells {body location: (x, y, width, height)} = the rectangles of the same-named cells in the player inventory, translated to the grid image's position in the mercenary base image."""
|
||||
import gen_merc_art
|
||||
dx, dy = 2 * gen_merc_art.DX - INV_AT[0], 2 * gen_merc_art.DY - INV_AT[1]; out = {}
|
||||
for s in ALL:
|
||||
a, b = _block(player_text, 'slot_' + s); m = re.search(r'"rect"\s*:\s*\{\s*"x"\s*:\s*(\d+)\s*,\s*"y"\s*:\s*(\d+)\s*,\s*"width"\s*:\s*(\d+)\s*,\s*"height"\s*:\s*(\d+)\s*\}', player_text[a:b])
|
||||
if not m: raise SystemExit('merc_slots:玩家物品栏布局里 slot_%s 没有 rect' % s)
|
||||
x, y, w, h = map(int, m.groups()); out[s] = (x + dx, y + dy, w, h)
|
||||
return out
|
||||
|
||||
def transform(text, player_text):
|
||||
for n in BAND: text = _set_y(text, n, lambda y: y + SHIFT)
|
||||
for n, (y, h) in ROWS_TXT.items(): # 名字 / 等级两行:见 ROWS_TXT | The name / level rows: see ROWS_TXT
|
||||
a, b = _block(text, n); blk = text[a:b]
|
||||
blk, n1 = re.subn(r'("rect"\s*:\s*\{\s*"x"\s*:\s*-?\d+\s*,\s*"y"\s*:\s*)-?\d+(\s*,\s*"width"\s*:\s*\d+\s*,\s*"height"\s*:\s*)\d+', lambda m: '%s%d%s%d' % (m.group(1), y, m.group(2), h), blk, count=1)
|
||||
blk, n2 = re.subn(r'"v"\s*:\s*"bottom"', '"v": "center"', blk, count=1)
|
||||
if n1 != 1 or n2 != 1: raise SystemExit('merc_slots:%s 的 rect / 竖向对齐和原版布局对不上(原版布局变了?)' % n)
|
||||
text = text[:a] + blk + text[b:]
|
||||
for n in STATS:
|
||||
def fn(y, n=n):
|
||||
if y not in ROWS: raise SystemExit('merc_slots:属性表控件 %s 的 y = %d 不在行表里(原版布局变了?)' % (n, y))
|
||||
return ROWS[y]
|
||||
text = _set_y(text, n, fn)
|
||||
R = rects(player_text)
|
||||
for s in ('head', 'torso', 'right_arm', 'left_arm'): # 原四格:挪到玩家栏的格位,停靠方向换成新的 | The original four cells: moved to the player panel's cell positions, with navigation targets replaced by the new ones
|
||||
a, b = _block(text, 'slot_' + s); blk = text[a:b]; i = blk.index('"navigation"'); j = touch_layout._block_end(blk, blk.index('{', i)) + 1
|
||||
blk = blk[:i] + _nav(s) + blk[j:]; x, y, w, h = R[s]
|
||||
blk, n = re.subn(r'"rect"\s*:\s*\{[^}]*\}', '"rect": { "x": %d, "y": %d, "width": %d, "height": %d }' % (x, y, w, h), blk, count=1)
|
||||
if n != 1: raise SystemExit('merc_slots:佣兵面板 slot_%s 没有 rect' % s)
|
||||
text = text[:a] + blk + text[b:]
|
||||
add = ''
|
||||
for s in NEW:
|
||||
pa, pb = _block(player_text, 'slot_' + s); bg = re.search(r'"backgroundFilename"\s*:\s*"([^"]+)"', player_text[pa:pb]).group(1); x, y, w, h = R[s]
|
||||
add += ',\n { "type": "InventorySlotWidget", "name": "slot_%s", "fields": { "rect": { "x": %d, "y": %d, "width": %d, "height": %d }, "backgroundFilename": "%s", %s } }' % (s, x, y, w, h, bg, _nav(s))
|
||||
# 盖板放在物品格之后(画在上层)。颜色按实跑截图配到和原版不可用格(佣兵拿双手武器时的副手格)同一个红:副手格实测约 (41, 8, 9)、空凹槽底色约 (19, 19, 19),
|
||||
# 盖板不透明度 0.78 时颜色 = (目标 − 0.22 × 底色) ÷ 0.78 ÷ 255(第一版 (70, 8, 10) 太扎眼)
|
||||
# The covers come after the item cells (drawn on top). The color was matched from actual-run screenshots to the same red as an original disabled cell (the off-hand cell when the mercenary holds a two-handed weapon): the off-hand cell measured about (41, 8, 9), the empty recess background about (19, 19, 19),
|
||||
# and with cover opacity 0.78 the color = (target − 0.22 × background) ÷ 0.78 ÷ 255 (the first version (70, 8, 10) was too glaring)
|
||||
for s in NEW:
|
||||
x, y, w, h = R[s]
|
||||
add += ',\n { "type": "RectangleWidget", "name": "TouchMercLock_%s", "fields": { "rect": { "x": 99999, "y": %d, "width": %d, "height": %d }, "color": [ 0.187, 0.019, 0.022, 0.78 ] } }' % (s, y, w, h)
|
||||
a, b = _block(text, 'slot_left_arm')
|
||||
return text[:b] + add + text[b:]
|
||||
|
||||
def build(romfs, outdir, repl):
|
||||
"""触屏版:叠在触摸布局已改的那份(右上角关闭钮)上。返回 {包内逻辑路径: 本地文件}。 | Touch version: stacked on the copy already modified by the touch layout (close button at the top right). Returns {logical path in the package: local file}."""
|
||||
import gen_merc_art
|
||||
out = {}; p = os.path.join(outdir, 'ms_hirelinginventorybg.sprite'); shutil.copyfile(os.path.join(gen_merc_art.ART, 'HirelingInventoryBG.sprite'), p); out[BG] = p
|
||||
logical = touch_layout.read_layout(romfs, PANEL)[0].lower(); src = repl.get(logical)
|
||||
text = open(src, encoding='utf-8').read() if src else touch_layout.read_layout(romfs, PANEL)[1]
|
||||
p = os.path.join(outdir, 'ms_hireling.json'); open(p, 'w', encoding='utf-8').write(transform(text, touch_layout.read_layout(romfs, PLAYER)[1])); out[logical] = p
|
||||
return out
|
||||
|
||||
def build_pad(romfs, outdir):
|
||||
"""手柄版:原版布局上直接改。 | Controller layout: edited directly on the original layout."""
|
||||
logical, text = touch_layout.read_layout(romfs, PANEL)
|
||||
p = os.path.join(outdir, 'pad_hireling.json'); open(p, 'w', encoding='utf-8').write(transform(text, touch_layout.read_layout(romfs, PLAYER)[1]))
|
||||
return {logical.lower(): p}
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
# mini(或本机)量测锁。只有一把:就是 Mac 冒烟、触屏用例、回归局共用的 macsmoke 锁($DM_ROOT/run/ios/macsmoke.lock),本文件只是它的一层名字。
|
||||
# 为什么不另设一把:带窗口的宿主一开窗就到前台,别人的 iOS 包窗口被盖住 / 失去前台后系统不再给显示刷新回调,对方整局不出帧。
|
||||
# 曾有一次逐通道量测拿的是单独的「测量锁」,与另外两路回归局互不相识地并行了约 28 分钟,对方 5 局出秒级长帧、要重跑;
|
||||
# 同样的事冒烟也撞过一次(那次只改了起局脚本,这把锁没并)。凡是在 mini 上开窗口、要显示刷新的任务都只认这一把。
|
||||
# 用法不变:source mlock.sh; mlock_acquire "<线名> <在量什么> 约 <时长>"; trap mlock_release EXIT
|
||||
# 批量脚本自己先取锁(它会 export XT_LOCK_HELD=1),里面逐局调的 xtrace.sh mac 见到这个变量就不再取;排队与「持有者已不在就接手」由 devlock.sh 管。
|
||||
# Measurement lock for the second Mac (or the local machine). There is only one: the macsmoke lock shared by Mac smoke tests, touchscreen cases and regression runs ($DM_ROOT/run/ios/macsmoke.lock); this file is just another name layered over it.
|
||||
# Why not set up a separate one: a windowed host comes to the foreground as soon as it opens its window, and once someone else's iOS app window is covered / loses the foreground the system stops delivering display refresh callbacks to it, so the other side outputs no frames for the whole run.
|
||||
# Once, a per-pass measurement took a separate "measurement lock" and ran in parallel with two other regression lines for about 28 minutes, neither aware of the other; 5 of the other side's runs got second-long frames and had to be rerun;
|
||||
# the smoke test also hit the same thing once (that time only the run launcher script was changed, and this lock was not merged in). Any task that opens a window on the second Mac and needs display refresh honors only this one lock.
|
||||
# Usage unchanged: source mlock.sh; mlock_acquire "<line name> <what is being measured> approx <duration>"; trap mlock_release EXIT
|
||||
# Batch scripts take the lock themselves first (it exports XT_LOCK_HELD=1), and xtrace.sh mac invoked per run inside sees this variable and does not take it again; queuing and "take over if the holder is gone" are handled by devlock.sh.
|
||||
mlock_acquire() {
|
||||
[ "${XT_LOCK_HELD:-}" = 1 ] && return 0
|
||||
export DM_DEVLOCK_DIR=${XT_LOCK_DIR:-${DM_ROOT:-$HOME/dm-work}/run/ios/macsmoke.lock}
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/devlock.sh" || { echo "🔴 mlock:同目录下没有 devlock.sh"; return 1; }
|
||||
devlock_acquire "$1" || return 1
|
||||
export XT_LOCK_HELD=1; MLOCK_MINE=1
|
||||
}
|
||||
mlock_release() { [ "${MLOCK_MINE:-}" = 1 ] || return 0; devlock_release; MLOCK_MINE=; unset XT_LOCK_HELD; }
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""原版技能图集 / HUD 小图 → TouchArt PNG,原版 Skills / Skilldesc → 纯 C 索引 dm_touch_native_art.c。构建时从玩家自己的游戏文件生成,不进仓库。
|
||||
来源与指纹冻结在仓库里的 Sources/TouchArt/native_art_manifest.json(只有原版路径与哈希):读包后先核原件 SHA-256 / MD5 与两张表的 SHA-256,
|
||||
解码后核 PNG 的 SHA-256(解码只解块、不重绘像素);对不上就报错(游戏版本不对)。
|
||||
用法:generate.py <原版 RomFS(Update)> 产物生成在原位置、git 忽略(dm/ios/.gitignore):Sources/TouchArt/dm_native_*.png、Sources/dm_touch_native_art.c
|
||||
(.c 里按 Sources/ 写了相对 include,PNG 由 DmTouchOverlay.m / 工程 / 测试按 Sources/TouchArt 引用,所以不挪目录)
|
||||
Original game skill atlas / HUD small images → TouchArt PNG, original game Skills / Skilldesc → pure C index dm_touch_native_art.c. Generated at build time from the player's own game files, not kept in the repository.
|
||||
Sources and fingerprints are frozen in Sources/TouchArt/native_art_manifest.json in the repository (only original game paths and hashes): after reading the package, first verify the SHA-256 / MD5 of the original files and the SHA-256 of the two tables,
|
||||
after decoding verify the SHA-256 of the PNGs (decoding only decodes blocks, it does not redraw pixels); on a mismatch report an error (wrong game version).
|
||||
Usage: generate.py <original game RomFS (Update)> The build output is generated in place and git-ignored (dm/ios/.gitignore): Sources/TouchArt/dm_native_*.png, Sources/dm_touch_native_art.c
|
||||
(the .c has a relative include written against Sources/, and the PNGs are referenced by DmTouchOverlay.m / the project / the tests via Sources/TouchArt, so the directory is not moved)"""
|
||||
import csv, hashlib, io, json, sys
|
||||
from pathlib import Path
|
||||
HERE = Path(__file__).resolve().parent; IOS = HERE.parent.parent
|
||||
sys.path.insert(0, str(HERE.parent))
|
||||
import romfs_art
|
||||
sha = lambda b: hashlib.sha256(b).hexdigest()
|
||||
canonical = lambda obj: json.dumps(obj, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
classes = ['amazon', 'Sorceress', 'Necromancer', 'paladin', 'Barbarian', 'Druid', 'Assassin', 'Warlock', 'SubMenu']
|
||||
codes = ['ama', 'sor', 'nec', 'pal', 'bar', 'dru', 'ass', 'war', '']
|
||||
classes_by_code = {v: i for i, v in enumerate(codes)}
|
||||
COMMON_ICON = {357: 20, 358: 22, 360: 24, 361: 30, 362: 32, 363: 34, 364: 36, 370: 38}
|
||||
|
||||
|
||||
def main(romfs):
|
||||
mpath = IOS / 'Sources/TouchArt/native_art_manifest.json'; man = json.loads(mpath.read_text())
|
||||
tables = {}
|
||||
for t in man['official_tables']:
|
||||
raw = romfs_art.read(romfs, 'global/excel/' + t['file'])
|
||||
if sha(raw) != t['sha256']: raise SystemExit('native_art:游戏文件里的 %s 和冻结的不一样(游戏版本不对?要 3.3.94012)' % t['file'])
|
||||
tables[t['file']] = list(csv.DictReader(io.StringIO(raw.decode('utf-8')), delimiter='\t'))
|
||||
art = IOS / 'Sources/TouchArt'; atlases = {}
|
||||
for a in man['assets']:
|
||||
raw = romfs_art.read(romfs, a['official_path'].split('data:data/', 1)[-1])
|
||||
if sha(raw) != a['official_sprite_sha256'] or hashlib.md5(raw).hexdigest() != a['official_sprite_md5']:
|
||||
raise SystemExit('native_art:%s 的原件和冻结的不一样(游戏版本不对?)' % a['official_path'])
|
||||
b = io.BytesIO(); romfs_art.sprite(romfs, a['official_path'].split('data:data/', 1)[-1]).save(b, 'PNG')
|
||||
if sha(b.getvalue()) != a['decoded_png_sha256']: raise SystemExit('native_art:%s 解出的 PNG 与冻结的不一致(Pillow 版本?)' % a['asset'])
|
||||
(art / a['asset']).write_bytes(b.getvalue()); atlases[a['asset']] = a
|
||||
atl = [atlases['dm_native_skill_%d.png' % i] for i in range(len(classes))]
|
||||
desc = {r['skilldesc']: r for r in tables['skilldesc.txt']}; rows = []
|
||||
for r in tables['skills.txt']:
|
||||
raw = int(r['*Id']); char = classes_by_code.get(r['charclass'], -1); cel = desc.get(r['skilldesc'], {}).get('IconCel', '')
|
||||
frame = int(cel) if cel.strip() else -1
|
||||
if char < 0 or frame < 0 or frame + 1 >= atl[char]['frame_count']: char = frame = -1
|
||||
# 手柄版后加的通用动作:官方表的 IconCel 是占位值 2(普通攻击那一帧),游戏的技能树 / 绑定框画的是通用图集里各自的图。
|
||||
# 帧号逐个对过原版绑定框里同一技能的大图标(综合技能页逐个长按):交互、拾取、表情、换武器、地图、显示物品、跑 / 走、方块拾取
|
||||
# Generic actions added later by the controller version: IconCel in the official table is the placeholder value 2 (the normal attack frame), while the game's skill tree / binding box draws each one's own image from the generic atlas.
|
||||
# The frame numbers were checked one by one against the big icon of the same skill in the original game's binding box (long-pressing each on the General Skills page): interact, pick up, emote, swap weapons, map, show items, run / walk, block pickup
|
||||
if raw in COMMON_ICON: frame = COMMON_ICON[raw]; assert char >= 0 and frame + 1 < atl[char]['frame_count']
|
||||
rows.append([raw, char, frame])
|
||||
assert len({r[0] for r in rows}) == len(rows)
|
||||
if sha(canonical(rows)) != man['descriptor_index_sha256']: raise SystemExit('native_art:技能索引和冻结的不一致')
|
||||
gpath = IOS / 'docs/native_art_v1_geometry.json'; binding = IOS / 'docs/touch_layout_spec_native_binding_v5.json'
|
||||
out = ['/* Generated from frozen official Skills/Skilldesc; do not hand-edit rows. */', '#include "dm_touch_native_art.h"', '#include "../../host/dm_input.h"', '#include <stddef.h>',
|
||||
'const dm_ta_atlas dm_ta_atlases[DM_TA_ATLASES]={']
|
||||
for a in atl: out.append(' {"%s",%d,%d,%d,%d,%d},' % (a['asset'][:-4], *a['atlas_px'], a['frame_width'], a['frame_pitch'], a['frame_count']))
|
||||
out += ['};', f'const char dm_ta_manifest_sha[]="{sha(mpath.read_bytes())}";', f'const char dm_ta_geometry_sha[]="{sha(gpath.read_bytes())}";',
|
||||
f'const char dm_ta_binding_sha[]="{sha(binding.read_bytes())}";', 'static const struct { uint32_t id; int atlas,frame; } rows[]={']
|
||||
out += [' {%d,%d,%d},' % tuple(row) for row in rows]; out += ['};']
|
||||
out += [(HERE / 'implementation.c.inc').read_text()]
|
||||
(IOS / 'Sources/dm_touch_native_art.c').write_text('\n'.join(out) + '\n')
|
||||
print(f'native_art:{len(rows)} 条技能索引、{len(atlases)} 张 PNG(原件 SHA256 + MD5、PNG SHA256 都核过)→ {art}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1])
|
||||
@@ -0,0 +1,33 @@
|
||||
static dm_ta_glyph unknown(uint32_t id,const char *reason) {
|
||||
return (dm_ta_glyph){DM_TA_UNKNOWN,-1,-1,-1,-1,-1,id,reason};
|
||||
}
|
||||
int dm_ta_frame_at(int atlas,int frame,dm_ta_frame *out) {
|
||||
if(!out || atlas<0 || atlas>=DM_TA_ATLASES || frame<0)return 0;
|
||||
const dm_ta_atlas *a=&dm_ta_atlases[atlas];
|
||||
if(frame>=a->count || frame*a->pitch+a->frame_width>a->width)return 0;
|
||||
*out=(dm_ta_frame){frame*a->pitch,0,a->frame_width,a->height};return 1;
|
||||
}
|
||||
dm_ta_glyph dm_ta_skill(uint32_t id) {
|
||||
dm_ta_glyph g=unknown(id,"unknown_skill");
|
||||
if(id==UINT32_MAX){g.status=DM_TA_EMPTY;g.reason="empty_slot";return g;}
|
||||
for(size_t i=0;i<sizeof rows/sizeof rows[0];i++)if(rows[i].id==id) {
|
||||
dm_ta_frame frame;
|
||||
if(!dm_ta_frame_at(rows[i].atlas,rows[i].frame,&frame) || !dm_ta_frame_at(rows[i].atlas,rows[i].frame+1,&frame))return g;
|
||||
g.status=DM_TA_GLYPH;g.atlas=rows[i].atlas;g.normal_frame=rows[i].frame;g.pressed_frame=rows[i].frame+1;g.reason="official_raw_id";return g;
|
||||
}
|
||||
return g;
|
||||
}
|
||||
dm_ta_glyph dm_ta_current(const dm_tg_snapshot *s,uint64_t button,uint64_t now) { return dm_ta_current_set(s,button,now,0); }
|
||||
dm_ta_glyph dm_ta_current_set(const dm_tg_snapshot *s,uint64_t button,uint64_t now,int skill_set) {
|
||||
dm_ta_glyph g=unknown(UINT32_MAX,"empty_unknown");
|
||||
if(!s || !s->supported || !s->valid || !s->ready || s->source!=DM_TG_SOURCE_NATIVE_GETTER ||
|
||||
s->identity_scope!=DM_TG_IDENTITY_NATIVE || !s->captured_ns || now<s->captured_ns ||
|
||||
now-s->captured_ns>DM_TG_MAX_AGE_NS || (s->selected_bank!=0 && s->selected_bank!=16))return g;
|
||||
uint32_t logical=0;
|
||||
switch(button){case DM_BTN_A:logical=0x2000;break;case DM_BTN_B:logical=0x1000;break;
|
||||
case DM_BTN_X:logical=0x8000;break;case DM_BTN_Y:logical=0x4000;break;case DM_BTN_R:logical=0x200;break;default:return g;}
|
||||
int slot=-1;
|
||||
for(int i=0;i<DM_TG_FACETS;i++)if(s->mapping[i].logical==logical){if(slot>=0)return g;slot=(int)(skill_set?s->mapping[i].alt:s->mapping[i].normal);}
|
||||
if(slot<0 || slot>=(skill_set?12:6))return g;
|
||||
g=dm_ta_skill(s->raw_skill_id[slot]);g.slot=slot;g.effective_slot=s->selected_bank+slot;return g;
|
||||
}
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
# 画面验收:选角页、职业选择页、局内营地各跑一局,出「我方 | 真值」并排图(每次画面修复后跑,Mac 与真机各一套)。
|
||||
# 用法:dm/ios/tools/pages.sh mac|ios 产物:$DM_ROOT/run/ios/pages/<端>_<页>_并排.png(真机另有 <页>_屏幕.png 与三项核对)
|
||||
# 我方图 = 游戏渲染帧(DM_NVN_SHOT,1600x900):选角 / 职业页第 300 帧,局内第 900 帧;并排图下附平均亮度(我方 / 真值);真机另截整个窗口(DM_SCREEN_SHOT,看方向 / 黑边 / 实际显示)
|
||||
# 真值 = $DM_ROOT/run/verify/truth_shots/(Switch 原版,标准存档 save_ref,有 DLC);局内 = $DM_ROOT/run/verify/dm/pq/p0.png(640x360,并排时放大)
|
||||
# 职业页进入键序同 drive.py --newchar-shot:Plus → (战网框)下 → A;进局同 act2 回放:A → (难度框)A
|
||||
# Visual acceptance: one run each for the character select page, class select page and in-game camp, producing "ours | ground truth" side-by-side images (run after every visual fix, one set each for Mac and real device).
|
||||
# Usage: dm/ios/tools/pages.sh mac|ios Output: $DM_ROOT/run/ios/pages/<target>_<page>_并排.png (real device also has <page>_屏幕.png and three checks)
|
||||
# Our image = game render frame (DM_NVN_SHOT, 1600x900): frame 300 for the character select / class pages, frame 900 in-game; mean brightness (ours / ground truth) is appended below the side-by-side image; the real device also captures the whole window (DM_SCREEN_SHOT, to see orientation / black bars / actual display)
|
||||
# Ground truth = $DM_ROOT/run/verify/truth_shots/ (the original Switch game, standard save save_ref, with DLC); in-game = $DM_ROOT/run/verify/dm/pq/p0.png (640x360, enlarged when placed side by side)
|
||||
# Key sequence to enter the class page is the same as drive.py --newchar-shot: Plus → (Battle.net dialog) Down → A; entering the game is the same as the act2 replay: A → (difficulty dialog) A
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
T=${1:?mac 或 ios}; OUT=${DM_OUT:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/3.3.94012-r10}
|
||||
P=${DM_ROOT:-$HOME/dm-work}/run/ios/pages; mkdir -p "$P"; TR=${DM_ROOT:-$HOME/dm-work}/run/verify/truth_shots
|
||||
source tools/local_env.sh && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
|
||||
SAVE_REF=${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref/0000000000000001/0
|
||||
KEYS_CLS='PLUS@OpenPanel:MainMenuButtonRibbon>OpenPanel:OnlinePlayModeModal,DOWN@OnlinePlayModeModal,A@ControllerActionEnd>CharacterCreatePanel'
|
||||
KEYS_GAME='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,MSG:CharacterSelect:LoadCharacter:0@OpenPanel:CharacterSelectPanel%1>FrontEndNavigation:ToGame'
|
||||
keys(){ case $1 in cls) echo "$KEYS_CLS" ;; game) echo "$KEYS_GAME" ;; esac; }
|
||||
frame(){ case $1 in game) echo 900 ;; *) echo 300 ;; esac; } # 局内第 900 帧约 30 秒(含进局读取) | In-game frame 900 is about 30 seconds (including loading on entering the game)
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
truth(){ case $1 in sel) echo "$TR/选角页_saveref_joe_有DLC.png" ;; cls) echo "$TR/职业选择页_有DLC.png" ;; game) echo "${DM_ROOT:-$HOME/dm-work}/run/verify/dm/pq/p0.png" ;; esac; }
|
||||
side(){ # 我方 真值 输出 | ours ground-truth output
|
||||
python3 - "$1" "$2" "$3" <<'PY'
|
||||
import sys; from PIL import Image, ImageDraw
|
||||
a, b = (Image.open(p).convert('RGB').resize((1600, 900)) for p in sys.argv[1:3])
|
||||
o = Image.new('RGB', (3216, 940), (40, 40, 40)); o.paste(a, (0, 40)); o.paste(b, (1616, 40))
|
||||
import numpy as np
|
||||
la, lb = (float(np.asarray(x).mean()) for x in (a, b))
|
||||
d = ImageDraw.Draw(o); d.text((10, 10), f'OURS mean {la:.1f} ' + sys.argv[1].split('/')[-1], fill=(255, 255, 0)); d.text((1626, 10), f'TRUTH (Switch) mean {lb:.1f} ' + sys.argv[2].split('/')[-1], fill=(0, 255, 255))
|
||||
o.save(sys.argv[3]); print(f'平均亮度 我方 {la:.1f} / 真值 {lb:.1f}')
|
||||
PY
|
||||
}
|
||||
rc=0; RUN=$(date +%H%M%S) # 真机截图文件名带本次时刻:Documents 里的旧图不会被当成本次结果 | Real device screenshot file names carry this run's time: old images in Documents will not be mistaken for this run's results
|
||||
[ $T = mac ] && { make -s -C ../host || { t "🔴 Mac 宿主编译失败"; exit 1; }; }
|
||||
[ $T = ios ] && { ./run.sh build > "$P/ios_build.log" 2>&1 || { t "🔴 真机构建失败"; tail -5 "$P/ios_build.log"; exit 1; }; ./run.sh install >> "$P/ios_build.log" 2>&1 || { t "🔴 真机装机失败"; tail -5 "$P/ios_build.log"; exit 1; }; }
|
||||
for pg in ${PAGES:-sel cls game}; do
|
||||
unset DM_KEYS DEVICECTL_CHILD_DM_KEYS
|
||||
if [ $T = mac ]; then
|
||||
rm -f "$P/mac_$pg.png"; rm -rf "$P/save_$pg"; cp -R "$SAVE_REF" "$P/save_$pg" && chmod -R u+w "$P/save_$pg"
|
||||
[ $pg != sel ] && export DM_KEYS="$(keys $pg)"
|
||||
DM_SAVE="$P/save_$pg" DM_UIMSG=1 DM_NVN_SHOT="$(frame $pg):$P/mac_$pg.png" DM_WATCH=$(( $(frame $pg) / 30 + 8 )) ../host/dmhost "$OUT" main sdk > "$P/mac_$pg.log" 2>&1
|
||||
else
|
||||
[ $pg != sel ] && export DEVICECTL_CHILD_DM_KEYS="$(keys $pg)"
|
||||
DEVICECTL_CHILD_DM_SAVE_FRESH=1 DEVICECTL_CHILD_DM_UIMSG=1 DEVICECTL_CHILD_DM_NVN_SHOT="$(frame $pg):shot_${pg}_$RUN.png" DEVICECTL_CHILD_DM_SCREEN_SHOT="$(( $(frame $pg) / 30 + 2 )):screen_${pg}_$RUN.png" \
|
||||
DEVICECTL_CHILD_DM_WATCH=$(( $(frame $pg) / 30 + 6 )) ./run.sh boot 90 > "$P/ios_$pg.run" 2>&1
|
||||
cp "${DM_ROOT:-$HOME/dm-work}/run/ios/out/boot.txt" "$P/ios_$pg.log"
|
||||
rm -f "$P/ios_$pg.png" "$P/ios_screen_$pg.png"
|
||||
for f in shot screen; do for x in png png.txt; do [ $f.$x = shot.png.txt ] && continue
|
||||
dst="$P/ios_$([ $f = screen ] && echo screen_)$pg.$x"
|
||||
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source "Documents/${f}_${pg}_$RUN.$x" --destination "$dst" > /dev/null 2>&1 || { t "🔴 拉回 ${f}_${pg}_$RUN.$x 失败"; rc=1; }
|
||||
done; done
|
||||
t "真机 $pg 屏幕级三项:"; python3 tools/screen_check.py "$P/ios_screen_$pg.png" "$P/ios_screen_$pg.png.txt" "$P/ios_$pg.log" --want "${DM_SCREEN_WANT:-16:9}" || rc=1
|
||||
if [ "${DM_SCREEN_WANT:-16:9}" = full ]; then # 全屏口径另核:② 不拉伸(局内 HUD 球)、④ 输出分辨率 = 前端给的值;③ 安全区只作参考(不留安全区) | Additional checks under the full-screen criterion: ② no stretching (in-game HUD orbs), ④ output resolution = the value given by the front end; ③ safe area for reference only (no safe area is reserved)
|
||||
NEG="${DM_FS_NEG_DIR:-${DM_ROOT:-$HOME/dm-work}/run/ios/fs}/neg_$pg.png"; [ -f "$NEG" ] || NEG="" # 16:9 负对照屏幕截图(DM_GAME_RES=1600x900 跑出,存 fs/neg_<页>.png) | 16:9 negative-control screen capture (produced with DM_GAME_RES=1600x900, saved as fs/neg_<page>.png)
|
||||
t "真机 $pg 全屏核对:"; python3 tools/fullscreen_check.py $pg "$P/ios_screen_$pg.png" "$P/ios_screen_$pg.png.txt" "$P/ios_$pg.log" $NEG || rc=1
|
||||
fi
|
||||
fi
|
||||
[ -f "$P/${T}_$pg.png" ] || { t "🔴 $T $pg 没截到第 $(frame $pg) 帧(看 $P/${T}_$pg.log)"; rc=1; continue; }
|
||||
side "$P/${T}_$pg.png" "$(truth $pg)" "$P/${T}_${pg}_并排.png" && t "$T $pg 并排图:$P/${T}_${pg}_并排.png"
|
||||
done
|
||||
exit $rc
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
# 百宝囊框与「存放」按钮(宿主 dm/host/dm_pouch.c):物品栏面板(手柄 Switch 版布局)底部金币框左右各加一个我们自己的控件。
|
||||
# 左:百宝囊框 = 原版金币框那张底(gen_pouch_art.py 从物品栏底图裁、压窄)+ 原版符文物品图 + 件数;点它宿主出清单(原版说明框样式)。
|
||||
# 右:「存放」= 原版前端小按钮图 FrontEnd_ButtonSmall + 原版字符串 @strGoldDeposit(存放)。
|
||||
# 两个按钮都发 PanelManager:ClosePanel:TouchPouch / TouchStore(空操作,宿主当信号收,同编年史页子页签)。全包在一个容器 TouchPouchBox 里(面板直接子控件数要 ≤ 256,见 touch_layout._RW)。
|
||||
# 坐标:物品栏底图摆在面板 (38 + …) 处、1 像素 = 2 单位,金币框外圈在单位 x 512–906、y 1294–1422;网格 x 216–1196。框与按钮各占金币框两侧的空当。
|
||||
# 宿主按「自定义」页开关把整个容器挪到屏外(关)或挪回(开)
|
||||
# Pouch box and 「存放」(Deposit) button (host dm/host/dm_pouch.c): one widget of our own is added on each side of the gold box at the bottom of the inventory panel (controller Switch layout).
|
||||
# Left: pouch box = the original game's gold box backing (cropped from the inventory base image and narrowed by gen_pouch_art.py) + the original rune item image + piece count; tapping it makes the host show a list (in the original game's tooltip box style).
|
||||
# Right: 「存放」(Deposit) = the original front-end small button image FrontEnd_ButtonSmall + the original string @strGoldDeposit (Deposit).
|
||||
# Both buttons send PanelManager:ClosePanel:TouchPouch / TouchStore (a no-op; the host receives it as a signal, same as the chronicle page's sub-tabs). Everything is wrapped in one container TouchPouchBox (the panel's direct child widget count must be ≤ 256, see touch_layout._RW).
|
||||
# Coordinates: the inventory base image is placed at (38 + ...) in the panel, 1 pixel = 2 units, the gold box's outer ring is at units x 512–906, y 1294–1422; grid x 216–1196. The box and the button each occupy the gap on either side of the gold box.
|
||||
# The host moves the whole container off screen (off) or back (on) according to the switch on the 「自定义」(Custom) page
|
||||
import os, shutil
|
||||
import touch_layout
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
INV = 'controller/console/switch/playerinventoryexpansionlayouthd.json'
|
||||
TIP = 99999 # 说明框缺省在屏外,宿主按字的大小摆 | The tooltip box is off screen by default; the host positions it according to the size of the text
|
||||
|
||||
def widgets():
|
||||
return (' { "type": "Widget", "name": "TouchPouchBox", "children": [\n'
|
||||
' { "type": "ButtonWidget", "name": "TouchPouch", "fields": { "rect": { "x": 222, "y": 1294, "width": 280, "height": 128 }, "filename": "Controller/Panel/zspouch/PouchBox", '
|
||||
'"onClickMessage": "PanelManager:ClosePanel:TouchPouch" } },\n'
|
||||
' { "type": "ImageWidget", "name": "TouchPouchIcon", "fields": { "rect": { "x": 246, "y": 1310, "scale": 0.95 }, "filename": "Items/misc/rune/el_rune" } },\n'
|
||||
' { "type": "TextBoxWidget", "name": "TouchPouchCount", "fields": { "rect": { "x": 350, "y": 1294, "width": 140, "height": 128 }, "text": "0", '
|
||||
'"style": { "fontColor": "$FontColorGoldYellow", "pointSize": "$MediumLargeFontSize", "alignment": { "h": "left", "v": "center" } } } },\n'
|
||||
' { "type": "ButtonWidget", "name": "TouchStore", "fields": { "rect": { "x": 916, "y": 1323, "width": 366, "scale": 0.74 }, "filename": "FrontEnd/HD/Final/FrontEnd_ButtonSmall", "hoveredFrame": 1, '
|
||||
'"textString": "@strGoldDeposit", "textColor": "$LightButtonTextColor", "text/style": "$StyleFEButtonText", "onClickMessage": "PanelManager:ClosePanel:TouchStore" } },\n'
|
||||
' { "type": "NineTileImageWidget", "name": "TouchPouchTipBg", "fields": { "rect": { "x": %d, "y": 0, "width": 700, "height": 400 }, "filename": "PANEL/TooltipBorder/TooltipBorder", "backgroundColor": [0.0, 0.0, 0.0, 0.85], "tileScale": 1.0 } },\n'
|
||||
' { "type": "TextBoxWidget", "name": "TouchPouchTip", "fields": { "rect": { "x": %d, "y": 0, "width": 900, "height": 600 }, "text": "", "fitToText": true, '
|
||||
'"style": { "fontColor": "$FontColorWhite", "pointSize": "$TooltipFontSize", "alignment": { "h": "center", "v": "top" }, "options": { "newlineHandling": "standard" } } } },\n'
|
||||
' ] },\n') % (TIP, TIP)
|
||||
|
||||
def inv_layout(s):
|
||||
if '"TouchPouchBox"' in s: raise SystemExit('pouch_layout:物品栏布局里已经有 TouchPouchBox')
|
||||
i = s.rstrip().rfind(']'); assert s.rstrip().endswith('}') and i > 0
|
||||
return s[:i].rstrip(' ') + widgets() + ' ' + s[i:]
|
||||
|
||||
def build(romfs, outdir, repl):
|
||||
out = {}
|
||||
p = os.path.join(outdir, 'ws_pouchbox.sprite'); shutil.copyfile(os.path.join(__import__('gen_paths').gen_dir('NativeHUD', 'pouch'), 'PouchBox.sprite'), p); out['+data/hd/global/ui/controller/panel/zspouch/pouchbox.sprite'] = p
|
||||
logical = touch_layout.read_layout(romfs, INV)[0].lower(); src = repl.get(logical)
|
||||
text = open(src, encoding='utf-8').read() if src else touch_layout.read_layout(romfs, INV)[1] # 叠在触摸布局已改的那份上(符文之语清单等) | Stacked on the copy already modified by the touch layout (runeword list etc.)
|
||||
p = os.path.join(outdir, 'pouch_' + os.path.basename(INV)); open(p, 'w', encoding='utf-8').write(inv_layout(text)); out[logical] = p
|
||||
return out, {'files': len(out)}
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
# 免费的开发者账号(个人团队)用的工程描述:从 project.yml 去掉它签不了、用不上的东西,写出 project_free.yml(run.sh 在 DM_FREE_ACCOUNT=1 时调)。
|
||||
# 去掉的:
|
||||
# · 六行权限:iCloud 三项、持续执行、增加内存上限、扩展虚拟寻址——免费账号签不了;
|
||||
# · 资源下载扩展(RomfsDownloader 目标、主程序对它的依赖、Info.plist 里托管资源包的三个键)——它只服务「苹果托管资源包」,
|
||||
# 那要通过 TestFlight / 商店分发才有;自己签名装机用不上,却要多占一个应用标识(免费账号 7 天内能新建的标识有上限)。
|
||||
# 去掉后资源照旧走「拷进 App 的文件夹」这条路。
|
||||
# 每一类去掉了几处都核对,对不上就报错不出文件(工程描述改了格式时别悄悄漏删)。
|
||||
# Project description for a free developer account (personal team): removes from project.yml what it cannot sign or has no use for, and writes project_free.yml (called by run.sh when DM_FREE_ACCOUNT=1).
|
||||
# Removed:
|
||||
# · six entitlement lines: the three iCloud items, sustained execution, increased memory limit, extended virtual addressing -- a free account cannot sign them;
|
||||
# · the asset download extension (the RomfsDownloader target, the main app's dependency on it, the three Info.plist keys for hosted asset packs) -- it only serves "Apple-hosted asset packs",
|
||||
# which exist only when distributing through TestFlight / the store; it is of no use when signing and installing yourself, yet takes up one more App ID (a free account has a cap on how many IDs it can create within 7 days).
|
||||
# After removal, assets still go through the "folder copied into the App" path as before.
|
||||
# The number of places removed in each category is checked, and on a mismatch it reports an error and produces no file (so that nothing is silently left unremoved when the project description changes format).
|
||||
import re, sys
|
||||
src, dst = sys.argv[1], sys.argv[2]
|
||||
L = open(src, encoding='utf-8').read().split('\n')
|
||||
ENT = re.compile(r'^ *com\.apple\.developer\.(kernel\.increased-memory-limit|kernel\.extended-virtual-addressing|sustained-execution|icloud-container-identifiers|icloud-services|ubiquity-container-identifiers):')
|
||||
BA = re.compile(r'^ *(BAAppGroupID|BAHasManagedAssetPacks|BAUsesAppleHosting):')
|
||||
out, n_ent, n_ba, n_dep, n_tgt, i = [], 0, 0, 0, 0, 0
|
||||
while i < len(L):
|
||||
l = L[i]
|
||||
if ENT.match(l): n_ent += 1; i += 1; continue
|
||||
if BA.match(l): n_ba += 1; i += 1; continue
|
||||
if re.match(r'^ *- target: RomfsDownloader\b', l): n_dep += 1; i += 1; continue
|
||||
if re.match(r'^ RomfsDownloader:\s*$', l): # 整个目标块:到下一个同级键(两格缩进)为止 | the whole target block: up to the next key at the same level (two-space indent)
|
||||
n_tgt += 1; i += 1
|
||||
while i < len(L) and not re.match(r'^ \S', L[i]) and not re.match(r'^\S', L[i]): i += 1
|
||||
continue
|
||||
out.append(l); i += 1
|
||||
if (n_ent, n_ba, n_dep, n_tgt) != (6, 3, 1, 1): sys.exit('project_free.py:该去掉的东西数目不对(权限 %d / 6、托管资源包键 %d / 3、依赖 %d / 1、扩展目标 %d / 1)——工程描述的写法变了,先改这个脚本' % (n_ent, n_ba, n_dep, n_tgt))
|
||||
if any('RomfsDownloader' in l and not l.lstrip().startswith('#') for l in out): sys.exit('project_free.py:去掉之后工程描述里还有 RomfsDownloader')
|
||||
open(dst, 'w', encoding='utf-8').write('\n'.join(out))
|
||||
@@ -0,0 +1,79 @@
|
||||
"""从玩家自己的游戏文件(Switch 版 RomFS)读原版素材:构建时生成 NativeHUD / TouchArt 等资源用(仓库里不放原版衍生的图和字)。
|
||||
read(romfs, path) 按包内路径(如 'hd/global/ui/PANEL/HUD_02/front_panel.sprite',不分大小写)读出原始字节(build_manifest.psv 定位,同 touch_layout)
|
||||
sprite(romfs, path) 精灵图 → RGBA 整张(多帧横排)。v61 = DXT5 块线性(解块线性用仓库里的 dm/gfx/tex/nvn_deswizzle.c 现编),v31 = 原始 RGBA
|
||||
font(romfs, name) 原版字体写到临时文件,返回路径(PIL ImageFont.truetype 用)
|
||||
out_dir() 生成产物的根目录(gen_paths.gen_dir:环境变量 DM_GEN_ASSETS,缺省 dm/ios/Gen/assets,不进 git)
|
||||
Reads the original game's assets from the player's own game files (Switch RomFS): used at build time to generate resources such as NativeHUD / TouchArt (the repo holds no images or text derived from the original game).
|
||||
read(romfs, path) read raw bytes by path in package (e.g. 'hd/global/ui/PANEL/HUD_02/front_panel.sprite', case-insensitive) (located via build_manifest.psv, same as touch_layout)
|
||||
sprite(romfs, path) sprite → whole RGBA image (multiple frames side by side). v61 = DXT5 block-linear (un-block-linearized with the repo's dm/gfx/tex/nvn_deswizzle.c compiled on the fly), v31 = raw RGBA
|
||||
font(romfs, name) write the original game's font to a temp file and return the path (for PIL ImageFont.truetype)
|
||||
out_dir() root directory of generated build output (gen_paths.gen_dir: environment variable DM_GEN_ASSETS, default dm/ios/Gen/assets, not in git)"""
|
||||
import ctypes as C, io, os, struct, subprocess, tempfile
|
||||
from PIL import Image
|
||||
import touch_layout
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); DM = os.path.normpath(os.path.join(HERE, '..', '..'))
|
||||
|
||||
|
||||
from gen_paths import gen_dir as out_dir # 生成产物的根目录(见 gen_paths.py) | Root directory of generated build output (see gen_paths.py)
|
||||
|
||||
|
||||
class Desc(C.Structure): _fields_ = [('target', C.c_int), ('format', C.c_int), ('flags', C.c_int), ('samples', C.c_int), ('width', C.c_uint32), ('height', C.c_uint32),
|
||||
('depth', C.c_uint32), ('levels', C.c_uint32), ('stride', C.c_uint32), ('pkg_block_h', C.c_int)]
|
||||
class Layout(C.Structure): _fields_ = [('size', C.c_uint64), ('layer_size', C.c_uint64), ('align', C.c_uint32), ('layers', C.c_uint32), ('bpb', C.c_uint32), ('tileH', C.c_uint), ('tileD', C.c_uint)]
|
||||
_lib = None
|
||||
|
||||
|
||||
def lib():
|
||||
"""块线性 ↔ 线性的转换库:仓库里的 nvn_deswizzle.c + nvn_tex.c 现编成动态库(每次进程编一次)。 | Block-linear ↔ linear conversion library: the repo's nvn_deswizzle.c + nvn_tex.c compiled on the fly into a dynamic library (compiled once per process)."""
|
||||
global _lib
|
||||
if _lib is None:
|
||||
p = os.path.join(tempfile.mkdtemp(), 'deswizzle.dll' if os.name == 'nt' else 'deswizzle.dylib')
|
||||
# Windows 上动态库的函数要点名导出才找得到(实测:不带这三项能编能加载,但取不到函数)
|
||||
# On Windows a dynamic library's functions must be exported by name to be found (measured: without these three options it compiles and loads, but the functions cannot be fetched)
|
||||
win = ['-Wl,/EXPORT:nvn_tex_layout', '-Wl,/EXPORT:nvn_deswizzle', '-Wl,/EXPORT:nvn_swizzle'] if os.name == 'nt' else ['-fPIC']
|
||||
subprocess.run(['clang', '-O2', '-shared', *win, '-I' + os.path.join(DM, 'gfx', 'nvn'), '-I' + os.path.join(DM, 'gfx', 'tex'), '-o', p,
|
||||
os.path.join(DM, 'gfx', 'tex', 'nvn_deswizzle.c'), os.path.join(DM, 'gfx', 'nvn', 'nvn_tex.c')], check=True)
|
||||
L = C.CDLL(p); L.nvn_tex_layout.argtypes = [C.POINTER(Desc), C.POINTER(Layout)]
|
||||
L.nvn_deswizzle.argtypes = [C.POINTER(Desc), C.c_uint, C.c_uint, C.c_void_p, C.c_void_p, C.c_size_t]
|
||||
L.nvn_swizzle.argtypes = [C.POINTER(Desc), C.c_uint, C.c_uint, C.c_void_p, C.c_size_t, C.c_void_p]
|
||||
_lib = L
|
||||
return _lib
|
||||
|
||||
|
||||
def read(romfs, path):
|
||||
want = path.lower().lstrip('/')
|
||||
if not want.startswith('data/'): want = 'data/' + want
|
||||
for line in open(os.path.join(romfs, 'data', 'build_manifest.psv'), encoding='utf-8'):
|
||||
f = line.rstrip('\n').split('|')
|
||||
if len(f) >= 11 and f[9].lower().split(':', 1)[-1] == want: return touch_layout._read_entry(romfs, f)
|
||||
raise SystemExit('romfs_art:游戏文件里没有 %s(RomFS 版本不对?要 3.3.94012)' % path)
|
||||
|
||||
|
||||
def dxt5(b, w, h):
|
||||
d = Desc(1, 0x44, 0, 0, w, h, 1, 1, 0, b[23] + 1); pitch = (w + 3) // 4 * 16
|
||||
lin = C.create_string_buffer(pitch * ((h + 3) // 4)); src = C.create_string_buffer(b[40:], len(b) - 40)
|
||||
assert lib().nvn_deswizzle(C.byref(d), 0, 0, src, lin, pitch) == 0
|
||||
hdr = [124, 0x81007, h, w, len(lin), 0, 1] + [0] * 11 + [32, 4, struct.unpack('<I', b'DXT5')[0], 0, 0, 0, 0, 0] + [0x1000, 0, 0, 0, 0]
|
||||
return Image.open(io.BytesIO(b'DDS ' + struct.pack('<31I', *hdr) + lin.raw)).convert('RGBA')
|
||||
|
||||
|
||||
def sprite(romfs, path):
|
||||
b = read(romfs, path); assert b[:4] == b'SpA1', path
|
||||
ver, fw, w, h = struct.unpack_from('<HHII', b, 4)
|
||||
if ver == 61: return dxt5(b, w, h)
|
||||
if ver == 31: return Image.frombytes('RGBA', (w, h), b[40:40 + w * h * 4])
|
||||
raise SystemExit('romfs_art:%s 精灵图版本 %d 不认识' % (path, ver))
|
||||
|
||||
|
||||
def frame(romfs, path, i=0):
|
||||
"""多帧横排的精灵图取第 i 帧(帧宽 = 头里的显示宽)。 | Take frame i of a sprite with multiple frames side by side (frame width = the display width in the header)."""
|
||||
b = read(romfs, path); fw = struct.unpack_from('<H', b, 6)[0]; im = sprite(romfs, path)
|
||||
return im.crop((i * fw, 0, (i + 1) * fw, im.height))
|
||||
|
||||
|
||||
_fonts = {}
|
||||
def font(romfs, name):
|
||||
if name not in _fonts:
|
||||
p = os.path.join(tempfile.mkdtemp(), os.path.basename(name)); open(p, 'wb').write(read(romfs, 'hd/ui/fonts/' + name)); _fonts[name] = p
|
||||
return _fonts[name]
|
||||
@@ -0,0 +1,42 @@
|
||||
# 本机起 iOS 包的「存档钥匙」:在同一台 Mac、同一个容器里跑局,共用 Documents/save.test;多步用例(第一局写、第二局带 DM_SAVE_TEST=1 接着用)
|
||||
# 的两步之间别的线一起局就把它换掉,读数会无声对错档。做法:每条线一把钥匙(环境变量 DM_SAVE_KEY,自己取名),钥匙名下的那份测试存档平时收在
|
||||
# 容器 Data/save.keep.<钥匙>,起局前换进 Documents/save.test,跑完换回去——别的线重置的只是它自己那份。被 smoke_mac.sh、touch_e2e_mac.sh、uireg/run_mac.sh source,
|
||||
# 都在持 macsmoke 锁之后调(同一时刻只有一个调用方在动容器)。
|
||||
# savekey_in <容器 Data 目录> <这一局的环境(空格分隔的 K=V)> 返回非零 = 这一局不许起(已打印红字)
|
||||
# savekey_out <容器 Data 目录> 收尾时调;没换进过就是空操作
|
||||
# 抗中断:换进时写标记 Data/save.test.owner(内容 = 钥匙);局被杀 / 脚本异常退出没来得及换回的,下一个调用方的 savekey_in 先照标记把它归位。
|
||||
# 不带钥匙:一次性的局(带 DM_SAVE_FRESH,或压根不用测试存档)照旧用公共那份;多步接着用的(DM_SAVE_TEST=1 且没带 DM_SAVE_FRESH)拒绝起局。
|
||||
# "Save key" for launching the iOS app on this Mac: runs on the same Mac in the same container share Documents/save.test; between the two steps of a multi-step case (first run writes, second run continues with DM_SAVE_TEST=1)
|
||||
# another developer starting a run replaces it, and the readout is silently checked against the wrong save. What it does: one key per developer (environment variable DM_SAVE_KEY, named as you like); the test save under a key is normally kept in
|
||||
# the container's Data/save.keep.<key>, swapped into Documents/save.test before a run starts and swapped back afterwards -- another developer's reset only touches its own copy. Sourced by smoke_mac.sh, touch_e2e_mac.sh and uireg/run_mac.sh,
|
||||
# always called after taking the macsmoke lock (only one caller touches the container at any moment).
|
||||
# savekey_in <container Data directory> <this run's environment (space-separated K=V)> non-zero return = this run must not start (red text already printed)
|
||||
# savekey_out <container Data directory> call at wrap-up; a no-op if nothing was swapped in
|
||||
# Interruption-proof: on swap-in the marker Data/save.test.owner is written (content = key); if a run was killed / the script exited abnormally before swapping back, the next caller's savekey_in first puts it back according to the marker.
|
||||
# Without a key: one-off runs (with DM_SAVE_FRESH, or not using the test save at all) use the common copy as before; multi-step continuing ones (DM_SAVE_TEST=1 without DM_SAVE_FRESH) are refused.
|
||||
_sk_pub=_public
|
||||
_sk_put_back() { # 把现在 Documents/save.test 这份收回它主人名下,再把公共那份放回原位 | Put the current Documents/save.test back under its owner's name, then put the common copy back in place
|
||||
local C=$1 own; own=$(cat "$C/save.test.owner" 2>/dev/null) || return 0; [ -n "$own" ] || { rm -f "$C/save.test.owner"; return 0; }
|
||||
rm -rf "$C/Documents/save.test.work" "$C/save.keep.$own"
|
||||
[ -d "$C/Documents/save.test" ] && mv "$C/Documents/save.test" "$C/save.keep.$own"
|
||||
[ -d "$C/save.keep.$_sk_pub" ] && mv "$C/save.keep.$_sk_pub" "$C/Documents/save.test"
|
||||
rm -f "$C/save.test.owner"
|
||||
}
|
||||
savekey_in() {
|
||||
local C=$1 env=" ${2:-} " key=${DM_SAVE_KEY:-}
|
||||
[ -f "$C/save.test.owner" ] && { echo "存档钥匙:上一局(钥匙「$(cat "$C/save.test.owner")」)没换回,先归位" >&2; _sk_put_back "$C"; }
|
||||
if [ -z "$key" ]; then
|
||||
case "$env" in *" DM_SAVE_TEST=1 "*) case "$env" in *" DM_SAVE_FRESH="*) ;; *)
|
||||
echo "【红】这一局带 DM_SAVE_TEST=1 接着用上一局的测试存档,却没带存档钥匙:本机容器是各线共用的,两步之间会被别的局换档。给这几步都带上同一个 DM_SAVE_KEY=<你这条线自己取的名字>;这一局不起" >&2; return 1;; esac;; esac
|
||||
return 0
|
||||
fi
|
||||
case "$key" in *[!A-Za-z0-9_.-]*|"$_sk_pub"|"") echo "【红】DM_SAVE_KEY 只能用字母、数字、_ . -,且不能叫 ${_sk_pub};这一局不起" >&2; return 1;; esac
|
||||
rm -rf "$C/Documents/save.test.work" "$C/save.keep.$_sk_pub"
|
||||
[ -d "$C/Documents/save.test" ] && mv "$C/Documents/save.test" "$C/save.keep.$_sk_pub"
|
||||
echo "$key" > "$C/save.test.owner"
|
||||
if [ -d "$C/save.keep.$key" ]; then mv "$C/save.keep.$key" "$C/Documents/save.test"
|
||||
elif [ -d "$C/save.keep.$_sk_pub" ]; then cp -R "$C/save.keep.$_sk_pub" "$C/Documents/save.test" # 这把钥匙第一次用:从公共那份起步 | First use of this key: start from the common copy
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
savekey_out() { [ -f "$1/save.test.owner" ] && _sk_put_back "$1"; return 0; }
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
# 真机屏幕级验收(App 内 DM_SCREEN_SHOT 截整个窗口):核屏幕上实际显示的样子,补 DM_NVN_SHOT 只截游戏渲染帧看不到的问题
|
||||
# (真机目测发现:画面转 90°、横向拉伸、黑边、选角页 3D 场景全黑——渲染帧对拍全过却都没测出)。
|
||||
# 用法:screen_check.py <screen.png> <screen.png.txt> <宿主日志> [--want full|16:9]
|
||||
# ① 方向:界面方向为横屏(UIInterfaceOrientation 3/4),且截图宽 > 高;①b 全屏口径下整列纯黑列数 = 0(内容铺满,不只是视口铺满)
|
||||
# ② 宽高比:日志最后一行「出图视口」—— full:视口占满画布;16:9:视口 16:9 且居中(保底方案);画布比例须等于截图比例(层没跟着转会不等)
|
||||
# ③ 画面不大面积全黑:视口区域内近黑像素(三通道最大值 < 8)占比 ≤ 85%(阈值本工具自定,目前没有共用的全黑阈值)
|
||||
# 退出码 0 = 三项全过。
|
||||
# Real device screen-level acceptance (the in-App DM_SCREEN_SHOT captures the whole window): checks what is actually displayed on screen, covering problems that DM_NVN_SHOT, which captures only the game render frame, cannot see
|
||||
# (found by eye on a real device: picture rotated 90°, horizontal stretching, black bars, the character select page's 3D scene all black -- render-frame comparison all passed yet caught none of them).
|
||||
# Usage: screen_check.py <screen.png> <screen.png.txt> <host log> [--want full|16:9]
|
||||
# ① Orientation: interface orientation is landscape (UIInterfaceOrientation 3/4), and screenshot width > height; ①b under the full-screen criterion the number of entirely black columns = 0 (content fills the screen, not just the viewport)
|
||||
# ② Aspect ratio: the last 「出图视口」(output viewport) line in the log -- full: viewport fills the canvas; 16:9: viewport is 16:9 and centered (fallback scheme); the canvas ratio must equal the screenshot ratio (they differ if the layer did not rotate along)
|
||||
# ③ Picture not largely black: the share of near-black pixels (max of the three channels < 8) within the viewport area ≤ 85% (threshold defined by this tool; there is currently no shared all-black threshold)
|
||||
# Exit code 0 = all three pass.
|
||||
import argparse, re, sys
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('png'); ap.add_argument('meta'); ap.add_argument('log')
|
||||
ap.add_argument('--want', choices=['full', '16:9'], default='full')
|
||||
a = ap.parse_args()
|
||||
BLACK_MAX, BLACK_FRAC = 8, 0.85
|
||||
|
||||
img = np.asarray(Image.open(a.png).convert('RGB')).astype(np.int16)
|
||||
H, W = img.shape[:2]
|
||||
meta = dict(l.split('\t', 1) for l in open(a.meta).read().splitlines() if '\t' in l)
|
||||
orient = int(meta['orientation'])
|
||||
vps = re.findall(r'出图视口 (\d+),(\d+) (\d+)x(\d+) / 画布 (\d+)x(\d+)', open(a.log, errors='replace').read())
|
||||
bad = 0
|
||||
def res(ok, msg):
|
||||
global bad
|
||||
print(('过 ' if ok else '【红】') + msg); bad += not ok
|
||||
|
||||
res(orient in (3, 4) and W > H, f'① 方向:界面方向 {orient}(3/4 = 横屏),截图 {W}x{H}')
|
||||
if not vps:
|
||||
res(False, '② 宽高比:日志里没有「出图视口」行(没出过图?)'); vx = vy = 0; vw, vh, cw, ch = W, H, W, H
|
||||
else:
|
||||
vx, vy, vw, vh, cw, ch = map(int, vps[-1])
|
||||
same = abs(cw / ch - W / H) < 0.01
|
||||
if a.want == 'full': ok = same and vx == 0 and vy == 0 and abs(vw - cw) <= 1 and abs(vh - ch) <= 1; what = '占满画布'
|
||||
else: ok = same and abs(vw / vh - 16 / 9) < 0.01 and abs(2 * vx + vw - cw) <= 1 and abs(2 * vy + vh - ch) <= 1; what = '16:9 居中'
|
||||
res(ok, f'② 宽高比(要{what}):视口 {vx},{vy} {vw}x{vh} / 画布 {cw}x{ch}({cw / ch:.4f});截图比例 {W / H:.4f}')
|
||||
# ①b 内容铺满(视口满不等于内容满—— 全屏两侧各 44 列游戏界面层画的黑柱,原判据测不出):
|
||||
# 取屏幕中间 80% 的行,每列最大亮度 ≤ 1 记为「整列纯黑」。全屏口径须 0 列;16:9 口径只报数(负对照应约 2×260 列)
|
||||
# ①b Content fills the screen (a full viewport does not mean full content -- in full screen, the 44-column black pillars drawn by the game UI layer on each side were not caught by the original criterion):
|
||||
# take the middle 80% of the screen's rows; a column whose max brightness ≤ 1 counts as an "entirely black column". The full-screen criterion requires 0 columns; the 16:9 criterion only reports the count (the negative control should be about 2×260 columns)
|
||||
band = img[int(H * 0.1):int(H * 0.9)].max(axis=(0, 2)); blk = band <= 1; nb = int(blk.sum())
|
||||
lb = int(np.argmax(~blk)) if (~blk).any() else W; rb = int(np.argmax(~blk[::-1])) if (~blk).any() else W
|
||||
if a.want == 'full': res(nb == 0, f'①b 内容铺满:整列纯黑 {nb} 列(左起连续 {lb}、右起连续 {rb};判据 0)')
|
||||
else: print(f' ①b(16:9 口径只报数)整列纯黑 {nb} 列(左起连续 {lb}、右起连续 {rb})')
|
||||
sx, sy = W / cw, H / ch
|
||||
reg = img[int(vy * sy):int((vy + vh) * sy), int(vx * sx):int((vx + vw) * sx)]
|
||||
frac = float((reg.max(axis=2) < BLACK_MAX).mean()) if reg.size else 1.0
|
||||
res(frac <= BLACK_FRAC, f'③ 不大面积全黑:视口区域近黑像素占 {frac * 100:.1f}%(阈值 ≤ {BLACK_FRAC * 100:.0f}%)')
|
||||
sys.exit(1 if bad else 0)
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/bin/bash
|
||||
# 出「壳」:一个不含任何游戏内容、没有签名的安装包。使用者用自己的游戏文件(dm/tools/d2rm_pack.py)把游戏程序与衍生内容
|
||||
# 做进去,再用自签工具整包签名装机——全程不需要 Xcode,也不需要 Mac。
|
||||
# shell_build.sh [ios|mac] ios(缺省)= 真机用的壳;mac = 「Mac 上跑的 iOS 包」变体,只给我们自己在 Mac 上验这条路用
|
||||
# 产物($DM_ROOT/build/shell/<ios|mac>/):
|
||||
# D2RMobile-shell.ipa 壳。里面没有:游戏程序、着色器库、覆盖层、界面素材、任何从游戏文件生成的表
|
||||
# shell_manifest.txt 壳里缺的东西的清单(安装包内路径,一行一个;以 / 结尾 = 整个目录)。d2rm_pack.py 照它核对做全了没有
|
||||
# ref/ 对照:用本机游戏文件生成的那些内容(不发布,只用来核对工具的产出)
|
||||
# 做法:把源码树拷到临时副本里构建,不动当前工作树(三份「从游戏文件生成、编进代码」的文件要换成替身,换在副本里)。
|
||||
# 出壳的这台机器要有游戏文件与全套构建环境(和平时出包一样):要用真实的生成结果定表的大小、定清单。
|
||||
# Build the "shell": an unsigned install package with no game content at all. Users use their own game files (dm/tools/d2rm_pack.py) to put the game program and derived content
|
||||
# into it, then sign the whole package with a sideloading tool and install it -- no Xcode and no Mac needed at any point.
|
||||
# shell_build.sh [ios|mac] ios (default) = the shell for real devices; mac = the "iOS app running on Mac" variant, only for ourselves to verify this path on a Mac
|
||||
# Build outputs ($DM_ROOT/build/shell/<ios|mac>/):
|
||||
# D2RMobile-shell.ipa The shell. Not inside: game program, shader libraries, overlay, UI assets, any table generated from the game files
|
||||
# shell_manifest.txt Manifest of what the shell lacks (paths inside the install package, one per line; ending with / = a whole directory). d2rm_pack.py checks against it whether everything has been made
|
||||
# ref/ Reference: the content generated from this machine's game files (not published, only used to check the tool's output)
|
||||
# Approach: copy the source tree to a temporary copy and build there, leaving the current worktree untouched (the three files "generated from the game files and compiled into the code" have to be replaced with stubs, and the replacing is done in the copy).
|
||||
# The machine that builds the shell must have the game files and the full build environment (same as for a normal package build): the real generation results are needed to fix the table sizes and the manifest.
|
||||
set -u
|
||||
KIND=${1:-ios}; case $KIND in ios|mac) ;; *) echo "用法:shell_build.sh [ios|mac]"; exit 2;; esac
|
||||
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); SRC=$(cd "$HERE/../.." && pwd) # SRC = dm/
|
||||
ROOT=${DM_ROOT:-$HOME/dm-work}; O=$ROOT/build/shell/$KIND; W=$O/tree; DD=$O/dd
|
||||
t() { echo "[$(date +%T)] $*"; }; die() { t "🔴 $*"; exit 1; }
|
||||
mkdir -p "$O" && rm -rf "$W" "$O/ref" "$O/app" "$O/D2RMobile-shell.ipa" "$O/shell_manifest.txt" && mkdir -p "$W" "$O/ref" || die "建不了 $O"
|
||||
rsync -a --exclude '/ios/Gen' --exclude '/ios/DmIOS.xcodeproj' --exclude '.iosdd*' --exclude '/ios/local.env' "$SRC/" "$W/dm/" || die "拷源码树失败"
|
||||
# 壳的包名只是占位:自签工具装机时会换成使用者自己的。团队号同理(不签名,用不到)
|
||||
# The shell's package name is only a placeholder: the sideloading tool replaces it with the user's own at install time. Same for the team ID (not signed, so it is not used)
|
||||
printf 'DM_TEAM_ID=0000000000\nDM_BUNDLE_ID=org.d2rmobile.app\nDM_FREE_ACCOUNT=1\n' > "$O/shell.env"; export DM_LOCAL_ENV=$O/shell.env DM_FREE_ACCOUNT=1 DM_ROOT=$ROOT
|
||||
cd "$W/dm/ios" || die "副本里没有 dm/ios"
|
||||
t "生成(与平时出包同一步:用本机游戏文件)"; DM_GEN_ONLY=1 DM_IOS_DD="$DD" bash run.sh build > "$O/gen.log" 2>&1 || { tail -5 "$O/gen.log"; die "生成失败,日志 $O/gen.log"; }
|
||||
# 三份编进代码的表:真实数据留作对照,源文件换成替身
|
||||
# The three tables compiled into the code: the real data is kept as reference, and the source files are replaced with stubs
|
||||
python3 tools/shell_stubs.py data "$W/dm" "$O/ref/derived.tsv" || die "拆表失败"
|
||||
python3 tools/shell_stubs.py stubs "$W/dm" || die "写替身失败"
|
||||
# 模块映像不进可执行文件:内嵌汇编清空、去掉它的链接参数;打开装载器的壳分支
|
||||
# The module images do not go into the executable: empty the embedded assembly and remove its link flags; turn on the loader's shell branch
|
||||
OUT=$(bash ../tools/product.sh path touch) || die "取不到产物目录"
|
||||
python3 ../tools/guest_dylib.py "$OUT" "$O/ref" main sdk > /dev/null || die "对照用的动态库没写出来"
|
||||
echo '// 壳:模块映像不在可执行文件里(tools/shell_build.sh)' > Gen/embed.S
|
||||
sed -i '' -e 's/ -Wl,-segprot,__DM[A-Za-z0-9]*W,rw,rw//g' -e 's/^OTHER_CFLAGS = \$(inherited) /OTHER_CFLAGS = $(inherited) -DDM_SHELL /' Gen/dm.xcconfig
|
||||
grep -q -- '-DDM_SHELL' Gen/dm.xcconfig && ! grep -q segprot Gen/dm.xcconfig || die "构建配置没改对:$(grep -n 'OTHER_' Gen/dm.xcconfig)"
|
||||
# 真机用的壳同时面向 iPhone 与 iPad(设备族是构建设置,要作为命令行参数传);Mac 变体不传,窗口与坐标换算照开发包
|
||||
# The device shell targets both iPhone and iPad (device family is a build setting and must be passed as a command-line argument); the Mac variant does not pass it, and its window and coordinate mapping follow the dev build
|
||||
if [ "$KIND" = mac ]; then DEST='platform=macOS,arch=arm64,variant=Designed for iPad'; PROD=Release-iphoneos; FAM=; else DEST='generic/platform=iOS'; PROD=Release-iphoneos; FAM=DM_DEVICE_FAMILY=1,2; fi
|
||||
t "构建(不签名)"
|
||||
xcodebuild -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destination "$DEST" -derivedDataPath "$DD" \
|
||||
CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= $FAM build > "$O/build.log" 2>&1 || { grep -E 'error:' "$O/build.log" | head -5; die "构建失败,日志 $O/build.log"; }
|
||||
APP=$(ls -d "$DD"/Build/Products/Release-*/DmIOS.app 2> /dev/null | head -1); [ -d "$APP" ] || die "没找到构建出的 App"
|
||||
cp -R "$APP" "$O/app" || die "拷 App 失败"; A=$O/app
|
||||
# 壳里不该有的:凡是从游戏文件来的,一律搬到 ref/ 对照,并记进清单。下面这张表就是「衍生内容」的全部定义——
|
||||
# 往包里加新的衍生内容时要来这里登记,否则末尾的核对会把它当成壳的一部分发出去(核对:壳里不许出现清单外的大文件 / 图片)。
|
||||
# What must not be in the shell: anything that comes from the game files is moved to ref/ as reference and recorded in the manifest. The table below is the complete definition of "derived content" --
|
||||
# when adding new derived content to the package, register it here, otherwise the check at the end would ship it as part of the shell (check: no large files / images outside the manifest may appear in the shell).
|
||||
: > "$O/shell_manifest.txt"
|
||||
take() { # 安装包内路径(以 / 结尾 = 目录) [nolist = 只搬走、不记进清单:使用者不需要补的东西] | path inside the install package (ending with / = a directory) [nolist = only moved away, not recorded in the manifest: things users do not need to add]
|
||||
local p=${1%/}; [ -e "$A/$p" ] || return 0
|
||||
mkdir -p "$O/ref/$(dirname "$p")" && mv "$A/$p" "$O/ref/$p" || die "搬不走 $p"; [ "${2:-}" = nolist ] || echo "$1" >> "$O/shell_manifest.txt"; }
|
||||
V=$(sed -n 's/^#define DMSH_CHAIN "\(.*\)"/\1/p' ../gfx/nvn/dmsh_chain.h); [ -n "$V" ] && [ -d "$A/msl/b-$V" ] || die "着色器库目录不对(链版本「$V」)"
|
||||
take "msl/b-$V/"; rmdir "$A/msl" 2> /dev/null
|
||||
for d in romfs_overlay romfs_overlay_variants hud_v4_ui mapgoal mercslots; do take "$d/"; done
|
||||
# 测试存档(我们自己的回归用)与老机型补充包的覆盖层(没带补充包时是空目录):壳里不带,使用者也不用补
|
||||
# Test saves (for our own regression) and the overlay of the Legacy Device Pack (an empty directory when no Legacy Device Pack is included): not carried in the shell, and users do not need to add them either
|
||||
for d in save_ref save_ref_warlock romfs_overlay_astc romfs_overlay_astc_variants; do take "$d/" nolist; done
|
||||
for f in "$A"/dm/*.fixups.tsv "$A"/dm/*.gates.tsv "$A"/dm/bootlist.tsv "$A"/dm/main.cuts.tsv "$A"/dm/c1_full.tsv "$A"/dm_native_*.png "$A"/native_art_manifest.json; do [ -e "$f" ] && take "${f#$A/}"; done
|
||||
echo "dm/derived.tsv" >> "$O/shell_manifest.txt"; echo "Frameworks/Guest.framework/" >> "$O/shell_manifest.txt"
|
||||
# 清单与版本信息随壳走(d2rm_pack.py 读它们:壳要的产物代号、着色器链版本对不上就拒绝往里做)
|
||||
# The manifest and version info travel with the shell (d2rm_pack.py reads them: if the build output codename or shader chain version the shell requires does not match, it refuses to pack into it)
|
||||
cp "$O/shell_manifest.txt" "$A/dm/shell_manifest.txt"
|
||||
# 着色器源码摘要与出壳这台机器的 spirv-cross 版本也随壳走:使用者的翻译工具版本不同、翻出来的源码不一样时,d2rm_pack.py 当场报出来
|
||||
# The shader source digest and the spirv-cross version of the machine that built the shell ship with the shell too: when the user's translator version differs and produces different sources, d2rm_pack.py reports it on the spot
|
||||
SD=$(python3 ../tools/d2rm_pack.py --src-digest "$ROOT/build/cache/metal_shader_cache/b-$V") && [ -n "$SD" ] || die "算不出着色器源码摘要"
|
||||
SCV=$(brew list --versions spirv-cross 2> /dev/null | awk '{print $2}')
|
||||
printf 'PRODUCT=%s\nCHAIN=%s\nKIND=%s\nSHADER_SRC=%s\nSPIRV_CROSS=%s\n' "$(head -1 ../PRODUCT)" "$V" "$KIND" "$SD" "${SCV:-unknown}" > "$A/dm/shell_info.txt"
|
||||
# 资源下载扩展:只有走苹果托管资源包的正式包才用;自签装机时扩展还要多占一个应用标识,壳里不带
|
||||
# Asset download extension: only release packages that go through Apple-hosted asset packs use it; when sideloading, the extension would also take up one more App ID, so the shell does not carry it
|
||||
rm -rf "$A/Extensions" "$A/PlugIns"
|
||||
for k in BAAppGroupID BAHasManagedAssetPacks BAUsesAppleHosting; do /usr/libexec/PlistBuddy -c "Delete :$k" "$A/Info.plist" 2> /dev/null; done
|
||||
rm -rf "$A/_CodeSignature" "$A/embedded.mobileprovision"
|
||||
# 核对:壳的可执行文件里没有模块映像节;壳里剩下的文件逐个列出来留档
|
||||
# Check: the shell's executable has no module image sections; the files left in the shell are listed one by one for the record
|
||||
n=$(otool -l "$A/DmIOS" | grep -c -E 'sectname __dm.*x[01]|segname __DM.*W'); [ "$n" = 0 ] || die "壳的可执行文件里还有模块映像节 $n 个"
|
||||
# 再核一道内容:对照数据里的每个字符串(物品名、图标路径、套装名,8 个字符以上的)在壳的任何文件里都搜不到;
|
||||
# 模块映像开头的 64 字节也搜不到(防止哪天又被编进来)
|
||||
# One more check of the content: no string in the reference data (item names, icon paths, set names, those of 8 characters or more) can be found in any file of the shell;
|
||||
# the first 64 bytes of the module images cannot be found either (in case they get compiled in again some day)
|
||||
python3 - "$A" "$O/ref" "$W/dm" <<'PYEOF' || die "壳里搜到了游戏内容(见上)"
|
||||
import os, sys
|
||||
app, ref, src = sys.argv[1:]
|
||||
needles = set()
|
||||
for l in open(os.path.join(ref, 'derived.tsv'), encoding='utf-8'):
|
||||
f = l.rstrip('\n').split('\t')
|
||||
if f[0] in ('VTROW', 'VTSET'): needles.update(x.encode() for x in f[1:] if len(x) >= 8 and not x.lstrip('-').isdigit())
|
||||
g = open(os.path.join(ref, 'Guest.framework', 'Guest'), 'rb').read(); needles.add(g[0x4000:0x4040]); needles.add(g[0x200000:0x200040])
|
||||
# 仓库源码里本来就写着的字符串不算(少数物品名是我们的功能代码里点名用的,随源码公开):副本里三份生成文件此时已是替身,搜到的都是手写源码
|
||||
blob = b'\0'.join(open(os.path.join(d, fn), 'rb').read() for top in ('host', 'gfx', 'ios/Sources') for d, _, fs in os.walk(os.path.join(src, top)) for fn in fs if fn.endswith(('.c', '.m', '.h')))
|
||||
own = {n for n in needles if n in blob}; needles -= own
|
||||
bad = 0
|
||||
for d, _, fs in os.walk(app):
|
||||
for fn in fs:
|
||||
b = open(os.path.join(d, fn), 'rb').read()
|
||||
hit = [n for n in needles if n in b]
|
||||
if hit: bad += 1; print(' %s 里有 %d 处对照内容,如 %r' % (os.path.relpath(os.path.join(d, fn), app), len(hit), hit[0][:40]))
|
||||
print('内容核对:%d 个特征串(另有 %d 个是源码里本来就有的,不算)× %d 个文件,命中 %d 个文件' % (len(needles), len(own), sum(len(fs) for _, _, fs in os.walk(app)), bad)); sys.exit(1 if bad else 0)
|
||||
PYEOF
|
||||
( cd "$A" && find . -type f | sort | while read -r f; do printf '%s\t%s\n' "$(stat -f %z "$f")" "$f"; done ) > "$O/shell_files.tsv"
|
||||
( cd "$O" && rm -rf Payload && mkdir Payload && cp -R app Payload/DmIOS.app && zip -qry D2RMobile-shell.ipa Payload && rm -rf Payload ) || die "打包失败"
|
||||
t "壳:$O/D2RMobile-shell.ipa($(du -h "$O/D2RMobile-shell.ipa" | cut -f1),$(wc -l < "$O/shell_files.tsv" | tr -d ' ') 个文件);缺的内容 $(wc -l < "$O/shell_manifest.txt" | tr -d ' ') 项,清单 $O/shell_manifest.txt"
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
# 壳用:把三份「从游戏文件生成、编进代码」的文件拆成两半——
|
||||
# 数据 → 一份 derived.tsv(随使用者自己的游戏文件生成,放进安装包的 dm/)
|
||||
# 替身 → 同名的三份源文件,里面没有数据,只有大小固定的空表和启动时从 derived.tsv 填表的几行(host/dm_derived_rt.h)
|
||||
# 这样壳的可执行文件里不含这三张表的内容,而用它们的代码(diag.c、dm_vault_ui.c、DmTouchOverlay.m …)一行不用改。
|
||||
# 表的条数会写进替身(数组大小):条数随游戏版本固定,不是游戏内容。
|
||||
# 用法:shell_stubs.py data <dm 目录> <输出 derived.tsv> 读真实的三份生成文件,写数据(d2rm_pack.py 与 shell_build.sh 都用)
|
||||
# shell_stubs.py stubs <dm 目录> 把三份生成文件原地换成替身(只在 shell_build.sh 的临时副本里做)
|
||||
# For the shell: split the three files "generated from the game files and compiled into the code" into two halves --
|
||||
# data → one derived.tsv (generated from the user's own game files, placed in dm/ of the install package)
|
||||
# stubs → three source files of the same names, with no data inside, only fixed-size empty tables and the few lines that fill the tables from derived.tsv at startup (host/dm_derived_rt.h)
|
||||
# This way the shell's executable does not contain the content of these three tables, while the code that uses them (diag.c, dm_vault_ui.c, DmTouchOverlay.m ...) needs not a single line changed.
|
||||
# The entry counts of the tables are written into the stubs (array sizes): the counts are fixed by the game version and are not game content.
|
||||
# Usage: shell_stubs.py data <dm directory> <output derived.tsv> read the three real generated files and write the data (used by both d2rm_pack.py and shell_build.sh)
|
||||
# shell_stubs.py stubs <dm directory> replace the three generated files in place with stubs (done only in shell_build.sh's temporary copy)
|
||||
import os, re, sys
|
||||
|
||||
CSTR = r'"((?:[^"\\]|\\.)*)"'
|
||||
|
||||
|
||||
def unq(s): return bytes(s, 'utf-8').decode('unicode_escape').encode('latin-1').decode('utf-8') if '\\' in s else s
|
||||
|
||||
|
||||
def paths(dm):
|
||||
return (os.path.join(dm, 'host', 'dm_hud_exp.h'), os.path.join(dm, 'host', 'dm_vault_tab.h'), os.path.join(dm, 'ios', 'Sources', 'dm_touch_native_art.c'))
|
||||
|
||||
|
||||
def parse(dm):
|
||||
hud, vault, art = (open(p, encoding='utf-8').read() for p in paths(dm))
|
||||
exp = [int(x) for x in re.search(r'k_exp\[100\] = \{(.*?)\};', hud, re.S).group(1).replace('\n', ' ').split(',') if x.strip()]
|
||||
assert len(exp) == 100, len(exp)
|
||||
parts = [unq(x) for x in re.findall(CSTR, re.search(r'vt_part_name\[VT_NPART\] = \{(.*?)\};', vault).group(1))]
|
||||
rows = [(int(a), int(b), int(c), int(d), int(e), int(f), unq(k), unq(i)) for a, b, c, d, e, f, k, i in
|
||||
re.findall(r'^\s*\{ (\d+), (\d+), (\d+), (\d+), (\d+), (-?\d+), %s, %s \},$' % (CSTR, CSTR), vault, re.M)]
|
||||
sets = [unq(x) for x in re.findall(CSTR, re.search(r'vt_set_key\[\] = \{(.*?)\};', vault).group(1))]
|
||||
assert rows and sets and len(parts) == int(re.search(r'#define VT_NPART (\d+)', vault).group(1))
|
||||
assert vault.count('\n { ') == len(rows), (vault.count('\n { '), len(rows))
|
||||
m = re.search(r'static const struct \{ uint32_t id; int atlas,frame; \} rows\[\]=\{\n(.*?)\n\};', art, re.S)
|
||||
trows = [tuple(int(x) for x in t) for t in re.findall(r'^ \{(\d+),(-?\d+),(-?\d+)\},$', m.group(1), re.M)]
|
||||
assert len(trows) == m.group(1).count('\n') + 1, (len(trows), m.group(1).count('\n') + 1)
|
||||
return exp, parts, rows, sets, trows, (hud, vault, art, m)
|
||||
|
||||
|
||||
def data(dm, dst):
|
||||
exp, parts, rows, sets, trows, _ = parse(dm)
|
||||
L = ['EXP\t' + '\t'.join(map(str, exp[i:i + 10])) for i in range(0, 100, 10)]
|
||||
L += ['VTPART\t' + p for p in parts] + ['VTROW\t' + '\t'.join(map(str, r)) for r in rows] + ['VTSET\t' + s for s in sets]
|
||||
L += ['TAROW\t%d\t%d\t%d' % t for t in trows]
|
||||
for l in L: assert '\n' not in l and l.count('\t') < 16
|
||||
for r in rows: assert '\t' not in r[6] and '\t' not in r[7]
|
||||
with open(dst, 'w', encoding='utf-8', newline='\n') as f: f.write('\n'.join(L) + '\n')
|
||||
return len(exp), len(parts), len(rows), len(sets), len(trows)
|
||||
|
||||
|
||||
def stubs(dm):
|
||||
exp, parts, rows, sets, trows, (hud, vault, art, m) = parse(dm)
|
||||
p_hud, p_vault, p_art = paths(dm)
|
||||
open(p_hud, 'w', encoding='utf-8').write('''// 壳的替身(ios/tools/shell_stubs.py 生成):经验表不编进代码,启动时从安装包的 dm/derived.tsv 读(标签 EXP,每行 10 个)
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include "dm_derived_rt.h"
|
||||
static uint32_t k_exp[100];
|
||||
static void k_exp_row(char **f, int n, void *ctx) { int *i = ctx; for (int k = 0; k < n && *i < 100; k++) k_exp[(*i)++] = (uint32_t)strtoul(f[k], NULL, 10); }
|
||||
__attribute__((constructor)) static void k_exp_load(void) { int i = 0; dm_derived_each("EXP", k_exp_row, &i); }
|
||||
''')
|
||||
open(p_vault, 'w', encoding='utf-8').write('''// 壳的替身(ios/tools/shell_stubs.py 生成):编年史仓库固定表不编进代码,启动时从安装包的 dm/derived.tsv 读
|
||||
// (标签 VTPART / VTROW / VTSET)。条数随游戏版本固定,写成数组大小;内容全在数据文件里。
|
||||
#include "dm_derived_rt.h"
|
||||
#define VT_NPART %d
|
||||
static const char *vt_part_name[VT_NPART];
|
||||
typedef struct { uint8_t kind, part, tier; uint16_t row, lvl; int16_t set; const char *key, *icon; } vt_row;
|
||||
static vt_row vt_rows[%d];
|
||||
#define VT_NROW (int)(sizeof vt_rows / sizeof vt_rows[0])
|
||||
static const char *vt_set_key[%d];
|
||||
#define VT_NSET (int)(sizeof vt_set_key / sizeof vt_set_key[0])
|
||||
static void vt_part_cb(char **f, int n, void *ctx) { int *i = ctx; if (n >= 1 && *i < VT_NPART) vt_part_name[(*i)++] = strdup(f[0]); }
|
||||
static void vt_set_cb(char **f, int n, void *ctx) { int *i = ctx; if (n >= 1 && *i < VT_NSET) vt_set_key[(*i)++] = strdup(f[0]); }
|
||||
static void vt_row_cb(char **f, int n, void *ctx) { int *i = ctx; if (n < 8 || *i >= VT_NROW) return;
|
||||
vt_rows[(*i)++] = (vt_row){ (uint8_t)atoi(f[0]), (uint8_t)atoi(f[1]), (uint8_t)atoi(f[2]), (uint16_t)atoi(f[3]), (uint16_t)atoi(f[4]), (int16_t)atoi(f[5]), strdup(f[6]), strdup(f[7]) }; }
|
||||
__attribute__((constructor)) static void vt_load(void) { int a = 0, b = 0, c = 0;
|
||||
dm_derived_each("VTPART", vt_part_cb, &a); dm_derived_each("VTROW", vt_row_cb, &b); dm_derived_each("VTSET", vt_set_cb, &c);
|
||||
for (int i = a; i < VT_NPART; i++) vt_part_name[i] = ""; for (int i = c; i < VT_NSET; i++) vt_set_key[i] = "";
|
||||
for (int i = b; i < VT_NROW; i++) vt_rows[i] = (vt_row){ .set = -1, .key = "", .icon = "" };
|
||||
if (a != VT_NPART || b != VT_NROW || c != VT_NSET) fprintf(stderr, "[dm] 【红】编年史仓库表没读全:部位 %%d / %%d、条目 %%d / %%d、套装 %%d / %%d\\n", a, VT_NPART, b, VT_NROW, c, VT_NSET); }
|
||||
''' % (len(parts), len(rows), len(sets)))
|
||||
stub = art[:m.start()] + '''static struct { uint32_t id; int atlas,frame; } rows[%d]; /* 壳的替身:技能索引不编进代码,启动时从安装包的 dm/derived.tsv 读(标签 TAROW) */
|
||||
static void ta_row_cb(char **f, int n, void *ctx) { int *i = ctx; if (n < 3 || *i >= (int)(sizeof rows / sizeof rows[0])) return;
|
||||
rows[*i].id = (uint32_t)strtoul(f[0], NULL, 10); rows[*i].atlas = atoi(f[1]); rows[*i].frame = atoi(f[2]); (*i)++; }
|
||||
__attribute__((constructor)) static void ta_load(void) { int i = 0; dm_derived_each("TAROW", ta_row_cb, &i);
|
||||
for (int k = i; k < (int)(sizeof rows / sizeof rows[0]); k++) { rows[k].id = UINT32_MAX - 1; rows[k].atlas = rows[k].frame = -1; }
|
||||
if (i != (int)(sizeof rows / sizeof rows[0])) fprintf(stderr, "[dm] 【红】技能图标索引没读全:%%d / %%d\\n", i, (int)(sizeof rows / sizeof rows[0])); }''' % len(trows) + art[m.end():]
|
||||
stub = stub.replace('#include <stddef.h>', '#include <stddef.h>\n#include "../../host/dm_derived_rt.h"', 1); assert 'dm_derived_rt.h' in stub
|
||||
open(p_art, 'w', encoding='utf-8').write(stub)
|
||||
return len(parts), len(rows), len(sets), len(trows)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) == 4 and sys.argv[1] == 'data': print('derived.tsv:经验 %d、部位 %d、仓库条目 %d、套装 %d、技能索引 %d' % data(sys.argv[2], sys.argv[3]))
|
||||
elif len(sys.argv) == 3 and sys.argv[1] == 'stubs': print('替身已写:部位 %d、仓库条目 %d、套装 %d、技能索引 %d' % stubs(sys.argv[2]))
|
||||
else: sys.exit('用法:shell_stubs.py data <dm 目录> <输出 derived.tsv> | shell_stubs.py stubs <dm 目录>')
|
||||
Executable
+150
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
# 慢帧归因:输出慢帧清单,每帧拆成 CPU 侧 / 等待侧 / GPU 侧。两种输入:
|
||||
# · 宿主日志(boot.txt 或经日志端口实时读回的流,开 DM_SLOWFRAME=1):只含掉帧帧的「[slowframe]\t帧号\t@名=值…」行
|
||||
# 与每 300 帧一行分母,读数阶段分段用同一份日志里的 UIMSG;用法 slowframe.py boot.txt 或 … | slowframe.py -
|
||||
# · 逐帧文件(DM_NVN_TSV,可加 DM_NVN_TSV_CALLS=0)+ 可选 boot 日志:slowframe.py frames.tsv [boot.txt]
|
||||
# --all 连启动 / 读取阶段的慢帧也逐帧列出
|
||||
#
|
||||
# 慢帧口径:上屏间隔 @presented_ms > 16.7×1.5 ms 或 −1(系统丢弃)记一次掉帧;进局前的帧单列。
|
||||
# 无上屏时刻的日志(Mac 无窗口)退回用 @frame_ms > 25 ms,并在表头注明。
|
||||
# 各分项(ms,均为该帧号,即上一次出图调用到本次出图调用之间):
|
||||
# 间隔 @frame_ms 出图线程两次调 QueuePresent 的间隔
|
||||
# CPU @cpu_ms 出图线程本帧在 CPU 上的时间(−1 = 换了线程);其中 @sub_cpu_ms 提交回放、@upload_ms 贴图上传、
|
||||
# @lib_new / @pso_new 同步建库 / 建管线个数;@proc_cpu_ms 全进程所有线程 CPU(看是否别的线程吃满核)
|
||||
# 等待 @wait_ms 取图时按 60 Hz 节拍等(主动让出,不是问题);@pq_wait_ms 等出图队列归还交换链贴图;
|
||||
# 离 CPU 其余 = 间隔 − CPU − 节拍等 − 队列等(锁等待、被抢占、客体同步等)
|
||||
# GPU @gpu_ms 本帧命令缓冲 GPU 忙时之和;@gpu_end_ms − @call_ms = 出图调用后多久 GPU 做完;
|
||||
# @pres_at_ms − @gpu_end_ms = GPU 做完到上屏;@drawable_ms 出图线程等 nextDrawable
|
||||
# Slow-frame attribution: outputs a list of slow frames, each broken into CPU side / wait side / GPU side. Two kinds of input:
|
||||
# · Host log (boot.txt or the stream read back live via the log port, with DM_SLOWFRAME=1): contains only "[slowframe]\tframe number\t@name=value..." lines for dropped frames
|
||||
# and one denominator line per 300 frames; segmentation by reading phase uses the UIMSG in the same log; usage slowframe.py boot.txt or ... | slowframe.py -
|
||||
# · Per-frame file (DM_NVN_TSV, optionally with DM_NVN_TSV_CALLS=0) + optional boot log: slowframe.py frames.tsv [boot.txt]
|
||||
# --all also lists slow frames in the launch / loading phases frame by frame
|
||||
# Slow-frame definition: a present interval @presented_ms > 16.7×1.5 ms or −1 (dropped by the system) counts as one dropped frame; frames before entering the game are listed separately.
|
||||
# Logs without present times (Mac without a window) fall back to @frame_ms > 25 ms, noted in the table header.
|
||||
# Components (ms, all for that frame number, i.e. between the previous frame-output call and this frame-output call):
|
||||
# Interval @frame_ms interval between the frame-output thread's two calls to QueuePresent
|
||||
# CPU @cpu_ms the frame-output thread's time on CPU this frame (−1 = the thread changed); of which @sub_cpu_ms is submission replay, @upload_ms texture upload,
|
||||
# @lib_new / @pso_new the number of synchronous library / pipeline builds; @proc_cpu_ms CPU of all threads in the whole process (to see whether other threads saturate the cores)
|
||||
# Wait @wait_ms waiting on the 60 Hz tick when acquiring the image (a voluntary yield, not a problem); @pq_wait_ms waiting for the frame-output queue to return a swapchain texture;
|
||||
# other off-CPU = interval − CPU − tick wait − queue wait (lock waits, preemption, guest synchronization, etc.)
|
||||
# GPU @gpu_ms sum of GPU busy time of this frame's command buffers; @gpu_end_ms − @call_ms = how long after the frame-output call the GPU finished;
|
||||
# @pres_at_ms − @gpu_end_ms = from GPU finish to present; @drawable_ms the frame-output thread waiting on nextDrawable
|
||||
import re, sys, collections
|
||||
|
||||
PERIOD = 1000 / 60
|
||||
DROP = PERIOD * 1.5
|
||||
|
||||
def load(lines):
|
||||
"""返回 (逐帧字段, 日志分母行 (judged, slow, 判据) 或 None, 原始行列表供分段) | Returns (per-frame fields, log denominator line (judged, slow, criterion) or None, list of raw lines for segmentation)"""
|
||||
F = collections.defaultdict(dict); den = None; raw = []
|
||||
for l in lines:
|
||||
raw.append(l)
|
||||
p = l.rstrip("\n").split("\t")
|
||||
if p[0].endswith("[slowframe]") and len(p) > 2: # 日志行(前面可能带日志前缀) | Log line (may be preceded by a log prefix)
|
||||
if p[1] == "#":
|
||||
kv = dict(x.split("=", 1) for x in p[3:] if "=" in x)
|
||||
den = (int(kv["judged"]), int(kv["slow"]), kv.get("判据", "?"))
|
||||
elif p[1].isdigit():
|
||||
for x in p[2:]:
|
||||
k, _, v = x.partition("=")
|
||||
try: F[int(p[1])][k] = float(v)
|
||||
except ValueError: pass
|
||||
continue
|
||||
if len(p) != 3 or not p[0].isdigit() or not p[1].startswith("@"): continue # 末行可能被截断 | The last line may be truncated
|
||||
try: F[int(p[0])][p[1]] = float(p[2])
|
||||
except ValueError: pass
|
||||
return F, den, raw
|
||||
|
||||
def phases(lines):
|
||||
"""UIMSG 读取画面区间 → (第一次打开读取画面的时刻, [(开, 关)…]);没有任何 UIMSG 行返回 None | UIMSG loading screen intervals → (time the loading screen was first opened, [(open, close)...]); returns None if there are no UIMSG lines at all"""
|
||||
iv, o, first, seen = [], None, None, False
|
||||
for l in lines:
|
||||
if "UIMSG" in l: seen = True
|
||||
m = re.search(r"UIMSG \[([\d.]+)s\] PanelManager (OpenPanel|UnloadPanel) LoadScreenPanel", l)
|
||||
if not m: continue
|
||||
t = float(m.group(1))
|
||||
if m.group(2) == "OpenPanel": o = t; first = t if first is None else first
|
||||
elif o is not None: iv.append((o, t)); o = None
|
||||
if o is not None: iv.append((o, 1e18))
|
||||
return (first, iv) if seen else None
|
||||
|
||||
def phase_of(d, ph):
|
||||
if ph is None or "@t_s" not in d: return "未分段"
|
||||
first, iv = ph
|
||||
t = d["@t_s"]
|
||||
if first is None or t < first: return "前端"
|
||||
return "读取" if any(a <= t <= b for a, b in iv) else "局内"
|
||||
|
||||
def g(d, k):
|
||||
return d.get(k)
|
||||
|
||||
def attribute(d):
|
||||
"""返回 (CPU 侧 ms, 等待侧 ms, 离 CPU 其余 ms, GPU 侧描述, 判定) | Returns (CPU-side ms, wait-side ms, other off-CPU ms, GPU-side description, verdict)"""
|
||||
fr, cpu = g(d, "@frame_ms"), g(d, "@cpu_ms")
|
||||
wait, pq = g(d, "@wait_ms") or 0.0, g(d, "@pq_wait_ms") or 0.0
|
||||
cpu_ok = cpu is not None and cpu >= 0
|
||||
other = fr - cpu - wait - pq if fr is not None and cpu_ok else None
|
||||
call, g1, pres = g(d, "@call_ms"), g(d, "@gpu_end_ms"), g(d, "@pres_at_ms")
|
||||
gpu_after = g1 - call if g1 is not None and call is not None else None
|
||||
disp = pres - g1 if pres is not None and g1 is not None else None
|
||||
# 判定:出图调用间隔没超(CPU 按时交了帧)→ GPU / 显示侧;超了 → 看间隔里最大的一块
|
||||
# Verdict: present call interval not exceeded (the CPU delivered the frame on time) → GPU / display side; exceeded → look at the largest piece within the interval
|
||||
if fr is None: verdict = "缺 @frame_ms"
|
||||
elif fr <= DROP:
|
||||
if gpu_after is not None and gpu_after > PERIOD: verdict = "GPU 侧(出图调用后 %.1f ms 才做完)" % gpu_after
|
||||
elif (g(d, "@drawable_ms") or 0) > PERIOD / 2: verdict = "显示侧(等 drawable %.1f ms)" % d["@drawable_ms"]
|
||||
else: verdict = "CPU 按时、GPU 按时:看前几帧积压 / 系统丢弃"
|
||||
elif not cpu_ok: verdict = "间隔超时,缺 @cpu_ms(旧日志或换线程),无法拆"
|
||||
else:
|
||||
parts = {"CPU": cpu, "队列等": pq, "离 CPU 其余(锁 / 抢占)": other}
|
||||
k = max(parts, key=parts.get)
|
||||
verdict = "%s 主导 %.1f / %.1f ms" % (k, parts[k], fr)
|
||||
return cpu if cpu_ok else None, wait + pq, other, gpu_after, disp, verdict
|
||||
|
||||
def fmt(v, w=6):
|
||||
return ("%*.1f" % (w, v)) if v is not None else " " * (w - 1) + "-"
|
||||
|
||||
def main(argv):
|
||||
args = [a for a in argv if not a.startswith("--")]
|
||||
if not args: sys.exit(__doc__ or "用法:slowframe.py frames.tsv [boot.txt] [--all]")
|
||||
show_all = "--all" in argv
|
||||
src = sys.stdin if args[0] == "-" else open(args[0], errors="replace")
|
||||
F, den, raw = load(src)
|
||||
ph = phases(open(args[1], errors="replace") if len(args) > 1 else raw)
|
||||
frames = sorted(F)
|
||||
has_pres = any("@presented_ms" in F[f] for f in frames)
|
||||
if den is not None: # 日志输入:只有掉帧帧的行,分母来自宿主每 300 帧的统计行 | Log input: only lines for dropped frames; the denominator comes from the host's stats line every 300 frames
|
||||
print(f"# 日志输入(DM_SLOWFRAME):宿主判据 {den[2]},宿主统计 可判 {den[0]} 帧、掉帧 {den[1]} 帧(截至最后一行分母);日志里掉帧行 {len(frames)} 帧")
|
||||
key = "@presented_ms" if has_pres else "@frame_ms"
|
||||
def slow(d):
|
||||
v = d.get(key)
|
||||
return v is not None and (v > DROP or (has_pres and v < 0))
|
||||
judged = [f for f in frames if key in F[f]]
|
||||
S = [f for f in judged if slow(F[f])]
|
||||
n_cpu = sum(1 for f in frames if F[f].get("@cpu_ms", -1) >= 0)
|
||||
print(f"# 帧 {len(frames)}({frames[0] if frames else '-'}–{frames[-1] if frames else '-'});判据 {key} > {DROP:.1f} ms"
|
||||
+ (" 或 −1" if has_pres else "(无上屏时刻,退回出图调用间隔)")
|
||||
+ f";可判 {len(judged)} 帧;有 @cpu_ms {n_cpu} 帧;分段 {'boot 日志' if ph else '无'}")
|
||||
by = collections.Counter(phase_of(F[f], ph) for f in judged)
|
||||
sl = collections.Counter(phase_of(F[f], ph) for f in S)
|
||||
if den is None: print("# 各段 慢帧 / 可判帧:" + ";".join(f"{p} {sl[p]}/{by[p]}" for p in ("前端", "读取", "局内", "未分段") if by[p]))
|
||||
else: print("# 各段 慢帧:" + (";".join(f"{p} {sl[p]}" for p in ("前端", "读取", "局内", "未分段") if sl[p]) or "无"))
|
||||
rows = [f for f in S if show_all or phase_of(F[f], ph) in ("局内", "未分段")]
|
||||
print("帧\tt_s\t阶段\t上屏ms\t间隔ms\tCPU\t其中提交\t上传\t建库/管线\t进程CPU\t节拍+队列等\t离CPU其余\tGPU忙\tGPU完成-调用\t完成-上屏\t等drawable\t前3帧最大间隔\t判定")
|
||||
verdicts = collections.Counter()
|
||||
for f in rows:
|
||||
d = F[f]
|
||||
cpu, waits, other, gafter, disp, verdict = attribute(d)
|
||||
prev = d.get("@prev3_max_frame_ms", max((F[p].get("@frame_ms", 0) for p in range(f - 3, f) if p in F), default=None))
|
||||
verdicts[verdict.split("(")[0].split(" 主导")[0]] += 1
|
||||
cr = "%d/%d" % (d.get("@lib_new", 0), d.get("@pso_new", 0)) if "@lib_new" in d else "-"
|
||||
print("\t".join([str(f), fmt(d.get("@t_s"), 1).strip(), phase_of(d, ph), fmt(d.get("@presented_ms")).strip(), fmt(d.get("@frame_ms")).strip(),
|
||||
fmt(cpu).strip(), fmt(d.get("@sub_cpu_ms")).strip(), fmt(d.get("@upload_ms")).strip(), cr, fmt(d.get("@proc_cpu_ms")).strip(),
|
||||
fmt(waits).strip(), fmt(other).strip(), fmt(d.get("@gpu_ms")).strip(), fmt(gafter).strip(), fmt(disp).strip(),
|
||||
fmt(d.get("@drawable_ms")).strip(), fmt(prev).strip(), verdict]))
|
||||
print("# 列出 %d 帧%s;判定汇总:%s" % (len(rows), "" if show_all else "(只列局内 / 未分段,--all 看全部)",
|
||||
";".join(f"{k} {v}" for k, v in verdicts.most_common()) or "无"))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
Executable
+318
@@ -0,0 +1,318 @@
|
||||
#!/bin/bash
|
||||
# 真机启动冒烟:构建、装机后按次数启动,验证主菜单、进局、撤下加载屏三项。
|
||||
# Real device launch smoke test: build and install, then launch the given number of times, verifying three items: main menu, entering the game, loading screen dismissed.
|
||||
set -u
|
||||
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/local_env.sh" && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
D=$DM_DEVICE
|
||||
B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
|
||||
N=${1:-1}
|
||||
ROOT=${DM_ROOT:-$HOME/dm-work}/run/ios/smoke
|
||||
RUN="$ROOT/$(date +%Y%m%d_%H%M%S)"
|
||||
R=${DM_ROOT:-$HOME/dm-work}/run/ios
|
||||
# 派生数据放被测树自己的 .iosdd(与 accept ⑧ 同):共享 $DM_ROOT/run/ios/dd 会被别的工作树同时构建覆盖,装出签名不全的包(ApplicationVerificationFailed)
|
||||
# Derived data goes in the tree under test's own .iosdd (same as accept ⑧): the shared $DM_ROOT/run/ios/dd gets overwritten by other worktrees building at the same time, installing a package with incomplete signing (ApplicationVerificationFailed)
|
||||
TREE=$(git rev-parse --show-toplevel 2>/dev/null || pwd); DD=$TREE/.iosdd
|
||||
APP=$DD/Build/Products/Release-iphoneos/DmIOS.app
|
||||
KEYS_DEFAULT='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame'
|
||||
KEYS=${SMOKE_KEYS:-$KEYS_DEFAULT}
|
||||
TIMEOUT_BIN=${TIMEOUT_BIN:-$(command -v timeout || command -v gtimeout || true)}
|
||||
|
||||
if [ -z "$TIMEOUT_BIN" ]; then
|
||||
echo "SMOKE RED 0/$N 用时 0 秒"
|
||||
echo "【红】缺少 timeout 命令"
|
||||
exit 2
|
||||
fi
|
||||
case "$N" in
|
||||
''|*[!0-9]*|0) echo "SMOKE RED 0/$N 用时 0 秒"; echo "【红】次数必须是正整数"; exit 2;;
|
||||
esac
|
||||
|
||||
mkdir -p "$RUN"
|
||||
TOOLS=$(cd "$(dirname "$0")" && pwd)
|
||||
# 本机这头的端口每次现取一个空的:两台测试机各有各的设备锁,两边的冒烟会同时跑,写死同一个端口后起的那个转发绑不上、读到的是先起那台的日志
|
||||
# The local end of the port is a free one picked fresh each time: the two test devices each have their own device lock and smoke tests on both run at
|
||||
# the same time; with one hard-coded port the forward started later cannot bind, and what is read is the log of the device started first
|
||||
DEV_PORT=${SMOKE_DEV_PORT:-27100}; LOCAL_PORT=${SMOKE_LOCAL_PORT:-$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1])")}
|
||||
command -v iproxy >/dev/null || { echo "SMOKE RED 0/$N 用时 0 秒"; echo "【红】缺少 iproxy(brew install libimobiledevice)"; exit 2; }
|
||||
# 设备锁:与 run.sh 碰手机路径同一把(dm/ios/tools/devlock.sh:可重入、记 lstart、旧格式锁兼容)
|
||||
# 电量闸(测试机没电关机断了 7 小时):取锁前读电量,< 30% 暂停全部真机局、充到 60% 放行(dm/ios/tools/devbattery.sh)
|
||||
# Device lock: the same one as run.sh's phone-touching paths (dm/ios/tools/devlock.sh: reentrant, records lstart, compatible with old-format locks)
|
||||
# Battery gate (the test device ran out of power and shut down, cutting things off for 7 hours): read the battery level before taking the lock; < 30% pauses all real device runs, released once charged to 60% (dm/ios/tools/devbattery.sh)
|
||||
source "$(dirname "$0")/devbattery.sh"; devbattery_gate || { echo "SMOKE RED 0/$N 用时 0 秒"; echo "【红】电量闸拒绝:${DEVBATTERY_LINE:-}"; exit 2; }; echo "冒烟开跑前 $DEVBATTERY_LINE"
|
||||
source "$(dirname "$0")/devlock.sh"
|
||||
devlock_acquire "${SMOKE_OWNER:-未署名} 冒烟 $(basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")"
|
||||
# 冒烟台账:每次运行(含构建失败 / 被信号中断)追加一行,合入前按 HEAD 查 3/3。
|
||||
# 列:时刻 调用方 被测树 HEAD 未提交改动数 结果 ok/N 用时秒 各次分段 结果目录;未提交改动数 > 0 时这行不能证明 HEAD 冒烟过
|
||||
# 设了 SMOKE_KEYS(自定键序 = 反例 / 专项)的运行,结果列前缀「反例:」,不算该 HEAD 的冒烟记录
|
||||
# Smoke-test ledger (a log of past smoke results, one line per run): every invocation (including build failures / signal interruptions) appends one line; before merge, 3/3 is checked by HEAD.
|
||||
# Columns: time, caller, tree under test, HEAD, number of uncommitted changes, result ok/N, elapsed seconds, per-launch segments, result directory; when the number of uncommitted changes > 0 this line cannot prove HEAD passed the smoke test
|
||||
# For invocations with SMOKE_KEYS set (custom key sequence = negative case / targeted test), the result column is prefixed with 「反例:」(negative case:), and they do not count as that HEAD's smoke-test record
|
||||
LEDGER=${SMOKE_LEDGER:-${DM_ROOT:-$HOME/dm-work}/run/ios/smoke_ledger.tsv}; LEDGER_RES=中断; LEDGER_SEGS=""; ok=0
|
||||
ledger_write() {
|
||||
local top head dirty
|
||||
top=$(git rev-parse --show-toplevel 2>/dev/null || pwd); head=$(git -C "$top" rev-parse HEAD 2>/dev/null || echo 无)
|
||||
dirty=$(git -C "$top" status --porcelain --untracked-files=no 2>/dev/null | wc -l | tr -d ' ')
|
||||
mkdir -p "$(dirname "$LEDGER")"
|
||||
[ -s "$LEDGER" ] || printf '时刻\t调用方\t被测树\tHEAD\t未提交改动\t结果\t成功/次数\t用时秒\t各次分段\t结果目录\n' >> "$LEDGER"
|
||||
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s/%s\t%s\t%s\t%s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "${SMOKE_OWNER:-未署名}" "$top" "$head" "$dirty" \
|
||||
"${SMOKE_KEYS:+反例:}${SMOKE_TEST_STALE:+反例:}$LEDGER_RES" "$ok" "$N" "$(( $(date +%s) - ${T0:-$(date +%s)} ))" "${LEDGER_SEGS:-无}" "$RUN" >> "$LEDGER"
|
||||
}
|
||||
trap 'ledger_write; [ -n "${IPROXY_PID:-}" ] && kill "$IPROXY_PID" 2>/dev/null; devlock_release' EXIT
|
||||
trap 'exit 143' INT TERM # 收信号必须退出(经 EXIT 放锁);只放锁不退出会让本进程继续碰手机而锁已归别人 | On receiving a signal it must exit (releasing the lock via EXIT); releasing the lock without exiting would let this process keep touching the phone while the lock already belongs to someone else
|
||||
|
||||
T0=$(date +%s)
|
||||
echo "SMOKE 开始 $N 次,结果目录 $RUN"
|
||||
|
||||
if ! "$TIMEOUT_BIN" 600s env DM_NOINSTALL=1 DM_IOS_DD="$DD" bash dm/ios/run.sh build >"$RUN/build.log" 2>&1; then
|
||||
LEDGER_RES=构建失败
|
||||
echo "【红】构建失败:$RUN/build.log"
|
||||
echo "SMOKE RED 0/$N 用时 $(( $(date +%s) - T0 )) 秒"
|
||||
exit 2
|
||||
fi
|
||||
if ! "$TIMEOUT_BIN" 60s xcrun devicectl device install app --device "$D" "$APP" >"$RUN/install.log" 2>&1; then
|
||||
LEDGER_RES=装机失败
|
||||
echo "【红】装机失败:$RUN/install.log"
|
||||
echo "SMOKE RED 0/$N 用时 $(( $(date +%s) - T0 )) 秒"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# 端口转发必须点名设备:电脑上插着两台测试机时,不点名的 iproxy 自己挑一台,挑到另一台就是「包在听、这边全程拒连、日志端口零行」
|
||||
# (合批冒烟 0/3:包装在、起在目标机上,转发连的是另一台)。按 DM_DEVICE 查出这台的 UDID;查不到就不跑,不拿「大概是它」去试
|
||||
# Port forwarding must name the device: with two test devices plugged into the computer, an iproxy without a device name picks one by itself, and
|
||||
# picking the other one gives "the app is listening, connections refused here the whole time, zero lines on the log port"
|
||||
# (batch smoke test 0/3: the app was installed and launched on the target device, but the forward was connected to the other one). Look up this device's
|
||||
# UDID from DM_DEVICE; if it cannot be found do not run, and do not try with "probably this one"
|
||||
"$TIMEOUT_BIN" 20s xcrun devicectl list devices --json-output "$RUN/devices.json" >/dev/null 2>&1
|
||||
UDID=$(python3 -c "import json,sys;print(next((d.get('hardwareProperties',{}).get('udid','') for d in json.load(open(sys.argv[1]))['result']['devices'] if sys.argv[2] in (d.get('identifier'), d.get('hardwareProperties',{}).get('udid'))), ''))" "$RUN/devices.json" "$D" 2>/dev/null)
|
||||
if [ -z "$UDID" ]; then
|
||||
LEDGER_RES=查不到设备
|
||||
echo "【红】按 DM_DEVICE 查不到这台设备的 UDID($RUN/devices.json):端口转发没法点名设备"
|
||||
echo "SMOKE RED 0/$N 用时 $(( $(date +%s) - T0 )) 秒"
|
||||
exit 2
|
||||
fi
|
||||
iproxy -u "$UDID" "$LOCAL_PORT:$DEV_PORT" >"$RUN/iproxy.log" 2>&1 & IPROXY_PID=$!
|
||||
sleep 1; kill -0 "$IPROXY_PID" 2>/dev/null || { LEDGER_RES=转发没起来; echo "【红】端口转发没起来($RUN/iproxy.log:$(tail -1 "$RUN/iproxy.log" | cut -c1-120))"; echo "SMOKE RED 0/$N 用时 $(( $(date +%s) - T0 )) 秒"; exit 2; }
|
||||
|
||||
# CoreDeviceService 是本用户的 XPC 服务,结束后下一条 devicectl 自动拉起;实测其坏会话让 launch 拖 37–120 s
|
||||
# CoreDeviceService is this user's XPC service; after it is ended the next devicectl brings it up automatically; measured, its bad sessions make launch drag 37–120 s
|
||||
cds_restart() {
|
||||
local p; p=$(pgrep -u "$(id -u)" -f 'CoreDeviceService.xpc/Contents/MacOS/CoreDeviceService' | head -1)
|
||||
[ -n "$p" ] && { kill -TERM "$p"; for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$p" 2>/dev/null || break; sleep 0.5; done; kill -0 "$p" 2>/dev/null && kill -KILL "$p"; }
|
||||
echo "健康检查:$1 → 重启 CoreDeviceService(原 pid ${p:-无})"; LEDGER_SEGS="${LEDGER_SEGS:+$LEDGER_SEGS;}重启服务:$1"
|
||||
}
|
||||
|
||||
# 设备上本包 DmIOS 的 pid,一行一个。查询失败(devicectl 出错 / 超时 / 输出读不懂)返回 2、不输出——调用处不许把失败当成「没有进程」
|
||||
# The pids of this package's DmIOS on the device, one per line. On query failure (devicectl error / timeout / unreadable output) returns 2 with no output -- the call site must not treat failure as "no process"
|
||||
pids() {
|
||||
local json="$RUN/processes.json"
|
||||
rm -f "$json"
|
||||
# 每次查询都把返回码、用时、报错原文记进结果目录:「拉起前查设备进程表连续失败」两天出现在 12 次合入里,原先报错丢进 /dev/null,一条原文都没留下,定不了因
|
||||
# Every query records its return code, elapsed time and raw error text in the result directory: "querying the device process table before
|
||||
# launch failed repeatedly" showed up in 12 merges over two days, and the errors used to go to /dev/null, leaving not a single line of raw
|
||||
# text, so the cause could not be determined
|
||||
local _s=$(python3 -c 'import time;print(time.time())') _rc
|
||||
"$TIMEOUT_BIN" 15s xcrun devicectl device info processes --device "$D" --json-output "$json" >/dev/null 2>"$RUN/pids_last.err"; _rc=$?
|
||||
echo "$(date +%T) 查进程表 rc=$_rc 用时 $(python3 -c "import time;print(round(time.time()-$_s,2))") 秒;调用方 ${FUNCNAME[1]:-?};$(head -c 300 "$RUN/pids_last.err" | tr '\n' ' ')" >> "$RUN/pids_trace.log"
|
||||
[ $_rc = 0 ] || return 2
|
||||
python3 - "$json" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
try:
|
||||
processes = json.load(open(sys.argv[1]))["result"]["runningProcesses"]
|
||||
except (OSError, KeyError, TypeError, ValueError):
|
||||
raise SystemExit(2)
|
||||
for process in processes:
|
||||
executable = process.get("executable", "")
|
||||
if executable.endswith("DmIOS.app/DmIOS"):
|
||||
print(process["processIdentifier"])
|
||||
PY
|
||||
}
|
||||
|
||||
stop_pid() {
|
||||
local pid=$1
|
||||
"$TIMEOUT_BIN" 15s xcrun devicectl device process terminate --device "$D" --pid "$pid" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
count_lines() {
|
||||
local pattern=$1
|
||||
[ -f "$2" ] || return 0
|
||||
grep -c -- "$pattern" "$2" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# 下一次拉起之前,等上一个本包进程确实从设备进程表里消失(查一次约 0.15 秒)。日志端口关了只说明 App 在退,进程表里还有它的那一小段里发 launch,
|
||||
# 系统会把这次 launch 记到将死的进程头上,随后自己重拉一个不带任何环境变量的实例(没有日志端口、按键脚本、看门狗),后面几次 launch 都只是把它调到前台
|
||||
# (出包冒烟:第 2 次 launch 距第 1 次 quit 约 1 秒,第 2、3 次与玩家路径全是日志端口零行)。超过上限还在 = 不是在退的实例,按 pid 结束并记一行。
|
||||
# Before the next launch, wait until the previous process of this package has really disappeared from the device process table (one query takes about 0.15 seconds). The log port closing only shows the App is exiting; if launch is sent in the short window while the process table still has it,
|
||||
# the system attributes this launch to the dying process, then relaunches on its own an instance without any environment variables (no log port, key script, watchdog), and the following launches merely bring it to the foreground
|
||||
# (packaging smoke test: the 2nd launch was about 1 second after the 1st quit, and the 2nd and 3rd launches and the player path all had zero lines on the log port). Still there past the limit = not an exiting instance; end it by pid and log one line.
|
||||
gone_timeout=${SMOKE_GONE_TIMEOUT:-5}; ENV_RELAUNCH=0
|
||||
wait_gone() {
|
||||
local t0 p q rc lim=$gone_timeout; t0=$(date +%s)
|
||||
while :; do
|
||||
p=$(pids); rc=$?; [ -n "$p" ] && p="$(echo $p) "
|
||||
if [ "$rc" -ne 0 ]; then # 查不到进程表 ≠ 已退出:接着等;查询一直失败到上限就记一行放行(收尾那道检查会再查) | Unable to query the process table ≠ exited: keep waiting; if queries keep failing up to the limit, log one line and let it through (the wrap-up check will query again)
|
||||
if [ $(( $(date +%s) - t0 )) -ge "$lim" ]; then
|
||||
echo "$1:拉起前查设备进程表连续失败 ${lim} 秒,不能确认上一局已退出;最后一次报错:$(head -c 200 "$RUN/pids_last.err" 2>/dev/null | tr '\n' ' ')(逐次记录在 $RUN/pids_trace.log)"; LEDGER_SEGS="${LEDGER_SEGS:+$LEDGER_SEGS;}进程表查询失败:$1"; return
|
||||
fi
|
||||
sleep 0.3; continue
|
||||
fi
|
||||
[ -n "$p" ] || break
|
||||
if [ $(( $(date +%s) - t0 )) -ge "$lim" ]; then
|
||||
echo "$1:拉起前本包进程 pid ${p}等了 ${lim} 秒仍在进程表里,按 pid 结束"; LEDGER_SEGS="${LEDGER_SEGS:+$LEDGER_SEGS;}拉起前强制结束:$1"
|
||||
for q in $p; do stop_pid "$q"; done; t0=$(date +%s); lim=$((lim + 5))
|
||||
fi
|
||||
sleep 0.3
|
||||
done
|
||||
}
|
||||
# 「起来了但没拿到环境」:launch 成功、日志端口零行、设备上却有本包进程。按 pid 结束,由调用处重起一次;单独记数(环境重起),不算红也不吞掉
|
||||
# "Launched but did not get the environment": launch succeeded, zero lines on the log port, yet the device has this package's process. End it by pid and let the call site relaunch once; counted separately (environment relaunch), neither counted as red nor swallowed
|
||||
noenv_instance() {
|
||||
local p q; p=$(pids | tr '\n' ' '); [ -n "$p" ] || return 1
|
||||
ENV_RELAUNCH=$((ENV_RELAUNCH + 1)); echo "$1:launch 成功但日志端口零行,设备上有本包进程 pid ${p}= 起来了但没拿到环境变量;按 pid 结束,重起一次(环境重起累计 ${ENV_RELAUNCH} 次)"
|
||||
for q in $p; do stop_pid "$q"; done; return 0
|
||||
}
|
||||
# 验这两道逻辑用的故障注入(结果记成反例,不算冒烟证据):SMOKE_TEST_STALE=pre 在第 2 次的「等进程消失」之前、=post 在它之后,先拉起一个不带环境变量的实例
|
||||
# Fault injection for verifying these two pieces of logic (results are recorded as negative cases, not counted as smoke-test evidence): SMOKE_TEST_STALE=pre launches an instance without environment variables before the 2nd "wait for the process to disappear", =post after it
|
||||
stale_inject() { ( for v in $(env | sed -n 's/^\(DEVICECTL_CHILD_[A-Z_]*\)=.*/\1/p'); do unset "$v"; done; "$TIMEOUT_BIN" -k 5s 30s xcrun devicectl device process launch --device "$D" "$B" -mode boot >"$RUN/stale_launch.txt" 2>&1 ); sleep 3; echo "故障注入($1):已拉起一个不带环境变量的实例 pid $(pids | tr '\n' ' ')"; }
|
||||
|
||||
find_pid() {
|
||||
pids | awk 'NR == 1 { print; exit }'
|
||||
}
|
||||
|
||||
ok=0
|
||||
known_pk=0
|
||||
main_menu_timeout=${SMOKE_MAIN_MENU_TIMEOUT:-40}
|
||||
game_screen_timeout=${SMOKE_GAME_SCREEN_TIMEOUT:-30}
|
||||
case "$main_menu_timeout:$game_screen_timeout" in
|
||||
''|*[!0-9:]*|*:*:*) echo "SMOKE RED 0/$N 用时 0 秒"; echo "【红】阶段上限必须是非负整数"; exit 2;;
|
||||
esac
|
||||
for i in $(seq 1 "$N"); do
|
||||
OUT="$RUN/$i"
|
||||
mkdir -p "$OUT"
|
||||
START=$(date +%s)
|
||||
attempt=0
|
||||
result=1
|
||||
stage=启动
|
||||
pid=""
|
||||
envre=0
|
||||
CONSOLE="$RUN/console_${i}.txt"
|
||||
: > "$CONSOLE"
|
||||
while [ "$attempt" -lt 3 ]; do
|
||||
attempt=$((attempt + 1))
|
||||
attempt_log="$OUT/console_${attempt}.txt"
|
||||
: > "$attempt_log"
|
||||
export DEVICECTL_CHILD_DM_SAVE_FRESH=warlock
|
||||
export DEVICECTL_CHILD_DM_WATCH=$((main_menu_timeout + game_screen_timeout + 5))
|
||||
export DEVICECTL_CHILD_DM_UIMSG=1
|
||||
export DEVICECTL_CHILD_DM_LOG_PORT=$DEV_PORT
|
||||
export DEVICECTL_CHILD_DM_KEYS="$KEYS"
|
||||
# 日志走 iproxy 读 App 测试端口(logport.py),devicectl 只用来拉起;不带 --terminate-existing:上一局已由 quit 退出,并由 wait_gone 等到进程表里没有它
|
||||
# (--console 首行约 76 s;--terminate-existing 在有存活实例时拖 37–120 s;copy from 文件通道同样卡)
|
||||
# The log is read from the App's test port via iproxy (logport.py), devicectl is only used to launch; no --terminate-existing: the previous run has already exited via quit, and wait_gone has waited until it is gone from the process table
|
||||
# (--console first line about 76 s; --terminate-existing drags 37–120 s when a live instance exists; the copy from file channel stalls the same way)
|
||||
python3 "$TOOLS/logport.py" quit "$LOCAL_PORT" 10 || { echo "第 $i/$N 次:上一局实例 quit 后仍在,改用 devicectl 结束"; for p in $(pids); do stop_pid "$p"; done; }
|
||||
[ "${CDS_DUE:-0}" = 1 ] && { cds_restart "上一局拉起超 10 s"; CDS_DUE=0; }
|
||||
[ "${SMOKE_TEST_STALE:-}" = pre ] && [ "$i" = 2 ] && [ "$envre" = 0 ] && stale_inject pre
|
||||
wait_gone "第 $i 次"
|
||||
[ "${SMOKE_TEST_STALE:-}" = post ] && [ "$i" = 2 ] && [ "$envre" = 0 ] && stale_inject post
|
||||
tA=$(date +%s)
|
||||
"$TIMEOUT_BIN" -k 5s 20s xcrun devicectl device process launch --device "$D" "$B" -mode boot >"$OUT/launch_${attempt}.txt" 2>&1; lrc=$?
|
||||
# 健康检查:拉起失败 / 超时 → 重启本用户 CoreDeviceService 再试一次;成功但 > 10 s → 下一局前重启
|
||||
# Health check: launch failed / timed out → restart this user's CoreDeviceService and try once more; succeeded but > 10 s → restart before the next run
|
||||
if [ "$lrc" -ne 0 ]; then
|
||||
cds_restart "第 $i 次拉起失败(rc=$lrc)"; tA=$(date +%s)
|
||||
"$TIMEOUT_BIN" -k 5s 30s xcrun devicectl device process launch --device "$D" "$B" -mode boot >>"$OUT/launch_${attempt}.txt" 2>&1; lrc=$?
|
||||
elif [ $(( $(date +%s) - tA )) -gt 10 ]; then CDS_DUE=1; fi
|
||||
eval "$(python3 "$TOOLS/logport.py" read "$LOCAL_PORT" "$attempt_log" "$main_menu_timeout" "$game_screen_timeout")"
|
||||
cat "$attempt_log" >> "$CONSOLE"
|
||||
if [ "$result" -ne 0 ] && [ -z "$tL" ] && [ "$lrc" -eq 0 ] && [ "$envre" = 0 ] && noenv_instance "第 $i 次"; then envre=1; attempt=$((attempt - 1)); continue; fi
|
||||
[ "$pk" = 1 ] && { known_pk=1; stage=启动; }
|
||||
chan=""; [ "$lrc" -ne 0 ] && chan="(拉起失败:devicectl 退出码 $lrc)"
|
||||
[ "$result" -ne 0 ] && [ -z "$tL" ] && [ "$lrc" -eq 0 ] && chan="(日志端口零行:App 未监听或 iproxy 不通)"
|
||||
[ "$exited" = 1 ] || chan="$chan(quit 后实例未退)"
|
||||
|
||||
if [ "$result" -eq 0 ]; then
|
||||
break
|
||||
fi
|
||||
if [ "$pk" = 1 ] && [ "$attempt" -lt 3 ]; then
|
||||
echo "第 $i/$N 次出现已知PK,补跑 $((attempt))/2"
|
||||
continue
|
||||
fi
|
||||
break
|
||||
done
|
||||
|
||||
# 分段耗时:连接=发起拉起→日志端口首行(devicectl 取设备隧道的耗时,不是 App 的;只列不判慢),主菜单=首行→MainMenuButtonRibbon,进局=主菜单→ToGame,撤屏=ToGame→读取画面撤下。
|
||||
# 正常值是初估(待真机数据校准):主菜单 10 / 进局 5 / 撤屏 8 s;超过 2 倍标「⚠️慢」
|
||||
# Segment timings: connect = launch issued → first line on the log port (the time devicectl takes to get the device tunnel, not the App's; listed only, not judged slow), main menu = first line → MainMenuButtonRibbon, enter game = main menu → ToGame, screen dismissal = ToGame → loading screen dismissed.
|
||||
# Normal values are initial estimates (to be calibrated with real device data): main menu 10 / enter game 5 / screen dismissal 8 s; over 2× is marked 「⚠️慢」(slow)
|
||||
seg=""; prev=$tA; for kv in "连接:$tL:9999" "主菜单:$tM:10" "进局:$tG:5" "撤屏:$tS:8"; do IFS=: read -r nm tt nv <<<"$kv"; [ -n "$tt" ] || break; d=$((tt - prev)); w=""; [ $d -gt $((nv * 2)) ] && w="⚠️慢"; seg="$seg $nm ${d}s$w"; prev=$tt; done
|
||||
# App 自己的启动 = 日志里「启动计时 … T6 dm_main 前 N ms」(零点 = 进程创建);实测 148–160 ms,超过 500 ms 标慢
|
||||
# The App's own launch = 「启动计时 … T6 dm_main 前 N ms」(launch timing ... T6 before dm_main N ms) in the log (zero point = process creation); measured 148–160 ms, over 500 ms is marked slow
|
||||
t6=$(sed -n 's/.*T6 dm_main 前 \([0-9]*\)\.[0-9]* ms.*/\1/p' "$CONSOLE" 2>/dev/null | head -1)
|
||||
if [ -n "$t6" ]; then w=""; [ "$t6" -gt 500 ] && w="⚠️慢"; seg="$seg 启动(App) ${t6}ms$w"; fi
|
||||
if [ "$result" -eq 0 ]; then
|
||||
echo "第 $i/$N 次 OK:主菜单 $(count_lines MainMenuButtonRibbon "$CONSOLE") 进局 $(count_lines 'FrontEndNavigation ToGame' "$CONSOLE") 撤屏 1,用时 $(( $(date +%s) - START )) 秒;分段$seg"
|
||||
ok=$((ok + 1))
|
||||
LEDGER_SEGS="${LEDGER_SEGS:+$LEDGER_SEGS;}$i:OK$seg"
|
||||
else
|
||||
LEDGER_SEGS="${LEDGER_SEGS:+$LEDGER_SEGS;}$i:RED@$stage$seg"
|
||||
echo "第 $i/$N 次 RED:卡在:${stage}(主菜单 $(count_lines MainMenuButtonRibbon "$CONSOLE")/进局 $(count_lines 'FrontEndNavigation ToGame' "$CONSOLE")/撤屏 0);分段$seg${chan}"
|
||||
fi
|
||||
done
|
||||
|
||||
# 玩家路径:产品缺省下 30 s alarm / 15 s 无进展看门狗曾杀掉桌面启动的 App,而所有测试都显式设 DM_WATCH 从未测到。
|
||||
# 每次冒烟 1 局(不带任何启动参数 = 玩家点图标,原先带 -mode boot,掩盖了缺省模式是探针的缺陷):去掉看门狗与存档等测试变量,只带日志口与按键;进局 35 s 后开暂停菜单(PLUS → R → R)再静置 20 s——跨过两种看门狗门限;反例运行(设了 SMOKE_KEYS)不跑
|
||||
# Player path: under product defaults the 30 s alarm / 15 s no-progress watchdog used to kill an App launched from the home screen, and since all tests explicitly set DM_WATCH this was never caught.
|
||||
# 1 run per smoke test (with no launch arguments at all = the player tapping the icon; previously it carried -mode boot, masking the defect that the default mode was the probe): drop test variables such as watchdog and save, carrying only the log port and keys; 35 s after entering the game open the pause menu (PLUS → R → R) then idle 20 s -- crossing both watchdog thresholds; negative-case runs (SMOKE_KEYS set) do not run it
|
||||
PLAYER_RES=跳过
|
||||
if [ -z "${SMOKE_KEYS:-}" ] && [ "${SMOKE_PLAYER:-1}" = 1 ]; then
|
||||
python3 "$TOOLS/logport.py" quit "$LOCAL_PORT" 10 >/dev/null 2>&1 || for p in $(pids); do stop_pid "$p"; done
|
||||
KP="$KEYS_DEFAULT,PLUS@UnloadPanel:LoadScreenPanel%35>OpenPanel:PlayerInventoryExpansionLayout,R@OpenPanel:PlayerInventoryExpansionLayout%1>OpenPanel:SkillsTreePanel,R@OpenPanel:SkillsTreePanel%1>OpenPanel:PauseLayout"
|
||||
player_once() {
|
||||
wait_gone "玩家路径"
|
||||
env -u DEVICECTL_CHILD_DM_WATCH -u DEVICECTL_CHILD_DM_SAVE_FRESH DEVICECTL_CHILD_DM_SAVE_TEST=1 DEVICECTL_CHILD_DM_LOG_PORT=$DEV_PORT DEVICECTL_CHILD_DM_UIMSG=1 DEVICECTL_CHILD_DM_KEYS="$KP" \
|
||||
"$TIMEOUT_BIN" -k 5s 30s xcrun devicectl device process launch --device "$D" "$B" > "$RUN/player_launch.txt" 2>&1 || { cds_restart "玩家路径拉起失败"; env -u DEVICECTL_CHILD_DM_WATCH -u DEVICECTL_CHILD_DM_SAVE_FRESH DEVICECTL_CHILD_DM_SAVE_TEST=1 DEVICECTL_CHILD_DM_LOG_PORT=$DEV_PORT DEVICECTL_CHILD_DM_UIMSG=1 DEVICECTL_CHILD_DM_KEYS="$KP" "$TIMEOUT_BIN" -k 5s 30s xcrun devicectl device process launch --device "$D" "$B" >> "$RUN/player_launch.txt" 2>&1; }
|
||||
pr=$(python3 "$TOOLS/logport.py" player "$LOCAL_PORT" "$RUN/player.txt" "$main_menu_timeout" 35 20)
|
||||
}
|
||||
player_once
|
||||
# 同上一道防线:玩家路径日志零字节而设备上有本包进程 = 没拿到环境,结束后重起一次
|
||||
# Same line of defense as above: player path log zero bytes while the device has this package's process = the environment was not received; end it and relaunch once
|
||||
[ -s "$RUN/player.txt" ] || { noenv_instance "玩家路径" && player_once; }
|
||||
# 产品缺省必须真出声:玩家路径日志里要有真出声的 AudioOut 打开行,出现「静音接收端」即红
|
||||
# Product defaults must really produce sound: the player path log must contain an AudioOut open line with real sound output, and 「静音接收端」(muted sink) appearing means failure
|
||||
au_real=$(grep -c 'audio::OpenAudioOut .*真出声' "$RUN/player.txt" 2>/dev/null); au_null=$(grep -c 'audio::OpenAudioOut .*静音接收端' "$RUN/player.txt" 2>/dev/null)
|
||||
hud_ok=$(LC_ALL=C grep -a 'dm_hud:' "$RUN/player.txt" 2>/dev/null | LC_ALL=C grep -a -v -c '未读到玩家') # 产品缺省必须读得到受控玩家(同 smoke_mac.sh) | Product defaults must be able to read the controlled player (same as smoke_mac.sh)
|
||||
red_n=$(LC_ALL=C grep -a -c '【红】' "$RUN/player.txt" 2>/dev/null) # 玩家路径日志不许有红行(同 smoke_mac.sh) | The player path log must have no failure lines (same as smoke_mac.sh)
|
||||
if [[ "$pr" == result=0* ]] && [ "${au_real:-0}" -gt 0 ] && [ "${au_null:-0}" = 0 ] && [ "${hud_ok:-0}" -gt 0 ] && [ "${red_n:-0}" = 0 ]; then PLAYER_RES=OK; echo "玩家路径 OK:无看门狗变量,进局 35 s + 暂停菜单 20 s 仍活着;AudioOut 真出声 ${au_real} 路($pr)"
|
||||
else PLAYER_RES=RED; echo "玩家路径 RED:$pr;AudioOut 真出声 ${au_real:-0} 路 / 静音接收端 ${au_null:-0} 路(须真出声 > 0、静音 0);读到玩家状态 ${hud_ok:-0} 行(须 > 0);红行 ${red_n:-0} 条(须 0)"; fi
|
||||
LEDGER_SEGS="${LEDGER_SEGS:+$LEDGER_SEGS;}玩家路径:$PLAYER_RES"
|
||||
fi
|
||||
|
||||
[ "$ENV_RELAUNCH" -gt 0 ] && { echo "环境重起 ${ENV_RELAUNCH} 次(起来的实例没拿到环境变量,已按 pid 结束并重起;不算红)"; LEDGER_SEGS="${LEDGER_SEGS:+$LEDGER_SEGS;}环境重起:${ENV_RELAUNCH}次"; }
|
||||
left=""; left_rc=2
|
||||
for _ in 1 2 3; do left=$(pids) && { left_rc=0; break; }; sleep 2; done # devicectl 偶发失败重试;三次都失败 = 不能确认,按红报 | Retry on sporadic devicectl failures; all three failing = cannot confirm, report as a failure
|
||||
left=$(echo $left)
|
||||
if [ "$left_rc" -ne 0 ]; then
|
||||
echo "【红】结束后查设备进程表 3 次都失败(devicectl 出错 / 超时),不能确认本包已退出"
|
||||
LEDGER_SEGS="${LEDGER_SEGS:+$LEDGER_SEGS;}收尾进程表查询失败"
|
||||
elif [ -n "$left" ]; then
|
||||
echo "【红】结束后仍有本包 DmIOS pid:$left"
|
||||
# 残留实例的 App 端日志(Documents/boot.txt)在结束它之前拉回:下次拉起会清空重写,锁外别的任务一拉起证据就没了
|
||||
# The leftover instance's App-side log (Documents/boot.txt) is pulled back before ending it: the next launch clears and rewrites it, and as soon as another task outside the lock launches, the evidence is gone
|
||||
"$TIMEOUT_BIN" 60s xcrun devicectl device copy from --device "$D" --domain-type appDataContainer --domain-identifier "$B" --source Documents/boot.txt --destination "$RUN/boot_left.txt" >/dev/null 2>&1 \
|
||||
&& echo "残留实例日志:$RUN/boot_left.txt($(grep -c '' "$RUN/boot_left.txt") 行,末行:$(tail -1 "$RUN/boot_left.txt" | cut -c1-80))"
|
||||
for pid in $left; do stop_pid "$pid"; done
|
||||
fi
|
||||
|
||||
elapsed=$(( $(date +%s) - T0 ))
|
||||
if [ "$ok" -eq "$N" ] && [ "$left_rc" -eq 0 ] && [ -z "$left" ] && [ "$PLAYER_RES" != RED ]; then
|
||||
[ "$known_pk" -eq 1 ] && echo "【已知PK】占不到 pthread 键 507:已按规则补跑,最终通过"
|
||||
LEDGER_RES=OK
|
||||
echo "SMOKE OK $ok/$N 用时 $elapsed 秒"
|
||||
exit 0
|
||||
fi
|
||||
[ "$known_pk" -eq 1 ] && echo "【已知PK】占不到 pthread 键 507:已按规则最多补跑 2 次"
|
||||
LEDGER_RES=RED
|
||||
echo "SMOKE RED $ok/$N 用时 $elapsed 秒"
|
||||
exit 1
|
||||
Executable
+279
@@ -0,0 +1,279 @@
|
||||
#!/bin/bash
|
||||
# Mac 上的 iOS 冒烟:同一个 iOS 包(arm64 iphoneos 的 DmIOS.app,不是 Mac 宿主)按「Designed for iPad」在 Apple 芯片 Mac 上原样启动,
|
||||
# 判据与 smoke.sh 相同(主菜单 / 进局 / 撤屏 ×N + 玩家路径 + 真出声),写同一份台账(结果列前缀「Mac:」,末列设备)。做法出处:
|
||||
# SMOKE_MAC_PKG_ONLY=1:只构建、包装、(远端时)传到 smoke_mac_in/<目录名>,不取锁、不跑、不记冒烟台账,末行「SMOKE-MAC 只出包 <路径>」。
|
||||
# 出回归包用(回归包出完不再单跑一次冒烟占 mini 锁,那一遍的第一局本身就验了起包到进局;合入的冒烟门槛仍由 merge.sh 管)。
|
||||
# 用法:smoke_mac.sh <次数>。SMOKE_MAC_HOST=local(缺省)| <ssh 目标,如 用户名@主机>:远端只跑不构建——本机构建、包好后 rsync 过去,结果拉回本机记账。
|
||||
# 能替真机的:iOS 外壳(main.m / front_ios.m / UIKit / 资源定位 / 生命周期)起得来、进得了局、不被看门狗杀、真出声。不能替的:热态、真实触点、A19 GPU 时间、安装。
|
||||
# iOS smoke test on Mac: the same iOS app (arm64 iphoneos DmIOS.app, not the Mac host) launched as is on an Apple silicon Mac as "Designed for iPad",
|
||||
# criteria same as smoke.sh (main menu / enter game / screen dismissal ×N + player path + real sound), written to the same ledger (result column prefixed "Mac:", device in the last column). Source of the method:
|
||||
# SMOKE_MAC_PKG_ONLY=1: only build, wrap, and (when remote) transfer to smoke_mac_in/<directory name>; no lock taken, no run, no smoke-test ledger entry, last line 「SMOKE-MAC 只出包 <路径>」(SMOKE-MAC package only <path>).
|
||||
# For building regression packages (after a regression package is built, no separate smoke test is run to occupy the second Mac's lock; the first run of that pass itself verifies package launch through entering the game; the merge smoke-test gate is still managed by merge.sh).
|
||||
# Usage: smoke_mac.sh <count>. SMOKE_MAC_HOST=local (default) | <ssh target, e.g. user@host>: the remote only runs, does not build -- build and wrap locally, rsync it over, and pull the results back to the local machine for the ledger.
|
||||
# What it can stand in for the real device on: the iOS shell (main.m / front_ios.m / UIKit / resource location / lifecycle) launches, gets into the game, is not killed by the watchdog, really produces sound. What it cannot: thermal state, real touch points, A19 GPU time, installation.
|
||||
set -u # 变量后紧跟中文标点一律写 ${名}:无 UTF-8 区域(ssh 非交互)时 bash 会把标点字节并进变量名(mini「$segs;」报未绑定) | Whenever a variable is immediately followed by Chinese punctuation always write ${name}: without a UTF-8 locale (non-interactive ssh) bash merges the punctuation bytes into the variable name (on the second Mac 「$segs;」 was reported as unbound)
|
||||
N=${1:-1}
|
||||
# 真机档位(缺省开):Mac 上的窗口不是手机的比例和安全区,布局缩放 / 控件内缩 / 命中框和真机不是一套数,「mini 过、真机不同」多次出在这里。
|
||||
# 缺省带上真机的画面分辨率与左右安全区(iPhone 17 Pro Max:2868x1320、左右各 62 点),前端按这块画面矩形摆控件、换算触点。DM_MAC_DEVICE_PROFILE=0 回到按 Mac 窗口原样跑
|
||||
# Real device profile (on by default): a window on Mac does not have the phone's aspect ratio and safe area; layout scale / widget inset / hit boxes are not the same set of numbers as on a real device, and "passes on the second Mac, differs on real device" has come from here many times.
|
||||
# By default it carries the real device's picture resolution and left/right safe areas (iPhone 17 Pro Max: 2868x1320, 62 points on each side), and the front end places widgets and converts touch points by this picture rectangle. DM_MAC_DEVICE_PROFILE=0 goes back to running as-is by the Mac window
|
||||
DEVP=""; [ "${DM_MAC_DEVICE_PROFILE:-1}" != 0 ] && DEVP="--env DM_GAME_RES=2868x1320 --env DM_TEST_SAFE_L=62 --env DM_TEST_SAFE_R=62"
|
||||
# 在有人用着的这台 Mac 上直接跑(不是经 ssh 派到远端那一段)时,出图不走显示节拍:别的窗口把游戏窗口完全盖住,系统就不给它发显示节拍,
|
||||
# 冒烟会红在「显示节拍激活中连续 2.0 秒没回调」(一天里撞了多次,红的是桌面不是改动)。DM_PRESENT_LINK=0 = 自己取 drawable,窗口被盖也照出帧。
|
||||
# 远端(无人桌面的 mini)和真机冒烟仍走缺省的显示节拍那条路,那条路由它们守。要在本机也走显示节拍:SMOKE_MAC_PRESENT_LINK=1。
|
||||
# When run directly on this Mac while someone is using it (not the part dispatched to the remote machine over ssh), presentation does not use the
|
||||
# display link: when other windows completely cover the game window, the system stops sending it display-link ticks,
|
||||
# and the smoke test fails with "no callback for 2.0 consecutive seconds while the display link is active" (hit several times in one day; the failure came
|
||||
# from the desktop state, not from the change under test). DM_PRESENT_LINK=0 = acquire the drawable ourselves, so frames are still presented with the window covered.
|
||||
# The remote machine (the second Mac with an unattended desktop) and real-device smoke tests still take the default display-link path, and that path is
|
||||
# guarded by them. To use the display link on this machine too: SMOKE_MAC_PRESENT_LINK=1.
|
||||
[ -z "${SMOKE_MAC_STAGE:-}" ] && [ "${SMOKE_MAC_PRESENT_LINK:-0}" = 0 ] && DEVP="$DEVP --env DM_PRESENT_LINK=0"
|
||||
# 本脚本运行时要用到的同目录文件,只列这一处:起跑前逐个核在不在(缺了当场红,不跑到一半才报),派到远端时也按这份清单同步。
|
||||
# 新加一个 source / 调用的同目录文件,就加进这里—— 漏了后加的三份,远端一起就报「DM_BUNDLE_ID 未设」,在台账留了假红。
|
||||
# The same-directory files this script needs at run time, listed in this one place only: before starting, each is checked to be present (a missing one is a failure on the spot, not reported halfway through the run), and when dispatching to the remote machine the sync also goes by this list.
|
||||
# When a new same-directory file is sourced / called, add it here -- the three added later were missed, the remote side reported 「DM_BUNDLE_ID 未设」(DM_BUNDLE_ID not set) as soon as it started, and a false failure was left in the ledger.
|
||||
SMOKE_MAC_DEPS="local_env.sh logport.py devlock.sh devbattery.sh cloud_guard.sh save_key.sh launch_guard.sh smoke_touch.txt uireg"
|
||||
_sm_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); _sm_miss=
|
||||
for _sm_f in $SMOKE_MAC_DEPS; do [ -e "$_sm_dir/$_sm_f" ] || _sm_miss="$_sm_miss $_sm_f"; done
|
||||
[ -z "$_sm_miss" ] || { echo "SMOKE-MAC RED 0/${1:-1} 用时 0 秒"; echo "【红】冒烟脚本的依赖文件缺了:${_sm_miss}(目录 ${_sm_dir}),没有起跑"; exit 2; }
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/local_env.sh" # 本机配置(包名、团队号、设备号) | Local config (package name, team ID, device ID)
|
||||
B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
|
||||
TOOLS=$(cd "$(dirname "$0")" && pwd)
|
||||
KEYS_DEFAULT='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame'
|
||||
KEYS=${SMOKE_KEYS:-$KEYS_DEFAULT}
|
||||
case "$N" in ''|*[!0-9]*|0) echo "SMOKE-MAC RED 0/$N 用时 0 秒"; echo "【红】次数必须是正整数"; exit 2;; esac
|
||||
main_menu_timeout=${SMOKE_MAIN_MENU_TIMEOUT:-40}; game_screen_timeout=${SMOKE_GAME_SCREEN_TIMEOUT:-30}
|
||||
|
||||
# ---------- 跑(在放包的那台 Mac 上执行;本机直接调,远端经 ssh 以 SMOKE_MAC_STAGE=run 调)----------
|
||||
# 入参:W = 包好的 <名>.app,RUN = 结果目录。标准输出逐行同 smoke.sh;末行 SMOKE-MAC OK|RED;另写 $RUN/segs.txt 给外层记账
|
||||
# ---------- Run (executed on the Mac holding the package; called directly on the local machine, called over ssh with SMOKE_MAC_STAGE=run on the remote) ----------
|
||||
# Arguments: W = the wrapped <name>.app, RUN = result directory. Stdout line by line same as smoke.sh; last line SMOKE-MAC OK|RED; additionally writes $RUN/segs.txt for the outer layer's ledger
|
||||
run_stage() {
|
||||
local W=$1 RUN=$2 ok=0 known_pk=0 segs="" T0; T0=$(date +%s)
|
||||
exe="$W/Wrapper/DmIOS.app/DmIOS"; mkdir -p "$RUN"
|
||||
[ -x "$exe" ] || { echo "【红】包不完整:$exe"; echo "SMOKE-MAC RED 0/$N 用时 0 秒"; return 2; }
|
||||
# 同一台 Mac 上所有 Mac 冒烟共用一个 App 容器(同一 bundle id:boot.txt、存档会互相覆盖),串行:借设备锁的实现、换一把锁
|
||||
# All Mac smoke tests on the same Mac share one App container (same bundle id: boot.txt and saves would overwrite each other), so they are serialized: borrow the device lock's implementation, with a different lock
|
||||
export DM_DEVLOCK_DIR=${DM_ROOT:-$HOME/dm-work}/run/ios/macsmoke.lock; source "$TOOLS/devlock.sh"; source "$TOOLS/cloud_guard.sh"; source "$TOOLS/save_key.sh"; source "$TOOLS/launch_guard.sh"
|
||||
devlock_acquire "${SMOKE_OWNER:-未署名} Mac 冒烟"
|
||||
# 找实例:系统有时把包迁到随机路径下运行(App Translocation,/private/var/folders/…/d/Wrapper/DmIOS.app/DmIOS),不能按原路径认,按可执行文件后缀认。
|
||||
# iOS 包在 Mac 上同一 bundle id 只能有一个实例(再 open 报 -10670):开跑前已有实例 = 别人的或上次残留的,不替人结束,报出 pid 即红
|
||||
# open 报错时把现场留下(一次合入红:玩家路径两次 open 都报 No such file or directory,90 秒后触摸玩家路径也起不来,下一次合入又好了;当时本机另有两个任务在出冒烟包,故意重叠复现 1 次没复现,因果未定)。
|
||||
# 只取证不改行为:包路径各层在不在、软链指向、挂载表里的 Wrapper、同机上别的构建 / 实例、锁的持有者。下次再撞到,读 $RUN/open_fail_diag.txt
|
||||
# Finding instances: the system sometimes relocates the package to run under a random path (App Translocation, /private/var/folders/.../d/Wrapper/DmIOS.app/DmIOS), so it cannot be matched by the original path; match by executable suffix.
|
||||
# An iOS app on Mac can have only one instance per bundle id (another open reports -10670): an instance already present before starting = someone else's or a leftover from last time; do not end it for them, report the pid and fail
|
||||
# When open fails, keep the evidence (one failed merge: both player path opens reported No such file or directory, 90 seconds later the touch player path could not launch either, and the next merge was fine again; at the time two other tasks on this machine were building smoke-test packages; one deliberate overlap attempt did not reproduce it, causality undetermined).
|
||||
# Evidence only, no behavior change: whether each level of the package path exists, where the symlinks point, the Wrapper in the mount table, other builds / instances on the same machine, the lock holder. Next time it is hit, read $RUN/open_fail_diag.txt
|
||||
open_diag() { { echo "== $(date '+%Y-%m-%d %H:%M:%S') $1"; ls -ld "$W" "$W/Wrapper" "$W/Wrapper/DmIOS.app" "$W/WrappedBundle" "$exe" 2>&1; echo "软链 → $(readlink "$W/WrappedBundle" 2>&1)"; echo "-- 挂载表里的 Wrapper"; mount | grep -F Wrapper;
|
||||
echo "-- 同机的构建 / 实例"; ps -axo pid=,lstart=,command= | grep -E "xcodebuild|/Wrapper/DmIOS\.app/DmIOS|smoke_mac\.sh|touch_e2e" | grep -v grep | cut -c1-260; echo "-- 锁持有者 $(cat "$DM_DEVLOCK_DIR/owner" 2>/dev/null)"; } >> "$RUN/open_fail_diag.txt" 2>&1; }
|
||||
# 只认本包(bundle id = $B):同机还可能跑着回归多实例的重签包 <包名>.reg<N>(各自独立容器),按可执行文件后缀认会把它们当成本包、收尾时一起杀掉。
|
||||
# 查不到 bundle id 的(刚起、系统还没登记)照旧算本包,只排除明确是别的 bundle 的
|
||||
# Only this package is recognized (bundle id = $B): the same machine may also be running the regression multi-instance re-signed packages <package name>.reg<N> (each with its own container); matching by executable suffix would take them as this package and kill them along at wrap-up.
|
||||
# Those whose bundle id cannot be found (just launched, not yet registered by the system) still count as this package; only those clearly belonging to another bundle are excluded
|
||||
pids() { local p b; for p in $(ps -axo pid=,comm= | awk '{ pid=$1; $1=""; sub(/^ /,""); if ($0 ~ /\/Wrapper\/DmIOS\.app\/DmIOS$/) print pid }'); do
|
||||
b=$(lsappinfo info -only bundleID -app "$p" 2>/dev/null | sed -n 's/.*="\(.*\)"$/\1/p'); [ -z "$b" ] || [ "$b" = "$B" ] && echo "$p"; done; }
|
||||
stop_all() { local p; for p in $(pids); do kill -TERM "$p" 2>/dev/null; done; sleep 1; for p in $(pids); do kill -KILL "$p" 2>/dev/null; done; }
|
||||
SK_C=''; CLEAN='stop_all; [ -z "$SK_C" ] || savekey_out "$SK_C"; devlock_release' # 退出钩子由调用处统一挂(外层还要记账),这里只登记要做的清理 | The exit hook is installed centrally by the call site (the outer layer also has to record in the ledger); here only the cleanup to be done is registered
|
||||
container() { local m; for m in "$HOME"/Library/Containers/*/.com.apple.containermanagerd.metadata.plist; do
|
||||
[ "$(/usr/libexec/PlistBuddy -c 'Print :MCMMetadataIdentifier' "$m" 2>/dev/null)" = "$B" ] && { echo "$(dirname "$m")/Data"; return 0; }; done; return 1; }
|
||||
freeport() { python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1])"; }
|
||||
# 资源:容器的 Library/Application Support/romfs/data(与真机开发装机同一位置)。容器由系统在首次启动时建;缺资源就从 SMOKE_MAC_ROMFS 克隆(APFS 克隆不占空间)
|
||||
# iCloud 总闸(tools/cloud_guard.sh):这个脚本起的每一个实例都把云端指到一次性本地目录,不连真实 iCloud
|
||||
# Assets: the container's Library/Application Support/romfs/data (same location as a development install on a real device). The container is created by the system on first launch; missing assets are cloned from SMOKE_MAC_ROMFS (APFS clones take no space)
|
||||
# iCloud master gate (tools/cloud_guard.sh): every instance launched by this script points the cloud at a one-off local directory and does not connect to real iCloud
|
||||
cloud_guard_env "" "" || return 1; local CGA=${CG_ENV:+--env $CG_ENV}
|
||||
local C; C=$(container) || { open -n "$W" $CGA --args -mode boot "${LG_ARGS[@]}"; for _ in $(seq 1 30); do C=$(container) && break; sleep 0.5; done; stop_all; }
|
||||
[ -n "${C:-}" ] || { echo "【红】系统没有给 $B 建容器(首次启动失败?包未签进本机?)"; echo "SMOKE-MAC RED 0/$N 用时 $(( $(date +%s) - T0 )) 秒"; return 2; }
|
||||
# 存档钥匙(tools/save_key.sh):整轮冒烟用自己名下的一份测试存档(缺省钥匙 smoke),不动别的线留在公共位置的那份
|
||||
# Save key (tools/save_key.sh): the whole smoke round uses a test save under its own name (default key smoke) and does not touch the copy other developers leave in the common location
|
||||
SK_C=$C; DM_SAVE_KEY=${DM_SAVE_KEY:-smoke} savekey_in "$C" "" || return 1
|
||||
launch_guard_pre "$C" # 起包不被系统「恢复窗口」弹框挡住(tools/launch_guard.sh) | Keep the launch from being blocked by the system's "restore windows" dialog (tools/launch_guard.sh)
|
||||
local rom="$C/Library/Application Support/romfs" src=${SMOKE_MAC_ROMFS:-${DM_ROOT:-$HOME/dm-work}/build/romfs_zhCN/data}
|
||||
if [ ! -f "$rom/data/.build.config" ]; then
|
||||
[ -f "$src/.build.config" ] || { echo "【红】容器里没有资源,$src 也没有(SMOKE_MAC_ROMFS 指到 romfs 的 data 目录)"; echo "SMOKE-MAC RED 0/$N 用时 0 秒"; return 2; }
|
||||
mkdir -p "$rom" && rm -rf "$rom/data" && cp -cR "$src" "$rom/data" || { echo "【红】克隆资源失败"; return 2; }
|
||||
echo "资源:已从 $src 克隆进容器"
|
||||
fi
|
||||
# 被测机器数据盘余量 < 5 GB 不跑(mini 两次红时数据盘只剩 140–476 MB:仪器原始录制没清;清到 27 GB 后的测量恢复正常。与两次红的因果未做对照)
|
||||
# Do not run when the machine under test's data disk has < 5 GB free (on the two failures on the second Mac the data disk had only 140–476 MB left: raw Instruments recordings had not been cleaned; measurements returned to normal after cleaning to 27 GB. The causal link to the two failures was not tested with a control)
|
||||
local free_gb; free_gb=$(df -g "$HOME" | awk 'NR==2 {print $4}')
|
||||
[ "${free_gb:-0}" -ge 5 ] || { echo "【红】被测机器 $(hostname -s) 数据盘只剩 ${free_gb} GB(< 5 GB),不跑"; echo "SMOKE-MAC RED 0/$N 用时 0 秒"; devlock_release; CLEAN=''; return 2; }
|
||||
# 屏幕睡着时取不到可绘制表面,游戏主线程卡在取图(第 1 局进局后停在拍 4、15 秒看门狗;回溯在 NVN 取图调用里,后两局正常)。跑之前唤醒屏幕并在本次运行期间保持不睡
|
||||
# When the screen is asleep no drawable surface can be obtained and the game main thread stalls acquiring the image (run 1 stopped at tick 4 after entering the game, 15-second watchdog; the backtrace was inside the NVN acquire-image call, the next two runs were normal). Wake the screen before running and keep it awake for the duration of this invocation
|
||||
caffeinate -u -t 3 >/dev/null 2>&1; caffeinate -d -w $$ >/dev/null 2>&1 &
|
||||
local pre; pre=$(pids | tr '\n' ' ')
|
||||
[ -z "$pre" ] || { echo "【红】本机已有 $B 的实例在跑(pid ${pre},非本次启动):先结束它再跑"; echo "SMOKE-MAC RED 0/$N 用时 0 秒"; devlock_release; CLEAN=''; return 2; }
|
||||
for i in $(seq 1 "$N"); do
|
||||
local OUT="$RUN/$i" attempt=0 result=1 stage=启动 START port tA seg prev d w nm tt nv kv chan; mkdir -p "$OUT"; START=$(date +%s)
|
||||
local pk=0 tL="" tM="" tG="" tS="" exited=1
|
||||
while [ "$attempt" -lt 3 ]; do
|
||||
attempt=$((attempt + 1)); port=$(freeport); tA=$(date +%s)
|
||||
open -n "$W" $DEVP $CGA --env DM_SAVE_FRESH=warlock --env DM_WATCH=$((main_menu_timeout + game_screen_timeout + 5)) --env DM_UIMSG=1 --env DM_LOG_PORT="$port" --env "DM_KEYS=$KEYS" \
|
||||
--args -mode boot "${LG_ARGS[@]}" > "$OUT/launch_${attempt}.txt" 2>&1; local lrc=$?
|
||||
[ "$lrc" -ne 0 ] && [ -z "$(pids)" ] && { sleep 2; echo "第 $i 次:open 失败($(tail -1 "$OUT/launch_${attempt}.txt" | cut -c1-80)),重试一次"; open -n "$W" $DEVP $CGA --env DM_SAVE_FRESH=warlock --env DM_WATCH=$((main_menu_timeout + game_screen_timeout + 5)) --env DM_UIMSG=1 --env DM_LOG_PORT="$port" --env "DM_KEYS=$KEYS" --args -mode boot "${LG_ARGS[@]}" >> "$OUT/launch_${attempt}.txt" 2>&1; lrc=$?; tA=$(date +%s); }
|
||||
eval "$(python3 "$TOOLS/logport.py" read "$port" "$OUT/console_${attempt}.txt" "$main_menu_timeout" "$game_screen_timeout")"
|
||||
cat "$OUT/console_${attempt}.txt" >> "$RUN/console_${i}.txt"
|
||||
chan=""; [ "$lrc" -ne 0 ] && chan="(open 退出码 ${lrc})"
|
||||
[ "$result" -ne 0 ] && [ -z "$tL" ] && [ "$lrc" -eq 0 ] && chan="(日志端口零行:App 没起来或未监听)"
|
||||
[ "$exited" = 1 ] || { chan="${chan}(quit 后实例未退)"; stop_all; }
|
||||
[ "$result" -eq 0 ] && break
|
||||
[ "$pk" = 1 ] && [ "$attempt" -lt 3 ] && { known_pk=1; echo "第 $i/$N 次出现已知PK,补跑 $attempt/2"; continue; }
|
||||
break
|
||||
done
|
||||
seg=""; prev=$tA; for kv in "启动:$tL:3" "主菜单:$tM:10" "进局:$tG:5" "撤屏:$tS:8"; do IFS=: read -r nm tt nv <<<"$kv"; [ -n "$tt" ] || break; d=$((tt - prev)); w=""; [ $d -gt $((nv * 2)) ] && w="⚠️慢"; seg="$seg $nm ${d}s$w"; prev=$tt; done
|
||||
if [ "$result" -eq 0 ]; then ok=$((ok + 1)); segs="${segs:+${segs};}$i:OK$seg"; echo "第 $i/$N 次 OK:用时 $(( $(date +%s) - START )) 秒;分段$seg"
|
||||
else segs="${segs:+${segs};}$i:RED@$stage$seg"; echo "第 $i/$N 次 RED:卡在:${stage};分段$seg${chan}"; fi
|
||||
done
|
||||
# 玩家路径:不带 -mode、不带看门狗与存档变量(= 玩家点图标),进局 35 s 后开暂停菜单再静置 20 s;须真出声
|
||||
# Player path: no -mode, no watchdog or save variables (= the player tapping the icon), 35 s after entering the game open the pause menu then idle 20 s; must really produce sound
|
||||
local PLAYER_RES=跳过
|
||||
if [ -z "${SMOKE_KEYS:-}" ] && [ "${SMOKE_PLAYER:-1}" = 1 ]; then
|
||||
stop_all; local port pr au_real au_null hud_ok red_n; port=$(freeport)
|
||||
local KP="$KEYS_DEFAULT,PLUS@UnloadPanel:LoadScreenPanel%35>OpenPanel:PlayerInventoryExpansionLayout,R@OpenPanel:PlayerInventoryExpansionLayout%1>OpenPanel:SkillsTreePanel,R@OpenPanel:SkillsTreePanel%1>OpenPanel:PauseLayout"
|
||||
# 有一次合入在 mini 上这一步报「Launch failed … Launchd job spawn failed(POSIX 162)」、日志 0 行,原样重跑即过;原因没查到(系统日志读不到),
|
||||
# 当时台账里 mini 上没有别的 Mac 冒烟在跑(锁落在被测机器上:run_stage 在哪台跑就锁哪台的 macsmoke.lock)。本机没有实例在跑时等 2 秒重试一次,两次的报错都留在 player_launch.txt
|
||||
# Once during a merge this step on the second Mac reported "Launch failed ... Launchd job spawn failed (POSIX 162)" with 0 log lines, and passed when rerun unchanged; the cause was not found (the system log could not be read),
|
||||
# at the time the ledger showed no other Mac smoke test running on the second Mac (the lock lives on the machine under test: whichever machine run_stage runs on, that machine's macsmoke.lock is taken). When no instance is running on this machine, wait 2 seconds and retry once; both error messages are kept in player_launch.txt
|
||||
open -n "$W" $DEVP $CGA --env DM_SAVE_TEST=1 --env DM_LOG_PORT="$port" --env DM_UIMSG=1 --env "DM_KEYS=$KP" > "$RUN/player_launch.txt" 2>&1 \
|
||||
|| { [ -z "$(pids)" ] && { sleep 2; echo "玩家路径:open 失败($(tail -1 "$RUN/player_launch.txt" | cut -c1-80)),重试一次"; open_diag 玩家路径; open -n "$W" $DEVP $CGA --env DM_SAVE_TEST=1 --env DM_LOG_PORT="$port" --env DM_UIMSG=1 --env "DM_KEYS=$KP" >> "$RUN/player_launch.txt" 2>&1; }; }
|
||||
pr=$(python3 "$TOOLS/logport.py" player "$port" "$RUN/player.txt" "$main_menu_timeout" 35 20)
|
||||
au_real=$(grep -c 'audio::OpenAudioOut .*真出声' "$RUN/player.txt" 2>/dev/null); au_null=$(grep -c 'audio::OpenAudioOut .*静音接收端' "$RUN/player.txt" 2>/dev/null)
|
||||
# 产品缺省必须读得到受控玩家(UIKit 底栏数字与难度条靠它;曾经拍入口只在带测试变量时才挂,玩家路径下一直没有)
|
||||
# Product defaults must be able to read the controlled player (the UIKit bottom bar numbers and difficulty bar rely on it; the tick entry used to be hooked only when test variables were set, so it was always missing on the player path)
|
||||
hud_ok=$(LC_ALL=C grep -a 'dm_hud:' "$RUN/player.txt" 2>/dev/null | LC_ALL=C grep -a -v -c '未读到玩家')
|
||||
# 玩家路径日志不许有红行(产品缺省路径上的常驻红行 = 没人看的告警;曾经每次启动有 14 条面板栈假红)
|
||||
# The player path log must have no failure lines (a permanent failure line on the product default path = an alarm nobody looks at; there used to be 14 false panel-stack failures at every launch)
|
||||
red_n=$(LC_ALL=C grep -a -c '【红】' "$RUN/player.txt" 2>/dev/null)
|
||||
if [[ "$pr" == result=0* ]] && [ "${au_real:-0}" -gt 0 ] && [ "${au_null:-0}" = 0 ] && [ "${hud_ok:-0}" -gt 0 ] && [ "${red_n:-0}" = 0 ]; then PLAYER_RES=OK; echo "玩家路径 OK:进局 35 s + 暂停菜单 20 s 仍活着;AudioOut 真出声 ${au_real} 路(${pr})"
|
||||
else PLAYER_RES=RED; echo "玩家路径 RED:${pr};AudioOut 真出声 ${au_real:-0} 路 / 静音接收端 ${au_null:-0} 路(须真出声 > 0、静音 0);读到玩家状态 ${hud_ok:-0} 行(须 > 0);红行 ${red_n:-0} 条(须 0):$(LC_ALL=C grep -a -m1 '【红】' "$RUN/player.txt" 2>/dev/null | cut -c1-80)"; fi
|
||||
segs="${segs:+${segs};}玩家路径:$PLAYER_RES"
|
||||
fi
|
||||
# 触摸玩家路径:从空存档起,只用触点——点职业、创建、选模式、起名 → 进局;不碰摇杆点三下空地坐标不变;点脚下的小站开小站面板(进局落在小站上,营地 NPC 都不在画面里;按类号 tap_unit 落真实触点,走世界点按 → 交互同一条路)。
|
||||
# 固定种子与时间(NPC 站位要可重复,触点脚本是盲点);其余是产品缺省。排在玩家路径之后:它把 save.test 清空了
|
||||
# Touch player path: starting from an empty save, using touch points only -- tap the class, create, choose mode, name → enter the game; without touching the stick, tap empty ground three times and the coordinates stay unchanged; tap the waypoint underfoot to open the waypoint panel (the game is entered standing on the waypoint, with none of the camp NPCs in view; tap_unit by class number lands a real touch point, going through the same world tap → interact path).
|
||||
# Fixed seed and time (NPC positions must be repeatable, the touch point script taps blind); the rest are product defaults. Placed after the player path: it empties save.test
|
||||
local TOUCH_RES=跳过
|
||||
if [ -z "${SMOKE_KEYS:-}" ] && [ "${SMOKE_TOUCH:-1}" = 1 ]; then
|
||||
stop_all; local tport tr p0 p1 nt dlg; tport=$(freeport)
|
||||
cp "${SMOKE_TOUCH_SCRIPT:-$TOOLS/smoke_touch.txt}" "$C/Documents/smoke_touch.txt" # SMOKE_TOUCH_SCRIPT:换一份脚本(验判据会不会红用) | SMOKE_TOUCH_SCRIPT: substitute another script (for verifying whether the criterion will fail)
|
||||
# smoke_touch.txt 的裸坐标是按 667x375 的 16:9 画面写的:带 DM_TOUCH_REF=667x375 由前端按游戏画面矩形换算(界面按画面高缩放、水平居中),
|
||||
# 所以真机档位(画面 2.17:1、上下留边)与原样档位(DM_MAC_DEVICE_PROFILE=0,换算为恒等)用同一份脚本
|
||||
# The bare coordinates in smoke_touch.txt are written for a 667x375 16:9 picture: with DM_TOUCH_REF=667x375 the front end converts by the game picture rectangle (UI scaled by picture height, horizontally centered),
|
||||
# so the real device profile (picture 2.17:1, margins top and bottom) and the as-is profile (DM_MAC_DEVICE_PROFILE=0, conversion is the identity) use the same script
|
||||
open -n "$W" $DEVP $CGA --env DM_TOUCH_REF=667x375 --env DM_SAVE_FRESH=empty --env DM_LOG_PORT="$tport" --env DM_UIMSG=1 --env DM_TOUCH_SCRIPT=smoke_touch.txt --env DM_TOUCH_SCRIPT_START=menu \
|
||||
--env DM_GAME_SEED=0x12345678 --env DM_FIXED_TIME=1790000000 > "$RUN/touch_launch.txt" 2>&1 || open_diag 触摸玩家路径
|
||||
tr=$(python3 "$TOOLS/logport.py" until "$tport" "$RUN/touch.txt" $((main_menu_timeout + 50)) '[script] 全部')
|
||||
p0=$(LC_ALL=C grep -a '\[script\] pos ' "$RUN/touch.txt" | sed -n 1p | sed 's/.*pos \(.*)\).*/\1/'); p1=$(LC_ALL=C grep -a '\[script\] pos ' "$RUN/touch.txt" | sed -n 2p | sed 's/.*pos \(.*)\).*/\1/')
|
||||
nt=$(LC_ALL=C grep -a -c '世界目标.*没有目标' "$RUN/touch.txt"); dlg=$(LC_ALL=C grep -a -c 'OpenPanel WaypointsPanel' "$RUN/touch.txt")
|
||||
if [[ "$tr" == result=0* ]] && [ -n "$p0" ] && [ "$p0" = "$p1" ] && [ "${nt:-0}" -ge 3 ] && [ "${dlg:-0}" -gt 0 ]; then TOUCH_RES=OK; echo "触摸玩家路径 OK:空存档建角进局;点空地 ${nt} 下坐标不变(${p0});点小站开小站面板(${tr})"
|
||||
else TOUCH_RES=RED; echo "触摸玩家路径 RED:${tr};点空地前后坐标「${p0}」/「${p1}」(须相同且非空);没有目标 ${nt:-0} 下(须 ≥3);开小站面板 ${dlg:-0} 次(须 >0);日志 $RUN/touch.txt"; fi
|
||||
segs="${segs:+${segs};}触摸路径:$TOUCH_RES"
|
||||
fi
|
||||
local left; left=$(pids | tr '\n' ' ')
|
||||
[ -n "$left" ] && { echo "【红】结束后仍有本包 DmIOS pid:$left"; cp "$C/Documents/boot.txt" "$RUN/boot_left.txt" 2>/dev/null; stop_all; }
|
||||
stop_all; local cg_ok=1; cat "$RUN"/*.txt "$RUN"/*/*.txt "$C/Documents/boot.txt" 2>/dev/null > "$RUN/.cg_all" ; cloud_guard_check "$RUN/.cg_all" || cg_ok=0; rm -f "$RUN/.cg_all"; cloud_guard_clean "$C/Documents"
|
||||
savekey_out "$C"; SK_C=''; devlock_release; CLEAN=''
|
||||
printf '%s\n' "$segs" > "$RUN/segs.txt"; printf '%s\n' "$ok" > "$RUN/ok.txt"
|
||||
[ "$known_pk" -eq 1 ] && echo "【已知PK】占不到 pthread 键 507:已按规则补跑"
|
||||
if [ "$ok" -eq "$N" ] && [ -z "$left" ] && [ "$PLAYER_RES" != RED ] && [ "$TOUCH_RES" != RED ] && [ "$cg_ok" = 1 ]; then echo "SMOKE-MAC OK $ok/$N 用时 $(( $(date +%s) - T0 )) 秒"; return 0; fi
|
||||
# 红了就把被测机器当时的负载和占 CPU 前几名留下(mini 上两次红时有 xctrace 700% 和成批宿主在跑,事后才查到)
|
||||
# On failure, save the load of the machine under test at that moment and its top CPU consumers (on the two failures on the second Mac, xctrace at 700% and a batch of hosts were running, only found afterwards)
|
||||
echo "被测机器 $(hostname -s) 负载 $(sysctl -n vm.loadavg);占 CPU 前 5:$(ps -axo pcpu=,comm= | sort -rn | head -5 | awk '{ n=split($2,a,"/"); printf "%s%% %s;", $1, a[n] }')"
|
||||
echo "SMOKE-MAC RED $ok/$N 用时 $(( $(date +%s) - T0 )) 秒"; return 1
|
||||
}
|
||||
# ---------- 界面固定回归 b 局(uireg/,在放包的那台 Mac 上执行;运行约 85 秒:进局 → 走到 NPC 旁 → 逐项点界面,判据只读日志)----------
|
||||
# 入参同 run_stage。结果一行写进 $RUN/uireg_res.txt:OK(通N 未判M) 或 RED(通N 不通M 红K);判据 = 有判据的项全通(通 > 0、不通 = 0)且日志【红】0 行,「未判」不计
|
||||
# ---------- Fixed UI regression run b (uireg/, executed on the Mac holding the package; runs about 85 seconds: enter the game → walk up to the NPC → tap through the UI item by item, criteria read only the log) ----------
|
||||
# Arguments same as run_stage. One result line is written to $RUN/uireg_res.txt: OK(通N 未判M) or RED(通N 不通M 红K) (通 = pass, 不通 = fail, 未判 = unjudged, 红 = red); criterion = all items that have a criterion pass (pass > 0, fail = 0) and 0 lines of 【红】(red) in the log; 「未判」(unjudged) is not counted
|
||||
uireg_stage() {
|
||||
local W=$1 RUN=$2 ul un ur res; mkdir -p "$RUN"
|
||||
ul=$(PYTHONUTF8=1 UIREG_APP="$W" UIREG_OUT="$RUN/uireg" UIREG_RUNNER= python3 "$TOOLS/uireg/uireg.py" iphone b 2>&1 | tee "$RUN/uireg.txt" | LC_ALL=C grep -a '^# 共 ' | tail -1)
|
||||
un=$(printf '%s' "$ul" | sed -n 's/.*通 \([0-9]*\)、不通 \([0-9]*\)、未判 \([0-9]*\).*/\1 \2 \3/p'); ur=$(LC_ALL=C sed -n 's/.*日志【红】\([0-9]*\) 行.*/\1/p' "$RUN/uireg.txt" | tail -1)
|
||||
set -- $un
|
||||
if [ "${1:-0}" -gt 0 ] && [ "${2:-1}" = 0 ] && [ "${ur:-1}" = 0 ]; then res="OK(通$1 未判$3)"; else res="RED(通${1:-?} 不通${2:-?} 红${ur:-?})"; fi
|
||||
printf '%s\n' "$res" > "$RUN/uireg_res.txt"; echo "界面回归 b 局 ${res}:${ul:-没有出结果行}"
|
||||
}
|
||||
CLEAN=''
|
||||
# 清一小时以前的 b 局包副本(<目录>/uireg_*);挂载表里还有它的路径就跳过留到下次——包退出后 Wrapper 的挂载不一定立刻撤,删掉还挂着的源目录会留下卸不掉的挂载条目
|
||||
# Clean run-b package copies older than one hour (<dir>/uireg_*); if the mount table still has its path, skip it and leave it for next time -- the Wrapper mount is not necessarily removed right after the package exits, and deleting a source directory that is still mounted leaves a mount entry that cannot be unmounted
|
||||
if [ "${SMOKE_MAC_STAGE:-}" = prune ]; then
|
||||
find "${SMOKE_MAC_WRAP:?}" -maxdepth 1 -name 'uireg_*' -mmin +60 2>/dev/null | while IFS= read -r d; do mount | LC_ALL=C grep -qF "$d/" || rm -rf "$d"; done; exit 0; fi
|
||||
if [ "${SMOKE_MAC_STAGE:-}" = uireg ]; then uireg_stage "${SMOKE_MAC_WRAP:?}" "${SMOKE_MAC_RUN:?}"; exit 0; fi
|
||||
if [ "${SMOKE_MAC_STAGE:-}" = run ]; then trap 'eval "$CLEAN"' EXIT; trap 'exit 143' INT TERM; run_stage "${SMOKE_MAC_WRAP:?}" "${SMOKE_MAC_RUN:?}"; exit $?; fi
|
||||
|
||||
# ---------- 外层:构建 → 包 Wrapper →(本机 | 远端)跑 → 记账 ----------
|
||||
# ---------- Outer layer: build → wrap in Wrapper → run (local | remote) → record in ledger ----------
|
||||
HOST=${SMOKE_MAC_HOST:-local}
|
||||
TREE=$(git rev-parse --show-toplevel 2>/dev/null || pwd); DD=$TREE/.iosdd_mac # 与真机冒烟的 .iosdd 分开:两种目标的中间产物互不覆盖 | Separate from the real device smoke test's .iosdd: intermediate outputs of the two targets do not overwrite each other
|
||||
RUN="${DM_ROOT:-$HOME/dm-work}/run/ios/smoke_mac/$(date +%Y%m%d_%H%M%S)_$$"; mkdir -p "$RUN"
|
||||
LEDGER=${SMOKE_LEDGER:-${DM_ROOT:-$HOME/dm-work}/run/ios/smoke_ledger.tsv}; LEDGER_RES=中断; ok=0; T0=$(date +%s)
|
||||
ledger_write() { # 与 smoke.sh 同表;结果列带「Mac:」前缀(merge.sh 现在只认无前缀的真机 OK),末列 = 设备 | Same table as smoke.sh; the result column carries the "Mac:" prefix (merge.sh now only accepts unprefixed real device OK), last column = device
|
||||
local head dirty dev; head=$(git -C "$TREE" rev-parse HEAD 2>/dev/null || echo 无); dirty=$(git -C "$TREE" status --porcelain --untracked-files=no 2>/dev/null | wc -l | tr -d ' ')
|
||||
dev="Mac:$([ "$HOST" = local ] && hostname -s || echo "$HOST")"
|
||||
[ -s "$LEDGER" ] || printf '时刻\t调用方\t被测树\tHEAD\t未提交改动\t结果\t成功/次数\t用时秒\t各次分段\t结果目录\n' >> "$LEDGER"
|
||||
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s/%s\t%s\t%s\t%s\t%s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "${SMOKE_OWNER:-未署名}" "$TREE" "$head" "$dirty" \
|
||||
"${SMOKE_KEYS:+反例:}Mac:$LEDGER_RES" "$ok" "$N" "$(( $(date +%s) - T0 ))" "$(cat "$RUN/segs.txt" 2>/dev/null || echo 无)" "$RUN" "$dev" >> "$LEDGER"
|
||||
}
|
||||
trap 'eval "$CLEAN"; ledger_write' EXIT; trap 'exit 143' INT TERM
|
||||
echo "SMOKE-MAC 开始 $N 次(${HOST}),结果目录 $RUN"
|
||||
UIREG_REDMARK=${DM_ROOT:-$HOME/dm-work}/run/ios/uireg_b_last_red.txt; [ -s "$UIREG_REDMARK" ] && echo "上次界面回归 b 局红(只报不拦):$(cat "$UIREG_REDMARK")"
|
||||
( cd "$TREE/dm/ios" && DM_GEN_ONLY=1 DM_IOS_DD="$DD" bash run.sh build && source tools/asc_env.sh && asc_auth &&
|
||||
xcodebuild -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destination 'platform=macOS,arch=arm64,variant=Designed for iPad' \
|
||||
-derivedDataPath "$DD" -allowProvisioningUpdates ${ASC_AUTH[@]+"${ASC_AUTH[@]}"} build ) > "$RUN/build.log" 2>&1 \
|
||||
|| { LEDGER_RES=构建失败; echo "【红】构建失败:$RUN/build.log"; grep -E "error:|🔴" "$RUN/build.log" | head -5; echo "SMOKE-MAC RED 0/$N 用时 $(( $(date +%s) - T0 )) 秒"; exit 2; }
|
||||
# 直接 open 构建产物会报 incorrect executable format:要包成 <名>.app/Wrapper/DmIOS.app + WrappedBundle 软链
|
||||
# Directly opening the build output reports incorrect executable format: it must be wrapped as <name>.app/Wrapper/DmIOS.app + a WrappedBundle symlink
|
||||
W="$DD/DmMacSmoke.app"; rm -rf "$W"; mkdir -p "$W/Wrapper" && cp -cR "$DD/Build/Products/Release-iphoneos/DmIOS.app" "$W/Wrapper/" && ln -s Wrapper/DmIOS.app "$W/WrappedBundle" \
|
||||
|| { LEDGER_RES=构建失败; echo "【红】包 Wrapper 失败"; exit 2; }
|
||||
if [ "${SMOKE_MAC_PKG_ONLY:-0}" = 1 ] && [ "$HOST" = local ]; then trap 'eval "$CLEAN"' EXIT; echo "SMOKE-MAC 只出包 $W"; exit 0; fi
|
||||
if [ "$HOST" = local ]; then
|
||||
run_stage "$W" "$RUN"; rc=$?
|
||||
else
|
||||
# SMOKE_MAC_RNAME=<目录名>:远端目录名不用工作树名(缺省仍是它)。远端那个目录的路径上留了卸不掉的失效挂载点时(挂载源已不存在,只有重启能清),从它 open 一律报「没有这个文件」,换个目录名绕开。
|
||||
# SMOKE_MAC_RNAME=<directory name>: the remote directory name does not use the worktree name (which remains the default). When a stale mount point that cannot be unmounted is left on that remote directory's path (the mount source no longer exists; only a reboot clears it), every open from it reports 「没有这个文件」(no such file); switch directory names to get around it.
|
||||
S="ssh -o BatchMode=yes -o ConnectTimeout=8 $HOST"; RD="dm-work/run/ios/smoke_mac_in/${SMOKE_MAC_RNAME:-$(basename "$TREE")}"; RR="$RD/run_$(basename "$RUN")"
|
||||
# 传包带墙钟上限(包约 260 MB,局域网几十秒;给 180 s)并把 rsync 的报错原文打出来:mini 盘满时 rsync 报 No space left 后挂着不退,一次合入卡了 17 分钟
|
||||
# Package transfer has a wall-clock limit (package about 260 MB, tens of seconds over LAN; 180 s given) and prints rsync's error text verbatim: when the second Mac's disk is full rsync reports No space left and then hangs without exiting; one merge was stuck for 17 minutes
|
||||
TB=$(command -v timeout || command -v gtimeout)
|
||||
{ $S "mkdir -p $RD/tools" && ${TB:+$TB 180} rsync -a --delete "$W" "$HOST:$RD/" && ${TB:+$TB 30} rsync -a "$TOOLS/smoke_mac.sh" $(for _sm_f in $SMOKE_MAC_DEPS; do printf '%s ' "$TOOLS/$_sm_f"; done) "$HOST:$RD/tools/"; } > "$RUN/rsync.log" 2>&1 \
|
||||
|| { LEDGER_RES=传包失败; echo "【红】传包到 $HOST 失败(退出码 $?;124 = 超时):$(tail -2 "$RUN/rsync.log" | tr '\n' ' ' | cut -c1-200)"; echo "SMOKE-MAC RED 0/$N 用时 $(( $(date +%s) - T0 )) 秒"; exit 2; }
|
||||
if [ "${SMOKE_MAC_PKG_ONLY:-0}" = 1 ]; then trap 'eval "$CLEAN"' EXIT; echo "SMOKE-MAC 只出包 $HOST:$RD/DmMacSmoke.app"; exit 0; fi
|
||||
$S "SMOKE_MAC_STAGE=run SMOKE_MAC_WRAP=\$HOME/$RD/DmMacSmoke.app SMOKE_MAC_RUN=\$HOME/$RR SMOKE_OWNER='${SMOKE_OWNER:-未署名}' SMOKE_PLAYER=${SMOKE_PLAYER:-1} DM_MAC_DEVICE_PROFILE=${DM_MAC_DEVICE_PROFILE:-1} ${SMOKE_KEYS:+SMOKE_KEYS='$SMOKE_KEYS'} bash \$HOME/$RD/tools/smoke_mac.sh $N"; rc=$?
|
||||
rsync -a "$HOST:$RR/" "$RUN/" 2>/dev/null; $S "rm -rf \$HOME/$RR"
|
||||
fi
|
||||
ok=$(cat "$RUN/ok.txt" 2>/dev/null || echo 0)
|
||||
[ "$rc" -eq 0 ] && LEDGER_RES=OK || LEDGER_RES=RED
|
||||
# 界面回归 b 局【只报不拦,临时状态】:SMOKE_UIREG=1 时跑(缺省不跑;合入门槛 merge.sh 触发的那次冒烟会带上)。结果上、时间上都不拦——
|
||||
# 冒烟主体出了结果就返回,b 局放到后台另取 macsmoke 锁跑,跑完往台账补一行(同一个 HEAD,结果列 Mac:界面回归b:OK / RED,不会被当成冒烟证据),
|
||||
# 红了留现场并登记,下一次冒烟开头打印一句。
|
||||
# 后台那一局用包的一份克隆副本(返回之前同步做好,目录名带本次运行号):紧接着的下一次冒烟会在取锁之前重新包装 / 同步原来那个目录,
|
||||
# 包开着的时候它的 Wrapper 被删或被整体替换,会留下卸不掉的失效挂载点。副本不当场删,下次到这里时清一小时以前、且挂载表里已经没有的(prune 阶段)。
|
||||
# 升成门槛的条件:台账里攒满 30 遍后看偶发率再定(数法见 uireg/usage.md)。
|
||||
# UI regression run b [report only, non-blocking; temporary status]: runs when SMOKE_UIREG=1 (not run by default; the smoke test triggered by the merge gate merge.sh includes it). It blocks neither on result nor on time --
|
||||
# the main smoke test returns as soon as it has a result, run b goes to the background and takes the macsmoke lock separately, and when done appends a line to the ledger (same HEAD, result column Mac:界面回归b:OK / RED (UI regression b), which will not be taken as smoke-test evidence),
|
||||
# on failure, the artifacts are preserved and registered, and the next smoke test prints a line about it at the start.
|
||||
# That background run uses a cloned copy of the package (made synchronously before returning, directory name carrying this invocation's run number): the immediately following smoke test re-wraps / re-syncs the original directory before taking the lock,
|
||||
# and if a package's Wrapper is deleted or wholly replaced while the package is open, it leaves a stale mount point that cannot be unmounted. The copy is not deleted on the spot; the next time we get here, those older than one hour and no longer in the mount table are cleaned (prune stage).
|
||||
# Condition for promoting it to a gate: decide after 30 passes have accumulated in the ledger, looking at the flake rate (how to count: see uireg/usage.md).
|
||||
if [ "$rc" -eq 0 ] && [ -z "${SMOKE_KEYS:-}" ] && [ "${SMOKE_UIREG:-0}" = 1 ]; then
|
||||
UH=$(git -C "$TREE" rev-parse HEAD 2>/dev/null || echo 无); UD=$(git -C "$TREE" status --porcelain --untracked-files=no 2>/dev/null | wc -l | tr -d ' ')
|
||||
UN=uireg_$(basename "$RUN")
|
||||
if [ "$HOST" = local ]; then SMOKE_MAC_STAGE=prune SMOKE_MAC_WRAP="$DD" bash "$TOOLS/smoke_mac.sh"; mkdir -p "$DD/$UN" && cp -cR "$W" "$DD/$UN/"; ucp=$?
|
||||
else $S "SMOKE_MAC_STAGE=prune SMOKE_MAC_WRAP=\$HOME/$RD bash \$HOME/$RD/tools/smoke_mac.sh; mkdir -p \$HOME/$RD/$UN && cp -cR \$HOME/$RD/DmMacSmoke.app \$HOME/$RD/$UN/"; ucp=$?; fi
|
||||
if [ "$ucp" -ne 0 ]; then echo "界面回归 b 局没跑:克隆包副本失败(只报不拦)"
|
||||
else
|
||||
( t0=$(date +%s)
|
||||
if [ "$HOST" = local ]; then SMOKE_MAC_STAGE=uireg SMOKE_MAC_WRAP="$DD/$UN/DmMacSmoke.app" SMOKE_MAC_RUN="$RUN" bash "$TOOLS/smoke_mac.sh"
|
||||
else
|
||||
$S "SMOKE_MAC_STAGE=uireg SMOKE_MAC_WRAP=\$HOME/$RD/$UN/DmMacSmoke.app SMOKE_MAC_RUN=\$HOME/$RD/$UN/out SMOKE_OWNER='${SMOKE_OWNER:-未署名}' bash \$HOME/$RD/tools/smoke_mac.sh"
|
||||
rsync -a "$HOST:$RD/$UN/out/" "$RUN/" 2>/dev/null
|
||||
fi
|
||||
res=$(cat "$RUN/uireg_res.txt" 2>/dev/null || echo "RED(没有出结果)")
|
||||
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "${SMOKE_OWNER:-未署名}" "$TREE" "$UH" "$UD" "Mac:界面回归b:${res%%(*}" "-" "$(( $(date +%s) - t0 ))" "界面回归b:$res" "$RUN" \
|
||||
"Mac:$([ "$HOST" = local ] && hostname -s || echo "$HOST")" >> "$LEDGER"
|
||||
case $res in OK*) : > "$UIREG_REDMARK";; *) echo "$(date '+%m-%d %H:%M') ${SMOKE_OWNER:-未署名} ${UH:0:9} ${res},现场 $RUN/uireg(表在 tables/ 下,日志 pw/ur_iphone_b/boot.txt)" > "$UIREG_REDMARK";; esac
|
||||
) > "$RUN/uireg_bg.log" 2>&1 < /dev/null &
|
||||
disown; echo "界面回归 b 局已放到后台跑(只报不拦),结果会补进台账;日志 $RUN/uireg_bg.log"
|
||||
fi
|
||||
fi
|
||||
exit "$rc"
|
||||
@@ -0,0 +1,21 @@
|
||||
3.50 down 0 488,209
|
||||
3.62 up 0
|
||||
4.30 down 0 433,189
|
||||
4.42 up 0
|
||||
7.00 down 0 334,343
|
||||
7.12 up 0
|
||||
10.00 down 0 167,193
|
||||
10.12 up 0
|
||||
13.00 type Smoke
|
||||
14.00 alert ok
|
||||
22.00 pos
|
||||
22.50 down 0 300,60
|
||||
22.62 up 0
|
||||
23.50 down 0 41,120
|
||||
23.62 up 0
|
||||
24.50 down 0 330,70
|
||||
24.62 up 0
|
||||
26.00 pos
|
||||
26.50 tap_unit 2 119 5
|
||||
30.00 pos
|
||||
36.00 pos
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/bin/bash
|
||||
# 真机局内浸泡(同 Mac 浸泡口径):r17 + 术士存档可写副本 + cvd5 真值局的种子 / 固定时刻 + cvd5 回放进局;回放完(DM:ReplayDone)后先按 B 关闭传送点菜单(确认 ClosePanel:WaypointsPanelExpansion),再
|
||||
# 左摇杆按 左→上→右→下 各 8 秒循环走动到浸泡结束;DM_SOAK 每 60 秒一行,墙钟上限 35 分钟。
|
||||
# 用法:[DM_OUT=产物目录(缺省 r17)] [SOAK_IV=采样秒(缺省 60)] dm/ios/tools/soak.sh [分钟=35] 产物:$DM_ROOT/run/ios/soak/(soak.tsv、boot.txt、报告)
|
||||
# 判据:soak_report.py 四项(拍号增长、第 5 分钟后内存斜率、句柄 / 线程不变、帧时间 p95 前后段)+ 真机两项(每分钟温控档位与 footprint、p95 随时间)
|
||||
# Real device in-game soak (same basis as the Mac soak): r17 + writable copy of the warlock save + the seed / fixed time of the cvd5 ground truth run + cvd5 replay to enter the game; after the replay finishes (DM:ReplayDone) first press B to close the waypoint menu (confirming ClosePanel:WaypointsPanelExpansion), then
|
||||
# walk in a loop with the left stick left→up→right→down for 8 seconds each until the soak ends; one DM_SOAK line every 60 seconds, wall-clock limit 35 minutes.
|
||||
# Usage: [DM_OUT=build output dir (default r17)] [SOAK_IV=sampling seconds (default 60)] dm/ios/tools/soak.sh [minutes=35] Output: $DM_ROOT/run/ios/soak/ (soak.tsv, boot.txt, report)
|
||||
# Criteria: soak_report.py's four items (tick number growth, memory slope after minute 5, handles / threads unchanged, frame time p95 first vs. second half) + two real device items (thermal state and footprint per minute, p95 over time)
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
source tools/local_env.sh && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
MIN=${1:-35}; D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}; R=${DM_ROOT:-$HOME/dm-work}/run/ios/soak
|
||||
TR=${DM_ROOT:-$HOME/dm-work}/data/switch/truth_runs/cvd5; CVD=$TR/c2s.jsonl; RUN=$(date +%H%M%S)
|
||||
export DM_OUT=${DM_OUT:-$(bash "$(dirname "$0")/../../tools/product.sh" path keypage)}
|
||||
SEED=$(python3 -c "import json;print(hex(json.load(open('$TR/meta.json'))['game_seed']))"); FT=$(python3 -c "import json;print(json.load(open('$TR/meta.json'))['fix_time'])")
|
||||
K='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,MSG:CharacterSelect:LoadCharacter:0@OpenPanel:CharacterSelectPanel%1>FrontEndNavigation:ToGame,B@DM:ReplayDone>ClosePanel:WaypointsPanelExpansion'
|
||||
# 小站关闭确认后循环走动:各步前置留空(上一步松开即按);按键表上限 256 项 → 前 3 项进局 / 关小站 + 248 项 × 8 秒 ≈ 33 分钟
|
||||
# After the waypoint close is confirmed, walk in a loop: each step's pre-delay is left empty (press as soon as the previous step releases); key table limit 256 entries → first 3 entries enter the game / close the waypoint + 248 entries × 8 seconds ≈ 33 minutes
|
||||
W='LSL@+8'; for i in $(seq 1 247); do W="$W,$(echo LSU LSR LSD LSL | cut -d' ' -f$(( (i - 1) % 4 + 1 )))@+8"; done
|
||||
K="$K,$W"
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
mkdir -p "$R"; rm -f "$R"/soak.tsv "$R"/boot.txt
|
||||
./run.sh build > "$R/build.log" 2>&1 || { t "🔴 构建失败"; tail -5 "$R/build.log"; exit 1; }
|
||||
./run.sh install >> "$R/build.log" 2>&1 || { t "🔴 装机失败"; tail -5 "$R/build.log"; exit 1; }
|
||||
xcrun devicectl device copy to --device $D --domain-type appDataContainer --domain-identifier $B --source "$CVD" --destination Documents/cvd5_replay.jsonl > "$R/push.log" 2>&1 || { t "🔴 推回放文件失败"; exit 1; }
|
||||
export DEVICECTL_CHILD_DM_KEYS="$K"
|
||||
DEVICECTL_CHILD_DM_SAVE_FRESH=warlock DEVICECTL_CHILD_DM_GAME_SEED=$SEED DEVICECTL_CHILD_DM_FIXED_TIME=$FT DEVICECTL_CHILD_DM_C2S_REPLAY=cvd5_replay.jsonl \
|
||||
DEVICECTL_CHILD_DM_SOAK="soak_$RUN.tsv,${SOAK_IV:-60}" DEVICECTL_CHILD_DM_PRESENT_HZ=60 DEVICECTL_CHILD_DM_WATCH=$((MIN * 60)) \
|
||||
xcrun devicectl device process launch --device $D --terminate-existing $B -mode boot > "$R/launch.log" 2>&1 || { t "🔴 启动失败"; tail -3 "$R/launch.log"; exit 1; }
|
||||
t "已启动,浸泡 $MIN 分钟"
|
||||
alive(){ xcrun devicectl device info processes --device $D 2>/dev/null | grep -q "DmIOS.app/DmIOS"; }
|
||||
s=$SECONDS
|
||||
while alive && [ $((SECONDS - s)) -lt $((MIN * 60 + 120)) ]; do sleep 60; done
|
||||
[ $((SECONDS - s)) -lt $((MIN * 60 - 30)) ] && t "🔴 进程在第 $(((SECONDS - s) / 60)) 分钟就没了(崩溃或被杀)"
|
||||
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source "Documents/soak_$RUN.tsv" --destination "$R/soak.tsv" > /dev/null 2>&1 || t "🔴 拉 soak.tsv 失败"
|
||||
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source Documents/boot.txt --destination "$R/boot.txt" > /dev/null 2>&1 || t "🔴 拉 boot.txt 失败"
|
||||
t "结束(墙钟 $(((SECONDS - s) / 60)) 分钟)"
|
||||
python3 "${DM_ROOT:-$HOME/dm-work}/run/platform/soak_report.py" "$R/soak.tsv" "$R/boot.txt"
|
||||
echo "⑤ 每分钟温控档位 / footprint:"
|
||||
python3 - "$R/soak.tsv" "$R/boot.txt" <<'PY'
|
||||
import sys, re
|
||||
th = {int(m[1]): int(m[2]) for m in re.finditer(r'\[浸泡\] 第 (\d+) 秒 温控档位 (\d+)', open(sys.argv[2], errors='replace').read())}
|
||||
rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1])][1:]
|
||||
for r in rows:
|
||||
s = int(float(r[0])); near = min(th, key=lambda k: abs(k - s)) if th else None
|
||||
print(f' {s:5d} 秒 拍 {r[1]:>6} footprint {r[6]:>7} MiB 温控 {th[near] if near is not None else "?"}')
|
||||
print('⑥ 帧时间 p95 随时间(每 300 帧一段):')
|
||||
seg = [(int(m[1]), float(m[2]), float(m[3])) for m in re.finditer(r'计时 至帧 (\d+): 帧时间 p50 ([\d.]+) / p95 ([\d.]+)', open(sys.argv[2], errors='replace').read())]
|
||||
for i in range(0, len(seg), 6): print(' ' + ' '.join(f'帧{f}:{p95:.1f}' for f, _, p95 in seg[i:i + 6]))
|
||||
red = sorted({l.strip() for l in open(sys.argv[2], errors='replace') if '【红】' in l and '贴图号' not in l})
|
||||
print('红:' + ('无' if not red else ' | '.join(red[:5])))
|
||||
PY
|
||||
@@ -0,0 +1,61 @@
|
||||
# 偏暗分类:我方像素 → 真值像素 的映射拟合(读 pages.sh 产物 mac_sel / mac_game;静态区域逐像素配对,已证同位姿:相位相关平移 0,0)。修一轮后重跑看 k 是否回到 1。用法:python3 dm/ios/tools/tonefit.py
|
||||
# Darkness classification: fit of the mapping our pixels → ground truth pixels (reads pages.sh outputs mac_sel / mac_game; pixel-by-pixel pairing in static regions, same pose already proven: phase-correlation shift 0,0). Rerun after a round of fixes to see whether k returns to 1. Usage: python3 dm/ios/tools/tonefit.py
|
||||
import numpy as np; from PIL import Image, ImageDraw
|
||||
import os; DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
|
||||
P = DM_ROOT + '/run/ios/pages/'; T = DM_ROOT + '/run/verify/'; O = DM_ROOT + '/run/ios/tonefit/'
|
||||
import os; os.makedirs(O, exist_ok=True)
|
||||
def lin(e): return np.where(e <= 0.04045, e / 12.92, ((e + 0.055) / 1.055) ** 2.4)
|
||||
PAGES = {
|
||||
'选角': (P + 'mac_sel.png', T + 'truth_shots/选角页_saveref_joe_有DLC.png', (1600, 900),
|
||||
[(0, 0, 345, 900), (690, 110, 970, 900), (1055, 350, 1425, 490), (690, 800, 910, 850), (290, 540, 430, 720)]),
|
||||
'局内': (P + 'mac_game.png', T + 'dm/pq/p0.png', (640, 360),
|
||||
[(0, 295, 640, 360), (40, 40, 75, 120), (465, 90, 500, 160), (510, 250, 545, 305), (290, 110, 350, 200),
|
||||
(120, 170, 175, 235), (240, 120, 290, 205), (135, 70, 205, 105), (255, 60, 380, 95), (180, 230, 290, 305), (0, 0, 640, 12)]),
|
||||
}
|
||||
def density(x, y, title, path, fitlines):
|
||||
N = 400; R = float(max(np.quantile(x, 0.995), np.quantile(y, 0.995))) * 1.05
|
||||
img = Image.new('RGB', (N + 70, N + 50), (255, 255, 255)); d = ImageDraw.Draw(img)
|
||||
H, _, _ = np.histogram2d(np.clip(x, 0, R), np.clip(y, 0, R), bins=N, range=[[0, R], [0, R]])
|
||||
H = np.sqrt(H / H.max()); H = (255 * (1 - np.clip(H * 3, 0, 1))).astype(np.uint8)
|
||||
img.paste(Image.fromarray(np.flipud(H.T)).convert('RGB'), (50, 10))
|
||||
X = lambda v: 50 + v / R * N; Y = lambda v: 10 + N - v / R * N
|
||||
d.rectangle((50, 10, 50 + N, 10 + N), outline=(0, 0, 0)); d.line((X(0), Y(0), X(R), Y(R)), fill=(170, 170, 170)) # y = x
|
||||
for f, col in fitlines:
|
||||
xs = np.linspace(0, R, 200); ys = np.clip(f(xs), 0, R); d.line([(X(a), Y(b)) for a, b in zip(xs, ys)], fill=col, width=2)
|
||||
bins = np.linspace(0, R, 25)
|
||||
for i in range(24):
|
||||
q = (x >= bins[i]) & (x < bins[i + 1])
|
||||
if q.sum() > 30: mx, my = (bins[i] + bins[i + 1]) / 2, float(np.median(y[q])); d.ellipse((X(mx) - 3, Y(my) - 3, X(mx) + 3, Y(my) + 3), fill=(0, 160, 0))
|
||||
d.text((50, N + 15), f'{title} x=truth y=ours range 0..{R:.3f} grey: y=x blue: k*lin red: pow green: bin median', fill=(0, 0, 0)); img.save(path)
|
||||
for name, (po, pt, size, masks) in PAGES.items():
|
||||
a = np.asarray(Image.open(po).convert('RGB').resize(size, Image.BILINEAR)).astype(float) / 255
|
||||
b = np.asarray(Image.open(pt).convert('RGB').resize(size, Image.BILINEAR)).astype(float) / 255
|
||||
m = np.ones(size[::-1], bool)
|
||||
for x0, y0, x1, y1 in masks: m[y0:y1, x0:x1] = False
|
||||
o, t = a[m].ravel(), b[m].ravel()
|
||||
keep = (t > 8 / 255) & (t < 250 / 255) & (o < 250 / 255); o, t = o[keep], t[keep]
|
||||
# 稳健:先按线性光倍数粗拟合,剔除残差最大的 15%(残余错位、风吹草动),再在剩余样本上做三种拟合
|
||||
# Robustness: first a coarse fit by linear-light multiplier, discard the 15% with the largest residuals (residual misalignment, slight scene movement), then do the three fits on the remaining samples
|
||||
ol, tl = lin(o), lin(t); k0 = np.sum(ol * tl) / np.sum(tl * tl); r = np.abs(ol - k0 * tl); s = r < np.quantile(r, 0.85)
|
||||
o, t, ol, tl = o[s], t[s], ol[s], tl[s]
|
||||
k = np.sum(ol * tl) / np.sum(tl * tl); rk = np.sqrt(np.mean((o - np.clip(((k * tl) ** (1 / 2.4)) * 1.055 - 0.055, 0, 1)) ** 2)) # 残差按编码值算(近似反变换) | Residual computed on encoded values (approximate inverse transform)
|
||||
pos = (o > 1 / 255); lt, lo = np.log(t[pos]), np.log(o[pos])
|
||||
g = np.sum(lo * lt) / np.sum(lt * lt); rg = np.sqrt(np.mean((o - t ** g) ** 2))
|
||||
A = np.vstack([lt, np.ones_like(lt)]).T; (g2, c2), *_ = np.linalg.lstsq(A, lo, rcond=None); rg2 = np.sqrt(np.mean((o[pos] - np.exp(c2) * t[pos] ** g2) ** 2))
|
||||
# 分段:线性光空间暗部 / 中部 / 亮部的倍数(真值编码值分段)
|
||||
# Segments: multipliers for the dark / mid / bright parts in linear-light space (segmented by ground truth encoded value)
|
||||
seg = []
|
||||
for lo_, hi_ in ((0.03, 0.15), (0.15, 0.35), (0.35, 0.6), (0.6, 1.0)):
|
||||
q = (t >= lo_) & (t < hi_)
|
||||
seg.append((lo_, hi_, int(q.sum()), float(np.sum(ol[q] * tl[q]) / np.sum(tl[q] ** 2)) if q.sum() > 50 else float('nan')))
|
||||
# 分箱中位曲线(编码值)
|
||||
# Binned median curve (encoded values)
|
||||
bins = np.linspace(0, 1, 21); mid = [(bins[i], float(np.median(o[(t >= bins[i]) & (t < bins[i + 1])])) if ((t >= bins[i]) & (t < bins[i + 1])).sum() > 30 else None) for i in range(20)]
|
||||
print(f'== {name}:配对样本 {o.size}(通道合计,剔除最差 15% 后)')
|
||||
print(f' ① 线性光过原点倍数 k = {k:.3f}(编码值残差 RMS {rk * 255:.1f}/255)')
|
||||
print(f' ② 编码值幂 我方 = 真值^γ:γ = {g:.3f}(残差 RMS {rg * 255:.1f}/255);带系数 我方 = {np.exp(c2):.3f}·真值^{g2:.3f}(残差 {rg2 * 255:.1f}/255)')
|
||||
print(' ③ 线性光分段倍数(按真值编码值段):' + ';'.join(f'[{a_:.2f},{b_:.2f}) n={n} k={kk:.3f}' for a_, b_, n, kk in seg))
|
||||
print(' 分箱中位(真值编码 → 我方编码):' + ' '.join(f'{x:.2f}→{y:.3f}' for x, y in mid if y is not None))
|
||||
density(t, o, f'{name} sRGB encoded', O + f'{name}_编码值.png', [(lambda x, g=g: x ** g, (220, 0, 0)), (lambda x, k=k: np.clip(((k * lin(x)) ** (1 / 2.4)) * 1.055 - 0.055, 0, 1), (0, 0, 220))])
|
||||
density(tl, ol, f'{name} linear light', O + f'{name}_线性光.png', [(lambda x, k=k: k * x, (0, 0, 220))])
|
||||
print('图:', O)
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/bin/bash
|
||||
# 真机触屏端到端:装好的 App 按触点脚本自动操作,拉回日志与截图。用法:
|
||||
# [PREFIX=c2s.jsonl] tools/touch_e2e.sh <脚本文件> <结果目录> [秒=60]
|
||||
# PREFIX:先回放一段原版命令包(如出营地到野外),固定种子/时间;回放窗口结束后触点脚本接手(脚本时间要排在窗口之后)。
|
||||
# 脚本格式见 front_ios.m 的 touch_script_start(首次进游戏后计时)。存档每局换术士标准存档新副本(DM_SAVE_FRESH=warlock)。
|
||||
# 只按本 App bundle / 自己启动的 pid 停进程;不碰别的 App 与设备设置。
|
||||
# Real-device touch end-to-end: the installed App is operated automatically by a touch point script, and logs and screenshots are pulled back. Usage:
|
||||
# [PREFIX=c2s.jsonl] tools/touch_e2e.sh <script file> <result dir> [seconds=60]
|
||||
# PREFIX: first replay a stretch of the original game's command packets (e.g. from leaving the camp to the wilderness), with fixed seed/time; after the replay window ends the touch point script takes over (script times must be scheduled after the window).
|
||||
# For the script format see touch_script_start in front_ios.m (timing starts after first entering the game). Each run swaps in a fresh copy of the standard warlock save (DM_SAVE_FRESH=warlock).
|
||||
# Processes are stopped only by this App's bundle / the pid we launched ourselves; other Apps and device settings are not touched.
|
||||
set -euo pipefail
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/local_env.sh" && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
|
||||
SCRIPT=$1; OUT=$2; CAP=${3:-60}
|
||||
mkdir -p "$OUT"; cp "$SCRIPT" "$OUT/script.txt"
|
||||
# 设备锁(可重入:外层已持锁的调用不受影响)。直接调本脚本时没人取锁——Mac 版 touch_e2e_mac.sh 自己取、真机版以前靠调用者取,口径不一
|
||||
# 电量闸:取锁前读电量,< 30% 暂停全部真机局、充到 60% 放行;读数记进本局产物 battery.txt(表头用)
|
||||
# Device lock (reentrant: calls whose outer layer already holds the lock are unaffected). When this script is called directly nobody takes the lock -- the Mac version touch_e2e_mac.sh takes it itself, while the real-device version used to rely on the caller, an inconsistent convention
|
||||
# Battery gate: read the battery level before taking the lock; below 30% pause all real-device runs, release them once charged to 60%; the reading is recorded in this run's output battery.txt (used for the header)
|
||||
source "$(dirname "$0")/devbattery.sh"; devbattery_gate || { echo "【红】电量闸拒绝:${DEVBATTERY_LINE:-}" | tee "$OUT/battery.txt"; exit 3; }; echo "$DEVBATTERY_LINE" > "$OUT/battery.txt"
|
||||
source "$(dirname "$0")/devlock.sh"; devlock_acquire "${SMOKE_OWNER:-未署名} 真机触屏 $(basename "$OUT")"; trap devlock_release EXIT
|
||||
# 本局编号做产物名前缀:旧局文件名不同,不会被当成本局结果拉回(App 开日志前就退出的一局曾拉回前一天的旧 c2s / target)。
|
||||
# 不逐个推空文件清旧产物:每次 devicectl 约 20 s,10 个文件把锁内时间拖到 324 s
|
||||
# Use this run's id as the prefix of the output names: files from old runs have different names and will not be pulled back as this run's results (a run where the App exited before opening its logs once pulled back the previous day's old c2s / target).
|
||||
# Do not clear old output by pushing empty files one by one: each devicectl call takes about 20 s, and 10 files stretched the time under lock to 324 s
|
||||
RID=r$(date +%H%M%S)
|
||||
awk -v r="$RID" '($2=="shot"||$2=="tshot"){$3=r"_"$3} {print}' "$SCRIPT" > "$OUT/script_run.txt"
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
dc(){ timeout 60 xcrun devicectl device "$@"; } # 每次 devicectl 限 60 s:无超时的调用卡住会长时间占设备锁(UDC 卡 27 分钟饿死整条队) | Each devicectl call is capped at 60 s: a call without a timeout that hangs holds the device lock for a long time (UDC hung for 27 minutes and starved the whole queue)
|
||||
pids(){ dc info processes --device $D --json-output "$OUT/.ps.json" >/dev/null 2>&1; python3 -c "import json,sys;print(' '.join(str(p['processIdentifier']) for p in json.load(open(sys.argv[1]))['result']['runningProcesses'] if 'DmIOS.app/DmIOS' in p.get('executable','')))" "$OUT/.ps.json"; }
|
||||
for p in $(pids); do t "停残留 DmIOS pid $p"; dc process terminate --device $D --pid $p >/dev/null 2>&1 || true; done
|
||||
dc copy to --device $D --domain-type appDataContainer --domain-identifier $B --source "$OUT/script_run.txt" --destination Documents/touch_script.txt >/dev/null
|
||||
[ -n "${PREFIX:-}" ] && dc copy to --device $D --domain-type appDataContainer --domain-identifier $B --source "$PREFIX" --destination Documents/e2e_prefix.jsonl >/dev/null
|
||||
ENV=$(CAP=$CAP RID=$RID PREFIX=${PREFIX:-} E2E_ENV=${E2E_ENV:-} E2E_KEYS=${E2E_KEYS:-} python3 - <<'EOF'
|
||||
import json, os
|
||||
r = os.environ["RID"]
|
||||
env = {
|
||||
"DM_SAVE_FRESH": "warlock", # 档位不设 = 产品缺省(主机档)。之前这里写死掌机档(DM_OPMODE=0),触屏脚本看到的界面参数与玩家看到的不是同一份;要测掌机档用 E2E_ENV 传
|
||||
"DM_TOUCH_SCRIPT": "touch_script.txt", "DM_TOUCH_CONTROL_LOG": "1",
|
||||
"DM_C2S_LOG": r + "_c2s.jsonl", "DM_UIMSG": r + "_uimsg.jsonl", "DM_STATE": r + "_state.jsonl",
|
||||
"DM_TICKS": r + "_ticks.jsonl", "DM_TICKS_FULL": "1", "DM_TICKS_N": "0", "DM_TARGET_LOG": r + "_target.jsonl",
|
||||
"DM_KEYS": os.environ.get("E2E_KEYS") or "X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame", # E2E_KEYS:换起局键序(同 touch_e2e_mac.sh)
|
||||
"DM_WATCH": str(int(os.environ["CAP"]) + 60),
|
||||
}
|
||||
if os.environ["PREFIX"]:
|
||||
env.update({"DM_C2S_REPLAY": "e2e_prefix.jsonl", "DM_GAME_SEED": "305419896", "DM_FIXED_TIME": "1790895128"})
|
||||
if os.environ.get("E2E_ENV"): env.update(json.loads(os.environ["E2E_ENV"])) # 额外环境(JSON),对照实验用,如 {"DM_GAME_SEED":"1"}
|
||||
env = {k: v for k, v in env.items() if v is not None} # E2E_ENV 里写 null = 去掉这个缺省(如 {"DM_SAVE_FRESH":null,"DM_SAVE_TEST":"1"}:沿用上一局的 save.test)
|
||||
print(json.dumps(env))
|
||||
EOF
|
||||
)
|
||||
dc process launch --device $D --terminate-existing --environment-variables "$ENV" --json-output "$OUT/launch.json" $B -mode boot > "$OUT/launch.log" 2>&1
|
||||
PID=$(python3 -c "import json;print(json.load(open('$OUT/launch.json'))['result']['process']['processIdentifier'])")
|
||||
t "启动 pid $PID,跑 ${CAP}s"; sleep "$CAP"
|
||||
dc process terminate --device $D --pid "$PID" > "$OUT/stop.log" 2>&1 && t "已停 pid $PID" || t "pid $PID 已自行退出"
|
||||
# 只拉本局产物(Documents 里有 9 GB romfs,不整目录拉):启动日志、四份记录、脚本里的截图
|
||||
# E2E_PULL(空格分隔,不带本局前缀,如 "c2s.jsonl state.jsonl s2.png"):只拉这几份——每次 copy from 约 20 s,全拉会把锁内时间拖过 2 分钟
|
||||
# Pull only this run's build output (Documents holds a 9 GB romfs, so do not pull the whole directory): boot log, the four records, screenshots taken by the script
|
||||
# E2E_PULL (space-separated, without this run's prefix, e.g. "c2s.jsonl state.jsonl s2.png"): pull only these files -- each copy from takes about 20 s, and pulling everything pushes the time under lock past 2 minutes
|
||||
ALL="boot.txt ${RID}_c2s.jsonl ${RID}_uimsg.jsonl ${RID}_ticks.jsonl ${RID}_target.jsonl ${RID}_state.jsonl $(awk '$2=="shot"{print $3; print $3".txt"} $2=="tshot"{print $3; print $3".json"}' "$OUT/script_run.txt")"
|
||||
[ -n "${E2E_PULL:-}" ] && ALL=$(for f in $E2E_PULL; do [ "$f" = boot.txt ] && echo boot.txt || echo "${RID}_$f"; done)
|
||||
for f in $ALL; do
|
||||
g=${f#${RID}_} # 拉回后去掉本局前缀,结果目录里的文件名与旧版一致(e2e_* 照旧) | After pulling, strip this run's prefix so the file names in the result directory match the old version (e2e_* unchanged)
|
||||
case $f in ${RID}_*.jsonl) g=e2e_$g;; esac
|
||||
dc copy from --device $D --domain-type appDataContainer --domain-identifier $B --source "Documents/$f" --destination "$OUT/$g" >> "$OUT/copy.log" 2>&1 || t "【红】拉不到 $f(本局没写)"
|
||||
done
|
||||
left=$(pids); [ -z "$left" ] && t "设备上 DmIOS 进程 0" || t "【红】仍有 DmIOS 进程 $left"
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/bin/bash
|
||||
# Mac 上的触屏端到端:与真机 touch_e2e.sh 同参数、同产物名,被测的是同一个 iOS 包(smoke_mac.sh 包好的 <树>/.iosdd_mac/DmMacSmoke.app,先跑过一次 smoke_mac.sh 或自行构建)。
|
||||
# [PREFIX=c2s.jsonl] [E2E_REF=956x440] tools/touch_e2e_mac.sh <脚本文件> <结果目录> [秒=60]
|
||||
# E2E_REF=<宽>x<高>(如真机的 956x440):脚本里的裸坐标是按这个点数的屏幕写的,由 App 换算到 Mac 窗口(DM_TOUCH_REF,front_ios.m scriptPoint);@名字 的控件目标不换算。
|
||||
# 文件直接读写 App 容器(不经 devicectl,每份省约 20 s);与 Mac 冒烟共用一把锁(同一容器)。
|
||||
# Touch end-to-end on the Mac: same parameters and same output names as the real-device touch_e2e.sh; what is tested is the same iOS app (<tree>/.iosdd_mac/DmMacSmoke.app packaged by smoke_mac.sh; run smoke_mac.sh once first or build it yourself).
|
||||
# [PREFIX=c2s.jsonl] [E2E_REF=956x440] tools/touch_e2e_mac.sh <script file> <result dir> [seconds=60]
|
||||
# E2E_REF=<width>x<height> (e.g. the real device's 956x440): bare coordinates in the script are written for a screen of this many points and converted by the App to the Mac window (DM_TOUCH_REF, front_ios.m scriptPoint); widget targets of the form @name are not converted.
|
||||
# Files are read and written directly in the App container (not through devicectl, saving about 20 s per file); shares one lock with the Mac smoke test (same container).
|
||||
set -u # 不开 -e:devlock.sh 按 smoke.sh 的口径写(只 set -u),其内部条件式返回非零会被 -e 当失败退出 | Do not enable -e: devlock.sh is written to smoke.sh's convention (only set -u), and a non-zero return from its internal conditionals would be treated by -e as a failure and exit
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/local_env.sh" # 本机配置(包名、团队号、设备号) | Local config (package name, team ID, device ID)
|
||||
B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
|
||||
SCRIPT=$1; OUT=$2; CAP=${3:-60}
|
||||
TOOLS=$(cd "$(dirname "$0")" && pwd); TREE=$(git -C "$TOOLS" rev-parse --show-toplevel)
|
||||
W=${E2E_MAC_APP:-$TREE/.iosdd_mac/DmMacSmoke.app}; exe="$W/Wrapper/DmIOS.app/DmIOS"
|
||||
[ -x "$exe" ] || { echo "【红】没有包:${W}(先跑 dm/ios/tools/smoke_mac.sh 1)"; exit 2; }
|
||||
mkdir -p "$OUT"; cp "$SCRIPT" "$OUT/script.txt"
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
C=""; for m in "$HOME"/Library/Containers/*/.com.apple.containermanagerd.metadata.plist; do
|
||||
[ "$(/usr/libexec/PlistBuddy -c 'Print :MCMMetadataIdentifier' "$m" 2>/dev/null)" = "$B" ] && C="$(dirname "$m")/Data"; done
|
||||
[ -n "$C" ] || { echo "【红】本机没有 $B 的容器(先跑 smoke_mac.sh 1)"; exit 2; }
|
||||
DOC="$C/Documents"
|
||||
export DM_DEVLOCK_DIR=${DM_ROOT:-$HOME/dm-work}/run/ios/macsmoke.lock; source "$TOOLS/devlock.sh"; source "$TOOLS/cloud_guard.sh"; source "$TOOLS/save_key.sh"; source "$TOOLS/launch_guard.sh"; devlock_acquire "${SMOKE_OWNER:-未署名} Mac 触屏 $(basename "$OUT")"
|
||||
# 找实例按可执行文件后缀(系统有时把包迁到随机路径下运行,按原路径认不到);同一 bundle id 在 Mac 上只能有一个实例,开跑前已有实例即红、不替人结束
|
||||
# Find the instance by executable suffix (the system sometimes relocates the bundle to a random path to run it, so the original path does not match); the same bundle id can have only one instance on the Mac; an instance already existing before the run starts is a failure, and we do not terminate it on someone else's behalf
|
||||
pids(){ ps -axo pid=,comm= | awk '{ pid=$1; $1=""; sub(/^ /,""); if ($0 ~ /\/Wrapper\/DmIOS\.app\/DmIOS$/) print pid }'; }
|
||||
stop_all(){ local p; for p in $(pids); do kill -TERM "$p" 2>/dev/null || true; done; sleep 1; for p in $(pids); do kill -KILL "$p" 2>/dev/null || true; done; }
|
||||
pre=$(pids | tr '\n' ' '); [ -z "$pre" ] || { echo "【红】本机已有 $B 的实例在跑(pid ${pre},非本次启动):先结束它再跑"; devlock_release; exit 2; }
|
||||
trap 'stop_all; savekey_out "$C"; devlock_release' EXIT; trap 'exit 143' INT TERM
|
||||
RID=r$(date +%H%M%S)
|
||||
awk -v r="$RID" '($2=="shot"||$2=="tshot"){$3=r"_"$3} {print}' "$SCRIPT" > "$OUT/script_run.txt"
|
||||
cp "$OUT/script_run.txt" "$DOC/touch_script.txt"
|
||||
[ -n "${PREFIX:-}" ] && cp "$PREFIX" "$DOC/e2e_prefix.jsonl"
|
||||
KEYS=${E2E_KEYS:-'X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame'} # E2E_KEYS:换起局键序(如主菜单直接 A 进默认角色) | E2E_KEYS: replace the run-start key sequence (e.g. press A on the main menu to enter the default character directly)
|
||||
ARGS=(--env DM_SAVE_FRESH=warlock --env DM_TOUCH_SCRIPT=touch_script.txt --env DM_TOUCH_CONTROL_LOG=1
|
||||
--env "DM_C2S_LOG=${RID}_c2s.jsonl" --env "DM_UIMSG=${RID}_uimsg.jsonl" --env "DM_STATE=${RID}_state.jsonl"
|
||||
--env "DM_TICKS=${RID}_ticks.jsonl" --env DM_TICKS_FULL=1 --env DM_TICKS_N=0 --env "DM_TARGET_LOG=${RID}_target.jsonl"
|
||||
--env "DM_KEYS=$KEYS" --env "DM_WATCH=$((CAP + 60))")
|
||||
# 真机档位(缺省开,同 smoke_mac.sh):带真机的画面分辨率与左右安全区;DM_MAC_DEVICE_PROFILE=0 回到按 Mac 窗口原样跑(脚本写死窗口点、按旧布局录的用例用这个)
|
||||
# Real-device profile (on by default, same as smoke_mac.sh): carries the real device's screen resolution and left/right safe areas; DM_MAC_DEVICE_PROFILE=0 goes back to running as-is in the Mac window (use this for scripts with hard-coded window points and cases recorded against the old layout)
|
||||
[ "${DM_MAC_DEVICE_PROFILE:-1}" != 0 ] && ARGS+=(--env DM_GAME_RES=2868x1320 --env DM_TEST_SAFE_L=62 --env DM_TEST_SAFE_R=62)
|
||||
# E2E_DESK=1:这台 Mac 有人在用(窗口会被别的窗口盖住)时带上,出图不走显示节拍、窗口被盖也照出帧(同 smoke_mac.sh 的说明);无人桌面的 mini 不用带
|
||||
# E2E_DESK=1: set it when someone is using this Mac (the window may be covered by other windows); presentation then does not use the display link and
|
||||
# frames are still presented with the window covered (see the note in smoke_mac.sh); not needed on the second Mac with an unattended desktop
|
||||
[ "${E2E_DESK:-0}" = 1 ] && ARGS+=(--env DM_PRESENT_LINK=0)
|
||||
[ -n "${E2E_REF:-}" ] && ARGS+=(--env "DM_TOUCH_REF=$E2E_REF")
|
||||
[ -n "${PREFIX:-}" ] && ARGS+=(--env DM_C2S_REPLAY=e2e_prefix.jsonl --env DM_GAME_SEED=305419896 --env DM_FIXED_TIME=1790895128)
|
||||
if [ -n "${E2E_ENV:-}" ]; then while IFS= read -r kv; do ARGS+=(--env "$kv"); done < <(python3 -c "import json,sys;[print(f'{k}={v}') for k,v in json.loads(sys.argv[1]).items()]" "$E2E_ENV"); fi
|
||||
# iCloud 总闸(tools/cloud_guard.sh):云端指到一次性本地目录;调用方用 E2E_ENV 自己指了本地云端的照它的
|
||||
# iCloud master gate (tools/cloud_guard.sh): the cloud is pointed at a one-off local directory; if the caller specified a local cloud itself through E2E_ENV, that one is used
|
||||
cloud_guard_env "$DOC" "$(python3 -c "import json,sys;print(' '.join(f'{k}={v}' for k,v in json.loads(sys.argv[1] or '{}').items()))" "${E2E_ENV:-}")" || exit 1
|
||||
[ -z "$CG_ENV" ] || ARGS+=(--env "$CG_ENV")
|
||||
# 存档钥匙(tools/save_key.sh):带 DM_SAVE_KEY 的换进自己那份测试存档;多步接着用却不带钥匙的不起
|
||||
# Save key (tools/save_key.sh): runs with DM_SAVE_KEY swap in their own test save; multi-step continuing runs without a key are not started
|
||||
savekey_in "$C" "$(python3 -c "import json,sys;print(' '.join(f'{k}={v}' for k,v in json.loads(sys.argv[1] or '{}').items() if v is not None))" "${E2E_ENV:-}")" || exit 1
|
||||
launch_guard_pre "$C"; mv "$DOC/boot.txt" "$DOC/boot_prev.txt" 2>/dev/null
|
||||
open -n "$W" "${ARGS[@]}" --args -mode boot "${LG_ARGS[@]}" > "$OUT/launch.log" 2>&1 || { echo "【红】open 启动失败:$(tail -1 "$OUT/launch.log")"; exit 1; }
|
||||
for _ in $(seq 30); do [ -s "$DOC/boot.txt" ] && break; sleep 0.5; done; [ -s "$DOC/boot.txt" ] || { launch_guard_blocked "$B" "open 之后 15 秒"; exit 3; }
|
||||
t "已启动,跑 ${CAP}s"; sleep "$CAP"; stop_all; t "已停"
|
||||
CG_BAD=0; cloud_guard_check "$DOC/boot.txt" || CG_BAD=1; cloud_guard_clean "$DOC"
|
||||
ALL="boot.txt ${RID}_c2s.jsonl ${RID}_uimsg.jsonl ${RID}_ticks.jsonl ${RID}_target.jsonl ${RID}_state.jsonl $(awk '$2=="shot"{print $3; print $3".txt"} $2=="tshot"{print $3; print $3".json"}' "$OUT/script_run.txt")"
|
||||
[ -n "${E2E_PULL:-}" ] && ALL=$(for f in $E2E_PULL; do [ "$f" = boot.txt ] && echo boot.txt || echo "${RID}_$f"; done)
|
||||
for f in $ALL; do
|
||||
g=${f#${RID}_}; case $f in ${RID}_*.jsonl) g=e2e_$g;; esac
|
||||
if [ -f "$DOC/$f" ]; then cp "$DOC/$f" "$OUT/$g"; [ "$f" = boot.txt ] || rm -f "$DOC/$f"; else t "【红】没有 ${f}(本局没写)"; fi
|
||||
done
|
||||
left=$(pids); [ -z "$left" ] && t "本机 DmIOS 进程 0" || t "【红】仍有 DmIOS 进程 $left"
|
||||
[ "$CG_BAD" = 0 ] || exit 4
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""全触摸方案:简中字符串里的手柄说法换成触摸说法(所有的手柄按钮操作介绍都应该换成触摸操作介绍;点一下就能完成的提示直接去掉)。
|
||||
做法 = RomFS 覆盖层换字符串文件(与布局覆盖同一套机制),只改 zhCN 一列、按键名定位、原文不符即报错。
|
||||
手势口径:单击看详情并比较、双击使用、拖动装备 / 丢弃 / 出售、长按药水进腰带、底栏十字按钮开面板。
|
||||
Full-touch scheme: in the Simplified Chinese strings, controller wording is replaced with touch wording (every description of a controller button action should become a description of the touch action; hints for things done with a single tap are removed outright).
|
||||
Approach = replace the string files through the RomFS overlay (the same mechanism as the layout overlay), change only the zhCN column, locate entries by key name, and report an error if the original text does not match.
|
||||
Gesture conventions: single tap to see details and compare, double tap to use, drag to equip / drop / sell, long press a potion to put it in the belt, the cross button on the bottom bar opens panels."""
|
||||
import hashlib, json, os, re
|
||||
import touch_layout
|
||||
|
||||
U = '' # 确认键图标; 比较键; 加号键 | Confirm key icon; compare key; plus key
|
||||
# 文件 → {键: (原文校验, 新文)};原文校验 = 游戏现行文字的 SHA-1 前 8 位(表里不存原文);新文为空串 = 这句不要了
|
||||
# file → {key: (original text check, new text)}; original text check = first 8 characters of the SHA-1 of the game's current text (the table does not store the original text); an empty new text = this sentence is dropped
|
||||
TABLE = {
|
||||
'ui-controller.json': {
|
||||
'UseItemController': ('4c4adb8b', '双击使用'),
|
||||
'OpenHoradricCubeController': ('e2d89ec6', '双击打开'),
|
||||
'ReadScrollController': ('61e448cc', '双击阅读'),
|
||||
'UsePotionOfLifeController': ('2ccab0ae', '双击永久增加20点生命值'),
|
||||
'UseBookOfSkillController': ('619bdd63', '双击增加你的技能点'),
|
||||
'UseScrollOfResistanceController': ('bc185cbc', '双击施法'),
|
||||
'UseTokenOfAbsolutionController': ('9a7778b6', '双击重设属性技能点'),
|
||||
'UseTerrorTokenAct1Controller': ('aefa10c5', '双击恐惧化第一幕'),
|
||||
'UseTerrorTokenAct2Controller': ('3005cb15', '双击恐惧化第二幕'),
|
||||
'UseTerrorTokenAct3Controller': ('45921fbf', '双击恐惧化第三幕'),
|
||||
'UseTerrorTokenAct4Controller': ('5ebcc635', '双击恐惧化第四幕'),
|
||||
'UseTerrorTokenAct5Controller': ('0bd3c1fd', '双击恐惧化第五幕'),
|
||||
'comparisonTooltipController': ('0abebcab', ''), # 单击物品就出详情并和身上的比较,不用提示 | A single tap on an item shows its details and compares it with what is equipped, so no hint is needed
|
||||
'hireComparisonTooltipController': ('2f147b1d', ''),
|
||||
'StrYouDiedConsole': ('5336efaf', '你挂了'), # 下面就有「继续」按钮 | There is a 「继续」(Continue) button right below
|
||||
'ControllerInteractButton': ('54234e14', ''), # NPC / 可交互物名字旁的确认键图标(图已透明,占位也去掉) | The confirm key icon next to the names of NPCs / interactable objects (the image is already transparent; the placeholder is removed too)
|
||||
'ControllerTitleScreenPrompt': ('d701b1f2', '点击屏幕开始'),
|
||||
'EnterCharacterName': ('c516bdc5', ''),
|
||||
# 两件可比装备(如两个戒指)之间切换 = 再单击同一件物品(行为归输入层)
|
||||
# Switching between two comparable equipped items (e.g. two rings) = single-tap the same item again (the behavior belongs to the input layer)
|
||||
'ControllerCycleComparisonTooltips': ('d53c0a25', '再点一次与另一件比较'),
|
||||
'SelectButtonNoteText': ('aa4e91fa', ''), # 触摸下交互 = 点目标、拾取 = 点物品名,与技能键无关 | Under touch, interact = tap the target and pick up = tap the item name, unrelated to the skill buttons
|
||||
'MoviePlaybackHoldToSkip_switch': ('f3a05873', ''), # 过场不放(宿主 0.1 秒播完),这句不要 | Cutscenes are not played (the host finishes them in 0.1 s), so this sentence is dropped
|
||||
},
|
||||
'ui.json': {
|
||||
# 通知里不写怎么操作(界面更简洁;十字按钮变红已表达)
|
||||
# Notifications do not say how to operate (the UI is cleaner; the cross button turning red already conveys it)
|
||||
'LevelUpStatsNotificationController': ('7854f598', '你升级了。'),
|
||||
'LevelUpNotificationController': ('7ba311c9', '你升级了。'),
|
||||
'QuestLogNotificationController': ('7b65d87d', '任务已更新。'),
|
||||
'MoviePlaybackHoldToSkip': ('f3a05873', ''),
|
||||
# 大字号排版(不是手柄说法):角色页「技能名 / 命中值」两行标题在 84 高的格子里放不下两行大字——改成单行「技能名命中值」
|
||||
# Large font layout (not controller wording): the two-line title 「技能名 / 命中值」(skill name / Attack Rating) on the character page cannot fit two lines of large text in a cell 84 high -- changed to the single line 「技能名命中值」(skill name Attack Rating)
|
||||
'strchratr': ('703341e1', '%s命中值'),
|
||||
'strchrrat': ('703341e1', '%s命中值'),
|
||||
},
|
||||
}
|
||||
|
||||
# 英文列(英文版):同一批键的 enUS 改成触摸说法;口径同上(空串 = 这句不要)。不在这里的键英文照原版。
|
||||
# 人物页「%s\n命中值」那两条是中文大字号排版问题,英文不动。别的语言列不改(产品只做中英,别的语言我们自己的字按英文)
|
||||
# 与中文表同一写法:原文只存校验(SHA-1 前 8 位),表里不存原版文字
|
||||
# English column (English version): enUS for the same set of keys is changed to touch wording; same rules as above (empty string = this sentence is
|
||||
# dropped). Keys not listed here keep the original English.
|
||||
# The two character-sheet entries of the form "%s, newline, Attack Rating" are a layout issue of the large Chinese font and are left alone in English.
|
||||
# Other language columns are not changed (the product covers only Chinese and English; in other languages our own text uses English)
|
||||
# Written the same way as the Chinese table: for the source text only a check is stored (first 8 characters of the SHA-1), and the original game's text
|
||||
# is not stored in the table
|
||||
EN = {
|
||||
'ui-controller.json': {
|
||||
'UseItemController': ('3c07d84d', 'Double-tap to Use'),
|
||||
'OpenHoradricCubeController': ('3c06b741', 'Double-tap to Open'),
|
||||
'ReadScrollController': ('5b76ecf7', 'Double-tap to Read'),
|
||||
'UsePotionOfLifeController': ('74604765', 'Double-tap to permanently add 20 to Life'),
|
||||
'UseBookOfSkillController': ('3a031cc6', 'Double-tap to learn skill of your choice'),
|
||||
'UseScrollOfResistanceController': ('ce192aed', 'Double-tap to Cast'),
|
||||
'UseTokenOfAbsolutionController': ('3ba19ef3', 'Double-tap to reset Stat/Skill Points'),
|
||||
'UseTerrorTokenAct1Controller': ('73cb07eb', 'Double-tap to terrorize Act 1'),
|
||||
'UseTerrorTokenAct2Controller': ('8c394882', 'Double-tap to terrorize Act 2'),
|
||||
'UseTerrorTokenAct3Controller': ('558bcf92', 'Double-tap to terrorize Act 3'),
|
||||
'UseTerrorTokenAct4Controller': ('07eadb68', 'Double-tap to terrorize Act 4'),
|
||||
'UseTerrorTokenAct5Controller': ('9f1ff50e', 'Double-tap to terrorize Act 5'),
|
||||
'comparisonTooltipController': ('48cc0c36', ''),
|
||||
'hireComparisonTooltipController': ('a97423d0', ''),
|
||||
'StrYouDiedConsole': ('e2908c71', 'You have died'),
|
||||
'ControllerInteractButton': ('54234e14', ''),
|
||||
'ControllerTitleScreenPrompt': ('75c1a3c8', 'Tap the Screen to Begin'),
|
||||
'EnterCharacterName': ('8334a399', ''),
|
||||
'ControllerCycleComparisonTooltips': ('389c3ec9', 'Tap again to compare with the other'),
|
||||
'SelectButtonNoteText': ('e0bafb15', ''),
|
||||
'MoviePlaybackHoldToSkip_switch': ('dab56a9e', ''),
|
||||
},
|
||||
'ui.json': {
|
||||
'LevelUpStatsNotificationController': ('525fb31a', "You've leveled up."),
|
||||
'LevelUpNotificationController': ('1e4882b2', "You've leveled up."),
|
||||
'QuestLogNotificationController': ('94d110a8', 'Quest has been updated.'),
|
||||
'MoviePlaybackHoldToSkip': ('dab56a9e', ''),
|
||||
},
|
||||
}
|
||||
|
||||
# 手柄支持:手柄说法 ↔ 触摸说法按模式切,不再改字符串文件——build_sidecar 出旁路表,宿主触屏模式把串表里这几个键的串换成触摸说法、
|
||||
# 手柄模式换回原文(dm/host/dm_padmode.c)。只有下面这两条是排版用的(大字号,两种模式都要),照旧改文件
|
||||
# Controller support: controller wording ↔ touch wording is switched by mode and the string files are no longer modified. build_sidecar emits a sidecar table;
|
||||
# in touch mode the host swaps the strings of these keys in the string table to the touch wording,
|
||||
# and in controller mode swaps the original text back (dm/host/dm_padmode.c). Only the two entries below are for typesetting (large font size, needed in
|
||||
# both modes) and still modify the files as before
|
||||
FILE_ONLY = {'strchratr', 'strchrrat'}
|
||||
|
||||
def build_sidecar(romfs):
|
||||
"""[(键, 原文校验, 触摸说法)]:FILE_ONLY 以外的全部条目;原文校验同 TABLE(宿主按它认串表里的原文,对不上不换)。 | [(key, source checksum, touch wording)]: all entries other than FILE_ONLY; the source checksum is the same as in TABLE (the host uses it to identify the original text in the string table and does not swap on a mismatch)."""
|
||||
out = []
|
||||
for name, items in TABLE.items():
|
||||
path, text = touch_layout.read_layout(romfs, None, suffix='/lng/strings/' + name)
|
||||
for key, (old, new) in items.items():
|
||||
if key in FILE_ONLY: continue
|
||||
m = re.search(r'"Key":\s*"%s",.*?"zhCN":\s*("(?:[^"\\]|\\.)*")' % re.escape(key), text, re.S)
|
||||
if not m: raise SystemExit('touch_strings:%s 里没有键 %s' % (name, key))
|
||||
cur = json.loads(m.group(1))
|
||||
if hashlib.sha1(cur.encode('utf-8')).hexdigest()[:8] != old: raise SystemExit('touch_strings:%s 的原文变了(校验 %s,现行「%s」)——原包换了版本,核过再改表' % (key, old, cur))
|
||||
out.append((key, old, new))
|
||||
# 英文列(英文版):同一批键再各出一行,原文校验是 enUS 的原文。宿主按「串表里此刻的原文」认校验(dm_padmode.c str_apply),
|
||||
# 游戏语言是英文时中文那行对不上不换、英文这行对上才换,反之亦然;不用宿主另跟语言
|
||||
# English column (English version): the same set of keys gets one more row each, whose source-text check is against the enUS source text. The host
|
||||
# matches the check against "the source text in the string table at this moment" (dm_padmode.c str_apply):
|
||||
# when the game language is English the Chinese row does not match and is not applied while the English row matches and is applied, and vice versa; the
|
||||
# host does not have to follow the language separately
|
||||
for key, (old, new) in EN.get(name, {}).items():
|
||||
m = re.search(r'"Key":\s*"%s",.*?"enUS":\s*("(?:[^"\\]|\\.)*")' % re.escape(key), text, re.S)
|
||||
if not m: raise SystemExit('touch_strings:%s 里没有键 %s 的 enUS' % (name, key))
|
||||
cur = json.loads(m.group(1))
|
||||
if hashlib.sha1(cur.encode('utf-8')).hexdigest()[:8] != old: raise SystemExit('touch_strings:%s 的 enUS 原文变了(校验 %s,现行「%s」)——原包换了版本,核过再改表' % (key, old, cur))
|
||||
out.append((key, old, new))
|
||||
return out
|
||||
|
||||
def build(romfs, outdir):
|
||||
"""返回 ({包内逻辑路径(小写): 本地文件}, 改了几条)。 | Returns ({logical path in package (lowercase): local file}, number of entries changed)."""
|
||||
repl = {}; total = 0
|
||||
for name, items in TABLE.items():
|
||||
path, text = touch_layout.read_layout(romfs, None, suffix='/lng/strings/' + name)
|
||||
if not any(k in FILE_ONLY for k in items): continue
|
||||
for key, (old, new) in items.items():
|
||||
if key not in FILE_ONLY: continue
|
||||
m = re.search(r'"Key":\s*"%s",.*?"zhCN":\s*("(?:[^"\\]|\\.)*")' % re.escape(key), text, re.S)
|
||||
if not m: raise SystemExit('touch_strings:%s 里没有键 %s' % (name, key))
|
||||
cur = json.loads(m.group(1))
|
||||
if hashlib.sha1(cur.encode('utf-8')).hexdigest()[:8] != old: raise SystemExit('touch_strings:%s 的原文变了(校验 %s,现行「%s」)——原包换了版本,核过再改表' % (key, old, cur))
|
||||
text = text[:m.start(1)] + json.dumps(new, ensure_ascii=False) + text[m.end(1):]; total += 1
|
||||
o = os.path.join(outdir, 'str_' + name); open(o, 'w', encoding='utf-8-sig', newline='').write(text); repl[path.lower()] = o
|
||||
return repl, total
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,78 @@
|
||||
# 改动文件 → 受影响的 uireg 局(uireg_pick.py 读;合入门槛 = 受影响局 + 核心局 + Mac 冒烟,整表只在出大包前 / 夜里浸泡)
|
||||
# 列:路径通配(fnmatch,相对仓库根)<TAB> 局(空格分隔;* = 整表;- = 不挑局,只跑核心局)。从上往下匹配,取第一条命中的行(具体的写在前、通配的兜底写在后)。@uireg = 按 uireg.py 改动落在哪些局里。
|
||||
# 新规矩:交来的分支只跑「这里挑出的局 + 它自己的专项」,两档整表只在合批候选头上跑一遍;批次叠放时用 uireg_pick.py --main <前一批候选头> 挑。
|
||||
# 这里挑不到的东西靠专项补:秘境(dm_rift*)要真机专项;手柄(dm_padmode / hle_hid / dm_gamepad.m)要手柄局;资源定位(romfs_validate / asset_dl / main.m 启动段)要真机资源现场;
|
||||
# 动 dm/ios 外壳启动路径(main.m、front_ios.m 的建视图 / 生命周期段)的分支,交回归前必须自己跑过真机 smoke.sh(bg-launch 两次退回:iPad 档进不了局、真机冒烟 0/3)。
|
||||
# 新加局时顺手在这里登记;没登记的 dm/ 源文件,uireg_pick.py 记「未登记」并按整表处理(宁多跑不漏跑)。
|
||||
dm/host/tests/* -
|
||||
dm/host/Makefile -
|
||||
dm/tools/patch_nso.py *
|
||||
dm/PRODUCT *
|
||||
dm/ios/tools/gen_romfs_overlay.py *
|
||||
dm/i18n/* *
|
||||
dm/ios/tools/dm_i18n.py *
|
||||
dm/host/dm_i18n* *
|
||||
dm/ios/tools/annot_strings.py k j rw1 rw2 kbb vt1
|
||||
dm/host/dm_textbox* k j rw1 rw2 kbb vt1
|
||||
dm/host/dm_runeword* k j rw1 rw2 rwp rwd d
|
||||
dm/host/dm_vault* vf1 vf2 vt1 pg1 pg2 c s sb t u d cb
|
||||
dm/host/dm_pages* pg1 pg2 vt1 c s sb
|
||||
dm/ios/tools/wide_stash.py vf1 vf2 vt1 pg1 pg2 c s sb t u d cb
|
||||
dm/ios/tools/gen_trove_art.py s sb t u d cb
|
||||
dm/ios/tools/gen_widestash_art.py vf1 vf2 vt1 pg1 pg2 c s sb t u d cb
|
||||
dm/ios/tools/gen_vault_table.py vt1
|
||||
dm/host/dm_potpick* bd bdm p q b
|
||||
dm/host/dm_lootfilter* bd bdm p q b
|
||||
dm/host/dm_autobuff* bd bdm p q b
|
||||
dm/host/dm_beltauto* ba bd bdm p q b
|
||||
dm/host/dm_kills* kba kbb
|
||||
dm/host/dm_elysium* v v2 kbb
|
||||
dm/host/dm_bossrush* kbb bd
|
||||
dm/host/dm_townwp* *
|
||||
dm/host/dm_rift* kba kbb dc wp tp
|
||||
dm/host/dm_unit.h kbb dc wp tp
|
||||
dm/host/dm_pouch* t u s sb vt1 c
|
||||
dm/host/dm_padmode* a f rf2 pk od pvb psel0 psel1 psel2 psel3
|
||||
dm/host/hle_fs.c rf1 rf2 rf3 e pg2 vt1 v od
|
||||
dm/host/hle_tact* a e od
|
||||
dm/host/hle_hid* a f rf2 pk sl1
|
||||
dm/ios/Sources/dm_gamepad.m a f rf2 pk
|
||||
dm/host/romfs_validate* e pk rf2
|
||||
dm/ios/Sources/asset_dl.m e pk rf2
|
||||
dm/ios/Sources/main.m a e pk rf2 top od
|
||||
dm/ios/run.sh e pk
|
||||
dm/i18n/* a e k kba vt1 rf2
|
||||
dm/host/dm_bright* a top
|
||||
dm/host/dm_drophaptic* kbb
|
||||
dm/host/dm_freetp* tp a p q f g
|
||||
dm/host/dm_dropfilter* kbb
|
||||
dm/host/dm_shoprefresh* b m p ra top me1 me3 pvb
|
||||
dm/host/dm_world* ex tb tp dz top i b
|
||||
dm/host/dm_actions* a g n
|
||||
dm/host/dm_hud* a f pk bd bdm q g
|
||||
dm/host/dm_uiscreen* a f pk bd q sb
|
||||
dm/host/dm_cloudsync* rf3 e pg2 vt1 v
|
||||
dm/host/dm_update* e
|
||||
dm/host/dm_custom* e kbb
|
||||
dm/host/hle_charname* e v
|
||||
dm/host/dm_namegen* e v
|
||||
dm/host/dm_textinput* e v vt1
|
||||
dm/host/dm_cursor* a c f g h j m n p q s t u sb cb sl1 sl2 me1 me2 pg2 vt1 rw1 bd
|
||||
dm/host/hle_touch* a c f g h j m n p q s t u sb cb sl1 sl2 me1 me2 pg2 vt1 rw1 bd
|
||||
dm/host/touch_mac.c a c j s sb pg2 vt1 rw1
|
||||
dm/ios/tools/touch_layout.py a c f g h j k m n p q s t u sb cb sl1 me1 me2 pg2 vt1 vf1 vf2 rw1 rw2 kba bd pk pvb
|
||||
dm/ios/Sources/front_ios.m a c f g h j m n p q s t u sb cb sl1 sl2 me1 me2 pg2 vt1 rw1 bd pk
|
||||
dm/ios/Sources/* a e pk rf2
|
||||
dm/ios/NativeHUD/* a f pk bd g q
|
||||
dm/host/diag.c -
|
||||
dm/host/crash.c -
|
||||
dm/host/hle_* *
|
||||
dm/host/*.c *
|
||||
dm/host/*.h *
|
||||
dm/ios/tools/uireg/uireg.py @uireg
|
||||
dm/ios/tools/* -
|
||||
dm/verify/* -
|
||||
docs/* -
|
||||
*.md -
|
||||
dm/ios/tools/merc_slots.py f ms
|
||||
dm/ios/tools/gen_merc_art.py f ms
|
||||
|
Executable
+48
@@ -0,0 +1,48 @@
|
||||
#!/bin/bash
|
||||
# uireg 的起局脚本(真机 iPhone):UIREG_RUNNER=<本文件> python3 uireg.py iphone <局名…>。接口同 run_mac.sh(<标签> <上限秒> < 触点脚本)。
|
||||
# 走 ../touch_e2e.sh:它自己取设备锁、按 pid 停 App、设备读本机配置(local_env.sh)。被测的是手机上已经装好的那个包——装包与本脚本之间放过锁的话,包可能已被别人换掉,
|
||||
# 要保证是自己的包,就在外层先取设备锁把「装包 + 跑」包住(设备锁可重入)。
|
||||
# 与 Mac 上的差别:只有 iphone 档;跑满上限秒才收(不提前收);只拉 boot.txt 与命令包日志——截图每张约 20 秒不拉,所以「只看截图」的项在真机上都是未判;
|
||||
# 没有 d 局的专用存档(PW_SAVE 非空的局不跑)。
|
||||
# UIREG_PULL="put_00.png put_01.png":额外拉回这几张截图(读画面的判据要用;每张约 20 秒,算在持锁时间里)。
|
||||
# uireg run-start script (real-device iPhone): UIREG_RUNNER=<this file> python3 uireg.py iphone <run names...>. Same interface as run_mac.sh (<label> <limit seconds> < touch point script).
|
||||
# Goes through ../touch_e2e.sh: it takes the device lock itself, stops the App by pid, and reads the device from the local config (local_env.sh). What is tested is the bundle already installed on the phone -- if the lock was released between installing and this script, the bundle may already have been replaced by someone else,
|
||||
# so to make sure it is your own bundle, take the device lock in an outer layer first to wrap 'install + run' (the device lock is reentrant).
|
||||
# Differences from the Mac: only the iphone profile; the run ends only after the full limit in seconds (no early end); only boot.txt and the command packet log are pulled -- screenshots take about 20 seconds each and are not pulled, so 'screenshot-only' items are all unjudged on the real device;
|
||||
# there is no dedicated save for the d runs (runs with a non-empty PW_SAVE are not run).
|
||||
# UIREG_PULL="put_00.png put_01.png": additionally pull back these screenshots (needed for criteria that read the picture; about 20 seconds each, counted in the lock hold time).
|
||||
unset LANG LC_CTYPE; export LC_ALL=C # touch_e2e.sh 里「变量后紧跟中文标点」的行在 UTF-8 区域设置下会被 bash 3.2 当成变量名的一部分 | Lines in touch_e2e.sh where 'a variable is immediately followed by Chinese punctuation' are treated by bash 3.2 as part of the variable name under a UTF-8 locale
|
||||
TAG=$1; CAP=$2; HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
O=${UIREG_OUT:-${DM_ROOT:-$HOME/dm-work}/run/uireg}/pw/$TAG; mkdir -p "$O"; cat > "$O/in.txt"
|
||||
[ "${UIREG_MODE:-iphone}" = iphone ] || { echo "计时:真机只有 iphone 档,没跑" > "$O/timing.txt"; exit 2; }
|
||||
[ -z "${PW_SAVE:-}" ] || { echo "计时:真机上没有存档 ${PW_SAVE},没跑" > "$O/timing.txt"; exit 2; }
|
||||
rm -f "$O/boot.txt" "$O/boot_full.txt" "$O/c2s.jsonl" "$O/e2e_c2s.jsonl"
|
||||
# 触点脚本的裸坐标按 667×375 的 16:9 画面写 → DM_TOUCH_REF 由 App 换算到真机屏;touch_e2e.sh 一定带按键脚本变量,这里给一条永不触发的占位键序,
|
||||
# 并显式打开前端自动进选角页(DM_FE_AUTO,不带按键脚本时它缺省就开);命令包日志名与存档由 touch_e2e.sh 自己定
|
||||
# The touch point script's bare coordinates are written for a 667×375 16:9 picture → converted by the App to the real-device screen via DM_TOUCH_REF; touch_e2e.sh always passes the key script variable, so a placeholder key sequence that never triggers is given here,
|
||||
# and front-end auto-entry into the character select page is turned on explicitly (DM_FE_AUTO, which is on by default when no key script is passed); the command packet log name and the save are decided by touch_e2e.sh itself
|
||||
J=$(python3 -c "
|
||||
import json,sys
|
||||
d={'DM_TOUCH_SCRIPT_START':'menu','DM_TOUCH_REF':'667x375','DM_FE_AUTO':'1'}
|
||||
for kv in sys.argv[1].split():
|
||||
k,v=kv.split('=',1)
|
||||
if k not in ('DM_C2S_LOG','DM_SAVE_FRESH'): d[k]=v
|
||||
print(json.dumps(d))" "${PW_ENV:-}")
|
||||
t0=$(date +%s)
|
||||
E2E_KEYS='B@OpenPanel:NoSuchPanelEver' E2E_ENV="$J" E2E_PULL="boot.txt c2s.jsonl ${UIREG_PULL:-}" bash "$HERE/../touch_e2e.sh" "$O/in.txt" "$O" "$CAP" > "$O/e2e.log" 2>&1
|
||||
[ -f "$O/e2e_c2s.jsonl" ] && cp "$O/e2e_c2s.jsonl" "$O/c2s.jsonl"
|
||||
# 包对不对读出来核:boot.txt 首行的构建号必须等于被测提交的提交时间戳(dm/ios/run.sh build 写进去的)。被测提交缺省 = 本脚本所在树的 HEAD,
|
||||
# 包是从别的树出的就用 UIREG_EXPECT_COMMIT=<提交> 指明。不等 = 设备上跑的不是这一批的包(没装 / 被别人换了 / 树不干净出的包)→ 整局作废:日志换成一行红,各项都判不通。
|
||||
# Whether the package is the right one is read out and checked: the build number on the first line of boot.txt must equal the commit timestamp of the
|
||||
# commit under test (written in by dm/ios/run.sh build). The commit under test defaults to HEAD of the tree this script lives in;
|
||||
# if the package was built from another tree, name it with UIREG_EXPECT_COMMIT=<commit>. A mismatch = the device is not running this batch's package
|
||||
# (not installed / replaced by someone else / built from a dirty tree) → the whole run is void: the log is replaced by a single failure line and every item
|
||||
# fails.
|
||||
EXP=$(git -C "$HERE" log -1 --format=%ct ${UIREG_EXPECT_COMMIT:-} 2>/dev/null); GOT=$(LC_ALL=C grep -a -m1 -o 'boot: 版本 [^ ]* 构建 [0-9]*' "$O/boot.txt" 2>/dev/null | awk '{print $NF}')
|
||||
if [ "${UIREG_BUILD_CHECK:-1}" = 1 ] && [ -f "$O/boot.txt" ] && [ "$GOT" != "$EXP" ]; then
|
||||
mv "$O/boot.txt" "$O/boot_wrongpkg.txt"; echo "[dm] 【红】包不对,整局作废:设备上这一局的构建号 ${GOT:-读不到},期望 ${EXP:-读不到}(提交 $(git -C "$HERE" log -1 --format=%h ${UIREG_EXPECT_COMMIT:-} 2>/dev/null | cut -c1-9) 的提交时间戳);原日志在 boot_wrongpkg.txt" > "$O/boot.txt"
|
||||
fi
|
||||
# 真机跑满上限秒才收:脚本走完之后静置的那一段(会有「无进展」看门狗红行)不属于这一局,日志截到「note 结束」为止,与 Mac 上见到记号就收的范围一致;全文留在 boot_full.txt
|
||||
# On the real device the run only ends after the full limit in seconds: the idle stretch after the script finishes (which gets 「无进展」(no progress) watchdog failure lines) does not belong to this run, so the log is cut at 「note 结束」(note end), matching the range on the Mac where the run ends as soon as the marker is seen; the full text is kept in boot_full.txt
|
||||
if LC_ALL=C grep -a -q '\[script\] note 结束' "$O/boot.txt" 2>/dev/null; then mv "$O/boot.txt" "$O/boot_full.txt"; LC_ALL=C awk '{ print } /\[script\] note 结束/ { exit }' "$O/boot_full.txt" > "$O/boot.txt"; fi
|
||||
echo "计时:真机整局墙钟 $(( $(date +%s) - t0 )) 秒(含排锁、推脚本、拉日志)" > "$O/timing.txt"
|
||||
Executable
+89
@@ -0,0 +1,89 @@
|
||||
#!/bin/bash
|
||||
# uireg 的起局脚本(Mac 上的 iOS 包,在本机跑):run_mac.sh <标签> <上限秒> < 触点脚本。约定见 uireg.py 文件头与「usage.md」。
|
||||
# 玩家路径:只带触点脚本,不带按键脚本接管;PW_ENV(空格分隔的 K=V)原样加到起包环境;PW_SAVE 非空 = 换上容器 Data 下这份存档的副本,跑完挪回。
|
||||
# 包按 UIREG_MODE 挑:iphone = $UIREG_APP(缺省 <树>/.iosdd_mac/DmMacSmoke.app,smoke_mac.sh 包好的那份);ipad / ipadfull = $UIREG_APP_IPAD(没有缺省,出法见usage.md)。
|
||||
# 不拷包、不同步,直接从给的路径起(计时里「拷包」恒为 0)。要换包请另起目录名,包在跑的时候别动它的 Wrapper 那层:
|
||||
# 系统把 <包>/Wrapper 挂载出去跑,挂着时源目录被删或整体替换,会留下卸不掉的失效挂载点,那个路径从此 open 不了。
|
||||
# Run launcher script for uireg (the iOS app on Mac, run on this machine): run_mac.sh <tag> <limit seconds> < touch point script. Conventions are in the uireg.py file header and usage.md.
|
||||
# Player path: only a touch point script, no key script taking over; PW_ENV (space-separated K=V) is added as-is to the app launch environment; non-empty PW_SAVE = swap in a copy of this save under the container's Data, and move it back after the run.
|
||||
# The app is picked by UIREG_MODE: iphone = $UIREG_APP (default <tree>/.iosdd_mac/DmMacSmoke.app, the one packaged by smoke_mac.sh); ipad / ipadfull = $UIREG_APP_IPAD (no default, see usage.md for how to produce it).
|
||||
# No copying or syncing of the app, it is launched directly from the given path (the 「拷包」(copy app) entry in the timing is always 0). To switch apps use another directory name, and do not touch the app's Wrapper layer while it is running:
|
||||
# the system mounts <app>/Wrapper out to run it; if the source directory is deleted or replaced wholesale while mounted, a stale mount point that cannot be unmounted is left behind, and that path can never be opened again.
|
||||
set -u
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../local_env.sh" # 本机配置(包名、团队号、设备号) | Local config (package name, team ID, device ID)
|
||||
B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
|
||||
TAG=$1; CAP=$2; HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
O=${UIREG_OUT:-${DM_ROOT:-$HOME/dm-work}/run/uireg}/pw/$TAG; mkdir -p "$O"; cat > "$O/script.txt"; : > "$O/launch.log"
|
||||
fail(){ echo "$*" | tee "$O/fail.txt"; echo "计时:${1}" > "$O/timing.txt"; exit 2; }
|
||||
case ${UIREG_MODE:-iphone} in
|
||||
iphone) W=${UIREG_APP:-$(git -C "$HERE" rev-parse --show-toplevel 2>/dev/null)/.iosdd_mac/DmMacSmoke.app};;
|
||||
*) W=${UIREG_APP_IPAD:-};;
|
||||
esac
|
||||
[ -x "$W/Wrapper/DmIOS.app/DmIOS" ] || fail "没有包(画面档 ${UIREG_MODE:-iphone}):${W:-未设 UIREG_APP_IPAD}"
|
||||
C=""; for m in "$HOME"/Library/Containers/*/.com.apple.containermanagerd.metadata.plist; do
|
||||
[ "$(/usr/libexec/PlistBuddy -c 'Print :MCMMetadataIdentifier' "$m" 2>/dev/null)" = "$B" ] && C="$(dirname "$m")/Data"; done
|
||||
D="$C/Documents"; [ -n "$C" ] && [ -d "$D" ] || fail "本机没有 $B 的容器(先跑一次 smoke_mac.sh 1)"
|
||||
# 同一台 Mac 上同包只能起一个实例:与 Mac 冒烟 / 触屏用例共用 macsmoke 锁(可重入:外层已持锁的调用不再排队)
|
||||
# Only one instance of the same app can be started on one Mac: shares the macsmoke lock with the Mac smoke test / touch cases (reentrant: a call whose outer layer already holds the lock does not queue again)
|
||||
T_B=$(date +%s); export DM_DEVLOCK_DIR=${DM_ROOT:-$HOME/dm-work}/run/ios/macsmoke.lock; source "$HERE/../devlock.sh"; devlock_acquire "${SMOKE_OWNER:-未署名} 界面回归 $TAG"; T_C=$(date +%s)
|
||||
# 只认本包(bundle id = $B):同机还可能跑着回归多实例的重签包 <包名>.reg<N>(各自独立容器),按可执行文件后缀认会把它们当成本包、收尾时一起杀掉。
|
||||
# 查不到 bundle id 的(刚起、系统还没登记)照旧算本包,只排除明确是别的 bundle 的
|
||||
# Only this package is recognized (bundle id = $B): the same machine may also be running the regression multi-instance re-signed packages <package name>.reg<N> (each with its own container); matching by executable suffix would take them as this package and kill them along at wrap-up.
|
||||
# Those whose bundle id cannot be found (just launched, not yet registered by the system) still count as this package; only those clearly belonging to another bundle are excluded
|
||||
pids() { local p b; for p in $(ps -axo pid=,comm= | awk '{ pid=$1; $1=""; sub(/^ /,""); if ($0 ~ /\/Wrapper\/DmIOS\.app\/DmIOS$/) print pid }'); do
|
||||
b=$(lsappinfo info -only bundleID -app "$p" 2>/dev/null | sed -n 's/.*="\(.*\)"$/\1/p'); [ -z "$b" ] || [ "$b" = "$B" ] && echo "$p"; done; }
|
||||
stop_all(){ local p; for p in $(pids); do kill -TERM "$p" 2>/dev/null; done; sleep 1; for p in $(pids); do kill -KILL "$p" 2>/dev/null; done; }
|
||||
pre=$(pids | tr '\n' ' '); [ -z "$pre" ] || { devlock_release; fail "本机已有 $B 的实例在跑(pid ${pre},非本次启动)"; }
|
||||
# 换存档的收尾:跑过的那份留在 Data 下(save.uireg_ran,只留最近一份),原存档挪回 Documents/save。挪不回 = 容器里的正式存档不在原位,之后所有本机包都受影响:
|
||||
# 报红(fail.txt + 退出码 4)并写明原存档在哪,不静默(只读副本挪不走,原存档留在 swap 目录里没人知道)
|
||||
# 换存档一律换进测试存档目录 Documents/save.test 并带 DM_SAVE_TEST=1 起局,不碰产品存档 Documents/save:挂产品存档目录的局会连真实 iCloud,
|
||||
# 登着真实账号的机器上换进去的测试角色会被同步上云。跑完再查一遍日志,出现同步动作就报红。
|
||||
# Wrap-up of a save swap: the copy that was run stays under Data (save.uireg_ran, only the latest one kept), and the original save moves back to Documents/save. Failing to move it back = the real save in the container is not in place, which affects every local package afterwards:
|
||||
# report a failure (fail.txt + exit code 4) and state where the original save is, never silently (a read-only copy cannot be moved away, and nobody would know the original save was left in the swap directory)
|
||||
# A save swap always swaps into the test save directory Documents/save.test and starts the run with DM_SAVE_TEST=1, without touching the product save Documents/save: a run that mounts the product save directory connects to real iCloud,
|
||||
# and on a machine signed in to a real account the swapped-in test character would be synced to the cloud. After the run the log is checked once more, and any sync action is reported as a failure.
|
||||
SV="$D/save.test"; SWAP=""; BAD=""; restore(){ [ -n "$SWAP" ] || return 0; chmod -R u+w "$SV" 2>/dev/null; rm -rf "$C/save.uireg_ran" "$SV.work"
|
||||
if mv "$SV" "$C/save.uireg_ran" && mv "$SWAP" "$SV"; then SWAP=""; else BAD=1; echo "【红】换存档后挪不回:原测试存档在 ${SWAP},Documents/save.test 不是原来那份,手工核对后挪回" | tee "$O/fail.txt"; [ -f "$O/timing.txt" ] && sed -i '' '1s/$/ 【红】换存档后挪不回,见 fail.txt/' "$O/timing.txt"; fi; } # timing.txt 那行 uireg.py 会抄进表头 | uireg.py copies the timing.txt line into the table header
|
||||
trap 'stop_all; restore; savekey_out "$C"; devlock_release; [ -z "$BAD" ] || exit 4' EXIT; trap 'exit 143' INT TERM
|
||||
# 存档钥匙(../save_key.sh):带 DM_SAVE_KEY 的换进自己那份测试存档;带 DM_SAVE_TEST=1 接着用却不带钥匙的不起。换存档的局(PW_SAVE)自带存档,不走钥匙
|
||||
# Save key (../save_key.sh): runs with DM_SAVE_KEY swap in their own test save; runs continuing with DM_SAVE_TEST=1 but without a key are not started. Save-swap runs (PW_SAVE) bring their own save and do not use a key
|
||||
source "$HERE/../launch_guard.sh"; launch_guard_pre "$C"; source "$HERE/../save_key.sh"; [ -n "${PW_SAVE:-}" ] || savekey_in "$C" "${PW_ENV:-}" || fail "存档钥匙不许起这一局(见上一行红字)"
|
||||
if [ -n "${PW_SAVE:-}" ]; then
|
||||
[ -d "$C/$PW_SAVE" ] || fail "容器 Data 下没有存档 ${PW_SAVE}(d 局专用,备法见usage.md)"
|
||||
# SWAP 等原存档真的挪走了才置(先置的话,挪不走时收尾会把没动过的原存档当成「跑过的那份」挪走);副本一律加写权限:
|
||||
# 外来存档目录常是只读的,原样拷进来游戏的存档事务清不掉它生成的 save.work,之后任何包启动都 FATAL
|
||||
# SWAP is set only once the original save has really been moved away (if set first, when the move fails the cleanup would move away the untouched original save as 'the one that was run'); copies always get write permission added:
|
||||
# external save directories are often read-only, and copied in as-is the game's save transaction cannot clear the save.work it generates, after which any bundle FATALs on launch
|
||||
S1="$C/save.uireg_swap_$$"; [ -d "$SV" ] || mkdir -p "$SV"; mv "$SV" "$S1" || fail "换存档失败:原测试存档挪不走"; SWAP="$S1"; rm -rf "$SV.work"
|
||||
cp -R "$C/$PW_SAVE" "$SV" && chmod -R u+w "$SV" || fail "换存档失败:副本拷不进去"
|
||||
fi
|
||||
caffeinate -u -t 3 >/dev/null 2>&1 # 屏幕睡着时取不到可绘制表面,游戏主线程会卡在取图 | While the screen is asleep no drawable surface can be obtained, and the game's main thread gets stuck acquiring the drawable
|
||||
RID=u$(date +%H%M%S); awk -v r="$RID" '$2=="shot"{$3=r"_"$3} {print}' "$O/script.txt" > "$D/touch_script.txt"
|
||||
EX=(); for kv in ${PW_ENV:-}; do EX+=(--env "$kv"); done; [ -z "${PW_SAVE:-}" ] || EX+=(--env DM_SAVE_TEST=1)
|
||||
# 本机起包的总闸(../cloud_guard.sh):每一局都带「不同步」开关,自己指了本地云端目录的 iCloud 用例除外;跑完核启动日志
|
||||
# Master gate for launching the package on this Mac (../cloud_guard.sh): every run carries the "no sync" switch, except iCloud cases that specify a local cloud directory themselves; the launch log is checked after the run
|
||||
source "$HERE/../cloud_guard.sh"; cloud_guard_env "$D" "${PW_ENV:-}" || fail "总闸不许起这一局(见上一行红字)"; [ -z "$CG_ENV" ] || EX+=(--env "$CG_ENV")
|
||||
# DM_UIMSG=1:界面消息行(UIMSG …)只有带了它才打进日志,前端 / 确认框 / 暂停菜单那批判据靠这些行;DM_WATCH:到点自己退出的兜底
|
||||
# open 后 10 秒没有 boot.txt = 这次没起来:收掉重起一次,再不行整局判失败,不等满上限
|
||||
# DM_UIMSG=1: UI message lines (UIMSG ...) are written to the log only with it, and the criteria for the front end / confirmation box / pause menu batch rely on these lines; DM_WATCH: the fallback that exits by itself when time is up
|
||||
# No boot.txt 10 seconds after open = it did not start this time: kill it and start again once, and if that fails too the whole run is judged failed without waiting out the limit
|
||||
launch(){ mv "$D/boot.txt" "$D/boot_prev.txt" 2>/dev/null
|
||||
open -n "$W" ${EX[@]+"${EX[@]}"} --env DM_TOUCH_SCRIPT=touch_script.txt --env DM_TOUCH_SCRIPT_START=menu --env DM_UIMSG=1 --env "DM_WATCH=$((CAP + 60))" --args -mode boot "${LG_ARGS[@]}" >> "$O/launch.log" 2>&1
|
||||
local i; for i in $(seq 20); do [ -s "$D/boot.txt" ] && return 0; sleep 0.5; done; return 1; }
|
||||
TRY=1
|
||||
if ! launch; then stop_all; TRY=2; launch || { launch_guard_blocked "$B" "两次 open 各等 10 秒" 2>&1 | tee "$O/fail.txt"; echo "计时:拷包 0 排锁 $((T_C - T_B)) 启动失败(两次都没有 boot.txt)" | tee "$O/timing.txt"; exit 3; }; fi
|
||||
T_D=$(date +%s)
|
||||
# 见到脚本末行的记号就收;上限秒只是兜底
|
||||
# End the run as soon as the marker on the script's last line is seen; the limit in seconds is only a fallback
|
||||
END=$((T_D + CAP)); while [ "$(date +%s)" -lt "$END" ]; do LC_ALL=C grep -a -q '\[script\] note 结束' "$D/boot.txt" 2>/dev/null && break; [ -n "$(pids)" ] || break; sleep 0.5; done; T_E=$(date +%s)
|
||||
stop_all
|
||||
cp "$D/boot.txt" "$O/boot.txt" 2>/dev/null; [ -f "$D/pwc2s.jsonl" ] && mv "$D/pwc2s.jsonl" "$O/c2s.jsonl"
|
||||
# 真实 iCloud 闸:本该不同步的局出现了同步动作 = 连了真云端,这一局作废
|
||||
# Real iCloud gate: a sync action appearing in a run that should not sync = it connected to the real cloud, and this run is void
|
||||
cloud_guard_check "$O/boot.txt" || { BAD=1; echo "【红】这一局出现了 iCloud 同步动作,结果作废,立刻核云端目录" | tee "$O/fail.txt"; }; cloud_guard_clean "$D"
|
||||
# 换存档的局:进局后日志里的角色名(宿主每次进局都打「刷怪积分牌:「<角色名>」…」)必须是换进来那份存档里的角色,不是 = 挂的不是换进去的那份
|
||||
# Save-swap runs: the character name in the log after entering the run (the host prints 「刷怪积分牌:「<角色名>」…」(kill board: "<character name>"...) on every run entry) must be the character in the swapped-in save; if it is not = the save mounted is not the one swapped in
|
||||
if [ -n "${PW_SAVE:-}" ]; then WHO=$(LC_ALL=C sed -n 's/.*刷怪积分牌:「\([^」]*\)」.*/\1/p' "$O/boot.txt" 2>/dev/null | tail -1)
|
||||
if [ -n "$WHO" ] && [ ! -f "$C/$PW_SAVE/$WHO/$WHO.d2s" ]; then BAD=1; echo "【红】换存档没生效:进局的角色「${WHO}」不在 ${PW_SAVE} 里,这一局不算" | tee "$O/fail.txt"; fi; fi
|
||||
for f in "$D/${RID}"_*; do [ -f "$f" ] && mv "$f" "$O/$(basename "$f" | sed "s/^${RID}_//")"; done
|
||||
echo "计时:拷包 0 排锁 $((T_C - T_B)) 起包 $((T_D - T_C)) 运行 $((T_E - T_D)) 收尾 $(( $(date +%s) - T_E )) 启动次数 $TRY" | tee "$O/timing.txt"
|
||||
File diff suppressed because it is too large
Load Diff
Executable
+69
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
# 按改动挑局:git diff 基点..被测头 的文件 → affected.tsv → 受影响局;开跑前查基点。
|
||||
# 合入门槛从简 = Mac 冒烟 + 一档受影响局;没有受影响局时跑核心局;--core 时再并上核心局。整表只放夜里。
|
||||
# 用法:uireg_pick.py <被测提交或分支> [--main main]
|
||||
# 输出最后一行「局:…」给脚本用(含 * 表示要整表);退出码 0 = 可以跑,3 = 基点旧且主干改动碰到受影响局(先变基,不跑注定失败的局)。
|
||||
# Pick runs by change: files from git diff base..head under test → affected.tsv → affected runs; check the base before starting.
|
||||
# The merge threshold kept simple = Mac smoke test + affected runs in one mode; when there are no affected runs, run the core runs; with --core the core runs are added on top. The full table runs only at night.
|
||||
# Usage: uireg_pick.py <commit or branch under test> [--main main]
|
||||
# The last output line 「局:…」(runs: …) is for scripts (containing * means the full table is needed); exit code 0 = OK to run, 3 = the base is old and mainline changes touch affected runs (rebase first, do not run runs that are bound to fail).
|
||||
import sys, os, re, fnmatch, subprocess
|
||||
CORE = "e k s sb t pk rf2 pg2 vt1 j".split() # 核心局:前端 / 镶嵌与符文之语 / 储藏箱存取与按钮 / 魔盒 / iPad 身体框 / 重开 / 个人仓库翻页 / 编年史仓库;单档运行合计约 6.5 分钟 | core runs: front end / socketing and runewords / stash deposit-withdraw and buttons / cube / iPad body box / restart / personal stash paging / chronicle vault; about 6.5 minutes in total for a single-mode pass
|
||||
H = os.path.dirname(os.path.abspath(__file__))
|
||||
def git(*a): return subprocess.run(["git", *a], capture_output=True, text=True, check=True).stdout
|
||||
def rules():
|
||||
r = []
|
||||
for ln in open(os.path.join(H, "affected.tsv"), encoding="utf-8"):
|
||||
if not ln.strip() or ln.startswith("#"): continue
|
||||
pat, games = ln.rstrip("\n").split("\t", 1); r.append((pat, games.split()))
|
||||
return r
|
||||
def uireg_games(base, head): # uireg.py 改动落在哪些局:改动行号 → 往上找最近的 G("名" | which runs a uireg.py change falls into: changed line number → search upward for the nearest G("name"
|
||||
out = git("diff", "-U0", base, head, "--", "dm/ios/tools/uireg/uireg.py")
|
||||
if not out: return set()
|
||||
src = git("show", f"{head}:dm/ios/tools/uireg/uireg.py").split("\n"); gs = set()
|
||||
for m in re.finditer(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", out, re.M):
|
||||
a, n = int(m.group(1)), int(m.group(2) or 1)
|
||||
for ln in range(a, a + max(n, 1)):
|
||||
for j in range(min(ln, len(src)) - 1, -1, -1):
|
||||
g = re.search(r'\bG\("([a-z0-9]+)"', src[j])
|
||||
if g: gs.add(g.group(1)); break
|
||||
return gs
|
||||
def classify(files, base, head, R):
|
||||
pick, why, unreg = set(), [], []
|
||||
for f in files:
|
||||
hit = next(((p, g) for p, g in R if fnmatch.fnmatch(f, p)), None)
|
||||
if hit is None:
|
||||
if f.startswith("dm/"): unreg.append(f); pick.add("*"); why.append(f"{f} → 未登记,按整表")
|
||||
continue
|
||||
p, g = hit
|
||||
if g == ["-"]: why.append(f"{f} → 只跑核心局({p})"); continue
|
||||
if g == ["@uireg"]: u = uireg_games(base, head); pick |= u; why.append(f"{f} → 改了这些局的脚本:{' '.join(sorted(u)) or '无'}"); continue
|
||||
pick |= set(g); why.append(f"{f} → {' '.join(g)}({p})")
|
||||
return pick, why, unreg
|
||||
def main():
|
||||
a = [x for x in sys.argv[1:] if not x.startswith("--")]; head = a[0] if a else "HEAD"
|
||||
mainref = sys.argv[sys.argv.index("--main") + 1] if "--main" in sys.argv else "main"
|
||||
R = rules(); mb = git("merge-base", head, mainref).strip()
|
||||
files = [f for f in git("diff", "--name-only", mb, head).split("\n") if f]
|
||||
pick, why, unreg = classify(files, mb, head, R)
|
||||
ahead = int(git("rev-list", "--count", f"{mb}..{mainref}").strip() or 0)
|
||||
print(f"被测 {git('rev-parse', '--short', head).strip()},基点 {mb[:9]},主干 {mainref} 领先基点 {ahead} 个提交;改动文件 {len(files)} 个")
|
||||
for w in why: print(" " + w)
|
||||
rc = 0
|
||||
if ahead:
|
||||
mfiles = [f for f in git("diff", "--name-only", mb, mainref).split("\n") if f]
|
||||
mp, mwhy, _ = classify(mfiles, mb, mainref, R)
|
||||
mp.discard("@uireg")
|
||||
sel = pick | set(CORE)
|
||||
clash = "*" in mp or ("*" in pick and mp) or (mp & sel)
|
||||
if clash:
|
||||
rc = 3; print(f"【红】基点旧:主干在基点之后改了受影响局用到的东西({' '.join(sorted(mp & sel)) if '*' not in mp else '整表级改动'}),先变基到 {git('rev-parse', '--short', mainref).strip()} 再跑:")
|
||||
for w in mwhy:
|
||||
if not w.endswith("只跑核心局(-)") and "→ 只跑核心局" not in w: print(" 主干 " + w)
|
||||
else: print("基点虽旧,主干的改动不碰这次要跑的局,可以跑")
|
||||
full = "*" in pick
|
||||
aff = sorted(pick - {"*"}); core = "--core" in sys.argv or not aff
|
||||
games = ["*"] if full else aff + ([c for c in CORE if c not in pick] if core else [])
|
||||
print(f"受影响局:{'整表' if full else ' '.join(sorted(pick)) or '无'}" + (f";并上核心局:{' '.join(CORE)}" if not full and core else "") + (f";未登记文件 {len(unreg)} 个(请补进 affected.tsv)" if unreg else ""))
|
||||
print("局:" + " ".join(games)); sys.exit(rc)
|
||||
if __name__ == "__main__": main()
|
||||
@@ -0,0 +1,204 @@
|
||||
# uireg — scripted regression of the touch UI
|
||||
|
||||
中文:[usage.zh-CN.md](usage.zh-CN.md)
|
||||
|
||||
Taps through the touch UI item by item and outputs one "expected → actual result" line per item. What is under test is the iOS package itself, driven only by touch scripts (which take the same path as real fingers, see "Touch scripts" in [../../README.md](../../README.md)); the criteria read the log of that run.
|
||||
|
||||
**About saves first**: the whole regression suite is written against one specific multi-character save. This save is not provided with the repository and cannot be distributed. The smoke test save that can be generated from the repository is only enough for the smoke test. See "Which saves are needed" below; without that save, the in-game state and tap positions of most runs do not match.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `uireg.py` | All cases and criteria: generates the touch script of each run, calls the runner script, reads the log and produces the result table |
|
||||
| `run_mac.sh` | Runner script (default): runs the iOS package on a Mac, on this machine |
|
||||
| `run_dev.sh` | Runner script: runs the already installed package on a real iPhone |
|
||||
| `uireg_pick.py`, `affected.tsv` | Pick the affected runs according to the changed files |
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. Being able to run the iOS package on a Mac: first get `tools/make_fixture.sh` and `tools/smoke_mac.sh 1` working once, following "Smoke test" in [../../README.md](../../README.md). After that this machine has the wrapped package (`.iosdd_mac/DmMacSmoke.app` under the repository root; if the source was not obtained with git clone, it is under the directory the smoke test script was run from), this app's container, and the game assets inside the container.
|
||||
2. The local configuration `dm/ios/local.env` has `DM_BUNDLE_ID`.
|
||||
3. Some criteria read screenshots and need `python3` to be able to `import PIL` (Pillow). It still runs without it; those items report `未判` (not judged).
|
||||
|
||||
All steps can be done on this machine alone; no second Mac is needed.
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
# run from the repository root
|
||||
python3 dm/ios/tools/uireg/uireg.py iphone # all runs
|
||||
python3 dm/ios/tools/uireg/uireg.py iphone b # only run b
|
||||
python3 dm/ios/tools/uireg/uireg.py iphone a c e # several runs
|
||||
```
|
||||
|
||||
The first argument is the screen profile:
|
||||
|
||||
| Screen profile | Meaning | Which package is used |
|
||||
|---|---|---|
|
||||
| `iphone` | iPhone aspect ratio | `UIREG_APP`, default `.iosdd_mac/DmMacSmoke.app` under the repository root (if the source was not obtained with git clone there is no default and you have to give it) |
|
||||
| `ipadfull` | iPad true full screen (the default picture on iPad: 3D fills the whole screen, and the UI is a 16:9 block anchored to the bottom) | `UIREG_APP_IPAD`, must be given |
|
||||
| `ipad` | iPad 16:9 with borders | Same as above |
|
||||
|
||||
One run = launch the app once, go through one script, exit. Runs are independent of each other and can be run individually. Runs are serial with respect to each other: a given bundle ID can have only one instance on one Mac, and the runner script uses the lock `$DM_ROOT/run/ios/macsmoke.lock` to queue with the Mac smoke test.
|
||||
|
||||
### How to read the results
|
||||
|
||||
- After each run finishes, one line is printed: wall-clock time, timing segments, number of red lines in the log.
|
||||
- The last line: `# 共 N 项:通 A、不通 B、未判 C;合计墙钟 … 秒;表 <path>` (N items in total: A passed, B failed, C not judged; total wall-clock … seconds; table `<path>`), followed by every item that did not pass or was not judged.
|
||||
- The result table: `$UIREG_OUT/tables/<screen profile>_<MMDD_HHMM>/表.md`.
|
||||
- The artifacts of each run: `$UIREG_OUT/pw/<prefix>_<screen profile>_<run name>/`, containing `boot.txt` (the log of that run), `script.txt` (the touch script actually used), screenshots, and `timing.txt`.
|
||||
|
||||
There are two kinds of `未判` (not judged): the item only left a screenshot and has no log criterion; or the criterion has to read a screenshot but cannot read it. Both need a person to look at the picture before a conclusion can be drawn, and are not treated as passed.
|
||||
|
||||
The criterion of each item only looks at the part of the log after that item's marker. What counts as a red line is not only lines containing `【红】` (red) but also `FATAL`, the watchdog, GPU command buffer errors and so on; the regular expression is `LOGRED` in `uireg.py`.
|
||||
|
||||
## Which saves are needed
|
||||
|
||||
### Standard save
|
||||
|
||||
Most runs launch with `DM_SAVE_FRESH=warlock`: the app makes a fresh copy of its bundled standard save and uses that, without touching the real save. The standard save is brought into the app from `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0/` when the package is built.
|
||||
|
||||
The script assumes that the character select list of this save has four characters, and each run selects by row number:
|
||||
|
||||
| Row | The character the script assumes | Examples of runs that use it |
|
||||
|---|---|---|
|
||||
| 1 | Level 76 Paladin | `i`, `me1`, `me2`, `sl1`, `rf1` |
|
||||
| 2 | Level 1 Warlock (this row is selected by default) | Most runs |
|
||||
| 3 | Another character | `e` (only selects it on the character select page), `wd1` |
|
||||
| 4 | Level 88 Sorceress, with a mercenary | `f`, `q`, `tp`, `cb`, `pg1`, `bdm`, `rf2`, `me3` |
|
||||
|
||||
Many tap positions and criteria also depend on things these characters already have (scrolls in the inventory, equipment worn, stash contents, waypoints already opened).
|
||||
|
||||
**This four-character save is not in the repository; you need to provide your own.** The smoke test save generated by `tools/make_fixture.sh` has only two newly created characters and is placed in the same directory; which runs can pass when the regression is run with it has not been verified. To run the whole suite, you have to prepare a save that satisfies the table above yourself, put it in that directory, and rebuild the package.
|
||||
|
||||
The items, gold and positions each run needs do not come from the save; they are given on the spot after entering the game by test switches (`DM_TEST_GIVE` and others, written in the definition of each run in `uireg.py`), and the random seed and game time are fixed, so the same save yields the same in-game state on every run.
|
||||
|
||||
### Dedicated saves
|
||||
|
||||
The runs below do not use the standard save but swap in a dedicated save instead. These are likewise not in the repository; you need to provide your own. The directory names are hard-coded in the script and have no meaning of their own:
|
||||
|
||||
| Directory name | Runs that use it | Contents the script assumes |
|
||||
|---|---|---|
|
||||
| `save.pw_rune_stack` (the name can be changed with `UIREG_STACK_SAVE`) | `d`, `t`, `u` | Warlock; the rune page of the stash has one stack of 12 runes |
|
||||
| `save.rg_act4done` | `g1`–`g4` | A character that has completed Act IV |
|
||||
| `save.rg_act4` | `ex` | A character in Act IV with the waypoint opened |
|
||||
| `save.rg_joejoe` | `tb`, `dz` | A character in Act II; the script goes from the waypoint in town to the Canyon of the Magi; `dz` also needs the quest staff in the inventory |
|
||||
| `save.sl_player` | `vf1` | A character with items in both the personal stash and the shared stash |
|
||||
|
||||
Where to put them: place the save directory under the `Data` directory of this app's container on the Mac (at the same level as `Documents`); the directory must be writable. Before such a run starts, `run_mac.sh` moves the existing `Documents/save` in the container aside and puts in a copy of the dedicated save, then moves it back when the run is finished; should it fail to move it back, it reports red and states where the original save is.
|
||||
|
||||
When the corresponding directory does not exist, that run fails immediately and states in `fail.txt` which save is missing, without affecting other runs.
|
||||
|
||||
## Which runs exist
|
||||
|
||||
A run name is the first argument of `G("…")` in `uireg.py`; below they are grouped by content. For exactly what each item taps and what it judges, the definition of that run in `uireg.py` is authoritative.
|
||||
|
||||
| Run | Contents |
|
||||
|---|---|
|
||||
| `e` | Character select page, character creation, naming (creates a new character and enters the game) |
|
||||
| `v` | Create a character after ticking the additional mode on the character creation page, enter the game, open the stash and look at the shared page |
|
||||
| `a` | Swapping gear in equipment slots, bottom bar and panel tabs, minimap, stick, casting skills in the wild, pause menu and settings page |
|
||||
| `b` | NPC dialogue menu, buying and selling on the merchant page, single tap / drag and drop / double tap / long press in the inventory |
|
||||
| `c` | Stash drag and drop and tabs, gold amount box, tapping outside the box while several kinds of dialog are open |
|
||||
| `s`, `sb` | Put a rune into the stash and take it out again; tap every button of the stash one by one |
|
||||
| `d`, `t`, `u` | Taking items from a stacked slot: the basic gesture, with the Horadric Cube in the inventory, with only one free slot left in the inventory (dedicated save) |
|
||||
| `g`, `h` | Skill binding; the `综合技能` (general skills) page of the skill tree |
|
||||
| `i`, `f`, `q`, `bdm` | Mercenary: hiring and reviving, inventory drag and drop with a mercenary, double-tapping a belt potion to feed the mercenary |
|
||||
| `j`, `k` | Socketing; making one runeword |
|
||||
| `rw1`, `rw2`, `rwp`, `rwd` | Runeword list: opening by long press, paging and details, one-tap crafting |
|
||||
| `m`, `n`, `p`, `ra` | Merchant page: dragging onto the merchant panel to sell, long press on the shelf to buy in bulk, long press on a potion to refill the belt, repair all |
|
||||
| `me1`–`me4` | Two-row / three-row / four-row dialogue menus when different characters face the same NPC |
|
||||
| `sl1`, `sl2`, `sl3` | Imbuing, adding sockets, personalizing. `sl2` and `sl3` are marked in the script comments as drafts that have not actually been run yet |
|
||||
| `cb` | With the Horadric Cube page open, double tap to send items into / out of the Horadric Cube |
|
||||
| `bd`, `ba` | Belt: double tap on an empty slot to fill up, automatic belt refill when opening the inventory |
|
||||
| `pk`, `g1`–`g4`, `ex`, `tb`, `tp`, `dz` | Tapping things in the world: the tappable range of a chest, the upper, middle and lower sections of a portal, exits, the town portal, the quest pedestal (most need dedicated saves) |
|
||||
| `wp` | Entering the game lands next to the town waypoint |
|
||||
| `rf1`–`rf3` | One-tap restart from the pause menu, restarting three times in a row per run |
|
||||
| `pg1`, `pg2` | Paging through the personal stash |
|
||||
| `vt1`, `vf1`, `vf2` | The sixth tab of the stash (the collection page added by the shell): deposit, withdraw, search, switching back and forth between tabs |
|
||||
| `kba`, `kbb` | Kill statistics panel: tap each widget one by one; look at the statistics after kills |
|
||||
| `wd1`, `wd2` | No-progress watchdog: no false positive when returning to the front end and sitting idle; it still triggers when nothing moves at all after launch |
|
||||
| `dc` | Death in the wild → tap `继续` (Continue) on the death screen → revive in town |
|
||||
| `top` | Exists only in the `ipadfull` profile: the minimap and area name at the true top of the screen, and the title bars of the panels |
|
||||
|
||||
The scope when no run name is given:
|
||||
|
||||
- `iphone`, `ipadfull`: everything in the table above (`top` only in `ipadfull`).
|
||||
- `ipad` (the bordered profile is not the default picture on iPad): runs only the part related to the screen aspect ratio, automatically skipping `d g h j k t u v m n p ra q pk g1–g4 ex tb tp`, and skipping the casting-in-the-wild part within run `a`. They can still be run when named explicitly.
|
||||
- The tap positions of `g1`–`g4` have only been measured for the two sets `iphone` and `ipadfull`.
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Variable | Meaning | Default |
|
||||
|---|---|---|
|
||||
| `UIREG_RUNNER` | Runner script | `run_mac.sh` in the same directory |
|
||||
| `UIREG_OUT` | Output root directory | `$DM_ROOT/run/uireg` |
|
||||
| `UIREG_APP` | The package for the `iphone` profile (`<name>.app`, containing `Wrapper/DmIOS.app`) | `.iosdd_mac/DmMacSmoke.app` under the repository root |
|
||||
| `UIREG_APP_IPAD` | The package for the `ipad` / `ipadfull` profiles | None, must be given |
|
||||
| `UIREG_STACK_SAVE` | Directory name of the dedicated save for runs `d`, `t`, `u` | `save.pw_rune_stack` |
|
||||
| `UIREG_EXTRA_ENV` | Environment variables added to the app for every run (space-separated `K=V`) | Unset |
|
||||
| `UIREG_FORBID` | Regular expression: if it appears anywhere in the log of a run, the run counts as failed | Unset |
|
||||
| `UIREG_REQUIRE` | Regular expression: must appear in the log of the run; the result states the number of occurrences (used to confirm that a certain switch really took effect) | Unset |
|
||||
| `UIREG_TAG` | Prefix of each run's artifact directory name (keeps two regression passes apart when they queue one after the other) | `ur` |
|
||||
| `SMOKE_OWNER` | The name shown while queueing for the lock | `未署名` (unsigned) |
|
||||
|
||||
## Packages for the iPad profiles
|
||||
|
||||
The repository has no separate script for building an iPad package. The procedure is the same as the two packaging steps in `tools/smoke_mac.sh`, with just one more build setting:
|
||||
|
||||
1. The same `xcodebuild` command, with `DM_DEVICE_FAMILY=1,2` added at the end (adds iPad to the device family; the project targets only iPhone by default, see `../../project.yml`).
|
||||
2. Wrap it the same way as `<name>.app/Wrapper/DmIOS.app`, plus the `WrappedBundle` symlink.
|
||||
|
||||
Use a new directory name each time you build a package, then give the path to `UIREG_APP_IPAD`.
|
||||
|
||||
## Rules for swapping packages
|
||||
|
||||
When a Mac runs an iOS package, the system mounts `<package>/Wrapper` in order to run it. If this directory is deleted or replaced wholesale while it is mounted, a stale mount point that cannot be unmounted is left behind; that path can no longer be opened from then on, and only a reboot clears it. So:
|
||||
|
||||
- Do not touch the package while it is running.
|
||||
- To swap packages, use a different directory name; or only do incremental updates of same-named files, without deleting or wholesale replacing `Wrapper`.
|
||||
|
||||
`run_mac.sh` itself does not copy the package; it launches directly from the given path.
|
||||
|
||||
## Running on a real device
|
||||
|
||||
```bash
|
||||
UIREG_RUNNER=dm/ios/tools/uireg/run_dev.sh python3 dm/ios/tools/uireg/uireg.py iphone a c
|
||||
```
|
||||
|
||||
`run_dev.sh` runs **the package that is already installed** on the phone through `../touch_e2e.sh`; the prerequisites are the same as for the real-device smoke test (see "Real-device smoke test" in [../../README.md](../../README.md)). Differences from running on a Mac:
|
||||
|
||||
- Only the `iphone` profile.
|
||||
- Runs that need dedicated saves are not run.
|
||||
- Each run is collected only after running for the full limit in seconds; the log is cut off at the marker for the end of the script, and the full text is saved separately as `boot_full.txt`.
|
||||
- By default only the log is pulled back, not the screenshots, so items that need screenshots are all `未判` (not judged) on a real device. To pull certain screenshots, name them with `UIREG_PULL="<file name> <file name>"`.
|
||||
- It is not responsible for installing the package. To guarantee that what is under test is the package you just installed yourself, take the device lock in an outer layer first and wrap "install + run" together (the device lock is reentrant, `../devlock.sh`).
|
||||
|
||||
## Picking runs by change
|
||||
|
||||
```bash
|
||||
python3 dm/ios/tools/uireg/uireg_pick.py <commit or branch under test> --main <main branch>
|
||||
```
|
||||
|
||||
It compares which files have changed since the fork point between the commit under test and the main branch, lists which runs should be run according to `affected.tsv` (path glob → affected runs), and the last line, `局:…` (runs: …), gives the names of the runs to run. `*` means the whole table has to be run; source files under `dm/` that are not registered are treated as the whole table. With `--core`, or when there are no affected runs at all, a set of core runs defined in the script is merged in. When adding a new run, remember to register it in `affected.tsv`.
|
||||
|
||||
## The run attached after the Mac smoke test
|
||||
|
||||
When `tools/smoke_mac.sh` is run with `SMOKE_UIREG=1`, one pass of `iphone b` is additionally run after the smoke test passes:
|
||||
|
||||
- It runs in the background and does not affect the smoke test's own result or exit code.
|
||||
- It uses a cloned copy of the package of this smoke test, so smoke-testing again or re-wrapping right afterwards cannot touch the copy it has open.
|
||||
- When it finishes, it adds one line to the smoke test record `$DM_ROOT/run/ios/smoke_ledger.tsv`, where the result column is `Mac:界面回归b:OK` or `Mac:界面回归b:RED` (`界面回归` = UI regression). The condition for passing: all items that have a criterion pass, and the log has 0 red lines; `未判` (not judged) items are not counted.
|
||||
- If it is red, the artifacts are left under `uireg/` in the result directory of that smoke test, and the next smoke test gives a one-line reminder at its start.
|
||||
|
||||
Note that run `b` likewise depends on the standard save described above.
|
||||
|
||||
## Conventions for writing your own runner script
|
||||
|
||||
If you want the same set of cases to run in another environment, you can write another runner script and point `UIREG_RUNNER` at it:
|
||||
|
||||
- Invocation: `bash $UIREG_RUNNER <tag> <limit seconds>`, with the touch script given on standard input.
|
||||
- Environment variables passed in: `PW_ENV` (space-separated `K=V`, added as is to the app's launch environment), `PW_SAVE` (directory name of the dedicated save to swap in; empty for most runs), `UIREG_MODE` (screen profile; pick the package according to it), `UIREG_OUT`.
|
||||
- Put the outputs in `$UIREG_OUT/pw/<tag>/`: `boot.txt` (required), screenshots (using the original names given by `shot` in the script), `timing.txt` (one line of text starting with `计时:` (timing:), which is copied as is into the result table), `c2s.jsonl` (a record of the command packets the game sends; may be absent).
|
||||
- The last line of the touch script is `<seconds> note 结束` (`结束` = end): the run can be collected as soon as `[script] note 结束` appears in the log, and the limit in seconds is only a fallback.
|
||||
@@ -0,0 +1,204 @@
|
||||
# uireg — 触摸界面的脚本化回归
|
||||
|
||||
English: [usage.md](usage.md)
|
||||
|
||||
把触摸界面逐项点一遍,每项出一行「期望 → 真结果」。被测的是 iOS 包本身,只用触点脚本驱动(和真手指走同一条路,见 [../../README.zh-CN.md](../../README.zh-CN.md)「触点脚本」),判据读这一局的日志。
|
||||
|
||||
**先说存档**:整套回归是照着一份特定的多角色存档写的,这份存档不随仓库提供,也不能分发。仓库里能生成的冒烟存档只够跑冒烟。详见下面「需要什么存档」;没有那份存档时,多数局的现场和点位对不上。
|
||||
|
||||
## 文件
|
||||
|
||||
| 文件 | 作用 |
|
||||
|---|---|
|
||||
| `uireg.py` | 全部用例与判据:生成每一局的触点脚本、调起局脚本、读日志出结果表 |
|
||||
| `run_mac.sh` | 起局脚本(缺省):在本机跑 Mac 上的 iOS 包 |
|
||||
| `run_dev.sh` | 起局脚本:在真机 iPhone 上跑已装好的包 |
|
||||
| `uireg_pick.py`、`affected.tsv` | 按改动的文件挑出受影响的局 |
|
||||
|
||||
## 前提
|
||||
|
||||
1. 能在 Mac 上跑 iOS 包:先按 [../../README.zh-CN.md](../../README.zh-CN.md)「冒烟」跑通一次 `tools/make_fixture.sh` 和 `tools/smoke_mac.sh 1`。这之后本机就有包好的包(仓库根目录下 `.iosdd_mac/DmMacSmoke.app`;源码不是用 git 克隆来的话,它在你运行冒烟脚本时所在的目录下)、这个 App 的容器,以及容器里的游戏资源。
|
||||
2. 本机配置 `dm/ios/local.env` 里有 `DM_BUNDLE_ID`。
|
||||
3. 部分判据要读截图,需要 `python3` 能 `import PIL`(Pillow)。没有也能跑,这些项会报「未判」。
|
||||
|
||||
全部步骤都可以只在本机做,不需要第二台 Mac。
|
||||
|
||||
## 跑法
|
||||
|
||||
```bash
|
||||
# 在仓库根目录执行
|
||||
python3 dm/ios/tools/uireg/uireg.py iphone # 全部局
|
||||
python3 dm/ios/tools/uireg/uireg.py iphone b # 只跑 b 局
|
||||
python3 dm/ios/tools/uireg/uireg.py iphone a c e # 跑几局
|
||||
```
|
||||
|
||||
第一个参数是画面档:
|
||||
|
||||
| 画面档 | 含义 | 用哪个包 |
|
||||
|---|---|---|
|
||||
| `iphone` | iPhone 比例 | `UIREG_APP`,缺省是仓库根目录下的 `.iosdd_mac/DmMacSmoke.app`(源码不是用 git 克隆来的话没有缺省值,要自己给) |
|
||||
| `ipadfull` | iPad 真全屏(iPad 上的缺省画面:3D 铺满整屏,界面是贴底的一块 16:9) | `UIREG_APP_IPAD`,必须给 |
|
||||
| `ipad` | iPad 16:9 留边 | 同上 |
|
||||
|
||||
一局 = 启动一次 App、走一段脚本、退出。各局互相独立,可以单独跑。局与局之间串行:同一个包名在一台 Mac 上只能有一个实例,起局脚本用 `$DM_ROOT/run/ios/macsmoke.lock` 这把锁和 Mac 冒烟排队。
|
||||
|
||||
### 结果怎么看
|
||||
|
||||
- 每跑完一局打印一行:墙钟时间、计时分段、日志里的红行数。
|
||||
- 最后一行:`# 共 N 项:通 A、不通 B、未判 C;合计墙钟 … 秒;表 <路径>`,后面跟着每个没通过或未判的项。
|
||||
- 结果表:`$UIREG_OUT/tables/<画面档>_<月日_时分>/表.md`。
|
||||
- 每局的现场:`$UIREG_OUT/pw/<前缀>_<画面档>_<局名>/`,里面有 `boot.txt`(这一局的日志)、`script.txt`(实际用的触点脚本)、截图、`timing.txt`。
|
||||
|
||||
「未判」有两种:这一项只留了截图、没有日志判据;或者判据要读截图但读不出来。两种都要人看图才能下结论,不会被当成通过。
|
||||
|
||||
每一项的判据只看日志里该项记号之后的那一段。红行的口径不只是带「【红】」的行,还包括 `FATAL`、看门狗、GPU 命令缓冲出错等,正则在 `uireg.py` 的 `LOGRED`。
|
||||
|
||||
## 需要什么存档
|
||||
|
||||
### 标准存档
|
||||
|
||||
多数局启动时带 `DM_SAVE_FRESH=warlock`:App 把自带的标准存档拷一份新的来用,不碰真实存档。标准存档是出包时从 `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0/` 带进 App 的。
|
||||
|
||||
脚本假定这份存档的选角列表里有四个角色,并且各局按行号去选:
|
||||
|
||||
| 行 | 脚本假定的角色 | 用到它的局举例 |
|
||||
|---|---|---|
|
||||
| 1 | 76 级圣骑士 | `i`、`me1`、`me2`、`sl1`、`rf1` |
|
||||
| 2 | 1 级术士(缺省选这一行) | 大多数局 |
|
||||
| 3 | 另一个角色 | `e`(只在选角页选中它)、`wd1` |
|
||||
| 4 | 88 级法师,带佣兵 | `f`、`q`、`tp`、`cb`、`pg1`、`bdm`、`rf2`、`me3` |
|
||||
|
||||
许多点位和判据还依赖这些角色身上现成的东西(背包里的卷轴、身上的装备、仓库内容、已开的小站)。
|
||||
|
||||
**这份四角色存档不在仓库里,需要自备。** `tools/make_fixture.sh` 生成的冒烟存档只有两个新建的角色,放在同一个目录;用它跑回归,哪些局能过没有验证过。要跑整套,得自己准备一份满足上表的存档放到那个目录,再重新出包。
|
||||
|
||||
各局需要的物品、金币、站位不靠存档,由测试开关在进局后当场给出(`DM_TEST_GIVE` 等,写在 `uireg.py` 每一局的定义里),并固定了随机种子与游戏时间,所以同一份存档每次跑出来的现场相同。
|
||||
|
||||
### 专用存档
|
||||
|
||||
下面几局不用标准存档,而是换上一份专用存档。它们同样不在仓库里,要自备;目录名是脚本里写死的,名字本身没有含义:
|
||||
|
||||
| 目录名 | 用它的局 | 脚本假定的内容 |
|
||||
|---|---|---|
|
||||
| `save.pw_rune_stack`(可用 `UIREG_STACK_SAVE` 改名) | `d`、`t`、`u` | 术士;箱子的符文页里有一叠 12 个符文 |
|
||||
| `save.rg_act4done` | `g1`–`g4` | 第四幕已通关的角色 |
|
||||
| `save.rg_act4` | `ex` | 在第四幕、小站已开的角色 |
|
||||
| `save.rg_joejoe` | `tb`、`dz` | 在第二幕的角色,脚本从城里的小站去法师峡谷;`dz` 还要背包里带着任务法杖 |
|
||||
| `save.sl_player` | `vf1` | 个人仓库与共享仓库里都有物品的角色 |
|
||||
|
||||
放法:把存档目录放到 Mac 上这个 App 容器的 `Data` 目录下(和 `Documents` 同级),目录要可写。`run_mac.sh` 在这一局开始前把容器里现有的 `Documents/save` 挪开,换上专用存档的副本,跑完再挪回;万一挪不回会报红并写明原存档在哪。
|
||||
|
||||
没有对应目录时,这一局直接失败并在 `fail.txt` 里写明缺哪份存档,不影响别的局。
|
||||
|
||||
## 有哪些局
|
||||
|
||||
局名是 `uireg.py` 里 `G("…")` 的第一个参数,下面按内容分组。具体每一项点什么、判什么,以 `uireg.py` 里该局的定义为准。
|
||||
|
||||
| 局 | 内容 |
|
||||
|---|---|
|
||||
| `e` | 选角页、建角、起名(会新建一个角色并进局) |
|
||||
| `v` | 勾选建角页上的附加模式后建角,进局开箱看共享页 |
|
||||
| `a` | 装备位换装、底栏与面板页签、小地图、摇杆、野外技能施放、暂停菜单与设置页 |
|
||||
| `b` | NPC 对话菜单、商人页买卖、物品栏的单击 / 拖放 / 双击 / 长按 |
|
||||
| `c` | 储藏箱拖放与页签、金币数量框、几种弹框开着时点框外 |
|
||||
| `s`、`sb` | 符文放进储藏箱再取出;储藏箱每个按钮逐个点 |
|
||||
| `d`、`t`、`u` | 从成叠的格子里取件:基本手法、背包里带着魔盒时、背包只剩一格时(专用存档) |
|
||||
| `g`、`h` | 技能绑定;技能树的「综合技能」页 |
|
||||
| `i`、`f`、`q`、`bdm` | 雇佣兵:雇佣与复活、带佣兵时物品栏拖放、双击腰带药水喂佣兵 |
|
||||
| `j`、`k` | 镶嵌;做一个符文之语 |
|
||||
| `rw1`、`rw2`、`rwp`、`rwd` | 符文之语清单:长按打开、分页与详情、一键合成 |
|
||||
| `m`、`n`、`p`、`ra` | 商人页:拖到商人面板卖出、货架长按大量购买、长按药水补腰带、全部修理 |
|
||||
| `me1`–`me4` | 不同角色面对同一个 NPC 时两行 / 三行 / 四行的对话菜单 |
|
||||
| `sl1`、`sl2`、`sl3` | 灌魔、打孔、个性化。`sl2`、`sl3` 在脚本注释里标明是还没实际跑过的草稿 |
|
||||
| `cb` | 魔盒页开着时双击把物品送进 / 送出魔盒 |
|
||||
| `bd`、`ba` | 腰带:空格双击补满、开背包自动补腰带 |
|
||||
| `pk`、`g1`–`g4`、`ex`、`tb`、`tp`、`dz` | 点世界里的东西:箱子的可点范围、传送门上中下几段、出口、回城门、任务底座(多数要专用存档) |
|
||||
| `wp` | 进局落在城镇小站旁 |
|
||||
| `rf1`–`rf3` | 暂停菜单的一键重开,每局连开三次 |
|
||||
| `pg1`、`pg2` | 个人仓库翻页 |
|
||||
| `vt1`、`vf1`、`vf2` | 储藏箱的第六个页签(外壳加的收藏页):存入、取出、搜索、页签来回切 |
|
||||
| `kba`、`kbb` | 击杀统计面板:各控件逐个点;击杀之后看统计 |
|
||||
| `wd1`、`wd2` | 无进展看门狗:回到前端静置不误判;启动后一直不动仍会判定 |
|
||||
| `dc` | 野外死亡 → 点死亡画面的「继续」→ 复活回城 |
|
||||
| `top` | 只在 `ipadfull` 档存在:屏幕真顶部的小地图与地名、各面板标题栏 |
|
||||
|
||||
不写局名时的范围:
|
||||
|
||||
- `iphone`、`ipadfull`:上表全部(`top` 只在 `ipadfull`)。
|
||||
- `ipad`(留边档不是 iPad 的缺省画面):只跑和画面比例有关的那部分,自动跳过 `d g h j k t u v m n p ra q pk g1–g4 ex tb tp`,`a` 局里跳过野外施放那一段。点名仍然可以跑。
|
||||
- `g1`–`g4` 的点位只量了 `iphone` 和 `ipadfull` 两套。
|
||||
|
||||
## 环境变量
|
||||
|
||||
| 变量 | 含义 | 缺省 |
|
||||
|---|---|---|
|
||||
| `UIREG_RUNNER` | 起局脚本 | 同目录 `run_mac.sh` |
|
||||
| `UIREG_OUT` | 产物根目录 | `$DM_ROOT/run/uireg` |
|
||||
| `UIREG_APP` | `iphone` 档的包(`<名>.app`,里面是 `Wrapper/DmIOS.app`) | 仓库根目录下 `.iosdd_mac/DmMacSmoke.app` |
|
||||
| `UIREG_APP_IPAD` | `ipad` / `ipadfull` 档的包 | 无,必须给 |
|
||||
| `UIREG_STACK_SAVE` | `d`、`t`、`u` 局专用存档的目录名 | `save.pw_rune_stack` |
|
||||
| `UIREG_EXTRA_ENV` | 每局都加给 App 的环境变量(空格分隔的 `K=V`) | 不设 |
|
||||
| `UIREG_FORBID` | 正则:整局日志里出现就算不通 | 不设 |
|
||||
| `UIREG_REQUIRE` | 正则:整局日志里必须出现,结果里写出现次数(用来确认某个开关真的生效了) | 不设 |
|
||||
| `UIREG_TAG` | 每局现场目录名的前缀(两遍回归先后排队时分开放) | `ur` |
|
||||
| `SMOKE_OWNER` | 排锁时显示的名字 | 未署名 |
|
||||
|
||||
## iPad 档的包
|
||||
|
||||
仓库里没有单独出 iPad 包的脚本。做法和 `tools/smoke_mac.sh` 里出包的那两步相同,只多一项构建设置:
|
||||
|
||||
1. 同样的 `xcodebuild` 命令,末尾加 `DM_DEVICE_FAMILY=1,2`(设备族里加上 iPad;工程缺省只面向 iPhone,见 `../../project.yml`)。
|
||||
2. 同样包成 `<名>.app/Wrapper/DmIOS.app`,外加 `WrappedBundle` 软链。
|
||||
|
||||
每次出包用一个新的目录名,然后把路径给 `UIREG_APP_IPAD`。
|
||||
|
||||
## 换包的规矩
|
||||
|
||||
Mac 跑 iOS 包时,系统把 `<包>/Wrapper` 挂载出去运行。挂着的时候这层目录被删或被整体替换,会留下卸不掉的失效挂载点,那个路径从此打不开,只有重启能清。所以:
|
||||
|
||||
- 包在跑的时候不动它。
|
||||
- 要换包就换一个目录名;或者只做同名文件的增量更新,不删、不整体替换 `Wrapper`。
|
||||
|
||||
`run_mac.sh` 自己不拷包,直接从给的路径启动。
|
||||
|
||||
## 在真机上跑
|
||||
|
||||
```bash
|
||||
UIREG_RUNNER=dm/ios/tools/uireg/run_dev.sh python3 dm/ios/tools/uireg/uireg.py iphone a c
|
||||
```
|
||||
|
||||
`run_dev.sh` 通过 `../touch_e2e.sh` 在手机上跑**已经装好的那个包**,前提与真机冒烟相同(见 [../../README.zh-CN.md](../../README.zh-CN.md)「真机冒烟」)。和 Mac 上的差别:
|
||||
|
||||
- 只有 `iphone` 档。
|
||||
- 要专用存档的局不跑。
|
||||
- 每局跑满上限秒才收;日志截到脚本结束的记号为止,全文另存为 `boot_full.txt`。
|
||||
- 缺省只拉回日志,不拉截图,所以要看截图的项在真机上都是「未判」。要拉某几张截图,用 `UIREG_PULL="<文件名> <文件名>"` 点名。
|
||||
- 它不负责装包。要保证被测的是自己刚装的包,在外层先取设备锁,把「装包 + 跑」包在一起(设备锁可重入,`../devlock.sh`)。
|
||||
|
||||
## 按改动挑局
|
||||
|
||||
```bash
|
||||
python3 dm/ios/tools/uireg/uireg_pick.py <被测提交或分支> --main <主干分支>
|
||||
```
|
||||
|
||||
它比较被测提交与主干的分叉点之后改了哪些文件,按 `affected.tsv`(路径通配 → 受影响的局)列出该跑哪些局,最后一行 `局:…` 就是要跑的局名。`*` 表示要跑整表;没有登记的 `dm/` 下的源文件按整表处理。加 `--core`,或者没有任何受影响的局时,会并上脚本里的一组核心局。新加一局时记得在 `affected.tsv` 里登记。
|
||||
|
||||
## 挂在 Mac 冒烟后面的那一局
|
||||
|
||||
`tools/smoke_mac.sh` 带 `SMOKE_UIREG=1` 时,冒烟通过后会加跑一遍 `iphone b`:
|
||||
|
||||
- 放在后台跑,不影响冒烟自己的结果和退出码。
|
||||
- 用的是这次冒烟的包的一份克隆副本,所以紧接着再冒烟、重新包装都碰不到它正开着的那份。
|
||||
- 跑完往冒烟记录 `$DM_ROOT/run/ios/smoke_ledger.tsv` 补一行,结果列是 `Mac:界面回归b:OK` 或 `Mac:界面回归b:RED`。通过的条件:有判据的项全通,且日志红行为 0;「未判」不计。
|
||||
- 红了,现场留在那次冒烟结果目录的 `uireg/` 下,下一次冒烟开头会提示一句。
|
||||
|
||||
注意 `b` 局同样依赖上面说的标准存档。
|
||||
|
||||
## 自己写起局脚本时的约定
|
||||
|
||||
想让同一套用例跑在别的环境上,可以另写一个起局脚本,用 `UIREG_RUNNER` 指过去:
|
||||
|
||||
- 调用方式:`bash $UIREG_RUNNER <标签> <上限秒>`,触点脚本从标准输入给。
|
||||
- 传入的环境变量:`PW_ENV`(空格分隔的 `K=V`,原样加到 App 的启动环境)、`PW_SAVE`(要换上的专用存档目录名,多数局为空)、`UIREG_MODE`(画面档,据此挑包)、`UIREG_OUT`。
|
||||
- 产物放到 `$UIREG_OUT/pw/<标签>/`:`boot.txt`(必需)、截图(用脚本里 `shot` 给的原名)、`timing.txt`(一行以「计时:」开头的文字,会原样抄进结果表)、`c2s.jsonl`(游戏发出的命令包记录,可以没有)。
|
||||
- 触点脚本的最后一行是 `<秒> note 结束`:日志里出现 `[script] note 结束` 就可以收,上限秒只是兜底。
|
||||
@@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env python3
|
||||
# 储藏箱加宽(编年史仓库第 1 步):个人 / 共享页 10 → 14 列。
|
||||
# 数据:两份 inventory.bin(excel/ 与 excel/base/)的大储藏箱页两行(第 10、25 行,+16 字节 = 列数)10 → 14,个人页与共享页都用这两行;服务端按它判格子是否合法(实测 x=12 放得进、存读档不丢)。
|
||||
# 画面:储藏箱底图(个人 / 共享 / 通用)在格子区插 4 列、下段金币框居中;宝石 / 材料 / 符文三页的底图两侧本来透明,左右各补 98 像素透明 = 居中。
|
||||
# 外框是 14 个面板共用的一张图(ControllerOverlay 的 Background),不改它,另加一个 WideBackground(原双面板帧左半插宽 196 像素),
|
||||
# 平时放屏幕外,储藏箱开着时由宿主挪进来(dm_cursor.c ui_widestash_pump)。贴图都由 gen_widestash_art.py 预先做成原包同款 DXT5 块线性,放在 NativeHUD/widestash/,这里只拷。
|
||||
# 面板矩形的左移 / 加宽、物品栏右移、标题条也在宿主做(各档位的面板矩形不同,不写死在这里)。
|
||||
# 1 像素 = 2 布局单位;加宽 392 单位 = 196 像素 = 4 格。
|
||||
# Stash widening (chronicle vault step 1): personal / shared pages 10 → 14 columns.
|
||||
# Data: in the two inventory.bin copies (excel/ and excel/base/) the two large-stash page rows (rows 10 and 25, +16 bytes = column count) go 10 → 14, and both the personal and shared pages use these two rows; the server uses it to judge whether a cell is legal (measured: an item fits at x=12 and is not lost across save and load).
|
||||
# Picture: the stash background images (personal / shared / generic) get 4 columns inserted in the cell area and the gold box in the lower section centered; the background images of the three gem / material / rune pages are transparent on both sides anyway, so 98 transparent pixels are added on each side = centered.
|
||||
# The outer frame is one image shared by 14 panels (the Background of ControllerOverlay); it is not changed, and a separate WideBackground is added (the left half of the original double-panel frame widened by inserting 196 pixels),
|
||||
# normally kept off screen and moved in by the host while the stash is open (dm_cursor.c ui_widestash_pump). The textures are all prepared in advance by gen_widestash_art.py as DXT5 block-linear, the same kind as the original package, and placed in NativeHUD/widestash/; here they are only copied.
|
||||
# Shifting left / widening of the panel rectangle, shifting the inventory right and the title bar are also done on the host (panel rectangles differ per profile and are not hard-coded here).
|
||||
# 1 pixel = 2 layout units; widening of 392 units = 196 pixels = 4 cells.
|
||||
import json, os, re, shutil, sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import touch_layout
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); ART = __import__('gen_paths').gen_dir('NativeHUD', 'widestash') # 构建时由 gen_widestash_art.py / gen_vault_cover.py 生成 | Generated at build time by gen_widestash_art.py / gen_vault_cover.py
|
||||
COLS = 14; EX = 392 # 加宽布局单位 | Widening in layout units
|
||||
BANK = 'controller/bankexpansionlayouthd.json'; OVERLAY = 'controller/controlleroverlayhd.json'
|
||||
SPRITES = {n: 'controller/panel/stash/v2/' + n.lower() for n in ('StashPanelBG', 'StashPanelBGPersonal', 'StashPanelBGShared')} # NativeHUD/widestash/<名>_wide.sprite → 原路径 | NativeHUD/widestash/<name>_wide.sprite → original path
|
||||
SPRITES.update({n: 'controller/panel/stash/v2/additionalstash/' + n.lower() for n in ('AdvancedStash_Gems_Console', 'AdvancedStash_Consumables_Console', 'AdvancedStash_Runes_Console')})
|
||||
WIDE_FRAME = 'controller/panel/zswide/mainpanelbg_wide' # 新增路径(casc_overlay 要求新增文件落在新子目录里) | Newly added path (casc_overlay requires newly added files to land in a new subdirectory)
|
||||
|
||||
def _entry(romfs, suffix):
|
||||
for line in open(os.path.join(romfs, 'data', 'build_manifest.psv'), encoding='utf-8'):
|
||||
f = line.rstrip('\n').split('|')
|
||||
if len(f) >= 11 and not line.startswith('#') and f[9].lower().endswith(suffix): return f[9].split(':', 1)[1].lower(), touch_layout._read_entry(romfs, f)
|
||||
raise SystemExit('wide_stash:包里没有 ' + suffix)
|
||||
|
||||
def _shift(s, name, dx, start=0):
|
||||
"""控件 name 的 rect x 加 dx(按文本改:布局带注释与尾逗号)。返回新文本。 | Add dx to the rect x of the widget named name (edited as text: layouts carry comments and trailing commas). Returns the new text."""
|
||||
m = re.search(r'"name"\s*:\s*"%s"' % re.escape(name), s[start:])
|
||||
if not m: raise SystemExit('wide_stash:储藏箱布局里没有控件 ' + name)
|
||||
i = start + m.end(); r = re.compile(r'"rect"\s*:\s*\{\s*"x"\s*:\s*(-?\d+)').search(s, i)
|
||||
if not r or s.find('"name"', i, r.start()) != -1: raise SystemExit('wide_stash:控件 %s 的 rect 不在它自己的字段里' % name)
|
||||
return s[:r.start(1)] + str(int(r.group(1)) + dx) + s[r.end(1):]
|
||||
|
||||
def _container_x(s, name, dx):
|
||||
"""无 rect 的容器(高级页三个)加 rect;有 rect 的(魔盒)加 dx。 | Containers without a rect (the three on the advanced pages) get a rect added; those with a rect (the cube) get dx added."""
|
||||
m = re.search(r'"name"\s*:\s*"%s"' % re.escape(name), s); i = m.end()
|
||||
nxt = s.find('"children"', i); f = s.find('"fields"', i)
|
||||
if f != -1 and f < nxt: return _shift(s, name, dx)
|
||||
return s[:i] + ',\n "fields": { "rect": { "x": %d, "y": 0 } }' % dx + s[i:]
|
||||
|
||||
# 珍宝匣:宝石 / 符文 / 材料三页的格位合到宝石页那一页(底图 gen_trove_art.py)。原版按物品码认格位(槽控件字段 itemCode),与控件挂在哪个容器、摆在哪里无关(实测):
|
||||
# 三个容器里的槽控件全部拿掉,按珍宝匣的几何重写进宝石容器;材料、符文两个容器留空壳(原版按名字找它们)
|
||||
# Trove: the slots of the gems / runes / materials pages are merged into the gems page (background gen_trove_art.py). The game identifies slots by item code (slot widget field itemCode), regardless of which container the widget is in or where it sits (measured):
|
||||
# all slot widgets in the three containers are removed and rewritten into the gem container with the Trove geometry; the materials and runes containers are left as empty shells (the game looks them up by name)
|
||||
def trove_slots(s):
|
||||
import gen_trove_art as T
|
||||
pat = re.compile(r'\{\s*"type"\s*:\s*"AdvancedStashSlotWidget"\s*,\s*"name"\s*:\s*"(\w+)"\s*,\s*"fields"\s*:\s*\{\s*"rect"\s*:\s*\{[^}]*\}\s*,\s*"itemCode"\s*:\s*"(\w+)"\s*,?\s*\}\s*,?\s*\}\s*,?')
|
||||
codes = [m.group(2) for m in pat.finditer(s)]; want = T.slots()
|
||||
if sorted(codes) != sorted(want) or any(m.group(1) != m.group(2) for m in pat.finditer(s)): raise SystemExit('wide_stash:高级仓库槽控件不是原版那 91 个(找到 %d 个;原版布局变了?)' % len(codes))
|
||||
s = pat.sub('', s); i = s.index('"children"', s.index('"name": "advancedstash_gems"')); i = s.index('[', i) + 1
|
||||
new = ',\n'.join(' { "type": "AdvancedStashSlotWidget", "name": "%s", "fields": { "rect": { "width": %d, "height": %d, "x": %d, "y": %d }, "itemCode": "%s" } }' % (c, w, h, x, y, c) for c, (x, y, w, h) in sorted(want.items()))
|
||||
return s[:i] + '\n' + new + '\n ' + s[i:]
|
||||
|
||||
TOUCH_ONLY = {'TouchStashLeft', 'TouchStashRight', 'close'} # 触屏版插回的控件(touch_layout INGAME):手柄版布局(原版 + 功能改动,gen_romfs_overlay.py)里没有,没有就不挪 | Widgets re-inserted for the touch version (touch_layout INGAME): absent from the controller layouts (original + feature changes, gen_romfs_overlay.py); if absent, nothing is moved
|
||||
def _has(s, nm): return re.search(r'"name"\s*:\s*"%s"' % re.escape(nm), s) is not None
|
||||
def bank_layout(text):
|
||||
s = text; n0 = s.count('"cellCount": { "x": 10, "y": 10 }')
|
||||
if n0 != 1: raise SystemExit('wide_stash:储藏箱格子 cellCount 10×10 应为 1 处,找到 %d 处(原版布局变了?)' % n0)
|
||||
s = s.replace('"cellCount": { "x": 10, "y": 10 }', '"cellCount": { "x": %d, "y": 10 }' % COLS)
|
||||
half = EX // 2
|
||||
for nm in ('gold_amount', 'gold_withdraw', 'StashNavigation', 'TouchStashLeft', 'TouchStashRight'): # 下段居中的那排 | The centered row in the lower section
|
||||
if nm in TOUCH_ONLY and not _has(s, nm): continue
|
||||
s = _shift(s, nm, half)
|
||||
for nm in ('ShowPreviousLadderSeasonToggle', 'close'):
|
||||
if nm in TOUCH_ONLY and not _has(s, nm): continue
|
||||
s = _shift(s, nm, EX) # 靠右的:赛季开关;关闭钮落在宽外框右上角凹槽(外框右边比原来多出 196,面板左移 196 ⇒ 面板内 +392) | Right-aligned ones: the season toggle; the close button lands in the notch at the top-right corner of the wide outer frame (the right side of the outer frame extends 196 more than before and the panel shifts left 196 ⇒ +392 within the panel)
|
||||
s = trove_slots(s)
|
||||
for nm in ('advancedstash_gems', 'advancedstash_materials', 'advancedstash_runes', 'advancedstash_horadriccube'): s = _container_x(s, nm, half)
|
||||
s = _shift(s, 'advancedstash_horadriccube', -2 * __import__('gen_trove_art').SHIFT) # 合成格(连同转化钮)跟着底图里的台座左移 | the crafting slot (with its Transmute button) shifts left with the pedestal in the background
|
||||
s = vault_tab(s)
|
||||
return s
|
||||
|
||||
# 编年史仓库第 3 步(储藏箱第六个页签「编年史」)。
|
||||
# 页签条 5 → 6:点第六个游戏照收、不发包(宿主实测),它在这一页画魔盒那套格子与「提取」钮——宿主在这一页把它们挪走,换上这里加的 TouchVault。
|
||||
# 背景图表(backgroundFile)不能加第 6 项:加了游戏载入储藏箱布局就崩(main+0xb12024,宿主实测);不加时第六页照常画。TouchVault 缺省挪在屏外(游戏不认 visible: false),宿主切到第六页才挪回 (0, 0)。
|
||||
# 坐标按面板(加宽前,格子区 x 156–1528、y 139–1119;宿主加宽时整个面板一起挪)。文字、图、格子状态全由宿主 dm_vault_ui.c 写;点击一律发无人收的 ClosePanel:TouchV_*(同积分牌)
|
||||
# Chronicle vault step 3 (the stash's sixth tab 「编年史」(Chronicle)).
|
||||
# Tab strip 5 → 6: the game accepts a tap on the sixth as usual and sends no packet (measured on the host), and on this page it draws the cube's set of cells and the 「提取」(Withdraw) button -- on this page the host moves them away and puts in the TouchVault added here.
|
||||
# The background image table (backgroundFile) cannot get a 6th entry: with it the game crashes as soon as it loads the stash layout (main+0xb12024, measured on the host); without it the sixth page draws normally. TouchVault is moved off screen by default (the game does not honor visible: false), and the host moves it back to (0, 0) only when switching to the sixth page.
|
||||
# Coordinates are relative to the panel (before widening, cell area x 156–1528, y 139–1119; when the host widens, the whole panel moves together). Text, images and cell states are all written by the host dm_vault_ui.c; all taps send a ClosePanel:TouchV_* that nobody receives (same as the kill board)
|
||||
VAULT_COLS, VAULT_ROWS, VAULT_SET_ROWS, VAULT_SET_N = 3, 4, 7, 6 # 宿主 dm_vault_ui.c 同值(暗金每页 4 行:上面让给两排部位页签) | Same values as the host dm_vault_ui.c (uniques have 4 rows per page: the space above is given to the two rows of body-part tabs)
|
||||
VX, VW = 156, 1372
|
||||
PARTS = ['@dmVaultPart%d' % i for i in range(11)] # 中英表 dmVaultPart0–10(头盔 … 法杖与法器,同 gen_vault_table.py PARTS / 宿主 vt_part_name 的次序);英文长的分两行(页签字框高 104 放得下两行) | Chinese-English string table dmVaultPart0–10 (Helms ... Staves & Casters, same order as gen_vault_table.py PARTS / the host's vt_part_name); long English names are split into two lines (the tab text box is 104 high, which fits two lines)
|
||||
PT_FONT = 23 # 部位页签字号(直接给数,宿主截图量:17 → 每字 12.8 像素):五个字的「盾牌与手套」要放进页签面(约 88 像素),原版最小档 $SmallFontSize 放不下;11 个页签同一字号 | Body-part tab font size (given directly as a number; measured from a host screenshot: 17 → 12.8 pixels per character): the five-character 「盾牌与手套」(Shields and Gloves) has to fit on the tab face (about 88 pixels), and the original game's smallest tier $SmallFontSize does not fit; all 11 tabs use the same font size
|
||||
PT_Y, PT_PITCH = 228, 108 # 部位页签第一排的 y、两排间距(页签图 107×60 像素 = 214×120 单位,下沿 16 单位是选中菱形) | y of the first row of body-part tabs and the spacing between the two rows (tab image 107×60 pixels = 214×120 units, the bottom 16 units being the selection diamond)
|
||||
UNIQ_Y = PT_Y + 2 * PT_PITCH + 72 # 暗金格子区的 y(宿主 dm_vault_ui.c VU_UNIQ_Y 同值) | y of the unique cell area (same value as VU_UNIQ_Y in the host dm_vault_ui.c)
|
||||
def _vt_text(name, x, y, w, h, color, size, align='left', text='', trunc=True):
|
||||
return {'type': 'TextBoxWidget', 'name': name, 'fields': {'rect': {'x': x, 'y': y, 'width': w, 'height': h}, 'text': text,
|
||||
'style': {'fontColor': color, 'pointSize': size, 'alignment': {'h': align, 'v': 'center'}}, 'truncateWithEllipsis': trunc}}
|
||||
def _vt_nl(w): # 字里的 \n 照换行排(原版布局同写法 options.newlineHandling = standard;不加时 \n 画成同一行):部位页签英文分两行 | a newline escape in the text is laid out as a line break (the original layouts use the same options.newlineHandling = standard; without it the escape is drawn on the same line): the part tabs are split into two lines in English
|
||||
w['fields']['style']['options'] = {'newlineHandling': 'standard'}; return w
|
||||
def _vt_box(name, x, y, w, h, rgba, border=None): # 原版九宫格(提示框底那种):底色填满;border = 边框图 | Original-game nine-slice (the tooltip backing kind): background color fills it; border = border image
|
||||
f = {'rect': {'x': x, 'y': y, 'width': w, 'height': h}, 'backgroundColor': rgba} # 不给 filename = 只画底色、没有边(宿主实测) | No filename given = only the background color is drawn, with no border (measured on the host)
|
||||
if border: f.update(filename=border, tileScale=0.5)
|
||||
return {'type': 'NineTileImageWidget', 'name': name, 'fields': f}
|
||||
def _vt_tile(name, x, y, w, h): # 一格:暗底 + 金框(存着才显示,原版手柄选中框;框控件四边各大 18,金线落在格边,见暗金格 CellGold)+ 物品图容器(宿主按图大小缩放居中) | One cell: dark backing + gold frame (shown only when stored, the original game's controller selection frame; the frame widget is 18 larger on each of the four sides so the gold line falls on the cell edge, see the unique cell CellGold) + item image container (the host scales and centers by image size)
|
||||
return [_vt_box(name, x, y, w, h, [0.03, 0.028, 0.026, 1.0]), dict(_vt_box(name + 'Gold', x - 18, y - 18, w + 36, h + 36, [0, 0, 0, 0], 'Controller/PANEL/ControllerSelector/ControllerSelectorBorder')),
|
||||
{'type': 'Widget', 'name': name + 'Box', 'fields': {'rect': {'x': x + 8, 'y': y + 8, 'width': w - 16, 'height': h - 16}},
|
||||
'children': [{'type': 'ImageWidget', 'name': name + 'Img', 'fields': {'rect': {'x': 0, 'y': 0}}}]}]
|
||||
def _vt_check(name, x, y, label):
|
||||
return [{'type': 'ToggleButtonWidget', 'name': name, 'fields': {'rect': {'x': x, 'y': y, 'width': 65, 'height': 65}, 'sound': 'cursor_menu_select_hd',
|
||||
'filename': 'Lobby\\CreateGame\\CreateGame_AdvancedCheckbox', 'untoggledFrame': 0, 'untoggledPressedFrame': 1, 'untoggledHoveredFrame': 3, 'untoggledDisabledFrame': 2,
|
||||
'toggledFrame': 4, 'toggledPressedFrame': 5, 'toggledHoveredFrame': 6, 'onClickMessage': 'PanelManager:ClosePanel:' + name}},
|
||||
{'type': 'TextBoxWidget', 'name': name + '_Text', 'fields': {'text': label, 'rect': {'x': x + 75, 'y': y - 5, 'height': 50}, 'style': '$StyleSettingsTitle', 'fitToText': True}}]
|
||||
def _vt_sub(name, x, label):
|
||||
return {'type': 'ToggleButtonWidget', 'name': name, 'fields': {'rect': {'x': x, 'y': 0, 'width': 250, 'height': 66, 'scale': 0.7}, 'sound': 'cursor_menu_select_hd',
|
||||
'filename': 'PANEL\\Chronicle\\Slot_list_small_golddeco', 'untoggledFrame': 0, 'toggledFrame': 1, 'onClickMessage': 'PanelManager:ClosePanel:' + name},
|
||||
'children': [_vt_text('Text', 25, 0, 330, 94, '$FontColorWhite', '$LargeFontSize', 'center', label)]}
|
||||
def vault_widgets():
|
||||
CW, CH, GAP = (VW - 2 * 8) // VAULT_COLS, 130, 8
|
||||
cells = []
|
||||
for k in range(VAULT_COLS * VAULT_ROWS):
|
||||
r, c = divmod(k, VAULT_COLS); x, y = c * (CW + GAP), r * (CH + GAP)
|
||||
cells.append({'type': 'Widget', 'name': 'TouchV_U%d' % k, 'fields': {'rect': {'x': x, 'y': y, 'width': CW, 'height': CH}}, 'children':
|
||||
# 存着 = 整格金框(CellGold,原版手柄选中框):放在最后画在最上层,框住整格;字只排在框里那一圈之内(否则金框压字、字出框)。
|
||||
# 选中框的金线画在框控件边往里约 18 单位处(外面那圈是光晕;宿主截图量:62 像素高的框,线在上下各 8.5 像素)。框控件比格子四边各大 18,金线正好落在格边上,
|
||||
# 格里的图标、两行字、圆点都在线以内(框与格同一个矩形);光晕落在格间缝里。图标格自己的小金框不用(只留一个框)
|
||||
# Stored = gold frame around the whole cell (CellGold, the original game's controller selection frame): placed last so it is drawn on the top layer, framing the whole cell; text is laid out only inside the ring within the frame (otherwise the gold frame covers the text or the text leaves the frame).
|
||||
# The gold line of the selection frame is drawn about 18 units inward from the edge of the frame widget (the ring outside it is glow; measured from a host screenshot: for a frame 62 pixels high, the line is 8.5 pixels in at top and bottom). The frame widget is 18 larger than the cell on each of the four sides, so the gold line falls exactly on the cell edge,
|
||||
# and the icon, two lines of text and dot in the cell are all inside the line (frame and cell are the same rectangle); the glow falls in the gaps between cells. The icon cell's own small gold frame is not used (only one frame is kept)
|
||||
[_vt_box('Bg', 0, 0, CW, CH, [0.065, 0.062, 0.058, 1.0])] + _vt_tile('Tile', 10, 10, 90, CH - 20) + [_vt_text('Name', 110, 10, CW - 160, 56, '$FontColorGoldYellow', '$MediumFontSize'),
|
||||
_vt_text('Sub', 110, 66, CW - 124, 54, '$FontColorMoreLightGray', '$SmallFontSize'),
|
||||
_vt_text('Dot', CW - 54, 8, 44, 44, '$FontColorGoldYellow', '$SmallFontSize', 'center', trunc=False),
|
||||
_vt_box('CellGold', -18, -18, CW + 36, CH + 36, [0, 0, 0, 0], 'Controller/PANEL/ControllerSelector/ControllerSelectorBorder')]})
|
||||
RH = 116; sets = []
|
||||
for r in range(VAULT_SET_ROWS):
|
||||
# BgGold = 集齐的行:不要金框,整行底色提亮成暗金(宿主按集齐与否显隐)
|
||||
# BgGold = a fully collected row: no gold frame, the whole row's background is brightened to dark gold (the host shows / hides it depending on whether it is fully collected)
|
||||
row = [_vt_box('Bg', 0, 0, VW, RH, [0.08, 0.075, 0.07, 1.0]), _vt_box('BgGold', 0, 0, VW, RH, [0.19, 0.15, 0.07, 1.0]),
|
||||
_vt_text('Name', 20, -2, 520, 60, '$FontColorGreen', '$MediumLargeFontSize'), _vt_text('Count', 20, 66, 520, 46, '$FontColorMoreLightGray', '$SmallFontSize')] # 两行字的矩形中心相距 61(原 52):中文字形比矩形里的字框高,原先上行的字脚贴着下行的字头 | The centers of the two text rectangles are 61 apart (was 52): Chinese glyphs are taller than the text box within the rectangle, and previously the feet of the upper line touched the heads of the lower line
|
||||
for j in range(VAULT_SET_N): row += _vt_tile('Tile%d' % j, 560 + j * 132, 6, 124, RH - 12) + [_vt_text('Tile%dDot' % j, 560 + j * 132 + 80, 0, 52, 46, '$FontColorGoldYellow', '$SmallFontSize', 'center', trunc=False)] # 收录过没存 = 右上金点 | Collected before but not stored = gold dot at the top right
|
||||
sets.append({'type': 'Widget', 'name': 'TouchV_S%d' % r, 'fields': {'rect': {'x': 0, 'y': r * (RH + 8), 'width': VW, 'height': RH}}, 'children': row})
|
||||
return {'type': 'Widget', 'name': 'TouchVault', 'fields': {'rect': {'x': 99999, 'y': 0, 'width': 1730, 'height': 1300}}, 'children': [
|
||||
_vt_box('TouchV_Back', VX - 14, 136, VW + 28, 1000, [0.13, 0.125, 0.12, 1.0]), # 盖住储藏箱底图自带的格子线(整块暗底) | Covers the cell grid lines built into the stash background image (one whole dark backing)
|
||||
# 底部盖板:第六页没有自己的底图,游戏照画上一页的(个人 / 共享 / 魔盒凹槽各不同),还露着嵌入魔盒容器的「转化」「提取」钮;触摸由宿主挡掉(dm_vault_ui.c)。
|
||||
# 盖板是原版个人页底图格子以下整条、抹掉金币框(gen_vault_cover.py,不要大黑块),与从哪页切来无关;要在翻页条之前(翻页条画在它上面)
|
||||
# Bottom cover: the sixth page has no base image of its own, so the game draws the previous page's (personal / shared / Horadric Cube recess all differ), and the 「转化」(Transmute) and 「提取」(Withdraw) buttons embedded in the Horadric Cube container still show; touches are blocked by the host (dm_vault_ui.c).
|
||||
# The cover is the whole strip below the grid of the original personal page base image with the gold box erased (gen_vault_cover.py, no big black block), independent of which page one switched from; it must come before the page bar (the page bar is drawn on top of it)
|
||||
{'type': 'ImageWidget', 'name': 'TouchV_Cover', 'fields': {'rect': {'x': -2, 'y': 1132}, 'filename': 'Controller/Panel/zswide/VaultBottom'}},
|
||||
{'type': 'Widget', 'name': 'TouchV_Top', 'fields': {'rect': {'x': VX, 'y': 150, 'width': VW, 'height': 70}}, 'children': [
|
||||
_vt_sub('TouchV_SubU', 0, '@Unique'), _vt_sub('TouchV_SubS', 260, '@Sets'), # 原版串(中文同字) | original strings (same characters in Chinese)
|
||||
# 搜索框:原版编年史搜索框那一套(GrowableImage 底 + InputTextBoxWidget),点它游戏开 TextInputModal、dm_textinput.c 接系统键盘(同金币数量框)。
|
||||
# 键盘是整段交回,打完点「完成」才筛(不是边打边筛)。缩 0.75 塞进这一行;字由宿主每帧读(输入框 +0x12a8)
|
||||
# Search box: the original game's chronicle search box set (GrowableImage backing + InputTextBoxWidget); tapping it makes the game open TextInputModal, and dm_textinput.c hooks up the system keyboard (same as the gold amount box).
|
||||
# The keyboard hands the text back as one whole piece, and filtering happens only after typing and tapping 「完成」(Done) (not filtering while typing). Scaled 0.75 to fit into this row; the text is read by the host every frame (input box +0x12a8)
|
||||
{'type': 'GrowableImageWidget', 'name': 'TouchV_SearchBg', 'fields': {'rect': {'x': 540, 'y': -6, 'width': 1109, 'height': 102, 'scale': 0.75},
|
||||
'filename': 'PANEL\\Chronicle\\Chronicle_InputBox_Center', 'hoveredFrame': 1, 'leftCap/filename': 'PANEL\\Chronicle\\Chronicle_InputBox_Left', 'rightCap/filename': 'PANEL\\Chronicle\\Chronicle_InputBox_Right'},
|
||||
'children': [{'type': 'InputTextBoxWidget', 'name': 'TouchV_Search', 'fields': {'rect': {'x': 40, 'y': 0, 'width': 1036, 'height': 102}, 'backgroundColor': {'r': 0, 'g': 0, 'b': 0, 'a': 0.0},
|
||||
'maxStringLength': 16, 'imeEnabled': True, 'hint': {'text': '@dmVaultSearchHint', 'style': {'fontFace': 'BlizzardGlobal', 'alignment': {'v': 'center'}, 'pointSize': '$MediumLargeFontSize', 'fontColor': {'a': 84}}},
|
||||
'fontStyle': {'fontFace': 'BlizzardGlobal', 'alignment': {'v': 'center'}, 'pointSize': '$MediumLargeFontSize'}, 'useParentRectAsFocusRect': True, 'fontType': '12ptF',
|
||||
'onUpdateMessage': 'TouchVaultMessage:Search', 'virtualKeyboardType': 'Alphabet', 'leftCursorPadding': 40}}]}]},
|
||||
# 部位页签(替掉下拉):原版储藏箱页签图(CTRL_Tabs_215_TGA,帧 0 未选 / 帧 1 选中带菱形),两排 6 + 5,第二排错开半格;
|
||||
# 点按由宿主按 Hit 框认(dm_vault_ui.c,不发鼠标给游戏);选中那个宿主换帧、显示白字 TextOn,其余金字 Text
|
||||
# Body-part tabs (replacing the dropdown): the original game's stash tab image (CTRL_Tabs_215_TGA, frame 0 unselected / frame 1 selected with a diamond), two rows of 6 + 5, the second row offset by half a cell;
|
||||
# taps are recognized by the host from the Hit boxes (dm_vault_ui.c, no mouse is sent to the game); for the selected one the host changes the frame and shows the white text TextOn, the rest show the gold text Text
|
||||
{'type': 'Widget', 'name': 'TouchV_Parts', 'fields': {'rect': {'x': VX, 'y': PT_Y, 'width': VW, 'height': 2 * PT_PITCH}}, 'children': [
|
||||
{'type': 'Widget', 'name': 'TouchV_PT%d' % i, 'fields': {'rect': {'x': (i % 6) * 228 + (i // 6) * 114, 'y': (i // 6) * PT_PITCH, 'width': 214, 'height': 104}}, 'children': [
|
||||
{'type': 'ImageWidget', 'name': 'Img', 'fields': {'rect': {'x': 0, 'y': 0}, 'filename': 'Controller/Panel/Stash/V2/AdditionalStash/CTRL_Tabs_215_TGA', 'frame': 0}},
|
||||
_vt_box('Hit', 0, 0, 214, 104, [0, 0, 0, 0]),
|
||||
_vt_nl(_vt_text('Text', 4, 0, 206, 104, '$FontColorGoldYellow', PT_FONT, 'center', p, trunc=False)),
|
||||
_vt_nl(_vt_text('TextOn', 4, 0, 206, 104, '$FontColorWhite', PT_FONT, 'center', p, trunc=False))]} for i, p in enumerate(PARTS)]},
|
||||
_vt_text('TouchV_Stats', VX, PT_Y + 2 * PT_PITCH + 6, 780, 56, '$FontColorBeige', '$SmallFontSize'), # 宽到档次勾选框左沿(782):英文统计行长(左对齐,中文不受影响) | extends to the left edge of the quality tier checkboxes (782): the English stats row is long (left-aligned, Chinese is unaffected)
|
||||
{'type': 'Widget', 'name': 'TouchV_Tiers', 'fields': {'rect': {'x': VX + VW - 590, 'y': PT_Y + 2 * PT_PITCH, 'width': 590, 'height': 65}}, 'children':
|
||||
_vt_check('TouchV_T0', 0, 0, '@dmVaultTierN') + _vt_check('TouchV_T1', 200, 0, '@dmVaultTierX') + _vt_check('TouchV_T2', 400, 0, '@dmVaultTierE')}, # 中文同原版 NormalQuality 等;英文用简写(原版全称三个挤在 590 里叠字,英文版) | Chinese is the same as the original NormalQuality etc.; English uses abbreviations (the three original full names overlap when squeezed into 590, English version)
|
||||
{'type': 'Widget', 'name': 'TouchV_Uniq', 'fields': {'rect': {'x': VX, 'y': UNIQ_Y, 'width': VW, 'height': VAULT_ROWS * 138}}, 'children': cells},
|
||||
{'type': 'Widget', 'name': 'TouchV_Sets', 'fields': {'rect': {'x': 99999, 'y': 296, 'width': VW, 'height': 870}}, 'children': sets},
|
||||
# 底部翻页条(去掉下面的空黑框,按钮下移、放大、上下居中、好点按):页码和左右箭头排在底部装饰带的竖向正中(两枚环饰的中线 y 1262),
|
||||
# 箭头用原版大号箭头图(Lobby/Final/LobbyArrowLargeL / R,每帧 47×54 像素 = 94×108 单位,帧 0 常态 / 2 按下 / 3 不可用),放大 1.25 倍;
|
||||
# 点按区是各自一块透明的命中框 310×310 单位(iPhone 真机档位 1 单位 ≈ 0.164 点 → 约 51 点见方,16:9 档约 62 点;别贴着 44 点下限),从行区下沿往下铺、超出面板底边也算,不压最后一行的格子;宿主按命中框认(dm_vault_ui_pager_hit)。
|
||||
# 原版的小箭头 TouchStashLeft / Right 被盖板压住,这一页不用
|
||||
# Bottom page bar (remove the empty black box below; move the buttons down, enlarge them, center them vertically, make them easy to tap): the page number and left / right arrows are arranged at the vertical center of the bottom decorative band (the center line of the two ring ornaments, y 1262),
|
||||
# the arrows use the original large arrow images (Lobby/Final/LobbyArrowLargeL / R, 47×54 pixels per frame = 94×108 units, frame 0 normal / 2 pressed / 3 disabled), scaled 1.25×;
|
||||
# each tap area is its own transparent hit box of 310×310 units (on the real iPhone profile 1 unit ≈ 0.164 points → about 51 points square, about 62 points on the 16:9 profile; do not sit right at the 44-point minimum), extending downward from the bottom edge of the row area, counting even beyond the panel's bottom edge, and not overlapping the last row of cells; the host recognizes taps by the hit boxes (dm_vault_ui_pager_hit).
|
||||
# The original small arrows TouchStashLeft / Right are under the cover and not used on this page
|
||||
{'type': 'ImageWidget', 'name': 'TouchV_PgL', 'fields': {'rect': {'x': 562, 'y': 1195, 'scale': 1.25}, 'filename': 'Lobby/Final/LobbyArrowLargeL', 'frame': 0}},
|
||||
{'type': 'ImageWidget', 'name': 'TouchV_PgR', 'fields': {'rect': {'x': 992, 'y': 1195, 'scale': 1.25}, 'filename': 'Lobby/Final/LobbyArrowLargeR', 'frame': 0}},
|
||||
_vt_box('TouchV_PgLHit', 466, 1168, 310, 310, [0, 0, 0, 0]), _vt_box('TouchV_PgRHit', 896, 1168, 310, 310, [0, 0, 0, 0]),
|
||||
_vt_text('TouchV_Page', 696, 1222, 280, 80, '$FontColorGoldYellow', '$LargeFontSize', 'center'),
|
||||
{'type': 'ImageWidget', 'name': 'TouchV_Drag', 'fields': {'rect': {'x': 99999, 'y': 0}}}, # 从格子拖回背包时跟手的物品图(宿主摆) | Item image that follows the finger when dragging from a cell back to the inventory (placed by the host)
|
||||
# 说明框(第 5 步):原版物品说明框那套(提示框九宫格边 + 八成黑底、原版说明文字倒排行序),放最后 = 画在最上面;宿主按字的大小摆,缺省在屏外
|
||||
# Tooltip (step 5): the original game's item tooltip set (tooltip nine-slice border + 80% black backing, original-game description text with reversed line order), placed last = drawn on top; the host places it according to the text size, off screen by default
|
||||
{'type': 'NineTileImageWidget', 'name': 'TouchV_TipBg', 'fields': {'rect': {'x': 99999, 'y': 0, 'width': 900, 'height': 600}, 'filename': 'PANEL/TooltipBorder/TooltipBorder', 'backgroundColor': [0.0, 0.0, 0.0, 0.85], 'tileScale': 1.0}},
|
||||
{'type': 'TextBoxWidget', 'name': 'TouchV_Tip', 'fields': {'rect': {'x': 99999, 'y': 0, 'width': 1100, 'height': 600}, 'text': '', 'fitToText': True,
|
||||
'style': {'fontColor': '$FontColorWhite', 'pointSize': '$TooltipFontSize', 'alignment': {'h': 'center', 'v': 'top'}, 'options': {'pipeCharacterBehavior': 'handle', 'newlineHandling': 'reversed'}}}}]}
|
||||
|
||||
def vault_tab(s):
|
||||
for a, b in (('"tabCount": 5,', '"tabCount": 6,'), ('"inactiveFrames": [ 0, 0, 0, 0, 0 ],', '"inactiveFrames": [ 0, 0, 0, 0, 0, 0 ],'), ('"activeFrames": [ 1, 1, 1, 1, 1 ],', '"activeFrames": [ 1, 1, 1, 1, 1, 1 ],'),
|
||||
('"disabledFrames": [-1, 0, 0, 0, 0 ],', '"disabledFrames": [-1, 0, 0, 0, 0, -1 ],'), ('"textStrings": [ "@personal", "@shared", "@gems", "@materials", "@runes" ],', '"textStrings": [ "@personal", "@shared", "@dmTroveTab", "@materials", "@runes", "@dmStashVaultTab" ],')):
|
||||
if s.count(a) != 1: raise SystemExit('wide_stash:储藏箱布局 %s 不是原样(原版布局变了?)' % a.strip())
|
||||
s = s.replace(a, b)
|
||||
# 页签条右端的手柄键帽(ZR):原版按五个页签摆在 x 1135(= 五个页签的右沿 1075 再往外 60),加了第六个页签后正好落在「编年史」页签的字上(看图发现)。
|
||||
# 现在屏上只有四个页签(珍宝匣把材料 / 符文两个页签收掉了,dm_cursor.c ui_trove_tabs_pump):键帽放在第四个页签右沿(860)外 60;左端的 ZL 不动。只改 BankTabs 这一条(同文件里另外几条页签条不动);触屏版键帽是透明图,位置无所谓
|
||||
# Controller keycap (ZR) at the right end of the tab bar: the game places it at x 1135 for five tabs (= the right edge of five tabs, 1075, plus 60); with a sixth tab added it landed right on the text of the "Chronicle" tab (found by looking at a screenshot).
|
||||
# There are now only four tabs on screen (the Trove removed the materials / runes tabs, dm_cursor.c ui_trove_tabs_pump): the keycap goes 60 beyond the right edge of the fourth tab (860); ZL at the left end stays. Only the BankTabs entry is changed (the other tab bars in the same file are untouched); the touch keycap is a transparent image, so its position does not matter
|
||||
i = s.index('"name": "BankTabs"'); k = '"tabRightIndicatorPosition": "$HalfPanelRightTabButtonPromptPosition",'; j = s.find(k, i)
|
||||
if j < 0 or j - i > 2500: raise SystemExit('wide_stash:BankTabs 的右端键帽位置不是原样(原版布局变了?)')
|
||||
s = s[:j] + '"tabRightIndicatorPosition": { "x": 920, "y": -2 },' + s[j + len(k):]
|
||||
# 个人仓库页码(dm_pages.c):自己的文字控件,不再借原版共享页那块页码(SharedStashTabContainer / CurrentSharedStashText)。缺省在屏外,宿主在个人页挪进来
|
||||
# Personal stash page number (dm_pages.c): our own text widget, no longer borrowing the original game's shared page number block (SharedStashTabContainer / CurrentSharedStashText). Off screen by default; the host moves it in on personal pages
|
||||
pg = {'type': 'Widget', 'name': 'TouchPgPage', 'fields': {'rect': {'x': 99999, 'y': 0, 'width': 1730, 'height': 1300}}, 'children': [
|
||||
_vt_text('TouchPgPage_Text', 675, 1159, 322, 64, '$FontColorGoldYellow', '$MediumFontSize', 'center')]}
|
||||
end = s.rstrip().rstrip('}').rstrip(); assert end.endswith(']'); at = len(end) - 1
|
||||
return s[:at].rstrip().rstrip(',') + ',\n ' + json.dumps(pg, ensure_ascii=False) + ',\n ' + json.dumps(vault_widgets(), ensure_ascii=False) + '\n ' + s[at:]
|
||||
|
||||
def overlay_layout(text):
|
||||
i = text.find('"name": "Background"'); j = text.find('"TabBarWidget", "name": "Tabs"')
|
||||
if i < 0 or j < 0: raise SystemExit('wide_stash:外框布局里没有 Background / Tabs(原版布局变了?)')
|
||||
k = text.rfind('{', 0, j)
|
||||
add = ('{\n "type": "ImageWidget", "name": "WideBackground",\n "fields": {\n'
|
||||
' "rect": { "x": 99999, "y": 0 },\n "filename": "Controller/Panel/zswide/MainPanelBG_Wide",\n },\n },\n ')
|
||||
text = text[:k] + add + text[k:]
|
||||
# 魔盒并排时的两个标题(dm_cursor.c 魔盒并排那段):原版标题条此时写的是「赫拉迪克方块 | 物品栏」(魔盒面板在原版里占左边那一位),
|
||||
# 并排后左边其实是储藏箱、右边是魔盒。原版那两个字挪出屏(位置守卫),换成我们自己的两个文字控件:字用原版串(@stash / @box)、样式照面板标题,
|
||||
# 位置照储藏箱加宽后原版两个标题字的矩形(左 -196 宽 1832、右 1636 宽 1440,见 dm_cursor.c ui_wide_pump),缺省在屏外
|
||||
# The two titles while the cube is side by side (the cube side-by-side section of dm_cursor.c): the original title bar then reads 「赫拉迪克方块 | 物品栏」(Horadric Cube | Inventory) (in the original game the cube panel occupies the left position),
|
||||
# but once side by side the left is actually the stash and the right is the cube. The two original title texts are moved off screen (position guard) and replaced with two text widgets of our own: the text uses the original strings (@stash / @box), the style follows the panel title,
|
||||
# and the positions follow the rects of the two original title texts after the stash is widened (left -196 width 1832, right 1636 width 1440, see dm_cursor.c ui_wide_pump); off screen by default
|
||||
st = {'type': 'Widget', 'name': 'TouchSideTitle', 'fields': {'rect': {'x': 99999, 'y': 0, 'width': 3272, 'height': 103}}, 'children': [
|
||||
_vt_text('TouchSideTitle_L', 0, 0, 1832, 103, '$FontColorWhite', '$MediumFontSize', 'center', '@stash'),
|
||||
_vt_text('TouchSideTitle_R', 1832, 0, 1440, 103, '$FontColorWhite', '$MediumFontSize', 'center', '@box')]}
|
||||
# 插在标题条 Tabs 这个控件的后面、同一个父控件里(同一套缩放与原点,各种屏幕档位都跟着原版标题走;画在标题条之上)
|
||||
# Inserted right after the title bar's Tabs widget, in the same parent widget (same scaling and origin, so it follows the original title on every screen profile; drawn above the title bar)
|
||||
j = text.find('"TabBarWidget", "name": "Tabs"'); k = text.rfind('{', 0, j); d = 0; e = k
|
||||
while e < len(text):
|
||||
c = text[e]
|
||||
if c == '{': d += 1
|
||||
elif c == '}':
|
||||
d -= 1
|
||||
if d == 0: break
|
||||
e += 1
|
||||
if d != 0: raise SystemExit('wide_stash:外框布局里 Tabs 控件的括号没配上(原版布局变了?)')
|
||||
return text[:e + 1] + ',\n ' + json.dumps(st, ensure_ascii=False) + text[e + 1:]
|
||||
|
||||
def build(romfs, outdir, repl):
|
||||
out = {}
|
||||
# 表有两份:excel/inventory.bin 与 excel/base/inventory.bin,游戏按角色所属的模式选一套数据表(取格函数 main+0x560b80 按 [单位+0x1bd] 选)。
|
||||
# 只改一份时,用另一套的角色(如 88 级法师这类老角色)界面画 14 列、游戏按 10 宽取格,指到第 10 列越界读崩 main+0x560c6c
|
||||
# There are two copies of the table: excel/inventory.bin and excel/base/inventory.bin; the game picks one set of data tables by the mode the character belongs to (the cell lookup function main+0x560b80 selects by [unit+0x1bd]).
|
||||
# If only one copy is changed, for characters using the other set (old characters such as the level 88 sorceress) the UI draws 14 columns while the game looks up cells at width 10, and pointing at column 10 reads out of bounds and crashes at main+0x560c6c
|
||||
for sub in ('', 'base_'):
|
||||
path, inv = _entry(romfs, '/global/excel/' + sub.replace('_', '/') + 'inventory.bin'); inv = bytearray(inv)
|
||||
for row in (10, 25):
|
||||
o = 4 + row * 240 + 16
|
||||
if inv[o:o + 2] != b'\x0a\x0a': raise SystemExit('wide_stash:%s 第 %d 行不是 10×10(原版表变了?)' % (path, row))
|
||||
inv[o] = COLS
|
||||
# 佣兵加装备位(秘境 10 层解锁,产物 r39 起配服务端那道门):佣兵行(第 11 行,第二套第 26 行)原版只定义了右手 / 身 / 左手 / 头四个部位的格子,
|
||||
# 项链 / 右戒 / 左戒 / 腰带 / 鞋 / 手套(格序 4–9)全是 −1;服务端放置校验 main+0x65032c 对非玩家主人固定读第 11 行,四个坐标全负就拒。
|
||||
# 这里照玩家行(第 0 行)的相对位置补上:玩家面板原点在 x = 320,佣兵面板在 0;第二套整体再偏 (+80, +60)(两行已有四格的差)。每格 20 字节:左 右 上 下 + 1 个整数
|
||||
# Extra mercenary equipment slots (unlocked at rift level 10; paired with the server-side gate from build output r39): the mercenary row (row 11, row 26 in the second set) in the original only defines cells for the four body locations right hand / torso / left hand / head,
|
||||
# while amulet / right ring / left ring / belt / boots / gloves (cell order 4–9) are all −1; the server placement check main+0x65032c always reads row 11 for non-player owners and rejects when all four coordinates are negative.
|
||||
# Here they are filled in following the relative positions in the player row (row 0): the player panel's origin is at x = 320 and the mercenary panel's at 0; the second set is offset by a further (+80, +60) overall (the difference of the four existing cells between the two rows). 20 bytes per cell: left right top bottom + 1 integer
|
||||
import struct
|
||||
for row, dx, dy in ((11, -320, 0), (26, -240, 60)):
|
||||
base = 4 + row * 240 + 0x28
|
||||
if struct.unpack_from('<4i', inv, base + 4 * 0x14) != (-1, -1, -1, -1): raise SystemExit('wide_stash:%s 第 %d 行的项链格不是空的(原版表变了?)' % (path, row))
|
||||
for k in range(4, 10):
|
||||
l, r, t, b_, x = struct.unpack_from('<5i', inv, 4 + 0x28 + k * 0x14)
|
||||
struct.pack_into('<5i', inv, base + k * 0x14, l + dx, r + dx, t + dy, b_ + dy, x)
|
||||
p = os.path.join(outdir, 'ws_' + sub + 'inventory.bin'); open(p, 'wb').write(inv); out[path] = p
|
||||
for n, rel in SPRITES.items():
|
||||
p = os.path.join(outdir, 'ws_' + n + '.sprite'); shutil.copyfile(os.path.join(ART, n + '_wide.sprite'), p); out['data/hd/global/ui/' + rel + '.sprite'] = p
|
||||
p = os.path.join(outdir, 'ws_mainpanelbg_wide.sprite'); shutil.copyfile(os.path.join(ART, 'MainPanelBG_Wide.sprite'), p); out['+data/hd/global/ui/' + WIDE_FRAME + '.sprite'] = p
|
||||
for n in ('VaultBottom',): # 编年史页底部盖板(gen_vault_cover.py 从宽共享页底图裁的) | Bottom cover of the chronicle page (cropped by gen_vault_cover.py from the wide shared page background image)
|
||||
p = os.path.join(outdir, 'ws_' + n.lower() + '.sprite'); shutil.copyfile(os.path.join(ART, n + '.sprite'), p); out['+data/hd/global/ui/controller/panel/zswide/' + n.lower() + '.sprite'] = p
|
||||
for rel, fn in ((BANK, bank_layout), (OVERLAY, overlay_layout)):
|
||||
logical = touch_layout.read_layout(romfs, rel)[0].lower(); src = repl.get(logical)
|
||||
text = open(src, encoding='utf-8').read() if src else touch_layout.read_layout(romfs, rel)[1] # 叠在触摸布局已改的那份上 | Stacked on top of the copy already modified by the touch layout
|
||||
p = os.path.join(outdir, 'ws_' + os.path.basename(rel)); open(p, 'w', encoding='utf-8').write(fn(text)); out[logical] = p
|
||||
return out, {'cols': COLS, 'files': len(out)}
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
# 后处理链上界矩阵:每局一种环境,输出各趟(按首绘片元键)对深度预通道片元的归一比值。
|
||||
# 用法:ppm.sh <序列…>,元素 = base / nofxaa / bloomq0 / skiptm / skipcp / skipfx / skipcopy / skiplin
|
||||
# Upper-bound matrix for the post-processing chain: one environment per run; outputs each pass's (keyed by first-draw fragment key) normalized ratio to the depth pre-pass fragment.
|
||||
# Usage: ppm.sh <sequence...>, elements = base / nofxaa / bloomq0 / skiptm / skipcp / skipfx / skipcopy / skiplin
|
||||
PN=$(bash "$(dirname "$0")/../../tools/product.sh" name touch); D=${XT_MINI_DIR:-$(ls -dt "${DM_ROOT:-$HOME/dm-work}"/run/mini/*_"$PN" 2>/dev/null | head -1)}; [ -d "$D" ] || { echo "没有 mini 同步目录 ${DM_ROOT:-$HOME/dm-work}/run/mini/*_$PN(先 mini_sync.sh,或用 XT_MINI_DIR 指定)"; exit 2; }; T=$D/src/dm/ios/tools; B=${DM_ROOT:-$HOME/dm-work}/run/xtrace/batch_$(date +%m%d_%H%M%S)_ppm; mkdir -p $B; O=$B/out.tsv; : > $O
|
||||
source $T/mlock.sh; mlock_acquire "${XT_OWNER:?先设 XT_OWNER=线名} 后处理矩阵 $# 局 约 $(( $# * 95 / 60 )) 分钟"; trap mlock_release EXIT; i=0
|
||||
for v in "$@"; do
|
||||
case $v in
|
||||
base) x=;; nofxaa) x="DM_NVN_NOFXAA=1";; bloomq0) x="DM_NVN_BLOOM_Q=0";;
|
||||
skiptm) x="DM_NVN_SKIP_FS=2e2d6700,f371fb3f,a1b1aab6";; skipcp) x="DM_NVN_SKIP_FS=52aac1f2,9a650561";; skipfx) x="DM_NVN_SKIP_FS=ebcfcd1f";;
|
||||
skipcopy) x="DM_NVN_SKIP_FS=d5fcb22f,45a5b1ff";; skiplin) x="DM_NVN_SKIP_FS=56c2fef6,5ddee022";; *) echo "未知 $v"; continue;;
|
||||
esac
|
||||
i=$((i + 1)); R=$B/$(printf %02d $i)_$v
|
||||
XT_DIR=$R XT_ENV="DM_NVN_ENC_LABEL=1 $x" XT_ONLY='^metal-gpu-intervals$' XT_TREE=$D/src XT_OUT=$D/out/$PN XT_SAVE=$D/data/switch/save_ref_warlock/0000000000000001 \
|
||||
bash $T/xtrace.sh mac camp 'Game Performance' 12 35 > $R.log 2>&1
|
||||
red=$(grep -c '【红】' $R/host.err 2>/dev/null)
|
||||
python3 $T/xtrace_report.py $R 2>/dev/null | python3 ${DM_ROOT:-$HOME/dm-work}/run/xtrace/ppm_row.py "$v" "$red" | tee -a $O
|
||||
[ -d $R/tables ] && find $R/tables -delete # 读数已进 out.tsv,导出的表不留(单局约 100 MB) | The readings are already in out.tsv, so the exported tables are not kept (about 100 MB per run)
|
||||
done
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
# 读 xtrace_report.py 的输出,按首绘片元键归并各趟 GPU 区间(片元 + 顶点),除以深度预通道片元(94949567 @ 2151x990)做同局归一,打一行
|
||||
# Read the output of xtrace_report.py, merge each pass's GPU intervals (fragment + vertex) by first-draw fragment key, divide by the depth pre-pass fragment (94949567 @ 2151x990) to normalize within the same run, and print one line
|
||||
import sys, re, collections
|
||||
name, red = sys.argv[1], sys.argv[2]
|
||||
g = collections.Counter(); tot = nf = ref = 0
|
||||
for l in sys.stdin:
|
||||
m = re.search(r'(\d+) 帧.*合计 ([\d.]+)', l)
|
||||
if m and 'metal-gpu-intervals' in l: nf = int(m[1]); tot = float(m[2])
|
||||
m = re.match(r'\s+([\d.]+) ms/帧\s+[\d.]+%\s+[\d.]+ 段/帧\s+(\w+)\s+p\d+ (\d+x\d+) (\w+) d\d+', l)
|
||||
if not m: continue
|
||||
g[m[4]] += float(m[1])
|
||||
if m[4] == '94949567' and m[3] == '2151x990' and m[2] == 'Fragment': ref = float(m[1])
|
||||
keys = [('5c1ca4e7', '场景'), ('a1b1aab6', '色调映射趟'), ('2e2d6700', '泛光叠加'), ('f371fb3f', '大气'), ('9a650561', '合成趟'), ('52aac1f2', '放大'),
|
||||
('ebcfcd1f', 'FXAA'), ('d5fcb22f', '颜色拷贝'), ('45a5b1ff', '颜色降采样'), ('56c2fef6', '线性化深度'), ('fbb33036', '透明合并'), ('8e80084d', '透明上采样'), ('2938a5b7', '泛光截取')]
|
||||
ref = ref or 1e9
|
||||
warn = '' if nf >= 350 and 5 <= tot <= 13 else ' ⚠作废(帧数 / 采样量异常:正常约 440 帧、合计 7–10)'
|
||||
print('%s\t%d 帧 合计 %.2f 红 %s\t' % (name, nf, tot, red) + ' '.join('%s %.2f' % (n, g[k] / ref) for k, n in keys if g[k] > 0) + ' | 合计÷基准 %.1f' % (tot / ref) + warn)
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
# 单个着色器变体的上界量法:XT_OWNER=<持有者名> var.sh <序列…>,序列元素 = base 或变体名
|
||||
# 变体库在 $DM_ROOT/run/xtrace/terr/<名>/b-89f2d5b38edb/(整套克隆后只换被改着色器的 _b.metallib;metallib 在本机编,mini 没有编译工具链)
|
||||
# 每局:带窗口营地 3D 0.75,预热 35 s 录 12 s;一行:帧数、区间合计、主通道(p11)片元、深度预通道(p08)片元、归一比值、红字数
|
||||
# 判法:看「对p08」相对基线;基线至少三局、每变体至少两局,两局对不上不报,<3% 算噪声;帧数明显少或合计异常小的那局作废
|
||||
# 整批持 mini 测量锁(同一时刻只跑一份测量);每局用自己的目录、按进程号出表
|
||||
# Upper-bound measurement for a single shader variant: XT_OWNER=<holder name> var.sh <sequence...>, sequence elements = base or a variant name
|
||||
# The variant library is in $DM_ROOT/run/xtrace/terr/<name>/b-89f2d5b38edb/ (a full clone with only the modified shader's _b.metallib replaced; the metallib is compiled on the local machine, the second Mac has no compiler toolchain)
|
||||
# Each run: windowed, camp, 3D 0.75, warm up 35 s and record 12 s; one line: frame count, interval total, main pass (p11) fragment, depth pre-pass (p08) fragment, normalized ratio, number of failure lines
|
||||
# How to judge: look at 「对p08」(vs p08) relative to the baseline; at least three baseline runs and at least two runs per variant; if the two runs disagree do not report it, and <3% counts as noise; a run with clearly fewer frames or an abnormally small total is void
|
||||
# The whole batch holds the second Mac's measurement lock (only one measurement runs at a time); each run uses its own directory and produces tables by process id
|
||||
PN=$(bash "$(dirname "$0")/../../tools/product.sh" name touch); D=${XT_MINI_DIR:-$(ls -dt "${DM_ROOT:-$HOME/dm-work}"/run/mini/*_"$PN" 2>/dev/null | head -1)}; [ -d "$D" ] || { echo "没有 mini 同步目录 ${DM_ROOT:-$HOME/dm-work}/run/mini/*_$PN(先 mini_sync.sh,或用 XT_MINI_DIR 指定)"; exit 2; }; T=$D/src/dm/ios/tools; W=${DM_ROOT:-$HOME/dm-work}/run/xtrace/terr; B=${DM_ROOT:-$HOME/dm-work}/run/xtrace/batch_$(date +%m%d_%H%M%S)_var; mkdir -p $B; O=$B/out.tsv; : > $O
|
||||
source $T/mlock.sh; mlock_acquire "${XT_OWNER:?先设 XT_OWNER=线名} 着色器变体 $# 局 约 $(( $# * 95 / 60 )) 分钟"; trap mlock_release EXIT
|
||||
i=0; for v in "$@"; do i=$((i + 1)); R=$B/$(printf %02d $i)_$v
|
||||
e="DM_NVN_ENC_LABEL=1"; [ $v = base ] || { [ -d $W/$v/b-89f2d5b38edb ] || { echo "没有变体库 $W/$v"; continue; }; e="$e DM_MSL_DIR=$W/$v"; }
|
||||
XT_DIR=$R XT_ENV="$e" XT_ONLY='^metal-gpu-intervals$' XT_TREE=$D/src XT_OUT=$D/out/$PN XT_SAVE=$D/data/switch/save_ref_warlock/0000000000000001 bash $T/xtrace.sh mac camp 'Game Performance' 12 35 > $R.log 2>&1
|
||||
red=$(grep -c '【红】' $R/host.err 2>/dev/null)
|
||||
python3 $T/xtrace_report.py $R 2>/dev/null | awk -v k=$v -v red=$red '/metal-gpu-intervals/{match($0,/[0-9]+ 帧/); nf=substr($0,RSTART,RLENGTH); match($0,/合计 [0-9.]+/); tot=substr($0,RSTART+7,RLENGTH-7)} / p11 /{if($6=="Fragment")f=$1} / p08 /{if($6=="Fragment")df=$1} END{w=(nf+0>=350 && tot+0>=5 && tot+0<=13)?"":"\t⚠作废(帧数 / 采样量异常:正常约 440 帧、合计 7–10)"; printf "%s\t%s 合计 %s\tp11 片元 %s\tp08 片元 %s\t对p08 %.3f\t红 %s%s\n",k,nf,tot,f,df,(df>0?f/df:0),red,w}' | tee -a $O
|
||||
[ -d $R/tables ] && find $R/tables -delete # 读数已进 out.tsv,导出的表不留(单局约 100 MB) | The readings are already in out.tsv, so the exported tables are not kept (about 100 MB per run)
|
||||
done; echo "结果 $O"
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/bin/bash
|
||||
# 苹果 Instruments 命令行录制 + 导出:真机上把 App 拉进营地 / 野外,预热后用 xctrace 挂上进程录一段,再把 .trace 里每张表导出成 XML。
|
||||
# 以后量「时间花在哪」先用它,不先造开关。模板:Game Performance / Game Performance Overview / Metal System Trace / Power Profiler / CPU Counters / System Trace / Time Profiler。
|
||||
# 用法(真机):XT_TREE=<已构建的树(有 .iosdd)> xtrace.sh <camp|wild|menu|blank> <模板名> [录制秒=30] [预热秒=30]
|
||||
# menu = 停在主菜单(触摸覆盖层隐藏)、blank = 纯 Metal 空白页(-mode blank,零子视图):给「系统合成器走不走直接上屏」做对照(看 displayed-surfaces-interval 的 direct-to-display 列)
|
||||
# 用法(本机 / mini,带窗口宿主):XT_OWNER=<线名+在量什么> XT_TREE=<树> XT_OUT=<产物> xtrace.sh mac camp <模板名> [录制秒=30] [预热秒=60] 可调 XT_RES / XT_3D / XT_ENV / XT_DIR;进门取 mini 测量锁(mlock.sh)
|
||||
# XT_INSTALL=1 先装机(装的就是 XT_TREE 的包);XT_ENV="DM_X=1 DM_Y=2" 追加 App 环境;XT_EXPORT=0 只录不导出(之后可 xtrace.sh export <trace>)
|
||||
# 单独导出:xtrace.sh export <x.trace> → 同目录 toc.xml + tables/<schema>.xml
|
||||
# 产物:$DM_ROOT/run/ios/xtrace/<时刻>_<场景>_<模板>/{t.trace, toc.xml, tables/*.xml, launch.log, record.log}。走设备锁(测量类),单段占机 = 预热 + 录制 + 约 20 s。
|
||||
# Apple Instruments command-line recording + export: on the real device, bring the App into the camp / wilderness, after warm-up attach xctrace to the process and record a stretch, then export every table in the .trace as XML.
|
||||
# From now on, to measure 'where the time goes' use this first instead of building switches first. Templates: Game Performance / Game Performance Overview / Metal System Trace / Power Profiler / CPU Counters / System Trace / Time Profiler.
|
||||
# Usage (real device): XT_TREE=<built tree (with .iosdd)> xtrace.sh <camp|wild|menu|blank> <template name> [record seconds=30] [warm-up seconds=30]
|
||||
# menu = stay on the main menu (touch overlay hidden), blank = pure Metal blank page (-mode blank, zero subviews): a control for 'whether the system compositor goes direct-to-display' (look at the direct-to-display column of displayed-surfaces-interval)
|
||||
# Usage (local machine / the second Mac, windowed host): XT_OWNER=<line name + what is being measured> XT_TREE=<tree> XT_OUT=<build output> xtrace.sh mac camp <template name> [record seconds=30] [warm-up seconds=60] adjustable: XT_RES / XT_3D / XT_ENV / XT_DIR; takes the second Mac's measurement lock on entry (mlock.sh)
|
||||
# XT_INSTALL=1 installs first (what is installed is XT_TREE's bundle); XT_ENV="DM_X=1 DM_Y=2" appends App environment; XT_EXPORT=0 records only without exporting (later you can run xtrace.sh export <trace>)
|
||||
# Standalone export: xtrace.sh export <x.trace> → toc.xml + tables/<schema>.xml in the same directory
|
||||
# Build output: $DM_ROOT/run/ios/xtrace/<time>_<scene>_<template>/{t.trace, toc.xml, tables/*.xml, launch.log, record.log}. Goes through the device lock (measurement class); device occupancy per segment = warm-up + recording + about 20 s.
|
||||
export DM_DEVLOCK_CLASS=measure
|
||||
export XT_TABLES="ca-client-buffer-wait-interval ca-client-present-request display-vsyncs-interval display-surface-swap displayed-surfaces-interval metal-gpu-intervals metal-gpu-state-intervals metal-application-encoders-list metal-application-intervals metal-driver-event-intervals metal-command-buffer-error metal-shader-profiler-intervals metal-shader-profiler-shader-list gpu-performance-state-intervals gpu-performance-device-state-intervals gpu-shader-profiler-interval gpu-shader-profiler-sample gpu-counter-info gpu-counter-value device-thermal-state-intervals context-switch cpu-state graphics-compiler-activity-intervals graphics-compiler-spill-events hang-risks system-load thread-info"
|
||||
set -u
|
||||
t(){ echo "[$(date +%T)] $*"; }
|
||||
# xctrace 每录一次会在用户临时目录留一个 instruments*.ktrace(约 1.5 GB)且不清:85 个共 120 GB 把 mini 写满。录完删本次的,顺带删半小时前的陈货。
|
||||
# Each xctrace recording leaves an instruments*.ktrace (about 1.5 GB) in the user temp directory and never cleans it: 85 of them totaling 120 GB filled up the second Mac. Delete this recording's after it finishes, and along the way delete stale ones older than half an hour.
|
||||
kt_mark(){ KT0=$1/.kt0; : > "$KT0"; }
|
||||
kt_clean(){ local T; T=$(getconf DARWIN_USER_TEMP_DIR); find "$T" -maxdepth 1 -name 'instruments*.ktrace' \( -newer "$KT0" -o -mmin +30 \) -delete 2>/dev/null; }
|
||||
xexport(){ # <trace>:导出目录页与每张表(同名表多份时加序号) | <trace>: export the table of contents and every table (add an index when there are several tables with the same name)
|
||||
local tr=$1 d; d=$(dirname "$tr"); mkdir -p "$d/tables"
|
||||
# 真机 trace 导目录页时 xctrace 会崩(ProcessLoader 段错误,单表导出不受影响)→ 退回按内置表名逐张试
|
||||
# xctrace crashes when exporting the table of contents of a real-device trace (ProcessLoader segmentation fault; single-table export is unaffected) → fall back to trying the built-in table names one by one
|
||||
xcrun xctrace export --input "$tr" --toc --output "$d/toc.xml" 2> "$d/export.log" || { t "目录页导不出,按内置表名逐张导"; for s in $XT_TABLES; do echo "<table schema=\"$s\"/>"; done > "$d/toc.xml"; }
|
||||
python3 - "$tr" "$d" <<'PY'
|
||||
import sys, re, os, subprocess, collections
|
||||
tr, d = sys.argv[1:3]; toc = open(d + '/toc.xml').read(); seen = collections.Counter()
|
||||
skip = re.compile(os.environ.get('XT_SKIP', r'^(kdebug|os-log|os-signpost|time-sample|time-profile|counters-profile)')) # 原始内核事件表单张可上 GB,缺省不导;XT_SKIP='^$' 全导
|
||||
only = re.compile(os.environ.get('XT_ONLY', '^(' + '|'.join(os.environ['XT_TABLES'].split()) + ')$')) # 缺省只导读数用得上的表(全导约 6 分钟);XT_ONLY=. 全导
|
||||
for s in re.findall(r'<table [^>]*schema="([^"]+)"', toc):
|
||||
seen[s] += 1
|
||||
if skip.search(s) or not only.search(s): continue
|
||||
out = f'{d}/tables/{s}' + (f'.{seen[s]}' if seen[s] > 1 else '') + '.xml'
|
||||
xp = f'/trace-toc/run[@number="1"]/data/table[@schema="{s}"][{seen[s]}]'
|
||||
r = subprocess.run(['xcrun', 'xctrace', 'export', '--input', tr, '--xpath', xp, '--output', out], capture_output=True, text=True)
|
||||
print(f'{s}\t{out if r.returncode == 0 else "失败:" + r.stderr.strip()[:80]}')
|
||||
PY
|
||||
}
|
||||
[ "${1:-}" = export ] && { xexport "${2:?缺 .trace 路径}"; exit; }
|
||||
if [ "${1:-}" = mac ]; then # 本机(Mac / mini)带窗口宿主:xtrace.sh mac <camp|wild> <模板> [录制秒=30] [预热秒=60];份额类读数在这里取,不占手机 | Local machine (Mac / the second Mac) windowed host: xtrace.sh mac <camp|wild> <template> [record seconds=30] [warm-up seconds=60]; share-type readings are taken here, without occupying the phone
|
||||
SC=${2:?camp|wild}; TPL=${3:?模板名}; SEC=${4:-30}; WARM=${5:-60}; W=${XT_TREE:?XT_TREE = 含 dm/host/dmhost 的树}; OUT=${XT_OUT:?XT_OUT = 产物目录}
|
||||
source "$(dirname "$0")/mlock.sh"; mlock_acquire "${XT_OWNER:-未署名} xctrace $SC $(basename "$TPL" .tracetemplate) 约 $((WARM + SEC + 40)) s"; trap mlock_release EXIT # 同一时刻只跑一份测量;批量脚本自己持锁时这里不再取 | Only one measurement runs at a time; when a batch script holds the lock itself it is not taken again here
|
||||
SV=${XT_SAVE:-${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001}; R=${XT_DIR:-${XT_RUN:-${DM_ROOT:-$HOME/dm-work}/run/xtrace}/$(date +%m%d_%H%M%S)_mac_${SC}_$(basename "$TPL" .tracetemplate | tr ' ' '_')}; mkdir -p "$R/temp" # XT_DIR:调用方指定本局目录(别用「取最新目录」,会拿到别人那局) | XT_DIR: the caller specifies this run's directory (do not use 'take the newest directory', it will pick up someone else's run)
|
||||
[ "$(df -m "$R" | awk 'NR==2{print $4}')" -ge 20480 ] || { echo "🔴 磁盘剩余不足 20 GB,不跑(清 ${DM_ROOT:-$HOME/dm-work}/run/xtrace 里旧的 t.trace)"; exit 1; }
|
||||
cp -R "$SV/0" "$R/save" && chmod -R u+w "$R/save" || { echo "🔴 拷存档失败"; exit 1; }
|
||||
K='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,MSG:CharacterSelect:LoadCharacter:0@OpenPanel:CharacterSelectPanel%1>FrontEndNavigation:ToGame'
|
||||
[ "$SC" = camp ] || { echo "🔴 mac 模式目前只接了营地(野外要回放前缀,后补)"; exit 2; }
|
||||
( cd "$W/dm/host" && bash "${XT_GUIRUN:-$W/dm/tools/guirun.sh}" -o "$R/host.log" -e "$R/host.err" -p "$R/pid" DM_WINDOW=1 DM_GAME_RES=${XT_RES:-2868x1320} DM_3D_SCALE=${XT_3D:-0.75} \
|
||||
DM_KEYS="$K" DM_SAVE="$R/save" DM_TEMP="$R/temp" DM_NVN_SHMAP="$W/dm/gfx/nvn/shader_map.tsv" DM_WATCH=$((WARM + SEC + 60)) ${XT_ENV:-} -- "$W/dm/host/dmhost" "$OUT" main sdk ) &
|
||||
t "已起带窗口宿主,预热 $WARM s"; sleep "$WARM"; p=$(cat "$R/pid" 2>/dev/null); kill -0 "$p" 2>/dev/null || { t "🔴 宿主不在了"; tail -3 "$R/host.log" "$R/host.err"; exit 1; }
|
||||
t "录制 $TPL $SEC s(pid ${p})"; kt_mark "$R"; timeout -k 5 $((SEC + 60)) xcrun xctrace record --template "$TPL" --attach "$p" --time-limit "${SEC}s" --output "$R/t.trace" --no-prompt > "$R/record.log" 2>&1; kill "$p" 2>/dev/null; kt_clean
|
||||
[ -d "$R/t.trace" ] || { t "🔴 没有录到 trace"; tail -5 "$R/record.log"; exit 1; }
|
||||
t "录完 → $R/t.trace"; [ "${XT_EXPORT:-1}" = 0 ] || xexport "$R/t.trace" | tee "$R/tables.tsv" | wc -l | xargs -I{} echo "导出 {} 张表 → $R/tables/"
|
||||
# 导出完就删录制本体与存档副本(单局 100–400 MB;73 局把 mini 磁盘写满,之后的录制存不下、出空表)。XT_KEEP_TRACE=1 保留
|
||||
# Delete the recording itself and the save copy as soon as the export finishes (100–400 MB per run; 73 runs filled the second Mac's disk, and later recordings could not be stored and produced empty tables). XT_KEEP_TRACE=1 keeps them
|
||||
[ "${XT_EXPORT:-1}" = 0 ] || [ "${XT_KEEP_TRACE:-0}" = 1 ] || for sub in t.trace save save.work temp; do [ -e "$R/$sub" ] && find "$R/$sub" -delete; done
|
||||
echo "RUN $R PID $p"; exit # 出表:xtrace_report.py <目录>(自动按 $R/pid 的进程号过滤) | Produce tables: xtrace_report.py <dir> (automatically filters by the process id in $R/pid)
|
||||
fi
|
||||
SC=${1:?camp|wild|menu|blank}; TPL=${2:?模板名}; SEC=${3:-30}; WARM=${4:-30} # 占机 = 预热 + 录制 + 约 60 s,测量类单轮上限 4 分钟 | Device occupancy = warm-up + recording + about 60 s; the single-round limit for measurement jobs is 4 minutes
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/local_env.sh" && local_env_need DM_DEVICE DM_IOS_UDID || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
|
||||
D=$DM_DEVICE; XD=${XT_UDID:-$DM_IOS_UDID}; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}; W=${XT_TREE:?XT_TREE 必填}
|
||||
APP=$W/.iosdd/Build/Products/Release-iphoneos/DmIOS.app; [ -d "$APP" ] || { echo "🔴 $APP 不存在(先构建)"; exit 1; }
|
||||
R=${DM_ROOT:-$HOME/dm-work}/run/ios/xtrace/$(date +%m%d_%H%M%S)_${SC}_$(basename "$TPL" .tracetemplate | tr ' ' '_'); mkdir -p "$R"
|
||||
K_CAMP='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,MSG:CharacterSelect:LoadCharacter:0@OpenPanel:CharacterSelectPanel%1>FrontEndNavigation:ToGame'
|
||||
K_WILD='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame'
|
||||
A='A@DM:ReplayDone+2'; for i in $(seq 1 40); do A="$A,$(echo LSL LSU LSR LSD | cut -d' ' -f$(( (i - 1) % 4 + 1 )))@+1,A@+2"; done
|
||||
envs=(DEVICECTL_CHILD_DM_BRIGHTNESS=0.5 DEVICECTL_CHILD_DM_SAVE_FRESH=warlock DEVICECTL_CHILD_DM_UIMSG=1) # DM_UIMSG=1:按键序列按界面消息触发,漏了就停在菜单页(录错过一次) | DM_UIMSG=1: the key sequence is triggered by UI messages; without it the run stays on the menu page (recorded wrongly once)
|
||||
case "$SC" in camp|wild|menu|blank) ;; *) echo "🔴 未知场景 $SC"; exit 2;; esac
|
||||
MODE=boot; [ "$SC" = blank ] && MODE=blank
|
||||
if [ "$SC" = camp ]; then envs+=(DEVICECTL_CHILD_DM_KEYS="$K_CAMP")
|
||||
elif [ "$SC" = menu ] || [ "$SC" = blank ]; then : # 不带按键:停在主菜单 / 空白页 | No keys: stay on the main menu / blank page
|
||||
else envs+=(DEVICECTL_CHILD_DM_KEYS="$K_WILD,$A" DEVICECTL_CHILD_DM_C2S_REPLAY=m1_wild.jsonl DEVICECTL_CHILD_DM_GAME_SEED=305419896); fi
|
||||
for e in ${XT_ENV:-}; do envs+=(DEVICECTL_CHILD_$e); done
|
||||
pid(){ xcrun devicectl device info processes --device $D 2>/dev/null | grep "DmIOS.app/DmIOS" | awk '{print $1}'; }
|
||||
source "$W/dm/ios/tools/devlock.sh"; devlock_acquire "${XT_OWNER:-未署名} xctrace $SC $TPL"; trap devlock_release EXIT; trap 'exit 143' INT TERM
|
||||
[ "${XT_INSTALL:-0}" = 1 ] && { timeout -k 5 120 xcrun devicectl device install app --device $D "$APP" > "$R/install.log" 2>&1 || { t "🔴 装机失败"; exit 1; }; }
|
||||
[ "$SC" = wild ] && { timeout -k 5 60 xcrun devicectl device copy to --device $D --domain-type appDataContainer --domain-identifier $B --source ${XT_WILD_C2S:-${DM_ROOT:-$HOME/dm-work}/run/verify/dm/run_sta_contract_1002_090004/wild_prefix_original_warlock/c2s.jsonl} --destination Documents/m1_wild.jsonl > /dev/null 2>&1 || t "🔴 推野外回放前缀失败"; }
|
||||
env "${envs[@]}" timeout -k 5 30 xcrun devicectl device process launch --device $D --terminate-existing $B -mode $MODE > "$R/launch.log" 2>&1 || { t "🔴 拉起失败"; tail -3 "$R/launch.log"; exit 1; }
|
||||
t "已拉起(${SC}),预热 $WARM s"; sleep "$WARM"
|
||||
p=$(pid); [ -n "$p" ] || { t "🔴 预热后进程不在(App 已退出)"; exit 1; }
|
||||
t "录制 $TPL $SEC s(pid ${p})"; kt_mark "$R"; timeout -k 5 $((SEC + 40)) xcrun xctrace record --device "$XD" --template "$TPL" --attach "$p" --time-limit "${SEC}s" --output "$R/t.trace" --no-prompt > "$R/record.log" 2>&1; rc=$?; kt_clean
|
||||
p=$(pid); [ -n "$p" ] && xcrun devicectl device process terminate --device $D --pid $p > /dev/null 2>&1
|
||||
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source Documents/perf.txt --destination "$R/perf.txt" > /dev/null 2>&1 # App 自记的每 10 秒一行:核场景与温控 | The line the App records itself every 10 seconds: verify the scene and thermal control
|
||||
devlock_release; trap - EXIT
|
||||
tail -4 "$R/perf.txt" 2>/dev/null | cut -f1-5,9-11; tail -4 "$R/perf.txt" 2>/dev/null | grep -q 局内 || t "🔴 录制期间 App 不在局内(看上面 perf.txt 末几行的场景列):这条不算数"
|
||||
[ -d "$R/t.trace" ] || { t "🔴 没有录到 trace(xctrace 退出码 ${rc})"; tail -5 "$R/record.log"; exit 1; }
|
||||
t "录完 → $R/t.trace($(du -sh "$R/t.trace" | cut -f1))"; [ "${XT_EXPORT:-1}" = 0 ] || xexport "$R/t.trace" | tee "$R/tables.tsv" | wc -l | xargs -I{} echo "导出 {} 张表 → $R/tables/"
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
# xtrace.sh 导出表的读数汇总。用法:xtrace_report.py <导出目录(含 tables/)> [进程名=DmIOS]
|
||||
# xctrace 导出的 XML 里同一个值第二次出现只写 ref="<id>",这里先按 id 还原再取数。时间单位:纳秒。
|
||||
# Summary of readings from the tables exported by xtrace.sh. Usage: xtrace_report.py <export dir (containing tables/)> [process name=DmIOS]
|
||||
# In the XML exported by xctrace, the second occurrence of the same value is written only as ref="<id>"; here values are first restored by id and then read. Time unit: nanoseconds.
|
||||
import sys, os, re, collections, statistics as st
|
||||
import xml.etree.ElementTree as ET
|
||||
D = sys.argv[1]
|
||||
# 第二参数:进程号(推荐)或进程名。不给时读 <目录>/pid(xtrace.sh mac 写的)。按进程名过滤会把同名的别人那局混进来(mini 上三个任务同时量,读数作废)。
|
||||
# Second argument: process id (recommended) or process name. If not given, read <dir>/pid (written by xtrace.sh mac). Filtering by process name mixes in someone else's same-named run (three jobs measuring at once on the second Mac, readings void).
|
||||
PROC = sys.argv[2] if len(sys.argv) > 2 else (open(os.path.join(D, 'pid')).read().strip() if os.path.exists(os.path.join(D, 'pid')) else 'DmIOS')
|
||||
def isme(s): return (f'({PROC})' in s or f'pid: {PROC}' in s) if PROC.isdigit() else PROC in s
|
||||
|
||||
def rows(schema):
|
||||
p = os.path.join(D, 'tables', schema + '.xml')
|
||||
if not os.path.exists(p) or os.path.getsize(p) == 0: return None, []
|
||||
root = ET.parse(p).getroot(); node = root.find('node'); cols = [c.findtext('mnemonic') for c in node.find('schema').findall('col')]
|
||||
ids = {}; out = []
|
||||
def val(e):
|
||||
if 'ref' in e.attrib: return ids.get(e.attrib['ref'])
|
||||
v = {'fmt': e.attrib.get('fmt', ''), 'text': (e.text or '').strip(), 'tag': e.tag, 'sub': {c.tag: val(c) for c in e}}
|
||||
if 'id' in e.attrib: ids[e.attrib['id']] = v
|
||||
return v
|
||||
for r in node.findall('row'):
|
||||
vs = [None if c.tag == 'sentinel' else val(c) for c in r]; out.append(dict(zip(cols, vs)))
|
||||
return cols, out
|
||||
num = lambda v: float(v['text']) if v and v['text'] not in ('', None) else None
|
||||
fmt = lambda v: v['fmt'] if v else ''
|
||||
def pct(a, q): a = sorted(a); return a[min(len(a) - 1, int(len(a) * q))] if a else float('nan')
|
||||
def dist(name, a, unit=1e6, u='ms'):
|
||||
a = [x / unit for x in a if x is not None]
|
||||
print(f'{name}:{len(a)} 个;' + (f'均值 {st.mean(a):.2f}、p50 {pct(a, .5):.2f}、p95 {pct(a, .95):.2f}、最大 {max(a):.2f} {u}' if a else '无数据'))
|
||||
def mine(r): # 这一行是否属于被测进程(有 process / thread 列的表) | Whether this row belongs to the process under test (for tables with process / thread columns)
|
||||
for k in ('process', 'thread'):
|
||||
if r.get(k) and isme(fmt(r[k])): return True
|
||||
return not any(r.get(k) for k in ('process', 'thread'))
|
||||
|
||||
print(f'# {D}')
|
||||
for s, col, label in (('ca-client-buffer-wait-interval', 'duration', '等下一张 drawable'), ('display-vsyncs-interval', 'duration', '垂直同步间隔'),
|
||||
('displayed-surfaces-interval', 'duration', '每张上屏画面的显示时长'), ('display-compositor-interval', 'duration', '合成器区间')):
|
||||
c, R = rows(s)
|
||||
if c is None: print(f'{label}:没有表 {s}'); continue
|
||||
dist(f'{label}({s})', [num(r[col]) for r in R if mine(r)])
|
||||
c, R = rows('metal-gpu-intervals') # GPU 上每个编码器的执行区间:按「第几个编码器 × 顶点 / 片元 / 计算」归并,除以帧数得每帧毫秒 | Execution intervals of each encoder on the GPU: merged by 'encoder index × vertex / fragment / compute', divided by the frame count to get milliseconds per frame
|
||||
if c:
|
||||
g = collections.defaultdict(float); n = collections.Counter(); frames = set(); tot = 0
|
||||
for r in R:
|
||||
lab = fmt(r.get('event-label'))
|
||||
if not isme(lab) or 'Command' not in lab: continue
|
||||
k = (re.sub(r'^Command Buffer \d+:|\s*\(.*$', '', lab).strip(), fmt(r.get('channel-name'))); d = num(r.get('duration')) or 0
|
||||
g[k] += d; n[k] += 1; tot += d; frames.add(fmt(r.get('frame-number')))
|
||||
nf = max(len(frames), 1); print(f'## metal-gpu-intervals:{len(R)} 行,{nf} 帧;本进程各编码器 GPU 区间合计 {tot / nf / 1e6:.2f} ms/帧(区间可并行重叠,是「活的份额」不是墙钟)')
|
||||
for k, v in sorted(g.items(), key=lambda kv: -kv[1])[:40]: print(f' {v / nf / 1e6:7.3f} ms/帧 {v / tot * 100:5.1f}% {n[k] / nf:4.1f} 段/帧 {k[1]:8s} {k[0]}')
|
||||
ch = collections.Counter()
|
||||
for k, v in g.items(): ch[k[1]] += v
|
||||
print(' 按阶段:' + ','.join(f'{k} {v / tot * 100:.1f}%' for k, v in ch.most_common()))
|
||||
for s in ('metal-application-encoders-list', 'metal-driver-event-intervals', 'metal-application-intervals'):
|
||||
c, R = rows(s)
|
||||
if c is None: print(f'没有表 {s}'); continue
|
||||
R = [r for r in R if mine(r)]; key = next((k for k in ('encoder-label', 'event-label', 'label', 'state', 'event-type', 'channel-name') if k in c), None)
|
||||
g = collections.defaultdict(list)
|
||||
for r in R: g[fmt(r.get(key)) if key else '全部'].append(num(r.get('duration')) or 0)
|
||||
tot = sum(sum(v) for v in g.values()); print(f'## {s}:{len(R)} 行,按「{key}」分组,总时长 {tot / 1e6:.1f} ms,列 {c}')
|
||||
for k, v in sorted(g.items(), key=lambda kv: -sum(kv[1]))[:25]: print(f' {sum(v) / 1e6:9.2f} ms {len(v):6d} 次 均 {st.mean(v) / 1e3:8.1f} µs {k[:70]}')
|
||||
for s, key in (('gpu-performance-state-intervals', 'gpu-performance-state'), ('device-thermal-state-intervals', 'thermal-state'), ('metal-gpu-state-intervals', 'state')):
|
||||
c, R = rows(s)
|
||||
if c is None: print(f'没有表 {s}'); continue
|
||||
g = collections.Counter()
|
||||
for r in R: g[(fmt(r.get(key)), fmt(r.get('track-label')) if 'track-label' in c else '')] += num(r.get('duration')) or 0
|
||||
tot = sum(g.values()) or 1; print(f'## {s}:{len(R)} 段'); [print(f' {v / tot * 100:5.1f}% {v / 1e9:7.2f} s {k}') for k, v in g.most_common(12)]
|
||||
c, R = rows('gpu-shader-profiler-interval') if os.path.exists(os.path.join(D, 'tables', 'gpu-shader-profiler-interval.xml')) else (None, [])
|
||||
if c:
|
||||
print(f'## gpu-shader-profiler-interval:{len(R)} 行,列 {c}'); key = next((k for k in ('shader-name', 'label', 'name', 'function', 'shader') if k in c), c[2] if len(c) > 2 else None)
|
||||
g = collections.Counter()
|
||||
for r in R: g[fmt(r.get(key))] += num(r.get('duration')) or 0
|
||||
tot = sum(g.values()) or 1; [print(f' {v / tot * 100:5.1f}% {v / 1e6:9.2f} ms {k[:80]}') for k, v in g.most_common(30)]
|
||||
c, R = rows('context-switch') # 各线程在哪类核上跑、被抢占多少次 | Which kind of core each thread runs on and how many times it is preempted
|
||||
if c:
|
||||
run = collections.defaultdict(collections.Counter); ev = collections.defaultdict(collections.Counter); last = {}
|
||||
for r in R:
|
||||
if not r.get('thread') or not isme(fmt(r['thread'])): continue
|
||||
th = fmt(r['thread']).split(' (')[0]; t = num(r['time']); e = fmt(r.get('event')); ev[th][e] += 1
|
||||
if th in last and last[th][1]: run[th][last[th][1]] += t - last[th][0]
|
||||
core = fmt(r.get('cpu')); last[th] = (t, ('P' if 'P Core' in core else 'E' if 'E Core' in core else '?') if e == 'Running' else None)
|
||||
print(f'## context-switch:{len(R)} 行;各线程在性能核 / 能效核上的运行时间与调度事件')
|
||||
for th, cnt in sorted(run.items(), key=lambda kv: -sum(kv[1].values()))[:14]:
|
||||
tot = sum(cnt.values()); print(f' {tot / 1e6:9.1f} ms P {cnt["P"] / tot * 100:5.1f}% E {cnt["E"] / tot * 100:5.1f}% 事件 {dict(ev[th].most_common(4))} {th[:40]}')
|
||||
for s in ('graphics-compiler-activity-intervals', 'metal-command-buffer-error', 'hang-risks', 'graphics-compiler-spill-events'):
|
||||
c, R = rows(s); print(f'{s}:' + ('没有这张表' if c is None else f'{len(R)} 行' + (f',总时长 {sum(num(r.get("duration")) or 0 for r in R) / 1e6:.1f} ms' if c and 'duration' in c else '')))
|
||||
Reference in New Issue
Block a user