Initial public release

This commit is contained in:
jhaizhou
2026-10-12 16:51:08 +08:00
commit 46578a2b5d
997 changed files with 218713 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
#import <UIKit/UIKit.h>
#include "dm_touch_controls.h"
#include "dm_touch_game_state.h"
#include "../../host/dm_hud.h"
// 绘制层不吃触点;真实事件由DmMetalView统一收集并保留dm_touch_set通路。
// The drawing layer does not consume touch points; real events are collected in one place by DmMetalView, keeping the dm_touch_set path.
@interface DmTouchOverlay : UIView
@property(nonatomic, assign) const dm_tc_state *controls;
@property(nonatomic, assign) BOOL navigationMode;
@property(nonatomic, assign) dm_tg_snapshot nativeMapping;
@property(nonatomic, assign) dm_hud_info hud;
@property(nonatomic, assign) BOOL dialogOnly; // 只开着 NPC 对话菜单:底栏照常画 | only the NPC dialog menu is open: the bottom bar is drawn as usual
@property(nonatomic, assign) BOOL hudBlocked; // 面板栈里有非常驻面板:UIKit 底栏让开(front_ios.m hud_stack_message) // 宿主每拍发布的 HUD 数字(底部 UI v4:经验条、角标、难度) | the panel stack has a non-persistent panel: the UIKit bottom bar gets out of the way (front_ios.m hud_stack_message) // HUD numbers published by the host every tick (bottom UI v4: experience bar, badges, difficulty)
- (NSDictionary *)controlMetadata;
@end
+315
View File
@@ -0,0 +1,315 @@
#import "DmTouchOverlay.h"
#include <math.h>
#include <TargetConditionals.h>
#include "dm_touch_native_art.h"
#include "hle.h"
#include "dm_input.h"
#include "../../host/dm_i18n.h"
#define DM_SKILL_IDLE_ALPHA .6 // 五个技能钮、回城钮、技能组切换钮没按着时的不透明度(底圈、圆环、图标同乘;要调浓淡只改这一处) | opacity of the five skill buttons, town portal button and skill set switch button when not held (base circle, ring and icon are all multiplied; this is the one place to tune it)
static UIColor *bronze(CGFloat a) { return [UIColor colorWithRed:.66 green:.53 blue:.32 alpha:a]; }
static void caption(NSString *s, CGRect rect, CGFloat size, CGFloat alpha) {
NSMutableParagraphStyle *p = [NSMutableParagraphStyle new]; p.alignment = NSTextAlignmentCenter;
UIFont *f = [UIFont fontWithName:@"Palatino" size:size];
[s drawInRect:rect withAttributes:@{NSFontAttributeName:f ?: [UIFont systemFontOfSize:size],
NSForegroundColorAttributeName:[UIColor colorWithRed:.85 green:.79 blue:.65 alpha:alpha],NSParagraphStyleAttributeName:p}];
}
// 技能钮上画哪个图标:读数入口与输入层相同(dm_ta_current_set),只多一条「旧了照旧画」。
// 测试注入 DM_TEST_OVERLAY_STALE_MS=<毫秒>:绘制时把「现在」往后拨这么多,等于技能快照已经这么旧(造「游戏停拍」时覆盖层的样子,不影响输入判定)
// Which icon to draw on a skill button: same reading entry as the input layer (dm_ta_current_set), with just one extra rule: "if stale, draw as before".
// Test injection DM_TEST_OVERLAY_STALE_MS=<ms>: when drawing, push "now" forward by this much, as if the skill snapshot were already this old (reproduces how the overlay looks when game ticks stall; does not affect input decisions)
static dm_ta_glyph shown_glyph(const dm_tg_snapshot *n, uint64_t button, uint64_t now, int set) {
static int64_t stale = -1; if (stale < 0) { const char *e = getenv("DM_TEST_OVERLAY_STALE_MS"); stale = e ? atoll(e) * 1000000ll : 0; }
now += (uint64_t)stale;
dm_ta_glyph g = dm_ta_current_set(n, button, now, set);
// 快照只是旧了(超过 250 毫秒没更新:游戏停拍、切后台那一瞬、长卡顿)→ 照它被取到那一刻的内容画,不退回 F 标签 / 十字——
// 绑定没变,只是暂时没人刷新;换场景时桥会把快照清空(dm_touch_game_bridge.c),那时取到时刻为 0,仍画占位。输入层的同一读数(front_ios.m)不走这里,照旧只认新鲜的
// The snapshot is merely stale (not updated for over 250 ms: game ticks stalled, the instant of going to background, a long hitch) → draw the content it had at the moment it was captured, do not fall back to the F label / cross --
// the binding has not changed, nobody is refreshing it for the moment; on scene change the bridge clears the snapshot (dm_touch_game_bridge.c), then the capture time is 0 and the placeholder is still drawn. The same reading in the input layer (front_ios.m) does not go through here and still accepts only fresh ones
if (g.status == DM_TA_UNKNOWN && n && n->captured_ns && now > n->captured_ns && now - n->captured_ns > DM_TG_MAX_AGE_NS) g = dm_ta_current_set(n, button, n->captured_ns, set);
return g;
}
@implementation DmTouchOverlay {
UIImage *_circle, *_joy, *_map, *_menu, *_nativeAtlases[DM_TA_ATLASES], *_silAtlases[DM_TA_ATLASES]; // _sil:同帧位的银色剪影图集(gen_hud_v4.py) | _sil: silver silhouette atlas at the same frame positions (gen_hud_v4.py)
NSMutableDictionary<NSString *,UIImage *> *_glyphFrames;
dm_ta_glyph _nativeVisualGlyphs[5];
}
- (instancetype)initWithFrame:(CGRect)f {
if (!(self = [super initWithFrame:f])) return nil;
self.backgroundColor = UIColor.clearColor; self.opaque = NO; self.userInteractionEnabled = NO;
_circle=[UIImage imageNamed:@"dm_native_circle"]; _joy=[UIImage imageNamed:@"dm_touch_joy"];
_map=[UIImage imageNamed:@"dm_native_map"]; _menu=[UIImage imageNamed:@"dm_native_menu"];
_glyphFrames=[NSMutableDictionary dictionary];
for(int i=0;i<DM_TA_ATLASES;i++) _nativeAtlases[i]=[UIImage imageNamed:[NSString stringWithUTF8String:dm_ta_atlases[i].asset]];
for(int i=0;i<DM_TA_ATLASES;i++) _silAtlases[i]=[UIImage imageWithContentsOfFile:[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:
[@"hud_v4_ui/sil_" stringByAppendingString:[NSString stringWithUTF8String:dm_ta_atlases[i].asset]]]];
return self;
}
- (void)setNativeMapping:(dm_tg_snapshot)n {
_nativeMapping=n;
uint64_t buttons[5]={DM_BTN_A,DM_BTN_B,DM_BTN_X,DM_BTN_Y,DM_BTN_R};
uint64_t hostNow=now_ns(); BOOL dirty=NO;
for(int i=0;i<5;i++) {
dm_ta_glyph next=shown_glyph(&n,buttons[i],hostNow,self.controls?self.controls->skill_set:0),previous=_nativeVisualGlyphs[i];
if(next.status!=previous.status || next.raw_skill_id!=previous.raw_skill_id || next.atlas!=previous.atlas ||
next.normal_frame!=previous.normal_frame || next.slot!=previous.slot || next.effective_slot!=previous.effective_slot)dirty=YES;
_nativeVisualGlyphs[i]=next;
}
// 复用现有front CADisplayLink赋快照:只在图或新鲜性改变时重绘,不另开timer。
// Reuse the existing front CADisplayLink to assign the snapshot: redraw only when the image or freshness changes, no extra timer.
if(dirty)[self setNeedsDisplay];
}
- (UIImage *)frameImage:(UIImage *)atlas key:(NSString *)key rect:(CGRect)rect {
if(!atlas) return nil;
UIImage *image=_glyphFrames[key]; if(image) return image;
CGImageRef crop=CGImageCreateWithImageInRect(atlas.CGImage,rect); if(!crop) return nil;
image=[UIImage imageWithCGImage:crop]; CGImageRelease(crop); _glyphFrames[key]=image; return image;
}
- (UIImage *)skillImage:(dm_ta_glyph)g held:(BOOL)held {
if(g.status!=DM_TA_GLYPH)return nil;
int frame=held?g.pressed_frame:g.normal_frame;dm_ta_frame f;
if(!dm_ta_frame_at(g.atlas,frame,&f))return nil;
UIImage *sil=_silAtlases[g.atlas]; // 优先剪影(技能键是圆形,PC 定稿演示图只放剪影) | Prefer the silhouette (skill buttons are round; the finalized PC demo image uses silhouettes only)
return [self frameImage:sil?sil:_nativeAtlases[g.atlas] key:[NSString stringWithFormat:@"%@:%d:%d",sil?@"sil":@"skill",g.atlas,frame] rect:CGRectMake(f.x,f.y,f.width,f.height)];
}
- (void)setNavigationMode:(BOOL)n { _navigationMode = n; [self setNeedsDisplay]; }
// ---- 底部 UI v4:UIKit 部分(经验条、「Lv · %」、角标、难度数字与 1–8 选择条),素材与几何由 tools/gen_hud_v4.py 生成(App 内 hud_v4_ui/)----
// 几何单位 = 2868×1320 效果图像素:点 = (像素 − 1434) × 屏高/1320 + 屏宽/2(x),像素 × 屏高/1320(y)——与原生 HUD 同样按屏高缩放、以屏幕中线居中
// ---- Bottom UI v4: UIKit part (experience bar, "Lv · %", badges, difficulty number and the 1–8 selector strip); assets and geometry are generated by tools/gen_hud_v4.py (hud_v4_ui/ inside the App) ----
// Geometry unit = pixels of the 2868×1320 mockup: point = (pixel − 1434) × screen height/1320 + screen width/2 (x), pixel × screen height/1320 (y) -- scaled by screen height and centered on the screen's center line, same as the native HUD
static NSDictionary *v4ui(void) {
static NSDictionary *ui; static dispatch_once_t once;
dispatch_once(&once, ^{ NSString *p=[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"hud_v4_ui/ui.json"];
NSData *d=[NSData dataWithContentsOfFile:p]; ui=d?[NSJSONSerialization JSONObjectWithData:d options:0 error:nil]:nil;
if(!ui) NSLog(@"【红】底部 UI v4:App 内缺 hud_v4_ui/ui.json"); });
return ui;
}
static UIImage *v4img(NSString *name) {
static NSMutableDictionary *cache; if(!cache) cache=[NSMutableDictionary dictionary];
UIImage *im=cache[name]; if(im) return im;
im=[UIImage imageWithContentsOfFile:[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:[@"hud_v4_ui" stringByAppendingPathComponent:name]]];
if(im) cache[name]=im; return im;
}
// 逐字贴预渲染字形(字效与效果图同源);align:0 居中、1 右对齐;(x, baseline) 为效果图像素
// Blit pre-rendered glyphs character by character (text effect from the same source as the mockup); align: 0 centered, 1 right-aligned; (x, baseline) are in mockup pixels
static void v4text(NSString *str, NSDictionary *glyphs, CGFloat x, CGFloat baseline, int align, CGFloat W, CGFloat u) {
CGFloat adv=0; for(NSUInteger i=0;i<str.length;i++) adv+=[glyphs[[str substringWithRange:NSMakeRange(i,1)]][@"adv"] doubleValue];
CGFloat pen=align==1?x-adv:x-adv/2;
for(NSUInteger i=0;i<str.length;i++) {
NSDictionary *gm=glyphs[[str substringWithRange:NSMakeRange(i,1)]]; if(!gm) continue;
UIImage *im=[gm[@"file"] isKindOfClass:NSString.class]?v4img(gm[@"file"]):nil;
if(im) [im drawInRect:CGRectMake((pen+[gm[@"dx"] doubleValue]-1434)*u+W/2,(baseline+[gm[@"dy"] doubleValue])*u,im.size.width*u,im.size.height*u)];
pen+=[gm[@"adv"] doubleValue];
}
}
- (void)drawV4:(CGContextRef)c {
NSDictionary *ui=v4ui(); const dm_hud_info h=self.hud; const dm_tc_state *s=self.controls;
if(!ui || !dm_hud_bar_visible(&h,self.navigationMode && !self.dialogOnly,self.hudBlocked)) return; // 只在局内常态显示:面板 / 读取画面 / 过场(导航态)与死亡时让开,不挡游戏自己的画面(dm_hud.h) | Shown only in the normal in-run state: yields during panels / loading screen / cutscenes (navigation mode) and on death, so it does not cover the game's own picture (dm_hud.h)
CGFloat W=self.bounds.size.width, u=self.bounds.size.height/1320.0;
CGFloat (^X)(CGFloat)=^(CGFloat px){ return (px-1434)*u+W/2; };
// 底栏静态美术:效果图原生分辨率直接贴(不经游戏 1568×720 渲染再放大);腰带格内挖空透出游戏画的药水、球心挖空透出球液
// Bottom bar static art: blit the mockup directly at native resolution (not rendered by the game at 1568×720 and then upscaled); the belt cells are cut out to show the potions drawn by the game, and the orb centers are cut out to show the orb liquid
UIImage *full=v4img(@"base_full.png"); NSDictionary *bo=ui[@"base"];
if(full) [full drawInRect:CGRectMake(X([bo[@"x"] doubleValue]),[bo[@"y"] doubleValue]*u,full.size.width*u,full.size.height*u)];
// 第 5 格(现为六格布局;原第 6 格)= 原版十字按钮整格替换(含边框);按住第 1 帧。两态:有未分配点数时红色 + 外圈金光(原版「有点可加」提示),否则默认色(暗底金十字)
// Cell 5 (now a six-cell layout; formerly cell 6) = the original game's cross button replacing the whole cell (border included); frame 1 while held. Two states: with unspent points it is red + an outer gold glow (the original game's "points available" hint), otherwise the default color (gold cross on dark base)
{ NSArray *s6=ui[@"slots"][5]; BOOL held=s && (s->buttons & DM_BTN_PLUS), alert=h.points>0 || h.quest_unread;
UIImage *btn=v4img(alert?(held?@"lvl_1.png":@"lvl_0.png"):(held?@"lvl_d1.png":@"lvl_d0.png")); CGRect r=CGRectMake(X([s6[0] doubleValue]),[s6[1] doubleValue]*u,([s6[2] doubleValue]-[s6[0] doubleValue])*u,([s6[3] doubleValue]-[s6[1] doubleValue])*u);
if(h.points>0) { CGContextSaveGState(c); CGContextSetShadowWithColor(c,CGSizeZero,10*u,[UIColor colorWithRed:1 green:.82 blue:.35 alpha:.95].CGColor); [btn drawInRect:r]; CGContextRestoreGState(c); }
if(btn) [btn drawInRect:r]; }
// 经验条:底槽 + 描边 + 填充(本级‰)+ 20 等分刻度,同效果图
// Experience bar: base groove + outline + fill (‰ of the current level) + 20 equal tick marks, same as the mockup
NSDictionary *e=ui[@"exp"]; CGFloat x0=[e[@"x0"] doubleValue], x1=[e[@"x1"] doubleValue], y=[e[@"y"] doubleValue], eh=[e[@"h"] doubleValue];
UIColor *(^rgb)(NSArray *)=^(NSArray *a){ return [UIColor colorWithRed:[a[0] doubleValue]/255 green:[a[1] doubleValue]/255 blue:[a[2] doubleValue]/255 alpha:1]; };
CGContextSetFillColorWithColor(c,rgb(e[@"track"]).CGColor); CGContextFillRect(c,CGRectMake(X(x0),y*u,(x1-x0)*u,eh*u));
CGContextSetStrokeColorWithColor(c,rgb(e[@"edge"]).CGColor); CGContextSetLineWidth(c,u); CGContextStrokeRect(c,CGRectMake(X(x0)+u/2,y*u+u/2,(x1-x0-1)*u,(eh-1)*u));
CGContextSetFillColorWithColor(c,rgb(e[@"fill"]).CGColor); CGContextFillRect(c,CGRectMake(X(x0+1),(y+1)*u,(x1-x0-2)*u*h.exp_permille/1000.0,(eh-2)*u));
int ticks=[e[@"ticks"] intValue]; CGContextSetFillColorWithColor(c,rgb(e[@"track"]).CGColor);
for(int t=1;t<ticks;t++) CGContextFillRect(c,CGRectMake(X(x0+round((x1-x0)*t/(double)ticks)),(y+1)*u,u,(eh-2)*u));
NSDictionary *vt=ui[@"vital"]; // 生命 / 法力:球顶上方居中,效果图字形原生分辨率(原生数值文字已挪出屏幕) | Life / mana: centered above the top of the orb, mockup glyphs at native resolution (the native numeric text has been moved off screen)
v4text([NSString stringWithFormat:@(dm_ui("dmHudLife")),h.hp,h.hp_max],vt[@"glyphs"],[vt[@"left_x"] doubleValue],[vt[@"baseline"] doubleValue],0,W,u);
v4text([NSString stringWithFormat:@(dm_ui("dmHudMana")),h.mp,h.mp_max],vt[@"glyphs"],[vt[@"right_x"] doubleValue],[vt[@"baseline"] doubleValue],0,W,u);
NSDictionary *lv=ui[@"lv"];
v4text([NSString stringWithFormat:@"Lv %d · %d%%",h.level,h.exp_permille/10],lv[@"glyphs"],[lv[@"x"] doubleValue],[lv[@"baseline"] doubleValue],0,W,u);
// 角标:腰带四列件数(第 1–4 格),右下内角右对齐(回城不要书 / 卷轴、不显示次数,第 5 格是十字)
// Badges: item counts of the four belt columns (cells 1–4), right-aligned at the inner bottom-right corner (town portal needs no tome / scroll and shows no count; cell 5 is the cross)
NSArray *slots=ui[@"slots"], *in=ui[@"inner"]; NSDictionary *bd=ui[@"badge"];
int counts[5]={0,h.belt[0],h.belt[1],h.belt[2],h.belt[3]};
for(int i=1;i<=4;i++) { if(!counts[i]) continue;
v4text([NSString stringWithFormat:@"%d",counts[i]],bd[@"glyphs"],[slots[i][0] doubleValue]+[in[2] doubleValue]+[bd[@"dx"] doubleValue],[slots[i][1] doubleValue]+[in[3] doubleValue]+[bd[@"dy"] doubleValue],1,W,u); }
// 难度:第 0 格当前档数字;选择条展开时画 8 格(当前档不透明、其余略淡)
// Difficulty: cell 0 shows the current level number; when the selector strip is expanded, draw 8 cells (current level opaque, the rest slightly faded)
void (^digit)(int,CGFloat,CGFloat,CGFloat)=^(int n,CGFloat cx,CGFloat cy,CGFloat alpha){ UIImage *d=v4img([NSString stringWithFormat:@"diff_%d.png",n]);
if(d) [d drawInRect:CGRectMake(X(cx)-d.size.width*u/2,cy*u-d.size.height*u/2,d.size.width*u,d.size.height*u) blendMode:kCGBlendModeNormal alpha:alpha]; };
CGFloat icx=([in[0] doubleValue]+[in[2] doubleValue]+1)/2, icy=([in[1] doubleValue]+[in[3] doubleValue]+1)/2;
if(h.players>=1 && h.players<=8) digit(h.players,[slots[0][0] doubleValue]+icx,[slots[0][1] doubleValue]+icy,1);
if(s && s->diff_open) {
NSDictionary *pk=ui[@"pick"]; UIImage *tile=v4img(@"slot.png");
for(int i=0;i<8;i++) {
CGFloat cx=[pk[@"center_x"] doubleValue]+(i-3.5)*[pk[@"pitch"] doubleValue], cy=[pk[@"y"] doubleValue];
CGFloat tw=tile.size.width, th=tile.size.height, a=(i+1==h.players)?1:.82;
if(tile) [tile drawInRect:CGRectMake(X(cx-tw/2),(cy-th/2)*u,tw*u,th*u) blendMode:kCGBlendModeNormal alpha:a];
digit(i+1,cx,cy,a);
}
}
}
- (void)drawRect:(CGRect)rect {
(void)rect;
const dm_tc_state *s = self.controls; if (!s) return;
const dm_tc_layout *l = &s->layout;
CGFloat k = l->joy_radius / 60;
if (k <= 0) return;
CGContextRef c = UIGraphicsGetCurrentContext();
uint64_t hostNow=now_ns(); dm_tg_snapshot native=self.nativeMapping;
NSString *labels[DM_TC_COUNT] = {@"主技能",@"技能一",@"技能二",@"技能三",@"技能四",@"回城",@"药剂",@"药剂",@"药剂",@"药剂",@"功能",@"地图"};
if (self.navigationMode) { labels[0]=@"确认/交换"; labels[1]=@"返回"; labels[2]=@"操作"; labels[3]=@"绑定"; labels[4]=@"下一页"; } // 底栏十字位置的「关闭」已去:关闭入口只留外框右上角那一个(dm_tc_nav_mask) | The 「关闭」(Close) at the bottom bar cross position has been removed: the only close entry left is the one at the top-right corner of the outer frame (dm_tc_nav_mask)
for (int i=0;i<DM_TC_COUNT;i++) {
if (!(s->enabled_targets & (1u<<i))) continue;
if(!self.navigationMode && i>DM_TC_PORTAL && i<=DM_TC_MENU) continue; // 底部 UI v4:腰带 / 功能入口(LevelUpButton)由原生 HUD 画;宿主只保 hit-test。回城(技能弧上方圆钮)照技能钮画 | Bottom UI v4: belt / function entry (LevelUpButton) are drawn by the native HUD; the host only keeps hit-test. Town portal (round button above the skill arc) is drawn like a skill button
const dm_tc_target *t = &l->target[i]; CGRect b = CGRectMake(t->x-t->r,t->y-t->r,t->r*2,t->r*2);
BOOL held = t->button != 0 && (s->buttons & t->button) == t->button;
if(i==DM_TC_PORTAL) for(int f=0;f<DM_TC_MAX_TOUCH;f++) held|=s->finger[f].active && s->finger[f].target==DM_TC_PORTAL; // 回城钮不出按键(宿主施放回城技能),按住态看手指 | The town portal button emits no key (the host casts the town portal skill); the held state is read from the fingers
CGFloat opacity = held ? .6 : .28;
if(!self.navigationMode && i==DM_TC_MAP && s->map_cancel_active) {
CGContextSetFillColorWithColor(c,[UIColor colorWithRed:.55 green:.05 blue:.04 alpha:.36].CGColor); CGContextFillRect(c,b); labels[i]=@"取消";
}
BOOL skillKey=!self.navigationMode && (i<=DM_TC_SKILL4 || i==DM_TC_PORTAL); // 回城钮(圆形、和技能图标一样) | Town portal button (round, same as the skill icons)
if (skillKey) { // PC 定稿演示图同款:深色圆底 + 古铜圆环(外亮内暗两道) | Same as the finalized PC demo image: dark round base + bronze ring (two strokes, bright outside and dark inside)
CGFloat lw=MAX(1.5,t->r*0.075);
// 五个技能钮与回城钮平时淡一些(DM_SKILL_IDLE_ALPHA,少挡画面),按住时恢复原样给手感;角标、标签、充能用完的灰态不跟着变
// The five skill buttons and the town portal button are faded when idle (DM_SKILL_IDLE_ALPHA, to block less of the view) and return to normal while held for feedback; badges, labels and the grey out-of-charges state do not change
CGFloat fr=held?1:DM_SKILL_IDLE_ALPHA;
CGContextSetFillColorWithColor(c,[UIColor colorWithRed:.086 green:.067 blue:.047 alpha:held?.92:.80*fr].CGColor); CGContextFillEllipseInRect(c,b);
CGContextSetLineWidth(c,lw); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.60 green:.47 blue:.28 alpha:held?1:.9*fr].CGColor);
CGContextStrokeEllipseInRect(c,CGRectInset(b,lw/2,lw/2));
CGContextSetLineWidth(c,lw*.5); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.12 green:.09 blue:.05 alpha:.9*fr].CGColor);
CGContextStrokeEllipseInRect(c,CGRectInset(b,lw*1.3,lw*1.3));
} else if (_circle) [_circle drawInRect:b blendMode:kCGBlendModeNormal alpha:opacity];
else {
CGContextSetFillColorWithColor(c,[UIColor colorWithWhite:.02 alpha:.16].CGColor); CGContextFillEllipseInRect(c,b);
CGContextSetStrokeColorWithColor(c,bronze(.28).CGColor); CGContextSetLineWidth(c,k); CGContextStrokeEllipseInRect(c,b);
}
UIImage *icon=nil; BOOL showCaption=YES; int ssKind=0, ssCharges=0;
if(!self.navigationMode && i<=DM_TC_SKILL4) {
dm_ta_glyph g=shown_glyph(&native,t->button,hostNow,s->skill_set);
if(g.status!=DM_TA_EMPTY && g.status!=DM_TA_UNKNOWN) { int dm_swapskill_slot(int,int*); ssKind=dm_swapskill_slot(g.slot,&ssCharges); }
icon=[self skillImage:g held:held];
showCaption=g.status!=DM_TA_EMPTY && !icon;
} else if(!self.navigationMode && i==DM_TC_PORTAL) {
icon=[self skillImage:dm_ta_skill(359) held:held]; // 原版回城技能图(技能描述表 Town Portal:通用技能页第 18 格,219 / 220 / 411 同一张),不显示次数 | the original game's town portal skill image (skill description table Town Portal: cell 18 of the generic skill page, 219 / 220 / 411 share one image), count not shown
} else if(!self.navigationMode && (i==DM_TC_MENU || i==DM_TC_MAP)) {
icon=[self frameImage:i==DM_TC_MAP?_map:_menu key:[NSString stringWithFormat:@"fixed:%d:%d",i,held] rect:CGRectMake(held?36:0,0,36,36)];
}
if(!self.navigationMode && i==DM_TC_MAP && s->map_cancel_active) {icon=nil;showCaption=YES;}
if(skillKey && !icon && (!showCaption || i==DM_TC_MAIN)) { // 主钮取不到图标(如第二套里这一格没绑)也画十字、不写「攻击」:空格按下去不出普通攻击,画攻击图标或写字都会骗人 // 空技能位:圆底圆环里一个单色十字,不写 F 标签;点它进绑定技能(行为由输入层接) | when the main button cannot get an icon (e.g. this cell is not bound in the second set) it also draws the cross and does not say 「攻击」(Attack): pressing an empty cell does not produce a normal attack, so drawing the attack icon or the text would both be misleading // empty skill slot: a single-color cross inside the round base and ring, no F label; tapping it goes to skill binding (the behavior is wired by the input layer)
CGFloat a_=t->r*.30, w_=MAX(1.5,t->r*.085);
CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.60 green:.47 blue:.28 alpha:held?1:.9].CGColor); CGContextSetLineWidth(c,w_); CGContextSetLineCap(c,kCGLineCapButt);
CGContextMoveToPoint(c,t->x-a_,t->y); CGContextAddLineToPoint(c,t->x+a_,t->y); CGContextMoveToPoint(c,t->x,t->y-a_); CGContextAddLineToPoint(c,t->x,t->y+a_); CGContextStrokePath(c);
continue;
}
if(skillKey) { // 剪影居中略偏上,下方标签:主键「攻击」,其余 F1–F4(第二套 F5–F8);空槽只有圆底、圆环与标签 | silhouette centered and slightly high, label below: main button 「攻击」(Attack), the others F1–F4 (second set F5–F8); an empty slot has only the round base, the ring and the label
BOOL bare=icon!=nil; // 有图标的技能钮不写字(最大的钮是「主技能 / 交互」、可绑任意技能,钮上只画所绑技能的图标,不写「攻击」):图标放大并居中。取不到图标时主钮仍落回「攻击」字样 | skill buttons that have an icon carry no text (the largest button is "main skill / interact" and can be bound to any skill, so the button draws only the bound skill's icon and does not say 「攻击」(Attack)): the icon is enlarged and centered. When no icon can be obtained the main button still falls back to the 「攻击」(Attack) text
BOOL spent=(ssKind&2) && ssCharges<=0; // 充能用完:钮变灰(灰底上按亮度贴图标 = 去色),按下也不换武器(dm_actions.c) | charges used up: the button turns gray (the icon applied by luminance on a gray base = desaturated), and pressing does not swap weapons either (dm_actions.c)
if(icon) { CGFloat size=b.size.width*(bare?.64:.56); CGSize in_=icon.size; CGFloat fit=size/MAX(in_.width,in_.height);
CGRect ir=CGRectMake(t->x-in_.width*fit/2,t->y-(bare?0:t->r*.12)-in_.height*fit/2,in_.width*fit,in_.height*fit);
if(spent) { CGContextSetFillColorWithColor(c,[UIColor colorWithWhite:.30 alpha:1].CGColor); CGContextFillEllipseInRect(c,CGRectInset(b,t->r*.14,t->r*.14));
[icon drawInRect:ir blendMode:kCGBlendModeLuminosity alpha:.55];
CGContextSetFillColorWithColor(c,[UIColor colorWithWhite:0 alpha:.35].CGColor); CGContextFillEllipseInRect(c,b); }
else [icon drawInRect:ir blendMode:kCGBlendModeNormal alpha:held?1:.92*DM_SKILL_IDLE_ALPHA]; }
// 副手组技能角标:右上「Ⅱ」= 技能在另一组武器上,按下先换武器;右下剩余次数 = 充能技能,字用腰带药水件数那套(ui.json badge)
// Secondary weapon set skill badges: top right "Ⅱ" = the skill is on the other weapon set, pressing swaps weapons first; bottom right remaining count = charged skill, the text uses the same style as the belt potion count (ui.json badge)
if(ssKind&1) { CGFloat br=t->r*.30, bx=t->x+t->r*.74, by=t->y-t->r*.74; CGRect bb=CGRectMake(bx-br,by-br,br*2,br*2), lw2=CGRectInset(bb,MAX(1,br*.08),MAX(1,br*.08));
CGContextSetFillColorWithColor(c,[UIColor colorWithRed:.11 green:.094 blue:.078 alpha:.95].CGColor); CGContextFillEllipseInRect(c,bb);
CGContextSetLineWidth(c,MAX(1,br*.14)); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.63 green:.50 blue:.27 alpha:1].CGColor); CGContextStrokeEllipseInRect(c,lw2);
CGFloat ts=br*1.15; caption(@"Ⅱ",CGRectMake(bx-br,by-ts*.62,br*2,ts*1.4),ts,1); }
if(ssKind&2) { NSDictionary *ui=v4ui(); CGFloat W=self.bounds.size.width, u=self.bounds.size.height/1320.0; NSDictionary *bd=ui[@"badge"];
if(bd && u>0) v4text([NSString stringWithFormat:@"%d",ssCharges<0?0:ssCharges],bd[@"glyphs"],(t->x+t->r*.66-W/2)/u+1434,(t->y+t->r*.42)/u,1,W,u); }
if(bare) continue;
NSString *ln=i==DM_TC_MAIN?@"lbl_main.png":[NSString stringWithFormat:@"lbl_f%d.png",i-DM_TC_SKILL1+1+(s->skill_set?4:0)];
UIImage *lbl=[UIImage imageWithContentsOfFile:[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:[@"hud_v4_ui" stringByAppendingPathComponent:ln]]];
if(lbl) { CGFloat lh=t->r*(i==DM_TC_MAIN?.30:.36), lw_=lbl.size.width*lh/lbl.size.height;
[lbl drawInRect:CGRectMake(t->x-lw_/2,t->y+t->r*.50-lh/2,lw_,lh)]; }
continue;
}
if(icon) {
CGFloat size=b.size.width*(i==DM_TC_MAIN?.55:.62);
CGSize intrinsic=icon.size;CGFloat fit=size/MAX(intrinsic.width,intrinsic.height);
CGRect glyph=CGRectMake(t->x-intrinsic.width*fit/2,t->y-intrinsic.height*fit/2,intrinsic.width*fit,intrinsic.height*fit);
[icon drawInRect:glyph blendMode:kCGBlendModeNormal alpha:held?1:.82];showCaption=NO;
}
CGFloat textSize = (i==DM_TC_MAIN ? 13 : 10)*k;
if(showCaption) caption(labels[i],CGRectMake(b.origin.x,t->y-textSize*.6,b.size.width,textSize*1.6),textSize,held ? 1 : .84);
if (i>=DM_TC_BELT1 && i<=DM_TC_BELT4) caption([NSString stringWithFormat:@"%d",i-DM_TC_BELT1+1],CGRectMake(t->x-10*k,t->y+8*k,20*k,12*k),8*k,.65);
}
if (!self.navigationMode && l->swap.r > 0) { // 技能组切换键:显示当前第几套 | skill set switch button: shows which set is current
CGRect b = CGRectMake(l->swap.x-l->swap.r,l->swap.y-l->swap.r,l->swap.r*2,l->swap.r*2);
// 与技能键同一套:深色圆底 + 古铜圆环(外亮内暗两道);上面「Ⅰ / Ⅱ」、下面小字「换组」
// Same scheme as the skill buttons: dark round base + bronze ring (two strokes, bright outside and dark inside); "Ⅰ / Ⅱ" on top, small text 「换组」(switch set) below
CGFloat lw=MAX(1.5,l->swap.r*0.075);
BOOL sheld=NO; for(int f=0;f<DM_TC_MAX_TOUCH;f++) sheld|=s->finger[f].active && hypot(s->finger[f].x-l->swap.x,s->finger[f].y-l->swap.y)<=l->swap.r; // 手指按在这颗上 | a finger is on this button
CGFloat fs=sheld?1:DM_SKILL_IDLE_ALPHA; // 同技能钮:平时淡、按住变实;「Ⅰ / Ⅱ」是状态指示,不淡 | same as skill buttons: faded normally, solid while held; "Ⅰ / Ⅱ" is a state indicator and is not faded
CGContextSetFillColorWithColor(c,[UIColor colorWithRed:.086 green:.067 blue:.047 alpha:sheld?.92:.80*fs].CGColor); CGContextFillEllipseInRect(c,b);
CGContextSetLineWidth(c,lw); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.60 green:.47 blue:.28 alpha:sheld?1:.9*fs].CGColor); CGContextStrokeEllipseInRect(c,CGRectInset(b,lw/2,lw/2));
CGContextSetLineWidth(c,lw*.5); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.12 green:.09 blue:.05 alpha:.9*fs].CGColor); CGContextStrokeEllipseInRect(c,CGRectInset(b,lw*1.3,lw*1.3));
CGFloat ts = 14*k; caption(s->skill_set ? @"Ⅱ" : @"Ⅰ",CGRectMake(b.origin.x,l->swap.y-ts*.8,b.size.width,ts*1.6),ts,1); // 只留 Ⅰ / Ⅱ、居中(「换组」小字去掉) | keep only Ⅰ / Ⅱ, centered (the small 「换组」(switch set) text is removed)
}
if (self.hud.valid && self.hud.dead) return; // 死亡画面:右侧圆钮已由掩码收起,左侧摇杆圈也不画(截图:死后摇杆圈还在) | death screen: the round buttons on the right are already hidden by the mask, and the stick ring on the left is not drawn either (screenshot: the stick ring was still there after death)
if (s->navigation_mode) return; // 面板开着(与起摇杆同一个判定:dm_touch_controls.c 起摇杆的条件带 !navigation_mode):摇杆起不来,静止淡影只会压在面板上(iPad 上双面板占满整宽)——不画 | a panel is open (the same check as starting the stick: the stick-start condition in dm_touch_controls.c includes !navigation_mode): the stick cannot start, and the idle faint shadow would only sit on top of the panel (on iPad the dual panels fill the whole width) - not drawn
BOOL moving = s->joy_slot >= 0;
CGPoint o = moving ? CGPointMake(s->joy_origin_x,s->joy_origin_y) : CGPointMake(l->joy_x,l->joy_y);
CGFloat radius=l->joy_radius;
CGRect base=CGRectMake(o.x-radius,o.y-radius,radius*2,radius*2);
CGContextSetLineWidth(c,k); CGContextSetStrokeColorWithColor(c,bronze(moving ?.32:.12).CGColor); CGContextStrokeEllipseInRect(c,base);
CGFloat dx=s->lx/32767.0*radius,dy=-s->ly/32767.0*radius;
CGRect thumb=CGRectMake(o.x+dx-23*k,o.y+dy-23*k,46*k,46*k);
if (_joy) [_joy drawInRect:thumb blendMode:kCGBlendModeNormal alpha:moving ?.8:.18];
if (moving && (s->lx || s->ly)) {
CGFloat angle=atan2(dy,dx);
CGContextSetStrokeColorWithColor(c,bronze(.7).CGColor); CGContextSetLineWidth(c,2*k);
CGContextAddArc(c,o.x,o.y,radius+3*k,angle-M_PI/6,angle+M_PI/6,0); CGContextStrokePath(c);
}
[self drawV4:c];
}
- (NSDictionary *)controlMetadata {
const dm_tc_state *s=self.controls; if (!s) return @{};
NSMutableArray *a=[NSMutableArray array];
dm_tg_snapshot visualNative=self.nativeMapping; uint64_t hostNow=now_ns();
NSString *names[DM_TC_COUNT]={@"main",@"skill1",@"skill2",@"skill3",@"skill4",@"portal",@"belt1",@"belt2",@"belt3",@"belt4",@"menu",@"map"};
for(int i=0;i<DM_TC_COUNT;i++) {
const dm_tc_target *t=&s->layout.target[i];
NSMutableDictionary *entry=[@{@"id":names[i],@"rect_pt":@[@(t->x-t->r),@(t->y-t->r),@(t->r*2),@(t->r*2)],@"npad_button":@(t->button),@"visible":@((s->enabled_targets&(1u<<i))!=0)} mutableCopy];
if(!self.navigationMode && i>=DM_TC_PORTAL && i<=DM_TC_MENU) {
entry[@"visual_owner"]=i==DM_TC_PORTAL?@"overlay_portal_skill":(i==DM_TC_MENU?@"native_levelup_button":@"native_game_belt"); entry[@"host_drawn"]=@NO;
entry[@"touch_enabled"]=@((s->enabled_targets&(1u<<i))!=0);
}
if(i<=DM_TC_SKILL4) {
dm_ta_glyph g=shown_glyph(&visualNative,t->button,hostNow,s->skill_set);
BOOL held=t->button && (s->buttons&t->button)==t->button;
BOOL drawn=!self.navigationMode && [self skillImage:g held:held]!=nil;
NSString *status=self.navigationMode?@"navigation_label":(g.status==DM_TA_EMPTY?@"empty_slot":(drawn?@"current_skill":@"empty_unknown"));
entry[@"currentSkill"]=@{@"schema":@"dm-current-skill-visual-1",@"status":status,@"reason":[NSString stringWithUTF8String:g.reason],@"raw_skill_id":@(g.raw_skill_id),@"slot":@(g.slot),@"effective_slot":@(g.effective_slot),@"atlas":@(g.atlas),@"normal_frame":@(g.normal_frame),@"pressed_frame":@(g.pressed_frame),@"display_frame":@(held?g.pressed_frame:g.normal_frame),@"glyph_drawn":@(drawn),@"icon_diameter_ratio":@(i==DM_TC_MAIN?.55:.62)};
}
[a addObject:entry];
}
[a addObject:@{@"id":@"swap",@"rect_pt":@[@(s->layout.swap.x-s->layout.swap.r),@(s->layout.swap.y-s->layout.swap.r),@(s->layout.swap.r*2),@(s->layout.swap.r*2)],@"skill_set":@(s->skill_set),@"visible":@(!self.navigationMode)}];
BOOL moving=s->joy_slot>=0; CGFloat k=s->layout.joy_radius/60;
CGFloat jx=moving?s->joy_origin_x:s->layout.joy_x,jy=moving?s->joy_origin_y:s->layout.joy_y,r=s->layout.joy_radius;
CGFloat tx=jx+s->lx/32767.0*r,ty=jy-s->ly/32767.0*r;
NSDictionary *joystick=@{@"id":@"joystick",@"active":@(moving),@"base_rect_pt":@[@(jx-r),@(jy-r),@(2*r),@(2*r)],@"thumb_rect_pt":@[@(tx-23*k),@(ty-23*k),@(46*k),@(46*k)]};
dm_tg_snapshot native=self.nativeMapping;
NSMutableArray *mapping=[NSMutableArray array],*ids=[NSMutableArray array];
for(int i=0;i<DM_TG_FACETS;i++) [mapping addObject:@{@"logical":@(native.mapping[i].logical),@"normal":@(native.mapping[i].normal),@"alt":@(native.mapping[i].alt)}];
for(int i=0;i<DM_TG_SLOTS;i++) [ids addObject:@(native.raw_skill_id[i])];
NSDictionary *nativeInfo=@{@"schema":@"dm-native-binding-4",@"source_id":@(native.source),@"source":native.source==DM_TG_SOURCE_NATIVE_GETTER?@"native_getter":@"none",
@"supported":@(native.supported),@"valid":@(native.valid),@"ready":@(native.ready),@"secondary_group":@(native.secondary_group),@"group_seen":@(native.group_seen),@"group_started_ns":@(native.group_started_ns),@"binding_identity":@(native.binding_identity),@"scene_epoch":@(native.scene_epoch),@"world_epoch":@(native.world_epoch),@"identity_kind":native.identity_scope==DM_TG_IDENTITY_NATIVE?@"fixed_native_hud_updater_cohort":(native.identity_scope==DM_TG_IDENTITY_SYNTHETIC?@"synthetic_stub":@"unconfirmed"),@"caller_identity":@(native.caller_identity),@"hud_identity":@(native.hud_identity),@"identity_scope":@(native.identity_scope),@"captured_ns":@(native.captured_ns),@"selected_bank":@(native.selected_bank),@"getter_input_slot":@(native.getter_input_slot),@"valid_scope":@"table_parse_only",@"observed_index":@(native.observed_index),@"mapping":mapping,@"raw_skill_ids":ids,
@"portal":@{@"valid":@(native.portal.valid),@"slot":@(native.portal.slot),@"raw_skill_id":@(native.portal.raw_skill_id),@"buttons":@(native.portal.buttons)}};
// capture版本与布局版本分开;期望state由测试输入提供,不用visible反推。
// The capture version and the layout version are separate; the expected state is supplied by the test input, not inferred back from visible.
return @{@"capture_schema":@"dm-touch-capture-2",@"profile_id":@"native_art_v1",@"binding_profile_id":@"touch_native_binding_v5",@"input_schema":@"dm-touch-input-5",@"native_mapping":nativeInfo,
@"layout_sha256":[NSString stringWithUTF8String:dm_ta_geometry_sha],@"geometry_sha256":[NSString stringWithUTF8String:dm_ta_geometry_sha],@"binding_protocol_sha256":[NSString stringWithUTF8String:dm_ta_binding_sha],
@"art_provenance":@{@"schema":@"dm-native-art-provenance-1",@"manifest":@"native_art_manifest.json",@"manifest_sha256":[NSString stringWithUTF8String:dm_ta_manifest_sha],@"shell_idle_alpha":@.28,@"shell_held_alpha":@.6,@"fixed_functions":@[@"portal",@"map",@"menu"],@"unsupported_state":@"no ammo/cooldown/mana tint"},
@"source":TARGET_OS_SIMULATOR?@"uikit_simulator_overlay":@"uikit_device_overlay",
@"right_aim":@{@"rx":@(s->rx),@"ry":@(s->ry),@"owner_slot":@(s->aim_slot),@"map_cancel_active":@(s->map_cancel_active),@"navigation_suppressed":@(s->navigation_mode),@"mapping":@"UIKit dx/r, -dy/r; independent clamped SDK axes"},
@"state":self.navigationMode?@"navigation":@"game",@"joystick":joystick,@"coordinate_space":@"UIKit points",@"view_size_pt":@[@(s->layout.width),@(s->layout.height)],@"navigation":@(self.navigationMode),@"controls":a,@"portal_request":@{@"gesture_epoch":@(s->gesture_epoch),@"binding_identity":@(s->portal_binding_identity),@"scene_epoch":@(s->portal_scene_epoch),@"phase":@(s->portal_phase),@"pending":@(s->portal_pending)},@"portal_binding_verified":@NO,@"game_hud_relayout_verified":@NO};
}
@end
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

File diff suppressed because one or more lines are too long
+17
View File
@@ -0,0 +1,17 @@
// 直装包的游戏资源下载(实现与下载站约定见 asset_dl.m)
// Game asset download for the direct-install build (implementation and the download-site conventions: see asset_dl.m)
#import <Foundation/Foundation.h>
@interface DmAssetDL : NSObject
+ (instancetype)shared;
+ (instancetype)astcPack; // 老机型补充包:下到 Documents/Legacy Device Pack/data(地址见 asset_dl.m 文件头) | Legacy Device Pack: downloaded to Documents/Legacy Device Pack/data (address: see the asset_dl.m file header)
// 定下载地址、取清单、盘点本地已有的。回调在主线程:err 非空 = 走不了直接下载(原因);remain / total = 还要下 / 总字节数;cellular = 当前是按流量计费的网络
// Determine the download address, fetch the manifest, take stock of what is already local. Callback on the main thread: err non-nil = direct download not possible (reason); remain / total = bytes still to download / total bytes; cellular = the current network is metered
- (void)prepare:(void (^)(NSString *err, int64_t remain, int64_t total, BOOL cellular))done;
// 上一次 prepare 判出手机空间不够时:还差多少字节(含 200 MB 余量)与手机可用字节;空间够 = 0
// When the last prepare found the phone short of space: how many bytes are still missing (including a 200 MB margin) and the phone's available bytes; enough space = 0
@property (atomic) int64_t shortBytes, freeBytes;
// 开始(或接着)下载。progress(已到手字节数, 总字节数, 附注或 nil) 与 done(失败原因或 nil) 都在主线程
// Start (or resume) downloading. progress(bytes received, total bytes, note or nil) and done(failure reason or nil) are both on the main thread
- (void)run:(void (^)(int64_t done, int64_t total, NSString *note))progress done:(void (^)(NSString *err))done;
@end
void dm_asset_dl_bg_events(NSString *ident, void (^done)(void)); // App 委托的 handleEventsForBackgroundURLSession 转来(按会话标识分给资源 / 补充包) | Forwarded from the App delegate's handleEventsForBackgroundURLSession (dispatched to assets / Legacy Device Pack by session identifier)
+262
View File
@@ -0,0 +1,262 @@
// 直装包的游戏资源下载(直装包没有苹果托管资源包,也用不了开发者账号的 iCloud)。
// 从我们自己的下载站把资源文件逐个拉到 Documents/D2R Mobile Resources/data,全部到齐后由 main.m 的 romfs_locate 照常校验、就地进游戏。
// 下载站目录:<根>/manifest.json({"files":[{"name","size","sha256"}…]},tools/asset_manifest.py 生成)+ <根>/data/<文件名>。
// 根地址怎么定(隧道换域名时不用重出包):环境变量 DM_ASSET_BASE(测试)→ 包内 dm/asset_pointers.txt 里的每个「地址文件」网址
// (取回的正文第一行就是根地址)→ 上次成功用过的根地址 → 包内 dm/asset_base.txt(出包时写进去的缺省根地址)。逐个试,谁的清单取得到用谁。
// 传输:后台会话(URLSession background),一次一个任务,每个任务取一个文件的一段(≤16 MB,Range),取完追加到 <文件名>.part;
// .part 的长度就是这个文件已到手的字节数——杀进程重开 / 断网重连都从这里接着取,不重头。整个文件到齐后核字节数与 SHA-256,
// 对了才改成正式文件名;不对就删掉重下(同一文件最多 3 次)。网络出错自动重试(间隔 2 → 30 秒),不用玩家点。
// 已经在目录里且字节数对的文件不重下(玩家用「文件」拷进来的那些)。
// 老机型补充包(显卡不支持 BC 的机型)走同一套:DmAssetDL.astcPack 下到 Documents/Legacy Device Pack/data,根地址只认
// 环境变量 DM_ASTC_PACK_BASE(测试)→ 上次用过的 → 包内 dm/astc_pack_base.txt(出包时写进去;空 = 没配自动下载,只能玩家用「文件」拷),后台会话标识另起一个。
// Game asset download for the direct-install build (a direct-install build has no Apple-hosted asset packs and cannot use the developer account's iCloud).
// Pull the asset files one by one from our own download site into Documents/D2R Mobile Resources/data; once all have arrived, romfs_locate in main.m verifies them as usual and enters the game in place.
// Download site layout: <root>/manifest.json ({"files":[{"name","size","sha256"}…]}, generated by tools/asset_manifest.py) + <root>/data/<file name>.
// How the root address is determined (no need to rebuild the package when the tunnel changes domain): environment variable DM_ASSET_BASE (test) → each "address file" URL in the bundled dm/asset_pointers.txt
// (the first line of the fetched body is the root address) → the last root address that worked → the bundled dm/asset_base.txt (default root address written at packaging time). Try them one by one; use whichever one's manifest can be fetched.
// Transfer: background session (URLSession background), one task at a time, each task fetches one range of one file (≤16 MB, Range) and appends it to <file name>.part when done;
// the length of .part is the number of bytes of this file already received -- killing and relaunching the process / reconnecting after a network drop both resume from here, not from the start. Once the whole file has arrived, verify the byte count and SHA-256,
// rename to the final file name only if they match; if not, delete and re-download (at most 3 times per file). Network errors retry automatically (interval 2 → 30 s), no player tap needed.
// Files already in the directory with the right byte count are not re-downloaded (those the player copied in with the Files app).
// The Legacy Device Pack (models whose GPU does not support BC) uses the same mechanism: DmAssetDL.astcPack downloads to Documents/Legacy Device Pack/data; the root address only accepts
// environment variable DM_ASTC_PACK_BASE (test) → the last one used → the bundled dm/astc_pack_base.txt (written at packaging time; empty = auto-download not configured, the player can only copy it in with the Files app); it gets a separate background session identifier.
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <Network/Network.h>
#import "asset_dl.h"
#include "../../host/dm_i18n.h"
void plog(const char *fmt, ...);
#define DL_CHUNK (16ll << 20)
static NSString *dm_dl_sid(NSString *suffix) { return [NSBundle.mainBundle.bundleIdentifier stringByAppendingString:suffix]; } // 后台会话标识 = 包名 + 后缀 | Background session identifier = bundle ID + suffix
@interface DmAssetDL () <NSURLSessionDownloadDelegate>
@property (strong) NSURLSession *session; @property (strong) dispatch_queue_t q;
@property (copy) NSString *base, *dir; @property (strong) NSArray<NSDictionary *> *files;
@property (assign) int64_t total, settled; // 清单总字节数;已落盘的字节数(正式文件 + 各 .part) | Total bytes in the manifest; bytes already on disk (final files + all .part)
@property (assign) int running, retry, cellular; @property (strong) NSMutableDictionary<NSString *, NSNumber *> *redo;
@property (copy) void (^onProgress)(int64_t, int64_t, NSString *); @property (copy) void (^onDone)(NSString *);
@property (copy) NSString *sid, *envBase, *ptrFile, *baseFile, *defKey; // 后台会话标识、测试用环境变量、包内地址文件 / 缺省根地址文件、记住上次根地址的键 | Background session identifier, test environment variable, bundled address file / default root address file, key that remembers the last root address
@property (copy) void (^bgDone)(void); // 系统为后台会话唤醒 App 时给的收尾回调 | Completion callback given by the system when it wakes the App for the background session
// 卡住自救:盯当前这一片的吞吐,明显掉速就取消它、换一个全新的进程内会话(= 全新连接)从 .part 的长度接着取。
// 起因:系统的后台会话会一直复用同一条连接,那条连接塌了(丢包 / 被限速)之后每一片都慢,结束 App 重开也接回同一条。
// Stall self-healing: watch the throughput of the current chunk; on a clear slowdown, cancel it and continue from the length of the .part file on a brand-new in-process session (= a brand-new connection).
// Why: the system background session keeps reusing the same connection; once that connection degrades (packet loss / throttling) every chunk is slow, and quitting and reopening the app re-attaches to the same one.
@property (strong) NSURLSession *fg; // 自救用的进程内会话;每次自救新建一个 | In-process session used for self-healing; a new one is created each time
@property (assign) int useFg, heal, skipWin; // 现在是否走进程内会话;本轮已自救几次;自救后先放过几个窗口再判(给新连接起速的时间,也防来回折腾) | Whether the in-process session is in use now; how many times this round has self-healed; how many windows to skip after a self-heal before judging again (gives the new connection time to ramp up and avoids flapping)
@property (assign) int64_t curBytes, winBytes; // 当前这一片已收字节;本窗口起点时的已收字节 | Bytes received for the current chunk; bytes received at the start of this window
@property (assign) CFAbsoluteTime winT; @property (assign) double best; // 本窗口起点时刻;本轮见过的最高窗口吞吐(字节 / 秒) | Start time of this window; best window throughput seen this round (bytes / second)
@property (strong) dispatch_source_t watch;
- (NSURLSession *)bg;
@end
@implementation DmAssetDL
+ (instancetype)shared { static DmAssetDL *s; static dispatch_once_t once; dispatch_once(&once, ^{ s = [[DmAssetDL alloc] initDir:@"D2R Mobile Resources/data" sid:dm_dl_sid(@".assets") env:@"DM_ASSET_BASE" ptr:@"asset_pointers.txt" base:@"asset_base.txt" key:@"dm_asset_base"]; }); return s; }
+ (instancetype)astcPack { static DmAssetDL *s; static dispatch_once_t once; dispatch_once(&once, ^{ s = [[DmAssetDL alloc] initDir:@"Legacy Device Pack/data" sid:dm_dl_sid(@".astcpack") env:@"DM_ASTC_PACK_BASE" ptr:nil base:@"astc_pack_base.txt" key:@"dm_astc_pack_base"]; }); return s; }
- (instancetype)initDir:(NSString *)dir sid:(NSString *)sid env:(NSString *)env ptr:(NSString *)ptr base:(NSString *)base key:(NSString *)key {
if ((self = [super init])) {
self.q = dispatch_queue_create("dm.assetdl", DISPATCH_QUEUE_SERIAL); self.redo = [NSMutableDictionary new];
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
{ const char *td = getenv("DM_ROMFS_TEST_DOC"); if (td && *td && !strchr(td, '/')) doc = [doc stringByAppendingPathComponent:@(td)]; } // 只测试用:与 main.m romfs_locate 同一个开关,下到被当成「D2R Mobile」的那个文件夹里 | test only: the same switch as romfs_locate in main.m; downloads into the folder that is treated as "D2R Mobile"
__weak DmAssetDL *w = self; // 切到后台:进程内会话在后台不保活,把在途这一片交还给系统的后台会话接着取 | Going to the background: an in-process session is not kept alive there, so hand the chunk in flight back to the system background session to carry on
[NSNotificationCenter.defaultCenter addObserverForName:@"UIApplicationDidEnterBackgroundNotification" object:nil queue:nil usingBlock:^(NSNotification *n) { DmAssetDL *d = w; if (d) dispatch_async(d.q, ^{
if (d.running && d.useFg) { plog("assets: 进后台,在途这一片交还给系统的后台会话"); d.useFg = 0; [d.fg invalidateAndCancel]; d.fg = nil; [d pump]; } }); }];
self.dir = [doc stringByAppendingPathComponent:dir]; self.sid = sid; self.envBase = env; self.ptrFile = ptr; self.baseFile = base; self.defKey = key;
}
return self;
}
void dm_asset_dl_bg_events(NSString *ident, void (^done)(void)) { DmAssetDL *d = [ident isEqualToString:dm_dl_sid(@".astcpack")] ? DmAssetDL.astcPack : DmAssetDL.shared; d.bgDone = done; dispatch_async(d.q, ^{ (void)[d bg]; }); } // 接回同标识的后台会话,事件才送得到 | Reattach the background session with the same identifier, otherwise the events cannot be delivered
- (NSURLSession *)bg { // 后台会话:同一个标识全进程只建一次;杀进程后重开用同一标识接回系统手里没做完的任务 | Background session: one identifier is created only once per process; after the process is killed and relaunched, the same identifier reattaches the unfinished tasks held by the system
if (!self.session) {
NSURLSessionConfiguration *c = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:self.sid];
c.sessionSendsLaunchEvents = YES; c.discretionary = NO; c.allowsCellularAccess = YES; c.HTTPMaximumConnectionsPerHost = 2;
c.timeoutIntervalForRequest = 60; c.timeoutIntervalForResource = 7 * 24 * 3600;
NSOperationQueue *oq = [NSOperationQueue new]; oq.underlyingQueue = self.q; oq.maxConcurrentOperationCount = 1;
self.session = [NSURLSession sessionWithConfiguration:c delegate:self delegateQueue:oq];
}
return self.session;
}
- (NSURLSession *)fgNew { // 新建一个进程内会话:不沿用任何已有连接 | Create a new in-process session: reuses no existing connection
[self.fg invalidateAndCancel];
NSURLSessionConfiguration *c = NSURLSessionConfiguration.ephemeralSessionConfiguration; c.allowsCellularAccess = YES; c.HTTPMaximumConnectionsPerHost = 2;
c.timeoutIntervalForRequest = 30; c.timeoutIntervalForResource = 3600; c.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSOperationQueue *oq = [NSOperationQueue new]; oq.underlyingQueue = self.q; oq.maxConcurrentOperationCount = 1;
self.fg = [NSURLSession sessionWithConfiguration:c delegate:self delegateQueue:oq]; return self.fg;
}
// 每 5 秒看一次当前这一片的吞吐(只在 self.q 上跑)。判掉速:一个窗口(缺省 20 秒)的平均吞吐低于 24 KB/s,
// 或低于本轮见过的最高窗口吞吐的四分之一且低于 512 KB/s。测试开关:DM_ASSET_STALL_MIN=<字节/秒>(低于它就算掉速)、DM_ASSET_STALL_WIN=<秒>
// Every 5 seconds, look at the throughput of the current chunk (runs only on self.q). Slowdown rule: the average throughput over one window (20 seconds by default) is below 24 KB/s,
// or below a quarter of the best window throughput seen this round and below 512 KB/s. Test switches: DM_ASSET_STALL_MIN=<bytes/second> (anything below counts as a slowdown), DM_ASSET_STALL_WIN=<seconds>
- (void)watchTick {
if (!self.running) return;
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); const char *ew = getenv("DM_ASSET_STALL_WIN"), *em = getenv("DM_ASSET_STALL_MIN"); double win = ew ? atof(ew) : 20;
if (!self.winT) { self.winT = now; self.winBytes = self.curBytes; return; }
if (now - self.winT < win) return;
double rate = MAX(0, self.curBytes - self.winBytes) / (now - self.winT); self.winT = now; self.winBytes = self.curBytes;
if (self.skipWin > 0) { self.skipWin--; if (rate > self.best) self.best = rate; return; }
BOOL slow = em ? rate < atof(em) : (rate < 24 * 1024 || (rate * 4 < self.best && rate < 512 * 1024));
if (rate > self.best) self.best = rate;
if (!slow) return;
self.heal++; self.skipWin = MIN(self.heal, 6); self.useFg = 1; self.winT = 0; self.curBytes = 0;
plog("assets: 这一片掉速(%.0f KB/s,本轮最高 %.0f KB/s):取消、换新连接从已下的地方接着取(第 %d 次)", rate / 1024, self.best / 1024, self.heal);
(void)[self fgNew];
[[self bg] getTasksWithCompletionHandler:^(NSArray *d0, NSArray *u0, NSArray<NSURLSessionDownloadTask *> *tasks) { for (NSURLSessionTask *t in tasks) if (t.state != NSURLSessionTaskStateCompleted) [t cancel];
[self report:[self scan] note:[NSString stringWithFormat:@(dm_ui("dmDlReconnect")), self.heal]]; [self pump]; }];
}
static NSData *dl_get(NSString *url, NSTimeInterval timeout) { // 小文件(地址文件、清单)同步取,不走缓存 | Small files (address file, manifest) are fetched synchronously, bypassing the cache
NSURL *u = [NSURL URLWithString:url]; if (!u) return nil;
NSURLSessionConfiguration *c = NSURLSessionConfiguration.ephemeralSessionConfiguration; c.timeoutIntervalForRequest = timeout; c.timeoutIntervalForResource = timeout * 2;
c.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSURLSession *s = [NSURLSession sessionWithConfiguration:c]; dispatch_semaphore_t sem = dispatch_semaphore_create(0); __block NSData *out = nil;
[[s dataTaskWithURL:u completionHandler:^(NSData *d, NSURLResponse *r, NSError *e) {
if (!e && [(NSHTTPURLResponse *)r statusCode] == 200) out = d; else plog("assets: 取 %s 失败:%s", url.UTF8String, e ? e.localizedDescription.UTF8String : [NSString stringWithFormat:@"HTTP %ld", (long)[(NSHTTPURLResponse *)r statusCode]].UTF8String);
dispatch_semaphore_signal(sem); }] resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); [s finishTasksAndInvalidate]; return out;
}
static NSString *dl_trim(NSString *s) { s = [s stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; while ([s hasSuffix:@"/"]) s = [s substringToIndex:s.length - 1]; return s; }
static NSArray<NSString *> *dl_lines(NSString *path) { // 包内文本:一行一项,# 开头是注释 | Bundled text: one item per line; lines starting with # are comments
NSMutableArray *a = [NSMutableArray new]; NSString *t = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
for (NSString *l in [t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { NSString *v = dl_trim(l); if (v.length && ![v hasPrefix:@"#"]) [a addObject:v]; }
return a;
}
// 定根地址并取清单。成功返回 nil,失败返回原因
// Determine the root address and fetch the manifest. Returns nil on success, the reason on failure
- (NSString *)resolve {
NSString *res = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"dm"]; NSMutableArray<NSString *> *cand = [NSMutableArray new];
if (getenv("DM_TEST_NO_DL_BASE")) return @(dm_ui("dmDlNoBase")); // 只测试用:同 main.m res_dl_configured | Test only: same as res_dl_configured in main.m
const char *e = getenv(self.envBase.UTF8String); if (e && *e) [cand addObject:dl_trim(@(e))];
else {
for (NSString *p in self.ptrFile ? dl_lines([res stringByAppendingPathComponent:self.ptrFile]) : @[]) {
NSData *d = dl_get(p, 8); NSString *t = d ? [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding] : nil;
NSString *first = dl_trim([t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet].firstObject ?: @"");
if ([first hasPrefix:@"https://"]) { plog("assets: 地址文件 %s → %s", p.UTF8String, first.UTF8String); [cand addObject:first]; }
}
NSString *last = [NSUserDefaults.standardUserDefaults stringForKey:self.defKey]; if (last.length) [cand addObject:last];
[cand addObjectsFromArray:dl_lines([res stringByAppendingPathComponent:self.baseFile])];
}
if (!cand.count) return @(dm_ui("dmDlNoBase"));
for (NSString *b in cand) {
NSData *d = dl_get([b stringByAppendingString:@"/manifest.json"], 15); if (!d) continue;
NSDictionary *j = [NSJSONSerialization JSONObjectWithData:d options:0 error:nil]; NSArray *fs = [j isKindOfClass:NSDictionary.class] ? j[@"files"] : nil;
int64_t tot = 0; BOOL ok = [fs isKindOfClass:NSArray.class] && fs.count;
for (NSDictionary *f in (ok ? fs : @[])) {
NSString *nm = [f isKindOfClass:NSDictionary.class] ? f[@"name"] : nil, *sha = [f isKindOfClass:NSDictionary.class] ? f[@"sha256"] : nil; NSNumber *sz = [f isKindOfClass:NSDictionary.class] ? f[@"size"] : nil;
if (![nm isKindOfClass:NSString.class] || !nm.length || [nm containsString:@"/"] || [nm hasPrefix:@"."] || ![sha isKindOfClass:NSString.class] || sha.length != 64 || ![sz isKindOfClass:NSNumber.class] || sz.longLongValue < 0) { ok = NO; break; }
}
if (!ok) { plog("assets: %s 的清单格式不对,换下一个地址", b.UTF8String); continue; }
// 只下档案文件与它的区段表:清单里别的(配置、密钥、提取工具的各张清单)游戏用不着(见 host/romfs_validate.c),不下、也就不会因为它们下不动
// Download only the archive files and their extent tables: the rest of the manifest (config, key, the extraction tool's manifests) is not needed by the
// game (see host/romfs_validate.c), so it is not downloaded and the download cannot get stuck on it
fs = [fs filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary *f, id _) { return [f[@"name"] hasSuffix:@".data"] || [f[@"name"] hasSuffix:@".data.holes"]; }]];
for (NSDictionary *f in fs) tot += [f[@"size"] longLongValue];
if (!fs.count) { plog("assets: %s 的清单里没有档案文件,换下一个地址", b.UTF8String); continue; }
self.base = b; self.files = fs; self.total = tot; [NSUserDefaults.standardUserDefaults setObject:b forKey:self.defKey];
plog("assets: 下载地址 %s,清单 %lu 个文件共 %lld 字节", b.UTF8String, (unsigned long)fs.count, tot); return nil;
}
return @(dm_ui("dmDlNoServer"));
}
static int64_t dl_size(NSString *p) { NSDictionary *a = [NSFileManager.defaultManager attributesOfItemAtPath:p error:nil]; return a ? (int64_t)[a fileSize] : -1; }
- (NSString *)final:(NSString *)nm { return [self.dir stringByAppendingPathComponent:nm]; }
- (NSString *)part:(NSString *)nm { return [self.dir stringByAppendingPathComponent:[nm stringByAppendingString:@".part"]]; }
- (BOOL)have:(NSDictionary *)f { return dl_size([self final:f[@"name"]]) == [f[@"size"] longLongValue]; } // 正式文件在且字节数对 | The final file exists and its byte count is right
- (int64_t)scan { int64_t n = 0; for (NSDictionary *f in self.files) { if ([self have:f]) n += [f[@"size"] longLongValue]; else { int64_t p = dl_size([self part:f[@"name"]]); if (p > 0) n += MIN(p, [f[@"size"] longLongValue]); } } return n; }
static NSString *dl_sha256(NSString *path) {
NSFileHandle *h = [NSFileHandle fileHandleForReadingAtPath:path]; if (!h) return nil; CC_SHA256_CTX c; CC_SHA256_Init(&c);
for (;;) { @autoreleasepool { NSData *d = [h readDataOfLength:1 << 20]; if (!d.length) break; CC_SHA256_Update(&c, d.bytes, (CC_LONG)d.length); } }
unsigned char dg[32]; CC_SHA256_Final(dg, &c); NSMutableString *s = [NSMutableString new]; for (int i = 0; i < 32; i++) [s appendFormat:@"%02x", dg[i]]; return s;
}
- (void)prepare:(void (^)(NSString *err, int64_t remain, int64_t total, BOOL cellular))done {
self.shortBytes = 0; self.freeBytes = 0; // 每次先清:更早一步失败(取清单断网等)时不留上一轮「空间不够」 | Clear first every time: when an earlier step fails (manifest fetch with no network, etc.), do not keep the previous round's "not enough space"
dispatch_async(self.q, ^{
NSString *err = getenv("DM_ASSET_DL_OFF") ? @"测试开关 DM_ASSET_DL_OFF:下载站当作走不通" : [self resolve]; if (err) { dispatch_async(dispatch_get_main_queue(), ^{ done(err, 0, 0, NO); }); return; }
NSFileManager *fm = NSFileManager.defaultManager; [fm createDirectoryAtPath:self.dir withIntermediateDirectories:YES attributes:nil error:nil];
[[NSURL fileURLWithPath:self.dir.stringByDeletingLastPathComponent] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; // 4 GB 资源不进 iCloud 备份 | The 4 GB of assets do not go into iCloud backup
self.settled = [self scan]; int64_t remain = self.total - self.settled;
NSNumber *freeb = nil; [[NSURL fileURLWithPath:self.dir] getResourceValue:&freeb forKey:NSURLVolumeAvailableCapacityForImportantUsageKey error:nil];
{ const char *ft = getenv("DM_ASSET_FREE_TEST"); if (ft) freeb = @((long long)(atof(ft) * 1e9)); } // 测试开关:把手机可用空间当成这么多 GB(造「空间不够」现场) | Test switch: treat the phone's free space as this many GB (reproduces the "not enough space" scenario)
self.freeBytes = freeb ? freeb.longLongValue : 0;
if (freeb && freeb.longLongValue < remain + (200ll << 20)) { self.shortBytes = remain + (200ll << 20) - freeb.longLongValue; NSString *m = [NSString stringWithFormat:@"手机剩余空间不够:还要下 %.2f GB,可用 %.2f GB", remain / 1e9, freeb.longLongValue / 1e9]; dispatch_async(dispatch_get_main_queue(), ^{ done(m, remain, self.total, NO); }); return; }
// 当前网络是不是按流量计费的(蜂窝 / 个人热点):是的话由界面先问玩家
// Whether the current network is metered (cellular / personal hotspot): if so, the UI asks the player first
nw_path_monitor_t mon = nw_path_monitor_create(); dispatch_semaphore_t sem = dispatch_semaphore_create(0); __block BOOL exp = NO; __block int got = 0;
nw_path_monitor_set_queue(mon, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
nw_path_monitor_set_update_handler(mon, ^(nw_path_t p) { if (!got) { got = 1; exp = nw_path_is_expensive(p); dispatch_semaphore_signal(sem); } });
nw_path_monitor_start(mon); dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC)); nw_path_monitor_cancel(mon);
if (getenv("DM_ASSET_CELL_TEST")) exp = YES;
plog("assets: 已有 %lld / %lld 字节,还要下 %lld;%s", self.settled, self.total, remain, exp ? "当前是按流量计费的网络" : "当前不是按流量计费的网络");
dispatch_async(dispatch_get_main_queue(), ^{ done(nil, remain, self.total, exp); });
});
}
- (void)run:(void (^)(int64_t, int64_t, NSString *))progress done:(void (^)(NSString *))done {
dispatch_async(self.q, ^{ self.onProgress = progress; self.onDone = done; self.running = 1; self.retry = 0; self.heal = 0; self.skipWin = 0; self.best = 0; self.winT = 0; self.curBytes = 0;
if (!self.watch) { self.watch = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.q); dispatch_source_set_timer(self.watch, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), 5 * NSEC_PER_SEC, NSEC_PER_SEC);
__weak DmAssetDL *w = self; dispatch_source_set_event_handler(self.watch, ^{ [w watchTick]; }); dispatch_resume(self.watch); }
[self pump]; });
}
- (void)report:(int64_t)done note:(NSString *)note { void (^p)(int64_t, int64_t, NSString *) = self.onProgress; int64_t t = self.total; if (p) dispatch_async(dispatch_get_main_queue(), ^{ p(done, t, note); }); }
- (void)finish:(NSString *)err { self.running = 0; void (^d)(NSString *) = self.onDone; self.onDone = nil; plog("assets: 直接下载结束:%s", err ? err.UTF8String : "全部到齐"); if (d) dispatch_async(dispatch_get_main_queue(), ^{ d(err); }); }
// 找到第一个没到齐的文件,给它起(或接回)一个分段任务。只在 self.q 上跑
// Find the first incomplete file and start (or reattach) a ranged task for it. Runs only on self.q
- (void)pump {
if (!self.running) return;
self.settled = [self scan];
for (NSDictionary *f in self.files) {
if ([self have:f]) continue;
NSString *nm = f[@"name"], *part = [self part:nm]; int64_t size = [f[@"size"] longLongValue], p = MAX(dl_size(part), 0);
if (p > size) { [NSFileManager.defaultManager removeItemAtPath:part error:nil]; p = 0; }
if (p == size) { // 到齐:核校验值,对了才改成正式名 | All received: verify the checksum; rename to the final name only if it matches
[self report:self.settled note:[NSString stringWithFormat:@(dm_ui("dmDlVerifying")), nm]];
if (!size) [NSFileManager.defaultManager createFileAtPath:part contents:NSData.data attributes:nil];
NSString *sha = dl_sha256(part);
if ([sha isEqualToString:f[@"sha256"]]) { NSError *e = nil; [NSFileManager.defaultManager removeItemAtPath:[self final:nm] error:nil];
if (![NSFileManager.defaultManager moveItemAtPath:part toPath:[self final:nm] error:&e]) { [self finish:[NSString stringWithFormat:@(dm_ui("dmDlWriteFail")), nm, e.localizedDescription]]; return; }
plog("assets: %s 到齐(%lld 字节,校验值对)", nm.UTF8String, size); continue; }
int n = self.redo[nm].intValue + 1; self.redo[nm] = @(n); [NSFileManager.defaultManager removeItemAtPath:part error:nil];
plog("assets: 🔴 %s 校验值不对(得 %s,应 %s),删掉重下(第 %d 次)", nm.UTF8String, sha.UTF8String, [f[@"sha256"] UTF8String], n);
if (n >= 3) { [self finish:[NSString stringWithFormat:@(dm_ui("dmDlBad3")), nm]]; return; }
p = 0; self.settled = [self scan];
}
int64_t end = MIN(p + DL_CHUNK, size) - 1; NSString *desc = [NSString stringWithFormat:@"%@\t%lld\t%lld", nm, p, end];
[[self bg] getTasksWithCompletionHandler:^(NSArray *d0, NSArray *u0, NSArray<NSURLSessionDownloadTask *> *tasks) {
BOOL alive = NO;
for (NSURLSessionTask *t in tasks) { if (t.state == NSURLSessionTaskStateCompleted) continue; if (!self.useFg && !alive && [t.taskDescription isEqualToString:desc]) { alive = YES; if (t.state == NSURLSessionTaskStateSuspended) [t resume]; } else [t cancel]; }
self.winT = 0; self.curBytes = 0; // 新的一片(或刚接回的一片):吞吐窗口从头量。接回的旧任务若是僵死的,一个窗口后照掉速处理 | A new chunk (or one just re-attached): measure the throughput window from scratch. If a re-attached old task is dead, it is treated as a slowdown after one window
if (alive) { plog("assets: 接回系统手里没做完的任务:%s 字节 %lld–%lld", nm.UTF8String, p, end); return; }
NSString *enc = [nm stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/data/%@", self.base, enc]]];
[rq setValue:[NSString stringWithFormat:@"bytes=%lld-%lld", p, end] forHTTPHeaderField:@"Range"]; rq.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSURLSessionDownloadTask *t = [(self.useFg ? (self.fg ?: [self fgNew]) : [self bg]) downloadTaskWithRequest:rq]; t.taskDescription = desc; [t resume];
}];
[self report:self.settled note:nil];
return;
}
[self finish:nil];
}
- (void)URLSession:(NSURLSession *)s downloadTask:(NSURLSessionDownloadTask *)t didWriteData:(int64_t)n totalBytesWritten:(int64_t)w totalBytesExpectedToWrite:(int64_t)x {
self.curBytes = w;
if (self.running) [self report:self.settled + w note:nil];
}
- (void)URLSession:(NSURLSession *)s downloadTask:(NSURLSessionDownloadTask *)t didFinishDownloadingToURL:(NSURL *)loc {
NSArray<NSString *> *d = [t.taskDescription componentsSeparatedByString:@"\t"]; if (d.count != 3) return;
NSString *nm = d[0], *part = [self part:nm]; int64_t off = d[1].longLongValue, end = d[2].longLongValue, got = dl_size(loc.path), have = MAX(dl_size(part), 0);
NSHTTPURLResponse *r = (NSHTTPURLResponse *)t.response; NSString *cr = [r valueForHTTPHeaderField:@"Content-Range"]; NSString *wantcr = [NSString stringWithFormat:@"bytes %lld-%lld/", off, end];
if (r.statusCode != 206 || ![cr hasPrefix:wantcr] || got != end - off + 1 || have != off) { // 不是要的那一段(服务器不认 Range / 中间页 / 重复送达):丢掉,pump 会按 .part 的实际长度重新要 | Not the range we asked for (server ignores Range / interstitial page / duplicate delivery): discard; pump will ask again based on the actual length of .part
plog("assets: 丢弃一段 %s 字节 %lld–%lld:HTTP %ld,Content-Range %s,收到 %lld 字节,.part 现有 %lld", nm.UTF8String, off, end, (long)r.statusCode, cr.UTF8String ?: "无", got, have); return; }
NSFileHandle *in = [NSFileHandle fileHandleForReadingAtPath:loc.path]; if (![NSFileManager.defaultManager fileExistsAtPath:part]) [NSFileManager.defaultManager createFileAtPath:part contents:nil attributes:nil];
NSFileHandle *out = [NSFileHandle fileHandleForWritingAtPath:part]; if (!in || !out) { plog("assets: 🔴 打不开 %s", part.UTF8String); return; }
@try { [out seekToEndOfFile]; for (;;) { @autoreleasepool { NSData *b = [in readDataOfLength:1 << 20]; if (!b.length) break; [out writeData:b]; } } [out synchronizeFile]; }
@catch (NSException *ex) { plog("assets: 🔴 写 %s 出错:%s", part.UTF8String, ex.reason.UTF8String); [out truncateFileAtOffset:(unsigned long long)off]; }
[out closeFile]; [in closeFile];
}
- (void)URLSession:(NSURLSession *)s task:(NSURLSessionTask *)t didCompleteWithError:(NSError *)e {
if (e && e.code == NSURLErrorCancelled) return; // 我们自己取消的多余任务 | Surplus tasks that we cancelled ourselves
if (!self.running) return; // 进程刚被系统唤醒、界面还没来要:落盘已在上面做完,等 run 时再接着 | The process was just woken by the system and the UI has not asked yet: writing to disk is already done above; resume when run is called
if (e) { int wait = MIN(30, 2 << MIN(self.retry, 4)); self.retry++;
plog("assets: 一段没取成(%s),%d 秒后自动重试(第 %d 次)", e.localizedDescription.UTF8String, wait, self.retry);
[self report:[self scan] note:[NSString stringWithFormat:@(dm_ui("dmDlNetRetry")), wait]];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, wait * NSEC_PER_SEC), self.q, ^{ [self pump]; }); return; }
self.retry = 0; [self pump];
}
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)s { void (^d)(void) = self.bgDone; self.bgDone = nil; if (d) dispatch_async(dispatch_get_main_queue(), d); }
@end
+44
View File
@@ -0,0 +1,44 @@
// iOS 启动 I/O 采样(DM_BOOTPROF=1 时生效;分段表 ⓪–⑥ 由宿主 diag.c 出,零点同为进程创建):
// 每 100 ms 一行 Documents/bootprof.tsv:t(秒,零点 = 进程创建,内核 p_starttime)、
// ri_pageins(缺页读入次数:内嵌代码段等文件页首次触达)、ri_diskio_bytesread(真读盘字节:RomFS 首读 + 代码页)、phys_footprint
// iOS startup I/O sampling (active when DM_BOOTPROF=1; the phase table ⓪–⑥ is produced by the host's diag.c, with the same zero point = process creation):
// one line every 100 ms to Documents/bootprof.tsv: t (seconds, zero point = process creation, kernel p_starttime),
// ri_pageins (page-in count: first touch of file pages such as the embedded code segment), ri_diskio_bytesread (bytes actually read from disk: first RomFS reads + code pages), phys_footprint
#import <Foundation/Foundation.h>
#include <sys/sysctl.h>
#include <sys/resource.h>
#include <mach/mach.h>
#include <pthread.h>
#include <unistd.h>
int proc_pid_rusage(int pid, int flavor, rusage_info_t *buffer); // libproc(iOS SDK 无头文件,符号在 libsystem) | libproc (no header in the iOS SDK; the symbol is in libsystem)
uint64_t now_ns(void); // 宿主时钟(hle_os.c) | Host clock (hle_os.c)
static uint64_t g_t0; // 本构造函数时刻 | Time of this constructor
static double g_pre_s; // 进程创建 → 本构造函数(秒) | Process creation → this constructor (seconds)
static void *sampler(void *p) {
FILE *f = fopen((const char *)p, "w"); if (!f) return NULL;
fprintf(f, "t_since_spawn\tpageins\tdisk_read_MiB\tfootprint_MiB\n");
for (int i = 0; i < 300; i++) { // 30 秒 | 30 seconds
struct rusage_info_v4 ri; task_vm_info_data_t vi; mach_msg_type_number_t n = TASK_VM_INFO_COUNT;
proc_pid_rusage(getpid(), RUSAGE_INFO_V4, (rusage_info_t *)&ri);
task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&vi, &n);
fprintf(f, "%.2f\t%llu\t%.1f\t%llu\n", g_pre_s + (now_ns() - g_t0) / 1e9, ri.ri_pageins, ri.ri_diskio_bytesread / 1048576.0, vi.phys_footprint >> 20);
fflush(f);
usleep(100000);
}
fclose(f); return NULL;
}
__attribute__((constructor)) static void bootprof_ios(void) {
g_t0 = now_ns();
if (!getenv("DM_BOOTPROF")) return;
struct kinfo_proc kp; size_t len = sizeof kp; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
struct timeval now; gettimeofday(&now, NULL);
if (!sysctl(mib, 4, &kp, &len, NULL, 0))
g_pre_s = (now.tv_sec - kp.kp_proc.p_starttime.tv_sec) + (now.tv_usec - kp.kp_proc.p_starttime.tv_usec) / 1e6;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
char *path = strdup([doc stringByAppendingPathComponent:@"bootprof.tsv"].fileSystemRepresentation);
pthread_t th; pthread_create(&th, NULL, sampler, path); pthread_detach(th);
}
+202
View File
@@ -0,0 +1,202 @@
// iCloud 存档同步的 iOS 一侧:拿 iCloud 容器目录、让云端的包先下载好,再调共用核心 dm_cloud_sync(dm/host/dm_cloudsync.c)。
// 启动:dm_cloud_boot 在 boot_thread 里、dm_main 挂存档之前调,最多等 5 秒,拉云端各包、按「后写覆盖先写」换进本地存档,之后游戏照常读存档列表。
// 运行中:存档每提交成功一次(hle_fs.c 的 Commit),提交钩子先把已提交目录 clonefile 成快照(写时复制,近乎零成本);局内只记成待传,出局 / 切后台时在串行队列里把快照与云端对比、只上传(allow_down = 0);不在局内的提交当场传。
// 只同步玩家真实存档 Documents/save;测试存档(save.test 等)缺省不同步。测试开关 DM_TEST_ICLOUD_SUB=<子目录名>:测试存档也同步,云端用容器里的这个子目录(与真实存档的 saves 隔开,不会把测试角色传到玩家设备上)。
// 测试开关 DM_TEST_ICLOUD_DIR=<本地目录>:用本地目录当云端(不碰 iCloud),测试存档也同步。不以 / 开头的路径拼到 App 的 Documents 下(下同)。
// 测试开关 DM_TEST_ICLOUD_ROOT=<本地目录>:用本地目录当 iCloud 容器的 Documents(下有 saves / saves_v2),验目录换代与一次性迁移;测试存档也同步。
// 开关:「自定义」页 icloud(缺省开)。没登录 iCloud / 本 App 的 iCloud 被关:取不到容器,整套跳过,日志记一行。
// iOS side of iCloud save sync: get the iCloud container directory, let the cloud packages download first, then call the shared core dm_cloud_sync (dm/host/dm_cloudsync.c).
// Startup: dm_cloud_boot is called in boot_thread before dm_main mounts the save; waits at most 5 seconds, pulls each cloud package and swaps it into the local save under "later write overwrites earlier write"; after that the game reads the save list as usual.
// While running: each time a save commit succeeds (Commit in hle_fs.c), the commit hook first clonefiles the committed directory into a snapshot (copy-on-write, nearly free); in a run it is only marked pending, and on leaving the run / going to background the snapshot is compared with the cloud on a serial queue, upload only (allow_down = 0); commits outside a run are uploaded on the spot.
// Only the player's real save Documents/save is synced; test saves (save.test etc.) are not synced by default. Test switch DM_TEST_ICLOUD_SUB=<subdirectory name>: test saves are synced too, and the cloud uses this subdirectory of the container (kept apart from the real save's saves, so test characters are not uploaded to the player's devices).
// Test switch DM_TEST_ICLOUD_DIR=<local directory>: use a local directory as the cloud (iCloud untouched); test saves are synced too. Paths not starting with / are joined under the App's Documents (same below).
// Test switch DM_TEST_ICLOUD_ROOT=<local directory>: use a local directory as the iCloud container's Documents (containing saves / saves_v2), to verify the directory generation change and the one-time migration; test saves are synced too.
// Switch: icloud on the 「自定义」(Custom) page (on by default). Not signed in to iCloud / iCloud turned off for this App: the container cannot be obtained, the whole thing is skipped and one log line is written.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <signal.h>
#include <sys/clonefile.h>
#include <stdatomic.h>
#include "front.h"
#include "hle.h"
int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const char *statef, int allow_down, uint64_t now_ms, int (*ready)(const char *unit));
int dm_custom_get(const char *key);
extern void (*g_dm_save_commit_hook)(const char *commit_dir);
static NSString *g_cloud, *g_save, *g_bak, *g_state; // 云端目录 / 本地存档 / 备份 / 状态文件 | Cloud directory / local save / backup / state file
static dispatch_queue_t g_q;
static uint64_t now_ms(void) { return (uint64_t)([NSDate date].timeIntervalSince1970 * 1000); }
// 云端某个单位的包是否已在本机(iCloud 里没下载的文件是占位:旧系统是「.<名>.icloud」,新系统是同名但下载状态不是「最新」)
// Whether a given unit's package in the cloud is already on this device (undownloaded files in iCloud are placeholders: on older systems ".<name>.icloud", on newer systems the same name with a download status other than "current")
static int pack_ready(const char *unit) {
NSString *nm = [NSString stringWithFormat:@"%s.pack", unit];
if ([NSFileManager.defaultManager fileExistsAtPath:[g_cloud stringByAppendingPathComponent:[NSString stringWithFormat:@".%@.icloud", nm]]]) return 0;
NSURL *u = [NSURL fileURLWithPath:[g_cloud stringByAppendingPathComponent:nm]]; NSString *st = nil;
if (![u getResourceValue:&st forKey:NSURLUbiquitousItemDownloadingStatusKey error:nil] || !st) return 1; // 不是 iCloud 管的文件(或没有这个包):按已在本机 | Not an iCloud-managed file (or no such package): treated as already on this device
return [st isEqualToString:NSURLUbiquitousItemDownloadingStatusCurrent];
}
static int pending_downloads(int start) { // 还没下载好的包数;start = 1 时顺手请系统开始下载 | Number of packages not yet downloaded; with start = 1 also ask the system to start downloading
int n = 0; NSFileManager *fm = NSFileManager.defaultManager;
for (NSString *f in [fm contentsOfDirectoryAtPath:g_cloud error:nil] ?: @[]) {
NSString *nm = f; if ([f hasPrefix:@"."] && [f hasSuffix:@".icloud"]) nm = [f substringWithRange:NSMakeRange(1, f.length - 8)];
if (![nm hasSuffix:@".pack"]) continue;
if (pack_ready([nm substringToIndex:nm.length - 5].UTF8String)) continue;
n++; if (start) [fm startDownloadingUbiquitousItemAtURL:[NSURL fileURLWithPath:[g_cloud stringByAppendingPathComponent:nm]] error:nil];
}
return n;
}
static int run_sync(NSString *save, int down) { // 在文件协调里做:iCloud 守护进程同时在写这个目录时不会读到半个文件 | Done inside file coordination: half-written files are not read while the iCloud daemon is writing this directory at the same time
__block int r = -1; NSError *err = nil;
[[[NSFileCoordinator alloc] initWithFilePresenter:nil] coordinateWritingItemAtURL:[NSURL fileURLWithPath:g_cloud] options:NSFileCoordinatorWritingForMerging error:&err byAccessor:^(NSURL *u) {
(void)u; r = dm_cloud_sync(save.fileSystemRepresentation, g_cloud.fileSystemRepresentation, g_bak.fileSystemRepresentation, g_state.fileSystemRepresentation, down, now_ms(), pack_ready); }];
if (err) LOG("【红】iCloud 同步:文件协调失败 %s", err.localizedDescription.UTF8String);
return r;
}
// 存档提交钩子(hle_fs.c,持着存档锁调):只做快照,其余放队列。
// 局内(58 分钟提交 127 次、上传 97 次,平均 35 秒碰一次网):只留最新那份快照记成「待传」,不上传;
// 退出这一局回到前端(主菜单 / 选角页)、切到后台时各传一次(dm_cloud_flush)。不在局内(选角 / 建角 / 删角色)的提交照旧当场传——
// 删角色只在选角页发生,拖到以后传的话被强杀后再启动会把删掉的角色从云端拉回来(启动同步把「本地没了」当丢失、从云端拿回)。
// 被强杀 / 崩溃没来得及传:待传快照随之作废(启动时清掉),启动那次同步看到本地自上次同步后改过、云端没变,照常补传(dm_cloudsync.c lchg && !cchg → UP)
// Save commit hook (hle_fs.c, called while holding the save lock): only takes a snapshot, the rest goes to the queue.
// In a run (127 commits and 97 uploads in 58 minutes, touching the network every 35 seconds on average): keep only the newest snapshot marked as "pending upload", do not upload;
// upload once each when leaving the run back to the front end (main menu / character select page) and when going to background (dm_cloud_flush). Commits outside a run (character select / create / delete character) are still uploaded on the spot --
// character deletion only happens on the character select page; if deferred, a force-kill followed by a relaunch would pull the deleted character back from the cloud (startup sync treats "missing locally" as lost and restores it from the cloud).
// Force-killed / crashed before uploading: the pending snapshot is voided with it (cleared at startup), and the startup sync sees local changed since the last sync and cloud unchanged, so it uploads as usual (dm_cloudsync.c lchg && !cchg → UP)
static NSString *g_pend; // 局内最新一次提交的快照(只在 g_q 上读写) | Snapshot of the newest commit in the run (read and written only on g_q)
static _Atomic int g_bg; // App 在后台:此时的提交(失活时请求的那次存盘)当场传 | App in background: a commit at this time (the save requested on resign active) is uploaded on the spot
static _Atomic int g_session; // 在一局里:进局(第一次出现局内画面)起,到游戏发「回到前端」(FrontEndNavigation:ToFrontEnd)为止——中间的读取画面(切幕 / 传送点)不算出局 | In a run: from entering the run (first appearance of the in-run picture) until the game sends "back to front end" (FrontEndNavigation:ToFrontEnd) -- loading screens in between (act change / waypoint) do not count as leaving the run
static void upload_snap(NSString *snap, const char *why) { // 在 g_q 上调 | Called on g_q
if (dm_custom_get("icloud")) { int n = run_sync(snap, 0); LOG("iCloud 同步:%s上传 %d 个", why, n); }
[NSFileManager.defaultManager removeItemAtPath:snap error:nil];
}
static void on_commit(const char *commit_dir) {
static unsigned seq; NSString *snap = [NSString stringWithFormat:@"%@.cloudsnap%u", g_save, ++seq];
[NSFileManager.defaultManager removeItemAtPath:snap error:nil];
if (clonefile(commit_dir, snap.fileSystemRepresentation, 0)) { LOG("【红】iCloud 同步:存档快照失败 errno=%d,这次提交不上传", errno); return; }
int defer = atomic_load(&g_session) && !atomic_load(&g_bg);
dispatch_async(g_q, ^{
if (defer) { if (g_pend) [NSFileManager.defaultManager removeItemAtPath:g_pend error:nil]; g_pend = snap; return; } // 局内:换成这一份,等出局 / 切后台 | In a run: replace with this copy and wait for leaving the run / going to background
if (g_pend) { [NSFileManager.defaultManager removeItemAtPath:g_pend error:nil]; g_pend = nil; } // 这一份更新,旧的待传作废 | This copy is newer; the old pending upload is voided
upload_snap(snap, atomic_load(&g_bg) ? "后台存档提交后" : "存档提交后(不在局内)");
});
}
// 出局 / 切后台:把局内攒下的最新一份传掉。切后台用系统给的后台收尾时间,传完才结束(最多约 30 秒,系统到点前会叫停)
// Leaving a run / going to background: upload the newest copy accumulated during the run. Going to background uses the background completion time granted by the system and ends only after the upload finishes (about 30 seconds at most; the system calls a stop before time is up)
void dm_cloud_flush(int background) {
if (!g_q) return; // 没开同步(测试存档 / 没登录 iCloud / 自定义页关了) | Sync not enabled (test save / not signed in to iCloud / turned off on the Custom page)
if (background) atomic_store(&g_bg, 1);
__block UIBackgroundTaskIdentifier tk = UIBackgroundTaskInvalid;
if (background) tk = [UIApplication.sharedApplication beginBackgroundTaskWithName:@"dm.cloud" expirationHandler:^{ LOG("【红】iCloud 同步:后台收尾时间到,系统叫停(没传完的下次启动补传)"); [UIApplication.sharedApplication endBackgroundTask:tk]; tk = UIBackgroundTaskInvalid; }];
dispatch_async(g_q, ^{
NSString *p = g_pend; g_pend = nil;
if (p) upload_snap(p, background ? "切到后台," : "退出这一局回到前端,");
else LOG("iCloud 同步:%s,局内没有待传的存档", background ? "切到后台" : "退出这一局回到前端");
if (tk != UIBackgroundTaskInvalid) dispatch_async(dispatch_get_main_queue(), ^{ if (tk != UIBackgroundTaskInvalid) { [UIApplication.sharedApplication endBackgroundTask:tk]; tk = UIBackgroundTaskInvalid; } });
});
}
void dm_cloud_foreground(void) { atomic_store(&g_bg, 0); }
static void cloud_ingame(int on) { if (on) atomic_store(&g_session, 1); }
static void cloud_charsel(void) { if (atomic_exchange(&g_session, 0)) dm_cloud_flush(0); } // 退出这一局回到前端(主菜单 / 选角页):这一局结束 | Left this run back to the front end (main menu / character select page): this run has ended
static NSURL *container(double limit) { // 取 iCloud 容器:要在主线程以外调,第一次可能要等系统建目录;取不到返回 nil 并记原因 | Get the iCloud container: must be called off the main thread; the first time may have to wait for the system to create the directory; returns nil and logs the reason if it cannot be obtained
__block NSURL *ct = nil; dispatch_semaphore_t got = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ ct = [NSFileManager.defaultManager URLForUbiquityContainerIdentifier:nil]; dispatch_semaphore_signal(got); });
if (dispatch_semaphore_wait(got, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(limit * NSEC_PER_SEC)))) { LOG("iCloud 不可用:取容器超过 %.0f 秒,本次只用本地存档", limit); return nil; }
if (!ct) LOG("iCloud 不可用:没登录 iCloud 或本 App 的 iCloud 被关,只用本地存档");
return ct;
}
// 云端目录换代(编年史仓库第 5 步;旧版本是覆盖更新的):本版起存档格式变了(储藏箱 14 列),旧包读新档会静默删掉新列里的物品。
// 云端改用 Documents/saves_v2,旧包仍用 Documents/saves,两边互不覆盖。新包第一次启动(saves_v2 还没有)把 saves 复制过去一次——只读旧目录,旧目录一个字节都不改、不删:
// 先等旧目录里的包全部下载到本机(占位文件复制过去是空的);逐个文件复制到 saves_v2.tmp,最后写完成清单 sw_migrated.txt(迁移时的全部包名),
// 再把 saves_v2.tmp 整个改名成 saves_v2——改名是最后一步,有 saves_v2 就一定是写完清单的整套。中途被杀:下次启动先删掉残留的 .tmp 从头再来。
// 没等到下载完 / 复制失败 = 本次不迁移也不同步,下次启动再试(先同步会建出空的 saves_v2,之后再也不迁移,别的设备在旧目录里的新档就漏了)。
// 用之前查齐(所有设备,含迁移的那台):saves_v2 里有清单、清单上的包都到了本机目录(已下载或是 iCloud 占位)才同步。另一台设备上 iCloud 是一个文件一个文件
// 下来的:没查齐就同步,本机较旧的那份会按「云端没有包 → 上传」传上去,后写覆盖掉迁移过来的新进度。查齐过一次就在本地记一笔(<存档>.cloudv2ok),以后不再查
// (之后角色删了包会少,不能一直按清单卡)。返回 0 = 本次跳过同步
// Cloud directory generation change (chronicle vault step 5; older versions were updated by overwrite): from this version the save format changed (stash has 14 columns); an old build reading a new save silently deletes the items in the new columns.
// The cloud now uses Documents/saves_v2 while old builds keep using Documents/saves, so neither overwrites the other. On its first launch (saves_v2 does not exist yet) the new build copies saves over once -- the old directory is only read, not one byte of it is changed or deleted:
// first wait until all packages in the old directory are downloaded to this device (a placeholder file would copy over as empty); copy file by file into saves_v2.tmp, and finally write the completion manifest sw_migrated.txt (all package names at migration time),
// then rename saves_v2.tmp as a whole to saves_v2 -- the rename is the last step, so if saves_v2 exists it is always a complete set with the manifest written. Killed midway: on the next launch delete the leftover .tmp first and start over.
// Download not finished in time / copy failed = no migration and no sync this time, retry on the next launch (syncing first would create an empty saves_v2, after which migration never happens again and new saves from other devices in the old directory would be missed).
// Check completeness before use (all devices, including the one that migrated): sync only when saves_v2 contains the manifest and every package on the manifest has reached this device's directory (downloaded, or present as an iCloud placeholder). On another device iCloud brings files down one
// at a time: syncing before the check passes, this device's older copy would be uploaded under "no package in the cloud → upload", and the later write would overwrite the newer migrated progress. Once the check has passed, record it locally (<save>.cloudv2ok) and never check again
// (later, deleting a character removes packages, so we cannot keep blocking on the manifest forever). Returns 0 = skip sync this time
static NSString *test_path(const char *e) { // 测试开关里的路径:不以 / 开头的拼到 App 的 Documents 下(真机容器路径每次装包都变) | Paths in test switches: those not starting with / are joined under the App's Documents (the real-device container path changes on every install)
if (!e) return nil; if (e[0] == '/') return @(e);
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@(e)];
}
static int v2_ready(NSString *nw, NSString *okf) { // 迁移过来的整套是否都到了本机 | Whether the whole migrated set has arrived on this device
NSFileManager *fm = NSFileManager.defaultManager; if ([fm fileExistsAtPath:okf]) return 1;
NSString *ls = [NSString stringWithContentsOfFile:[nw stringByAppendingPathComponent:@"sw_migrated.txt"] encoding:NSUTF8StringEncoding error:nil];
if (!ls) { LOG("iCloud 同步:saves_v2 里还没有完成清单(别的设备的迁移还没传完?),本次不同步"); return 0; }
int miss = 0, n = 0; for (NSString *f in [ls componentsSeparatedByString:@"\n"]) { if (!f.length) continue; n++;
if (![fm fileExistsAtPath:[nw stringByAppendingPathComponent:f]] && ![fm fileExistsAtPath:[nw stringByAppendingPathComponent:[NSString stringWithFormat:@".%@.icloud", f]]]) miss++; }
if (miss) { LOG("iCloud 同步:saves_v2 清单 %d 项还缺 %d 项没到本机,本次不同步", n, miss); return 0; }
[@"" writeToFile:okf atomically:YES encoding:NSUTF8StringEncoding error:nil]; LOG("iCloud 同步:saves_v2 清单 %d 项都已到本机", n); return 1;
}
static int migrate_v2(NSString *docs, double deadline) {
NSFileManager *fm = NSFileManager.defaultManager; NSString *nw = [docs stringByAppendingPathComponent:@"saves_v2"], *old = [docs stringByAppendingPathComponent:@"saves"], *tmp = [nw stringByAppendingString:@".tmp"];
if ([fm fileExistsAtPath:nw]) return 1;
if (![fm fileExistsAtPath:old]) { LOG("iCloud 同步:云端没有旧目录 saves,直接用 saves_v2"); [fm createDirectoryAtPath:nw withIntermediateDirectories:YES attributes:nil error:nil];
[@"" writeToFile:[nw stringByAppendingPathComponent:@"sw_migrated.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil]; return 1; } // 空清单:没有要等的包 | Empty manifest: no packages to wait for
g_cloud = old; int pend = pending_downloads(1);
while (pend && CFAbsoluteTimeGetCurrent() < deadline) { usleep(100000); pend = pending_downloads(0); }
g_cloud = nil;
if (pend) { LOG("iCloud 同步:旧目录 saves 还有 %d 个包没下载完,本次不迁移、不同步,下次启动再试", pend); return 0; }
const char *kill_at = getenv("DM_TEST_ICLOUD_MIGRATE_KILL"); // 测试:复制完第 N 个文件后自杀(N = marker:写完清单、改名之前),验中途被杀 | Test: kill self after copying the Nth file (N = marker: after writing the manifest, before the rename), to verify being killed midway
__block BOOL ok = YES; __block NSError *e2 = nil; __block NSMutableString *list = [NSMutableString string]; __block int copied = 0; NSError *err = nil;
[[[NSFileCoordinator alloc] initWithFilePresenter:nil] coordinateReadingItemAtURL:[NSURL fileURLWithPath:old] options:0 error:&err byAccessor:^(NSURL *u) {
if ([fm fileExistsAtPath:tmp]) { LOG("iCloud 同步:上次迁移没做完(有 saves_v2.tmp),删掉重来"); [fm removeItemAtPath:tmp error:nil]; }
ok = [fm createDirectoryAtPath:tmp withIntermediateDirectories:NO attributes:nil error:&e2];
for (NSString *f in [fm contentsOfDirectoryAtPath:u.path error:nil] ?: @[]) { if (!ok) break; if ([f hasPrefix:@"."]) continue; // 隐藏文件(系统的)不带 | Hidden files (the system's) are not carried over
ok = [fm copyItemAtPath:[u.path stringByAppendingPathComponent:f] toPath:[tmp stringByAppendingPathComponent:f] error:&e2]; if (!ok) break;
if ([f hasSuffix:@".pack"]) [list appendFormat:@"%@\n", f]; copied++;
if (kill_at && atoi(kill_at) == copied) { LOG("DM_TEST_ICLOUD_MIGRATE_KILL:复制完第 %d 个文件,自杀", copied); kill(getpid(), SIGKILL); } }
if (ok) ok = [list writeToFile:[tmp stringByAppendingPathComponent:@"sw_migrated.txt"] atomically:YES encoding:NSUTF8StringEncoding error:&e2];
if (ok && kill_at && !strcmp(kill_at, "marker")) { LOG("DM_TEST_ICLOUD_MIGRATE_KILL:清单已写、改名之前自杀"); kill(getpid(), SIGKILL); }
if (ok) ok = [fm moveItemAtPath:tmp toPath:nw error:&e2]; }];
if (!ok || err) { [fm removeItemAtPath:tmp error:nil];
if ([fm fileExistsAtPath:nw]) { LOG("iCloud 同步:saves_v2 已由别的设备建好,用它"); return 1; } // 两台同时迁:后改名的那台失败,用先到的那套 | Two devices migrating at once: the one that renames later fails and uses the set that arrived first
LOG("【红】iCloud 同步:旧目录 saves 复制到 saves_v2 失败(%s),本次不同步", (err ?: e2).localizedDescription.UTF8String ?: "?"); return 0; }
LOG("iCloud 同步:旧目录 saves 已复制到 saves_v2(%d 个文件,清单 %lu 个包),旧目录留给旧包用", copied, (unsigned long)[list componentsSeparatedByString:@"\n"].count - 1); return 1;
}
void dm_cloud_boot(void) {
const char *sv = getenv("DM_SAVE"), *sub = getenv("DM_TEST_ICLOUD_SUB"), *ldir = getenv("DM_TEST_ICLOUD_DIR"), *lroot = getenv("DM_TEST_ICLOUD_ROOT"); if (!sv) return;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *save = @(sv); int real = [save.stringByStandardizingPath isEqualToString:[doc stringByAppendingPathComponent:@"save"].stringByStandardizingPath];
int off = getenv("DM_TEST_ICLOUD_OFF") != NULL; // 测试总闸:脚本起的局一律带它(tools/cloud_guard.sh),整局不同步 | Test master gate: runs launched by scripts always carry it (tools/cloud_guard.sh), and the whole run does not sync
if (!real && !sub && !ldir && !lroot) { if (off) LOG("iCloud 同步:测试开关 DM_TEST_ICLOUD_OFF,本局不同步"); return; } // 测试存档:不同步 | Test save: not synced
// Mac 上跑的 iOS 包:缺省整个不连真实 iCloud。这个包只发 iPhone / iPad,Mac 上跑的全是开发与测试;开发机登着真实账号时,
// 它就是那个账号的又一台设备,任何脚本、手点图标都会和真实云端双向同步(出过把测试存档传进真实云端)。本地测试云端(DIR / ROOT)不受影响;
// 真要在 Mac 上连真实云端:同时给 DM_REAL_ICLOUD=1 与 DM_REAL_ICLOUD_CONFIRM=写入真实云端。真机不走这一支。
// iOS app running on a Mac: by default it does not connect to real iCloud at all. This package ships only for iPhone / iPad, and everything run on a Mac is development and testing; when the development machine is signed in to a real account,
// it is one more device of that account, and any script or a tap on the icon would sync both ways with the real cloud (test saves have been uploaded to the real cloud before). The local test cloud (DIR / ROOT) is unaffected;
// to really connect to the real cloud on a Mac: give both DM_REAL_ICLOUD=1 and DM_REAL_ICLOUD_CONFIRM=写入真实云端. Real devices do not take this branch.
if (NSProcessInfo.processInfo.isiOSAppOnMac && !ldir && !lroot) { const char *r1 = getenv("DM_REAL_ICLOUD"), *r2 = getenv("DM_REAL_ICLOUD_CONFIRM");
if (!(r1 && !strcmp(r1, "1") && r2 && !strcmp(r2, "写入真实云端"))) { LOG("iCloud 同步:Mac 上运行:缺省不同步 iCloud"); return; }
LOG("【红】iCloud 同步:Mac 上运行,已显式放开(DM_REAL_ICLOUD):本局连真实云端"); }
if (off) { LOG("iCloud 同步:测试开关 DM_TEST_ICLOUD_OFF,本局不同步"); return; }
if (!dm_custom_get("icloud")) { LOG("iCloud 同步:自定义页已关,不同步"); return; }
double t0 = CFAbsoluteTimeGetCurrent(), limit = 5.0;
if (ldir) g_cloud = test_path(ldir); // 测试:本地目录当云端(没有 iCloud 权限的开发包也能验整条链) | Test: use a local directory as the cloud (a dev build without iCloud entitlement can also verify the whole chain)
else if (sub) { NSURL *ct = container(limit); if (!ct) return; g_cloud = [[ct.path stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@(sub)]; }
else { NSString *docs = test_path(lroot); if (!lroot) { NSURL *ct = container(limit); if (!ct) return; docs = [ct.path stringByAppendingPathComponent:@"Documents"]; }
if (!migrate_v2(docs, t0 + limit)) return;
NSString *nw = [docs stringByAppendingPathComponent:@"saves_v2"]; if (!v2_ready(nw, [save stringByAppendingString:@".cloudv2ok"])) return;
g_cloud = nw; }
[NSFileManager.defaultManager createDirectoryAtPath:g_cloud withIntermediateDirectories:YES attributes:nil error:nil];
g_save = save; g_bak = [save stringByAppendingString:@".cloudbak"]; g_state = [save stringByAppendingString:@".cloudstate"];
if (ldir) { g_bak = [g_cloud stringByAppendingString:@".cloudbak"]; g_state = [g_cloud stringByAppendingString:@".cloudstate"]; } // 测试的本地云端:状态与备份跟云端目录走,不与真存档(同一路径、连真实 iCloud 时)共用——共用的话测试局会改写真存档的同步状态 | Local cloud for tests: state and backup follow the cloud directory and are not shared with the real save (same path, when connected to real iCloud) -- if shared, test runs would rewrite the real save's sync state
g_q = dispatch_queue_create("dm.cloud", DISPATCH_QUEUE_SERIAL);
for (NSString *f in [NSFileManager.defaultManager contentsOfDirectoryAtPath:save.stringByDeletingLastPathComponent error:nil] ?: @[]) // 上次被杀时没删掉的提交快照 | Commit snapshots not deleted when we were last killed
if ([f hasPrefix:[save.lastPathComponent stringByAppendingString:@".cloudsnap"]]) [NSFileManager.defaultManager removeItemAtPath:[save.stringByDeletingLastPathComponent stringByAppendingPathComponent:f] error:nil];
int pend = pending_downloads(1);
while (pend && CFAbsoluteTimeGetCurrent() - t0 < limit) { usleep(100000); pend = pending_downloads(0); }
int n = run_sync(save, 1);
LOG("iCloud 同步:启动 %.0f ms,动作 %d 个%s(云端目录 %s)", (CFAbsoluteTimeGetCurrent() - t0) * 1000, n, pend ? [NSString stringWithFormat:@",%d 个包没等到下载完、本次跳过", pend].UTF8String : "", ldir ? "本地测试目录" : sub ? sub : "saves_v2");
g_dm_save_commit_hook = on_commit;
{ extern void (*g_dm_ingame_hook)(int); extern void (*g_dm_charsel_hook)(void); g_dm_ingame_hook = cloud_ingame; g_dm_charsel_hook = cloud_charsel; } // 进局记一局开始;回到前端 = 这一局结束,传一次 | Entering a run marks the start of a run; returning to the front end = this run has ended, upload once
}
+147
View File
@@ -0,0 +1,147 @@
// 手柄接入(原版 Switch 本来就是手柄操作,恢复手柄支持;复用原版手柄交互,不自己设计)。
// iOS GameController(MFi / Xbox / PS / Switch Pro)的扩展手柄 → 原版手柄输入(宿主 dm_pad_set,与触屏输入在游戏取手柄时合并)。
// 四个面键按键帽上印的字母对应:提示条写哪个字母,就按手柄上印着那个字母的键(提示条画的是 Switch 键帽,不跟手柄型号换图)。
// 任天堂手柄(Switch Pro、Joy-Con)与 Switch 原样一致;Xbox 手柄 = 下 A、右 B、左 X、上 Y;没有字母的(PS 等)和认不出类型的按 Xbox 的位置排(下方键 = 确认)。
// 规则与认手柄类型的办法在 host/dm_padmap.h(纯函数,宿主单测 t_padmap 核);连接时记一行日志写明这个手柄用哪种排法。
// (先前一律按 Switch 的位置排——右键确认——Xbox 手柄玩家照提示条「A 选择」按印着 A 的下方键,实际发的是 B,选角页选不了人。)
// 系统给的面键是按位置定的、不看键帽上的字(GCExtendedGamepad.h:buttonA 下、buttonB 右、buttonX 左、buttonY 上);玩家在系统设置里改过键位的,系统已先换好再给我们。
// 任天堂手柄上系统给的是不是同样按位置(印 A 的右键 = buttonB),没有实体手柄实测过,依据只有头文件的约定。
// 肩键 L/R、扳机 ZL/ZR、摇杆按下 LS/RS、十字键、菜单键→+、选项键→-。
// 选项键(buttonOptions)有的手柄没有,那时减号没有来源:不拿 Home 键顶(头文件:系统不吃才轮到 App,靠不住),留空。Xbox 的视图键、PS 的分享 / 创建键、Switch Pro 的 − 都是选项键。
// 摇杆照原值换成 ±32767(GameController 与原版都是上为正)。
//
// 谁接管(谁有明确输入谁接管,不因漂移来回切):
// · 手柄「明确输入」= 按下任何一颗键,或把摇杆从中位推出来。摇杆带迟滞:推过 25% 才算推出,回到 15% 以内才算回中——停在阈值附近的漂移不会一会儿算一会儿不算。
// · 手柄有明确输入 → 手柄模式(布局换原版手柄版);碰屏幕 → 触屏模式(前端调 dm_gamepad_touched)。
// · 碰过屏幕之后,摇杆要先回中、再推出来才重新接管:一直偏着的摇杆(漂移大的手柄)不会把布局又切回手柄版。按键随时接管。
// · 触屏模式下手柄摇杆的值不交给游戏(手柄连着放在一边、摇杆有点漂移,不该盖掉触屏摇杆);手柄模式下没推出来的摇杆给 0、推出来的给原值。
// · 游戏取手柄处(hle_hid.c fill):触屏摇杆有值就用触屏的,否则用手柄的。
// 多个手柄:每个手柄各存各的键和摇杆,交给游戏的是合起来的——键取或、每根摇杆取推得最远的那个。断开一个只拿掉它那一份,别的手柄按着的键不丢。
// 失活 / 进后台 / 来电(前端 front_ios_focus_event → dm_gamepad_reset):所有手柄的键和摇杆清零。回调只在值变化时来,按着键切走、在后台松开,回来不会补一次「松开」。
// Controller support (the original Switch game is controller-driven to begin with, so controller support is restored; the original controller
// interaction is reused, nothing is designed from scratch).
// The extended gamepad of iOS GameController (MFi / Xbox / PS / Switch Pro) -> the original controller input (host dm_pad_set, merged with
// touch input when the game reads the controller).
// The four face buttons are mapped by the letter printed on the button glyph: whichever letter the button legend shows, press the button
// with that letter printed on the controller (the button legend draws Switch glyphs and does not change images per controller model).
// Nintendo controllers (Switch Pro, Joy-Con) are identical to the Switch as is; Xbox controllers = bottom A, right B, left X, top Y;
// controllers with no letters (PS etc.) and unrecognized types are laid out by the Xbox positions (bottom button = confirm).
// The rule and the way the controller type is recognized are in host/dm_padmap.h (pure function, checked by the host unit test t_padmap);
// on connect one log line states which layout this controller uses.
// (Previously everything was laid out by the Switch positions -- right button confirms -- so an Xbox controller player following the legend
// bar's "A Select" pressed the bottom button printed A, B was actually sent, and no character could be selected on the character select page.)
// The face buttons given by the system are defined by position, not by the letter on the glyph (GCExtendedGamepad.h: buttonA bottom,
// buttonB right, buttonX left, buttonY top); if the player has remapped buttons in system settings, the system has already applied that
// before handing them to us.
// Whether the system also reports Nintendo controllers by position (the right button printed A = buttonB) has not been measured on a
// physical controller; the only basis is the convention in the header file.
// Shoulder buttons L/R, triggers ZL/ZR, stick clicks LS/RS, D-pad, menu button -> +, options button -> -.
// Some controllers have no options button (buttonOptions), and then minus has no source: the Home button is not used as a substitute
// (header file: the app only gets it when the system does not consume it, which is unreliable), so it is left empty. The Xbox view button,
// the PS share / create button and the Switch Pro - button are all the options button.
// Sticks are converted from their raw values to +/-32767 (up is positive in both GameController and the original game).
// Who takes over (whoever has explicit input takes over; no flipping back and forth because of drift):
// - Controller "explicit input" = pressing any button, or pushing a stick out of center. Sticks have hysteresis: only past 25% counts as
// pushed out, and only back within 15% counts as centered -- drift sitting near the threshold does not count one moment and not the next.
// - The controller has explicit input -> controller mode (the layout switches to the original controller layout); touching the screen ->
// touch mode (the front end calls dm_gamepad_touched).
// - After the screen has been touched, a stick must return to center and then be pushed out before it takes over again: a stick that stays
// deflected (a controller with heavy drift) will not flip the layout back to the controller layout. Buttons take over at any time.
// - In touch mode the controller stick values are not handed to the game (a connected controller lying aside with slight stick drift
// should not override the touch stick); in controller mode a stick that is not pushed out gives 0 and one that is pushed out gives the
// raw value.
// - Where the game reads the controller (hle_hid.c fill): if the touch stick has a value the touch one is used, otherwise the controller's.
// Multiple controllers: each controller keeps its own buttons and sticks, and what the game gets is the combination -- buttons are ORed, and
// for each stick the one pushed furthest wins. Disconnecting one removes only its share; buttons held on other controllers are not lost.
// Resign active / entering background / incoming call (front end front_ios_focus_event -> dm_gamepad_reset): buttons and sticks of all
// controllers are zeroed. Callbacks only arrive when a value changes, so after switching away with a button held and releasing it in the
// background, no "release" is delivered on return.
#import <GameController/GameController.h>
#include "dm_input.h"
#include "dm_padmap.h"
#include "hle.h"
static void (*g_on_mode)(int pad);
static int g_pad_mode, g_need_center;
void dm_padmode_request(int pad); // 宿主 dm_padmode.c:布局换成原版手柄版 / 触屏版 | Host dm_padmode.c: switch the layouts to the original controller version / the touch version
static void set_mode(int pad) { if (g_pad_mode == pad) return; g_pad_mode = pad; dm_padmode_request(pad); LOG("手柄:%s", pad ? "手柄有输入 → 手柄模式" : "碰了屏幕 / 手柄断开 → 触屏模式"); if (g_on_mode) g_on_mode(pad); }
int dm_gamepad_mode(void) { return g_pad_mode; }
// 各手柄各存各的(槽 0、1 留给触点脚本的两个虚拟手柄,其余给实体手柄)
// Each controller is stored separately (slots 0 and 1 are reserved for the touch script's two virtual controllers, the rest are for physical controllers)
enum { NSLOT = 6 };
static struct { const void *who; uint64_t b; int32_t ax[4]; } g_s[NSLOT];
static int slot_of(const void *who, int make) { int fr = -1; for (int i = 0; i < NSLOT; i++) { if (g_s[i].who == who) return i; if (fr < 0 && !g_s[i].who) fr = i; }
if (make && fr >= 0) { memset(&g_s[fr], 0, sizeof g_s[fr]); g_s[fr].who = who; return fr; } return -1; }
static int32_t axis(float v) { if (v > 1) v = 1; if (v < -1) v = -1; return (int32_t)lroundf(v * DM_STICK_MAX); }
static int stick_on(int was, int32_t x, int32_t y) { double m = hypot(x, y) / DM_STICK_MAX; return was ? m >= 0.15 : m >= 0.25; } // 迟滞:推过 25% 算推出,回到 15% 内算回中 | Hysteresis: past 25% counts as pushed out, back within 15% counts as centered
// 把各手柄合起来、定模式、交给宿主。任何一份变了都重算一遍
// Merge all controllers, decide the mode and hand the result to the host. Recompute whenever any one of them changes
static void apply(void) {
uint64_t b = 0; int32_t ax[4] = {0}; double best[2] = {0};
for (int i = 0; i < NSLOT; i++) { if (!g_s[i].who) continue; b |= g_s[i].b;
for (int k = 0; k < 2; k++) { double m = hypot(g_s[i].ax[2 * k], g_s[i].ax[2 * k + 1]); if (m > best[k]) { best[k] = m; ax[2 * k] = g_s[i].ax[2 * k]; ax[2 * k + 1] = g_s[i].ax[2 * k + 1]; } } }
static int on[2]; static uint64_t prev_b;
on[0] = stick_on(on[0], ax[0], ax[1]); on[1] = stick_on(on[1], ax[2], ax[3]);
if (!on[0] && !on[1]) g_need_center = 0; // 碰过屏幕后摇杆回过中了:之后再推出来算数 | The stick has returned to center since the screen was touched: pushing it out again from now on counts
if ((b & ~prev_b) || ((on[0] || on[1]) && !g_need_center)) set_mode(1);
prev_b = b;
if (!g_pad_mode || !on[0]) ax[0] = ax[1] = 0; if (!g_pad_mode || !on[1]) ax[2] = ax[3] = 0; // 触屏模式不交摇杆;手柄模式下没推出来的给 0 | Sticks are not delivered in touch mode; in controller mode a stick that is not pushed out gives 0
// ZR:原版六个技能格之一。这一格空着(没绑技能)时按它 = 免费回城(手柄玩家也免费回城,与触屏回城钮一致);绑了技能就整颗交还原版(不再整颗占用)。
// 想把回城放在别的键上:原版选技能界面「综合技能」里有回城技能可绑(宿主进局时挂上的,dm_freetp.c),那条走原版自己的施放,不经这里。
// 只在游戏态接管:面板开着时 ZR 照常交给原版(储藏箱 / 编年史用 ZL / ZR 翻页签);按下时在游戏态接管的那一下,到松开前都不交给游戏
// ZR: one of the six original skill slots. While this slot is empty (no skill bound), pressing it = free town portal (controller players get
// the free town portal too, consistent with the touch town portal button); once a skill is bound the whole button is handed back to the
// original game (we no longer claim the whole button).
// To put town portal on another key: the original skill selection screen has a town portal skill under "General Skills" that can be bound
// (attached by the host on joining a run, dm_freetp.c); that one goes through the original game's own cast and does not pass through here.
// Taken over only in game state: with a panel open ZR goes to the original game as usual (the stash / Chronicle use ZL / ZR to switch tabs);
// a press that was taken over in game state is not handed to the game until it is released
{ static uint64_t prev; static int mine; void dm_tp_request(void); int dm_front_navigation(void), dm_freetp_zr_free(int zl);
if ((b & DM_BTN_ZR) && !(prev & DM_BTN_ZR)) { mine = !dm_front_navigation() && dm_freetp_zr_free((b & DM_BTN_ZL) != 0); if (mine) { dm_tp_request(); LOG("手柄:ZR(这一格空着)→ 免费回城"); } }
prev = b; if (mine) b &= ~(uint64_t)DM_BTN_ZR; if (!(b & DM_BTN_ZR) && !(prev & DM_BTN_ZR)) mine = 0; }
dm_pad_set(b, ax[0], ax[1], ax[2], ax[3]);
}
static void put(const void *who, uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {
int i = slot_of(who, 1); if (i < 0) return; g_s[i].b = b; g_s[i].ax[0] = lx; g_s[i].ax[1] = ly; g_s[i].ax[2] = rx; g_s[i].ax[3] = ry; apply();
}
static void drop(const void *who) { // 这个手柄没了:只拿掉它那一份;一个手柄都不剩才回触屏模式 | This controller is gone: remove only its share; return to touch mode only when no controller is left
int i = slot_of(who, 0); if (i < 0) return; memset(&g_s[i], 0, sizeof g_s[i]); apply();
for (int k = 0; k < NSLOT; k++) if (g_s[k].who) return;
set_mode(0);
}
void dm_gamepad_touched(void) { if (g_pad_mode) { g_need_center = 1; set_mode(0); apply(); } } // 前端:碰了屏幕。摇杆此刻偏着的话要先回中才重新接管 | Front end: the screen was touched. If a stick is deflected right now it must return to center before taking over again
void dm_gamepad_reset(void) { // 前端:失活 / 进后台 / 来电 | Front end: resign active / enter background / incoming call
int any = 0; for (int i = 0; i < NSLOT; i++) if (g_s[i].who) { any |= g_s[i].b != 0 || g_s[i].ax[0] || g_s[i].ax[1] || g_s[i].ax[2] || g_s[i].ax[3]; g_s[i].b = 0; memset(g_s[i].ax, 0, sizeof g_s[i].ax); }
if (any) { LOG("手柄:失活,手柄的键和摇杆清零"); apply(); }
}
// 测试(触点脚本 pad / pad2 / padoff / padoff2 步):没有实体手柄时走同一条路,只少了 GameController 回调那一层。n = 1 或 2:两个虚拟手柄
// Test (touch script pad / pad2 / padoff / padoff2 steps): without a physical controller the same path is taken, minus only the GameController callback
// layer. n = 1 or 2: two virtual controllers
void dm_gamepad_inject_n(int n, uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) { put((const void *)(intptr_t)(n == 2 ? 2 : 1), b, lx, ly, rx, ry); }
void dm_gamepad_drop_n(int n) { LOG("手柄:断开(虚拟手柄 %d)", n == 2 ? 2 : 1); drop((const void *)(intptr_t)(n == 2 ? 2 : 1)); }
void dm_gamepad_inject(uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) { dm_gamepad_inject_n(1, b, lx, ly, rx, ry); }
static void publish(GCController *c, GCExtendedGamepad *g) {
uint64_t b = 0;
b |= dm_padmap_face(dm_padmap_kind(c.productCategory.UTF8String, c.vendorName.UTF8String), g.buttonA.pressed, g.buttonB.pressed, g.buttonX.pressed, g.buttonY.pressed); // 按键帽上的字母(dm_padmap.h) | By the letter on the button glyph (dm_padmap.h)
if (g.leftShoulder.pressed) b |= DM_BTN_L; if (g.rightShoulder.pressed) b |= DM_BTN_R; if (g.leftTrigger.pressed) b |= DM_BTN_ZL; if (g.rightTrigger.pressed) b |= DM_BTN_ZR;
if (g.leftThumbstickButton.pressed) b |= DM_BTN_LS; if (g.rightThumbstickButton.pressed) b |= DM_BTN_RS;
if (g.buttonMenu.pressed) b |= DM_BTN_PLUS; if (g.buttonOptions.pressed) b |= DM_BTN_MINUS;
if (g.dpad.left.pressed) b |= DM_BTN_LEFT; if (g.dpad.up.pressed) b |= DM_BTN_UP; if (g.dpad.right.pressed) b |= DM_BTN_RIGHT; if (g.dpad.down.pressed) b |= DM_BTN_DOWN;
put((__bridge const void *)c, b, axis(g.leftThumbstick.xAxis.value), axis(g.leftThumbstick.yAxis.value), axis(g.rightThumbstick.xAxis.value), axis(g.rightThumbstick.yAxis.value));
}
static void attach(GCController *c) {
GCExtendedGamepad *g = c.extendedGamepad; if (!g) { LOG("手柄:%s 不是扩展手柄,不接", c.vendorName.UTF8String ?: "?"); return; }
LOG("手柄:连上 %s,类别 %s → 面键用 %s 排法", c.vendorName.UTF8String ?: "?", c.productCategory.UTF8String ?: "?", dm_padmap_kind(c.productCategory.UTF8String, c.vendorName.UTF8String) == DM_PADKIND_NINTENDO ? "任天堂(右 A、下 B、上 X、左 Y)" : "Xbox(下 A、右 B、左 X、上 Y)");
__weak GCController *wc = c;
g.valueChangedHandler = ^(GCExtendedGamepad *gp, GCControllerElement *el) { (void)el; GCController *sc = wc; if (sc) publish(sc, gp); };
}
void dm_gamepad_start(void (*on_mode)(int pad)) {
g_on_mode = on_mode;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserverForName:GCControllerDidConnectNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *n) { attach(n.object); }];
[nc addObserverForName:GCControllerDidDisconnectNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *n) {
LOG("手柄:断开 %s", ((GCController *)n.object).vendorName.UTF8String ?: "?"); drop((__bridge const void *)n.object); }];
for (GCController *c in GCController.controllers) attach(c);
}
+41
View File
@@ -0,0 +1,41 @@
#include "dm_metal_cache_guard.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int has_parent_component(const char *path) {
const char *cursor = path;
while (*cursor) {
while (*cursor == '/') cursor++;
const char *start = cursor;
while (*cursor && *cursor != '/') cursor++;
if ((size_t)(cursor - start) == 2 && !strncmp(start, "..", 2)) return 1;
}
return 0;
}
static int under(const char *path, const char *directory) {
size_t length = strlen(directory);
return strlen(path) > length && !strncmp(path, directory, length) && path[length] == '/';
}
int dm_metal_cache_path_allowed(const char *container_root, const char *target_path) {
char root[PATH_MAX], target[PATH_MAX], caches[PATH_MAX], temporary[PATH_MAX];
if (!container_root || !target_path || container_root[0] != '/' || target_path[0] != '/' ||
has_parent_component(container_root) || has_parent_component(target_path)) return 0;
if (!realpath(container_root, root) || !realpath(target_path, target)) return 0;
if (!strcmp(root, target)) return 0;
size_t prefix_length = strlen(container_root);
while (prefix_length > 1 && container_root[prefix_length - 1] == '/') prefix_length--;
if (strlen(target_path) <= prefix_length || strncmp(target_path, container_root, prefix_length)) return 0;
const char *relative = target_path + prefix_length;
if (strncmp(relative, "/Library/Caches/", strlen("/Library/Caches/")) &&
strncmp(relative, "/tmp/", strlen("/tmp/"))) return 0;
int caches_length = snprintf(caches, sizeof caches, "%s/Library/Caches", root);
int temporary_length = snprintf(temporary, sizeof temporary, "%s/tmp", root);
if (caches_length < 0 || (size_t)caches_length >= sizeof caches ||
temporary_length < 0 || (size_t)temporary_length >= sizeof temporary) return 0;
return under(target, caches) || under(target, temporary);
}
+6
View File
@@ -0,0 +1,6 @@
#ifndef DM_METAL_CACHE_GUARD_H
#define DM_METAL_CACHE_GUARD_H
int dm_metal_cache_path_allowed(const char *container_root, const char *target_path);
#endif
+89
View File
@@ -0,0 +1,89 @@
// 秘境爬塔左侧任务栏:放在左边并缩小,布局参考暗黑 3 右侧任务栏,倒计时条和整体风格按暗黑 2。
// 尺寸数字照设计稿:设计稿按 Mac 窗口 2 倍像素画(游戏区 1334×614),
// 这里以 u = 游戏区高 / 614 为单位换算。数据由 dm/host/dm_rift.c 出(dm_rift_hud),前端每帧调(front_ios.m tickTouchControls)。
// 字:原版 BlizzardGlobal——运行时从资源包读出来注册(不进仓库、不进 App 包);读不到就用系统粗体。
// 资源包读法同 dm/ios/tools/touch_layout.py read_layout:data/build_manifest.psv 按路径后缀找行 → 第 7 列编码键(第 10、11 字节 = 数据档号,12–16 = 偏移)、
// 第 8 列原始长度、第 9 列编码(n 原样 / z 整块 zlib / 其余 BLTE 分块:每块首字节 N 原样、Z = zlib)。
// Left-side quest bar for the rift tower climb: placed on the left and shrunk; the layout follows Diablo 3's right-side quest bar, the countdown bar and overall style follow Diablo 2.
// Size numbers follow the design mock: the mock is drawn at 2x pixels of the Mac window (game area 1334×614),
// and here everything is converted with u = game area height / 614 as the unit. Data comes from dm/host/dm_rift.c (dm_rift_hud); the front end calls it every frame (front_ios.m tickTouchControls).
// Font: the original game's BlizzardGlobal -- read from the asset pack at runtime and registered (not in the repository, not in the App bundle); if it cannot be read, use the system bold font.
// The asset pack is read the same way as dm/ios/tools/touch_layout.py read_layout: find the row in data/build_manifest.psv by path suffix → column 7 is the encoding key (bytes 10 and 11 = data archive number, 12–16 = offset),
// column 8 the raw length, column 9 the encoding (n as-is / z whole-block zlib / otherwise BLTE chunks: first byte of each chunk N as-is, Z = zlib).
#import <UIKit/UIKit.h>
#include "dm_i18n.h"
#import <CoreText/CoreText.h>
#include "../../host/dm_rift.h"
static NSData *zinflate(const uint8_t *p, size_t n, size_t cap) { // zlib(带 2 字节头)→ 原文;Foundation 的 Zlib 算法是裸 deflate,跳过头 | zlib (with 2-byte header) → plaintext; Foundation's Zlib algorithm is raw deflate, so skip the header
(void)cap; if (n < 2) return nil; return [[NSData dataWithBytes:p + 2 length:n - 2] decompressedDataUsingAlgorithm:NSDataCompressionAlgorithmZlib error:nil];
}
static NSData *romfs_file(NSString *suffix) {
const char *root = getenv("DM_ROMFS"); if (!root) return nil;
NSString *data = [@(root) stringByAppendingPathComponent:@"data"], *psv = [NSString stringWithContentsOfFile:[data stringByAppendingPathComponent:@"build_manifest.psv"] encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [psv componentsSeparatedByString:@"\n"]) { NSArray<NSString *> *f = [line componentsSeparatedByString:@"|"];
if (f.count < 11 || [line hasPrefix:@"#"] || ![f[9].lowercaseString hasSuffix:suffix]) continue;
NSString *ek = f[6]; if (ek.length < 32) return nil; uint8_t k[16]; for (int i = 0; i < 16; i++) k[i] = (uint8_t)strtol([[ek substringWithRange:NSMakeRange(i * 2, 2)] UTF8String], NULL, 16);
uint64_t off = 0; for (int i = 11; i < 16; i++) off = off << 8 | k[i]; long rawlen = f[7].longLongValue;
NSFileHandle *h = [NSFileHandle fileHandleForReadingAtPath:[data stringByAppendingPathComponent:[NSString stringWithFormat:@"%02d-%08d.data", k[9], k[10]]]]; if (!h) return nil;
[h seekToFileOffset:off]; NSData *raw = [h readDataOfLength:rawlen]; [h closeFile]; const uint8_t *r = raw.bytes; if ((long)raw.length != rawlen) return nil;
if ([f[8] isEqualToString:@"n"]) return raw;
if ([f[8] isEqualToString:@"z"]) return zinflate(r, raw.length, 64 << 20);
uint32_t hs = (uint32_t)r[4] << 24 | r[5] << 16 | r[6] << 8 | r[7], nch = (uint32_t)r[9] << 16 | r[10] << 8 | r[11], pos = hs; NSMutableData *o = [NSMutableData data];
for (uint32_t i = 0; i < nch; i++) { const uint8_t *e = r + 12 + i * 24; uint32_t es = (uint32_t)e[0] << 24 | e[1] << 16 | e[2] << 8 | e[3], ds = (uint32_t)e[4] << 24 | e[5] << 16 | e[6] << 8 | e[7];
if (pos + es > raw.length) return nil; const uint8_t *b = r + pos;
if (b[0] == 'N') [o appendBytes:b + 1 length:es - 1]; else { NSData *d = zinflate(b + 1, es - 1, ds); if (!d) return nil; [o appendData:d]; } pos += es; }
return o; }
return nil;
}
static UIFont *d2font(CGFloat size) { // 原版 BlizzardGlobal(中文、数字都是它) | The original game's BlizzardGlobal (used for both Chinese text and digits)
static NSString *name; static int tried;
if (!tried) { tried = 1; NSData *d = romfs_file(@"/hd/ui/fonts/blizzardglobal-v5_81.ttf");
CGDataProviderRef p = d ? CGDataProviderCreateWithCFData((__bridge CFDataRef)d) : NULL; CGFontRef f = p ? CGFontCreateWithDataProvider(p) : NULL;
if (f && CTFontManagerRegisterGraphicsFont(f, NULL)) name = (__bridge_transfer NSString *)CGFontCopyPostScriptName(f);
if (f) CGFontRelease(f); if (p) CGDataProviderRelease(p);
NSLog(@"[秘境] 任务栏字体:%@", name ?: @"读不到原版 BlizzardGlobal,用系统粗体"); }
return (name ? [UIFont fontWithName:name size:size] : nil) ?: [UIFont boldSystemFontOfSize:size];
}
static UIColor *rgb(int r, int g, int b, CGFloat a) { return [UIColor colorWithRed:r / 255.0 green:g / 255.0 blue:b / 255.0 alpha:a]; }
static CATextLayer *text_layer(void) { CATextLayer *t = [CATextLayer layer]; t.contentsScale = UIScreen.mainScreen.scale; t.shadowOpacity = 0.86; t.shadowOffset = CGSizeMake(1, 1); t.shadowRadius = 0; t.shadowColor = UIColor.blackColor.CGColor; return t; }
static void set_text(CATextLayer *t, NSString *s, UIFont *f, UIColor *c, CGRect fr, NSString *align) {
t.frame = fr; t.alignmentMode = align; t.foregroundColor = c.CGColor; t.font = (__bridge CFTypeRef)f; t.fontSize = f.pointSize;
if (![t.string isEqual:s]) t.string = s;
}
void dm_rift_hud_draw(UIView *host, CGRect wr, BOOL hide) {
static CALayer *box, *lineT, *lineB, *lineL, *track, *ticks[9]; static CAGradientLayer *fill; static CAShapeLayer *pin[2]; static CATextLayer *title, *sub, *timer, *goal;
dm_rift_hud_t h; int on = !hide && dm_rift_hud(&h);
if (!box) { if (!on) return;
box = [CALayer layer]; box.backgroundColor = rgb(0, 0, 0, 170 / 255.0).CGColor;
lineT = [CALayer layer]; lineB = [CALayer layer]; lineL = [CALayer layer]; track = [CALayer layer]; fill = [CAGradientLayer layer];
title = text_layer(); sub = text_layer(); timer = text_layer(); goal = text_layer();
for (CALayer *l in @[lineT, lineB, lineL, title, sub, timer, goal, track]) [box addSublayer:l];
[track addSublayer:fill]; for (int i = 0; i < 9; i++) { ticks[i] = [CALayer layer]; ticks[i].backgroundColor = rgb(0, 0, 0, 110 / 255.0).CGColor; [track addSublayer:ticks[i]]; }
for (int i = 0; i < 2; i++) { pin[i] = [CAShapeLayer layer]; pin[i].fillColor = rgb(160, 135, 80, 1).CGColor; pin[i].strokeColor = rgb(60, 48, 30, 1).CGColor; [box addSublayer:pin[i]]; }
[host.layer addSublayer:box]; }
[CATransaction begin]; [CATransaction setDisableActions:YES];
box.hidden = !on;
if (on) {
CGFloat u = wr.size.height / 614, W = 250 * u, H = 78 * u;
box.frame = CGRectMake(wr.origin.x + 28 * u, wr.origin.y + 150 * u, W, H);
lineT.frame = CGRectMake(0, 0, W, MAX(1, u)); lineB.frame = CGRectMake(0, H - MAX(1, u), W, MAX(1, u)); lineL.frame = CGRectMake(0, 0, 2 * u, H);
lineT.backgroundColor = lineB.backgroundColor = rgb(120, 100, 60, 0.9).CGColor; lineL.backgroundColor = rgb(150, 125, 75, 1).CGColor;
int g = h.guardian, s = h.secs_left < 0 ? 0 : h.secs_left; UIColor *gold = rgb(199, 179, 119, 1), *red = rgb(200, 50, 40, 1), *white = rgb(215, 210, 200, 1), *grey = rgb(150, 145, 135, 1);
set_text(title, @(dm_ui("dmRiftHudTitle")), d2font(17 * u), g ? red : gold, CGRectMake(10 * u, 6 * u, 40 * u, 22 * u), kCAAlignmentLeft);
NSString *st = h.done ? (h.inc ? [NSString stringWithFormat:@(dm_ui("dmRiftHudDone")), h.tier] : [NSString stringWithFormat:@(dm_ui("dmRiftHudLate")), h.tier]) : g ? @(dm_ui("dmRiftHudGuard")) : [NSString stringWithFormat:@(dm_ui("dmRiftTierN")), h.tier];
set_text(sub, st, d2font(14 * u), white, CGRectMake(48 * u, 9 * u, 130 * u, 19 * u), kCAAlignmentLeft);
set_text(timer, [NSString stringWithFormat:@"%d:%02d", s / 60, s % 60], d2font(17 * u), (s <= 60 && !h.done) ? red : gold, CGRectMake(W - 90 * u, 6 * u, 80 * u, 22 * u), kCAAlignmentRight);
NSString *gl = h.done ? (h.inc ? [NSString stringWithFormat:@(dm_ui("dmRiftHudNext")), h.tier + h.inc] : @(dm_ui("dmRiftHudSame"))) : g ? @(dm_ui("dmRiftHudKill")) : [NSString stringWithFormat:@(dm_ui("dmRiftHudGoal")), (int)(h.progress * 100)];
set_text(goal, gl, d2font(12 * u), grey, CGRectMake(10 * u, 32 * u, W - 20 * u, 17 * u), kCAAlignmentLeft);
CGRect tr = CGRectMake(11 * u, 55 * u, W - 22 * u, 10 * u); // 含 1 单位外框(条 8 + 外框各 1) // 进度条:外框暗边 + 深底,填充金褐(守护者转暗红),每 10% 一道刻痕,两端菱形钉 | Includes the 1-unit outer frame (bar 8 + frame 1 on each side) // Progress bar: dark-edged outer frame + deep background, golden-brown fill (turns dark red for the guardian), a notch every 10%, diamond studs at both ends
track.frame = tr; track.backgroundColor = rgb(25, 20, 14, 1).CGColor; track.borderColor = rgb(95, 78, 48, 1).CGColor; track.borderWidth = MAX(1, u);
CGFloat bw = MAX(1, u); fill.frame = CGRectMake(bw, bw, (tr.size.width - 2 * bw) * (h.done ? 1 : h.progress), tr.size.height - 2 * bw);
fill.colors = g ? @[(id)rgb(190, 50, 40, 1).CGColor, (id)rgb(110, 20, 15, 1).CGColor] : @[(id)rgb(205, 160, 80, 1).CGColor, (id)rgb(140, 100, 40, 1).CGColor];
for (int i = 0; i < 9; i++) ticks[i].frame = CGRectMake(bw + (tr.size.width - 2 * bw) * (i + 1) / 10, bw, MAX(1, u), tr.size.height - 2 * bw);
for (int i = 0; i < 2; i++) { CGFloat cx = i ? tr.origin.x + tr.size.width + 4 * u : tr.origin.x - 4 * u, cy = CGRectGetMidY(tr), r = 4 * u; UIBezierPath *p = [UIBezierPath bezierPath];
[p moveToPoint:CGPointMake(cx, cy - r)]; [p addLineToPoint:CGPointMake(cx + r, cy)]; [p addLineToPoint:CGPointMake(cx, cy + r)]; [p addLineToPoint:CGPointMake(cx - r, cy)]; [p closePath]; pin[i].path = p.CGPath; pin[i].lineWidth = MAX(1, u * 0.8); }
}
[CATransaction commit];
}
+90
View File
@@ -0,0 +1,90 @@
// 壳专用(不含游戏内容的公开版安装包,tools/shell_build.sh):首次启动把全部着色器一次编完,带进度。内测 / 自己用 Xcode 构建的包不编这个文件的内容。
// 为什么要有:使用者的电脑上没有苹果的着色器编译器时,着色器是以源码放进安装包的(tools/d2rm_pack.py、gfx/tools/nometal_run.py),
// 设备上用到哪个现编哪个。真机实测:平均约 80 毫秒一个、单个最长约 450 毫秒;边玩边编的话第一次进一个新场景会顿约 0.8 秒
// (编好的库同一处是 0.12 秒)。所以改成进主菜单之前一次编完——系统会把编好的结果缓存,之后游戏里再建同一个库不花时间。
// 做完的记号放在 Library/Caches(和系统的着色器缓存在同一处,系统清缓存时一起没,下次启动自动重做一遍)。
// 中途切到后台 / 被杀:已编的在系统缓存里,回来从头数一遍,已编的每个只要不到 1 毫秒,等于接着做。
// Shell only (the public install package with no game content, tools/shell_build.sh): on first launch compile all shaders in one go, with progress. Beta packages / packages you build yourself with Xcode do not compile this file's contents.
// Why it exists: when the user's computer has no Apple shader compiler, the shaders are put into the install package as source (tools/d2rm_pack.py, gfx/tools/nometal_run.py),
// and each is compiled on the device when it is first used. Measured on a real device: about 80 ms each on average, about 450 ms for the longest single one; compiling while playing, the first entry into a new scene stutters for about 0.8 seconds
// (0.12 seconds at the same spot with compiled libraries). So it is changed to compiling everything once before entering the main menu -- the system caches the compiled results, and building the same library again in the game afterwards takes no time.
// The completion marker is placed in Library/Caches (the same place as the system's shader cache, so it goes away together when the system clears caches, and the next launch automatically redoes it once).
// Sent to the background / killed midway: what was compiled is in the system cache; on return it counts from the start, each already compiled one taking less than 1 ms, which amounts to resuming.
#ifdef DM_SHELL
#import <Metal/Metal.h>
#import <UIKit/UIKit.h>
#include <stdatomic.h>
#include <stdio.h>
#include <string.h>
static void pl(NSString *s) { fprintf(stderr, "[dm] %s\n", s.UTF8String); }
static BOOL zh(void) { return [NSLocale.preferredLanguages.firstObject hasPrefix:@"zh"]; }
static NSString *libdir(void) { // <包>/msl/b-<链版本>:壳里只有一个版本目录 | <package>/msl/b-<chain version>: the shell has only one version directory
NSString *msl = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"msl"];
for (NSString *d in [NSFileManager.defaultManager contentsOfDirectoryAtPath:msl error:nil] ?: @[]) if ([d hasPrefix:@"b-"]) return [msl stringByAppendingPathComponent:d];
return nil;
}
static NSString *marker(NSString *dir) {
NSString *c = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
return [c stringByAppendingPathComponent:[NSString stringWithFormat:@"dm_shader_prep_%@_%@.done", dir.lastPathComponent, NSProcessInfo.processInfo.operatingSystemVersionString.length ? @(NSProcessInfo.processInfo.operatingSystemVersion.majorVersion * 100 + NSProcessInfo.processInfo.operatingSystemVersion.minorVersion).stringValue : @"0"]];
}
static BOOL is_source(NSString *path) { // 编好的库以 MTLB 开头;不是的就是源码 | a compiled library starts with MTLB; anything else is source
FILE *f = fopen(path.fileSystemRepresentation, "rb"); if (!f) return NO; char h[4] = {0}; size_t n = fread(h, 1, 4, f); fclose(f);
return n == 4 && memcmp(h, "MTLB", 4) != 0;
}
// 要不要做:返回 1 = 已接手(显示进度页,做完调 done);0 = 不用做(没有源码着色器,或上次已经做完)
// Whether it needs to run: returns 1 = taken over (shows the progress page, calls done when finished); 0 = nothing to do (no source shaders, or already finished last time)
int dm_shader_prep_begin(void (^done)(void)) {
NSString *dir = libdir(); if (!dir) return 0;
NSString *mk = marker(dir); if ([NSFileManager.defaultManager fileExistsAtPath:mk]) return 0;
NSMutableArray<NSString *> *src = [NSMutableArray array];
for (NSString *f in [[NSFileManager.defaultManager contentsOfDirectoryAtPath:dir error:nil] sortedArrayUsingSelector:@selector(compare:)] ?: @[])
if ([f hasSuffix:@".metallib"] && is_source([dir stringByAppendingPathComponent:f])) [src addObject:[dir stringByAppendingPathComponent:f]];
if (!src.count) return 0;
UIWindow *win = nil;
for (UIScene *s in UIApplication.sharedApplication.connectedScenes) if ([s isKindOfClass:UIWindowScene.class]) for (UIWindow *w in ((UIWindowScene *)s).windows) if (!win || w.isKeyWindow) win = w;
UIView *host = win.rootViewController.view ?: win; if (!host) { pl(@"【红】着色器准备:没有窗口可放进度页,跳过(进游戏后会边玩边编,第一次进新场景会顿)"); return 0; }
UIView *v = [[UIView alloc] initWithFrame:host.bounds]; v.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; v.backgroundColor = UIColor.blackColor;
UILabel *title = [UILabel new], *sub = [UILabel new], *note = [UILabel new]; UIProgressView *bar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
for (UILabel *l in @[title, sub, note]) { l.textColor = [UIColor colorWithWhite:0.85 alpha:1]; l.textAlignment = NSTextAlignmentCenter; l.numberOfLines = 0; l.translatesAutoresizingMaskIntoConstraints = NO; [v addSubview:l]; }
title.font = [UIFont systemFontOfSize:20 weight:UIFontWeightSemibold]; sub.font = [UIFont monospacedDigitSystemFontOfSize:15 weight:UIFontWeightRegular]; note.font = [UIFont systemFontOfSize:13]; note.textColor = [UIColor colorWithWhite:0.6 alpha:1];
bar.translatesAutoresizingMaskIntoConstraints = NO; bar.progressTintColor = [UIColor colorWithRed:0.78 green:0.36 blue:0.16 alpha:1]; [v addSubview:bar];
title.text = zh() ? @"首次启动:正在准备着色器" : @"First launch: preparing shaders";
note.text = zh() ? @"只需要做这一次,做完以后游戏里不会因为着色器卡顿。\n系统更新或重装之后会再做一次。可以切到后台,回来接着做。"
: @"This is only needed once; afterwards the game will not stutter because of shaders.\nIt runs again after a system update or a reinstall. You can switch away and it continues when you come back.";
[NSLayoutConstraint activateConstraints:@[
[title.centerXAnchor constraintEqualToAnchor:v.centerXAnchor], [title.bottomAnchor constraintEqualToAnchor:bar.topAnchor constant:-22],
[bar.centerXAnchor constraintEqualToAnchor:v.centerXAnchor], [bar.centerYAnchor constraintEqualToAnchor:v.centerYAnchor], [bar.widthAnchor constraintEqualToAnchor:v.widthAnchor multiplier:0.5],
[sub.centerXAnchor constraintEqualToAnchor:v.centerXAnchor], [sub.topAnchor constraintEqualToAnchor:bar.bottomAnchor constant:14],
[note.centerXAnchor constraintEqualToAnchor:v.centerXAnchor], [note.topAnchor constraintEqualToAnchor:sub.bottomAnchor constant:22], [note.widthAnchor constraintLessThanOrEqualToAnchor:v.widthAnchor multiplier:0.8]]];
[host addSubview:v];
UIApplication.sharedApplication.idleTimerDisabled = YES; // 这几分钟别自动锁屏 | do not auto-lock the screen during these few minutes
int total = (int)src.count, threads = (int)MAX(2, MIN(6, (NSInteger)NSProcessInfo.processInfo.activeProcessorCount - 2));
const char *te = getenv("DM_SHADER_PREP_THREADS"); if (te && atoi(te) > 0) threads = atoi(te); // 测试开关:指定并行数 | test switch: set the degree of parallelism
pl([NSString stringWithFormat:@"着色器准备:开始,共 %d 个,%d 线程", total, threads]);
CFAbsoluteTime t0 = CFAbsoluteTimeGetCurrent(); __block _Atomic int fin = 0, bad = 0;
void (^tick)(void) = ^{ int n = atomic_load(&fin); double el = CFAbsoluteTimeGetCurrent() - t0, left = n > 20 ? el / n * (total - n) : -1;
bar.progress = (float)n / total;
NSString *eta = left < 0 ? (zh() ? @"正在估算剩余时间" : @"estimating time left") : left >= 90 ? [NSString stringWithFormat:zh() ? @"预计还要 %.0f 分钟" : @"about %.0f min left", ceil(left / 60)] : [NSString stringWithFormat:zh() ? @"预计还要 %.0f 秒" : @"about %.0f s left", ceil(left / 5) * 5];
sub.text = [NSString stringWithFormat:@"%d / %d · %@", n, total, eta]; };
tick();
NSTimer *tm = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer *t) { tick(); }];
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
id<MTLDevice> dev = MTLCreateSystemDefaultDevice(); dispatch_semaphore_t sem = dispatch_semaphore_create(threads); dispatch_group_t g = dispatch_group_create();
for (NSString *p in src) { dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_group_async(g, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ @autoreleasepool {
NSString *txt = [NSString stringWithContentsOfFile:p encoding:NSUTF8StringEncoding error:nil]; NSError *e = nil;
id<MTLLibrary> l = txt ? [dev newLibraryWithSource:txt options:nil error:&e] : nil; // 与游戏里建库用的是同一个调用、同样的参数:缓存才对得上 | the same call with the same arguments as the game uses to build the library: only then does the cache match
if (!l && atomic_fetch_add(&bad, 1) < 5) pl([NSString stringWithFormat:@"【红】着色器准备:%@ 编不过:%@", p.lastPathComponent, e.localizedDescription ?: @"读不了"]);
int n = atomic_fetch_add(&fin, 1) + 1; if (n % 500 == 0) pl([NSString stringWithFormat:@"着色器准备:%d / %d,已用 %.0f 秒,温控档位 %ld", n, total, CFAbsoluteTimeGetCurrent() - t0, (long)NSProcessInfo.processInfo.thermalState]);
dispatch_semaphore_signal(sem); } }); }
dispatch_group_wait(g, DISPATCH_TIME_FOREVER);
double el = CFAbsoluteTimeGetCurrent() - t0; int nb = atomic_load(&bad);
pl([NSString stringWithFormat:@"着色器准备:完成 %d 个,编不过 %d 个,用时 %.1f 秒,%d 线程,结束时温控档位 %ld", total, nb, el, threads, (long)NSProcessInfo.processInfo.thermalState]);
if (!nb) [@"ok" writeToFile:mk atomically:YES encoding:NSUTF8StringEncoding error:nil]; // 有编不过的就不记完成:下次启动再来一遍(已编的很快) | if any failed to compile, do not record completion: run it again at the next launch (the already compiled ones are fast)
dispatch_async(dispatch_get_main_queue(), ^{ [tm invalidate]; [v removeFromSuperview]; UIApplication.sharedApplication.idleTimerDisabled = NO; done(); });
});
return 1;
}
#endif
+117
View File
@@ -0,0 +1,117 @@
// 暂停菜单「分享诊断日志」的 iOS 侧。
// 按钮是游戏自己的控件(布局 tools/touch_layout.py 的 _pause_no_help:借原版「消息记录」按钮,换字、改发 PanelManager:ClosePanel:TouchShareLog),
// 宿主收到这条空操作消息后调这里登记的回调(dm/host/diag.c)。这里做两件:
// ① 打一个文件:头部(构建号、机型、系统版本、温控 / 电量 / 内存 / 存储、本局与上一局的关键性能读数)+ 本局 boot.txt + 上一局 boot.previous.txt(main.m 每次启动前改名留下);
// ② 弹系统分享面板(UIActivityViewController),玩家自己选发到哪;iPad / Mac 上分享面板是弹出框,必须给锚点,否则一弹就崩。
// 隐私:只放这两份日志(游戏与宿主自己写的)和上面那几项机器读数;不取设备名、不取任何账号 / 位置 / 通讯录类信息。
// 测试开关 DM_TEST_SHARELOG_CLOSE=<秒>:分享面板照常弹出,过这么多秒自动收起;导出的文件另拷一份到 Documents/sharelog_test.txt 供回归核内容。
// iOS side of the pause menu's 「分享诊断日志」(Share Diagnostics).
// The button is the game's own widget (layout: _pause_no_help in tools/touch_layout.py: borrows the original game's 「消息记录」(Message Log) button, changes the text, and makes it send PanelManager:ClosePanel:TouchShareLog instead),
// and on receiving this no-op message the host calls the callback registered here (dm/host/diag.c). Two things are done here:
// ① Build one file: header (build number, device model, OS version, thermal / battery / memory / storage, key performance readings of this run and the previous run) + this run's boot.txt + the previous run's boot.previous.txt (left by main.m's rename before each launch);
// ② Present the system share sheet (UIActivityViewController), and the player chooses where to send it; on iPad / Mac the share sheet is a popover and must be given an anchor, otherwise it crashes as soon as it is presented.
// Privacy: only these two logs (written by the game and the host themselves) and the machine readings listed above are included; no device name, no account / location / contacts information of any kind.
// Test switch DM_TEST_SHARELOG_CLOSE=<seconds>: the share sheet is presented as usual and dismissed automatically after that many seconds; the exported file is also copied to Documents/sharelog_test.txt so regression can check its content.
#import <UIKit/UIKit.h>
#include <stdatomic.h>
#include <sys/sysctl.h>
#include <pwd.h>
#include <unistd.h>
#include "../../host/dm_i18n.h"
void plog(const char *fmt, ...);
void dm_sharelog_init(void (*cb)(void)); // dm/host/diag.c
// 日志里最后一条含 key 的行(不含行尾换行);没有返回 nil
// The last line in the log containing key (without the trailing newline); returns nil if none
static NSString *last_line(NSData *d, const char *key) {
if (!d.length) return nil;
NSData *k = [NSData dataWithBytes:key length:strlen(key)];
NSRange r = [d rangeOfData:k options:NSDataSearchBackwards range:NSMakeRange(0, d.length)]; if (r.location == NSNotFound) return nil;
const char *b = d.bytes; NSUInteger s = r.location, e = r.location;
while (s > 0 && b[s - 1] != '\n') s--;
while (e < d.length && b[e] != '\n') e++;
return [[NSString alloc] initWithBytes:b + s length:e - s encoding:NSUTF8StringEncoding] ?: @"(这一行不是合法 UTF-8)";
}
static void perf_block(NSMutableString *h, NSString *title, NSData *d) {
[h appendFormat:@"\n—— %@ ——\n", title];
if (!d) { [h appendString:@"(没有这份日志)\n"]; return; }
static const char *keys[] = { "boot: 版本", "[诊断]", "[perf]", "[nvn] 上屏", "温控档位" };
for (size_t i = 0; i < sizeof keys / sizeof *keys; i++) { NSString *l = last_line(d, keys[i]); [h appendFormat:@"%@\n", l ?: [NSString stringWithFormat:@"(没有「%@」行)", @(keys[i])]]; }
}
// 日志里的路径会带系统用户主目录(Mac 上是 /Users/<用户名>,iPhone 上是 /var/mobile):导出时一律换成 ~,不把用户名带出去
// Paths in the log carry the system user's home directory (/Users/<username> on Mac, /var/mobile on iPhone): on export always replace it with ~ so the username does not leak out
static NSData *scrub_home(NSData *d) {
struct passwd *pw = getpwuid(getuid()); const char *h = pw ? pw->pw_dir : NULL; size_t hn = h ? strlen(h) : 0;
if (!d || hn < 2) return d;
NSMutableData *o = [NSMutableData dataWithCapacity:d.length]; const uint8_t *b = d.bytes; size_t n = d.length, i = 0, from = 0;
while (i + hn <= n) { if (b[i] == (uint8_t)h[0] && !memcmp(b + i, h, hn)) { [o appendBytes:b + from length:i - from]; [o appendBytes:"~" length:1]; i += hn; from = i; } else i++; }
[o appendBytes:b + from length:n - from]; return o;
}
static NSDate *g_t0; // 本次启动时刻(dm_sharelog_boot) | Time of this launch (dm_sharelog_boot)
static NSURL *build_file(void) {
NSFileManager *fm = NSFileManager.defaultManager;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSData *cur = [NSData dataWithContentsOfFile:[doc stringByAppendingPathComponent:@"boot.txt"]], *prev = [NSData dataWithContentsOfFile:[doc stringByAppendingPathComponent:@"boot.previous.txt"]];
NSDictionary *inf = NSBundle.mainBundle.infoDictionary; NSString *build = [inf[@"CFBundleVersion"] description] ?: @"未知";
NSDateFormatter *df = [NSDateFormatter new]; df.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";
char hw[64] = "未知"; size_t hn = sizeof hw; sysctlbyname("hw.machine", hw, &hn, NULL, 0);
UIDevice *dev = UIDevice.currentDevice; dev.batteryMonitoringEnabled = YES;
NSArray<NSString *> *bst = @[ @"未知", @"放电", @"充电中", @"已充满" ]; int bs = (int)dev.batteryState;
NSDictionary *fsa = [fm attributesOfFileSystemForPath:doc error:nil]; NSProcessInfo *pi = NSProcessInfo.processInfo;
NSMutableString *h = [NSMutableString string];
[h appendFormat:@"D2R Mobile Diagnostics\n导出时间 %@\n版本 %@ 构建 %@\n机型 %s 系统 %@\n", [df stringFromDate:NSDate.date], [inf[@"CFBundleShortVersionString"] description] ?: @"未知", build, hw, pi.operatingSystemVersionString];
[h appendFormat:@"温控档位 %ld 低电量模式 %@ 电量 %.0f%% %@\n", (long)pi.thermalState, pi.lowPowerModeEnabled ? @"开" : @"关", dev.batteryLevel < 0 ? -1.0 : dev.batteryLevel * 100, bs >= 0 && bs <= 3 ? bst[bs] : @"未知"]; // 中文一律走 %@:NSString 的 %s 不按 UTF-8 解 | Chinese always goes through %@: NSString's %s does not decode as UTF-8
[h appendFormat:@"物理内存 %.1f GB 可用存储 %.1f GB 本次已运行 %.0f 分钟\n", pi.physicalMemory / 1073741824.0, [fsa[NSFileSystemFreeSize] doubleValue] / 1073741824.0, -g_t0.timeIntervalSinceNow / 60];
perf_block(h, @"本局关键读数(各取最后一条)", cur);
perf_block(h, @"上一局关键读数(各取最后一条)", prev);
NSMutableData *out = [[h dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
void (^part)(NSString *, NSData *) = ^(NSString *t, NSData *d) {
[out appendData:[[NSString stringWithFormat:@"\n\n===== %@(%@)=====\n", t, d ? [NSString stringWithFormat:@"%lu 字节", (unsigned long)d.length] : @"没有这份日志"] dataUsingEncoding:NSUTF8StringEncoding]];
if (d) [out appendData:d]; };
part(@"本局日志 boot.txt", cur); part(@"上一局日志 boot.previous.txt", prev);
NSString *dir = [NSTemporaryDirectory() stringByAppendingPathComponent:@"sharelog"]; // 只放这一份导出:每次重建这个目录(我们自己的,不碰别的) | Hold only this one export: rebuild this directory every time (it is our own; nothing else is touched)
[fm removeItemAtPath:dir error:nil]; [fm createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
df.dateFormat = @"yyyyMMdd_HHmmss";
NSString *p = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@(dm_ui("dmShareLogFile")), build, [df stringFromDate:NSDate.date]]];
out = [scrub_home(out) mutableCopy];
if (![out writeToFile:p atomically:YES]) { plog("诊断日志:【红】导出文件写不进 %s", p.UTF8String); return nil; }
plog("诊断日志:已打包 %s(%lu 字节:本局 %lu、上一局 %s)", p.lastPathComponent.UTF8String, (unsigned long)out.length, (unsigned long)cur.length,
prev ? [NSString stringWithFormat:@"%lu", (unsigned long)prev.length].UTF8String : "没有");
if (getenv("DM_TEST_SHARELOG_CLOSE")) [out writeToFile:[doc stringByAppendingPathComponent:@"sharelog_test.txt"] atomically:YES];
return [NSURL fileURLWithPath:p];
}
static UIViewController *top_vc(void) { // 同 front_ios.m 系统输入框找宿主的顺序:主窗口 → 前台活跃场景的窗口 → 任一窗口,再顺着已弹出的往上找 | Same order as front_ios.m's system input box uses to find its host: main window → a window of the foreground active scene → any window, then walk up through what is already presented
UIViewController *vc = nil, *alt = nil, *any = nil;
for (UIScene *s in UIApplication.sharedApplication.connectedScenes)
if ([s isKindOfClass:UIWindowScene.class]) for (UIWindow *w in ((UIWindowScene *)s).windows) {
if (!w.rootViewController) continue;
if (w.isKeyWindow) vc = w.rootViewController;
else if (s.activationState == UISceneActivationStateForegroundActive && !alt) alt = w.rootViewController;
else if (!any) any = w.rootViewController; }
vc = vc ?: alt ?: any; while (vc.presentedViewController) vc = vc.presentedViewController;
return vc;
}
static _Atomic int g_busy; // 打包 / 分享面板开着时再点不叠第二个 | Tapping again while packaging / the share sheet is open does not stack a second one
static void on_click(void) { // 宿主在游戏主线程调:玩家点了「分享诊断日志」 | Called by the host on the game main thread: the player tapped 「分享诊断日志」(Share Diagnostics)
if (atomic_exchange(&g_busy, 1)) { plog("诊断日志:分享面板还开着,这次点击不再弹"); return; }
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
NSURL *u = build_file();
dispatch_async(dispatch_get_main_queue(), ^{
UIViewController *vc = u ? top_vc() : nil;
if (!vc) { if (u) plog("诊断日志:【红】没找到可弹分享面板的界面"); atomic_store(&g_busy, 0); return; }
UIActivityViewController *a = [[UIActivityViewController alloc] initWithActivityItems:@[u] applicationActivities:nil];
a.completionWithItemsHandler = ^(UIActivityType t, BOOL done, NSArray *items, NSError *e) { (void)items;
plog("诊断日志:分享面板收起(%s%s%s)", done ? "已发到 " : "没发", done ? (t ?: @"未知").UTF8String : "", e ? [NSString stringWithFormat:@",错误 %@", e.localizedDescription].UTF8String : "");
atomic_store(&g_busy, 0); };
UIPopoverPresentationController *pp = a.popoverPresentationController; // iPad / Mac 上是弹出框:锚在画面正中(暂停菜单所在处),不画箭头 | On iPad / Mac it is a popover: anchored at the center of the picture (where the pause menu is), no arrow drawn
if (pp) { pp.sourceView = vc.view; pp.sourceRect = CGRectMake(CGRectGetMidX(vc.view.bounds), CGRectGetMidY(vc.view.bounds), 1, 1); pp.permittedArrowDirections = 0; }
[vc presentViewController:a animated:YES completion:^{
plog("诊断日志:分享面板已弹出(%s,%s)", pp ? "弹出框" : "底部面板", NSStringFromCGRect(a.view.frame).UTF8String);
const char *tc = getenv("DM_TEST_SHARELOG_CLOSE"); if (!tc) return;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(tc) * 1e9)), dispatch_get_main_queue(), ^{
[a dismissViewControllerAnimated:NO completion:^{ plog("诊断日志:测试开关 DM_TEST_SHARELOG_CLOSE 到点收起分享面板"); atomic_store(&g_busy, 0); }]; });
}];
});
});
}
void dm_sharelog_boot(void) { g_t0 = NSDate.date; dm_sharelog_init(on_click); } // main.m 起宿主前调一次 | main.m calls this once before starting the host
+698
View File
@@ -0,0 +1,698 @@
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include <math.h>
#include <string.h>
#include <stdatomic.h>
#define DM_TC_POINTER_MOVE_PT 10.0f
#define DM_TC_POINTER_HOLD_S 0.5
#define DM_TC_POINTER_TAP_S 0.35
/* 控件缩放。手机(画面高 ≤ 440 点,最大的 iPhone 横屏就是 440):min(1, 宽/667, 高/375),与原来一字不差。
比手机高的画面(iPad 上居中的 16:9 那块,13 寸是 1366×768 点):按画面高度等比放大(高/440),否则摇杆与技能钮还是手机的点数大小,
在大画面里只剩一小簇(Mac 上按 iPad 尺寸出图所见),而底栏与游戏界面都是按画面高度缩放的。
这条放大只在前端显式打开时生效(dm_tc_set_tall_scale,front_ios.m 建视图时开):Mac 宿主的触屏用例通路(dm/host/touch_mac.c)是把像素数
(2868×1320)当点数传进来的,13 个用例的坐标按「缩放 = 1」写;不加这道开关,1320 > 440 会把它们的控件放大 3 倍、主钮挪位(skill_main 红)。
Widget scale. Phone (picture height ≤ 440 points; the largest iPhone in landscape is exactly 440): min(1, width/667, height/375), identical to before to the letter.
Pictures taller than the phone's (the centered 16:9 block on iPad; 13-inch is 1366×768 points): scale up proportionally by picture height (height/440), otherwise the stick and skill buttons keep the phone's point size
and are just a small cluster in the large picture (as seen when rendering at iPad size on Mac), while the bottom bar and the game UI both scale by picture height.
This enlargement takes effect only when the front end turns it on explicitly (dm_tc_set_tall_scale, turned on when front_ios.m creates the view): the Mac host's touch test-case path (dm/host/touch_mac.c) passes pixel counts
(2868×1320) in as points, and the coordinates of the 13 test cases are written for "scale = 1"; without this switch, 1320 > 440 would enlarge their widgets 3x and move the main button (skill_main red). */
static int g_tall_scale;
void dm_tc_set_tall_scale(int on) { g_tall_scale = !!on; }
float dm_tc_scale_for_size(float width, float height) { float k = fminf(1.0f, fminf(width / 667.0f, height / 375.0f)); return g_tall_scale && k >= 1.0f && height > 440.0f ? height / 440.0f : k; }
static float scale_for(const dm_tc_layout *l) { return dm_tc_scale_for_size(l->width, l->height); }
/* 安全区(iPhone 横屏左右各有一条让给灵动岛 / 圆角的区域,17 Pro Max 实读各 62 点):右侧技能键整组、左侧摇杆按最小位移平移到全部落在安全区内,
组内相对排布不变。岛在哪一侧取决于玩家怎么拿,两侧都内缩。缺省 0(Mac 宿主、单测不设 = 原布局)。
Safe area (in iPhone landscape there is a strip on each of the left and right yielded to the Dynamic Island / rounded corners; read as 62 points each on a 17 Pro Max): the whole right-side skill key group and the left stick are translated by the minimum displacement so that they lie entirely inside the safe area,
with the relative arrangement within the group unchanged. Which side the island is on depends on how the player holds the device, so both sides are inset. Default 0 (Mac host and unit tests do not set it = original layout). */
static float g_safe_l, g_safe_r;
/* 屏幕底边归系统的那一条(点):从这里起手往上划会被系统当成底边手势(iPad 上连着两次就拉出程序坞),而移动恰好是同一处反复起手往上推。
这一条里起手不当摇杆、松手也不当点地;从上面起手的摇杆拖进来照常持有。只有 iPad 的前端会给非零值,手机恒为 0。
The strip along the bottom edge of the screen that belongs to the system (points): a swipe up starting here is taken by the system as a bottom-edge gesture (on iPad two in a row pull out the Dock), and movement is exactly a repeated push upward starting from the same place.
A touch starting in this strip is not treated as the stick, and its release is not treated as a ground tap; a stick drag that started above and moves in keeps its hold as usual. Only the iPad front end passes a non-zero value; on phones it is always 0. */
static float g_edge_b;
void dm_tc_set_edge_bottom(float bottom) { g_edge_b = isfinite(bottom) && bottom > 0 ? bottom : 0; }
void dm_tc_set_safe_insets(float left, float right) { g_safe_l = isfinite(left) && left > 0 ? left : 0; g_safe_r = isfinite(right) && right > 0 ? right : 0; }
void dm_tc_layout_make(dm_tc_layout *l, float width, float height) {
memset(l, 0, sizeof(*l));
l->width = isfinite(width) && width > 0 ? width : 0;
l->height = isfinite(height) && height > 0 ? height : 0;
float k = scale_for(l);
float main_x = l->width - 56 * k, main_y = l->height - 82 * k;
{ float over = main_x + 40*k - (l->width - g_safe_r); if (over > 0) main_x -= over; } /* 右侧一组里最靠右的是主技能键(半径 40) | The rightmost one in the right-side group is the main skill key (radius 40) */
l->target[DM_TC_MAIN] = (dm_tc_target){ main_x, main_y, 40*k, DM_BTN_A };
/* 四分之一弧的单位向量:180°、150°、120°、90°。 | Unit vectors of the quarter arc: 180°, 150°, 120°, 90°. */
const float dx[4] = {-1, -0.8660254038f, -0.5f, 0};
const float dy[4] = {0, -0.5f, -0.8660254038f, -1};
const uint64_t skill[4] = {DM_BTN_B, DM_BTN_X, DM_BTN_Y, DM_BTN_R};
for (int i = 0; i < 4; ++i)
l->target[DM_TC_SKILL1+i] = (dm_tc_target){main_x+112*k*dx[i], main_y+112*k*dy[i], 26*k, skill[i]};
/* 底栏 = 底部 UI v4 六格(NativeHUD/v4,游戏 HUD 按屏高缩放、以屏幕中线居中,所以按屏高换算):
效果图 2868×1320 里格心 x = 1090 + 120×格号、y = 1241.5、格宽 114;第 0 格难度,1–4 腰带四列,5 功能入口(PLUS)。
回城不在底栏(离药水太近易误触):改为技能弧最上面那颗(技能四)正上方的圆钮,同半径、间距 12,点下由宿主施放原版回城技能(dm_freetp.c),不出按键。
Bottom bar = the six cells of bottom UI v4 (NativeHUD/v4; the game HUD scales by screen height and is centered on the screen centerline, so convert by screen height):
in the 2868×1320 mock, cell center x = 1090 + 120×cell index, y = 1241.5, cell width 114; cell 0 difficulty, 1–4 the four belt columns, 5 the function entry (PLUS).
Town portal is not in the bottom bar (too close to the potions, easy to hit by mistake): it is instead a round button directly above the topmost one on the skill arc (skill four), same radius, gap 12; on tap the host casts the original game's town portal skill (dm_freetp.c), with no key press. */
/* 腰带四列对十字键:左 = 第 1 列、上 = 第 2 列、下 = 第 3 列、右 = 第 4 列(原版实测:按「右」第 4 列减、按「下」第 3 列减;首版把后两个写反了,真机才撞到) | The four belt columns map to the D-pad: left = column 1, up = column 2, down = column 3, right = column 4 (measured in the original game: pressing "right" decrements column 4, pressing "down" decrements column 3; the first version had the last two swapped, which was only hit on a real device) */
const uint64_t bottom[5] = {DM_BTN_LEFT, DM_BTN_UP, DM_BTN_DOWN, DM_BTN_RIGHT, DM_BTN_PLUS};
const int cell[5] = {1, 2, 3, 4, 5};
float u = l->height / 1320.0f;
for (int i = 0; i < 5; ++i)
l->target[DM_TC_BELT1+i] = (dm_tc_target){l->width/2+(1090+120*cell[i]-1434)*u, 1241.5f*u, 57*u, bottom[i]};
{ const dm_tc_target *s4 = &l->target[DM_TC_SKILL4]; l->target[DM_TC_PORTAL] = (dm_tc_target){s4->x, s4->y-s4->r-12*k-26*k, 26*k, 0}; }
/* 第 0 格难度与选择条:选择条 8 格同格宽、格距 120,中线对齐两球中线(效果图 1390),格心 y = 1051.5(七格之上、避开数值文字) | Cell 0 difficulty and the selector bar: the selector bar has 8 cells of the same cell width, cell pitch 120, centerline aligned with the centerline between the two orbs (mock 1390), cell center y = 1051.5 (above the seven cells, clear of the value text) */
l->diff = (dm_tc_target){l->width/2+(1090-1434)*u, 1241.5f*u, 57*u, 0};
for (int i = 0; i < 8; ++i) l->pick[i] = (dm_tc_target){l->width/2+(1390+(i-3.5f)*120-1434)*u, 1051.5f*u, 57*u, 0};
l->target[DM_TC_MAP] = (dm_tc_target){l->width-30*k, 30*k, 22*k, DM_BTN_MINUS};
/* 技能组切换:主技能左下、技能一下方,避开主技能与弧上四键 | Skill set switch: lower-left of the main skill, below skill one, clear of the main skill and the four keys on the arc */
/* 位置与大小:技能一正下方,半径 22(直径 44 点 ≈ 7.3 毫米);上沿离技能一下沿 4 点、下沿离屏幕底 10 点(956×440) | Position and size: directly below skill one, radius 22 (diameter 44 points ≈ 7.3 mm); top edge 4 points from the bottom edge of skill one, bottom edge 10 points from the bottom of the screen (956×440) */
/* 比手机窄的画面(16:9:iPad 留边 / 真全屏的游戏视图、667×375)底栏按屏高缩放、右端雕像翼尖(效果图 x 2075)会伸到换组键底下:
键向右让到离翼尖 8 点以外,大小不变(量:1366×768 下原位重叠 21 点;956×440 下本来就隔着 28 点,不动)
On pictures narrower than the phone's (16:9: iPad letterboxed / true full-screen game view, 667×375) the bottom bar scales by screen height and the right-end statue wing tip (mock x 2075) would extend under the set-switch key:
the key moves right to at least 8 points away from the wing tip, size unchanged (measured: at 1366×768 the original position overlaps by 21 points; at 956×440 it is already 28 points apart and is not moved) */
{ float sx = main_x-112*k, bar_r = l->width/2+(2015-1434)*u+8*k+22*k; /* 右雕像翼尖:七格时 2075,六格石条右端收进 60 | Right statue wing tip: 2075 with seven cells; with six cells the right end of the stone bar is pulled in by 60 */ if (sx < bar_r) sx = bar_r;
l->swap = (dm_tc_target){sx, main_y+52*k, 22*k, 0}; }
/* 底栏外侧是血 / 蓝球;球不是输入目标。 | Outside the bottom bar are the life / mana orbs; the orbs are not input targets. */
l->joy_x = fmaxf(90*k, g_safe_l + 60*k); /* 摇杆底盘(半径 60)左沿不越过安全区左界 | The left edge of the stick base (radius 60) does not cross the left boundary of the safe area */
l->joy_y = l->height - 100*k;
l->joy_radius = 60*k;
}
int dm_tc_hit(const dm_tc_layout *l, float x, float y) {
if (!isfinite(x) || !isfinite(y) || x < 0 || y < 0 || x > l->width || y > l->height)
return DM_TC_NONE;
for (int i = 0; i < DM_TC_COUNT; ++i) {
const dm_tc_target *t = &l->target[i];
float dx = x-t->x, dy = y-t->y;
if (t->r > 0 && dx*dx+dy*dy <= t->r*t->r) return i;
}
float sx = x-l->swap.x, sy = y-l->swap.y;
if (l->swap.r > 0 && sx*sx+sy*sy <= l->swap.r*l->swap.r) return DM_TC_SWAP;
return DM_TC_NONE;
}
static int skill_target(int target) {
return target >= DM_TC_MAIN && target <= DM_TC_SKILL4;
}
/* 拖动方向(单位向量,屏幕坐标):拖动不过 10 点死区 = 没有方向 | Drag direction (unit vector, screen coordinates): a drag that does not pass the 10-point dead zone = no direction */
static int aim_dir(const dm_tc_state *s, const dm_tc_finger *f, float *ux, float *uy) {
float dx = f->x-f->aim_origin_x, dy = f->y-f->aim_origin_y, d = hypotf(dx, dy);
if (!(d > 10 * scale_for(&s->layout))) return 0;
*ux = dx/d; *uy = dy/d; return 1;
}
static int inside_map_cancel(const dm_tc_state *s, const dm_tc_finger *f) {
const dm_tc_target *map = &s->layout.target[DM_TC_MAP];
return map->r > 0 && fabsf(f->x-map->x) <= map->r && fabsf(f->y-map->y) <= map->r;
}
static int g_iso_fix = 1;
void dm_tc_set_iso_fix(int on) { g_iso_fix = !!on; }
static void update_aim(dm_tc_state *s) {
s->rx = s->ry = 0;
s->aim_slot = DM_TC_NONE;
s->map_cancel_active = 0;
if (s->navigation_mode) return;
uint64_t latest = 0;
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) {
const dm_tc_finger *f = &s->finger[i];
if (!f->active || !skill_target(f->target)) continue;
if (inside_map_cancel(s, f)) s->map_cancel_active = 1;
if (!f->aim_cancelled && f->aim_move_sequence > latest) {
latest = f->aim_move_sequence;
s->aim_slot = i;
}
}
if (s->pulse_button) { s->rx = s->pulse_rx; s->ry = s->pulse_ry; return; }
float radius = 60 * scale_for(&s->layout);
if (s->aim_slot == DM_TC_NONE || radius <= 0) return;
const dm_tc_finger *f = &s->finger[s->aim_slot];
if (f->target != DM_TC_MAIN && hypotf(f->x-f->aim_origin_x, f->y-f->aim_origin_y) <= 10 * scale_for(&s->layout)) return; /* 技能钮:拖动不过 10 点 = 点按,不给方向,原版自动选目标 | Skill button: a drag of no more than 10 points = tap, no direction given, the original game auto-targets */
float dx = (f->x-f->aim_origin_x)/radius;
float dy = (f->aim_origin_y-f->y)/radius;
s->rx = (int32_t)lroundf(fmaxf(-1, fminf(1, dx))*DM_STICK_MAX);
s->ry = (int32_t)lroundf(fmaxf(-1, fminf(1, dy))*DM_STICK_MAX);
}
static void update(dm_tc_state *s) {
s->buttons = 0;
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) {
dm_tc_finger *f = &s->finger[i];
if (f->active && !f->aim_cancelled && f->target >= 0 && f->target < DM_TC_COUNT) {
uint64_t b = f->target==DM_TC_PORTAL && s->portal_pending ? DM_BTN_ZL : s->layout.target[f->target].button;
/* 拖动定方向(核心手势)。技能钮:按下后先等 DM_TC_AIM_SETTLE_S 看是点按还是拖动——拖过死区就带着右轴方向立刻键下,
没拖到点也键下(点按 = 原版自动选目标 / 朝向);否则键先下、右轴后偏,按下那一发朝的是旧朝向。
主钮:按下即键下,不等(它是最高频的键,点按不该多等;按下就拖的第一发是原生朝向,第二发起跟手)。
按住期间方向再变由宿主的瞄准适配每拍重取,这里不做「松—按」;判定时间不为「按下稍停再拖」加长。
Drag to set direction (the core gesture). Skill button: after press, first wait DM_TC_AIM_SETTLE_S to see whether it is a tap or a drag -- once dragged past the dead zone, key down immediately with the right-axis direction,
and key down too if the time is reached without dragging (tap = the original game's auto target / facing); otherwise the key would go down first and the right axis deflect later, and the shot at press would aim at the old facing.
Main button: key down on press, no wait (it is the most frequent key and a tap should not wait longer; with press-then-drag the first shot uses the native facing, and from the second shot on it follows the finger).
Direction changes while held are re-read every tick by the host's aim adapter, so no "release-press" is done here; the decision time is not lengthened for "press, pause, then drag". */
if (!s->navigation_mode && f->target >= DM_TC_SKILL1 && f->target <= DM_TC_SKILL4) {
float ux, uy;
if (!f->key_down && !aim_dir(s, f, &ux, &uy) && s->last_time_s - f->start_time_s < DM_TC_AIM_SETTLE_S) b = 0;
else if (!f->key_down) { f->key_down = 1; f->key_down_s = s->last_time_s; }
}
/* 多排腰带:腰带格上滑 = 展开、下滑 = 收起,所以键不在按下时发;一律等松手那一刻按位移判(dm_tc_end_at)。不设「按住到点就喝」的计时:
手慢一点的上滑 / 下滑会先被它判成喝药(真机与 mini 各撞一次)。只有 1 排时照旧按下即喝
Multi-row belt: swiping up on a belt cell = expand, swiping down = collapse, so the key is not sent on press; always wait for the moment of release and decide by displacement (dm_tc_end_at). No "drink once held long enough" timer:
a slightly slow swipe up / down would first be judged by it as drinking a potion (hit once each on a real device and on the second Mac). With only 1 row, still drink on press as before */
/* 只有 1 排时也一律松手那一刻喝(和多排同一条路) | with only 1 row, also always drink at the moment of release (same path as multiple rows) */
if (!s->navigation_mode && f->target >= DM_TC_BELT1 && f->target <= DM_TC_BELT4) b = 0;
s->buttons |= b;
}
}
s->buttons |= s->pulse_button;
/* 第二套技能:ZL 是原版的换组修饰键。只在用技能的那一刻带上——手指按着主钮 / 技能钮、或技能脉冲在发(含等着发)时;
其余时候不按:一直按着会让十字(+)、腰带、回城都变成「ZL + 键」的组合(Ⅱ 态下十字开不了面板)。
ZL 先下、主钮的键晚 DM_TC_ZL_LEAD_S 再下(同一帧按下游戏只认主键 = 放成第一组的技能)。
Second skill set: ZL is the original game's set-switch modifier. It is added only at the moment a skill is used -- while a finger is on the main button / a skill button, or a skill pulse is being sent (including waiting to be sent);
it is not pressed the rest of the time: holding it all the time would turn the cross (+), the belt and town portal all into "ZL + key" combos (in state Ⅱ the cross could not open the panel).
ZL goes down first, and the main button's key goes down DM_TC_ZL_LEAD_S later (pressed in the same frame, the game only recognizes the main key = casts the first set's skill). */
if (s->skill_set && !s->navigation_mode) {
/* 在发的脉冲只有是技能键(主钮 / 技能钮补的那一下)才带 ZL:多排腰带松手补的喝药脉冲带上 ZL 就成了原版「ZL + 腰带键 = 喂佣兵」
(本机 实跑:第二组下点腰带,0x26 包目标字节 = 1、佣兵生命 642 → 762 涨、玩家不变)
The pulse being sent carries ZL only if it is a skill button (the make-up press of the main button / a skill button): a drink pulse made up on release of a multi-row belt, if it carried ZL, would become the original game's "ZL + belt key = feed the mercenary"
(actual run on the local machine: tapping the belt under the second set, 0x26 packet target byte = 1, mercenary life rose 642 → 762, player unchanged) */
/* 等着补发的技能也要 ZL 领先——但只在没有别的脉冲在发时:腰带脉冲在发时带上 ZL 同样成了「喂佣兵」(单测探针读到 0x1100) | A skill waiting for a make-up send also needs ZL to lead -- but only when no other pulse is being sent: adding ZL while a belt pulse is being sent likewise becomes "feed the mercenary" (the unit-test probe read 0x1100) */
int use = s->defer_button != 0 && !s->pulse_button;
for (int t = DM_TC_MAIN; t <= DM_TC_SKILL4 && !use; ++t) if (s->pulse_button && s->pulse_button == s->layout.target[t].button) use = 1;
/* 手指按着第二组技能时发「给玩家喝」的腰带脉冲:ZL 还按着就成了原版「ZL + 腰带键 = 喂佣兵」。ZL 和按着的技能键要一起让开
(只松 ZL 不松技能键 = 放成第一组的技能),而且要先让开、隔一段再按腰带键:同一拍里「松 ZL + 按腰带键」游戏仍按 ZL 还在算
(真局实测:发出的还是喂佣兵包——宿主取手柄处对按下沿做锁存,这一拍采到的是 ZL 与腰带键都在)。所以分三段:
等着发(belt_gap_cell)→ 脉冲在发 → 收回后 ZL 先回来、领先满 DM_TC_ZL_LEAD_S 技能键再回来(同一帧按下游戏只认主键)
The "drink for the player" belt pulse sent while a finger holds a skill of the second skill set: with ZL still held it becomes the original game's "ZL + belt key = feed the mercenary". ZL and the held skill key have to get out of the way together
(releasing only ZL and not the skill key = casting the first set's skill), and they have to get out of the way first, with the belt key pressed after a gap: with "release ZL + press belt key" in the same tick the game still counts ZL as held
(measured in a real run: what went out was still the feed-the-mercenary packet -- where the host fetches the controller it latches the press edge, and what was sampled this tick was both ZL and the belt key down). So there are three stages:
waiting to send (belt_gap_cell) → the pulse is being sent → after it is withdrawn ZL comes back first, and the skill key comes back once ZL has led by a full DM_TC_ZL_LEAD_S (pressed in the same frame, the game only recognizes the main key) */
int belt_pulse = s->belt_gap_cell != 0;
for (int t = DM_TC_BELT1; t <= DM_TC_BELT4; ++t) if (s->pulse_button && s->pulse_button == s->layout.target[t].button) belt_pulse = 1;
if (belt_pulse) s->belt_pulse_s = s->last_time_s;
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) {
const dm_tc_finger *f = &s->finger[i];
if (!f->active || f->aim_cancelled || f->target < DM_TC_MAIN || f->target > DM_TC_SKILL4) continue;
if (!belt_pulse) use = 1;
if (belt_pulse || s->last_time_s - f->start_time_s < DM_TC_ZL_LEAD_S || (s->belt_pulse_s > 0 && s->last_time_s - s->belt_pulse_s < DM_TC_ZL_LEAD_S)) s->buttons &= ~s->layout.target[f->target].button;
}
if (use) s->buttons |= DM_BTN_ZL;
}
update_aim(s);
s->lx = s->ly = 0;
if (s->joy_slot < 0) return;
dm_tc_finger *f = &s->finger[s->joy_slot];
float dx = f->x-s->joy_origin_x, dy = s->joy_origin_y-f->y;
/* 输入行程不跟大屏的视觉放大走:拇指不随屏幕变大。满偏 60 点、死区 6 点,手机与 iPad 一致
(原先乘视觉倍数,12.9 寸 iPad 要推 105 点 ≈ 20 mm 才满偏,是手机的两倍)。底盘和摇杆头的大小仍按视觉倍数画。
Input travel does not follow the visual enlargement on large screens: the thumb does not grow with the screen. Full deflection 60 points, dead zone 6 points, same on phone and iPad
(it used to be multiplied by the visual factor, so a 12.9-inch iPad needed a 105-point ≈ 20 mm push for full deflection, twice the phone's). The size of the base and the stick head is still drawn by the visual factor. */
float in_k = fminf(1.0f, scale_for(&s->layout));
float distance = hypotf(dx, dy), radius = 60 * in_k;
float dead = 6 * in_k;
if (distance <= dead || radius <= dead) return;
float strength = fminf(1, (distance-dead)/(radius-dead));
/* 斜向预修正:原版把摇杆做纯 45° 旋转成世界方向、不补偿等距画面的 2:1,人实际走的屏幕角 = atan(tan(摇杆角) / 2)(推 45° 走 26.6°)。
手柄玩家看不见摇杆和画面的对应,触屏上手指画的就是屏幕方向,所以送值前把纵向放大 2 倍再缩回原幅度:屏幕角 = 手指角,推多深不变。
只动游戏态的移动摇杆(导航态没有摇杆值;技能方向走右轴,不经这里)
Diagonal pre-correction: the original game turns the stick into a world direction by a pure 45° rotation and does not compensate for the 2:1 of the isometric view, so the screen angle the character actually walks = atan(tan(stick angle) / 2) (push 45°, walk 26.6°).
Controller players do not see the mapping between stick and picture, but on a touchscreen what the finger draws is the screen direction, so before sending the value the vertical component is doubled and then scaled back to the original magnitude: screen angle = finger angle, push depth unchanged.
Only the movement stick in game state is affected (navigation state has no stick value; skill direction goes through the right axis and does not pass here) */
float ex = dx/distance, ey = dy/distance;
if (g_iso_fix) { float n = hypotf(ex, 2*ey); ex /= n; ey = 2*ey/n; }
s->lx = (int32_t)lroundf(ex * strength * DM_STICK_MAX);
s->ly = (int32_t)lroundf(ey * strength * DM_STICK_MAX);
}
static int pointer_finger(const dm_tc_state *s, const dm_tc_finger *f) {
return s->navigation_mode && f->active && s->pointer_slot >= 0 &&
&s->finger[s->pointer_slot] == f;
}
static void update_pointer(dm_tc_state *s) {
if (!s->pointer_valid || s->pointer_slot < 0 || s->pointer_slot >= DM_TC_MAX_TOUCH) return;
dm_tc_finger *f = &s->finger[s->pointer_slot];
if (f->pointer_dragged && s->pointer_pickup_done && !f->shop_drag && !f->locked_drag) {
s->pointer_x = f->x;
s->pointer_y = f->y - DM_TC_POINTER_LIFT_PT * scale_for(&s->layout);
}
}
/* 指针脉冲(kind 1 = 拖放的拿起,2 = 放下 / 点按):指针先落到 (x,y) 再按 A。上一个脉冲还没收(游戏还没取走)时不动指针、只记下,
等前端在上一个收回且游戏已看到一次「A 松开」之后调 dm_tc_pulse_resume 才开始——否则两下 A 连成一下、或拿起落在放下的位置
Pointer pulse (kind 1 = pick-up of a drag-and-drop, 2 = put-down / tap): the pointer first lands at (x,y), then A is pressed. While the previous pulse has not been released (the game has not consumed it yet) the pointer is not moved and the request is only recorded,
and it starts only when the front end calls dm_tc_pulse_resume, after the previous one is released and the game has seen "A released" once -- otherwise two A presses merge into one, or the pick-up lands at the put-down position */
static void pointer_pulse_btn(dm_tc_state *s, float x, float y, int kind, uint64_t button, double hold_s) {
if (!s->pulse_button) {
s->pointer_x = x; s->pointer_y = y;
s->pulse_button = button;
s->pulse_hold_s = hold_s;
s->pulse_rx = s->pulse_ry = 0;
s->pointer_pulse_active = kind;
++s->pulse_epoch;
} else {
s->pointer_pulse_pending = kind;
s->pointer_pending_x = x;
s->pointer_pending_y = y;
s->pointer_pending_button = button; s->pointer_pending_hold = hold_s;
}
}
static void pointer_pulse_start(dm_tc_state *s, float x, float y, int kind) { pointer_pulse_btn(s, x, y, kind, DM_BTN_A, 0); }
void dm_tc_pointer_release(dm_tc_state *s, int kind) { s->pointer_release_item = kind == 1 || kind == 3 || kind == 4 || kind == 8 ? kind : 0; }
void dm_tc_pointer_release_at(dm_tc_state *s, float x, float y) { s->pointer_release_item = 5; s->release_x = x; s->release_y = y; }
void dm_tc_set_holding(dm_tc_state *s, int holding) { s->holding = !!holding; }
void dm_tc_pointer_item(dm_tc_state *s, int kind) {
if (kind == 7) { s->pointer_shop = 1; kind = 1; }
s->pointer_lock = kind == 10; if (kind == 10) kind = 1;
s->pointer_stack = kind == 8; if (kind == 8) kind = 1; /* 8 = 高级仓库的成叠格:照物品区,只有双击不同 | 8 = stacked cell of the advanced stash: follows the item area, only double tap differs */ /* 7 = 商人货架上的货:别的都照物品区,只有起拖不同 | 7 = goods on the vendor shelf: everything else follows the item area, only drag start differs */
s->pointer_item = (kind >= 1 && kind <= 3) || kind == 6 || kind == 11 ? kind : 0; /* 11 = 这一下不点(底下是被盖住的按钮),但可以起滚动手势(设置页列表里的文字 / 空处) | 11 = this tap does not click (a covered button is underneath), but it may start a scroll gesture (text / empty space in the settings page list) */
if (s->mouse_click_mode && s->pointer_slot >= 0 && s->pointer_slot < DM_TC_MAX_TOUCH && s->finger[s->pointer_slot].active && !s->finger[s->pointer_slot].pointer_dragged) {
if (kind == 1) { if (!s->pulse_button) { s->pointer_valid = 1; s->pointer_x = s->finger[s->pointer_slot].aim_origin_x; s->pointer_y = s->finger[s->pointer_slot].aim_origin_y; } }
else s->pointer_valid = 0; /* 不在物品区:放开手柄光标(前端据此清掉光标请求,不再推摇杆) | Not in the item area: release the controller cursor (based on this the front end clears the cursor request and stops pushing the stick) */
}
} /* 1 物品区 2 页签(点按不发键也不发鼠标,前端另调宿主切页) | 1 item area, 2 tab (a tap sends neither a key nor a mouse click; the front end separately calls the host to switch pages) */
static _Atomic int g_dead_modal;
static _Atomic int g_vendor_open; /* 商人交易页开着:ZL 是切货架页签,「再点同一处 = 比较」不发 | Vendor trade page open: ZL switches shelf tabs, so "tap the same spot again = compare" is not sent */
static _Atomic int g_close_stop; /* 「面板外点按 = 按返回到面板关掉」途中弹出了确认框(名字以 Modal 结尾的面板打开):后面的返回键不再按 | A confirmation box popped up (a panel whose name ends in Modal opened) in the middle of "tap outside the panel = press back until the panel closes": stop pressing the remaining back presses */
static _Atomic int g_tap_box; /* 最近一次单击的物品是魔盒(前端每拍从宿主同步) | The most recently single-tapped item is the cube (synced by the front end from the host every tick) */
void dm_tc_set_tap_box(int on) { atomic_store(&g_tap_box, on != 0); }
static _Atomic unsigned g_cur_stack;
void dm_tc_set_cur_stack(unsigned id) { atomic_store(&g_cur_stack, id); }
static _Atomic unsigned g_hover_unid;
void dm_tc_set_hover_unid(unsigned id) { atomic_store(&g_hover_unid, id); }
static _Atomic int g_imbue_open; /* 单件任务槽面板开着(灌魔 / 打孔 / 个性化 / 古墓底座,同一个 ImbueItemsPanel) | Single-item quest slot panel open (imbue / socket / personalize / tomb pedestal, all the same ImbueItemsPanel) */
static _Atomic int g_cube_open; /* 赫拉迪克方块页开着:双击 = 按住 Y(原版「移到另一侧」:背包 → 方块 / 方块 → 背包),不是「使用 / 装备」 | Horadric Cube page open: double tap = hold Y (the original game's "move to the other side": inventory → cube / cube → inventory), not "use / equip" */
static _Atomic int g_vault_open; /* 储藏箱开在第六页「编年史」:双击背包物品 = 存进编年史仓库(走 use_seq,宿主 ui_use_pump 判页),不发原版「按住 Y」——那一页游戏当魔盒页 | Stash open on page six 「编年史」(Chronicle): double-tapping an inventory item = store it in the Chronicle vault (goes through use_seq; the host's ui_use_pump determines the page); do not send the original game's "hold Y" -- the game treats that page as the cube page */
static _Atomic int g_bank_open; /* 储藏箱开着(前端从宿主读游戏面板树的结果设进来,不靠开关消息):双击 = 按住 Y(移到另一侧) | Stash open (set by the front end from the host's reading of the game panel tree, not from open/close messages): double tap = hold Y (move to the other side) */
void dm_tc_set_panel_state(int bits) { atomic_store(&g_bank_open, (bits & 1) != 0); atomic_store(&g_vendor_open, (bits & 2) != 0); atomic_store(&g_dead_modal, (bits & 4) != 0); atomic_store(&g_imbue_open, (bits & 16) != 0); atomic_store(&g_cube_open, (bits & 32) != 0); atomic_store(&g_vault_open, (bits & 64) != 0); } /* 位同 dm_cursor.h 的 DM_PS_*;宿主读游戏状态得来 | Bits are the same as DM_PS_* in dm_cursor.h; obtained by the host reading the game state */
static void pointer_drag_begin(dm_tc_state *s, dm_tc_finger *f) {
f->pointer_dragged = 1;
if (s->pointer_lock) { f->locked_drag = 1; return; } /* 单件槽占用时从别的物品上起拖:不拿起,这次拖动什么都不做 | Drag starting from another item while the single-item slot is occupied: do not pick up; this drag does nothing */
if (s->pointer_shop || s->pointer_stack) { f->shop_drag = 1; s->pointer_x = 2; s->pointer_y = 2; update(s); return; } /* 从货架上的货起拖:不拿起;光标挪到屏幕角上,让货上的说明框收掉(买的时候宿主再把光标放回这件货上) | Drag starting from goods on the shelf: do not pick up; move the cursor to a screen corner so the tooltip on the goods closes (at purchase time the host puts the cursor back on that item) */
s->pointer_pickup_done = 0;
pointer_pulse_start(s, f->aim_origin_x, f->aim_origin_y, 1);
}
void dm_tc_cancel_all(dm_tc_state *s) {
++s->gesture_epoch; s->portal_pending=s->portal_phase=0; s->diff_open=0;
memset(s->finger, 0, sizeof(s->finger));
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) s->finger[i].target = DM_TC_NONE;
s->joy_slot = DM_TC_NONE;
s->joy_origin_x = s->joy_origin_y = 0;
s->buttons = 0;
s->lx = s->ly = s->rx = s->ry = 0;
s->aim_slot = DM_TC_NONE;
s->aim_move_sequence = 0;
s->map_cancel_active = 0;
s->pulse_button = 0; s->pulse_rx = s->pulse_ry = 0;
s->belt_q = 0; s->belt_gap_cell = 0; /* 排着的、等着发的喝药一起作废 | queued and pending drinks are voided as well */ /* 等着判单双击的腰带格、等着发的喂雇佣兵一起作废 | The belt cell waiting for single/double tap decision and the pending mercenary feed are voided together */
s->defer_button = 0; /* 等着补发的那下技能也作废:原先取消后 0.2 秒照样放出来 | The skill press waiting for a make-up send is voided as well: previously it was still cast 0.2 seconds after the cancel */
s->pointer_slot = DM_TC_NONE;
s->pointer_valid = 0; s->pointer_x = s->pointer_y = 0;
s->pointer_pickup_done = 0;
s->pointer_pulse_active = s->pointer_pulse_pending = 0;
s->pointer_pending_x = s->pointer_pending_y = 0;
}
int dm_tc_pulse_end(dm_tc_state *s, uint64_t epoch) {
if (!s->pulse_button || s->pulse_epoch != epoch) return 0;
int ended_pointer = s->pointer_pulse_active;
if (s->defer_button && s->defer_at_s < s->last_time_s + DM_TC_ZL_LEAD_S) s->defer_at_s = s->last_time_s + DM_TC_ZL_LEAD_S; /* 等着补发的技能:从这一刻起 ZL 才能领先(见 dm_tc_tick) | Skill waiting for a make-up send: ZL can start leading only from this moment (see dm_tc_tick) */
s->pulse_button = 0; s->pulse_rx = s->pulse_ry = 0; s->pulse_hold_s = 0;
s->pointer_pulse_active = 0;
if (ended_pointer == 1) {
s->pointer_pickup_done = 1;
update_pointer(s);
}
update(s);
return 1;
}
int dm_tc_pulse_pending(const dm_tc_state *s) { return !s->pulse_button && s->pointer_pulse_pending; }
int dm_tc_pulse_resume(dm_tc_state *s) {
if (s->pulse_button || !s->pointer_pulse_pending) return 0;
int kind = s->pointer_pulse_pending;
s->pointer_pulse_pending = 0;
pointer_pulse_btn(s, s->pointer_pending_x, s->pointer_pending_y, kind, s->pointer_pending_button ? s->pointer_pending_button : DM_BTN_A, s->pointer_pending_hold);
s->pointer_pending_button = 0; s->pointer_pending_hold = 0;
update(s);
return 1;
}
void dm_tc_init(dm_tc_state *s, float width, float height) {
memset(s, 0, sizeof(*s));
s->pointer_release_item = 1;
dm_tc_layout_make(&s->layout, width, height);
s->enabled_targets = (1u << DM_TC_COUNT) - 1;
dm_tc_cancel_all(s);
}
void dm_tc_resize(dm_tc_state *s, float width, float height) {
uint64_t portal = s->layout.target[DM_TC_PORTAL].button;
dm_tc_cancel_all(s);
dm_tc_layout_make(&s->layout, width, height);
s->layout.target[DM_TC_PORTAL].button = portal;
}
void dm_tc_enable_targets(dm_tc_state *s, uint32_t mask) {
mask &= (1u << DM_TC_COUNT) - 1;
if (mask == s->enabled_targets) return;
dm_tc_cancel_all(s);
s->enabled_targets = mask;
}
void dm_tc_set_joy_block(dm_tc_state *s, int block) { s->joy_block = block != 0; }
void dm_tc_set_navigation_mode(dm_tc_state *s, int navigation_mode) {
navigation_mode = !!navigation_mode;
if (navigation_mode == s->navigation_mode) return;
dm_tc_cancel_all(s);
s->navigation_mode = navigation_mode;
}
/* 系统取消了这根手指(通知横幅、系统手势):不当松手——不补脉冲、不点世界、不点界面;只把它按着的键、摇杆、光标放掉 | The system cancelled this finger (notification banner, system gesture): do not treat it as a release -- no make-up pulse, no world tap, no UI click; only let go of the keys, stick and cursor it was holding */
void dm_tc_cancel_finger(dm_tc_state *s, int slot) {
if (slot < 0 || slot >= DM_TC_MAX_TOUCH) return;
++s->gesture_epoch;
if (s->finger[slot].active && s->finger[slot].target == DM_TC_PORTAL) { dm_tc_cancel_portal(s); }
if (slot == s->joy_slot && s->finger[slot].active) { s->joy_lost_s = s->last_time_s; s->joy_lost_x = s->finger[slot].x; s->joy_lost_y = s->finger[slot].y; } /* 系统取消了摇杆那根手指:记下,紧接着在附近重新落下的接着当摇杆 | the system cancelled the joystick finger: record it, and a finger landing again nearby right afterwards continues as the joystick */
s->finger[slot] = (dm_tc_finger){.target=DM_TC_NONE};
if (slot == s->joy_slot) { s->joy_slot = DM_TC_NONE; s->joy_origin_x = s->joy_origin_y = 0; }
if (slot == s->aim_slot) s->aim_slot = DM_TC_NONE;
if (slot == s->pointer_slot) { s->pointer_item = 0; s->pointer_shop = 0; s->pointer_stack = 0; s->pointer_lock = 0; s->pointer_slot = DM_TC_NONE; s->pointer_valid = 0; }
update(s);
}
void dm_tc_cancel_portal(dm_tc_state *s) {
++s->gesture_epoch; s->portal_pending=s->portal_phase=0;
for (int i=0;i<DM_TC_MAX_TOUCH;++i)
if(s->finger[i].active && s->finger[i].target==DM_TC_PORTAL)
s->finger[i]=(dm_tc_finger){.target=DM_TC_NONE};
update(s);
}
void dm_tc_set_portal_binding(dm_tc_state *s,uint64_t mask,uint64_t identity,uint64_t scene) {
if(s->layout.target[DM_TC_PORTAL].button==mask && s->portal_binding_identity==identity && s->portal_scene_epoch==scene)return;
dm_tc_cancel_portal(s);
s->portal_binding_identity=identity;s->portal_scene_epoch=scene;
s->layout.target[DM_TC_PORTAL].button=mask;update(s);
}
void dm_tc_set_portal_button(dm_tc_state *s,uint64_t mask) {
dm_tc_set_portal_binding(s,mask,s->portal_binding_identity,s->portal_scene_epoch);
}
int dm_tc_portal_ack(dm_tc_state *s,uint64_t epoch,uint64_t identity,uint64_t scene) {
if(!s->portal_pending || s->gesture_epoch!=epoch || s->portal_binding_identity!=identity || s->portal_scene_epoch!=scene)return 0;
int active=0;for(int i=0;i<DM_TC_MAX_TOUCH;i++)active|=s->finger[i].active && s->finger[i].target==DM_TC_PORTAL;
if(!active)return 0;
s->portal_pending=0;s->portal_phase=2;update(s);return 1;
}
/* 腰带展开着、这一点不在腰带上(底排四格与展开的几排之外):前端据此在自己的手势(小地图块、空位十字)之前先收腰带并吃掉这一下 | Belt expanded and this point is not on the belt (outside the four bottom-row cells and the expanded rows): based on this the front end collapses the belt and consumes this tap before its own gestures (minimap block, empty-slot cross) */
int dm_tc_belt_outside(const dm_tc_state *s, float x, float y) {
if (s->navigation_mode || !s->belt_open || s->belt_rows <= 1) return 0;
int hit = dm_tc_hit(&s->layout, x, y); if (hit >= DM_TC_BELT1 && hit <= DM_TC_BELT4) return 0;
float u = s->layout.height / 1320.0f;
for (int r = 1; r < s->belt_rows && r < 4; ++r) for (int c = 0; c < 4; ++c) {
const dm_tc_target *t = &s->layout.target[DM_TC_BELT1+c];
if (fabsf(x - t->x) <= 60*u && fabsf(y - (t->y - (165.0f + 162.0f*(r-1))*u)) <= 53.75f*u) return 0;
}
return 1;
}
/* 腰带点一下 = 自己喝,点几下喝几瓶(原版手感,不判双击)。底排 = 补一个腰带键脉冲(不带 ZL,第二组下也不带);上面几排手柄没有键 = belt_request 交宿主喝那一格。
喂雇佣兵不在腰带上做手势:佣兵面板里的原版入口和「自动给佣兵喝药」设置照旧
One tap on the belt = the player drinks, several taps drink several (original feel, no double-tap detection). Bottom row = one belt key pulse (without ZL, also under the second set); upper rows have no controller key = belt_request asks the host to drink that cell.
Feeding the mercenary has no gesture on the belt: the game's own entry in the mercenary panel and the "auto-feed mercenary" setting are unchanged */
static void belt_fire(dm_tc_state *s, int cell) {
if (cell >= 0x100) { s->belt_request = cell; return; }
uint64_t btn = s->layout.target[DM_TC_BELT1 + (cell & 0xf)].button; if (!btn) return;
if (s->pulse_button || s->defer_button || s->belt_gap_cell) { s->belt_q = cell; return; } /* 有脉冲在发 / 有补发在等:排着(dm_tc_tick 空了再发) | A pulse is being sent / a make-up send is waiting: queue it (dm_tc_tick sends it when free) */
if (s->skill_set && !s->navigation_mode) for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) { /* 按着第二组技能:先松 ZL 和技能键,隔 DM_TC_ZL_LEAD_S 再按腰带键(见 update) | a skill of the second skill set is held: first release ZL and the skill key, and press the belt key after DM_TC_ZL_LEAD_S (see update) */
const dm_tc_finger *f = &s->finger[i]; if (!f->active || f->aim_cancelled || f->target < DM_TC_MAIN || f->target > DM_TC_SKILL4) continue;
s->belt_gap_cell = 0x1000 | cell; s->belt_gap_at = s->last_time_s + DM_TC_ZL_LEAD_S; update(s); return; }
s->pulse_rx = s->pulse_ry = 0; s->pulse_button = btn; ++s->pulse_epoch;
update(s);
}
void dm_tc_begin_at(dm_tc_state *s, int slot, float x, float y, double now_s) {
if (slot < 0 || slot >= DM_TC_MAX_TOUCH || s->finger[slot].active || !isfinite(x) || !isfinite(y)) return;
s->last_time_s = now_s;
dm_tc_finger *f = &s->finger[slot];
if (!s->navigation_mode) { /* 难度:点第 0 格开 / 收选择条;展开时点某格 = 选档并收起,点别处只收起、照常处理 | Difficulty: tapping cell 0 opens / collapses the selector bar; when expanded, tapping a cell = select that level and collapse; tapping elsewhere only collapses and is then handled as usual */
const dm_tc_target *d = &s->layout.diff;
int on_diff = d->r > 0 && hypotf(x-d->x, y-d->y) <= d->r, pick = -1;
for (int i = 0; s->diff_open && i < 8; ++i) if (hypotf(x-s->layout.pick[i].x, y-s->layout.pick[i].y) <= s->layout.pick[i].r) pick = i;
if (on_diff || pick >= 0) {
if (pick >= 0) s->diff_request = pick + 1;
s->diff_open = on_diff ? !s->diff_open : 0;
*f = (dm_tc_finger){.active=1, .target=DM_TC_DIFF, .x=x, .y=y}; update(s); return;
}
s->diff_open = 0;
}
int hit = dm_tc_hit(&s->layout, x, y);
if (!s->navigation_mode && s->belt_open && s->belt_rows > 1) { /* 腰带展开着:点上面几排 = 喝那一格;点腰带以外 = 只收起 | Belt expanded: tapping the upper rows = drink that cell; tapping outside the belt = only collapse */
float u = s->layout.height / 1320.0f; /* 展开的几排是游戏自己画的:列与底排对齐,排距 162、第一排比底排高 165(效果图单位;真机 2868×1320 实量,行距由 gen_hud_v4.py 的 bpy 定,改那边要一起改) | The expanded rows are drawn by the game itself: columns align with the bottom row, row pitch 162, the first row is 165 above the bottom row (mock units; measured on a real device at 2868×1320; the row spacing is set by bpy in gen_hud_v4.py, and changing it there requires changing it here too) */
for (int r = 1; r < s->belt_rows && r < 4; ++r) for (int c = 0; c < 4; ++c) {
const dm_tc_target *t = &s->layout.target[DM_TC_BELT1+c];
if (fabsf(x - t->x) <= 60*u && fabsf(y - (t->y - (165.0f + 162.0f*(r-1))*u)) <= 53.75f*u) {
belt_fire(s, 0x100 | r << 4 | c); /* 按下就喝那一格 | drink that cell on press */
*f = (dm_tc_finger){.active=1, .target=DM_TC_DIFF, .x=x, .y=y}; update(s); return;
}
}
if (hit < DM_TC_BELT1 || hit > DM_TC_BELT4) { /* 点别处:只收腰带,这一下不再做别的(不走路、不点世界、不按键) | Tap elsewhere: only collapse the belt; this tap does nothing else (no walking, no world tap, no key press) */
s->belt_request = 2; *f = (dm_tc_finger){.active=1, .target=DM_TC_DIFF, .x=x, .y=y}; update(s); return;
}
}
if (hit == DM_TC_SWAP) {
if (s->navigation_mode) hit = DM_TC_NONE;
else { s->skill_set = !s->skill_set; *f = (dm_tc_finger){.active=1, .target=DM_TC_SWAP, .x=x, .y=y}; update(s); return; }
}
int enabled = hit >= 0 && (s->enabled_targets & (1u << hit));
/* 面板态:被禁用的目标(底栏腰带 / 功能键 / 回城、圆钮收起后的技能钮位置)不占手指——它们压着的地方可能正是面板的按钮
(设置页「应用」在屏幕底部,落在禁用的底栏目标上,既不判类也不点击)。游戏态仍占着(防隐藏的回城触点变成摇杆)
Panel state: disabled targets (bottom-bar belt / function key / town portal, and the skill button positions after the round buttons are hidden) do not capture fingers -- the place they cover may be exactly a panel button
(「应用」(Apply) on the settings page is at the bottom of the screen and landed on a disabled bottom-bar target, getting neither classified nor clicked). In game state they still capture (preventing a hidden town-portal touch point from turning into the stick) */
if (s->navigation_mode && hit >= 0 && !enabled) hit = DM_TC_NONE;
if(enabled && hit==DM_TC_PORTAL && s->layout.target[hit].button && s->portal_phase==0) {
++s->gesture_epoch;
uint64_t mask=s->layout.target[hit].button;
s->portal_pending=(mask&DM_BTN_ZL) && (mask&~DM_BTN_ZL);
s->portal_phase=s->portal_pending?1:2;
}
*f = (dm_tc_finger){.active=1, .target=enabled ? hit : DM_TC_NONE, .x=x, .y=y,
.aim_origin_x=x, .aim_origin_y=y,
.start_time_s=now_s};
/* 禁用圆仍阻止落入左摇杆区,防止隐藏回城触点变成移动。 | A disabled circle still blocks falling through into the left stick area, preventing a hidden town-portal touch point from turning into movement. */
if (s->navigation_mode && hit == DM_TC_NONE && s->pointer_slot == DM_TC_NONE) {
s->pointer_slot = slot;
s->pointer_item = 0;
/* 鼠标点击模式下,手柄光标只跟「落在物品区的手指」走(前端答出命中后调 dm_tc_pointer_item):
光标是靠推摇杆走的,在没有自由光标的页面(选项、暂停菜单、小站)推摇杆 = 改当前选项 / 挪焦点(点页签顺带改了「显示物品」)
In mouse click mode the controller cursor follows only "a finger that landed in the item area" (the front end calls dm_tc_pointer_item once it has the hit answer):
the cursor moves by pushing the stick, and on pages without a free cursor (options, pause menu, waypoint) pushing the stick = changing the current option / moving the focus (tapping a tab changed 「显示物品」(Show Items) as a side effect) */
if (!s->mouse_click_mode) { s->pointer_valid = 1; s->pointer_x = x; s->pointer_y = y; }
} else if (!s->navigation_mode && hit == DM_TC_NONE && g_edge_b > 0 && x >= 0 && x < s->layout.width*0.43f && y > s->layout.height - g_edge_b) {
f->target = DM_TC_EDGE;
} else if (!s->navigation_mode && !s->joy_block && hit == DM_TC_NONE && s->joy_slot == DM_TC_NONE &&
x >= 0 && y <= s->layout.height && x < s->layout.width*0.43f && y > s->layout.height*0.25f &&
(hypotf(x - s->layout.joy_x, y - s->layout.joy_y) <= DM_TC_JOY_GRAB_K * s->layout.joy_radius ||
(s->joy_lost_s > 0 && now_s - s->joy_lost_s <= DM_TC_JOY_RESUME_S && hypotf(x - s->joy_lost_x, y - s->joy_lost_y) <= DM_TC_JOY_GRAB_K * s->layout.joy_radius))) {
/* 摇杆底座固定在左下角原位:手指落在底座附近(DM_TC_JOY_GRAB_K 倍半径内)才起摇杆,方向与幅度按「手指相对底座中心」算,
按住后拖到多远都照样识别;落在左侧别处不起摇杆(照旧是点地)。原先是浮动摇杆:落在左侧区域哪里,底座就出在哪里、松手回原位。
例外:摇杆那根手指刚被系统取消(通知横幅、系统手势;dm_tc_cancel_finger 记下时刻与位置),DM_TC_JOY_RESUME_S 内在原处附近重新落下的手指接着当摇杆——
拖远了的摇杆被系统打断一下不该就此断掉;浮动摇杆时这种情形表现为底座追着手指重起
The joystick base is fixed at its home position in the lower left: the joystick starts only when a finger lands near the base (within DM_TC_JOY_GRAB_K × radius), and direction and magnitude are computed as "finger relative to the base center";
once held it is still recognized however far it is dragged; landing elsewhere on the left does not start the joystick (it is a ground tap as before). Previously it was a floating joystick: wherever in the left area the finger landed, the base appeared there, returning to its home position on release.
Exception: when the joystick finger has just been cancelled by the system (notification banner, system gesture; dm_tc_cancel_finger records the time and position), a finger landing again near the same spot within DM_TC_JOY_RESUME_S continues as the joystick --
a joystick dragged far away should not be cut off for good by a brief system interruption; with the floating joystick this case showed up as the base restarting under the finger */
s->joy_lost_s = 0;
f->target = DM_TC_JOYSTICK;
s->joy_slot = slot;
s->joy_origin_x = s->layout.joy_x;
s->joy_origin_y = s->layout.joy_y;
}
update(s);
}
void dm_tc_move_at(dm_tc_state *s, int slot, float x, float y, double now_s) {
if (slot < 0 || slot >= DM_TC_MAX_TOUCH || !s->finger[slot].active || !isfinite(x) || !isfinite(y)) return;
s->last_time_s = now_s;
dm_tc_finger *f = &s->finger[slot];
f->x = x;
f->y = y;
if (pointer_finger(s, f)) {
float distance = hypotf(f->x-f->aim_origin_x, f->y-f->aim_origin_y);
if (!f->pointer_dragged && distance > DM_TC_POINTER_MOVE_PT * scale_for(&s->layout) && (!s->mouse_click_mode || s->pointer_item == 1))
pointer_drag_begin(s, f); /* 鼠标点击模式:只有从物品区起手才是拖放;别处的滑动不发键。按住不动超过长按时长再拖也算拖放(真人「按住停一下再拖」,z4:0.5 秒后才动的拖放拿不起来) | Mouse click mode: only a gesture starting in the item area is a drag-and-drop; swipes elsewhere send no key. Holding still longer than the long-press duration and then dragging also counts as drag-and-drop (a real person "holds for a moment and then drags"; z4: a drag that started moving only after 0.5 seconds could not pick the item up) */
/* 起手在模态框外 / 被上层盖住(类 6 = 这一下不点)也不起滚动 / 滑块手势:原先模态框开着时框外上下滑照样给底下发滚轮 | A gesture starting outside the modal box / covered by an upper layer (class 6 = this tap does not click) does not start a scroll / slider gesture either: previously, with a modal box open, swiping up and down outside it still sent wheel events to what was underneath */
else if (s->mouse_click_mode && s->pointer_item != 1 && s->pointer_item != 3 && s->pointer_item != 6 && !f->ui_drag && !f->pointer_dragged && distance > DM_TC_POINTER_MOVE_PT * scale_for(&s->layout))
f->ui_drag = fabsf(f->x - f->aim_origin_x) > fabsf(f->y - f->aim_origin_y) ? 2 : 1; /* 界面连续手势:过阈值那一刻按方向定型(纵 = 滚动,横 = 滑块) | Continuous UI gesture: the type is fixed by direction at the moment the threshold is crossed (vertical = scroll, horizontal = slider) */
update_pointer(s);
} else if (!s->navigation_mode && skill_target(f->target)) {
if (inside_map_cancel(s, f)) f->aim_cancelled = 1;
if (!f->aim_cancelled) f->aim_move_sequence = ++s->aim_move_sequence;
}
update(s);
}
void dm_tc_end_at(dm_tc_state *s, int slot, double now_s) {
if (slot < 0 || slot >= DM_TC_MAX_TOUCH) return;
s->last_time_s = now_s;
if(s->finger[slot].active && s->finger[slot].target==DM_TC_PORTAL) {
s->finger[slot]=(dm_tc_finger){.target=DM_TC_NONE};
for(int i=0;i<DM_TC_MAX_TOUCH;i++)if(s->finger[i].active && s->finger[i].target==DM_TC_PORTAL) {update(s);return;}
dm_tc_cancel_portal(s);return;
}
dm_tc_finger done = s->finger[slot];
if (s->navigation_mode && slot == s->pointer_slot) {
float distance = hypotf(done.x-done.aim_origin_x, done.y-done.aim_origin_y);
double elapsed = now_s - done.start_time_s;
/* 商人货架上的货长按 = 原版的「按住 Y 大量购买」(提示条原文;宿主读数:约 1.3 秒):背包里有没满的卷轴书 / 同类叠时买满,没有就和买 1 份一样;买多少、钱够不够都由游戏定,这里只替玩家按键 | Long press on goods on the vendor shelf = the original game's 「按住 Y 大量购买」(Hold Y to buy in bulk) (button legend text; host reading: about 1.3 seconds): when the inventory has a non-full scroll tome / stack of the same kind it buys until full, otherwise it is the same as buying 1; how many to buy and whether there is enough gold are decided by the game, and here we only press the key for the player */
if (done.pointer_long && !done.pointer_dragged && !done.shop_drag && s->pointer_item == 1 && s->pointer_shop) pointer_pulse_btn(s, done.aim_origin_x, done.aim_origin_y, 2, DM_BTN_Y, 1.3);
else if (done.pointer_long && !done.pointer_dragged && !done.shop_drag && s->pointer_item == 1 && !s->pointer_lock) ++s->long_press_seq; /* 长按在松手时才算(按住没动):按住到点就算的话,「按住停一下再拖」的药水会先被放进腰带(mini 药拖腰带脚本里多出 2 次) | Long press counts only at release (held without moving): if it counted as soon as the hold time was reached, a potion that is "held for a moment and then dragged" would first be put into the belt (2 extra occurrences in the potion-drag-to-belt script on the second Mac) */
if (done.locked_drag) { } /* 单件槽占用时拖别的物品:不发任何键 | Dragging another item while the single-item slot is occupied: send no key */
else if (done.shop_drag) { ++s->shop_drop_seq; } /* 买不买由前端按落点定;这里不发任何键 | Whether to buy is decided by the front end from the drop point; no key is sent here */
else if (done.pointer_dragged) {
if (s->pointer_release_item == 1) pointer_pulse_start(s, done.x, done.y - DM_TC_POINTER_LIFT_PT * scale_for(&s->layout), 2); /* 放在抬起点(物品显示的位置) | Place at the lifted point (where the item is displayed) */
else if (s->pointer_release_item == 5) pointer_pulse_start(s, s->release_x, s->release_y, 2); /* 宿主给的放下位置(装备槽 = 槽心) | Drop position given by the host (equipment slot = slot center) */
else if (s->pointer_release_item == 4) pointer_pulse_start(s, done.x, done.y, 2); /* 放在手指点(玩家对着手指放) | Place at the finger point (the player aims with the finger) */
else if (s->pointer_release_item == 3) pointer_pulse_btn(s, done.aim_origin_x, done.aim_origin_y, 2, DM_BTN_Y, 0.15); /* 手指在面板外 = 丢弃:指针回原处、到位后按 Y | Finger outside the panel = discard: pointer returns to the original spot and presses Y once in place */
else if (s->pointer_release_item == 8) { /* 松在单件任务槽上:按原版走法重做——先放回原格,再对它按住 Y(原版的「放进槽」)。只把物品拿在手上停在槽上方不算进槽:槽会显示它,但点确认不成交(本机 实测没有成交包) | Released on the single-item quest slot: redo it the original game's way -- first put it back in its original cell, then hold Y on it (the original game's "put into slot"). Merely holding the item and hovering over the slot does not count as entering the slot: the slot shows it, but tapping confirm does not complete the transaction (measured on the local machine: no transaction packet) */
pointer_pulse_start(s, done.aim_origin_x, done.aim_origin_y, 2); pointer_pulse_btn(s, done.aim_origin_x, done.aim_origin_y, 2, DM_BTN_Y, 1.3); }
else pointer_pulse_start(s, done.aim_origin_x, done.aim_origin_y, 2); /* 面板里的空白处:放回原处 | Blank area inside the panel: put it back where it was */
} else if (!done.ui_drag && !done.pointer_long && elapsed < DM_TC_POINTER_TAP_S && distance <= DM_TC_POINTER_MOVE_PT * scale_for(&s->layout)) { /* 拖出去又拖回原处不算点按 | Dragging out and back to the original spot does not count as a tap */
/* 单件任务槽面板开着时,手上那件就是「槽里那件」:点背包格仍是放回去,点别处按没拿着处理——确认 / 关闭按钮要能点,点面板外 = 关面板(不是把槽里那件丢到地上) | While the single-item quest slot panel is open, the held item is "the one in the slot": tapping an inventory cell still puts it back, tapping elsewhere is handled as if nothing were held -- the confirm / close buttons must be tappable, and tapping outside the panel = close the panel (not drop the slot's item on the ground) */
if (s->pointer_lock) { s->pointer_x = done.aim_origin_x; s->pointer_y = done.aim_origin_y; } /* 单件槽占用时点别的物品:只移光标出说明,单击 / 双击都不动它 | Tapping another item while the single-item slot is occupied: only move the cursor to show the tooltip; neither single nor double tap moves it */
else if (s->holding && s->pointer_item != 0 && !(atomic_load(&g_imbue_open) && s->pointer_item != 1)) { if (s->pointer_item == 1) pointer_pulse_start(s, done.aim_origin_x, done.aim_origin_y, 2);
else if (s->pointer_item == 3) pointer_pulse_btn(s, s->pointer_x, s->pointer_y, 2, DM_BTN_Y, 0.15); } /* 手上还拿着物品(上次没放成):点物品区 = 放下;点面板外 / 两侧黑网格 = 丢(Y);点页签等别处不动。
点按钮(类 0)不在这里吞掉、照常发鼠标点击:原先连合成钮也吞,手上有东西时点合成什么都不发;合成钮由宿主先收手上那件再按,见 dm_cursor.c
Still holding an item (the last drop did not succeed): tap the item area = put down; tap outside the panel / the black grid on either side = drop (Y); tapping tabs or elsewhere does nothing.
Tapping a button (class 0) is not swallowed here and sends a mouse click as usual: previously even the transmute button was swallowed, and tapping transmute with something in hand sent nothing; for the transmute button the host first stows the held item and then presses, see dm_cursor.c */
else if (s->pointer_item == 2) { ++s->tab_tap_seq; }
else if (s->pointer_item == 6 || s->pointer_item == 11) { } /* 压着被上层面板盖住的按钮:不点、不发键 | Pressing on a button covered by an upper panel: no click, no key */
else if (s->pointer_item == 3) { if (!atomic_load(&g_dead_modal)) { s->close_left = 3; s->close_next_s = now_s; atomic_store(&g_close_stop, 0); } } /* 面板外:不发鼠标点击(会落到游戏世界 = 点地走路),按 B 关面板——子菜单里一下 B 只退一级,所以按到面板关掉为止(至多 3 下,见 dm_tc_tick);死亡弹窗开着时不动 | Outside the panel: do not send a mouse click (it would land in the game world = tap ground to walk); press B to close the panel -- in a submenu one B only goes back one level, so press until the panel is closed (at most 3 presses, see dm_tc_tick); do nothing while the death popup is open */
else if (s->pointer_item) { /* 物品区:单击只移光标(游戏自己出说明);紧接着在同一处再点一下 = 按住 A / Y | Item area: a single tap only moves the cursor (the game shows the tooltip itself); another tap at the same spot right after = hold A / Y */
float ox = done.aim_origin_x, oy = done.aim_origin_y;
int dbl = now_s - s->last_tap_s < DM_TC_DOUBLE_TAP_S && hypotf(ox - s->last_tap_x, oy - s->last_tap_y) <= 2 * DM_TC_POINTER_MOVE_PT * scale_for(&s->layout);
if (dbl) { if (atomic_load(&g_hover_unid) && !s->pointer_stack && !s->pointer_shop) ++s->ident_seq; /* 未鉴定物品:双击 = 免费鉴定(各页都先判;商人货架上的货不算我方物品,宿主也不发布) | Unidentified item: double tap = free identify (checked first on every page; goods on the vendor shelf are not our items, and the host does not publish them either) */
else if (s->pointer_stack) ++s->stack_take_seq; /* 成叠格:取 1 件(原版短按 Y;这里不按键,按住 0.6 秒会变成「移动 3 个」) | Stacked cell: take 1 (short press Y in the original game; no key is pressed here, since holding for 0.6 seconds would become "move 3") */
else if (atomic_load(&g_imbue_open)) pointer_pulse_btn(s, ox, oy, 2, DM_BTN_Y, 1.3); /* 单件任务槽面板:原版对背包物品按住 Y = 放进槽(宿主读数:约 1.3 秒);不能当「使用」——否则在古墓底座前双击法杖会被装到手上 | Single-item quest slot panel: in the original game holding Y on an inventory item = put it into the slot (host reading: about 1.3 seconds); it must not be treated as "use" -- otherwise double-tapping the staff in front of the tomb pedestal would equip it in hand */
else if (atomic_load(&g_bank_open) && !atomic_load(&g_tap_box) && !atomic_load(&g_vault_open)) {
/* 背包里的物品:先发原版的 X(移动到堆叠栏)。能堆叠的(符文 / 宝石 / 材料)游戏收下、进堆叠格;不能堆叠的游戏对 X 不做任何事,0.4 秒后它还在光标下就退回按住 Y。
不直接按住 Y:那是「到仓库当前这一页」,在符文 / 宝石页且背包带着魔盒时会进页里嵌的魔盒格。仓库一侧的物品不走这里,仍是按住 Y 取回
Item in the inventory: first send the original game's X (move to the stacking tab). Stackable ones (runes / gems / materials) are accepted by the game and go into a stack cell; for non-stackable ones the game does nothing on X, and if it is still under the cursor after 0.4 seconds, fall back to hold Y.
Do not hold Y directly: that means "to the stash's current page", and on the rune / gem page with a cube in the inventory it would go into the cube cell embedded in the page. Items on the stash side do not go through here; they are still retrieved by holding Y */
if (atomic_load(&g_cur_stack)) { pointer_pulse_btn(s, ox, oy, 2, DM_BTN_X, 0.15); s->stash_x_check_s = now_s + 0.4; s->stash_x_x = ox; s->stash_x_y = oy; s->stash_x_id = atomic_load(&g_cur_stack); }
else pointer_pulse_btn(s, ox, oy, 2, DM_BTN_Y, DM_TC_HOLD_USE_S); }
else if (atomic_load(&g_cube_open) && !atomic_load(&g_bank_open)) pointer_pulse_btn(s, ox, oy, 2, DM_BTN_Y, DM_TC_HOLD_USE_S); /* 方块页(不是箱子里嵌的那格):原版按住 Y 一步送进 / 送出方块;与箱子页双击同一条规则 | Cube page (not the cell embedded in the stash): in the original game holding Y sends the item into / out of the cube in one step; same rule as double tap on the stash page */
else ++s->use_seq; /* 开着箱子:按住 Y = 移到另一侧(魔盒除外:原版开箱时按住 A 仍是打开魔盒,读码);否则交给宿主当场使用(原先按住 A 0.6 秒,约 0.4 秒后才生效) | Stash open: hold Y = move to the other side (except the cube: in the original game holding A with the stash open still opens the cube, per the code); otherwise hand it to the host to use on the spot (it used to hold A for 0.6 seconds and took effect only after about 0.4 seconds) */
s->last_tap_s = -1e9; }
else { /* 单击:移光标。隔了一会儿(不算双击)又点同一处 = 与另一件已装备的比较(原版按 ZL 循环;说明框文案「再点一次与另一件比较」) | Single tap: move the cursor. Tapping the same spot again after a while (not a double tap) = compare with the other equipped item (the original game cycles with ZL; tooltip text 「再点一次与另一件比较」(Tap again to compare with the other one)) */
int again = now_s - s->last_tap_s < 8.0 && hypotf(ox - s->last_tap_x, oy - s->last_tap_y) <= 2 * DM_TC_POINTER_MOVE_PT * scale_for(&s->layout);
if (again && !atomic_load(&g_bank_open) && !atomic_load(&g_vendor_open)) pointer_pulse_btn(s, ox, oy, 2, DM_BTN_ZL, 0); /* 开着箱子 / 商人页时 ZL 是切页签,不发(货上点第二下把货架翻到了下一页) | With the stash / vendor page open ZL switches tabs, so do not send it (a second tap on goods flipped the shelf to the next page) */
else if (!s->pulse_button) { s->pointer_x = ox; s->pointer_y = oy; }
++s->item_tap_seq; s->last_tap_s = now_s; s->last_tap_x = ox; s->last_tap_y = oy; }
} else if (s->tap_button) {
s->pointer_valid = 1; pointer_pulse_btn(s, s->tap_x, s->tap_y, 2, s->tap_button, 0); /* 前端改写:光标到点 + 按键(技能绑定里点技能) | Front-end rewrite: cursor to the point + key press (tapping a skill in skill binding) */
} else if (s->tap_move) {
s->pointer_valid = 1; s->pointer_x = s->tap_x; s->pointer_y = s->tap_y; ++s->tap_move_seq;
} else if (s->mouse_click_mode) {
s->mouse_click_x = done.aim_origin_x; s->mouse_click_y = done.aim_origin_y; ++s->mouse_click_seq;
} else pointer_pulse_start(s, done.aim_origin_x, done.aim_origin_y, 2);
}
s->pointer_item = 0; s->pointer_release_item = 1; s->pointer_shop = 0; s->pointer_stack = 0; s->pointer_lock = 0;
s->pointer_slot = DM_TC_NONE;
s->finger[slot] = (dm_tc_finger){.target=DM_TC_NONE};
update(s);
return;
}
/* 技能钮:按住 = 持续施放、拖动定方向、松手键起,不再是「按住瞄准、松手放一下」。
唯一要补的:点得太短,键还没来得及按下手就松了(不到点按 / 拖动的判定时间,或第二组里 ZL 还没领先够)——补成一个带方向的脉冲;
第二组里 ZL 还没领先够时,这个脉冲延到够了再发(dm_tc_tick)。
Skill button: hold = continuous cast, drag sets the direction, release lifts the key; no longer "hold to aim, release to cast once".
The only thing to make up: the tap was too short and the finger lifted before the key could go down (shorter than the tap / drag decision time, or in the second set ZL has not led long enough) -- make it up as one pulse with direction;
in the second set, when ZL has not led long enough, this pulse is delayed until it has (dm_tc_tick). */
if (done.active && done.target >= DM_TC_SKILL1 && done.target <= DM_TC_SKILL4 && !done.aim_cancelled && !s->navigation_mode
&& (!done.key_down || now_s - done.key_down_s < DM_TC_KEY_MIN_S || (s->skill_set && now_s - done.start_time_s < DM_TC_ZL_LEAD_S))) { /* 键没按下过,或按下不到 2 帧(游戏可能漏读):补成脉冲 | The key was never pressed, or was pressed for less than 2 frames (the game may miss it): make it up as a pulse */
float ux = 0, uy = 0; int has = aim_dir(s, &done, &ux, &uy);
s->pulse_rx = has ? (int32_t)lroundf(ux*DM_STICK_MAX) : 0; s->pulse_ry = has ? (int32_t)lroundf(-uy*DM_STICK_MAX) : 0;
if (s->skill_set && now_s - done.start_time_s < DM_TC_ZL_LEAD_S) { s->defer_button = s->layout.target[done.target].button; s->defer_at_s = done.start_time_s + DM_TC_ZL_LEAD_S; }
else { s->pulse_button = s->layout.target[done.target].button; ++s->pulse_epoch; }
}
if (done.active && !s->navigation_mode && done.target >= DM_TC_BELT1 && done.target <= DM_TC_BELT4) {
/* 腰带格松手这一刻判:多排时上移过阈值 = 展开,下移过阈值 = 收起;几乎没动 = 点了一下,这一刻就喝;横着滑走了什么都不做 | decided when a belt cell is released: with multiple rows, moved up past the threshold = expand, down past the threshold = collapse; barely moved = a tap, drink right then; slid away sideways = do nothing */
float th = DM_TC_BELT_SWIPE_PT * scale_for(&s->layout), up = done.aim_origin_y - done.y, dx = done.x - done.aim_origin_x;
if (s->belt_rows > 1 && up > th) s->belt_request = 1;
else if (s->belt_rows > 1 && up < -th) s->belt_request = 2;
else if (fabsf(dx) <= th && fabsf(up) <= th) belt_fire(s, 0x10 | (done.target - DM_TC_BELT1));
}
if (done.active && !s->navigation_mode && done.target == DM_TC_NONE && now_s - done.start_time_s < DM_TC_POINTER_TAP_S && /* 落在摇杆底座上的那一下是摇杆(一按就有方向),不再兼作点地 | the tap that lands on the joystick base is the joystick (direction as soon as pressed) and no longer doubles as a ground tap */
hypotf(done.x - done.aim_origin_x, done.y - done.aim_origin_y) <= DM_TC_POINTER_MOVE_PT * scale_for(&s->layout)) {
s->world_tap_x = done.aim_origin_x; s->world_tap_y = done.aim_origin_y; ++s->world_tap_seq; /* 点游戏世界 | Tap the game world */
}
s->finger[slot] = (dm_tc_finger){.target=DM_TC_NONE};
if (slot == s->joy_slot) {
s->joy_slot = DM_TC_NONE;
s->joy_origin_x = s->joy_origin_y = 0;
}
update(s);
}
void dm_tc_begin(dm_tc_state *s, int slot, float x, float y) { dm_tc_begin_at(s, slot, x, y, s->last_time_s); }
void dm_tc_move(dm_tc_state *s, int slot, float x, float y) { dm_tc_move_at(s, slot, x, y, s->last_time_s); }
void dm_tc_end(dm_tc_state *s, int slot) { dm_tc_end_at(s, slot, s->last_time_s); }
void dm_tc_pointer_press(dm_tc_state *s, float x, float y, uint64_t button) {
if (s->pointer_slot >= 0 && s->pointer_slot < DM_TC_MAX_TOUCH) s->finger[s->pointer_slot].pointer_long = 1;
s->pointer_valid = 1; pointer_pulse_btn(s, x, y, 2, button, 0); update(s);
}
void dm_tc_tick(dm_tc_state *s, double now_s) {
s->last_time_s = now_s;
/* 补发不许盖掉在发的脉冲(腰带喝药等):在发就等;那个脉冲收回时(dm_tc_pulse_end)把补发时刻推到 ZL 再领先满 DM_TC_ZL_LEAD_S 之后(原先到点直接覆盖,腰带那下没了) | The make-up send must not overwrite a pulse being sent (belt potion, etc.): wait while one is being sent; when that pulse is released (dm_tc_pulse_end), push the make-up time to after ZL has again led for a full DM_TC_ZL_LEAD_S (it used to overwrite directly when due, and the belt press was lost) */
if (s->belt_gap_cell && now_s >= s->belt_gap_at && !s->pulse_button) { uint64_t btn = s->layout.target[DM_TC_BELT1 + (s->belt_gap_cell & 0xf)].button; s->belt_gap_cell = 0;
if (btn && !s->navigation_mode) { s->pulse_rx = s->pulse_ry = 0; s->pulse_button = btn; ++s->pulse_epoch; } update(s); }
if (s->belt_q && !s->pulse_button && !s->defer_button && !s->belt_gap_cell) { int q = s->belt_q; s->belt_q = 0; if (!s->navigation_mode) belt_fire(s, q); }
if (s->defer_button && !s->pulse_button && now_s >= s->defer_at_s) { s->pulse_button = s->defer_button; s->defer_button = 0; ++s->pulse_epoch; update(s); }
else if (!s->navigation_mode) { /* 主钮 / 技能钮上有手指:判定时间、ZL 领先这两个时刻要按时刷新键值 | A finger is on the main button / a skill button: the key values must be refreshed on time at two moments, the decision time and the ZL lead */
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) if (s->finger[i].active && (s->finger[i].target >= DM_TC_MAIN && s->finger[i].target <= DM_TC_SKILL4)) { update(s); break; }
}
if (s->stash_x_check_s > 0 && now_s >= s->stash_x_check_s) { /* 发过 X 的那件还在光标下(不能堆叠 / 这个存档没有堆叠栏 / 那一叠满了):退回按住 Y,移到仓库当前页。核的是同一个物品 id,X 已经把它移走就什么都不做 | The item that X was sent for is still under the cursor (not stackable / this save has no stacking tab / that stack is full): fall back to hold Y, moving it to the stash's current page. The check is on the same item id; if X has already moved it away, do nothing */
s->stash_x_check_s = 0;
if (atomic_load(&g_bank_open) && atomic_load(&g_cur_stack) == s->stash_x_id && !s->holding && !s->pulse_button) { pointer_pulse_btn(s, s->stash_x_x, s->stash_x_y, 2, DM_BTN_Y, DM_TC_HOLD_USE_S); update(s); }
}
if (s->close_left > 0 && atomic_exchange(&g_close_stop, 0)) s->close_left = 0; /* 返回键引出了确认框(设置页有未应用的改动):停手,让玩家自己答——再按一下就成了替他选「放弃」(改动丢失) | The back button brought up a confirmation box (the settings page has unapplied changes): stop and let the player answer -- one more press would choose 「放弃」(Discard) on their behalf (changes lost) */
if (s->close_left > 0) { /* 面板外点按 = 关到底:面板还开着、上一下 B 已收回,就隔 0.3 秒再按一下 | Tap outside the panel = close all the way: if the panel is still open and the previous B has been released, press once more after 0.3 seconds */
if (!s->navigation_mode) s->close_left = 0;
else if (!s->pulse_button && now_s >= s->close_next_s) { s->pulse_button = DM_BTN_B; s->pulse_hold_s = 0; s->pulse_rx = s->pulse_ry = 0; s->pointer_pulse_active = 2; ++s->pulse_epoch; --s->close_left; s->close_next_s = now_s + 0.3; update(s); }
}
if (s->pointer_slot < 0 || s->pointer_slot >= DM_TC_MAX_TOUCH) return;
dm_tc_finger *f = &s->finger[s->pointer_slot];
if (!f->active || f->pointer_dragged || f->pointer_long) return;
if (s->mouse_click_mode && s->pointer_item != 1) return;
if (now_s - f->start_time_s >= DM_TC_POINTER_HOLD_S &&
hypotf(f->x-f->aim_origin_x, f->y-f->aim_origin_y) <= DM_TC_POINTER_MOVE_PT * scale_for(&s->layout)) {
f->pointer_long = 1;
s->pointer_x = f->aim_origin_x;
s->pointer_y = f->aim_origin_y;
update(s);
}
}
int dm_tc_navigation(dm_tc_scene *s, const char *cat, const char *act, const char *arg) {
static const char *names[]={"PlayerInventoryExpansionLayout","SkillsTreePanel","PauseLayout","PauseLayoutGarden","CharacterStatsPanel","QuestLogPanelExpansion","BankExpansionLayout","HoradricCubeLayout","WaypointsPanelExpansion","NpcDialogPanel","NpcTradePanel","ButtonBindingModal","SkillSelect","YouDiedModal"};
if(!strcmp(cat,"FrontEndNavigation")&&!strcmp(act,"ToFrontEnd")) { s->game=0;s->panels=0; }
if(!strcmp(cat,"PanelManager")) {
if(!strcmp(arg,"LoadScreenPanel")&&!strcmp(act,"OpenPanel"))s->game=0;
if(!strcmp(arg,"LoadScreenPanel")&&!strcmp(act,"UnloadPanel"))s->game=1;
if(!strcmp(act,"UnloadAll"))s->panels=0;
{ size_t al=strlen(arg); if((!strcmp(act,"OpenPanel")||!strcmp(act,"OpenExclusivePanel"))&&al>5&&!strcmp(arg+al-5,"Modal"))atomic_store(&g_close_stop,1); }
for(unsigned i=0;i<sizeof(names)/sizeof(*names);i++)if(!strcmp(arg,names[i])) {
if(!strcmp(act,"OpenPanel")||!strcmp(act,"OpenExclusivePanel"))s->panels|=1ull<<i;
if(!strcmp(act,"ClosePanel")||!strcmp(act,"UnloadPanel"))s->panels&=~(1ull<<i);
}
}
return !s->game||s->panels!=0;
}
/* 死亡弹窗开着:也算导航态(触点走界面点击,能点到「继续」),但五个手柄圆钮不给——死后点技能钮位置会触发复活,容易误触 | Death popup open: also counts as navigation state (touch points go through UI clicks, so 「继续」(Continue) can be tapped), but the five controller round buttons are not offered -- after death a tap at a skill button position triggers resurrection, which is easy to hit by mistake */
int dm_tc_scene_dead(void) { return atomic_load(&g_dead_modal); }
int dm_tc_scene_dialog_only(const dm_tc_scene *s) { return s->game && s->panels == (1ull << 9); } /* 面板表第 9 项 = NpcDialogPanel(见 dm_tc_navigation 的 names) | Entry 9 of the panel table = NpcDialogPanel (see names in dm_tc_navigation) */
+204
View File
@@ -0,0 +1,204 @@
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { DM_TC_MAX_TOUCH = 16, DM_TC_COUNT = 12 };
enum {
DM_TC_NONE = -1, DM_TC_JOYSTICK = -2, DM_TC_SWAP = -3, DM_TC_DIFF = -4, /* DIFF:难度格 / 选择条占用的手指,不发按键 | DIFF: a finger captured by the difficulty cell / selector bar; sends no key */
DM_TC_EDGE = -5, /* 屏幕底边归系统的那一条里起手的手指:不当摇杆,松手也不当点地 | A finger that started in the strip along the bottom edge of the screen that belongs to the system: not treated as the stick, and its release is not treated as a ground tap */
DM_TC_MAIN = 0,
DM_TC_SKILL1, DM_TC_SKILL2, DM_TC_SKILL3, DM_TC_SKILL4,
DM_TC_PORTAL, DM_TC_BELT1, DM_TC_BELT2, DM_TC_BELT3, DM_TC_BELT4,
DM_TC_MENU, DM_TC_MAP
};
typedef struct { float x, y, r; uint64_t button; } dm_tc_target;
typedef struct {
float width, height;
dm_tc_target target[DM_TC_COUNT];
float joy_x, joy_y, joy_radius;
dm_tc_target swap; /* 技能组切换键:本地开关,不直接发按键 | Skill set switch key: a local toggle; does not send a key directly */
dm_tc_target diff; /* 底部 UI v4 第 0 格难度:点开 / 收起 1–8 选择条,不发按键 | Bottom UI v4 cell 0 difficulty: tap to open / collapse the 1–8 selector bar; sends no key */
dm_tc_target pick[8]; /* 选择条 8 格(第 i 格 = 人数档 i+1),在七格上方 | The selector bar's 8 cells (cell i = player-count level i+1), above the seven cells */
} dm_tc_layout;
typedef struct {
int active, target;
float x, y;
float aim_origin_x, aim_origin_y;
uint64_t aim_move_sequence;
int aim_cancelled;
int key_down; double key_down_s; /* 技能钮:键是否已按下过、几时按下的(按下后先等判定时间,见 update) | Skill button: whether the key has gone down and when (after press, first wait the decision time, see update) */
double start_time_s;
int pointer_dragged, pointer_long;
/* 界面连续手势(鼠标点击模式、起手不在物品区也不在面板外、位移过阈值时按起始方向定型,定型后不变):1 = 纵向拖(滚动),2 = 横向拖(滑块)。
手势层只定型,前端看到后把起手点与当前点转给宿主(dm_ui_drag_*),滚动 / 滑块由宿主按游戏自己的命中去做
Continuous UI gesture (mouse click mode, started neither in the item area nor outside the panel; when displacement crosses the threshold the type is fixed by the initial direction and does not change afterwards): 1 = vertical drag (scroll), 2 = horizontal drag (slider).
The gesture layer only fixes the type; on seeing it the front end forwards the start point and current point to the host (dm_ui_drag_*), and the scroll / slider is done by the host according to the game's own hit testing */
int ui_drag;
int shop_drag; /* 从商人货架的货上起拖(不拿起):松手按落点买 / 不买 | Drag starting from goods on the vendor shelf (not picked up): on release, buy / do not buy by the drop point */
int locked_drag; /* 单件任务槽占用时从别的物品上起拖:不拿起,松手不发任何键 | Drag starting from another item while the single-item quest slot is occupied: do not pick up, and send no key on release */
} dm_tc_finger;
typedef struct {
dm_tc_layout layout;
dm_tc_finger finger[DM_TC_MAX_TOUCH];
int joy_slot;
float joy_origin_x, joy_origin_y;
uint32_t enabled_targets;
uint64_t buttons;
int32_t lx, ly, rx, ry;
int aim_slot, navigation_mode, map_cancel_active;
uint64_t aim_move_sequence;
int portal_pending, portal_phase; // 0idle / 1modifier-pending / 2armed
uint64_t gesture_epoch, portal_binding_identity, portal_scene_epoch;
/* 松手施放的短按脉冲:按键与右轴方向同时发布,前端到时调 dm_tc_pulse_end 收回 | Short-press pulse for release-to-cast: the key and the right-axis direction are published together, and the front end calls dm_tc_pulse_end to release it when due */
uint64_t pulse_button, pulse_epoch;
int32_t pulse_rx, pulse_ry;
uint64_t defer_button; double defer_at_s; /* 第二组里点得太短的那一下:等 ZL 领先够了再补发 | The too-short tap in the second set: make it up once ZL has led long enough */
/* 技能组:0 = 第一套;1 = 第二套(原版 Switch 按住 ZL 用 alt 槽)。是模式,不随取消/尺寸变化清零 | Skill set: 0 = first set; 1 = second set (on the original Switch game, holding ZL uses the alt slots). It is a mode and is not cleared on cancel/size change */
int skill_set;
/* 第二组技能(ZL 修饰):ZL 只在手指按着主钮 / 技能钮、或技能脉冲在发时按着,且先于技能键 DM_TC_ZL_LEAD_S 按下。
松手施放按得太短时,这一下脉冲延到 ZL 领先够了再发(dm_tc_tick 到点起)。
Second skill set (ZL modifier): ZL is held only while a finger is on the main button / a skill button or a skill pulse is being sent, and goes down DM_TC_ZL_LEAD_S before the skill button.
When a release-to-cast press is too short, that pulse is delayed until ZL has led long enough (dm_tc_tick starts it when due). */
int pointer_slot;
double last_time_s;
int pointer_pickup_done;
int pointer_pulse_active, pointer_pulse_pending;
float pointer_pending_x, pointer_pending_y;
int pointer_valid;
float pointer_x, pointer_y;
/* 物品手势:pointer_item = 当前指针手指落在物品区(前端在松手前按宿主命中结果置位)。物品区单击只移光标(出说明)、
双击 = 按住 A(游戏提示:按住 = 打开 / 使用 / 装备;开着箱子时按住 Y = 移到另一侧);非物品区单击照旧 = 移光标 + 按 A。
pulse_hold_s > 0 = 这个脉冲要按住这么久,前端在「游戏已取走」之外再等满它才收
Item gestures: pointer_item = the current pointer finger landed in the item area (set by the front end before release from the host's hit result). A single tap in the item area only moves the cursor (shows the tooltip),
double tap = hold A (game hint: hold = open / use / equip; with the stash open, hold Y = move to the other side); a single tap outside the item area is as before = move the cursor + press A.
pulse_hold_s > 0 = this pulse must be held this long, and the front end waits it out in full in addition to "the game has consumed it" before releasing */
int pointer_item;
/* 非物品区的点按走鼠标点击(暂停菜单按钮、布局里插回的关闭 / 修理等按钮只认鼠标):mouse_click_mode 由前端打开;
每次这样的点按 mouse_click_seq 加一,前端看到变化就在 (mouse_click_x, mouse_click_y) 发一次界面鼠标点击,不再按 A
Taps outside the item area go through mouse clicks (pause menu buttons and the close / repair buttons inserted back into the layout only respond to the mouse): mouse_click_mode is turned on by the front end;
each such tap increments mouse_click_seq, and on seeing a change the front end sends one UI mouse click at (mouse_click_x, mouse_click_y) and no longer presses A */
/* 拖放松手处(物品抬在手指上方的那个落点)是不是物品区:前端松手前置位。不是 = 拖到面板外 = 丢弃(指针回原处、到位后按 Y)。
holding = 光标上还拿着物品(上一次没放成):这时点物品区 = 放下(A),点别处不动
Whether the drag-and-drop release spot (the drop point where the item is lifted above the finger) is the item area: set by the front end before release. If not = dragged outside the panel = discard (pointer returns to the original spot and presses Y once in place).
holding = the cursor is still holding an item (the last drop did not succeed): then tapping the item area = put down (A), tapping elsewhere does nothing */
int pointer_release_item, holding; float release_x, release_y;
/* 游戏态(没开面板)的点按 = 点游戏世界:手指没落在任何控件目标上(含落在摇杆区但没拖动)、按下到抬起不到 0.35 秒、位移不超过点按阈值
→ world_tap_seq 加一,前端看到变化调宿主 dm_world_tap(点物品名拾取 / 点 NPC 对话 / 点箱子,点空地什么都不发)。
A tap in game state (no panel open) = tap the game world: the finger did not land on any widget target (including landing in the stick area without dragging), less than 0.35 seconds from press to lift, displacement within the tap threshold
→ world_tap_seq is incremented, and on seeing a change the front end calls the host's dm_world_tap (tap an item name to pick up / tap an NPC to talk / tap a chest; tapping empty ground sends nothing). */
unsigned world_tap_seq; float world_tap_x, world_tap_y;
int close_left; double close_next_s; /* 面板外点按后还要按几下 B、下一下最早什么时候(按到面板关掉为止) | After a tap outside the panel, how many more B presses remain and the earliest time of the next one (press until the panel is closed) */
/* 商人页:这次按下落在货架的货上(前端按宿主命中结果 7 置位)。从货上起拖 = 想买:不发「拿起」、光标留在那件货上(宿主买的是光标选中的那件);
松手时 shop_drop_seq 加一,前端按落点决定——落在背包类物品区 = 买,拖回货架 / 面板外 / 别处 = 不买
Vendor page: this press landed on goods on the shelf (set by the front end on host hit result 7). A drag starting from goods = intent to buy: do not send "pick up", and the cursor stays on that item (the host buys the item the cursor has selected);
on release shop_drop_seq is incremented and the front end decides by the drop point -- landing in an inventory-type item area = buy; dragged back to the shelf / outside the panel / elsewhere = do not buy */
int pointer_shop; unsigned shop_drop_seq;
int pointer_lock; /* 单件任务槽里有东西时按在别的物品上(宿主命中结果 10):照物品区移光标出说明,但不拿起、双击 / 长按 / 单击都不动它,也不把槽里那件放过来 | Pressing on another item while the single-item quest slot holds something (host hit result 10): move the cursor and show the tooltip as in the item area, but do not pick it up; double tap / long press / single tap do not move it, and the item in the slot is not placed here either */
/* 高级仓库的成叠格(前端按宿主命中结果 8 置位):别的都照物品区,只有双击不同——stack_take_seq 加一,前端调宿主 dm_stash_take(1) 取 1 件到背包 | Stacked cell of the advanced stash (set by the front end on host hit result 8): everything else follows the item area, only double tap differs -- stack_take_seq is incremented and the front end calls the host's dm_stash_take(1) to take 1 into the inventory */
int pointer_stack; unsigned stack_take_seq;
unsigned ident_seq; /* 物品区双击了一件未鉴定物品的次数(只有未鉴定时双击 = 免费鉴定,各页都先判这一条):前端看到变化调宿主 dm_ui_identify_hovered | Number of double taps on an unidentified item in the item area (only when unidentified does double tap = free identify, and this rule is checked first on every page): on seeing a change the front end calls the host's dm_ui_identify_hovered */
unsigned use_seq; /* 物品区双击的次数(没开箱子时):前端看到变化调宿主 dm_ui_use_item——按光标下物品走原生的使用 / 购买 / 装备,不等「按住 A」的门槛 | Number of double taps in the item area (when no stash is open): on seeing a change the front end calls the host's dm_ui_use_item -- performs the native use / buy / equip on the item under the cursor without waiting for the "hold A" threshold */
unsigned item_tap_seq; /* 物品区单击的次数(前端看到变化调宿主 dm_ui_item_tap:鉴定态下单击物品 = 鉴定它) | Number of single taps in the item area (on seeing a change the front end calls the host's dm_ui_item_tap: in identify state, single-tapping an item = identify it) */
unsigned long_press_seq; /* 物品区按住不动满长按时长的次数(前端看到变化调宿主 dm_ui_long_press:背包药水 → 腰带) | Number of times the item area was held still for the full long-press duration (on seeing a change the front end calls the host's dm_ui_long_press: inventory potion → belt) */
unsigned tab_tap_seq; /* 点按落在页签上的次数(前端看到变化调宿主 dm_ui_tab_go) | Number of taps that landed on a tab (on seeing a change the front end calls the host's dm_ui_tab_go) */
int mouse_click_mode; unsigned mouse_click_seq; float mouse_click_x, mouse_click_y;
/* 前端临时改写「面板内非物品区的点按」:非 0 = 不发鼠标点击,改成手柄光标走到触点、到位后按这个键(技能绑定流程里点技能 = 光标到它身上按 Y)。页签 / 面板外照旧 | Temporary front-end rewrite of "taps inside a panel outside the item area": non-zero = send no mouse click; instead the controller cursor walks to the touch point and presses this key on arrival (tapping a skill in the skill binding flow = cursor onto it and press Y). Tabs / outside the panel behave as before */
uint64_t tap_button; float tap_x, tap_y; int tap_move; unsigned tap_move_seq; /* tap_move:本次点按只把光标移到 tap_x / tap_y,不发点击(技能图标 / 属性「+」:先选中、再确认) | tap_move: this tap only moves the cursor to tap_x / tap_y and sends no click (skill icon / attribute "+": select first, then confirm) */
double pulse_hold_s;
double last_tap_s; float last_tap_x, last_tap_y;
double stash_x_check_s; float stash_x_x, stash_x_y; unsigned stash_x_id; /* 开着箱子双击背包物品先发了 X:到这个时刻那件还在光标下(游戏没收这下 X)就退回按住 Y | With the stash open, double-tapping an inventory item sent X first: if at this time the item is still under the cursor (the game did not accept that X), fall back to hold Y */
uint64_t pointer_pending_button; double pointer_pending_hold;
/* 难度:diff_open = 选择条展开;diff_request = 刚选中的人数档(1–8),前端交给宿主 dm_hud_request_players 后清零 | Difficulty: diff_open = selector bar expanded; diff_request = the player-count level just selected (1–8), cleared after the front end hands it to the host's dm_hud_request_players */
int diff_open, diff_request;
/* 腰带展开(原版键鼠「显示腰带」的那几排,手柄版没有入口):身上的腰带多于 1 排时,在腰带格上向上滑 = 展开、向下滑 / 点别处 = 收起,
展开后点上面几排的药 = 喝。belt_rows / belt_open 由前端每次触摸前按宿主读数写入;belt_request 前端取走后清零:
1 展开,2 收起,0x100 | 排 << 4 | 列 = 喝那一格(排 1–3 = 底排之上第几排)
Belt expansion (the rows of the original game's keyboard-and-mouse "show belt"; the controller version has no entry for it): when the worn belt has more than 1 row, swiping up on a belt cell = expand, swiping down / tapping elsewhere = collapse,
and after expansion tapping a potion in the upper rows = drink. belt_rows / belt_open are written by the front end from host readings before each touch; belt_request is cleared after the front end takes it:
1 expand, 2 collapse, 0x100 | row << 4 | column = drink that cell (row 1–3 = which row above the bottom row) */
int belt_rows, belt_open, belt_request;
/* 腰带点一下 = 自己喝,松手那一刻就喝,点几下喝几瓶;不判双击、腰带上不做喂雇佣兵的手势 | one tap on the belt = the player drinks, at the moment of release, several taps drink several; no double-tap detection, no mercenary feeding gesture on the belt */
int belt_gap_cell; double belt_gap_at; /* 按着第二组技能时要喝药:先把 ZL 和技能键松开、空出 DM_TC_ZL_LEAD_S,到 belt_gap_at 才按腰带键(belt_gap_cell = 等着的那一格,0 = 没有) | to drink a potion while a skill of the second skill set is held: first release ZL and the skill key and leave a gap of DM_TC_ZL_LEAD_S, and only at belt_gap_at press the belt key (belt_gap_cell = the cell that is waiting, 0 = none) */
double joy_lost_s; float joy_lost_x, joy_lost_y; /* 摇杆手指被系统取消的时刻与当时的位置(0 = 没有):紧接着在附近重新落下的手指接着当摇杆 | time and position at which the joystick finger was cancelled by the system (0 = none): a finger landing again nearby right afterwards continues as the joystick */
int joy_block; /* 讲话文字框单独开着(前端不进面板态):这时落在底座上的手指不起摇杆,照旧只当一次点击(关讲话框)。前端按面板栈写 | speech text box open on its own (the front end does not enter panel state): a finger on the base starts no stick and is still just one click (closes the speech box). Written by the front end from the panel stack */
double belt_pulse_s; /* 最近一次「给玩家喝」的腰带脉冲还在发的时刻:其间按着的第二组技能连同 ZL 一起让开,收回后 ZL 重新领先 DM_TC_ZL_LEAD_S 技能键才回来 | Time until which the most recent "player drinks" belt pulse is still being sent: during it the held second-set skill gives way together with ZL, and after the release ZL again leads by DM_TC_ZL_LEAD_S before the skill key comes back */
int belt_q; /* 此刻有别的脉冲在发 / 别的补发在等:排着,空了再落地(不互相盖掉)。值 = 格 | another pulse is being sent / another resend is pending: queue and fire when free (they never overwrite each other). Value = cell */
} dm_tc_state;
/* 原版UI消息驱动,不根据输入键猜面板。AutoMap是战斗叠加,不切导航。 | Driven by the original game's UI messages; panels are not guessed from input keys. AutoMap is a combat overlay and does not switch to navigation. */
typedef struct { int game; uint64_t panels; } dm_tc_scene;
int dm_tc_navigation(dm_tc_scene *scene, const char *cat, const char *act, const char *arg);
int dm_tc_scene_dialog_only(const dm_tc_scene *scene); /* 只开着 NPC 对话菜单 | Only the NPC dialog menu is open */
int dm_tc_scene_dead(void); /* 死亡弹窗开着(导航态,但不给手柄圆钮) | Death popup open (navigation state, but no controller round buttons) */
/* 坐标使用 UIKit 点;布局本身不画球、不声称游戏已绑定回城/腰带。 | Coordinates use UIKit points; the layout itself does not draw the orbs and does not claim the game has bound town portal/belt. */
/* 安全区左右内缩(点);在 init / resize 之前设,之后的布局按它把右侧技能键组与左摇杆移进安全区。缺省 0。 | Left/right safe-area insets (points); set before init / resize, and the layout afterwards uses them to move the right-side skill key group and the left stick into the safe area. Default 0. */
void dm_tc_set_safe_insets(float left, float right);
void dm_tc_set_edge_bottom(float bottom); /* 屏幕底边归系统的那一条的高度(点);0 = 没有。只约束移动摇杆的起手 | Height (points) of the strip along the bottom edge of the screen that belongs to the system; 0 = none. Constrains only where the movement stick may start */
void dm_tc_layout_make(dm_tc_layout *layout, float width, float height);
int dm_tc_hit(const dm_tc_layout *layout, float x, float y);
#define DM_TC_POINTER_LIFT_PT 40.0f // 功能页拖动时物品抬在手指上方的点数(× 控件缩放) | Number of points the item is lifted above the finger while dragging on function pages (× widget scale)
void dm_tc_set_tall_scale(int on); // 画面高 > 440 点时按 高/440 放大的开关;缺省关(Mac 宿主触屏用例传的是像素数,不能放大),iOS 前端建视图时开 | Switch for scaling up by height/440 when picture height > 440 points; default off (the Mac host touch test cases pass pixel counts and must not be scaled up); the iOS front end turns it on when creating the view
float dm_tc_scale_for_size(float width, float height); // 控件缩放:手机 min(1, 宽/667, 高/375);画面高 > 440 点(iPad)时按 高/440 等比放大 | Widget scale: phone min(1, width/667, height/375); when picture height > 440 points (iPad), scale up proportionally by height/440
void dm_tc_init(dm_tc_state *state, float width, float height);
/* 尺寸变更会取消全部触点,调用者随后推送归零状态。 | A size change cancels all touch points, and the caller then pushes the zeroed state. */
void dm_tc_resize(dm_tc_state *state, float width, float height);
/* 控件开关不改变布局;切换有效位时取消已有触点。 | Widget switches do not change the layout; existing touch points are cancelled when the valid bits are toggled. */
void dm_tc_enable_targets(dm_tc_state *state, uint32_t mask);
/* 导航模式(面板 / 对话 / 前端页开着)下可用的控件:右侧五个虚拟手柄圆钮(确认 / 返回 / 操作 / 绑定 / 下一页 = A B X Y R)。
底栏十字位置的「关闭」不再给:面板的关闭入口只留一个(外框右上角的关闭按钮;圆钮还在时另有「返回」)。
pad = 0:五个圆钮也不给(局内手指直接点界面接上之后用,开关 DM_TOUCH_NAV_PAD=0,缺省 1)。两个前端共用这一处,不各写各的。
Widgets available in navigation mode (a panel / dialog / front-end page is open): the five virtual controller round buttons on the right (confirm / back / action / bind / next page = A B X Y R).
The "close" at the bottom bar's cross position is no longer offered: only one close entry for panels remains (the close button at the top-right corner of the frame; while the round buttons are present there is also "back").
pad = 0: the five round buttons are not offered either (used once in-run fingers tapping the UI directly is hooked up; switch DM_TOUCH_NAV_PAD=0, default 1). Both front ends share this one place and do not each write their own. */
static inline uint32_t dm_tc_nav_mask(int pad) { return pad ? ((1u<<DM_TC_MAIN)|(1u<<DM_TC_SKILL1)|(1u<<DM_TC_SKILL2)|(1u<<DM_TC_SKILL3)|(1u<<DM_TC_SKILL4)) : 0; }
/* 模式变化释放全部手势;导航模式只按键,不启用技能拖拽和地图取消区。 | A mode change releases all gestures; navigation mode only presses keys and does not enable skill dragging or the map cancel area. */
void dm_tc_set_navigation_mode(dm_tc_state *state, int navigation_mode);
void dm_tc_set_joy_block(dm_tc_state *state, int block); /* 讲话文字框 / 对话菜单单独开着:落在底座上的手指不起摇杆、只当一次点击 | speech text box / dialogue menu open on its own: a finger on the base starts no stick and is just one click */
/* 只取消回城控件拥有的core触点;物理触点由前端保留。 | Cancel only the core touch point owned by the town-portal widget; the physical touch point is kept by the front end. */
void dm_tc_set_portal_button(dm_tc_state *state, uint64_t mask);
void dm_tc_set_portal_binding(dm_tc_state *state, uint64_t mask, uint64_t binding_identity, uint64_t scene_epoch);
/* 反馈确认仅作用于仍持有且身份/场景/请求一致的pending手势;返回是否首次armed。 | Feedback confirmation applies only to a pending gesture that is still held and whose identity/scene/request match; returns whether it was armed for the first time. */
int dm_tc_portal_ack(dm_tc_state *state, uint64_t gesture_epoch, uint64_t binding_identity, uint64_t scene_epoch);
void dm_tc_cancel_portal(dm_tc_state *state);
void dm_tc_begin(dm_tc_state *state, int slot, float x, float y);
void dm_tc_move(dm_tc_state *state, int slot, float x, float y);
void dm_tc_end(dm_tc_state *state, int slot);
void dm_tc_begin_at(dm_tc_state *state, int slot, float x, float y, double now_s);
void dm_tc_move_at(dm_tc_state *state, int slot, float x, float y, double now_s);
void dm_tc_end_at(dm_tc_state *state, int slot, double now_s);
void dm_tc_tick(dm_tc_state *state, double now_s);
void dm_tc_cancel_all(dm_tc_state *state);
void dm_tc_cancel_finger(dm_tc_state *state, int slot); /* 系统取消这根手指:不当松手,只放掉它按着的东西 | The system cancels this finger: do not treat it as a release, only let go of what it was holding */
/* 结束 epoch 对应的施放脉冲;返回是否有变化(调用者随后推送) | End the cast pulse corresponding to epoch; returns whether anything changed (the caller then pushes) */
int dm_tc_pulse_end(dm_tc_state *state, uint64_t pulse_epoch);
// 收回后还有排着的指针脉冲(拖放的「放下」在「拿起」没收时就到了):前端等游戏看到一次松开后调 resume 开始它
// After release there is still a queued pointer pulse (the "put-down" of a drag-and-drop arrived before the "pick-up" was released): the front end waits until the game has seen a release once, then calls resume to start it
int dm_tc_pulse_pending(const dm_tc_state *state);
void dm_tc_pointer_press(dm_tc_state *state, float x, float y, uint64_t button); /* 光标到 (x, y) 再按一下 button;当前指针手指记为「长按已处理」,松手不再算点按 | Cursor to (x, y), then press button once; the current pointer finger is marked "long press handled" and its release no longer counts as a tap */
void dm_tc_pointer_item(dm_tc_state *state, int kind); /* 指针手指的命中结果一出来就调(最晚松手前):1 = 物品区,2 = 页签,3 = 面板外(点按 = 关面板),其余 = 面板内别处(点按 = 鼠标点击) | Called as soon as the pointer finger's hit result is available (before release at the latest): 1 = item area, 2 = tab, 3 = outside the panel (tap = close the panel), anything else = elsewhere inside the panel (tap = mouse click) */
void dm_tc_pointer_release(dm_tc_state *state, int kind); /* 拖放松手前调:宿主的落点判定(1 放在抬起点 / 4 放在手指点 / 3 丢弃 / 0 放回原处) | Called before a drag-and-drop release: the host's drop decision (1 place at the lifted point / 4 place at the finger point / 3 discard / 0 put back where it was) */
void dm_tc_pointer_release_at(dm_tc_state *state, float x, float y); /* 拖放松手前调:放在这个位置(宿主算的,装备槽 = 槽心) | Called before a drag-and-drop release: place at this position (computed by the host; equipment slot = slot center) */
void dm_tc_set_holding(dm_tc_state *state, int holding);
void dm_tc_set_cur_stack(unsigned id); /* 仓库开着时光标此刻指着的背包物品的 id(指着仓库一侧 / 没指着 = 0) | id of the inventory item the cursor is pointing at right now while the stash is open (pointing at the stash side / pointing at nothing = 0) */
void dm_tc_set_hover_unid(unsigned id); /* 光标此刻指着的我方未鉴定物品 id(宿主 dm_ui_hover_unid):物品区双击先判它——非 0 = 鉴定(ident_seq 加一),不走各页原来的双击 | id of our unidentified item the cursor is pointing at right now (host dm_ui_hover_unid): an item-area double tap checks it first -- non-zero = identify (ident_seq incremented), skipping each page's original double tap */
void dm_tc_set_tap_box(int on); /* 最近一次单击的物品是不是魔盒(开着箱子时双击魔盒 = 打开) | Whether the most recently single-tapped item is the cube (with the stash open, double-tapping the cube = open) */
void dm_tc_set_panel_state(int bits); /* 宿主读游戏面板树得到的状态位(1 储藏箱开着 / 2 商人页 / 4 死亡弹窗);界面消息 DM:PanelState 到来时前端调 | State bits the host obtains by reading the game panel tree (1 stash open / 2 vendor page / 4 death popup); the front end calls this when the UI message DM:PanelState arrives */
void dm_tc_set_iso_fix(int on); /* 移动摇杆斜向预修正开关(缺省开;测量改前改后用) | Switch for the movement stick's diagonal pre-correction (default on; used to measure before and after the change) */
int dm_tc_belt_outside(const dm_tc_state *state, float x, float y);
#define DM_TC_AIM_SETTLE_S 0.08 /* 技能钮按下后等这么久判定是点按还是拖动(拖过死区就提前键下) | After a skill button is pressed, wait this long to decide tap versus drag (dragging past the dead zone puts the key down early) */
#define DM_TC_BELT_SWIPE_PT 24 /* 腰带格上松手时纵向位移过这么多点 = 展开 / 收起;不到 = 点按(喝) | On release over a belt cell, vertical displacement beyond this many points = expand / collapse; less = tap (drink) */
#define DM_TC_KEY_MIN_S 0.035 /* 技能键至少按住这么久(约 2 帧);不够的松手时补成脉冲,保证游戏读到 | A skill button is held at least this long (about 2 frames); a shorter one is made up as a pulse on release to guarantee the game reads it */
#define DM_TC_JOY_RESUME_S 0.35 /* 摇杆那根手指被系统取消后,这么久之内在原处附近重新落下的手指接着当摇杆(不要求落在底座附近) | after the joystick finger is cancelled by the system, a finger landing again near the same spot within this long continues as the joystick (landing near the base is not required) */
#define DM_TC_JOY_GRAB_K 1.5f /* 手指落在离摇杆底座中心这么多倍半径之内才起摇杆(底座固定,不跟落指点) | the joystick starts only when a finger lands within this many radii of the joystick base center (the base is fixed and does not follow the touch-down point) */
#define DM_TC_ZL_LEAD_S 0.17 /* 修饰键领先主键的时间(约 10 帧;同一帧按下游戏只认主键) | Time the modifier key leads the main key (about 10 frames; pressed in the same frame, the game only recognizes the main key) */
#define DM_TC_DOUBLE_TAP_S 0.40 /* 两次单击间隔上限 | Upper limit of the interval between two single taps */
#define DM_TC_HOLD_USE_S 0.60 /* 「按住」动作的按住时长:Mac 宿主实测 0.25 s 只捡起、0.45 s 打开魔盒 | Hold duration of the "hold" action: measured on the Mac host, 0.25 s only picks up, 0.45 s opens the cube */
int dm_tc_pulse_resume(dm_tc_state *state);
#ifdef __cplusplus
}
#endif
+125
View File
@@ -0,0 +1,125 @@
#include "dm_touch_game_state.h"
#include "dm_touch_game_identity.h"
#include "../../host/dm.h"
enum { OBS_BINDING_GETTER=6, MAPPING_OFFSET=0x2d13cbc, BINDING_OFFSET=0x2d5f0c0 };
static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
static dm_tg_snapshot latest;
static dm_tg_group group;
static dm_tg_hud_cohort hud_cohort;
static int scene_game;
static uint64_t scene_epoch,world_epoch;
static const module_t *main_module;
void dm_touch_game_set_scene(int game,uint64_t scene,uint64_t world) {
pthread_mutex_lock(&lock);
if(world_epoch!=world)dm_tg_hud_reset(&hud_cohort,world);
if(scene_game!=game || scene_epoch!=scene || world_epoch!=world) {
scene_game=game;scene_epoch=scene;world_epoch=world;memset(&group,0,sizeof group);
int supported=latest.supported;memset(&latest,0,sizeof latest);latest.supported=supported;
latest.scene_epoch=scene;latest.world_epoch=world;latest.portal.slot=-1;
}
pthread_mutex_unlock(&lock);
}
int dm_touch_game_snapshot(dm_tg_snapshot *out) {
if(!out)return 0;
pthread_mutex_lock(&lock);*out=latest;pthread_mutex_unlock(&lock);return out->valid;
}
/* 只读render实例门;不学习cohort,不续反馈TTL,不写客体。未知一律原render。 | Read-only render instance gate; does not learn the cohort, does not extend the feedback TTL, does not write to the guest. Anything unknown gets the original render. */
int dm_touch_game_hide_own_glyph(uint64_t widget) {
int match=0;pthread_mutex_lock(&lock);
const module_t *m=main_module;uint64_t t=now_ns();
if(m && scene_game && scene_epoch && world_epoch && hud_cohort.confirmed && hud_cohort.seen==63 &&
hud_cohort.world_epoch==world_epoch && latest.supported && latest.valid && latest.ready &&
latest.identity_scope==DM_TG_IDENTITY_NATIVE && latest.source==DM_TG_SOURCE_NATIVE_GETTER &&
latest.scene_epoch==scene_epoch && latest.world_epoch==world_epoch &&
latest.hud_identity==hud_cohort.hud_identity && latest.group_seen==63 &&
latest.captured_ns && t>=latest.captured_ns && t-latest.captured_ns<=DM_TG_MAX_AGE_NS) {
for(unsigned i=0;i<6;i++)if(widget && widget==hud_cohort.widget[i]) {
/* 一次读完[widget,widget+c91):VT、enum(+b18)、alwaysGetAlt(+c90)。读失败=原render。object是静态的(在lock内),不占客体线程的栈。 | Read [widget,widget+c91) in one go: VT, enum (+b18), alwaysGetAlt (+c90). Read failure = original render. object is static (inside the lock) and does not use the guest thread's stack. */
static unsigned char object[0xc91];uint64_t vt=0;uint32_t slot=UINT32_MAX;
if(widget<=UINT64_MAX-0xc90 && dm_tg_vm_read(widget,object,sizeof object)) {
memcpy(&vt,object,8);memcpy(&slot,object+0xb18,4);
if(vt==(uint64_t)m->base+0x208a5f8 && slot==i && !object[0xc90])match=1;
}
break;
}
}
pthread_mutex_unlock(&lock);return match;
}
/* 诊断(DM_BINDING_DIAG=1):各返回点计数,每 3 秒一行;身份确认失败再按原因码细分(identity.c) | Diagnostic (DM_BINDING_DIAG=1): counts per return point, one line every 3 seconds; identity confirmation failures are further broken down by reason code (identity.c) */
static unsigned dg[8], dg_id[8]; static uint64_t dg_last;
static void diag_tick(void) {
static int on=-1; if(on<0) on=getenv("DM_BINDING_DIAG")!=NULL; if(!on) return;
uint64_t t=now_ns(); if(t-dg_last<3000000000ull) return; dg_last=t;
LOG("绑定诊断:调用 %u|寄存器不符 %u|槽越界 %u|组不符 %u|不在局内 %u|身份未确认 %u(原因 3:%u 4:%u 5:%u 6:%u 7:%u,LR 偏移 %#llx 槽 %u)|成功 %u|scene_game %d world %llu",
dg[0],dg[1],dg[2],dg[3],dg[4],dg[5],dg_id[3],dg_id[4],dg_id[5],dg_id[6],dg_id[7],(unsigned long long)dm_tg_identity_lr,dm_tg_identity_slot,dg[6],scene_game,(unsigned long long)world_epoch);
}
static int live_check; /* 真游戏里才开(要调游戏函数);单测的假模块上不开 | Turned on only in the real game (it calls game functions); not turned on for the unit tests' fake module */
void dm_touch_game_live_check(int on) { live_check=on; }
/* 槽里绑的技能玩家现在还有没有(摘掉给技能的装备后,那颗钮回到空位;装备穿回来原版把绑定接回、钮自己回来——所以不清原版绑定表,只在快照里按空位报)。
判法照原版选用技能时那段 main+0x43f1ac–0x43f23c:技能链表 [玩家+0x100] 里找「技能号、物品号(槽 +4;-1 = 自己学的)都相同」的节点,
等级 = 节点 +0x38(自己学的再加装备加成 0x5b1710),夹到版本上限后 > 0 才算有。读不到玩家 / 版本不认 = 不改判。只在游戏线程调(观测门里)
Whether the player still has the skill bound in the slot (after taking off the gear that grants the skill, that button goes back to an empty slot; when the gear is put back on, the original game reconnects the binding and the button comes back by itself -- so the original binding table is not cleared, and the slot is only reported as empty in the snapshot).
The check follows the original game's code for selecting a skill at main+0x43f1ac–0x43f23c: in the skill linked list [player+0x100], find the node whose "skill number and item number (slot +4; -1 = self-learned) are both the same",
level = node +0x38 (for a self-learned one, plus the gear bonus 0x5b1710), and it counts as owned only if > 0 after clamping to the version cap. Player unreadable / version not recognized = verdict unchanged. Called only on the game thread (inside the observation gate) */
static int skill_live(const unsigned char *b,uint32_t id,int32_t item) {
if(id==UINT32_MAX || id==359 || id==219 || id==220)return 1; /* 空位、回城卷轴 / 书(原版取槽时自己换号,按数量判)不归这里 | Empty slots and town portal scrolls / tomes (the original game swaps the number itself when fetching the slot, judged by quantity) are not handled here */
uint64_t pl=((uint64_t(*)(uint32_t))(b+0x45f9d0))(*(const uint32_t*)(b+0x2d20e4c)); if(!pl)return 1;
uint8_t ver=*(uint8_t*)(pl+0x1bd); if(ver<1 || ver>3)return 1;
uint64_t l=*(uint64_t*)(pl+0x100),n=l?*(uint64_t*)l:0;
for(int k=0;n && k<1024;k++,n=*(uint64_t*)(n+8)) { uint64_t r=*(uint64_t*)n;
if(!r || *(int16_t*)r!=(int16_t)id || *(int32_t*)(n+0x44)!=item)continue;
int lv=*(int32_t*)(n+0x38); if(item==-1)lv+=((int(*)(uint64_t,uint64_t,int))(b+0x5b1710))(pl,n,0);
int cap=**(int32_t**)(*(uint64_t*)(b+0x2d64a18+(uint64_t)ver*16)+0x1500); if(lv<0)lv=0; if(lv>cap)lv=cap;
return lv>0; }
{ int dm_swapskill_equipped(int32_t); return item!=-1 && dm_swapskill_equipped(item); } /* 副手组技能:物品还穿在换手那组上 = 按下会先换武器再放(dm_actions.c),照常显示、角标「II」 | Off-hand set skill: the item is still worn on the weapon-swap set = pressing will swap weapons first and then cast (dm_actions.c); shown as usual, with corner badge "II" */
}
static void binding_getter(const uint64_t *regs) {
const module_t *m=main_module;
dg[0]++; diag_tick();
if(!m || !regs || regs[10]!=(uint64_t)(m->base+BINDING_OFFSET) || regs[8]%DM_TG_STRIDE){dg[1]++;return;}
uint64_t effective=regs[8]/DM_TG_STRIDE;
uint32_t input_slot=(uint32_t)regs[19]; // PRE-ldr原getter arg,不是ID。 | PRE-ldr arg of the original getter, not an ID.
if(input_slot>=DM_TG_SLOTS || effective>=28 || effective<input_slot){dg[2]++;return;}
uint64_t selected_bank=effective-input_slot;
if(selected_bank!=0 && selected_bank!=16){dg[3]++;return;}
unsigned dead=0; /* 绑着但玩家现在没有的技能(位 = 槽)。要调游戏函数,放在取锁之前 | Skills that are bound but the player does not currently have (bit = slot). This calls a game function, so it is placed before taking the lock */
for(int i=0;live_check && i<DM_TG_SLOTS;i++) { uint32_t id;int32_t item;const unsigned char *e=(const unsigned char*)m->base+BINDING_OFFSET+(selected_bank+i)*DM_TG_STRIDE;memcpy(&id,e,4);memcpy(&item,e+4,4);
static uint32_t gone[32]; int live=skill_live((const unsigned char*)m->base,id,item); if(!live)dead|=1u<<i;
if(gone[selected_bank+i]!=(live?UINT32_MAX:id)) { gone[selected_bank+i]=live?UINT32_MAX:id; if(!live)LOG("技能钮:槽 %d 绑的技能 %u(物品 %d)玩家现在没有,按空位显示",(int)selected_bank+i,id,item); else LOG("技能钮:槽 %d 的技能回来了,照常显示",(int)selected_bank+i); } }
pthread_mutex_lock(&lock);
if(!scene_game || !world_epoch) {dg[4]++;pthread_mutex_unlock(&lock);return;} // menu/nav不学cohort。 | menu/nav do not learn the cohort.
uint64_t caller=0,hud=0;
#ifndef DM_TG_TEST_SYNTHETIC_IDENTITY
/* 不读内存的前置筛:HUD updater在main3e2f68把arg放进w23、3e2f6c再mov w0,w23后BL原Get;原Get只动x19-x21,
被调函数按AAPCS保x23,所以HUD这条调用到门时必有x23==x19(arg)。不等=不是HUD updater,同「savedLR不符」一样IGNORE,省掉读栈。
Pre-filter that reads no memory: at main3e2f68 the HUD updater puts arg into w23, at 3e2f6c it does mov w0,w23 and then BL to the original Get; the original Get only touches x19-x21,
and the callee preserves x23 per AAPCS, so when this HUD call reaches the gate x23==x19 (arg) must hold. Not equal = not the HUD updater; IGNORE just like "savedLR mismatch", saving the stack read. */
if(regs[23]!=regs[19]) {dg[5]++;dg_id[4]++;pthread_mutex_unlock(&lock);return;}
#endif
#ifdef DM_TG_TEST_SYNTHETIC_IDENTITY
int scope=dm_touch_game_test_identity(regs,&caller,&hud); // 仅独立SDK_STUB构建;不与生产符号碰撞。 | Only for the standalone SDK_STUB build; does not collide with production symbols.
#else
int scope=dm_tg_hud_identity(&hud_cohort,regs,(uint64_t)m->base,scene_game,world_epoch,dm_tg_vm_read,&caller,&hud);
#endif
if(scope==DM_TG_IDENTITY_UNCONFIRMED) {dg[5]++;if(dm_tg_identity_reason>=0&&dm_tg_identity_reason<8)dg_id[dm_tg_identity_reason]++;pthread_mutex_unlock(&lock);return;} // cache/unknown/readFail全IGNORE,不清HUD快照/不续时。 | cache/unknown/readFail are all IGNORE; do not clear the HUD snapshot / do not extend the time.
unsigned char mapping[72],bindings[DM_TG_SLOTS*DM_TG_STRIDE]={0};
memcpy(mapping,m->base+MAPPING_OFFSET,sizeof mapping);
for(int i=0;i<DM_TG_SLOTS;i++)memcpy(bindings+i*DM_TG_STRIDE,m->base+BINDING_OFFSET+(selected_bank+i)*DM_TG_STRIDE,4);
uint32_t observed_id;memcpy(&observed_id,m->base+BINDING_OFFSET+regs[8],4);
dm_tg_snapshot s;
dm_tg_parse(&s,mapping,sizeof mapping,bindings,sizeof bindings,(int)selected_bank,(int)input_slot,(int)effective,observed_id,now_ns());
for(int i=0;i<DM_TG_SLOTS;i++)if(s.valid && (dead>>i&1) && !(s.portal.valid && s.portal.slot==i))s.raw_skill_id[i]=UINT32_MAX;
s.scene_epoch=scene_epoch;s.world_epoch=world_epoch;
dm_tg_group_observe(&group,&s,scene_game,scene_epoch,caller,hud,scope);latest=group.completed;dg[6]++;
pthread_mutex_unlock(&lock);
}
int dm_touch_game_attach(void) {
main_module=NULL;
pthread_mutex_lock(&lock);int supported=gate_obs_present(OBS_BINDING_GETTER);memset(&latest,0,sizeof latest);
latest.supported=supported;latest.scene_epoch=scene_epoch;latest.world_epoch=world_epoch;latest.portal.slot=-1;memset(&group,0,sizeof group);
pthread_mutex_unlock(&lock);
if(!supported)return 0;
if(g_nmod<1 || strcmp(g_mod[0].name,"main") || !g_mod[0].base ||
g_mod[0].size<BINDING_OFFSET+32*DM_TG_STRIDE || g_mod[0].size<MAPPING_OFFSET+72)return 0;
main_module=&g_mod[0];gate_obs_set(OBS_BINDING_GETTER,binding_getter);return 1;
}
+56
View File
@@ -0,0 +1,56 @@
#include "dm_touch_game_identity.h"
#include <string.h>
#ifdef __APPLE__
#include <mach/mach.h>
#include <mach/vm_map.h>
#endif
int dm_tg_vm_read(uint64_t address,void *out,size_t bytes) {
if(!out || !bytes || !address || address>UINT64_MAX-bytes)return 0;
#ifdef __APPLE__
vm_size_t copied=0;
kern_return_t rc=vm_read_overwrite(mach_task_self(),(vm_address_t)address,(vm_size_t)bytes,(vm_address_t)out,&copied);
return rc==KERN_SUCCESS && copied==bytes;
#else
(void)address;return 0;
#endif
}
/* 诊断(DM_BINDING_DIAG):最近一次的返回原因码与读到的 LR / 槽号,供 bridge 计数(v4 后快照全空,查卡在哪个返回点) | Diagnostic (DM_BINDING_DIAG): the most recent return reason code and the LR / slot number read, for bridge to count (after v4 the snapshot is entirely empty; find which return point it is stuck at) */
int dm_tg_identity_reason; uint64_t dm_tg_identity_lr; uint32_t dm_tg_identity_slot;
void dm_tg_hud_reset(dm_tg_hud_cohort *c,uint64_t world) {memset(c,0,sizeof(*c));c->world_epoch=world;}
static uint64_t add(uint64_t h,uint64_t v) {
for(int i=0;i<8;i++){h^=(unsigned char)(v>>(i*8));h*=1099511628211ull;}return h;
}
int dm_tg_hud_identity(dm_tg_hud_cohort *c,const uint64_t *regs,uint64_t base,int game,uint64_t world,
dm_tg_read_fn read_fn,uint64_t *caller,uint64_t *hud) {
dm_tg_identity_reason=1;
if(!caller || !hud)return DM_TG_IDENTITY_UNCONFIRMED;
*caller=*hud=0;
if(!c || !regs || !read_fn)return DM_TG_IDENTITY_UNCONFIRMED;
if(c->world_epoch!=world)dm_tg_hud_reset(c,world);
uint32_t arg=(uint32_t)regs[19];
dm_tg_identity_reason=3;
if(!game || !world || arg>=12 || base>UINT64_MAX-0x3e2f74)return DM_TG_IDENTITY_UNCONFIRMED;
dm_tg_identity_reason=4;
/* 原Get栈帧一次读完:fp-8=调用者x19(widget)、fp=上一帧fp、fp+8=savedLR;三者同在原Get序言刚写下的0x30字节帧里。 | Read the original Get's stack frame in one go: fp-8 = caller's x19 (widget), fp = previous frame's fp, fp+8 = savedLR; all three are in the 0x30-byte frame the original Get's prologue has just written. */
uint64_t fp=regs[29],frame[3]={0},lr=0,widget=0;
if(fp<8 || fp>UINT64_MAX-16 || !read_fn(fp-8,frame,sizeof frame))return DM_TG_IDENTITY_UNCONFIRMED;
widget=frame[0];lr=frame[2];dm_tg_identity_lr=lr-base;
if(lr!=base+0x3e2f74 || !widget || widget>UINT64_MAX-0xc90)return DM_TG_IDENTITY_UNCONFIRMED;
/* widget的enum(+b18)与alwaysGetAlt(+c90)同一对象内,一次读[+b18,+c91)。 | The widget's enum (+b18) and alwaysGetAlt (+c90) are inside the same object; read [+b18,+c91) in one go. */
uint32_t slot=UINT32_MAX;unsigned char always_alt=255;static unsigned char span[0xc91-0xb18]; /* 调用方(bridge 的门回调)持锁;不占客体线程的栈 | The caller (bridge's gate callback) holds the lock; does not use the guest thread's stack */ dm_tg_identity_reason=5;
if(read_fn(widget+0xb18,span,sizeof span)){memcpy(&slot,span,4);always_alt=span[0xc90-0xb18];}
if(slot>=6 || always_alt ||
(arg!=slot && arg!=slot+6)) { dm_tg_identity_slot=slot; return DM_TG_IDENTITY_UNCONFIRMED; }
dm_tg_identity_reason=6; dm_tg_identity_slot=slot;
if(c->widget[slot] && c->widget[slot]!=widget)return DM_TG_IDENTITY_UNCONFIRMED;
for(unsigned i=0;i<6;i++)if(i!=slot && c->widget[i]==widget)return DM_TG_IDENTITY_UNCONFIRMED;
if(c->confirmed){*caller=lr;*hud=c->hud_identity;dm_tg_identity_reason=0;return DM_TG_IDENTITY_NATIVE;}
dm_tg_identity_reason=7; /* 学习中:六槽未齐 | Learning: the six slots are not all filled yet */
c->widget[slot]=widget;c->seen|=1u<<slot;
if(c->seen==63) {
uint64_t h=add(1469598103934665603ull,world);for(int i=0;i<6;i++)h=add(h,c->widget[i]);
c->hud_identity=h?h:1;c->confirmed=1;
}
/* 首组六体只确认cohort,不把第六体借给反馈组;下一个原frame完整六组才ready。 | The first group of six only confirms the cohort and does not lend the sixth one to the feedback group; ready only once the next original frame has the complete six groups. */
return DM_TG_IDENTITY_UNCONFIRMED;
}
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "dm_touch_game_state.h"
typedef struct {
uint64_t world_epoch, widget[6], hud_identity;
uint32_t seen;
int confirmed;
} dm_tg_hud_cohort;
typedef int (*dm_tg_read_fn)(uint64_t address, void *out, size_t bytes);
/* 同进程Mach只读,不直接解引用未知FramePointer或widget堆地址。 | Same-process Mach read-only; never dereference an unknown FramePointer or widget heap address directly. */
int dm_tg_vm_read(uint64_t address, void *out, size_t bytes);
void dm_tg_hud_reset(dm_tg_hud_cohort *cohort, uint64_t world_epoch);
/* 首组六指针只确认cohort;返回身份从下一帧六组开始,不追认替换指针。 | The first group of six pointers only confirms the cohort; identity is returned starting from the next frame's six groups, and replaced pointers are not recognized retroactively. */
extern int dm_tg_identity_reason; extern uint64_t dm_tg_identity_lr; extern uint32_t dm_tg_identity_slot; /* 诊断用 | For diagnostics */
int dm_tg_hud_identity(dm_tg_hud_cohort *cohort, const uint64_t *regs,
uint64_t main_base, int game_no_panel, uint64_t world_epoch,
dm_tg_read_fn read_fn, uint64_t *caller, uint64_t *hud);
+83
View File
@@ -0,0 +1,83 @@
#include "dm_touch_game_state.h"
#include "../../host/dm_input.h"
#include <string.h>
static uint32_t u32(const unsigned char *p) {
return (uint32_t)p[0]|(uint32_t)p[1]<<8|(uint32_t)p[2]<<16|(uint32_t)p[3]<<24;
}
static uint64_t sdk(uint32_t logical) {
switch(logical) {
case 0x1000:return DM_BTN_B; case 0x2000:return DM_BTN_A;
case 0x4000:return DM_BTN_Y; case 0x8000:return DM_BTN_X;
case 0x200:return DM_BTN_R; case 0x800:return DM_BTN_ZR;
default:return 0;
}
}
static int portal(uint32_t id) { return id==359 || id==219 || id==220; }
int dm_tg_parse(dm_tg_snapshot *out,const void *mapping,size_t mapping_bytes,
const void *bank,size_t bank_bytes,int selected_bank,int getter_input_slot,
int observed_index,uint32_t observed_id,uint64_t captured_ns) {
if(!out)return 0;
memset(out,0,sizeof(*out)); out->supported=1;out->portal.slot=-1;
if(!mapping || !bank || mapping_bytes<DM_TG_FACETS*12 || bank_bytes<DM_TG_SLOTS*DM_TG_STRIDE ||
(selected_bank!=0 && selected_bank!=16) || getter_input_slot<0 || getter_input_slot>=DM_TG_SLOTS ||
observed_index!=selected_bank+getter_input_slot) return 0;
dm_tg_snapshot s=*out; unsigned normals=0,alts=0; uint64_t logicals=0;
const unsigned char *m=mapping,*b=bank;
for(int i=0;i<DM_TG_FACETS;i++) {
dm_tg_mapping *t=&s.mapping[i]; t->logical=u32(m+i*12);t->normal=u32(m+i*12+4);t->alt=u32(m+i*12+8);
uint64_t bit=sdk(t->logical);
if(!bit || (logicals&bit) || t->normal>=6 || t->alt<6 || t->alt>=12 ||
(normals&(1u<<t->normal)) || (alts&(1u<<(t->alt-6))))return 0;
logicals|=bit;normals|=1u<<t->normal;alts|=1u<<(t->alt-6);
}
for(int i=0;i<DM_TG_SLOTS;i++)s.raw_skill_id[i]=u32(b+i*DM_TG_STRIDE);
if(s.raw_skill_id[observed_index-selected_bank]!=observed_id)return 0;
/* 先替代栏,再普通栏;每栏按原slot顺序确定唯一入口。 | Alternate bar first, then the normal bar; within each bar the unique entry is determined in the original slot order. */
for(int pass=0;pass<2 && !s.portal.valid;pass++)for(int slot=pass?0:6;slot<(pass?6:12);slot++) {
if(!portal(s.raw_skill_id[slot]))continue;
for(int i=0;i<DM_TG_FACETS;i++)if((pass?s.mapping[i].normal:s.mapping[i].alt)==(uint32_t)slot) {
s.portal=(dm_tg_portal){sdk(s.mapping[i].logical)|(pass?0:DM_BTN_ZL),s.raw_skill_id[slot],slot,1};break;
}
if(s.portal.valid)break;
}
s.valid=1;s.source=DM_TG_SOURCE_NATIVE_GETTER;s.selected_bank=selected_bank;s.getter_input_slot=getter_input_slot;
s.observed_index=observed_index;s.captured_ns=captured_ns;*out=s;return 1;
}
uint64_t dm_tg_portal_mask(const dm_tg_snapshot *s,uint64_t host_now_ns) {
if(!s || !s->supported || !s->valid || !s->ready || !s->portal.valid || !s->captured_ns ||
host_now_ns<s->captured_ns || host_now_ns-s->captured_ns>DM_TG_MAX_AGE_NS)return 0;
return s->portal.buttons;
}
static uint64_t identity_add(uint64_t h,uint64_t value) {
for(int i=0;i<8;i++) { h^=(unsigned char)(value>>(i*8)); h*=1099511628211ull; }
return h;
}
static uint64_t binding_identity(const dm_tg_snapshot *s,uint64_t caller,uint64_t hud,int scope) {
uint64_t h=identity_add(1469598103934665603ull,(uint64_t)s->selected_bank);
h=identity_add(h,s->world_epoch);h=identity_add(h,caller);h=identity_add(h,hud);h=identity_add(h,(uint64_t)scope);
for(int i=0;i<DM_TG_FACETS;i++) {h=identity_add(h,s->mapping[i].logical);h=identity_add(h,s->mapping[i].normal);h=identity_add(h,s->mapping[i].alt);}
for(int i=0;i<DM_TG_SLOTS;i++)h=identity_add(h,s->raw_skill_id[i]);
return h?h:1;
}
int dm_tg_group_observe(dm_tg_group *g,const dm_tg_snapshot *table,int game,uint64_t scene,
uint64_t caller,uint64_t hud,int scope) {
if(!g || !table)return 0;
dm_tg_snapshot s=*table;s.ready=0;s.scene_epoch=scene;s.caller_identity=caller;s.hud_identity=hud;s.identity_scope=scope;
if(!s.valid || !game || !scene || !caller || !hud ||
(scope!=DM_TG_IDENTITY_NATIVE && scope!=DM_TG_IDENTITY_SYNTHETIC) ||
s.getter_input_slot<0 || s.getter_input_slot>=DM_TG_SLOTS) {
memset(g,0,sizeof(*g));g->completed=s;return 0;
}
s.binding_identity=binding_identity(&s,caller,hud,scope);s.secondary_group=s.getter_input_slot>=6;
int same=g->pending.binding_identity==s.binding_identity && g->pending.scene_epoch==scene &&
g->pending.world_epoch==s.world_epoch && g->pending.selected_bank==s.selected_bank && g->pending.caller_identity==caller && g->pending.hud_identity==hud && g->pending.identity_scope==scope &&
!memcmp(g->pending.mapping,s.mapping,sizeof s.mapping) && !memcmp(g->pending.raw_skill_id,s.raw_skill_id,sizeof s.raw_skill_id);
if(!same) { memset(g,0,sizeof(*g));g->completed=s; }
uint32_t bit=1u<<(s.getter_input_slot%6);
if(!same || g->pending.secondary_group!=s.secondary_group || (g->seen&bit)) {g->seen=0;g->started_ns=s.captured_ns;}
g->seen|=bit;s.group_seen=g->seen;s.group_started_ns=g->started_ns;g->pending=s;
if(g->seen!=63)return 0;
s.ready=1;g->completed=s;return 1;
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { DM_TG_FACETS=6, DM_TG_SLOTS=12, DM_TG_STRIDE=28,
DM_TG_MAX_AGE_NS=250000000,
DM_TG_IDENTITY_UNCONFIRMED=0, DM_TG_IDENTITY_NATIVE=1, DM_TG_IDENTITY_SYNTHETIC=2,
DM_TG_SOURCE_NONE=0, DM_TG_SOURCE_NATIVE_GETTER=1 };
typedef struct { uint32_t logical, normal, alt; } dm_tg_mapping;
typedef struct {
uint64_t buttons;
uint32_t raw_skill_id;
int slot, valid;
} dm_tg_portal;
typedef struct {
uint64_t captured_ns, group_started_ns, scene_epoch, world_epoch, binding_identity, caller_identity, hud_identity;
int ready, secondary_group, identity_scope;
uint32_t group_seen;
/* valid只证明捕获表解析完整,不证明当前武器bank、ammo或游戏施法状态。 | valid only proves the captured table parsed completely; it does not prove the current weapon bank, ammo or the game's casting state. */
int supported, valid, source, selected_bank, getter_input_slot, observed_index;
dm_tg_mapping mapping[DM_TG_FACETS];
uint32_t raw_skill_id[DM_TG_SLOTS];
dm_tg_portal portal;
} dm_tg_snapshot;
/* 只解析已复制的32位小端原表;不读取客体内存、不调用客体getter。 | Parses only the already-copied 32-bit little-endian original table; does not read guest memory and does not call guest getters. */
int dm_tg_parse(dm_tg_snapshot *out, const void *mapping, size_t mapping_bytes,
const void *bank, size_t bank_bytes, int selected_bank, int getter_input_slot,
int observed_index, uint32_t observed_id, uint64_t captured_ns);
typedef struct { dm_tg_snapshot pending, completed; uint32_t seen; uint64_t started_ns; } dm_tg_group;
/* 单normal/alt组的六facet完整且身份/scene一致才ready。身份未知则不ready。 | ready only when the six facets of a single normal/alt group are complete and identity/scene match. If identity is unknown, not ready. */
int dm_tg_group_observe(dm_tg_group *group, const dm_tg_snapshot *table, int game,
uint64_t scene_epoch, uint64_t caller_identity, uint64_t hud_identity, int identity_scope);
/* host now_ns时间域;未来/零时间戳及年龄>250ms时Portal输入归零。 | host now_ns time domain; for future/zero timestamps and age >250ms the Portal input is zeroed. */
uint64_t dm_tg_portal_mask(const dm_tg_snapshot *snapshot, uint64_t host_now_ns);
/* 生产桥:load_modules完成后的客体线程attach;UI只取锁内快照副本。 | Production bridge: attach on the guest thread after load_modules completes; the UI only takes a copy of the snapshot inside the lock. */
int dm_touch_game_attach(void);
/* 开:快照里把「绑着但玩家现在没有的技能」(如摘掉给技能的装备)按空位报;要调游戏函数,只在真游戏里开。 | On: in the snapshot, report "skills that are bound but the player does not currently have" (e.g. after taking off the gear that grants the skill) as empty slots; this calls game functions, so turn it on only in the real game. */
void dm_touch_game_live_check(int on);
int dm_touch_game_snapshot(dm_tg_snapshot *out);
void dm_touch_game_set_scene(int game_no_panel, uint64_t scene_epoch, uint64_t world_epoch);
#ifdef DM_TG_TEST_SYNTHETIC_IDENTITY
/* 仅SDK_STUB显式条件构建可提供此opaque seam;生产走strong Mach原HUD cohort。 | Only an explicitly conditional SDK_STUB build may provide this opaque seam; production uses the strong Mach original HUD cohort. */
int dm_touch_game_test_identity(const uint64_t *regs, uint64_t *caller_identity, uint64_t *hud_identity);
#endif
#ifdef __cplusplus
}
#endif
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "dm_touch_game_state.h"
enum { DM_TA_UNKNOWN=0, DM_TA_EMPTY=1, DM_TA_GLYPH=2, DM_TA_ATLASES=9 };
typedef struct { const char *asset; int width,height,frame_width,pitch,count; } dm_ta_atlas;
typedef struct { int x,y,width,height; } dm_ta_frame;
typedef struct { int status,atlas,normal_frame,pressed_frame,slot,effective_slot; uint32_t raw_skill_id; const char *reason; } dm_ta_glyph;
extern const dm_ta_atlas dm_ta_atlases[DM_TA_ATLASES];
extern const char dm_ta_manifest_sha[],dm_ta_geometry_sha[],dm_ta_binding_sha[];
dm_ta_glyph dm_ta_skill(uint32_t raw_skill_id);
dm_ta_glyph dm_ta_current(const dm_tg_snapshot *s,uint64_t sdk_button,uint64_t host_now_ns);
/* 同上,skill_set=1 取第二套(alt 槽,原版按住 ZL) | Same as above; skill_set=1 takes the second set (alt slots, hold ZL in the original game) */
dm_ta_glyph dm_ta_current_set(const dm_tg_snapshot *s,uint64_t sdk_button,uint64_t host_now_ns,int skill_set);
int dm_ta_frame_at(int atlas,int frame,dm_ta_frame *out);
+142
View File
@@ -0,0 +1,142 @@
// 构建号 + 新版本提示的 iOS 侧。
// 画面上的字和按钮是游戏自己的控件(布局 tools/touch_layout.py,写字与显隐 dm/host/dm_update.c);这里只管三件:
// ① 把自己的构建号(CFBundleVersion,与日志头「构建」同一个数)交给宿主,选角页左下角常显;
// ② 每次选角页出现(启动、从局里退回来)都在后台取一次版本文件(这是我们自己加的唯一一处联网,只读一个小文件,单次 10 秒超时、失败隔几秒重试共 3 次,不挡启动与进局;同一时刻只有一个查询在途);
// ③ 玩家点了「更新」→ 把版本文件里的安装链接交给系统打开(系统安装,整包覆盖,存档与资源不动)。
// 版本文件地址不在仓库里:出包脚本写进 Info.plist 的 SWUpdateURL(tools/adhoc.sh 传 DM_UPDATE_URL)。没有这个键、或构建号不是大于 1 的整数
// (开发签名包是 1)→ 不联网、不提示。不比自己新:画面上什么都不出;没网 / 超时 / 地址失效 / 格式不对:选角页构建号右边出一行失败提示(dm_update_fail:没有无线数据许可 → 提示去设置里允许;其余 → 提示去浏览器打开版本文件所在的站点),这次启动取到了就撤掉。
// 版本文件 latest.json(UTF-8)四个字段:{"build": 10051432, "note": "一句话 ≤ 24 个汉字", "urgent": false, "install_url": "…"},缺字段或类型不对 = 格式不对。
// 每次查完按新结果处理(不限一天一次,进首页就查、有新的就提示):比自己新 → 显示 / 换成这次的;不比自己新 → 撤掉已有提示;
// 取不到 / 格式不对 → 已有的提示留着不动(一次网络抖动不该把确实存在的新版本提示抹掉;这次启动还没提示过的话照旧什么都不出)。
// 测试注入(只影响这三件的输入,不设就是产品行为):DM_TEST_UPDATE_URL 换版本文件地址(可用 file://),DM_TEST_UPDATE_BUILD 换自己的构建号,
// DM_TEST_UPDATE_OPEN=0 点「更新」只记日志不真打开链接;DM_TEST_UPDATE_DENY=1 把取不到当成「无线数据许可被拒」。
// iOS side of the build number + new-version notice.
// The text and button on screen are the game's own widgets (layout in tools/touch_layout.py, text writing and show/hide in dm/host/dm_update.c); only three things are handled here:
// ① Hand our own build number (CFBundleVersion, the same number as 「构建」(Build) in the log header) to the host, always shown at the bottom-left of the character select page;
// ② Each time the character select page appears (launch, returning from a run), fetch the version file once in the background (this is the only network access we added ourselves; it reads one small file, 10-second timeout per attempt, retries a few seconds after a failure for 3 attempts in total, does not block launch or entering a run; only one query is in flight at any moment);
// ③ The player tapped 「更新」(Update) → hand the install link from the version file to the system to open (system install, whole-package overwrite, saves and assets untouched).
// The version file address is not in the repository: the packaging script writes it into SWUpdateURL in Info.plist (tools/adhoc.sh passes DM_UPDATE_URL). Without this key, or when the build number is not an integer greater than 1
// (dev-signed builds are 1) → no network access, no notice. Not newer than ours: nothing appears on screen; no network / timeout / dead address / bad format: a failure notice line appears to the right of the build number on the character select page (dm_update_fail: no wireless data permission → tell the player to allow it in Settings; otherwise → tell the player to open in a browser the site that serves the version file), removed once a fetch succeeds during this launch.
// The version file latest.json (UTF-8) has four fields: {"build": 10051432, "note": "one sentence, ≤ 24 Chinese characters", "urgent": false, "install_url": "..."}; a missing field or wrong type = bad format.
// After each query, act on the new result (not limited to once a day; query on entering the home page and show a notice if there is a new one): newer than ours → show / replace with this one; not newer than ours → remove the existing notice;
// fetch failed / bad format → leave the existing notice untouched (one network glitch should not erase a notice for a new version that really exists; if nothing has been shown yet during this launch, still show nothing as before).
// Test injection (affects only the inputs of these three things; unset = product behavior): DM_TEST_UPDATE_URL replaces the version file address (file:// is allowed), DM_TEST_UPDATE_BUILD replaces our own build number,
// DM_TEST_UPDATE_OPEN=0 makes tapping 「更新」(Update) only log without actually opening the link; DM_TEST_UPDATE_DENY=1 treats a failed fetch as "wireless data permission denied".
#import <UIKit/UIKit.h>
#import <Network/Network.h>
#include <stdatomic.h>
void plog(const char *fmt, ...);
void dm_update_init(int own_build, void (*on_select)(void), void (*on_click)(void)); // dm/host/dm_update.c
void dm_update_offer(int new_build, const char *note, int urgent);
void dm_update_safe_left(int units);
void dm_update_fail(int kind);
void dm_update_site(const char *host);
static NSString *g_url, *g_install; static int g_own; static _Atomic int g_inflight;
// 取不到时补一行系统眼里的网络状态:分清「手机没连网」和「这个 App 没拿到无线数据许可」(两种情况请求报的都是「没有网络」)。只读,不弹框
// When the fetch fails, add one line with the network state as the system sees it: tell apart "the phone is not connected" and "this App has not been granted wireless data permission" (in both cases the request reports "no network"). Read-only, no alert
static void upd_net_why(void) {
nw_path_monitor_t m = nw_path_monitor_create(); nw_path_monitor_set_queue(m, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
nw_path_monitor_set_update_handler(m, ^(nw_path_t p) {
static const char *st[] = { "无效", "通", "不通", "要先建连接" }, *why[] = { "系统没给原因", "蜂窝数据许可被拒", "无线局域网数据许可被拒", "本地网络许可被拒", "要先开 VPN" };
nw_path_status_t s = nw_path_get_status(p); nw_path_unsatisfied_reason_t r = nw_path_get_unsatisfied_reason(p);
plog("更新:系统网络路径 %s%s%s;无线局域网 %s、蜂窝 %s", s <= 3 ? st[s] : "未知", s == nw_path_status_satisfied ? "" : ",原因:", s == nw_path_status_satisfied ? "" : r <= 4 ? why[r] : "未知",
nw_path_uses_interface_type(p, nw_interface_type_wifi) ? "在用" : "没用上", nw_path_uses_interface_type(p, nw_interface_type_cellular) ? "在用" : "没用上");
// 选角页失败提示:系统说「数据许可被拒」= 玩家自己能在设置里开;其余 = 让玩家去浏览器手动更新
// Failure notice on the character select page: the system says "data permission denied" = the player can turn it on in Settings themselves; anything else = have the player update manually in a browser
const char *td = getenv("DM_TEST_UPDATE_DENY"); // 测试:=1 当成系统说「数据许可被拒」(Mac 上造不出这种现场) | Test: =1 behaves as if the system said "data permission denied" (this situation cannot be created on Mac)
int denied = (td && atoi(td)) || (s != nw_path_status_satisfied && (r == nw_path_unsatisfied_reason_cellular_denied || r == nw_path_unsatisfied_reason_wifi_denied));
dm_update_fail(denied ? 1 : 2); plog("更新:选角页显示%s", denied ? "「无法联网检查更新 · 请在设置里允许无线数据」" : "「检查更新失败 · 浏览器手动更新」");
nw_path_monitor_cancel(m);
});
nw_path_monitor_start(m);
}
// 版本文件 → 要不要提示。返回 nil = 提示(out 填好),否则是不提示的原因(进日志)
// Version file → whether to show a notice. Returns nil = show it (out is filled in); otherwise the reason for not showing it (goes to the log)
static NSString *upd_parse(NSData *d, int *build, NSString **note, int *urgent, NSString **install) {
NSDictionary *j = d ? [NSJSONSerialization JSONObjectWithData:d options:0 error:nil] : nil;
if (![j isKindOfClass:NSDictionary.class]) return @"格式不对:不是 JSON 对象";
NSNumber *b = j[@"build"], *u = j[@"urgent"]; NSString *n = j[@"note"], *i = j[@"install_url"];
if (![b isKindOfClass:NSNumber.class] || ![u isKindOfClass:NSNumber.class] || ![n isKindOfClass:NSString.class] || ![i isKindOfClass:NSString.class]) return @"格式不对:四个字段缺了或类型不对";
if (!(b.doubleValue >= 1 && b.doubleValue < 2e9) || b.doubleValue != b.intValue) return @"格式不对:build 不是正整数";
NSString *sch = [NSURL URLWithString:i].scheme.lowercaseString;
if (![sch isEqualToString:@"https"] && ![sch isEqualToString:@"itms-services"]) return @"格式不对:install_url 不是 https / itms-services 链接";
n = [[n componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet] componentsJoinedByString:@" "];
if (n.length > 24) n = [n substringWithRange:[n rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 24)]]; // 说明只有一行的位置:超过 24 个字截掉 | The note has room for only one line: truncate beyond 24 characters
*build = b.intValue; *note = n; *urgent = u.boolValue; *install = i; return nil;
}
static void upd_fetch(int n);
static void on_select(void) { // 宿主在游戏主线程调:选角页每出现一次调一次 | Called by the host on the game main thread: once each time the character select page appears
dispatch_async(dispatch_get_main_queue(), ^{ // 左安全区换成布局单位(2160 高)交给宿主,算法同 front_ios.m 给佣兵头像用的那处 | Convert the left safe area into layout units (2160 high) and hand it to the host; same algorithm as the place in front_ios.m used for the mercenary portrait
UIWindow *w = nil; for (UIScene *s in UIApplication.sharedApplication.connectedScenes) if ([s isKindOfClass:UIWindowScene.class]) { w = ((UIWindowScene *)s).windows.firstObject; if (w) break; }
const char *tl = getenv("DM_TEST_SAFE_L"); CGFloat l = tl ? atof(tl) : w.safeAreaInsets.left, hh = w.bounds.size.height; if (hh > 0) dm_update_safe_left((int)lround(l / hh * 2160));
});
if (!g_url) return;
if (atomic_exchange(&g_inflight, 1)) { plog("更新:上一次查询还没回来,这次不再发"); return; } // 同一时刻只有一个查询(含重试)在途 | Only one query (including retries) is in flight at any moment
upd_fetch(1);
}
// 一次查询最多试 UPD_TRIES 次(首页出过一次「检查更新失败」,服务端那段时间全是 200,请求多半没出手机)。
// 读代码能列出的客户端一次性失败:① 刚启动 / 刚回前台时系统网络路径还没就绪,waitsForConnectivity = NO 时立刻报 -1009;② 冷连接 DNS + TCP + TLS
// 在蜂窝上超过原先 5 秒的总时限(-1001);③ 每次新建会话、不复用连接,次次都是冷连接;④ DNS 首查失败(-1003)/ 连接中途丢(-1005)。
// 改:请求 10 秒、整体 15 秒;会话全程复用一个;失败隔 3 秒、6 秒再试,三次都失败才出失败提示(一次失败不出字);每次都记第几次、错误码。
// 不开 waitsForConnectivity:数据许可被拒时它会一直等到整体时限,玩家要多等十几秒才看到「去设置里允许」。
// 测试:DM_TEST_UPDATE_FAIL_FIRST=N 前 N 次故意查一个不存在的域名(造「一次失败、再试成功」)
// One query tries at most UPD_TRIES times (the home page once showed 「检查更新失败」(Update check failed) while the server returned all 200s during that period, so the request most likely never left the phone).
// One-off client failures that can be listed by reading the code: ① right after launch / returning to the foreground the system network path is not ready yet, and with waitsForConnectivity = NO it reports -1009 immediately; ② cold-connection DNS + TCP + TLS
// on cellular exceeds the former 5-second total limit (-1001); ③ a new session was created every time with no connection reuse, so every attempt was a cold connection; ④ the first DNS lookup fails (-1003) / the connection drops midway (-1005).
// Changes: request 10 seconds, overall 15 seconds; one session reused throughout; retry 3 seconds and 6 seconds after a failure, and show the failure notice only after all three fail (a single failure shows no text); log the attempt number and error code every time.
// waitsForConnectivity is not turned on: when the data permission is denied it waits until the overall limit, and the player would wait ten-odd more seconds before seeing 「去设置里允许」(Allow it in Settings).
// Test: DM_TEST_UPDATE_FAIL_FIRST=N deliberately queries a non-existent domain for the first N attempts (to create "fail once, succeed on retry")
#define UPD_TRIES 3
static void upd_fetch(int n) {
static NSURLSession *ses; static dispatch_once_t once;
dispatch_once(&once, ^{ NSURLSessionConfiguration *c = NSURLSessionConfiguration.ephemeralSessionConfiguration; c.timeoutIntervalForRequest = 10; c.timeoutIntervalForResource = 15;
c.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; c.waitsForConnectivity = NO; ses = [NSURLSession sessionWithConfiguration:c]; });
const char *tf = getenv("DM_TEST_UPDATE_FAIL_FIRST"); NSString *us = tf && n <= atoi(tf) ? @"https://nonexistent-dm.invalid/latest.json" : g_url;
NSURL *url = [NSURL URLWithString:us]; if (!url) { plog("更新:版本文件地址 %s 不是合法地址,不查", us.UTF8String); g_url = nil; atomic_store(&g_inflight, 0); return; }
[[ses dataTaskWithURL:url completionHandler:^(NSData *d, NSURLResponse *r, NSError *e) {
int build = 0, urgent = 0; NSString *note = nil, *install = nil, *why = nil;
if (e) why = [NSString stringWithFormat:@"取不到:%@", e.localizedDescription];
else if ([r isKindOfClass:NSHTTPURLResponse.class] && [(NSHTTPURLResponse *)r statusCode] != 200) why = [NSString stringWithFormat:@"取不到:HTTP %ld", (long)[(NSHTTPURLResponse *)r statusCode]];
else if (d.length > 4096) why = @"格式不对:超过 4096 字节";
else why = upd_parse(d, &build, &note, &urgent, &install);
if (!e && d.length && d.length <= 4096) { // 远程退回画法:版本文件里 "render_safe": true → 本局退回原画法;没有这个字段 = 新画法 | Remote fallback of the drawing method: "render_safe": true in the version file → this run falls back to the old drawing method; without this field = the new drawing method
NSDictionary *j = [NSJSONSerialization JSONObjectWithData:d options:0 error:nil]; NSNumber *rs = [j isKindOfClass:NSDictionary.class] ? j[@"render_safe"] : nil;
extern int g_dm_rt_ab; if ([rs isKindOfClass:NSNumber.class] && rs.boolValue) { if (g_dm_rt_ab) { g_dm_rt_ab = 0; plog("画法:版本文件 render_safe = true → 本局退回原画法"); } }
else plog("画法:版本文件没有 render_safe(或为 false)→ 新画法照常"); }
if (why) {
plog("更新:查 %s(第 %d / %d 次)→ %s%s", us.UTF8String, n, UPD_TRIES, why.UTF8String, n < UPD_TRIES ? ",稍后再试" : ",已有的提示不动");
if (e) plog("更新:第 %d 次取不到的错误码 %s %ld", n, e.domain.UTF8String, (long)e.code);
if (n < UPD_TRIES) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * n) * NSEC_PER_SEC), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ upd_fetch(n + 1); }); return; }
atomic_store(&g_inflight, 0);
if (e) upd_net_why(); else dm_update_fail(2); // 三次都失败才出字:网络错误由系统网络路径定原因(upd_net_why 里设),HTTP 非 200 / 格式不对 = 其余失败 | Text appears only after all three attempts fail: for a network error the reason is determined by the system network path (set in upd_net_why); HTTP non-200 / bad format = other failures
return; }
atomic_store(&g_inflight, 0);
if (n > 1) plog("更新:第 %d 次取到了(前面 %d 次失败)", n, n - 1);
dm_update_fail(0); // 这次取到了:撤掉失败提示 | Fetched successfully this time: remove the failure notice
if (build <= g_own) { plog("更新:查 %s → 最新构建 %d,不比自己(%d)新,不提示(已有的提示撤掉)", us.UTF8String, build, g_own); dm_update_offer(0, "", 0); return; }
plog("更新:查 %s → 有新构建 %d(%s,自己 %d):%s", us.UTF8String, build, urgent ? "建议立即更新" : "普通", g_own, note.UTF8String);
dispatch_async(dispatch_get_main_queue(), ^{ g_install = install; });
dm_update_offer(build, note.UTF8String, urgent);
}] resume];
}
static void on_click(void) { // 宿主在游戏主线程调:玩家点了「更新」 | Called by the host on the game main thread: the player tapped 「更新」(Update)
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *u = g_install ? [NSURL URLWithString:g_install] : nil; if (!u) { plog("更新:点了「更新」但没有安装链接"); return; }
const char *to = getenv("DM_TEST_UPDATE_OPEN"); if (to && !atoi(to)) { plog("更新:点了「更新」→ 安装链接 %s(DM_TEST_UPDATE_OPEN=0,不真打开)", g_install.UTF8String); return; }
plog("更新:点了「更新」→ 交系统打开安装链接");
[UIApplication.sharedApplication openURL:u options:@{} completionHandler:^(BOOL ok) { plog("更新:系统%s安装链接", ok ? "已接手" : "没能打开"); }];
});
}
void dm_update_boot(void) { // main.m 起宿主前调一次 | main.m calls this once before starting the host
const char *tb = getenv("DM_TEST_UPDATE_BUILD"), *tu = getenv("DM_TEST_UPDATE_URL");
NSString *v = tb ? @(tb) : [NSBundle.mainBundle.infoDictionary[@"CFBundleVersion"] description]; g_own = v.intValue;
if (![v isEqualToString:[NSString stringWithFormat:@"%d", g_own]] || g_own < 0) g_own = 0;
NSString *url = tu ? @(tu) : NSBundle.mainBundle.infoDictionary[@"SWUpdateURL"];
if ([url isKindOfClass:NSString.class] && url.length && g_own > 1) g_url = url;
if (g_url) dm_update_site([NSURL URLWithString:g_url].host.UTF8String); // 检查失败时提示玩家去浏览器打开的站点 = 版本文件所在的主机 | The site the player is told to open in a browser when the check fails = the host that serves the version file
plog("更新:自己的构建 %d,%s", g_own, g_url ? "到选角页后查一次新版本" : g_own > 1 ? "包里没有版本文件地址,不查新版本" : "开发包,不查新版本");
dm_update_init(g_own, on_select, on_click);
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+106
View File
@@ -0,0 +1,106 @@
// 宿主堆增长定位(诊断,DM_MALLOCDIAG=起始秒,结束秒 时生效;零点 = 本构造函数):
// 起始秒挂 libmalloc 的 malloc_logger 回调,逐次记分配 → 调用点(帧指针回溯 10 帧)、释放即销账;结束秒摘钩,
// 按「窗口内分配、到结束仍活着」的字节数给调用点排序,写 Documents/mallocdiag.txt(前 40 个,模块+偏移)。
// 为什么不用 xctrace Allocations:它的记录库跑在当前栈上,HLE 在客体线程的小栈上调 malloc 时探栈越过保护页(真机两次 sig=10 ___chkstk_darwin)。
// 约束:回调里不分配内存、栈帧小(可能跑在客体栈上);表满即停记并在报告里标红。
// Locating host heap growth (diagnostic; active when DM_MALLOCDIAG=start_seconds,end_seconds; zero point = this constructor):
// at the start second, hook libmalloc's malloc_logger callback and record each allocation → call site (frame-pointer backtrace of 10 frames), cancelling the entry on free; at the end second, unhook,
// sort call sites by the bytes "allocated inside the window and still live at the end", and write Documents/mallocdiag.txt (top 40, module+offset).
// Why not xctrace Allocations: its recording library runs on the current stack, and when HLE calls malloc on a guest thread's small stack the stack probe crosses the guard page (twice on a real device: sig=10 ___chkstk_darwin).
// Constraints: no memory allocation inside the callback, small stack frame (it may run on a guest stack); when a table fills up, stop recording and mark it as failed in the report.
#import <Foundation/Foundation.h>
#include <dlfcn.h>
#include <os/lock.h>
#include <pthread.h>
#include <stdatomic.h>
#include <unistd.h>
#include "dm.h"
typedef void(malloc_logger_t)(uint32_t type, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t result, uint32_t skip);
extern malloc_logger_t *malloc_logger; // libsystem_malloc 导出(MallocStackLogging / Instruments 用的同一挂点) | Exported by libsystem_malloc (the same hook point used by MallocStackLogging / Instruments)
enum { T_ALLOC = 2, T_DEALLOC = 4, T_ZONE = 8 };
#define NF 10
#define LIVE_BITS 22 // 活块表 4M 项 × 24 B = 96 MiB(只记窗口内分配) | Live-block table 4M entries × 24 B = 96 MiB (records only allocations inside the window)
#define SITE_BITS 16
typedef struct { uintptr_t p; uint32_t size, site; } live_t;
typedef struct { uintptr_t f[NF]; uint64_t bytes, n, total_n; } site_t;
static live_t *g_live; static site_t *g_site;
static os_unfair_lock g_lk = OS_UNFAIR_LOCK_INIT;
static int g_full;
static uint32_t hsite(const uintptr_t *f) { uint64_t h = 1469598103934665603ull; for (int i = 0; i < NF; i++) h = (h ^ f[i]) * 1099511628211ull; return (uint32_t)(h ^ h >> 32); }
static uint32_t hptr(uintptr_t p) { return (uint32_t)((p >> 4) * 0x9E3779B97F4A7C15ull >> (64 - LIVE_BITS)); }
static void on_alloc(uintptr_t p, uintptr_t size) {
uintptr_t f[NF] = {0}; uintptr_t *fp = __builtin_frame_address(0);
for (int i = 0, k = 0; fp && k < NF && i < NF + 1; i++) { // 跳过本函数自己的返回地址 | Skip this function's own return address
uintptr_t *nx = (uintptr_t *)fp[0]; uintptr_t lr = fp[1] & 0x0000ffffffffffffull;
if (i >= 1) f[k++] = lr;
if (!nx || nx <= fp || (uintptr_t)nx - (uintptr_t)fp > (1u << 20) || ((uintptr_t)nx & 7)) break;
fp = nx;
}
uint32_t s = hsite(f) & ((1u << SITE_BITS) - 1);
os_unfair_lock_lock(&g_lk);
for (uint32_t i = 0; i < (1u << SITE_BITS); i++, s = (s + 1) & ((1u << SITE_BITS) - 1)) {
site_t *e = &g_site[s];
if (!e->total_n) { memcpy(e->f, f, sizeof f); break; }
if (!memcmp(e->f, f, sizeof f)) break;
if (i == (1u << SITE_BITS) - 1) { g_full = 1; os_unfair_lock_unlock(&g_lk); return; }
}
g_site[s].bytes += size; g_site[s].n++; g_site[s].total_n++;
uint32_t h = hptr(p);
for (uint32_t i = 0; i < (1u << LIVE_BITS); i++, h = (h + 1) & ((1u << LIVE_BITS) - 1))
if (!g_live[h].p || g_live[h].p == 1) { g_live[h] = (live_t){p, (uint32_t)size, s}; os_unfair_lock_unlock(&g_lk); return; }
g_full = 1; os_unfair_lock_unlock(&g_lk);
}
static void on_free(uintptr_t p) {
uint32_t h = hptr(p);
os_unfair_lock_lock(&g_lk);
for (uint32_t i = 0; i < (1u << LIVE_BITS) && g_live[h].p; i++, h = (h + 1) & ((1u << LIVE_BITS) - 1))
if (g_live[h].p == p) { site_t *e = &g_site[g_live[h].site]; e->bytes -= g_live[h].size; e->n--; g_live[h].p = 1; break; } // 1 = 墓碑 | 1 = tombstone
os_unfair_lock_unlock(&g_lk);
}
static void logger(uint32_t type, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t result, uint32_t skip) {
(void)a1; (void)skip;
if ((type & (T_ALLOC | T_DEALLOC)) == (T_ALLOC | T_DEALLOC)) { // realloc:a2 = 旧块,a3 = 新长,result = 新块 | realloc: a2 = old block, a3 = new length, result = new block
if (a2) on_free(a2);
if (result) on_alloc(result, a3);
} else if (type & T_ALLOC) { if (result) on_alloc(result, a2); }
else if (type & T_DEALLOC) on_free(a2);
}
static void sym(char *o, size_t n, uintptr_t a) {
for (int i = 0; i < g_nmod; i++)
if (a >= (uintptr_t)g_mod[i].base && a < (uintptr_t)g_mod[i].base + g_mod[i].size) { snprintf(o, n, "%s+%#lx", g_mod[i].name, a - (uintptr_t)g_mod[i].base); return; }
Dl_info d; if (dladdr((void *)a, &d) && d.dli_sname) { snprintf(o, n, "%s+%#lx", d.dli_sname, a - (uintptr_t)d.dli_saddr); return; }
if (dladdr((void *)a, &d) && d.dli_fname) { const char *b = strrchr(d.dli_fname, '/'); snprintf(o, n, "%s+%#lx", b ? b + 1 : d.dli_fname, a - (uintptr_t)d.dli_fbase); return; }
snprintf(o, n, "%#lx", a);
}
static int by_bytes(const void *a, const void *b) { uint64_t x = (*(site_t *const *)a)->bytes, y = (*(site_t *const *)b)->bytes; return (x < y) - (x > y); }
static void *diag(void *arg) {
int *w = arg; sleep((unsigned)w[0]);
malloc_logger = logger;
sleep((unsigned)(w[1] - w[0]));
malloc_logger = NULL; usleep(200000); // 摘钩后等在途回调走完 | After unhooking, wait for in-flight callbacks to finish
static site_t *top[1u << SITE_BITS]; int nt = 0; uint64_t sum = 0, sumn = 0;
for (uint32_t i = 0; i < (1u << SITE_BITS); i++) if (g_site[i].total_n && g_site[i].bytes) { top[nt++] = &g_site[i]; sum += g_site[i].bytes; sumn += g_site[i].n; }
qsort(top, nt, sizeof *top, by_bytes);
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
FILE *f = fopen([doc stringByAppendingPathComponent:@"mallocdiag.txt"].fileSystemRepresentation, "w"); if (!f) return NULL;
fprintf(f, "窗口 %d–%d 秒:窗口内分配、到结束仍活着 %.2f MiB / %llu 块,调用点 %d 个%s\n", w[0], w[1], sum / 1048576.0, sumn, nt, g_full ? "(【红】表满,有漏记)" : "");
for (int i = 0; i < nt && i < 40; i++) {
fprintf(f, "%8.1f KiB %7llu 块(窗口内共分配 %llu 次)", top[i]->bytes / 1024.0, top[i]->n, top[i]->total_n);
for (int k = 0; k < NF && top[i]->f[k]; k++) { char s[160]; sym(s, sizeof s, top[i]->f[k]); fprintf(f, " ← %s", s); }
fputc('\n', f);
}
fclose(f); return NULL;
}
__attribute__((constructor)) static void mallocdiag_ios(void) {
const char *e = getenv("DM_MALLOCDIAG"); if (!e) return;
static int w[2]; if (sscanf(e, "%d,%d", &w[0], &w[1]) != 2 || w[1] <= w[0]) return;
g_live = calloc(1u << LIVE_BITS, sizeof *g_live); g_site = calloc(1u << SITE_BITS, sizeof *g_site);
pthread_t th; pthread_create(&th, NULL, diag, w); pthread_detach(th);
}