feat: imported input-box pets, with dsh-Go's sprite packs
Nothing is built in: Settings → 宠物 shows "尚未导入宠物" until a zip is picked. The zip holds a dsh-Go pack.json and PNG sheets; it is validated (pack.json, every named sheet) and unpacked under the app's private files directory, with enable, size (40/52/64) and remove kept on the device. A pack's canvas, anchor, per-animation box and frame list drive rendering: PetSlot reserves the area above the baseline and stands the sprite on the composer's top edge (or on the activity cap while a turn runs). Idle, thinking, working and error follow the chat's state, and a tap plays the pack's react-left/react-right. Only one sheet is decoded at a time. path_provider's JNI binding does not load on this engine, so MainActivity exposes the files directory over a tiny method channel instead. dist/deepy-whale-pet.zip is the Deepy whale for testing. Tests cover the real pack manifest, frame/state mapping and zip import. 0.4.0 (400).
This commit is contained in:
1 parent
ff0dbf1b37
commit
d72af036a1
16 files changed
+1410
-12
No files matched your search
@@ -0,0 +1,306 @@
|
||||
// Imported pets live on the device: a zip's `pack.json` and sprite sheets are
|
||||
// unpacked under the app's documents, and only this client reads them. There
|
||||
// is no built-in pet; nothing shows until the person imports one.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:archive/archive.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'pet_pack.dart';
|
||||
|
||||
class PetImportException implements Exception {
|
||||
final String message;
|
||||
const PetImportException(this.message);
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
class PetLibrary extends ChangeNotifier {
|
||||
PetLibrary._();
|
||||
static final PetLibrary instance = PetLibrary._();
|
||||
|
||||
static const _activeKey = 'pet.active.v1';
|
||||
static const _enabledKey = 'pet.enabled.v1';
|
||||
static const _sizeKey = 'pet.size.v1';
|
||||
|
||||
/// The canvas width a pet is drawn at; the list offers these.
|
||||
static const sizes = <double>[40, 52, 64];
|
||||
|
||||
PetPack? pack;
|
||||
bool enabled = false;
|
||||
double size = 52;
|
||||
|
||||
String? _packDir;
|
||||
bool _loaded = false;
|
||||
|
||||
// One decoded sheet at a time: a full sheet can be several megabytes, and
|
||||
// only the current mood is on screen.
|
||||
String? _imagePath;
|
||||
ui.Image? _image;
|
||||
Future<ui.Image?>? _loading;
|
||||
|
||||
bool get hasPet => pack != null;
|
||||
bool get ready => pack != null && enabled;
|
||||
|
||||
Future<void> ensureLoaded() async {
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
enabled = prefs.getBool(_enabledKey) ?? false;
|
||||
size = (prefs.getDouble(_sizeKey) ?? 52).clamp(32, 80);
|
||||
final active = prefs.getString(_activeKey);
|
||||
if (active != null && active.isNotEmpty) {
|
||||
final root = await _petsRoot();
|
||||
final dir = Directory('${root.path}/$active');
|
||||
final manifest = File('${dir.path}/pack.json');
|
||||
if (await manifest.exists()) {
|
||||
final json = jsonDecode(await manifest.readAsString());
|
||||
if (json is Map<String, dynamic>) {
|
||||
final parsed = PetPack.fromJson(json);
|
||||
if (parsed.isValid) {
|
||||
pack = parsed;
|
||||
_packDir = dir.path;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// A corrupt or half-written pet must not keep the app from starting.
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> setEnabled(bool value) async {
|
||||
enabled = value;
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_enabledKey, value);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> setSize(double value) async {
|
||||
size = value.clamp(32, 80);
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setDouble(_sizeKey, size);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// Unpacks and activates a pet package. [root] is for tests; the app uses
|
||||
/// the documents directory.
|
||||
Future<PetPack> importZip(List<int> bytes, {Directory? root}) async {
|
||||
if (bytes.isEmpty) throw const PetImportException('文件为空');
|
||||
if (bytes.length > 40 * 1024 * 1024) {
|
||||
throw const PetImportException('宠物包不能超过 40MB');
|
||||
}
|
||||
|
||||
final Archive archive;
|
||||
try {
|
||||
archive = ZipDecoder().decodeBytes(bytes, verify: true);
|
||||
} catch (_) {
|
||||
throw const PetImportException('不是有效的 zip 文件');
|
||||
}
|
||||
|
||||
ArchiveFile? manifest;
|
||||
for (final file in archive.files) {
|
||||
if (!file.isFile) continue;
|
||||
final name = file.name.replaceAll('\\', '/');
|
||||
if (name == 'pack.json' || name.endsWith('/pack.json')) {
|
||||
if (manifest == null || name.length < manifest.name.length) {
|
||||
manifest = file;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (manifest == null) {
|
||||
throw const PetImportException('压缩包里没有 pack.json');
|
||||
}
|
||||
|
||||
final manifestName = manifest.name.replaceAll('\\', '/');
|
||||
final base = manifestName == 'pack.json'
|
||||
? ''
|
||||
: manifestName.substring(0, manifestName.length - '/pack.json'.length);
|
||||
|
||||
final PetPack parsed;
|
||||
try {
|
||||
final text = utf8.decode(_content(manifest));
|
||||
final json = jsonDecode(text);
|
||||
if (json is! Map<String, dynamic>) throw const FormatException();
|
||||
parsed = PetPack.fromJson(json);
|
||||
} catch (_) {
|
||||
throw const PetImportException('pack.json 不是有效的宠物包');
|
||||
}
|
||||
if (!parsed.isValid) {
|
||||
throw const PetImportException('pack.json 缺少动画或状态');
|
||||
}
|
||||
|
||||
final id = _safeId(parsed.id.isNotEmpty ? parsed.id : parsed.name);
|
||||
final rootDir = root ?? await _petsRoot();
|
||||
await rootDir.create(recursive: true);
|
||||
final staging = Directory('${rootDir.path}/.$id.importing');
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
await staging.create(recursive: true);
|
||||
|
||||
try {
|
||||
var extracted = 0;
|
||||
for (final file in archive.files) {
|
||||
if (!file.isFile) continue;
|
||||
final name = file.name.replaceAll('\\', '/');
|
||||
if (base.isNotEmpty && !name.startsWith('$base/')) continue;
|
||||
final rel = base.isEmpty ? name : name.substring(base.length + 1);
|
||||
if (rel.isEmpty || rel.startsWith('/')) continue;
|
||||
final segments = rel.split('/');
|
||||
if (segments.any((s) => s.isEmpty || s == '..' || s == '.')) continue;
|
||||
final content = _content(file);
|
||||
extracted += content.length;
|
||||
if (extracted > 60 * 1024 * 1024) {
|
||||
throw const PetImportException('解压后超过 60MB');
|
||||
}
|
||||
final target = File('${staging.path}/$rel');
|
||||
await target.parent.create(recursive: true);
|
||||
await target.writeAsBytes(content, flush: true);
|
||||
}
|
||||
|
||||
for (final animation in parsed.animations.values) {
|
||||
if (animation.sheet.isEmpty) {
|
||||
throw PetImportException('动画 ${animation.name} 没有精灵图');
|
||||
}
|
||||
final sheet = File('${staging.path}/${animation.sheet}');
|
||||
if (!await sheet.exists()) {
|
||||
throw PetImportException('缺少精灵图 ${animation.sheet}');
|
||||
}
|
||||
}
|
||||
|
||||
final destination = Directory('${rootDir.path}/$id');
|
||||
if (await destination.exists()) await destination.delete(recursive: true);
|
||||
await staging.rename(destination.path);
|
||||
|
||||
_clearImages();
|
||||
pack = parsed;
|
||||
_packDir = destination.path;
|
||||
enabled = true;
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_activeKey, id);
|
||||
await prefs.setBool(_enabledKey, true);
|
||||
} catch (_) {}
|
||||
notifyListeners();
|
||||
return parsed;
|
||||
} catch (_) {
|
||||
if (await staging.exists()) {
|
||||
try {
|
||||
await staging.delete(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> remove() async {
|
||||
final dir = _packDir;
|
||||
pack = null;
|
||||
_packDir = null;
|
||||
enabled = false;
|
||||
_clearImages();
|
||||
notifyListeners();
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_activeKey);
|
||||
await prefs.setBool(_enabledKey, false);
|
||||
} catch (_) {}
|
||||
if (dir != null) {
|
||||
try {
|
||||
await Directory(dir).delete(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoded sheet for [animation], held one at a time.
|
||||
Future<ui.Image?> imageFor(PetAnimation animation) {
|
||||
final dir = _packDir;
|
||||
if (dir == null || animation.sheet.isEmpty) return Future.value(null);
|
||||
final path = '$dir/${animation.sheet}';
|
||||
if (_imagePath == path) {
|
||||
if (_image != null) return Future.value(_image);
|
||||
if (_loading != null) return _loading!;
|
||||
}
|
||||
_imagePath = path;
|
||||
_image?.dispose();
|
||||
_image = null;
|
||||
final loading = _decode(path);
|
||||
_loading = loading;
|
||||
return loading;
|
||||
}
|
||||
|
||||
Future<ui.Image?> _decode(String path) async {
|
||||
try {
|
||||
final bytes = await File(path).readAsBytes();
|
||||
final codec = await ui.instantiateImageCodec(bytes);
|
||||
final frame = await codec.getNextFrame();
|
||||
final image = frame.image;
|
||||
if (_imagePath != path) {
|
||||
image.dispose();
|
||||
return null;
|
||||
}
|
||||
_image = image;
|
||||
return image;
|
||||
} catch (_) {
|
||||
return null;
|
||||
} finally {
|
||||
if (_imagePath == path) _loading = null;
|
||||
}
|
||||
}
|
||||
|
||||
void _clearImages() {
|
||||
_image?.dispose();
|
||||
_image = null;
|
||||
_imagePath = null;
|
||||
_loading = null;
|
||||
}
|
||||
|
||||
static const _appDirChannel = MethodChannel('openchamber/appdir');
|
||||
|
||||
Future<Directory> _petsRoot() async {
|
||||
String? base;
|
||||
if (Platform.isAndroid) {
|
||||
// A tiny channel in MainActivity: enough to find the app's files dir
|
||||
// without the JNI-based path_provider, which this engine cannot load.
|
||||
try {
|
||||
base = await _appDirChannel.invokeMethod<String>('documents');
|
||||
} catch (_) {
|
||||
// Fall through to the StateError below.
|
||||
}
|
||||
} else {
|
||||
final env = Platform.environment;
|
||||
final data = env['XDG_DATA_HOME'];
|
||||
base = data != null && data.isNotEmpty
|
||||
? '$data/openchamber'
|
||||
: '${env['HOME'] ?? '.'}/.local/share/openchamber';
|
||||
}
|
||||
if (base == null || base.isEmpty) {
|
||||
throw StateError('no writable directory for pets');
|
||||
}
|
||||
final root = Directory('$base/pets');
|
||||
if (!await root.exists()) await root.create(recursive: true);
|
||||
return root;
|
||||
}
|
||||
|
||||
static List<int> _content(ArchiveFile file) {
|
||||
final content = file.content;
|
||||
return content is List<int> ? content : List<int>.from(content as List);
|
||||
}
|
||||
|
||||
static String _safeId(String raw) {
|
||||
final id = raw
|
||||
.toLowerCase()
|
||||
.replaceAll(RegExp(r'[^a-z0-9._-]+'), '-')
|
||||
.replaceAll(RegExp(r'^[-._]+|[-._]+$'), '');
|
||||
return id.isEmpty ? 'pet' : id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
// A pet package, in the shape dsh-Go's packs already use: `pack.json` points
|
||||
// at PNG sprite sheets, each frame cropped from a canvas of a few logical
|
||||
// pixels, and names the animations for each mood.
|
||||
import 'dart:ui';
|
||||
|
||||
/// One sheet frame in the play order, with how long it stays up.
|
||||
class PetFrame {
|
||||
final int index;
|
||||
final int ms;
|
||||
const PetFrame(this.index, this.ms);
|
||||
}
|
||||
|
||||
class PetAnimation {
|
||||
final String name;
|
||||
final String sheet;
|
||||
final int frameW;
|
||||
final int frameH;
|
||||
final int cols;
|
||||
final bool loop;
|
||||
|
||||
/// Where this animation sits on the pack's logical canvas.
|
||||
final Rect box;
|
||||
final List<PetFrame> frames;
|
||||
|
||||
const PetAnimation({
|
||||
required this.name,
|
||||
required this.sheet,
|
||||
required this.frameW,
|
||||
required this.frameH,
|
||||
required this.cols,
|
||||
required this.loop,
|
||||
required this.box,
|
||||
required this.frames,
|
||||
});
|
||||
|
||||
int get totalMs => frames.fold(0, (sum, f) => sum + f.ms);
|
||||
|
||||
factory PetAnimation.fromJson(String name, Map<String, dynamic> j) {
|
||||
final box = _rect(j['box'], const Rect.fromLTWH(0, 0, 1, 1));
|
||||
final cols = _int(j['cols'], 1).clamp(1, 4096);
|
||||
final total = _int(j['ms'], 50 * cols);
|
||||
final frames = <PetFrame>[];
|
||||
final raw = j['frames'];
|
||||
if (raw is List) {
|
||||
for (final e in raw) {
|
||||
if (e is! Map) continue;
|
||||
final ms = _int(e['ms'], 50);
|
||||
frames.add(PetFrame(_int(e['i'], 0), ms <= 0 ? 50 : ms));
|
||||
}
|
||||
}
|
||||
if (frames.isEmpty) {
|
||||
final each = (total / cols).round().clamp(16, 2000);
|
||||
for (var i = 0; i < cols; i++) {
|
||||
frames.add(PetFrame(i, each));
|
||||
}
|
||||
}
|
||||
return PetAnimation(
|
||||
name: name,
|
||||
sheet: j['sheet'] as String? ?? '',
|
||||
frameW: _int(j['frameW'], (box.width * 5).round()),
|
||||
frameH: _int(j['frameH'], (box.height * 5).round()),
|
||||
cols: cols,
|
||||
loop: j['loop'] != false,
|
||||
box: box,
|
||||
frames: frames,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pack says. Only the parts this client draws are kept; reactions
|
||||
/// and idle pools are read as far as they can be played.
|
||||
class PetPack {
|
||||
final String id;
|
||||
final String name;
|
||||
final String author;
|
||||
final String license;
|
||||
final String source;
|
||||
final bool pixelArt;
|
||||
|
||||
/// The logical canvas the frames are placed on.
|
||||
final Size canvas;
|
||||
|
||||
/// Where the pet's feet rest on that canvas.
|
||||
final Offset anchor;
|
||||
final Rect contentBox;
|
||||
|
||||
final Map<String, PetAnimation> animations;
|
||||
final Map<String, List<String>> states;
|
||||
|
||||
/// tapLeft / tapRight / tickle / drag -> animation name.
|
||||
final Map<String, String> reactions;
|
||||
|
||||
const PetPack({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.author,
|
||||
required this.license,
|
||||
required this.source,
|
||||
required this.pixelArt,
|
||||
required this.canvas,
|
||||
required this.anchor,
|
||||
required this.contentBox,
|
||||
required this.animations,
|
||||
required this.states,
|
||||
required this.reactions,
|
||||
});
|
||||
|
||||
bool get isValid =>
|
||||
animations.isNotEmpty && states.values.any((list) => list.any(animations.containsKey));
|
||||
|
||||
String? get idleName {
|
||||
for (final name in states['idle'] ?? const <String>[]) {
|
||||
if (animations.containsKey(name)) return name;
|
||||
}
|
||||
return animations.keys.isEmpty ? null : animations.keys.first;
|
||||
}
|
||||
|
||||
/// The first animation of [state] the pack actually has, then idle.
|
||||
String? animationForState(String state) {
|
||||
for (final name in states[state] ?? const <String>[]) {
|
||||
if (animations.containsKey(name)) return name;
|
||||
}
|
||||
return idleName;
|
||||
}
|
||||
|
||||
PetAnimation? animation(String? name) =>
|
||||
name == null ? null : animations[name];
|
||||
|
||||
factory PetPack.fromJson(Map<String, dynamic> j) {
|
||||
final canvasJson = j['canvas'];
|
||||
final cw = _double(canvasJson is Map ? canvasJson['w'] : null, 52);
|
||||
final ch = _double(canvasJson is Map ? canvasJson['h'] : null, cw);
|
||||
final anchorJson = j['anchor'];
|
||||
final ax = _double(anchorJson is Map ? anchorJson['x'] : null, cw / 2);
|
||||
final ay = _double(anchorJson is Map ? anchorJson['baseline'] : null, ch);
|
||||
|
||||
final animations = <String, PetAnimation>{};
|
||||
final rawAnims = j['animations'];
|
||||
if (rawAnims is Map) {
|
||||
for (final e in rawAnims.entries) {
|
||||
final value = e.value;
|
||||
if (e.key is String && value is Map) {
|
||||
animations[e.key as String] =
|
||||
PetAnimation.fromJson(e.key as String, Map<String, dynamic>.from(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final states = <String, List<String>>{};
|
||||
final rawStates = j['states'];
|
||||
if (rawStates is Map) {
|
||||
for (final e in rawStates.entries) {
|
||||
final list = e.value;
|
||||
if (e.key is String && list is List) {
|
||||
states[e.key as String] = [
|
||||
for (final v in list)
|
||||
if (v is String) v,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final reactions = <String, String>{};
|
||||
final rawReactions = j['reactions'];
|
||||
if (rawReactions is Map) {
|
||||
for (final key in const ['tapLeft', 'tapRight', 'tickle', 'drag']) {
|
||||
final v = rawReactions[key];
|
||||
if (v is String) {
|
||||
reactions[key] = v;
|
||||
} else if (v is Map) {
|
||||
final file = v['file'];
|
||||
final files = v['files'];
|
||||
if (file is String) {
|
||||
reactions[key] = file;
|
||||
} else if (files is List && files.isNotEmpty && files.first is String) {
|
||||
reactions[key] = files.first as String;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PetPack(
|
||||
id: j['id'] as String? ?? '',
|
||||
name: j['name'] as String? ?? '',
|
||||
author: j['author'] as String? ?? '',
|
||||
license: j['license'] as String? ?? '',
|
||||
source: j['source'] as String? ?? '',
|
||||
pixelArt: j['pixelArt'] != false,
|
||||
canvas: Size(cw, ch),
|
||||
anchor: Offset(ax, ay),
|
||||
contentBox: _rect(j['contentBox'], Rect.fromLTWH(0, 0, cw, ch)),
|
||||
animations: animations,
|
||||
states: states,
|
||||
reactions: reactions,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
int _int(Object? v, int fallback) =>
|
||||
v is num ? v.toInt() : (v is String ? int.tryParse(v) ?? fallback : fallback);
|
||||
|
||||
double _double(Object? v, double fallback) =>
|
||||
v is num ? v.toDouble() : (v is String ? double.tryParse(v) ?? fallback : fallback);
|
||||
|
||||
Rect _rect(Object? v, Rect fallback) {
|
||||
if (v is! Map) return fallback;
|
||||
return Rect.fromLTWH(
|
||||
_double(v['x'], fallback.left),
|
||||
_double(v['y'], fallback.top),
|
||||
_double(v['w'], fallback.width),
|
||||
_double(v['h'], fallback.height),
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user