Settings, config and saves: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: config (line 26), save (line 33), use (line 107).
1/// What a player has changed about how the game behaves for them, and where
2/// a run in progress is kept between launches.
3///
4/// `flutter3d_game`'s `GameSettings` is a value: a volume per audio bus,
5/// typed settings under namespaced keys, and the player's action map, each
6/// change a copy. It is written in the format envelope as `f3d.settings`.
7/// `SaveFile` is thin enough that this page calls the real `Storage` and
8/// `Snapshot` under it directly. `SettingsPanel` is the widget over a
9/// `GameSettingsController`, made of `SettingsSection`s; it is described in
10/// the guide rather than built here.
11///
12/// Quoted by `game_settings.md` and shown whole in the Source tab.
13library;
15import 'dart:convert';
17import 'package:flutter/widgets.dart';
18import 'package:flutter3d/flutter3d.dart';
19import 'package:flutter3d_app/flutter3d_app.dart';
20import 'package:flutter3d_audio/flutter3d_audio.dart' show AudioBus;
21import 'package:flutter3d_game/flutter3d_game.dart'
22 show GameSettingKeys, GameSettings, SettingKey;
23import 'package:flutter3d_showcase/src/demo/demo.dart';
24import 'package:flutter3d_sim/flutter3d_sim.dart';
26/// A setting of this game's own: typed, under its own namespace, with what it
27/// is when the player has not chosen.
28const SettingKey<bool> _subtitles = SettingKey<bool>(
29 'showcase.subtitles',
30 fallback: true,
31);
33/// Where a run in progress is kept. Everything below the field names is the
34/// real `Storage` and `Snapshot` this app already depends on.
35final class _SaveFile {
36 _SaveFile({required String appName}) : _storage = defaultStorage(appName);
38 final Storage _storage;
39 static const String _name = 'save.json';
41 Future<({String level, Snapshot run})?> read() async {
42 final text = await _storage.read(_name);
43 if (text == null) return null;
44 final json = jsonDecode(text) as Map<String, Object?>;
45 return (
46 level: json['level']! as String,
47 run: Snapshot.fromJson(json['run']! as Map<String, Object?>),
48 );
49 }
51 Future<void> write(String level, Snapshot run) => _storage.write(
52 _name,
53 jsonEncode(<String, Object?>{'level': level, 'run': run.toJson()}),
54 );
56 Future<void> clear() => _storage.remove(_name);
57}
59/// The `game-settings` page: a panel of settings and a save kept between
60/// launches. Its check is that an unset bus is at full volume, a save reads
61/// back with its level and state, and a cleared save reads back as nothing.
62final class GameSettingsDemo extends ShowcaseDemo {
63 late final String _report;
64 late final double _musicVolume;
65 late final double _sfxVolume;
66 late final String? _resumedLevel;
67 late final double? _resumedX;
68 late final bool _clearedSaveIsGone;
71 Future<void> prepare(DemoContext context) async {
72 final (
73 String report,
74 double musicVolume,
75 double sfxVolume,
76 String? resumedLevel,
77 double? resumedX,
78 bool clearedSaveIsGone,
79 ) = await _run();
80 _report = report;
81 _musicVolume = musicVolume;
82 _sfxVolume = sfxVolume;
83 _resumedLevel = resumedLevel;
84 _resumedX = resumedX;
85 _clearedSaveIsGone = clearedSaveIsGone;
86 }
89 Scene build(DemoContext context) {
90 final material = RenderMaterial(
91 name: 'panel',
92 baseColor: LinearColor.fromSrgb(0.5, 0.7, 0.5, 1.0),
93 );
94 final node = MeshNode(
95 DeviceMesh.upload(context.device, SphereShape(segments: 16).build()),
96 material,
97 );
98 return Scene()
99 ..add(node)
100 ..add(
101 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
102 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
103 );
104 }
106 static Future<(String, double, double, String?, double?, bool)> _run() async {
107 final config = const GameSettings()
108 .withVolume(AudioBus.music, 0.6)
109 .withValue(GameSettingKeys.cameraMotion, 0.0)
110 .withValue(_subtitles, false);
111 final musicVolume = config.volumeOf(AudioBus.music);
112 final sfxVolume = config.volumeOf(AudioBus.sfx);
113 final cameraMotion = config.valueOf(GameSettingKeys.cameraMotion);
114 // The file, in the envelope, read back.
115 final read = GameSettings.fromJson(config.toJson());
116 assert(!read.valueOf(_subtitles), 'a setting of its own came back');
118 final save = _SaveFile(appName: 'flutter3d-showcase-demo');
119 final snapshot = Snapshot(<String, Object?>{'x': 4.5});
120 await save.write('levels/one.json', snapshot);
121 final resumed = await save.read();
122 await save.clear();
123 final afterClear = await save.read();
125 final resumedX = (resumed?.run.data['x'] as num?)?.toDouble();
126 final report =
127 'music volume: $musicVolume, sfx (never set): $sfxVolume\n'
128 'camera motion setting: $cameraMotion\n'
129 'resumed at level ${resumed?.level}, x=$resumedX\n'
130 'after clearing the save: $afterClear';
131 return (
132 report,
133 musicVolume,
134 sfxVolume,
135 resumed?.level,
136 resumedX,
137 afterClear == null,
138 );
139 }
142 Widget? customBody(BuildContext buildContext, DemoContext context) =>
143 Container(
144 color: const Color(0xFF14161A),
145 padding: const EdgeInsets.all(24),
146 alignment: Alignment.topLeft,
147 child: DefaultTextStyle(
148 style: const TextStyle(color: Color(0xFFE8E8EC), fontSize: 16),
149 child: Text(_report),
150 ),
151 );
154 void verify(Scene scene, FrameResult frame) {
155 if (frame.drawCalls < 1) {
156 throw StateError('the panel marker was not drawn');
157 }
158 // Compared as numbers, not read back out of `_report`: `sfxVolume`'s
159 // default is a whole-number double, and a web backend prints one of
160 // those without its trailing `.0` — a compiled `1` failing a substring
161 // match against `'sfx (never set): 1.0'` would be this check catching
162 // its own string, not the config.
163 if (_musicVolume != 0.6 || _sfxVolume != 1.0) {
164 throw StateError('a bus nobody set should default to full volume');
165 }
166 if (_resumedLevel != 'levels/one.json' || _resumedX != 4.5) {
167 throw StateError(
168 'a written save should read back with its own level '
169 'and its own state',
170 );
171 }
172 if (!_clearedSaveIsGone) {
173 throw StateError('a cleared save should read back as nothing');
174 }
175 }
176}