Files
d2r-mobile/dm/android/app/java/org/d2rmobile/app/GameActivity.java
T
shenleiandClaude Opus 5.5 3c25cd89fc Android: move the shell to dm/android and the Vulkan backend to dm/gfx/vulkan
Mirror the iOS layout instead of nesting Android inside dm/host:
- dm/android/app       GameActivity app (manifest, java, res, build_apk.sh)
- dm/android/Sources   front_app.c, touch_app.c, front_headless.c
- dm/android/Makefile  entry point (apk / lib / install / headless / tests);
                       rules in build.mk (was dm/host/Makefile.android),
                       run with dm/host as cwd; outputs in dm/android/build/
- dm/android/tests     t_vk_perf
- dm/gfx/vulkan        nvn_vk.c and friends, next to the Metal backend

Only include paths, build paths and docs change; no code changes.
The Mac / iOS source lists do not pick up gfx/vulkan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:59:36 +09:00

288 lines
18 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 全屏横屏 Activity:SurfaceView 交给 Vulkan 后端出图,上面盖一层触屏 HUD(TouchOverlay);触点 / 手柄 / 软键盘转给 libd2r.so(front_app.c、touch_app.c)。
// Fullscreen landscape Activity: the SurfaceView goes to the Vulkan backend for presenting, with the touch HUD (TouchOverlay) on top; touches / controller / software keyboard go to libd2r.so (front_app.c, touch_app.c).
package org.d2rmobile.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.Choreographer;
import android.view.DisplayCutout;
import android.view.WindowInsets;
import android.widget.FrameLayout;
import android.os.Handler;
import android.os.Looper;
import android.text.InputFilter;
import android.util.DisplayMetrics;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
public final class GameActivity extends Activity implements SurfaceHolder.Callback {
private static native int nativeStart(String root, int screenW, int screenH);
private static native void nativeSurface(Object surface, float hz);
// 触屏 HUD(touch_app.c),坐标单位 dp | touch HUD (touch_app.c), coordinates in dp
private static native void nativeLayout(float w, float h, float safeL, float safeR);
private static native void nativeTouchEvent(int action, int pid, int[] pids, float[] xs, float[] ys, int n);
private static native int nativeTick();
static native Object[] nativeDraw(int part);
private static native void nativePad(int face, int other, boolean nintendo, float lx, float ly, float rx, float ry);
private static native long nativeFrames();
private static native String[] nativeTextRequest();
private static native void nativeTextResult(boolean ok, String text);
// 前后台:0 onPause、1 onStop(局内等存盘,最多 2.5 s)、2 onStart、3 onResume(front_app.c)| foreground / background: 0 onPause, 1 onStop (waits for the save in a run, at most 2.5 s), 2 onStart, 3 onResume (front_app.c)
private static native void nativeLifecycle(int ev);
// nn::hid 按钮位(dm_input.h)| nn::hid button bits (dm_input.h)
private static final int LS = 1 << 4, RS = 1 << 5, L = 1 << 6, R = 1 << 7, ZL = 1 << 8, ZR = 1 << 9,
PLUS = 1 << 10, MINUS = 1 << 11, LEFT = 1 << 12, UP = 1 << 13, RIGHT = 1 << 14, DOWN = 1 << 15;
private final Handler ui = new Handler(Looper.getMainLooper());
private SurfaceView view;
private boolean started;
private TouchOverlay overlay, joy, goals;
private float safeL, safeR;
private Vibrator vibrator;
private final int[] tPids = new int[32]; private final float[] tXs = new float[32], tYs = new float[32];
private int padFace, padKeys, padHat;
private float lx, ly, rx, ry, lt, rt;
private boolean nintendo;
private AlertDialog textDialog;
// 左上角 FPS 标签:每 1 s 按游戏出帧数更新 | top-left FPS label: refreshed every 1 s from the game's presented frame count
private TextView fps;
private long fpsFrames, fpsTime;
/* 游戏自己按 60 Hz(省电 30 Hz)出帧;120 Hz 面板上软件时钟和垂直同步拍频,帧落在 1/2/3 个 vsync 上抖动,所以把屏幕钉在同分辨率的 60 Hz 模式
* The game paces itself at 60 Hz (30 Hz in eco); on a 120 Hz panel the software clock beats against vsync and frames land on 1/2/3 vsyncs, so pin the panel to the same-resolution 60 Hz mode */
private void pin60Hz() {
if (android.os.Build.VERSION.SDK_INT < 23) return;
android.view.Display d = getWindowManager().getDefaultDisplay();
android.view.Display.Mode cur = d.getMode(), best = null;
for (android.view.Display.Mode m : d.getSupportedModes()) {
if (m.getPhysicalWidth() != cur.getPhysicalWidth() || m.getPhysicalHeight() != cur.getPhysicalHeight()) continue;
if (Math.abs(m.getRefreshRate() - 60f) < 1f) { best = m; break; }
}
if (best == null) return;
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.preferredDisplayModeId = best.getModeId();
getWindow().setAttributes(lp);
}
@Override protected void onCreate(Bundle state) {
super.onCreate(state);
// 库的构造函数要按 DM_ROOT 找 dm/derived.tsv(经验表等),所以先设环境变量再加载 | the library's constructors locate dm/derived.tsv (EXP table etc.) via DM_ROOT, so set it before loading
try { android.system.Os.setenv("DM_ROOT", new File(getFilesDir(), "d2r").getAbsolutePath(), true); } catch (Exception e) {}
System.loadLibrary("d2r");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (android.os.Build.VERSION.SDK_INT >= 28)
getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
pin60Hz();
view = new SurfaceView(this);
view.getHolder().addCallback(this);
view.setFocusable(true); view.setFocusableInTouchMode(true);
// 主体层与摇杆层分开:手指在摇杆上动时只重画摇杆层(见 touch_app.c op_list)。主体层不设 LAYER_TYPE_HARDWARE:在 Adreno 上那块离屏层刚进游戏的十几秒里会把屏幕顶部合成成台阶状黑块
// the body and joystick layers are separate: while a finger moves on the stick only the joystick layer is redrawn (see touch_app.c op_list). No LAYER_TYPE_HARDWARE on the body layer: on Adreno that offscreen layer composited stepped black blocks at the top of the screen for the first dozen seconds in game
overlay = new TouchOverlay(this, 0);
joy = new TouchOverlay(this, 1);
goals = new TouchOverlay(this, 2); // 小地图任务终点:跟着玩家走每帧变,单独一层不牵动主体层 | minimap quest goals: change every frame as the player walks, own layer so the body layer is untouched
FrameLayout root = new FrameLayout(this);
root.addView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(goals, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(overlay, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(joy, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
fps = new TextView(this);
fps.setTextSize(12); fps.setTextColor(0xffe9d9ba); fps.setBackgroundColor(0x80000000);
fps.setTypeface(android.graphics.Typeface.MONOSPACE); fps.setPadding(12, 4, 12, 4);
root.addView(fps, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
setContentView(root);
// 刘海 / 挖孔:横屏左右的安全边距交给布局(同 iOS safeAreaInsets)| cutout / punch hole: the landscape left / right safe insets go to the layout (like iOS safeAreaInsets)
root.setOnApplyWindowInsetsListener((v, in) -> {
DisplayCutout cut = in.getDisplayCutout();
safeL = cut != null ? cut.getSafeInsetLeft() : 0; safeR = cut != null ? cut.getSafeInsetRight() : 0;
fps.setTranslationX(safeL);
layoutHud(); return in;
});
overlay.addOnLayoutChangeListener((v, l, t, r, b, ol, ot, or, ob) -> layoutHud());
vibrator = getSystemService(Vibrator.class);
immersive();
ui.post(textPoll);
}
private void immersive() {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
@Override public void onWindowFocusChanged(boolean focus) { super.onWindowFocusChanged(focus); if (focus) immersive(); }
private void fail(String text) {
TextView t = new TextView(this); t.setText(text); t.setTextSize(18); t.setPadding(48, 48, 48, 48);
t.setTextColor(0xffe9d9ba); t.setBackgroundColor(0xff0d0d0f); setContentView(t);
}
// ---- Surface ----
@Override public void surfaceCreated(SurfaceHolder h) {}
@Override public void surfaceChanged(SurfaceHolder h, int format, int w, int hh) {
if (!started) {
DisplayMetrics m = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getRealMetrics(m);
File root = new File(getFilesDir(), "d2r");
int rc = nativeStart(root.getAbsolutePath(), m.widthPixels, m.heightPixels);
if (rc != 0) { fail("游戏文件不全(错误 " + rc + ")\n请把 dm/、romfs/、rt64/ 放到\n" + root.getAbsolutePath()); return; }
started = true;
layoutHud();
Choreographer.getInstance().postFrameCallback(frame);
}
// 同步交出窗口:surfaceDestroyed 返回前后端必须已放手,这里对称处理 | Hand the window over synchronously: the backend must let go before surfaceDestroyed returns, handled symmetrically here
nativeSurface(h.getSurface(), getWindowManager().getDefaultDisplay().getRefreshRate());
}
@Override public void surfaceDestroyed(SurfaceHolder h) {
if (started) nativeSurface(null, 0);
cancelTouches();
}
// ---- 触屏 HUD | touch HUD ----
private void layoutHud() {
if (!started || overlay.getWidth() <= 0) return;
float d = getResources().getDisplayMetrics().density;
nativeLayout(overlay.getWidth() / d, overlay.getHeight() / d, safeL / d, safeR / d);
overlay.invalidate(); joy.invalidate(); goals.invalidate();
}
// 每帧:推进 HUD 状态机(长按、松手脉冲、腰带 …),要重画才 invalidate;掉落震动按档位 | per frame: advance the HUD state machine (long press, release pulse, belt …), invalidate only when a redraw is needed; drop haptics by level
private final Choreographer.FrameCallback frame = new Choreographer.FrameCallback() { public void doFrame(long t) {
if (!started) return;
int r = nativeTick();
if ((r & 1) != 0) overlay.invalidate();
if ((r & 2) != 0) joy.invalidate();
if ((r & 4) != 0) goals.invalidate();
if (t - fpsTime >= 1_000_000_000L) {
long n = nativeFrames();
if (fpsTime != 0) fps.setText(String.format(java.util.Locale.ROOT, "%.1f FPS", (n - fpsFrames) * 1e9 / (t - fpsTime)));
fpsFrames = n; fpsTime = t;
}
int hap = r >> 4 & 3;
if (hap != 0 && vibrator != null && vibrator.hasVibrator())
vibrator.vibrate(VibrationEffect.createPredefined(hap == 1 ? VibrationEffect.EFFECT_HEAVY_CLICK : hap == 2 ? VibrationEffect.EFFECT_CLICK : VibrationEffect.EFFECT_TICK));
Choreographer.getInstance().postFrameCallback(this);
}};
private void cancelTouches() { if (started) nativeTouchEvent(3, -1, null, null, null, 0); }
@Override public boolean onTouchEvent(MotionEvent e) {
if (!started) return true;
int act = e.getActionMasked(), action;
switch (act) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: action = 0; break;
case MotionEvent.ACTION_MOVE: action = 1; break;
case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: action = 2; break;
case MotionEvent.ACTION_CANCEL: action = 3; break;
default: return true;
}
float d = getResources().getDisplayMetrics().density;
int n = Math.min(e.getPointerCount(), tPids.length);
for (int i = 0; i < n; i++) { tPids[i] = e.getPointerId(i); tXs[i] = e.getX(i) / d; tYs[i] = e.getY(i) / d; }
int pid = action == 0 || action == 2 ? e.getPointerId(e.getActionIndex()) : -1;
nativeTouchEvent(action, pid, tPids, tXs, tYs, n); // 重画交给同一帧随后的 doFrame(nativeTick 比对指令表) | the redraw is left to the doFrame later in the same frame (nativeTick compares the draw lists)
return true;
}
// ---- 实体手柄 | physical controller ----
private static boolean isPad(int source) {
return (source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD || (source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK;
}
private void padPublish() {
int other = padKeys | padHat | (lt > 0.5f ? ZL : 0) | (rt > 0.5f ? ZR : 0);
nativePad(padFace, other, nintendo, lx, ly, rx, ry);
}
private static float dead(float v) { return Math.abs(v) < 0.12f ? 0 : v; }
@Override public boolean dispatchKeyEvent(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.KEYCODE_BACK && !isPad(e.getSource())) return true; // 系统返回键不退出游戏 | the system back key does not quit the game
if (!started || !isPad(e.getSource())) return super.dispatchKeyEvent(e);
int face = 0, key = 0;
switch (code) {
case KeyEvent.KEYCODE_BUTTON_A: face = 1; break; // 下 | bottom
case KeyEvent.KEYCODE_BUTTON_B: face = 2; break; // 右 | right
case KeyEvent.KEYCODE_BUTTON_X: face = 4; break; // 左 | left
case KeyEvent.KEYCODE_BUTTON_Y: face = 8; break; // 上 | top
case KeyEvent.KEYCODE_BUTTON_L1: key = L; break;
case KeyEvent.KEYCODE_BUTTON_R1: key = R; break;
case KeyEvent.KEYCODE_BUTTON_L2: key = ZL; break;
case KeyEvent.KEYCODE_BUTTON_R2: key = ZR; break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: key = LS; break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: key = RS; break;
case KeyEvent.KEYCODE_BUTTON_START: key = PLUS; break;
case KeyEvent.KEYCODE_BUTTON_SELECT: case KeyEvent.KEYCODE_BACK: key = MINUS; break;
case KeyEvent.KEYCODE_DPAD_UP: key = UP; break;
case KeyEvent.KEYCODE_DPAD_DOWN: key = DOWN; break;
case KeyEvent.KEYCODE_DPAD_LEFT: key = LEFT; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: key = RIGHT; break;
default: return super.dispatchKeyEvent(e);
}
InputDevice d = e.getDevice(); nintendo = d != null && d.getName() != null && d.getName().toLowerCase().matches(".*(nintendo|switch|joy-con).*");
boolean down = e.getAction() == KeyEvent.ACTION_DOWN;
if (face != 0) padFace = down ? padFace | face : padFace & ~face;
else padKeys = down ? padKeys | key : padKeys & ~key;
padPublish();
return true;
}
@Override public boolean dispatchGenericMotionEvent(MotionEvent e) {
if (!started || !isPad(e.getSource()) || e.getAction() != MotionEvent.ACTION_MOVE) return super.dispatchGenericMotionEvent(e);
lx = dead(e.getAxisValue(MotionEvent.AXIS_X)); ly = dead(e.getAxisValue(MotionEvent.AXIS_Y));
rx = dead(e.getAxisValue(MotionEvent.AXIS_Z)); ry = dead(e.getAxisValue(MotionEvent.AXIS_RZ));
lt = Math.max(e.getAxisValue(MotionEvent.AXIS_LTRIGGER), e.getAxisValue(MotionEvent.AXIS_BRAKE));
rt = Math.max(e.getAxisValue(MotionEvent.AXIS_RTRIGGER), e.getAxisValue(MotionEvent.AXIS_GAS));
float hx = e.getAxisValue(MotionEvent.AXIS_HAT_X), hy = e.getAxisValue(MotionEvent.AXIS_HAT_Y);
padHat = (hx < -0.5f ? LEFT : 0) | (hx > 0.5f ? RIGHT : 0) | (hy < -0.5f ? UP : 0) | (hy > 0.5f ? DOWN : 0);
padPublish();
return true;
}
// ---- 软键盘 | software keyboard ----
private final Runnable textPoll = new Runnable() { public void run() {
if (started && textDialog == null) {
String[] r = nativeTextRequest();
if (r != null) showText(r);
}
ui.postDelayed(this, 250);
}};
private void showText(String[] r) {
final EditText edit = new EditText(this);
edit.setSingleLine(true); edit.setText(r[3]); edit.setSelection(edit.getText().length());
if (!r[2].isEmpty()) edit.setHint(r[2]);
int max = Integer.parseInt(r[4]); if (max > 0) edit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max)});
String msg = r[1] + (!r[1].isEmpty() && !r[2].isEmpty() ? "\n" : "") + r[2];
textDialog = new AlertDialog.Builder(this).setTitle(r[0].isEmpty() ? "输入" : r[0]).setMessage(msg.isEmpty() ? null : msg).setView(edit)
.setPositiveButton(android.R.string.ok, (d, w) -> { nativeTextResult(true, edit.getText().toString()); textDialog = null; })
.setNegativeButton(android.R.string.cancel, (d, w) -> { nativeTextResult(false, null); textDialog = null; })
.setOnCancelListener(d -> { nativeTextResult(false, null); textDialog = null; })
.create();
textDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
textDialog.show();
}
// ---- 前后台 | foreground / background ----
// 切走时按着的触点和手柄键一并清零:在后台松开收不到「松开」| touches and controller keys held while switching away are cleared: a release in the background never arrives
@Override protected void onPause() {
super.onPause();
if (!started) return;
cancelTouches();
padFace = padKeys = padHat = 0; lx = ly = rx = ry = lt = rt = 0; padPublish();
nativeLifecycle(0);
}
@Override protected void onStop() { super.onStop(); if (started) nativeLifecycle(1); }
@Override protected void onStart() { super.onStart(); if (started) nativeLifecycle(2); }
@Override protected void onResume() { super.onResume(); if (started) nativeLifecycle(3); }
@Override protected void onDestroy() {
ui.removeCallbacks(textPoll);
super.onDestroy();
// 宿主不支持在同一进程里重新起跑:Activity 销毁就结束进程 | The host cannot restart in the same process: end the process when the Activity is destroyed
if (isFinishing()) android.os.Process.killProcess(android.os.Process.myPid());
}
}