Adaptive resolution: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: adaptive (line 24), record (line 38), scale (line 43), size (line 60).
1/// Adaptive resolution: `RenderSettings.renderScale` shrinks every target the
2/// frame draws into, and `AdaptiveScale` decides the number from how long a
3/// frame has been taking.
4///
5/// Quoted by `adaptive_resolution.md` and shown whole in the Source tab.
6library;
8import 'package:flutter3d/flutter3d.dart';
9import 'package:flutter3d_showcase/pages/post/post_stage.dart';
10import 'package:flutter3d_showcase/src/demo/demo.dart';
12/// The `adaptive-resolution` page: the post stage drawn at the scale
13/// `AdaptiveScale` picks for a frame cost the page pretends. Its check is
14/// that the frame came out at that scale of 320 by 180.
15final class AdaptiveResolutionDemo extends ShowcaseDemo {
16 /// The frame cost fed to `AdaptiveScale` each frame, in milliseconds, 4 to
17 /// 40, standing in for a measured one.
18 double simulatedMs = 20.0;
20 /// The render scale `AdaptiveScale` answered with on the last update, read
21 /// into `RenderSettings.renderScale`; 1 is full size.
22 double scale = 1.0;
24 /// A window of one frame, so this page reacts on the very next tick rather
25 /// than averaging several — a real game wants a wider window than this.
26 final AdaptiveScale _adaptive = AdaptiveScale(
27 const AdaptiveScaleSettings(enabled: true, window: 1),
28 );
31 void configureView(DemoContext context) => PostStage.frame(context);
34 Scene build(DemoContext context) => PostStage.build(context).scene;
37 void update(DemoContext context, double dt) {
38 scale = _adaptive.recordFrame((simulatedMs * 1000).round());
39 }
42 RenderSettings settings(DemoContext context) => RenderSettings(
43 renderScale: scale,
44 );
47 List<DemoControl> controls(DemoContext context) => <DemoControl>[
48 SliderControl(
49 'Simulated frame cost',
50 min: 4,
51 max: 40,
52 value: () => simulatedMs,
53 onChanged: (double v) => simulatedMs = v,
54 format: (double v) => '${v.round()} ms',
55 ),
56 ];
59 void verify(Scene scene, FrameResult frame) {
60 final int expectedWidth = (320 * scale).round();
61 final int expectedHeight = (180 * scale).round();
62 if (frame.frame.width != expectedWidth ||
63 frame.frame.height != expectedHeight) {
64 throw StateError(
65 'asked for a frame scaled to $scale and got '
66 '${frame.frame.width}x${frame.frame.height}',
67 );
68 }
69 }
70}