From b79fee0ae2ac94f997445367b2089f61721952a2 Mon Sep 17 00:00:00 2001 From: Luan Nico Date: Sun, 10 Aug 2025 12:42:31 -0400 Subject: [PATCH] chore: Update min Dart constraint to 3.8 (#3676) Update min Dart constraint to 3.8, which will enable us to use the fancier collection literals. This requires bumping the min Flutter version as well: image --- .github/workflows/cicd.yml | 2 +- .../examples/lib/collision_detection.dart | 10 +- doc/flame/examples/lib/drag_events.dart | 14 +- doc/flame/examples/lib/ember.dart | 4 +- doc/flame/examples/lib/flower.dart | 4 +- doc/flame/examples/lib/glow_effect.dart | 12 +- doc/flame/examples/lib/pointer_events.dart | 19 +- doc/flame/examples/lib/remove_effect.dart | 4 +- doc/flame/examples/lib/rive_example.dart | 5 +- doc/flame/examples/lib/router.dart | 54 +- doc/flame/examples/lib/tap_events.dart | 8 +- doc/flame/examples/lib/value_route.dart | 10 +- doc/flame/examples/pubspec.yaml | 2 +- doc/tutorials/klondike/app/lib/main.dart | 8 +- .../klondike/app/lib/step2/klondike_game.dart | 12 +- .../app/lib/step3/components/card.dart | 8 +- .../klondike/app/lib/step3/klondike_game.dart | 12 +- .../klondike/app/lib/step3/rank.dart | 4 +- .../klondike/app/lib/step3/suit.dart | 2 +- .../app/lib/step4/components/card.dart | 6 +- .../lib/step4/components/foundation_pile.dart | 4 +- .../klondike/app/lib/step4/klondike_game.dart | 11 +- .../klondike/app/lib/step4/rank.dart | 4 +- .../klondike/app/lib/step4/suit.dart | 2 +- .../app/lib/step5/components/card.dart | 10 +- .../app/lib/step5/components/flat_button.dart | 36 +- .../lib/step5/components/foundation_pile.dart | 4 +- .../lib/step5/components/tableau_pile.dart | 3 +- .../app/lib/step5/klondike_world.dart | 6 +- .../klondike/app/lib/step5/rank.dart | 4 +- .../klondike/app/lib/step5/suit.dart | 2 +- doc/tutorials/klondike/app/pubspec.yaml | 2 +- .../platformer/app/lib/actors/ember.dart | 22 +- .../platformer/app/lib/ember_quest.dart | 24 +- doc/tutorials/platformer/app/pubspec.yaml | 2 +- doc/tutorials/space_shooter/app/lib/main.dart | 8 +- .../space_shooter/app/lib/step2/main.dart | 8 +- .../space_shooter/app/lib/step3/main.dart | 8 +- .../space_shooter/app/lib/step4/main.dart | 17 +- .../space_shooter/app/lib/step5/main.dart | 23 +- .../space_shooter/app/lib/step6/main.dart | 31 +- doc/tutorials/space_shooter/app/pubspec.yaml | 2 +- .../games/crystal_ball/lib/crystal_ball.dart | 23 +- .../src/game/components/input_handler.dart | 8 +- .../lib/src/game/entities/ground.dart | 48 +- .../lib/src/game/entities/the_ball.dart | 18 +- .../games/crystal_ball/lib/src/game/game.dart | 12 +- .../src/game/post_processes/ball_glow.dart | 8 +- .../lib/src/game/post_processes/firefly.dart | 5 +- .../game/post_processes/foreground_fog.dart | 4 +- .../lib/src/game/post_processes/water.dart | 5 +- examples/games/crystal_ball/pubspec.yaml | 2 +- examples/games/padracing/lib/ball.dart | 7 +- examples/games/padracing/lib/car.dart | 8 +- examples/games/padracing/lib/lap_line.dart | 7 +- examples/games/padracing/lib/lap_text.dart | 2 +- .../games/padracing/lib/padracing_game.dart | 30 +- examples/games/padracing/lib/tire.dart | 28 +- examples/games/padracing/pubspec.yaml | 2 +- .../lib/components/bullet_component.dart | 2 +- .../lib/components/enemy_component.dart | 2 +- .../lib/components/explosion_component.dart | 10 +- .../lib/components/star_component.dart | 2 +- examples/games/rogue_shooter/pubspec.yaml | 2 +- examples/games/trex/lib/background/cloud.dart | 11 +- .../games/trex/lib/background/horizon.dart | 3 +- .../games/trex/lib/obstacle/obstacle.dart | 4 +- .../trex/lib/obstacle/obstacle_type.dart | 16 +- examples/games/trex/pubspec.yaml | 2 +- examples/lib/commons/ember.dart | 8 +- .../stories/bridge_libraries/audio/audio.dart | 4 +- .../flame_forge2d/animated_body_example.dart | 8 +- .../flame_forge2d/composition_example.dart | 12 +- .../contact_callbacks_example.dart | 2 +- .../flame_forge2d/domino_example.dart | 2 +- .../flame_forge2d/joints/friction_joint.dart | 2 +- .../flame_forge2d/joints/gear_joint.dart | 7 +- .../flame_forge2d/joints/motor_joint.dart | 2 +- .../flame_forge2d/joints/mouse_joint.dart | 2 +- .../flame_forge2d/joints/revolute_joint.dart | 2 +- .../flame_forge2d/joints/weld_joint.dart | 11 +- .../flame_forge2d/sprite_body_example.dart | 8 +- .../flame_forge2d/utils/boundaries.dart | 2 +- .../flame_isolate/isolate.dart | 4 +- ...command_lifecycle_dialogue_controller.dart | 2 +- .../components/dialogue_text_box.dart | 18 +- .../jenny_command_lifecycle_example.dart | 10 +- .../bridge_libraries/flame_lottie/lottie.dart | 4 +- .../flame_spine/flame_spine.dart | 5 +- .../camera_and_viewport.dart | 5 +- .../camera_component_example.dart | 63 +- .../camera_component_properties_example.dart | 33 +- .../camera_follow_and_world_bounds.dart | 45 +- .../fixed_resolution_example.dart | 50 +- .../follow_component_example.dart | 24 +- .../static_components_example.dart | 12 +- .../collision_detection/circles_example.dart | 10 +- .../collidable_animation_example.dart | 28 +- .../collision_detection.dart | 10 +- .../multiple_shapes_example.dart | 38 +- .../collision_detection/quadtree_example.dart | 13 +- .../rays_in_shape_example.dart | 49 +- .../collision_detection/raytrace_example.dart | 113 ++-- .../components/clip_component_example.dart | 2 +- .../lib/stories/components/components.dart | 5 +- .../components_notifier_example.dart | 8 +- .../components_notifier_provider_example.dart | 8 +- .../components/composability_example.dart | 10 +- .../stories/components/look_at_example.dart | 6 +- .../components/look_at_smooth_example.dart | 3 +- .../stories/components/priority_example.dart | 26 +- .../components/spawn_component_example.dart | 36 +- .../components/time_scale_example.dart | 16 +- .../stories/effects/color_effect_example.dart | 18 +- .../effects/effect_controllers_example.dart | 68 +- .../effects/function_effect_example.dart | 18 +- .../stories/effects/glow_effect_example.dart | 14 +- .../stories/effects/move_effect_example.dart | 74 +-- .../effects/opacity_effect_example.dart | 12 +- .../effects/remove_effect_example.dart | 16 +- .../effects/rotate_around_effect_example.dart | 37 +- .../effects/rotate_effect_example.dart | 46 +- .../effects/sequence_effect_example.dart | 22 +- examples/lib/stories/experimental/shapes.dart | 32 +- .../input/double_tap_callbacks_example.dart | 14 +- .../input/gesture_hitboxes_example.dart | 16 +- .../input/hover_callbacks_example.dart | 10 +- .../input/joystick_advanced_example.dart | 12 +- .../lib/stories/input/joystick_player.dart | 2 +- .../overlapping_tap_callbacks_example.dart | 14 +- .../stories/input/tap_callbacks_example.dart | 8 +- examples/lib/stories/layout/layout.dart | 4 +- .../rendering/isometric_tile_map_example.dart | 8 +- .../stories/rendering/particles_example.dart | 8 +- .../particles_interactive_example.dart | 20 +- .../stories/rendering/rich_text_example.dart | 5 +- .../lib/stories/rendering/text_example.dart | 30 +- examples/lib/stories/router/router.dart | 4 +- .../stories/router/router_world_example.dart | 58 +- .../sprites/sprite_batch_load_example.dart | 6 +- .../stories/sprites/sprite_sheet_example.dart | 26 +- examples/lib/stories/structure/levels.dart | 37 +- examples/lib/stories/structure/structure.dart | 4 +- examples/lib/stories/svg/svg.dart | 4 +- examples/lib/stories/svg/svg_component.dart | 34 +- .../lib/stories/system/overlays_example.dart | 12 +- .../stories/system/pause_resume_example.dart | 4 +- .../lib/stories/system/resize_example.dart | 6 +- examples/lib/stories/tiled/tiled.dart | 4 +- .../utils/timer_component_example.dart | 8 +- .../sprite_animation_widget_example.dart | 15 +- .../widgets/sprite_widget_example.dart | 15 +- examples/pubspec.yaml | 2 +- .../update_components_benchmark.dart | 7 +- packages/flame/example/lib/main.dart | 10 +- packages/flame/example/pubspec.yaml | 2 +- packages/flame/lib/src/cache/images.dart | 29 +- .../behaviors/bounded_position_behavior.dart | 10 +- .../src/camera/behaviors/follow_behavior.dart | 16 +- .../lib/src/camera/camera_component.dart | 55 +- .../quadtree/quad_tree_broadphase.dart | 26 +- .../broadphase/quadtree/quadtree.dart | 7 +- .../quadtree_collision_detection.dart | 16 +- .../src/collisions/collision_callbacks.dart | 9 +- .../src/collisions/collision_detection.dart | 6 +- .../src/collisions/collision_passthrough.dart | 8 +- .../collisions/hitboxes/circle_hitbox.dart | 14 +- .../collisions/hitboxes/rectangle_hitbox.dart | 8 +- .../src/collisions/hitboxes/shape_hitbox.dart | 36 +- .../standard_collision_detection.dart | 13 +- .../lib/src/components/clip_component.dart | 60 +- .../lib/src/components/core/component.dart | 10 +- .../components/core/component_tree_root.dart | 4 +- .../src/components/core/recycled_queue.dart | 16 +- .../src/components/fps_text_component.dart | 8 +- .../components/input/button_component.dart | 4 +- .../input/hud_button_component.dart | 4 +- .../input/hud_margin_component.dart | 9 +- .../components/input/joystick_component.dart | 24 +- .../input/keyboard_listener_component.dart | 4 +- .../input/sprite_button_component.dart | 12 +- .../isometric_tile_map_component.dart | 9 +- .../mixins/component_viewport_margin.dart | 3 +- .../lib/src/components/mixins/has_paint.dart | 6 +- .../lib/src/components/mixins/has_world.dart | 6 +- .../src/components/parallax_component.dart | 10 +- .../src/components/position_component.dart | 18 +- .../components/raster_sprite_component.dart | 36 +- .../src/components/router/overlay_route.dart | 8 +- .../lib/src/components/router/route.dart | 6 +- .../components/router/router_component.dart | 4 +- .../src/components/router/value_route.dart | 6 +- .../src/components/router/world_route.dart | 8 +- .../components/scroll_text_box_component.dart | 18 +- .../lib/src/components/spawn_component.dart | 61 +- .../sprite_animation_component.dart | 52 +- .../sprite_animation_group_component.dart | 84 +-- .../lib/src/components/sprite_component.dart | 50 +- .../components/sprite_group_component.dart | 16 +- .../src/components/text_box_component.dart | 46 +- .../lib/src/components/text_component.dart | 4 +- .../connectors/component_tree_connector.dart | 32 +- .../lib/src/effects/anchor_by_effect.dart | 4 +- .../flame/lib/src/effects/anchor_effect.dart | 30 +- .../lib/src/effects/anchor_to_effect.dart | 4 +- .../flame/lib/src/effects/color_effect.dart | 18 +- .../controllers/callback_controller.dart | 4 +- .../controllers/curved_effect_controller.dart | 4 +- .../delayed_effect_controller.dart | 8 +- .../duration_effect_controller.dart | 6 +- .../controllers/effect_controller.dart | 8 +- .../infinite_effect_controller.dart | 4 +- .../controllers/pause_effect_controller.dart | 2 +- .../controllers/random_effect_controller.dart | 6 +- .../repeated_effect_controller.dart | 10 +- .../reverse_curved_effect_controller.dart | 4 +- .../sequence_effect_controller.dart | 16 +- .../controllers/sine_effect_controller.dart | 4 +- .../controllers/speed_effect_controller.dart | 6 +- .../controllers/zigzag_effect_controller.dart | 6 +- packages/flame/lib/src/effects/effect.dart | 10 +- .../src/effects/move_along_path_effect.dart | 14 +- .../flame/lib/src/effects/move_by_effect.dart | 4 +- .../flame/lib/src/effects/move_effect.dart | 30 +- .../flame/lib/src/effects/move_to_effect.dart | 6 +- .../flame/lib/src/effects/opacity_effect.dart | 10 +- .../lib/src/effects/provider_interfaces.dart | 4 +- .../flame/lib/src/effects/remove_effect.dart | 6 +- .../flame/lib/src/effects/rotate_effect.dart | 4 +- .../flame/lib/src/effects/scale_effect.dart | 25 +- .../lib/src/effects/sequence_effect.dart | 28 +- .../flame/lib/src/effects/size_effect.dart | 25 +- .../double_tap_dispatcher.dart | 8 +- .../events/hardware_keyboard_detector.dart | 2 +- .../events/messages/displacement_event.dart | 15 +- .../messages/double_tap_down_event.dart | 8 +- .../src/events/messages/drag_end_event.dart | 2 +- .../src/events/messages/drag_start_event.dart | 11 +- .../events/messages/drag_update_event.dart | 15 +- .../flame/lib/src/events/messages/event.dart | 7 +- .../events/messages/pointer_move_event.dart | 13 +- .../src/events/messages/position_event.dart | 5 +- .../src/events/messages/tap_down_event.dart | 11 +- .../lib/src/events/messages/tap_up_event.dart | 11 +- .../experimental/geometry/shapes/circle.dart | 6 +- .../experimental/geometry/shapes/polygon.dart | 14 +- .../geometry/shapes/rectangle.dart | 11 +- .../experimental/linear_layout_component.dart | 20 +- .../src/experimental/padding_component.dart | 4 +- .../lib/src/experimental/raycast_result.dart | 10 +- packages/flame/lib/src/game/flame_game.dart | 14 +- packages/flame/lib/src/game/game.dart | 5 +- .../lib/src/game/game_widget/game_widget.dart | 30 +- .../game_widget/gesture_detector_builder.dart | 10 +- .../flame/lib/src/game/overlay_manager.dart | 14 +- packages/flame/lib/src/game/transform2d.dart | 12 +- packages/flame/lib/src/geometry/line.dart | 10 +- .../lib/src/geometry/polygon_component.dart | 36 +- .../geometry/polygon_ray_intersection.dart | 31 +- .../lib/src/geometry/rectangle_component.dart | 20 +- .../lib/src/geometry/shape_intersections.dart | 16 +- packages/flame/lib/src/layers/processors.dart | 8 +- packages/flame/lib/src/nine_tile_box.dart | 2 +- packages/flame/lib/src/parallax.dart | 30 +- .../src/particles/accelerated_particle.dart | 6 +- .../lib/src/particles/image_particle.dart | 8 +- .../particles/sprite_animation_particle.dart | 12 +- .../lib/src/post_process/post_process.dart | 5 +- .../post_process/post_process_component.dart | 11 +- .../lib/src/rendering/paint_decorator.dart | 6 +- .../lib/src/rendering/shadow3d_decorator.dart | 16 +- .../src/rendering/transform2d_decorator.dart | 2 +- packages/flame/lib/src/sprite_animation.dart | 16 +- packages/flame/lib/src/sprite_batch.dart | 39 +- packages/flame/lib/src/sprite_sheet.dart | 17 +- packages/flame/lib/src/text/common/glyph.dart | 40 +- .../lib/src/text/common/line_metrics.dart | 15 +- .../src/text/elements/group_text_element.dart | 6 +- .../lib/src/text/elements/rect_element.dart | 2 +- .../elements/text_painter_text_element.dart | 14 +- .../lib/src/text/nodes/bold_text_node.dart | 2 +- .../lib/src/text/nodes/code_text_node.dart | 2 +- .../flame/lib/src/text/nodes/column_node.dart | 7 +- .../lib/src/text/nodes/custom_text_node.dart | 5 +- .../flame/lib/src/text/nodes/header_node.dart | 2 +- .../lib/src/text/nodes/italic_text_node.dart | 2 +- .../lib/src/text/nodes/paragraph_node.dart | 2 +- .../lib/src/text/nodes/plain_text_node.dart | 4 +- .../text/nodes/strikethrough_text_node.dart | 2 +- .../lib/src/text/nodes/text_block_node.dart | 7 +- .../lib/src/text/styles/background_style.dart | 28 +- .../lib/src/text/styles/block_style.dart | 4 +- .../lib/src/text/styles/document_style.dart | 44 +- packages/flame/lib/src/timer.dart | 10 +- .../lib/src/widgets/animation_widget.dart | 11 +- .../flame/lib/src/widgets/nine_tile_box.dart | 14 +- .../flame/lib/src/widgets/sprite_button.dart | 103 +-- .../flame/lib/src/widgets/sprite_painter.dart | 2 +- .../flame/lib/src/widgets/sprite_widget.dart | 10 +- packages/flame/pubspec.yaml | 2 +- .../test/_resources/custom_flame_game.dart | 4 +- .../test/camera/camera_test_helpers.dart | 2 +- .../flame/test/camera/viewfinder_test.dart | 25 +- .../fixed_resolution_viewport_test.dart | 25 +- .../viewports/fixed_size_viewport_test.dart | 15 +- .../camera/viewports/max_viewport_test.dart | 25 +- .../collision_callback_benchmark_test.dart | 11 +- .../collisions/collision_callback_test.dart | 362 +++++----- .../collisions/collision_detection_test.dart | 296 +++++---- .../collision_passthrough_test.dart | 8 +- .../collisions/collision_test_helpers.dart | 10 +- .../advanced_button_component_test.dart | 10 +- .../components/button_component_test.dart | 5 +- .../test/components/clip_component_test.dart | 10 +- .../flame/test/components/component_test.dart | 44 +- .../components/components_notifier_test.dart | 4 +- .../components/hud_button_component_test.dart | 11 +- .../input/sprite_button_component_test.dart | 15 +- .../components/joystick_component_test.dart | 6 +- .../component_viewport_margin_test.dart | 3 +- .../mixins/gesture_hitboxes_test.dart | 76 ++- .../components/mixins/has_decorator_test.dart | 2 +- .../flame/test/components/parallax_test.dart | 32 +- .../components/position_component_test.dart | 70 +- .../post_process_component_test.dart | 36 +- .../flame/test/components/route_test.dart | 8 +- .../components/router_component_test.dart | 12 +- .../test/components/spawn_component_test.dart | 72 +- ...sprite_animation_group_component_test.dart | 162 ++--- .../components/text_box_component_test.dart | 58 +- .../test/components/timer_component_test.dart | 98 +-- .../toogle_button_component_test.dart | 15 +- packages/flame/test/custom_component.dart | 12 +- .../flame/test/effects/color_effect_test.dart | 8 +- ...s_single_child_effect_controller_test.dart | 16 +- .../sine_effect_controller_test.dart | 6 +- .../speed_effect_controller_test.dart | 6 +- .../effects/move_along_path_effect_test.dart | 5 +- .../test/effects/opacity_effect_test.dart | 52 +- .../component_mixins/drag_callbacks_test.dart | 18 +- .../hover_callbacks_test.dart | 23 +- .../component_mixins/ignore_events_test.dart | 2 +- .../pointer_move_callbacks_test.dart | 23 +- .../component_mixins/tap_callbacks_test.dart | 33 +- .../multi_touch_drag_detector_test.dart | 5 +- .../multi_touch_tap_detector_test.dart | 5 +- .../linear_layout_component_test.dart | 133 ++-- .../experimental/padding_component_test.dart | 59 +- .../flame/test/extensions/canvas_test.dart | 3 +- .../flame/test/extensions/matrix4_test.dart | 5 +- .../flame/test/extensions/offset_test.dart | 24 +- .../flame/test/extensions/paint_test.dart | 309 ++++----- packages/flame/test/extensions/rect_test.dart | 67 +- packages/flame/test/extensions/size_test.dart | 23 +- .../flame/test/extensions/vector2_test.dart | 40 +- ...game_widget_controlled_lifecycle_test.dart | 6 +- .../game_widget_lifecycle_test.dart | 6 +- .../flame/test/game/transform2d_test.dart | 21 +- packages/flame/test/geometry/ray2_test.dart | 144 ++-- .../flame/test/gestures/detectors_test.dart | 22 +- .../test/particles/circle_particle_test.dart | 29 +- .../particles/composed_particle_test.dart | 10 +- .../particles/computed_particle_test.dart | 59 +- .../test/particles/curved_particle_test.dart | 26 +- .../test/particles/moving_particle_test.dart | 39 +- .../test/particles/scaled_particle_test.dart | 48 +- .../test/particles/scaling_particle_test.dart | 3 +- .../test/particles/sprite_particle_test.dart | 31 +- .../flame/test/sprite_animation_test.dart | 7 +- .../test/sprite_animation_ticker_test.dart | 101 +-- packages/flame/test/spritesheet_test.dart | 10 +- .../test/text/sprite_font_renderer_test.dart | 3 +- packages/flame/test/text/text_paint_test.dart | 5 +- .../widgets/nine_tile_box_widget_test.dart | 15 +- .../widgets/sprite_animation_widget_test.dart | 10 +- .../test/widgets/sprite_button_test.dart | 5 +- .../test/widgets/sprite_widget_test.dart | 10 +- packages/flame_3d/bin/build_shaders.dart | 5 +- .../example/lib/components/player.dart | 16 +- .../lib/components/rotating_light.dart | 10 +- .../example/lib/example_camera_3d.dart | 16 +- .../flame_3d/example/lib/example_game_3d.dart | 8 +- packages/flame_3d/example/pubspec.yaml | 2 +- .../lib/src/camera/camera_component_3d.dart | 38 +- .../lib/src/components/component_3d.dart | 10 +- .../lib/src/components/light_component.dart | 22 +- .../flame_3d/lib/src/components/line_3d.dart | 18 +- .../lib/src/components/object_3d.dart | 3 +- .../flame_3d/lib/src/extensions/color.dart | 10 +- .../flame_3d/lib/src/game/flame_game_3d.dart | 6 +- .../flame_3d/lib/src/game/transform_3d.dart | 10 +- packages/flame_3d/lib/src/model/model.dart | 14 +- .../lib/src/model/model_animation.dart | 4 +- .../flame_3d/lib/src/model/model_node.dart | 46 +- .../lib/src/parser/gltf/accessor.dart | 36 +- .../lib/src/parser/gltf/animation.dart | 68 +- .../src/parser/gltf/animation_channel.dart | 8 +- .../src/parser/gltf/animation_sampler.dart | 13 +- .../lib/src/parser/gltf/animation_target.dart | 8 +- .../flame_3d/lib/src/parser/gltf/buffer.dart | 8 +- .../lib/src/parser/gltf/buffer_view.dart | 14 +- .../flame_3d/lib/src/parser/gltf/camera.dart | 30 +- .../src/parser/gltf/camera_orthographic.dart | 12 +- .../src/parser/gltf/camera_perspective.dart | 12 +- .../lib/src/parser/gltf/gltf_node.dart | 5 +- .../lib/src/parser/gltf/gltf_root.dart | 50 +- .../flame_3d/lib/src/parser/gltf/image.dart | 10 +- .../lib/src/parser/gltf/material.dart | 58 +- .../flame_3d/lib/src/parser/gltf/mesh.dart | 10 +- .../lib/src/parser/gltf/morph_target.dart | 14 +- .../flame_3d/lib/src/parser/gltf/node.dart | 28 +- .../src/parser/gltf/normal_texture_info.dart | 10 +- .../parser/gltf/occlusion_texture_info.dart | 10 +- .../parser/gltf/pbr_metallic_roughness.dart | 34 +- .../lib/src/parser/gltf/primitive.dart | 36 +- .../flame_3d/lib/src/parser/gltf/sampler.dart | 14 +- .../flame_3d/lib/src/parser/gltf/scene.dart | 6 +- .../flame_3d/lib/src/parser/gltf/skin.dart | 10 +- .../lib/src/parser/gltf/sparse_accessor.dart | 30 +- .../parser/gltf/sparse_accessor_indices.dart | 10 +- .../parser/gltf/sparse_accessor_values.dart | 8 +- .../flame_3d/lib/src/parser/gltf/texture.dart | 18 +- .../lib/src/parser/gltf/texture_info.dart | 8 +- .../lib/src/parser/obj/surface_tool.dart | 15 +- .../flame_3d/lib/src/parser/obj_parser.dart | 5 +- .../lib/src/resources/material/material.dart | 4 +- .../resources/material/spatial_material.dart | 64 +- .../lib/src/resources/mesh/surface.dart | 6 +- .../lib/src/resources/mesh/vertex.dart | 40 +- .../lib/src/resources/shader/shader.dart | 20 +- .../src/resources/shader/uniform_array.dart | 10 +- .../src/resources/shader/uniform_slot.dart | 6 +- .../src/resources/shader/uniform_value.dart | 5 +- .../src/resources/texture/color_texture.dart | 30 +- packages/flame_3d/pubspec.yaml | 2 +- packages/flame_audio/example/pubspec.yaml | 2 +- packages/flame_audio/lib/bgm.dart | 4 +- packages/flame_audio/pubspec.yaml | 2 +- .../lib/src/composites/selector.dart | 2 +- .../lib/src/composites/sequence.dart | 2 +- .../lib/src/decorators/limiter.dart | 10 +- .../behavior_tree/pubspec.yaml | 2 +- .../flame_behavior_tree/example/lib/main.dart | 6 +- .../flame_behavior_tree/example/pubspec.yaml | 2 +- packages/flame_behavior_tree/pubspec.yaml | 2 +- .../test/has_behavior_tree_test.dart | 10 +- .../lib/src/game/components/enemy.dart | 2 +- .../lib/src/game/components/explosion.dart | 10 +- .../lib/src/game/components/player.dart | 2 +- .../src/game_stats/bloc/game_stats_state.dart | 10 +- packages/flame_bloc/example/pubspec.yaml | 2 +- .../lib/src/flame_bloc_listener.dart | 6 +- .../lib/src/flame_bloc_provider.dart | 8 +- .../lib/src/flame_multi_bloc_provider.dart | 6 +- packages/flame_bloc/pubspec.yaml | 2 +- .../test/src/flame_bloc_listenable_test.dart | 141 ++-- .../test/src/flame_bloc_provider_test.dart | 34 +- .../test/src/flame_bloc_reader_test.dart | 4 +- .../src/flame_multi_bloc_provider_test.dart | 18 +- packages/flame_console/example/lib/main.dart | 13 +- packages/flame_console/example/pubspec.yaml | 2 +- packages/flame_console/pubspec.yaml | 2 +- ...osition_component_attributes_provider.dart | 12 +- packages/flame_devtools/lib/repository.dart | 62 +- .../lib/widgets/component_tree_model.dart | 10 +- packages/flame_devtools/pubspec.yaml | 2 +- .../flame_fire_atlas/example/lib/main.dart | 14 +- .../flame_fire_atlas/example/pubspec.yaml | 2 +- packages/flame_fire_atlas/pubspec.yaml | 2 +- packages/flame_forge2d/example/lib/main.dart | 26 +- packages/flame_forge2d/example/pubspec.yaml | 2 +- .../flame_forge2d/lib/contact_callbacks.dart | 4 +- packages/flame_forge2d/lib/forge2d_game.dart | 16 +- packages/flame_forge2d/lib/forge2d_world.dart | 2 +- packages/flame_forge2d/pubspec.yaml | 2 +- .../flame_forge2d/test/forge2d_game_test.dart | 147 ++-- .../example/lib/brains/worker_overmind.dart | 30 +- .../example/lib/colonists_game.dart | 12 +- .../example/lib/game_map/game_map.dart | 9 +- .../example/lib/objects/colonists_object.dart | 12 +- .../example/lib/units/actions/movable.dart | 9 +- packages/flame_isolate/example/pubspec.yaml | 2 +- packages/flame_isolate/pubspec.yaml | 2 +- .../jenny/lib/src/command_storage.dart | 15 +- .../jenny/lib/src/dialogue_runner.dart | 8 +- .../jenny/lib/src/function_storage.dart | 20 +- .../jenny/lib/src/parse/parse.dart | 7 +- .../jenny/lib/src/parse/token.dart | 10 +- .../jenny/lib/src/parse/tokenize.dart | 30 +- .../lib/src/structure/dialogue_line.dart | 8 +- .../expressions/functions/_common.dart | 11 +- .../structure/expressions/functions/ceil.dart | 3 +- .../structure/expressions/functions/dec.dart | 3 +- .../expressions/functions/decimal.dart | 3 +- .../expressions/functions/floor.dart | 3 +- .../structure/expressions/functions/inc.dart | 3 +- .../structure/expressions/functions/int.dart | 3 +- .../expressions/functions/round.dart | 3 +- .../expressions/operators/_common.dart | 13 +- .../lib/src/structure/markup_attribute.dart | 12 +- .../jenny/lib/src/structure/node.dart | 6 +- .../jenny/lib/src/variable_storage.dart | 6 +- .../jenny/lib/src/yarn_project.dart | 12 +- packages/flame_jenny/jenny/pubspec.yaml | 2 +- .../jenny/test/dialogue_runner_test.dart | 46 +- .../jenny/test/dialogue_view_test.dart | 10 +- .../jenny/test/function_storage_test.dart | 13 +- .../jenny/test/parse/parse_test.dart | 471 +++++++------ .../jenny/test/parse/tokenize_test.dart | 626 +++++++++++------- .../commands/character_command_test.dart | 30 +- .../commands/declare_command_test.dart | 26 +- .../structure/commands/if_command_test.dart | 21 +- .../structure/commands/jump_command_test.dart | 16 +- .../commands/user_defined_command_test.dart | 24 +- .../commands/visit_command_test.dart | 16 +- .../functions/round_places_test.dart | 15 +- .../functions/visit_count_test.dart | 15 +- .../expressions/functions/visited_test.dart | 15 +- .../flame_jenny/jenny/test/test_scenario.dart | 8 +- packages/flame_jenny/jenny/test/utils.dart | 7 +- packages/flame_jenny/pubspec.yaml | 2 +- .../flame_kenney_xml/example/pubspec.yaml | 2 +- packages/flame_kenney_xml/pubspec.yaml | 2 +- packages/flame_lint/pubspec.yaml | 2 +- packages/flame_lottie/example/pubspec.yaml | 2 +- .../flame_lottie/lib/src/lottie_renderer.dart | 23 +- packages/flame_lottie/pubspec.yaml | 2 +- .../flame_lottie/test/flame_lottie_test.dart | 5 +- packages/flame_markdown/example/pubspec.yaml | 2 +- .../lib/custom_attribute_syntax.dart | 8 +- .../flame_markdown/lib/flame_markdown.dart | 29 +- packages/flame_markdown/pubspec.yaml | 2 +- .../test/flame_markdown_test.dart | 427 ++++++------ .../flame_network_assets/example/pubspec.yaml | 2 +- .../lib/src/flame_network_assets.dart | 31 +- .../lib/src/flame_network_images.dart | 12 +- packages/flame_network_assets/pubspec.yaml | 2 +- .../test/flame_network_image_test.dart | 5 +- .../src/effects/noise_effect_controller.dart | 4 +- packages/flame_noise/pubspec.yaml | 2 +- packages/flame_oxygen/example/lib/main.dart | 10 +- .../example/lib/system/kawabunga_system.dart | 11 +- .../example/lib/system/move_system.dart | 10 +- packages/flame_oxygen/example/pubspec.yaml | 2 +- .../flame_oxygen/lib/src/flame_world.dart | 4 +- packages/flame_oxygen/pubspec.yaml | 2 +- packages/flame_rive/example/lib/main.dart | 5 +- packages/flame_rive/example/pubspec.yaml | 2 +- .../flame_rive/lib/src/rive_component.dart | 38 +- packages/flame_rive/pubspec.yaml | 2 +- packages/flame_rive/test/flame_rive_test.dart | 5 +- packages/flame_riverpod/example/lib/main.dart | 7 +- packages/flame_riverpod/example/pubspec.yaml | 2 +- .../example/test/widget_test.dart | 24 +- packages/flame_riverpod/lib/src/widget.dart | 27 +- packages/flame_riverpod/pubspec.yaml | 2 +- packages/flame_riverpod/test/widget_test.dart | 141 ++-- packages/flame_spine/example/pubspec.yaml | 2 +- .../flame_spine/lib/src/spine_component.dart | 4 +- packages/flame_spine/pubspec.yaml | 2 +- .../flame_splash_screen/example/pubspec.yaml | 2 +- .../lib/src/controller.dart | 12 +- .../flame_splash_screen/lib/src/splash.dart | 3 +- packages/flame_splash_screen/pubspec.yaml | 2 +- .../flame_sprite_fusion/example/pubspec.yaml | 2 +- .../src/sprite_fusion_tilemap_component.dart | 15 +- packages/flame_sprite_fusion/pubspec.yaml | 2 +- .../test/test_asset_bundle.dart | 6 +- .../lib/src/core/component_tree.dart | 14 +- .../lib/src/core/game_controller.dart | 4 +- .../lib/src/widgets/left_panel.dart | 5 +- .../src/widgets/panels/hierarchy_view.dart | 2 +- packages/flame_studio/pubspec.yaml | 2 +- packages/flame_svg/example/pubspec.yaml | 2 +- packages/flame_svg/lib/svg.dart | 11 +- packages/flame_svg/pubspec.yaml | 2 +- packages/flame_test/example/pubspec.yaml | 2 +- .../lib/src/debug_text_renderer.dart | 8 +- packages/flame_test/lib/src/flame_test.dart | 37 +- packages/flame_test/lib/src/mock_image.dart | 42 +- packages/flame_test/lib/src/random_test.dart | 9 +- packages/flame_test/lib/src/test_golden.dart | 12 +- packages/flame_test/pubspec.yaml | 2 +- .../test/close_to_matrix4_test.dart | 20 +- .../test/debug_text_formatter_test.dart | 9 +- packages/flame_test/test/epsilon_test.dart | 3 +- .../flame_texturepacker/example/pubspec.yaml | 2 +- .../lib/flame_texturepacker.dart | 32 +- .../lib/src/texture_packer_atlas.dart | 7 +- .../lib/src/texture_packer_sprite.dart | 38 +- packages/flame_texturepacker/pubspec.yaml | 2 +- .../test/flame_texturepacker_test.dart | 5 +- packages/flame_tiled/example/lib/main.dart | 17 +- packages/flame_tiled/example/pubspec.yaml | 2 +- .../flame_tiled/lib/src/mutable_rect.dart | 2 +- .../tile_layers/tile_layer.dart | 80 +-- .../lib/src/renderable_tile_map.dart | 8 +- packages/flame_tiled/lib/src/tile_atlas.dart | 22 +- .../flame_tiled/lib/src/tiled_component.dart | 20 +- packages/flame_tiled/pubspec.yaml | 2 +- .../flame_tiled/test/test_asset_bundle.dart | 6 +- .../flame_tiled/test/tile_atlas_test.dart | 69 +- packages/flame_tiled/test/tiled_test.dart | 77 ++- pubspec.yaml | 4 +- 604 files changed, 6458 insertions(+), 5590 deletions(-) diff --git a/.github/workflows/cicd.yml b/.github/workflows/cicd.yml index bafe79f5a..839de2a88 100644 --- a/.github/workflows/cicd.yml +++ b/.github/workflows/cicd.yml @@ -9,7 +9,7 @@ on: env: - FLUTTER_MIN_VERSION: '3.27.1' + FLUTTER_MIN_VERSION: '3.32.0' jobs: # BEGIN LINTING STAGE diff --git a/doc/flame/examples/lib/collision_detection.dart b/doc/flame/examples/lib/collision_detection.dart index 1a9c10911..278affc76 100644 --- a/doc/flame/examples/lib/collision_detection.dart +++ b/doc/flame/examples/lib/collision_detection.dart @@ -36,11 +36,11 @@ class RectangleCollidable extends PositionComponent with CollisionCallbacks { late ShapeHitbox hitbox; RectangleCollidable(Vector2 position) - : super( - position: position, - size: Vector2.all(50), - anchor: Anchor.center, - ); + : super( + position: position, + size: Vector2.all(50), + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/doc/flame/examples/lib/drag_events.dart b/doc/flame/examples/lib/drag_events.dart index bae704e06..cb4253917 100644 --- a/doc/flame/examples/lib/drag_events.dart +++ b/doc/flame/examples/lib/drag_events.dart @@ -101,11 +101,15 @@ class DragTarget extends PositionComponent with DragCallbacks { class Trail extends Component { Trail(Vector2 origin) - : _paths = [Path()..moveTo(origin.x, origin.y)], - _opacities = [1], - _lastPoint = origin.clone(), - _color = - HSLColor.fromAHSL(1, random.nextDouble() * 360, 1, 0.8).toColor(); + : _paths = [Path()..moveTo(origin.x, origin.y)], + _opacities = [1], + _lastPoint = origin.clone(), + _color = HSLColor.fromAHSL( + 1, + random.nextDouble() * 360, + 1, + 0.8, + ).toColor(); final List _paths; final List _opacities; diff --git a/doc/flame/examples/lib/ember.dart b/doc/flame/examples/lib/ember.dart index c7cc0bc1a..1bb87697f 100644 --- a/doc/flame/examples/lib/ember.dart +++ b/doc/flame/examples/lib/ember.dart @@ -8,8 +8,8 @@ class EmberPlayer extends SpriteAnimationComponent with TapCallbacks { required super.size, super.position, void Function(EmberPlayer player)? onTap, - }) : _onTap = onTap, - super(); + }) : _onTap = onTap, + super(); Vector2 velocity = Vector2(0, 0); final void Function(EmberPlayer player)? _onTap; diff --git a/doc/flame/examples/lib/flower.dart b/doc/flame/examples/lib/flower.dart index 53bcc46aa..e50d5b61f 100644 --- a/doc/flame/examples/lib/flower.dart +++ b/doc/flame/examples/lib/flower.dart @@ -14,8 +14,8 @@ class Flower extends PositionComponent void Function(Flower)? onTap, Decorator? decorator, super.position, - }) : _onTap = onTap, - super(size: Vector2.all(size), anchor: Anchor.center) { + }) : _onTap = onTap, + super(size: Vector2.all(size), anchor: Anchor.center) { this.decorator.addLast(decorator); final radius = size * 0.38; _paths.add(_makePath(radius * 1.4, 6, -0.05, 0.8)); diff --git a/doc/flame/examples/lib/glow_effect.dart b/doc/flame/examples/lib/glow_effect.dart index 7ec5fdd05..01cc4acb0 100644 --- a/doc/flame/examples/lib/glow_effect.dart +++ b/doc/flame/examples/lib/glow_effect.dart @@ -16,14 +16,14 @@ class GlowEffectExample extends FlameGame { anchor: Anchor.center, paint: paint, )..add( - GlowEffect( - 10.0, - EffectController( - duration: 2, - infinite: true, - ), + GlowEffect( + 10.0, + EffectController( + duration: 2, + infinite: true, ), ), + ), ); } } diff --git a/doc/flame/examples/lib/pointer_events.dart b/doc/flame/examples/lib/pointer_events.dart index 20a70b069..ce89f9499 100644 --- a/doc/flame/examples/lib/pointer_events.dart +++ b/doc/flame/examples/lib/pointer_events.dart @@ -23,16 +23,19 @@ class HoverTarget extends PositionComponent with HoverCallbacks { static final Random _random = Random(); HoverTarget(Vector2 position) - : super( - position: position, - size: Vector2.all(50), - anchor: Anchor.center, - ); + : super( + position: position, + size: Vector2.all(50), + anchor: Anchor.center, + ); final _paint = Paint() - ..color = HSLColor.fromAHSL(1, _random.nextDouble() * 360, 1, 0.8) - .toColor() - .withValues(alpha: 0.5); + ..color = HSLColor.fromAHSL( + 1, + _random.nextDouble() * 360, + 1, + 0.8, + ).toColor().withValues(alpha: 0.5); @override void render(Canvas canvas) { diff --git a/doc/flame/examples/lib/remove_effect.dart b/doc/flame/examples/lib/remove_effect.dart index ba6d17f37..94a74b4f4 100644 --- a/doc/flame/examples/lib/remove_effect.dart +++ b/doc/flame/examples/lib/remove_effect.dart @@ -33,8 +33,8 @@ class RemoveEffectGame extends FlameGame with TapDetector { @override void update(double dt) { - textComponent.text = - (effect.controller.progress * delayTime).toStringAsFixed(2); + textComponent.text = (effect.controller.progress * delayTime) + .toStringAsFixed(2); super.update(dt); } } diff --git a/doc/flame/examples/lib/rive_example.dart b/doc/flame/examples/lib/rive_example.dart index 7696130f7..1bbf9ac82 100644 --- a/doc/flame/examples/lib/rive_example.dart +++ b/doc/flame/examples/lib/rive_example.dart @@ -9,8 +9,9 @@ class RiveExampleGame extends FlameGame with TapDetector { @override Future onLoad() async { - final skillsArtboard = - await loadArtboard(RiveFile.asset('assets/skills.riv')); + final skillsArtboard = await loadArtboard( + RiveFile.asset('assets/skills.riv'), + ); final controller = StateMachineController.fromArtboard( skillsArtboard, diff --git a/doc/flame/examples/lib/router.dart b/doc/flame/examples/lib/router.dart index e0f4fb1c0..c72141101 100644 --- a/doc/flame/examples/lib/router.dart +++ b/doc/flame/examples/lib/router.dart @@ -86,12 +86,12 @@ class RoundedButton extends PositionComponent with TapCallbacks { super.position, super.anchor = Anchor.center, }) : _textDrawable = TextPaint( - style: const TextStyle( - fontSize: 20, - color: Color(0xFF000000), - fontWeight: FontWeight.w800, - ), - ).toTextPainter(text) { + style: const TextStyle( + fontSize: 20, + color: Color(0xFF000000), + fontWeight: FontWeight.w800, + ), + ).toTextPainter(text) { size = Vector2(150, 40); _textOffset = Offset( (size.x - _textDrawable.width) / 2, @@ -179,15 +179,15 @@ abstract class SimpleButton extends PositionComponent with TapCallbacks { class BackButton extends SimpleButton with HasGameReference { BackButton() - : super( - Path() - ..moveTo(22, 8) - ..lineTo(10, 20) - ..lineTo(22, 32) - ..moveTo(12, 20) - ..lineTo(34, 20), - position: Vector2.all(10), - ); + : super( + Path() + ..moveTo(22, 8) + ..lineTo(10, 20) + ..lineTo(22, 32) + ..moveTo(12, 20) + ..lineTo(34, 20), + position: Vector2.all(10), + ); @override void action() => game.router.pop(); @@ -195,14 +195,14 @@ class BackButton extends SimpleButton with HasGameReference { class PauseButton extends SimpleButton with HasGameReference { PauseButton() - : super( - Path() - ..moveTo(14, 10) - ..lineTo(14, 30) - ..moveTo(26, 10) - ..lineTo(26, 30), - position: Vector2(60, 10), - ); + : super( + Path() + ..moveTo(14, 10) + ..lineTo(14, 30) + ..moveTo(26, 10) + ..lineTo(26, 30), + position: Vector2(60, 10), + ); bool isPaused = false; @@ -345,10 +345,10 @@ class Orbit extends PositionComponent { required this.planet, required this.revolutionPeriod, double initialAngle = 0, - }) : _paint = Paint() - ..style = PaintingStyle.stroke - ..color = const Color(0x888888aa), - _angle = initialAngle { + }) : _paint = Paint() + ..style = PaintingStyle.stroke + ..color = const Color(0x888888aa), + _angle = initialAngle { add(planet); } diff --git a/doc/flame/examples/lib/tap_events.dart b/doc/flame/examples/lib/tap_events.dart index c1a1b6f2a..bcc540e07 100644 --- a/doc/flame/examples/lib/tap_events.dart +++ b/doc/flame/examples/lib/tap_events.dart @@ -63,8 +63,12 @@ class TapTarget extends PositionComponent with TapCallbacks { class ExpandingCircle extends Component { ExpandingCircle(this._center) - : _baseColor = - HSLColor.fromAHSL(1, random.nextDouble() * 360, 1, 0.8).toColor(); + : _baseColor = HSLColor.fromAHSL( + 1, + random.nextDouble() * 360, + 1, + 0.8, + ).toColor(); final Color _baseColor; final Vector2 _center; diff --git a/doc/flame/examples/lib/value_route.dart b/doc/flame/examples/lib/value_route.dart index 405828a50..5c3f98a1e 100644 --- a/doc/flame/examples/lib/value_route.dart +++ b/doc/flame/examples/lib/value_route.dart @@ -83,15 +83,15 @@ class RateRoute extends ValueRoute class DialogBackground extends RectangleComponent with TapCallbacks { DialogBackground({super.position, super.size, super.children}) - : super( - anchor: Anchor.center, - paint: Paint()..color = const Color(0xee858585), - ); + : super( + anchor: Anchor.center, + paint: Paint()..color = const Color(0xee858585), + ); } class Star extends PositionComponent with TapCallbacks { Star({required this.value, required this.radius, super.position}) - : super(size: Vector2.all(2 * radius), anchor: Anchor.center); + : super(size: Vector2.all(2 * radius), anchor: Anchor.center); final int value; final double radius; diff --git a/doc/flame/examples/pubspec.yaml b/doc/flame/examples/pubspec.yaml index aba7ff9a2..7687e7091 100644 --- a/doc/flame/examples/pubspec.yaml +++ b/doc/flame/examples/pubspec.yaml @@ -5,7 +5,7 @@ version: 1.0.0 publish_to: none environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/doc/tutorials/klondike/app/lib/main.dart b/doc/tutorials/klondike/app/lib/main.dart index fd0f46712..059e39d5e 100644 --- a/doc/tutorials/klondike/app/lib/main.dart +++ b/doc/tutorials/klondike/app/lib/main.dart @@ -17,10 +17,10 @@ void main() { 'step4' => step4.main(), 'step5' => step5.main(), _ => runApp( - Directionality( - textDirection: TextDirection.ltr, - child: Text('Error=> unknown page name "$page"'), - ), + Directionality( + textDirection: TextDirection.ltr, + child: Text('Error=> unknown page name "$page"'), ), + ), }; } diff --git a/doc/tutorials/klondike/app/lib/step2/klondike_game.dart b/doc/tutorials/klondike/app/lib/step2/klondike_game.dart index 49a4c663b..6d5985f9c 100644 --- a/doc/tutorials/klondike/app/lib/step2/klondike_game.dart +++ b/doc/tutorials/klondike/app/lib/step2/klondike_game.dart @@ -28,8 +28,10 @@ class KlondikeGame extends FlameGame { 4, (i) => Foundation() ..size = cardSize - ..position = - Vector2((i + 3) * (cardWidth + cardGap) + cardGap, cardGap), + ..position = Vector2( + (i + 3) * (cardWidth + cardGap) + cardGap, + cardGap, + ), ); final piles = List.generate( 7, @@ -46,8 +48,10 @@ class KlondikeGame extends FlameGame { world.addAll(foundations); world.addAll(piles); - camera.viewfinder.visibleGameSize = - Vector2(cardWidth * 7 + cardGap * 8, 4 * cardHeight + 3 * cardGap); + camera.viewfinder.visibleGameSize = Vector2( + cardWidth * 7 + cardGap * 8, + 4 * cardHeight + 3 * cardGap, + ); camera.viewfinder.position = Vector2(cardWidth * 3.5 + cardGap * 4, 0); camera.viewfinder.anchor = Anchor.topCenter; } diff --git a/doc/tutorials/klondike/app/lib/step3/components/card.dart b/doc/tutorials/klondike/app/lib/step3/components/card.dart index 73fa99c05..fec7dd863 100644 --- a/doc/tutorials/klondike/app/lib/step3/components/card.dart +++ b/doc/tutorials/klondike/app/lib/step3/components/card.dart @@ -8,10 +8,10 @@ import '../suit.dart'; class Card extends PositionComponent { Card(int intRank, int intSuit) - : rank = Rank.fromInt(intRank), - suit = Suit.fromInt(intSuit), - _faceUp = false, - super(size: KlondikeGame.cardSize); + : rank = Rank.fromInt(intRank), + suit = Suit.fromInt(intSuit), + _faceUp = false, + super(size: KlondikeGame.cardSize); final Rank rank; final Suit suit; diff --git a/doc/tutorials/klondike/app/lib/step3/klondike_game.dart b/doc/tutorials/klondike/app/lib/step3/klondike_game.dart index 6ed71ab44..cf076631b 100644 --- a/doc/tutorials/klondike/app/lib/step3/klondike_game.dart +++ b/doc/tutorials/klondike/app/lib/step3/klondike_game.dart @@ -31,8 +31,10 @@ class KlondikeGame extends FlameGame { 4, (i) => Foundation() ..size = cardSize - ..position = - Vector2((i + 3) * (cardWidth + cardGap) + cardGap, cardGap), + ..position = Vector2( + (i + 3) * (cardWidth + cardGap) + cardGap, + cardGap, + ), ); final piles = List.generate( 7, @@ -49,8 +51,10 @@ class KlondikeGame extends FlameGame { world.addAll(foundations); world.addAll(piles); - camera.viewfinder.visibleGameSize = - Vector2(cardWidth * 7 + cardGap * 8, 4 * cardHeight + 3 * cardGap); + camera.viewfinder.visibleGameSize = Vector2( + cardWidth * 7 + cardGap * 8, + 4 * cardHeight + 3 * cardGap, + ); camera.viewfinder.position = Vector2(cardWidth * 3.5 + cardGap * 4, 0); camera.viewfinder.anchor = Anchor.topCenter; diff --git a/doc/tutorials/klondike/app/lib/step3/rank.dart b/doc/tutorials/klondike/app/lib/step3/rank.dart index 7a00f0460..0e23c4015 100644 --- a/doc/tutorials/klondike/app/lib/step3/rank.dart +++ b/doc/tutorials/klondike/app/lib/step3/rank.dart @@ -21,8 +21,8 @@ class Rank { double y2, double w, double h, - ) : redSprite = klondikeSprite(x1, y1, w, h), - blackSprite = klondikeSprite(x2, y2, w, h); + ) : redSprite = klondikeSprite(x1, y1, w, h), + blackSprite = klondikeSprite(x2, y2, w, h); final int value; final String label; diff --git a/doc/tutorials/klondike/app/lib/step3/suit.dart b/doc/tutorials/klondike/app/lib/step3/suit.dart index ec37d58c4..d516180c9 100644 --- a/doc/tutorials/klondike/app/lib/step3/suit.dart +++ b/doc/tutorials/klondike/app/lib/step3/suit.dart @@ -13,7 +13,7 @@ class Suit { } Suit._(this.value, this.label, double x, double y, double w, double h) - : sprite = klondikeSprite(x, y, w, h); + : sprite = klondikeSprite(x, y, w, h); final int value; final String label; diff --git a/doc/tutorials/klondike/app/lib/step4/components/card.dart b/doc/tutorials/klondike/app/lib/step4/components/card.dart index ef338b437..c5141d46b 100644 --- a/doc/tutorials/klondike/app/lib/step4/components/card.dart +++ b/doc/tutorials/klondike/app/lib/step4/components/card.dart @@ -11,9 +11,9 @@ import 'tableau_pile.dart'; class Card extends PositionComponent with DragCallbacks { Card(int intRank, int intSuit) - : rank = Rank.fromInt(intRank), - suit = Suit.fromInt(intSuit), - super(size: KlondikeGame.cardSize); + : rank = Rank.fromInt(intRank), + suit = Suit.fromInt(intSuit), + super(size: KlondikeGame.cardSize); final Rank rank; final Suit suit; diff --git a/doc/tutorials/klondike/app/lib/step4/components/foundation_pile.dart b/doc/tutorials/klondike/app/lib/step4/components/foundation_pile.dart index 959d10d2a..ce2fc3a14 100644 --- a/doc/tutorials/klondike/app/lib/step4/components/foundation_pile.dart +++ b/doc/tutorials/klondike/app/lib/step4/components/foundation_pile.dart @@ -9,8 +9,8 @@ import 'card.dart'; class FoundationPile extends PositionComponent implements Pile { FoundationPile(int intSuit, {super.position}) - : suit = Suit.fromInt(intSuit), - super(size: KlondikeGame.cardSize); + : suit = Suit.fromInt(intSuit), + super(size: KlondikeGame.cardSize); final Suit suit; final List _cards = []; diff --git a/doc/tutorials/klondike/app/lib/step4/klondike_game.dart b/doc/tutorials/klondike/app/lib/step4/klondike_game.dart index ae76f42dd..bc02b9a3b 100644 --- a/doc/tutorials/klondike/app/lib/step4/klondike_game.dart +++ b/doc/tutorials/klondike/app/lib/step4/klondike_game.dart @@ -26,8 +26,9 @@ class KlondikeGame extends FlameGame { await Flame.images.load('klondike-sprites.png'); final stock = StockPile(position: Vector2(cardGap, cardGap)); - final waste = - WastePile(position: Vector2(cardWidth + 2 * cardGap, cardGap)); + final waste = WastePile( + position: Vector2(cardWidth + 2 * cardGap, cardGap), + ); final foundations = List.generate( 4, (i) => FoundationPile( @@ -50,8 +51,10 @@ class KlondikeGame extends FlameGame { world.addAll(foundations); world.addAll(piles); - camera.viewfinder.visibleGameSize = - Vector2(cardWidth * 7 + cardGap * 8, 4 * cardHeight + 3 * cardGap); + camera.viewfinder.visibleGameSize = Vector2( + cardWidth * 7 + cardGap * 8, + 4 * cardHeight + 3 * cardGap, + ); camera.viewfinder.position = Vector2(cardWidth * 3.5 + cardGap * 4, 0); camera.viewfinder.anchor = Anchor.topCenter; diff --git a/doc/tutorials/klondike/app/lib/step4/rank.dart b/doc/tutorials/klondike/app/lib/step4/rank.dart index 7a00f0460..0e23c4015 100644 --- a/doc/tutorials/klondike/app/lib/step4/rank.dart +++ b/doc/tutorials/klondike/app/lib/step4/rank.dart @@ -21,8 +21,8 @@ class Rank { double y2, double w, double h, - ) : redSprite = klondikeSprite(x1, y1, w, h), - blackSprite = klondikeSprite(x2, y2, w, h); + ) : redSprite = klondikeSprite(x1, y1, w, h), + blackSprite = klondikeSprite(x2, y2, w, h); final int value; final String label; diff --git a/doc/tutorials/klondike/app/lib/step4/suit.dart b/doc/tutorials/klondike/app/lib/step4/suit.dart index ec37d58c4..d516180c9 100644 --- a/doc/tutorials/klondike/app/lib/step4/suit.dart +++ b/doc/tutorials/klondike/app/lib/step4/suit.dart @@ -13,7 +13,7 @@ class Suit { } Suit._(this.value, this.label, double x, double y, double w, double h) - : sprite = klondikeSprite(x, y, w, h); + : sprite = klondikeSprite(x, y, w, h); final int value; final String label; diff --git a/doc/tutorials/klondike/app/lib/step5/components/card.dart b/doc/tutorials/klondike/app/lib/step5/components/card.dart index 4c2f75570..f109e0b4f 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/card.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/card.dart @@ -18,11 +18,11 @@ import 'tableau_pile.dart'; class Card extends PositionComponent with DragCallbacks, TapCallbacks, HasWorldReference { Card(int intRank, int intSuit, {this.isBaseCard = false}) - : rank = Rank.fromInt(intRank), - suit = Suit.fromInt(intSuit), - super( - size: KlondikeGame.cardSize, - ); + : rank = Rank.fromInt(intRank), + suit = Suit.fromInt(intSuit), + super( + size: KlondikeGame.cardSize, + ); final Rank rank; final Suit suit; diff --git a/doc/tutorials/klondike/app/lib/step5/components/flat_button.dart b/doc/tutorials/klondike/app/lib/step5/components/flat_button.dart index 01ce788a2..10febb605 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/flat_button.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/flat_button.dart @@ -10,24 +10,24 @@ class FlatButton extends ButtonComponent { super.onReleased, super.position, }) : super( - button: ButtonBackground(const Color(0xffece8a3)), - buttonDown: ButtonBackground(Colors.red), - children: [ - TextComponent( - text: text, - textRenderer: TextPaint( - style: TextStyle( - fontSize: 0.5 * size!.y, - fontWeight: FontWeight.bold, - color: const Color(0xffdbaf58), - ), - ), - position: size / 2.0, - anchor: Anchor.center, - ), - ], - anchor: Anchor.center, - ); + button: ButtonBackground(const Color(0xffece8a3)), + buttonDown: ButtonBackground(Colors.red), + children: [ + TextComponent( + text: text, + textRenderer: TextPaint( + style: TextStyle( + fontSize: 0.5 * size!.y, + fontWeight: FontWeight.bold, + color: const Color(0xffdbaf58), + ), + ), + position: size / 2.0, + anchor: Anchor.center, + ), + ], + anchor: Anchor.center, + ); } class ButtonBackground extends PositionComponent with HasAncestor { diff --git a/doc/tutorials/klondike/app/lib/step5/components/foundation_pile.dart b/doc/tutorials/klondike/app/lib/step5/components/foundation_pile.dart index 9e9c1f393..4ec0ff2ee 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/foundation_pile.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/foundation_pile.dart @@ -9,8 +9,8 @@ import 'card.dart'; class FoundationPile extends PositionComponent implements Pile { FoundationPile(int intSuit, this.checkWin, {super.position}) - : suit = Suit.fromInt(intSuit), - super(size: KlondikeGame.cardSize); + : suit = Suit.fromInt(intSuit), + super(size: KlondikeGame.cardSize); final VoidCallback checkWin; diff --git a/doc/tutorials/klondike/app/lib/step5/components/tableau_pile.dart b/doc/tutorials/klondike/app/lib/step5/components/tableau_pile.dart index 37beb8f7e..bcde19897 100644 --- a/doc/tutorials/klondike/app/lib/step5/components/tableau_pile.dart +++ b/doc/tutorials/klondike/app/lib/step5/components/tableau_pile.dart @@ -111,7 +111,8 @@ class TableauPile extends PositionComponent implements Pile { } void calculateHitArea() { - height = KlondikeGame.cardHeight * 1.5 + + height = + KlondikeGame.cardHeight * 1.5 + (_cards.length < 2 ? 0.0 : _cards.last.y - _cards.first.y); } diff --git a/doc/tutorials/klondike/app/lib/step5/klondike_world.dart b/doc/tutorials/klondike/app/lib/step5/klondike_world.dart index 1247cd0e9..0bdf7f8cc 100644 --- a/doc/tutorials/klondike/app/lib/step5/klondike_world.dart +++ b/doc/tutorials/klondike/app/lib/step5/klondike_world.dart @@ -74,8 +74,10 @@ class KlondikeWorld extends World with HasGameReference { addAll(cards); add(baseCard); - playAreaSize = - Vector2(7 * cardSpaceWidth + cardGap, 4 * cardSpaceHeight + topGap); + playAreaSize = Vector2( + 7 * cardSpaceWidth + cardGap, + 4 * cardSpaceHeight + topGap, + ); final gameMidX = playAreaSize.x / 2; addButton('New deal', gameMidX, Action.newDeal); diff --git a/doc/tutorials/klondike/app/lib/step5/rank.dart b/doc/tutorials/klondike/app/lib/step5/rank.dart index 7a00f0460..0e23c4015 100644 --- a/doc/tutorials/klondike/app/lib/step5/rank.dart +++ b/doc/tutorials/klondike/app/lib/step5/rank.dart @@ -21,8 +21,8 @@ class Rank { double y2, double w, double h, - ) : redSprite = klondikeSprite(x1, y1, w, h), - blackSprite = klondikeSprite(x2, y2, w, h); + ) : redSprite = klondikeSprite(x1, y1, w, h), + blackSprite = klondikeSprite(x2, y2, w, h); final int value; final String label; diff --git a/doc/tutorials/klondike/app/lib/step5/suit.dart b/doc/tutorials/klondike/app/lib/step5/suit.dart index ec37d58c4..d516180c9 100644 --- a/doc/tutorials/klondike/app/lib/step5/suit.dart +++ b/doc/tutorials/klondike/app/lib/step5/suit.dart @@ -13,7 +13,7 @@ class Suit { } Suit._(this.value, this.label, double x, double y, double w, double h) - : sprite = klondikeSprite(x, y, w, h); + : sprite = klondikeSprite(x, y, w, h); final int value; final String label; diff --git a/doc/tutorials/klondike/app/pubspec.yaml b/doc/tutorials/klondike/app/pubspec.yaml index a0d5a751e..c6a5615b3 100644 --- a/doc/tutorials/klondike/app/pubspec.yaml +++ b/doc/tutorials/klondike/app/pubspec.yaml @@ -5,7 +5,7 @@ version: 1.0.0 publish_to: none environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/doc/tutorials/platformer/app/lib/actors/ember.dart b/doc/tutorials/platformer/app/lib/actors/ember.dart index fc3dac5b1..78dde97e3 100644 --- a/doc/tutorials/platformer/app/lib/actors/ember.dart +++ b/doc/tutorials/platformer/app/lib/actors/ember.dart @@ -46,11 +46,13 @@ class EmberPlayer extends SpriteAnimationComponent @override bool onKeyEvent(KeyEvent event, Set keysPressed) { horizontalDirection = 0; - horizontalDirection += (keysPressed.contains(LogicalKeyboardKey.keyA) || + horizontalDirection += + (keysPressed.contains(LogicalKeyboardKey.keyA) || keysPressed.contains(LogicalKeyboardKey.arrowLeft)) ? -1 : 0; - horizontalDirection += (keysPressed.contains(LogicalKeyboardKey.keyD) || + horizontalDirection += + (keysPressed.contains(LogicalKeyboardKey.keyD) || keysPressed.contains(LogicalKeyboardKey.arrowRight)) ? 1 : 0; @@ -114,7 +116,8 @@ class EmberPlayer extends SpriteAnimationComponent if (other is GroundBlock || other is PlatformBlock) { if (intersectionPoints.length == 2) { // Calculate the collision normal and separation distance. - final mid = (intersectionPoints.elementAt(0) + + final mid = + (intersectionPoints.elementAt(0) + intersectionPoints.elementAt(1)) / 2; @@ -154,12 +157,13 @@ class EmberPlayer extends SpriteAnimationComponent } add( OpacityEffect.fadeOut( - EffectController( - alternate: true, - duration: 0.1, - repeatCount: 5, - ), - )..onComplete = () { + EffectController( + alternate: true, + duration: 0.1, + repeatCount: 5, + ), + ) + ..onComplete = () { hitByEnemy = false; }, ); diff --git a/doc/tutorials/platformer/app/lib/ember_quest.dart b/doc/tutorials/platformer/app/lib/ember_quest.dart index d591ff054..ccd9b0cc5 100644 --- a/doc/tutorials/platformer/app/lib/ember_quest.dart +++ b/doc/tutorials/platformer/app/lib/ember_quest.dart @@ -58,21 +58,21 @@ class EmberQuestGame extends FlameGame for (final block in segments[segmentIndex]) { final component = switch (block.blockType) { const (GroundBlock) => GroundBlock( - gridPosition: block.gridPosition, - xOffset: xPositionOffset, - ), + gridPosition: block.gridPosition, + xOffset: xPositionOffset, + ), const (PlatformBlock) => PlatformBlock( - gridPosition: block.gridPosition, - xOffset: xPositionOffset, - ), + gridPosition: block.gridPosition, + xOffset: xPositionOffset, + ), const (Star) => Star( - gridPosition: block.gridPosition, - xOffset: xPositionOffset, - ), + gridPosition: block.gridPosition, + xOffset: xPositionOffset, + ), const (WaterEnemy) => WaterEnemy( - gridPosition: block.gridPosition, - xOffset: xPositionOffset, - ), + gridPosition: block.gridPosition, + xOffset: xPositionOffset, + ), _ => throw UnimplementedError(), }; world.add(component); diff --git a/doc/tutorials/platformer/app/pubspec.yaml b/doc/tutorials/platformer/app/pubspec.yaml index dd1b4c011..c6dd7a8b5 100644 --- a/doc/tutorials/platformer/app/pubspec.yaml +++ b/doc/tutorials/platformer/app/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/doc/tutorials/space_shooter/app/lib/main.dart b/doc/tutorials/space_shooter/app/lib/main.dart index b151a8e6b..7b6ce7927 100644 --- a/doc/tutorials/space_shooter/app/lib/main.dart +++ b/doc/tutorials/space_shooter/app/lib/main.dart @@ -21,11 +21,11 @@ void main() { 'step5' => step5.main(), 'step6' => step6.main(), _ => runApp( - Directionality( - textDirection: TextDirection.ltr, - child: Text('''Error: unknown page. Pass "step{1,6}" as a GET param; + Directionality( + textDirection: TextDirection.ltr, + child: Text('''Error: unknown page. Pass "step{1,6}" as a GET param; e.g: ${web.window.location}?step1'''), - ), ), + ), }; } diff --git a/doc/tutorials/space_shooter/app/lib/step2/main.dart b/doc/tutorials/space_shooter/app/lib/step2/main.dart index 73fe46070..36e0e45c3 100644 --- a/doc/tutorials/space_shooter/app/lib/step2/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step2/main.dart @@ -25,10 +25,10 @@ class SpaceShooterGame extends FlameGame with PanDetector { class Player extends SpriteComponent with HasGameReference { Player() - : super( - size: Vector2(100, 150), - anchor: Anchor.center, - ); + : super( + size: Vector2(100, 150), + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/doc/tutorials/space_shooter/app/lib/step3/main.dart b/doc/tutorials/space_shooter/app/lib/step3/main.dart index a785f35d5..68bafad10 100644 --- a/doc/tutorials/space_shooter/app/lib/step3/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step3/main.dart @@ -39,10 +39,10 @@ class SpaceShooterGame extends FlameGame with PanDetector { class Player extends SpriteAnimationComponent with HasGameReference { Player() - : super( - size: Vector2(100, 150), - anchor: Anchor.center, - ); + : super( + size: Vector2(100, 150), + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/doc/tutorials/space_shooter/app/lib/step4/main.dart b/doc/tutorials/space_shooter/app/lib/step4/main.dart index f84ab72d8..a67071908 100644 --- a/doc/tutorials/space_shooter/app/lib/step4/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step4/main.dart @@ -49,10 +49,10 @@ class SpaceShooterGame extends FlameGame with PanDetector { class Player extends SpriteAnimationComponent with HasGameReference { Player() - : super( - size: Vector2(100, 150), - anchor: Anchor.center, - ); + : super( + size: Vector2(100, 150), + anchor: Anchor.center, + ); late final SpawnComponent _bulletSpawner; @@ -76,7 +76,8 @@ class Player extends SpriteAnimationComponent selfPositioning: true, factory: (index) { return Bullet( - position: position + + position: + position + Vector2( 0, -height / 2, @@ -107,9 +108,9 @@ class Bullet extends SpriteAnimationComponent Bullet({ super.position, }) : super( - size: Vector2(25, 50), - anchor: Anchor.center, - ); + size: Vector2(25, 50), + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/doc/tutorials/space_shooter/app/lib/step5/main.dart b/doc/tutorials/space_shooter/app/lib/step5/main.dart index e33f7d0f5..0a4088b5e 100644 --- a/doc/tutorials/space_shooter/app/lib/step5/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step5/main.dart @@ -60,10 +60,10 @@ class SpaceShooterGame extends FlameGame with PanDetector { class Player extends SpriteAnimationComponent with HasGameReference { Player() - : super( - size: Vector2(100, 150), - anchor: Anchor.center, - ); + : super( + size: Vector2(100, 150), + anchor: Anchor.center, + ); late final SpawnComponent _bulletSpawner; @@ -87,7 +87,8 @@ class Player extends SpriteAnimationComponent selfPositioning: true, factory: (index) { return Bullet( - position: position + + position: + position + Vector2( 0, -height / 2, @@ -118,9 +119,9 @@ class Bullet extends SpriteAnimationComponent Bullet({ super.position, }) : super( - size: Vector2(25, 50), - anchor: Anchor.center, - ); + size: Vector2(25, 50), + anchor: Anchor.center, + ); @override Future onLoad() async { @@ -153,9 +154,9 @@ class Enemy extends SpriteAnimationComponent Enemy({ super.position, }) : super( - size: Vector2.all(enemySize), - anchor: Anchor.center, - ); + size: Vector2.all(enemySize), + anchor: Anchor.center, + ); static const enemySize = 50.0; diff --git a/doc/tutorials/space_shooter/app/lib/step6/main.dart b/doc/tutorials/space_shooter/app/lib/step6/main.dart index 128689658..0b53b52ec 100644 --- a/doc/tutorials/space_shooter/app/lib/step6/main.dart +++ b/doc/tutorials/space_shooter/app/lib/step6/main.dart @@ -62,10 +62,10 @@ class SpaceShooterGame extends FlameGame class Player extends SpriteAnimationComponent with HasGameReference { Player() - : super( - size: Vector2(100, 150), - anchor: Anchor.center, - ); + : super( + size: Vector2(100, 150), + anchor: Anchor.center, + ); late final SpawnComponent _bulletSpawner; @@ -89,7 +89,8 @@ class Player extends SpriteAnimationComponent selfPositioning: true, factory: (index) { return Bullet( - position: position + + position: + position + Vector2( 0, -height / 2, @@ -120,9 +121,9 @@ class Bullet extends SpriteAnimationComponent Bullet({ super.position, }) : super( - size: Vector2(25, 50), - anchor: Anchor.center, - ); + size: Vector2(25, 50), + anchor: Anchor.center, + ); @override Future onLoad() async { @@ -161,9 +162,9 @@ class Enemy extends SpriteAnimationComponent Enemy({ super.position, }) : super( - size: Vector2.all(enemySize), - anchor: Anchor.center, - ); + size: Vector2.all(enemySize), + anchor: Anchor.center, + ); static const enemySize = 50.0; @@ -214,10 +215,10 @@ class Explosion extends SpriteAnimationComponent Explosion({ super.position, }) : super( - size: Vector2.all(150), - anchor: Anchor.center, - removeOnFinish: true, - ); + size: Vector2.all(150), + anchor: Anchor.center, + removeOnFinish: true, + ); @override Future onLoad() async { diff --git a/doc/tutorials/space_shooter/app/pubspec.yaml b/doc/tutorials/space_shooter/app/pubspec.yaml index a5904ad82..efa24a0a8 100644 --- a/doc/tutorials/space_shooter/app/pubspec.yaml +++ b/doc/tutorials/space_shooter/app/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/examples/games/crystal_ball/lib/crystal_ball.dart b/examples/games/crystal_ball/lib/crystal_ball.dart index 9f7ad975e..0ef3572ef 100644 --- a/examples/games/crystal_ball/lib/crystal_ball.dart +++ b/examples/games/crystal_ball/lib/crystal_ball.dart @@ -21,17 +21,18 @@ and the glowing effect of the crystal ball. class _CrystalBallWidgetState extends State { // PreloadedPrograms is a simple data class that holds the preloaded - late final Future preloadedPrograms = Future.wait([ - FragmentProgram.fromAsset('packages/crystal_ball/shaders/ground.frag'), - FragmentProgram.fromAsset('packages/crystal_ball/shaders/fog.frag'), - FragmentProgram.fromAsset('packages/crystal_ball/shaders/firefly.frag'), - ]).then( - (l) => ( - waterFragmentProgram: l[0], - fogFragmentProgram: l[1], - fireflyFragmentProgram: l[2], - ), - ); + late final Future preloadedPrograms = + Future.wait([ + FragmentProgram.fromAsset('packages/crystal_ball/shaders/ground.frag'), + FragmentProgram.fromAsset('packages/crystal_ball/shaders/fog.frag'), + FragmentProgram.fromAsset('packages/crystal_ball/shaders/firefly.frag'), + ]).then( + (l) => ( + waterFragmentProgram: l[0], + fogFragmentProgram: l[1], + fireflyFragmentProgram: l[2], + ), + ); CrystalBallGame? game; diff --git a/examples/games/crystal_ball/lib/src/game/components/input_handler.dart b/examples/games/crystal_ball/lib/src/game/components/input_handler.dart index 771a04689..27aea09e8 100644 --- a/examples/games/crystal_ball/lib/src/game/components/input_handler.dart +++ b/examples/games/crystal_ball/lib/src/game/components/input_handler.dart @@ -7,10 +7,10 @@ import 'package:flutter/services.dart'; class InputHandler extends PositionComponent with TapCallbacks, HasGameReference { InputHandler() - : super( - anchor: Anchor.center, - size: kCameraSize, - ); + : super( + anchor: Anchor.center, + size: kCameraSize, + ); @override Future onLoad() async { diff --git a/examples/games/crystal_ball/lib/src/game/entities/ground.dart b/examples/games/crystal_ball/lib/src/game/entities/ground.dart index 35f324e1f..17802b564 100644 --- a/examples/games/crystal_ball/lib/src/game/entities/ground.dart +++ b/examples/games/crystal_ball/lib/src/game/entities/ground.dart @@ -17,37 +17,37 @@ class Rectangle extends PositionComponent ParentIsA, HasGameReference { Rectangle(double y) - : super( - anchor: Anchor.topCenter, - position: Vector2(0, y), - size: Vector2( - kCameraSize.x, - kCameraSize.y / 2, + : super( + anchor: Anchor.topCenter, + position: Vector2(0, y), + size: Vector2( + kCameraSize.x, + kCameraSize.y / 2, + ), + children: [ + RectangleHitbox( + size: Vector2( + kCameraSize.x, + kCameraSize.y / 2, + ), ), - children: [ + RectangleHitbox( + position: Vector2(0, kPlayerRadius), + size: Vector2( + kCameraSize.x, + kCameraSize.y / 2, + ), + ), + for (var i = 2; i < 30; i++) RectangleHitbox( + position: Vector2(0, kPlayerRadius * i), size: Vector2( kCameraSize.x, kCameraSize.y / 2, ), ), - RectangleHitbox( - position: Vector2(0, kPlayerRadius), - size: Vector2( - kCameraSize.x, - kCameraSize.y / 2, - ), - ), - for (var i = 2; i < 30; i++) - RectangleHitbox( - position: Vector2(0, kPlayerRadius * i), - size: Vector2( - kCameraSize.x, - kCameraSize.y / 2, - ), - ), - ], - ); + ], + ); double get topEdge => absolutePositionOfAnchor(Anchor.topCenter).y; } diff --git a/examples/games/crystal_ball/lib/src/game/entities/the_ball.dart b/examples/games/crystal_ball/lib/src/game/entities/the_ball.dart index 3bb31a0af..20cc8c8cf 100644 --- a/examples/games/crystal_ball/lib/src/game/entities/the_ball.dart +++ b/examples/games/crystal_ball/lib/src/game/entities/the_ball.dart @@ -16,15 +16,15 @@ class TheBall extends PositionComponent TheBall({ required Vector2 super.position, }) : super( - anchor: Anchor.center, - priority: 100000, - children: [ - CircleHitbox( - radius: kPlayerRadius, - anchor: Anchor.center, - ), - ], - ); + anchor: Anchor.center, + priority: 100000, + children: [ + CircleHitbox( + radius: kPlayerRadius, + anchor: Anchor.center, + ), + ], + ); final Vector2 velocity = Vector2.zero(); diff --git a/examples/games/crystal_ball/lib/src/game/game.dart b/examples/games/crystal_ball/lib/src/game/game.dart index cca79124d..3dd60129a 100644 --- a/examples/games/crystal_ball/lib/src/game/game.dart +++ b/examples/games/crystal_ball/lib/src/game/game.dart @@ -20,12 +20,12 @@ class CrystalBallGame extends FlameGame CrystalBallGame({ required this.preloadedPrograms, }) : super( - camera: CameraComponent.withFixedResolution( - width: kCameraSize.x, - height: kCameraSize.y, - ), - world: CrystalBallGameWorld(), - ) { + camera: CameraComponent.withFixedResolution( + width: kCameraSize.x, + height: kCameraSize.y, + ), + world: CrystalBallGameWorld(), + ) { camera.postProcess = PostProcessGroup( postProcesses: [ PostProcessSequentialGroup( diff --git a/examples/games/crystal_ball/lib/src/game/post_processes/ball_glow.dart b/examples/games/crystal_ball/lib/src/game/post_processes/ball_glow.dart index 0a186d3b8..05cb11ca8 100644 --- a/examples/games/crystal_ball/lib/src/game/post_processes/ball_glow.dart +++ b/examples/games/crystal_ball/lib/src/game/post_processes/ball_glow.dart @@ -60,8 +60,12 @@ class BallGlowPostProcess extends PostProcess { Vector2 size, Canvas canvas, ) { - final origin = - world.findGame()!.camera.visibleWorldRect.topLeft.toVector2(); + final origin = world + .findGame()! + .camera + .visibleWorldRect + .topLeft + .toVector2(); final theBall = world.theBall; final ballPosition = theBall.absolutePosition; final uvBall = (ballPosition - origin)..divide(kCameraSize); diff --git a/examples/games/crystal_ball/lib/src/game/post_processes/firefly.dart b/examples/games/crystal_ball/lib/src/game/post_processes/firefly.dart index 911434730..f03905818 100644 --- a/examples/games/crystal_ball/lib/src/game/post_processes/firefly.dart +++ b/examples/games/crystal_ball/lib/src/game/post_processes/firefly.dart @@ -33,8 +33,9 @@ class FireflyPostProcess extends PostProcess { final groundPosition = world.ground.rectangle.absolutePosition + Vector2(0, 1800); - final globalGroundPosition = - camera.viewfinder.localToGlobal(groundPosition); + final globalGroundPosition = camera.viewfinder.localToGlobal( + groundPosition, + ); final uvGround = globalGroundPosition.y / size.y; final cameraVerticalPos = world.cameraTarget.position.clone() diff --git a/examples/games/crystal_ball/lib/src/game/post_processes/foreground_fog.dart b/examples/games/crystal_ball/lib/src/game/post_processes/foreground_fog.dart index 6b2991216..ba7a73853 100644 --- a/examples/games/crystal_ball/lib/src/game/post_processes/foreground_fog.dart +++ b/examples/games/crystal_ball/lib/src/game/post_processes/foreground_fog.dart @@ -27,8 +27,8 @@ class ForegroundFogPostProcess extends PostProcess { @override void postProcess(Vector2 size, Canvas canvas) { - final origin = - CameraComponent.currentCamera!.visibleWorldRect.topLeft.toVector2(); + final origin = CameraComponent.currentCamera!.visibleWorldRect.topLeft + .toVector2(); shader.setFloatUniforms((value) { value.setVector(size); diff --git a/examples/games/crystal_ball/lib/src/game/post_processes/water.dart b/examples/games/crystal_ball/lib/src/game/post_processes/water.dart index ef410ae16..57f379344 100644 --- a/examples/games/crystal_ball/lib/src/game/post_processes/water.dart +++ b/examples/games/crystal_ball/lib/src/game/post_processes/water.dart @@ -27,8 +27,9 @@ class WaterPostProcess extends PostProcess { void postProcess(Vector2 size, Canvas canvas) { final groundPosition = world.ground.rectangle.position; final camera = CameraComponent.currentCamera!; - final globalGroundPosition = - camera.viewfinder.localToGlobal(groundPosition); + final globalGroundPosition = camera.viewfinder.localToGlobal( + groundPosition, + ); final uvGround = globalGroundPosition.y / size.y; final preRenderedSubtree = rasterizeSubtree(); diff --git a/examples/games/crystal_ball/pubspec.yaml b/examples/games/crystal_ball/pubspec.yaml index 437f18d04..0270aacb7 100644 --- a/examples/games/crystal_ball/pubspec.yaml +++ b/examples/games/crystal_ball/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: "0.1.0" environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/examples/games/padracing/lib/ball.dart b/examples/games/padracing/lib/ball.dart index 5655f7049..90f4c1d42 100644 --- a/examples/games/padracing/lib/ball.dart +++ b/examples/games/padracing/lib/ball.dart @@ -88,10 +88,11 @@ List createBalls(Vector2 trackSize, List walls, Ball bigBall) { ); final touchesBall = ball.initialPosition.distanceTo(bigBall.initialPosition) < - ball.radius + bigBall.radius; + ball.radius + bigBall.radius; if (!touchesBall) { - final touchesWall = - walls.any((wall) => wall.asRect.overlaps(ball.asRect)); + final touchesWall = walls.any( + (wall) => wall.asRect.overlaps(ball.asRect), + ); if (!touchesWall) { balls.add(ball); } diff --git a/examples/games/padracing/lib/car.dart b/examples/games/padracing/lib/car.dart index 322d9b92d..25d300d77 100644 --- a/examples/games/padracing/lib/car.dart +++ b/examples/games/padracing/lib/car.dart @@ -11,10 +11,10 @@ import 'package:padracing/tire.dart'; class Car extends BodyComponent { Car({required this.playerNumber, required this.cameraComponent}) - : super( - priority: 3, - paint: Paint()..color = colors[playerNumber], - ); + : super( + priority: 3, + paint: Paint()..color = colors[playerNumber], + ); static final colors = [ GameColors.green.color, diff --git a/examples/games/padracing/lib/lap_line.dart b/examples/games/padracing/lib/lap_line.dart index 1dc2854ad..033b8f897 100644 --- a/examples/games/padracing/lib/lap_line.dart +++ b/examples/games/padracing/lib/lap_line.dart @@ -11,7 +11,7 @@ import 'package:padracing/game_colors.dart'; class LapLine extends BodyComponent with ContactCallbacks { LapLine(this.id, this.initialPosition, this.size, {required this.isFinish}) - : super(priority: 1); + : super(priority: 1); final int id; final bool isFinish; @@ -94,8 +94,9 @@ class LapLine extends BodyComponent with ContactCallbacks { other.lapNotifier.value++; other.passedStartControl.clear(); } else if (!isFinish) { - other.passedStartControl - .removeWhere((passedControl) => passedControl.id > id); + other.passedStartControl.removeWhere( + (passedControl) => passedControl.id > id, + ); other.passedStartControl.add(this); } } diff --git a/examples/games/padracing/lib/lap_text.dart b/examples/games/padracing/lib/lap_text.dart index fbaea560c..359b14b14 100644 --- a/examples/games/padracing/lib/lap_text.dart +++ b/examples/games/padracing/lib/lap_text.dart @@ -8,7 +8,7 @@ import 'package:padracing/padracing_game.dart'; class LapText extends PositionComponent with HasGameReference { LapText({required this.car, required Vector2 position}) - : super(position: position); + : super(position: position); final Car car; late final ValueNotifier lapNotifier = car.lapNotifier; diff --git a/examples/games/padracing/lib/padracing_game.dart b/examples/games/padracing/lib/padracing_game.dart index 9ed5405d6..0f1d0cf58 100644 --- a/examples/games/padracing/lib/padracing_game.dart +++ b/examples/games/padracing/lib/padracing_game.dart @@ -133,14 +133,14 @@ class PadRacingGame extends Forge2DGame with KeyboardEvents { ..paint.style = PaintingStyle.stroke; final cameras = List.generate(numberOfPlayers, (i) { return CameraComponent( - world: world, - viewport: FixedSizeViewport(viewportSize.x, viewportSize.y) - ..position = alignedVector( - longMultiplier: i == 0 ? 0.0 : 1 / (i + 1), - shortMultiplier: 0.0, - ) - ..add(viewportRimGenerator()), - ) + world: world, + viewport: FixedSizeViewport(viewportSize.x, viewportSize.y) + ..position = alignedVector( + longMultiplier: i == 0 ? 0.0 : 1 / (i + 1), + shortMultiplier: 0.0, + ) + ..add(viewportRimGenerator()), + ) ..viewfinder.anchor = Anchor.center ..viewfinder.zoom = playZoom; }); @@ -149,13 +149,13 @@ class PadRacingGame extends Forge2DGame with KeyboardEvents { const mapCameraZoom = 0.5; final mapCameras = List.generate(numberOfPlayers, (i) { return CameraComponent( - world: world, - viewport: FixedSizeViewport(mapCameraSize.x, mapCameraSize.y) - ..position = Vector2( - viewportSize.x - mapCameraSize.x * mapCameraZoom - 50, - 50, - ), - ) + world: world, + viewport: FixedSizeViewport(mapCameraSize.x, mapCameraSize.y) + ..position = Vector2( + viewportSize.x - mapCameraSize.x * mapCameraZoom - 50, + 50, + ), + ) ..viewfinder.anchor = Anchor.topLeft ..viewfinder.zoom = mapCameraZoom; }); diff --git a/examples/games/padracing/lib/tire.dart b/examples/games/padracing/lib/tire.dart index 0309f7fa3..11f0726cf 100644 --- a/examples/games/padracing/lib/tire.dart +++ b/examples/games/padracing/lib/tire.dart @@ -15,12 +15,12 @@ class Tire extends BodyComponent { required this.jointDef, this.isTurnableTire = false, }) : super( - paint: Paint() - ..color = car.paint.color - ..strokeWidth = 0.2 - ..style = PaintingStyle.stroke, - priority: 2, - ); + paint: Paint() + ..color = car.paint.color + ..strokeWidth = 0.2 + ..style = PaintingStyle.stroke, + priority: 2, + ); static const double _backTireMaxDriveForce = 300.0; static const double _frontTireMaxDriveForce = 600.0; @@ -39,10 +39,12 @@ class Tire extends BodyComponent { final Set pressedKeys; - late final double _maxDriveForce = - isFrontTire ? _frontTireMaxDriveForce : _backTireMaxDriveForce; - late final double _maxLateralImpulse = - isFrontTire ? _frontTireMaxLateralImpulse : _backTireMaxLateralImpulse; + late final double _maxDriveForce = isFrontTire + ? _frontTireMaxDriveForce + : _backTireMaxDriveForce; + late final double _maxLateralImpulse = isFrontTire + ? _frontTireMaxLateralImpulse + : _backTireMaxLateralImpulse; // Make mutable if ice or something should be implemented final double _currentTraction = 1.0; @@ -165,8 +167,10 @@ class Tire extends BodyComponent { if (isTurnableTire && isTurning) { final turnPerTimeStep = _turnSpeedPerSecond * dt; final angleNow = joint.jointAngle(); - final angleToTurn = - (desiredAngle - angleNow).clamp(-turnPerTimeStep, turnPerTimeStep); + final angleToTurn = (desiredAngle - angleNow).clamp( + -turnPerTimeStep, + turnPerTimeStep, + ); final angle = angleNow + angleToTurn; joint.setLimits(angle, angle); } else { diff --git a/examples/games/padracing/pubspec.yaml b/examples/games/padracing/pubspec.yaml index d3324039e..589e215ca 100644 --- a/examples/games/padracing/pubspec.yaml +++ b/examples/games/padracing/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: collection: ^1.17.1 diff --git a/examples/games/rogue_shooter/lib/components/bullet_component.dart b/examples/games/rogue_shooter/lib/components/bullet_component.dart index 30211130c..f4de9b822 100644 --- a/examples/games/rogue_shooter/lib/components/bullet_component.dart +++ b/examples/games/rogue_shooter/lib/components/bullet_component.dart @@ -9,7 +9,7 @@ class BulletComponent extends SpriteAnimationComponent final Vector2 deltaPosition = Vector2.zero(); BulletComponent({required super.position, super.angle}) - : super(size: Vector2(10, 20), anchor: Anchor.center); + : super(size: Vector2(10, 20), anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/games/rogue_shooter/lib/components/enemy_component.dart b/examples/games/rogue_shooter/lib/components/enemy_component.dart index a9c1ffed2..3f67a87a3 100644 --- a/examples/games/rogue_shooter/lib/components/enemy_component.dart +++ b/examples/games/rogue_shooter/lib/components/enemy_component.dart @@ -9,7 +9,7 @@ class EnemyComponent extends SpriteAnimationComponent static final Vector2 initialSize = Vector2.all(25); EnemyComponent({required super.position}) - : super(size: initialSize, anchor: Anchor.center); + : super(size: initialSize, anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/games/rogue_shooter/lib/components/explosion_component.dart b/examples/games/rogue_shooter/lib/components/explosion_component.dart index 97bc06a18..3a35e4fd1 100644 --- a/examples/games/rogue_shooter/lib/components/explosion_component.dart +++ b/examples/games/rogue_shooter/lib/components/explosion_component.dart @@ -3,11 +3,11 @@ import 'package:flame/components.dart'; class ExplosionComponent extends SpriteAnimationComponent with HasGameReference { ExplosionComponent({super.position}) - : super( - size: Vector2.all(50), - anchor: Anchor.center, - removeOnFinish: true, - ); + : super( + size: Vector2.all(50), + anchor: Anchor.center, + removeOnFinish: true, + ); @override Future onLoad() async { diff --git a/examples/games/rogue_shooter/lib/components/star_component.dart b/examples/games/rogue_shooter/lib/components/star_component.dart index 30258fd60..9ee329224 100644 --- a/examples/games/rogue_shooter/lib/components/star_component.dart +++ b/examples/games/rogue_shooter/lib/components/star_component.dart @@ -4,7 +4,7 @@ class StarComponent extends SpriteAnimationComponent with HasGameReference { static const speed = 10; StarComponent({super.animation, super.position}) - : super(size: Vector2.all(20)); + : super(size: Vector2.all(20)); @override void update(double dt) { diff --git a/examples/games/rogue_shooter/pubspec.yaml b/examples/games/rogue_shooter/pubspec.yaml index 64ceaf79c..960c3508b 100644 --- a/examples/games/rogue_shooter/pubspec.yaml +++ b/examples/games/rogue_shooter/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 0.1.0 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/examples/games/trex/lib/background/cloud.dart b/examples/games/trex/lib/background/cloud.dart index 020467341..596a4fb78 100644 --- a/examples/games/trex/lib/background/cloud.dart +++ b/examples/games/trex/lib/background/cloud.dart @@ -6,10 +6,10 @@ import 'package:trex_game/trex_game.dart'; class Cloud extends SpriteComponent with ParentIsA, HasGameReference { Cloud({required Vector2 position}) - : super( - position: position, - size: initialSize, - ); + : super( + position: position, + size: initialSize, + ); static final Vector2 initialSize = Vector2(92.0, 28.0); @@ -53,7 +53,8 @@ class Cloud extends SpriteComponent @override void onGameResize(Vector2 size) { super.onGameResize(size); - y = ((absolutePosition.y / 2 - (maxSkyLevel - minSkyLevel)) + + y = + ((absolutePosition.y / 2 - (maxSkyLevel - minSkyLevel)) + game.random.nextDoubleBetween(minSkyLevel, maxSkyLevel)) - absolutePositionOf(absoluteTopLeftPosition).y; } diff --git a/examples/games/trex/lib/background/horizon.dart b/examples/games/trex/lib/background/horizon.dart index 3d0f06f8f..c8c3fd970 100644 --- a/examples/games/trex/lib/background/horizon.dart +++ b/examples/games/trex/lib/background/horizon.dart @@ -66,7 +66,8 @@ class Horizon extends PositionComponent with HasGameReference { List _generateLines() { final number = 1 + (game.size.x / lineSize.x).ceil() - groundLayers.length; - final lastX = (groundLayers.lastOrNull?.x ?? 0) + + final lastX = + (groundLayers.lastOrNull?.x ?? 0) + (groundLayers.lastOrNull?.width ?? 0); return List.generate( max(number, 0), diff --git a/examples/games/trex/lib/obstacle/obstacle.dart b/examples/games/trex/lib/obstacle/obstacle.dart index f2b6bc57c..b7f1d27a4 100644 --- a/examples/games/trex/lib/obstacle/obstacle.dart +++ b/examples/games/trex/lib/obstacle/obstacle.dart @@ -29,8 +29,8 @@ class Obstacle extends SpriteComponent with HasGameReference { } double computeGap(double gapCoefficient, double speed) { - final minGap = - (width * speed * settings.minGap * gapCoefficient).roundToDouble(); + final minGap = (width * speed * settings.minGap * gapCoefficient) + .roundToDouble(); final maxGap = (minGap * _maxGapCoefficient).roundToDouble(); return game.random.nextDoubleBetween(minGap, maxGap); } diff --git a/examples/games/trex/lib/obstacle/obstacle_type.dart b/examples/games/trex/lib/obstacle/obstacle_type.dart index ce03bca2e..db8414fc3 100644 --- a/examples/games/trex/lib/obstacle/obstacle_type.dart +++ b/examples/games/trex/lib/obstacle/obstacle_type.dart @@ -91,15 +91,15 @@ class ObstacleTypeSettings { Sprite sprite(Image spriteImage) { return switch (type) { ObstacleType.cactusSmall => Sprite( - spriteImage, - srcPosition: Vector2(446.0, 2.0), - srcSize: size, - ), + spriteImage, + srcPosition: Vector2(446.0, 2.0), + srcSize: size, + ), ObstacleType.cactusLarge => Sprite( - spriteImage, - srcPosition: Vector2(652.0, 2.0), - srcSize: size, - ), + spriteImage, + srcPosition: Vector2(652.0, 2.0), + srcSize: size, + ), }; } } diff --git a/examples/games/trex/pubspec.yaml b/examples/games/trex/pubspec.yaml index 250041760..fbaf1d06f 100644 --- a/examples/games/trex/pubspec.yaml +++ b/examples/games/trex/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 0.1.0 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/examples/lib/commons/ember.dart b/examples/lib/commons/ember.dart index e8309f538..88b2a87e1 100644 --- a/examples/lib/commons/ember.dart +++ b/examples/lib/commons/ember.dart @@ -5,10 +5,10 @@ import 'package:meta/meta.dart'; class Ember extends SpriteAnimationComponent with HasGameReference { Ember({super.position, Vector2? size, super.priority, super.key}) - : super( - size: size ?? Vector2.all(50), - anchor: Anchor.center, - ); + : super( + size: size ?? Vector2.all(50), + anchor: Anchor.center, + ); @mustCallSuper @override diff --git a/examples/lib/stories/bridge_libraries/audio/audio.dart b/examples/lib/stories/bridge_libraries/audio/audio.dart index 00e7cbdaf..5416b37cc 100644 --- a/examples/lib/stories/bridge_libraries/audio/audio.dart +++ b/examples/lib/stories/bridge_libraries/audio/audio.dart @@ -4,7 +4,9 @@ import 'package:examples/stories/bridge_libraries/audio/basic_audio_example.dart import 'package:flame/game.dart'; void addAudioStories(Dashbook dashbook) { - dashbook.storiesOf('Audio').add( + dashbook + .storiesOf('Audio') + .add( 'Basic Audio', (_) => GameWidget(game: BasicAudioExample()), codeLink: baseLink('bridge_libraries/audio/basic_audio_example.dart'), diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/animated_body_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/animated_body_example.dart index e8c4dd34e..07d310eb7 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/animated_body_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/animated_body_example.dart @@ -15,10 +15,10 @@ class AnimatedBodyExample extends Forge2DGame { '''; AnimatedBodyExample() - : super( - gravity: Vector2.zero(), - world: AnimatedBodyWorld(), - ); + : super( + gravity: Vector2.zero(), + world: AnimatedBodyWorld(), + ); } class AnimatedBodyWorld extends Forge2DWorld diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/composition_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/composition_example.dart index f68962bbb..e8aa956d0 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/composition_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/composition_example.dart @@ -28,12 +28,12 @@ class CompositionExample extends Forge2DGame { class TappableText extends TextComponent with TapCallbacks { TappableText(Vector2 position) - : super( - text: 'A normal tappable Flame component', - textRenderer: TextPaint(style: _textStyle), - position: position, - anchor: Anchor.center, - ); + : super( + text: 'A normal tappable Flame component', + textRenderer: TextPaint(style: _textStyle), + position: position, + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart index 27dd8167d..772e73b82 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/contact_callbacks_example.dart @@ -15,7 +15,7 @@ class ContactCallbacksExample extends Forge2DGame { '''; ContactCallbacksExample() - : super(gravity: Vector2(0, 10.0), world: ContactCallbackWorld()); + : super(gravity: Vector2(0, 10.0), world: ContactCallbackWorld()); } class ContactCallbackWorld extends Forge2DWorld diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/domino_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/domino_example.dart index b936fba3c..1ecd29b85 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/domino_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/domino_example.dart @@ -14,7 +14,7 @@ class DominoExample extends Forge2DGame { '''; DominoExample() - : super(gravity: Vector2(0, 10.0), world: DominoExampleWorld()); + : super(gravity: Vector2(0, 10.0), world: DominoExampleWorld()); } class DominoExampleWorld extends Forge2DWorld diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/friction_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/friction_joint.dart index 86f5e7db7..bc79b376b 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/friction_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/friction_joint.dart @@ -11,7 +11,7 @@ class FrictionJointExample extends Forge2DGame { '''; FrictionJointExample() - : super(gravity: Vector2.all(0), world: FrictionJointWorld()); + : super(gravity: Vector2.all(0), world: FrictionJointWorld()); } class FrictionJointWorld extends Forge2DWorld diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/gear_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/gear_joint.dart index 322cb9c4d..8b83110b3 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/gear_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/gear_joint.dart @@ -28,8 +28,11 @@ class GearJointWorld extends Forge2DWorld with HasGameReference { Future onLoad() async { super.onLoad(); - final box = - DraggableBox(startPosition: boxAnchor, width: boxWidth, height: 20); + final box = DraggableBox( + startPosition: boxAnchor, + width: boxWidth, + height: 20, + ); add(box); final ball1Anchor = boxAnchor - Vector2(boxWidth / 2 + ball1Radius, 0); diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/motor_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/motor_joint.dart index 64a214561..75f19c892 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/motor_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/motor_joint.dart @@ -13,7 +13,7 @@ class MotorJointExample extends Forge2DGame { '''; MotorJointExample() - : super(gravity: Vector2.zero(), world: MotorJointWorld()); + : super(gravity: Vector2.zero(), world: MotorJointWorld()); } class MotorJointWorld extends Forge2DWorld with TapCallbacks { diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/mouse_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/mouse_joint.dart index 2230f0e57..eee881627 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/mouse_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/mouse_joint.dart @@ -12,7 +12,7 @@ class MouseJointExample extends Forge2DGame { '''; MouseJointExample() - : super(gravity: Vector2(0, 10.0), world: MouseJointWorld()); + : super(gravity: Vector2(0, 10.0), world: MouseJointWorld()); } class MouseJointWorld extends Forge2DWorld diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/revolute_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/revolute_joint.dart index 72b9609b4..837fd76ba 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/revolute_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/revolute_joint.dart @@ -15,7 +15,7 @@ class RevoluteJointExample extends Forge2DGame { '''; RevoluteJointExample() - : super(gravity: Vector2(0, 10.0), world: RevoluteJointWorld()); + : super(gravity: Vector2(0, 10.0), world: RevoluteJointWorld()); } class RevoluteJointWorld extends Forge2DWorld diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/weld_joint.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/weld_joint.dart index b1daea4dc..500011532 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/joints/weld_joint.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/joints/weld_joint.dart @@ -54,11 +54,12 @@ class WeldJointWorld extends Forge2DWorld // screen space then gives us the coordinates of the upper left corner in // world space. final halfSize = game.screenToWorld(Vector2.zero())..absolute(); - final sectionWidth = ((leftPillar.center.x.abs() + - rightPillar.center.x.abs() + - pillarWidth) / - sectionsCount) - .ceilToDouble(); + final sectionWidth = + ((leftPillar.center.x.abs() + + rightPillar.center.x.abs() + + pillarWidth) / + sectionsCount) + .ceilToDouble(); Body? prevSection; for (var i = 0; i < sectionsCount; i++) { diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/sprite_body_example.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/sprite_body_example.dart index 0aea806f6..b21ffab63 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/sprite_body_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/sprite_body_example.dart @@ -12,10 +12,10 @@ class SpriteBodyExample extends Forge2DGame { '''; SpriteBodyExample() - : super( - gravity: Vector2(0, 10.0), - world: SpriteBodyWorld(), - ); + : super( + gravity: Vector2(0, 10.0), + world: SpriteBodyWorld(), + ); } class SpriteBodyWorld extends Forge2DWorld diff --git a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart index 7c02dc02c..cdbd98f98 100644 --- a/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart +++ b/examples/lib/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart @@ -22,7 +22,7 @@ class Wall extends BodyComponent { final double strokeWidth; Wall(this.start, this.end, {double? strokeWidth}) - : strokeWidth = strokeWidth ?? 1; + : strokeWidth = strokeWidth ?? 1; @override Body createBody() { diff --git a/examples/lib/stories/bridge_libraries/flame_isolate/isolate.dart b/examples/lib/stories/bridge_libraries/flame_isolate/isolate.dart index f5df511a9..1ae4076c3 100644 --- a/examples/lib/stories/bridge_libraries/flame_isolate/isolate.dart +++ b/examples/lib/stories/bridge_libraries/flame_isolate/isolate.dart @@ -4,7 +4,9 @@ import 'package:examples/stories/bridge_libraries/flame_isolate/simple_isolate_e import 'package:flame/game.dart'; void addFlameIsolateExample(Dashbook dashbook) { - dashbook.storiesOf('FlameIsolate').add( + dashbook + .storiesOf('FlameIsolate') + .add( 'Simple isolate example', (_) => GameWidget( game: SimpleIsolateExample(), diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/command_lifecycle_dialogue_controller.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/command_lifecycle_dialogue_controller.dart index 78f6ec0f8..746394c21 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/command_lifecycle_dialogue_controller.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/command_lifecycle_dialogue_controller.dart @@ -10,7 +10,7 @@ class CommandLifecycleDialogueController extends DialogueControllerComponent { }); final FutureOr Function(UserDefinedCommand command) onCommandOverride; final FutureOr Function(UserDefinedCommand command) - onCommandFinishOverride; + onCommandFinishOverride; @override FutureOr onCommand(UserDefinedCommand command) async { diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_text_box.dart b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_text_box.dart index fe38ebfcc..f0c7a3d79 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_text_box.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/components/dialogue_text_box.dart @@ -4,14 +4,14 @@ import 'package:flutter/material.dart'; class DialogueTextBox extends TextBoxComponent { DialogueTextBox({required super.text}) - : super( - position: Vector2(16, 16), - size: Vector2(704, 96), - textRenderer: TextPaint( - style: const TextStyle( - fontSize: fontSize, - color: Colors.black, - ), + : super( + position: Vector2(16, 16), + size: Vector2(704, 96), + textRenderer: TextPaint( + style: const TextStyle( + fontSize: fontSize, + color: Colors.black, ), - ); + ), + ); } diff --git a/examples/lib/stories/bridge_libraries/flame_jenny/jenny_command_lifecycle_example.dart b/examples/lib/stories/bridge_libraries/flame_jenny/jenny_command_lifecycle_example.dart index 020bba211..8b4bf075b 100644 --- a/examples/lib/stories/bridge_libraries/flame_jenny/jenny_command_lifecycle_example.dart +++ b/examples/lib/stories/bridge_libraries/flame_jenny/jenny_command_lifecycle_example.dart @@ -25,13 +25,15 @@ commands work. final yarnProject = YarnProject(); final dialogueControllerComponent = CommandLifecycleDialogueController( onCommandOverride: (command) async { - final exampleVariable = - yarnProject.variables.getVariable(r'$exampleVariable'); + final exampleVariable = yarnProject.variables.getVariable( + r'$exampleVariable', + ); onCommandLabel.text = 'onCommand: $exampleVariable'; }, onCommandFinishOverride: (command) async { - final exampleVariable = - yarnProject.variables.getVariable(r'$exampleVariable'); + final exampleVariable = yarnProject.variables.getVariable( + r'$exampleVariable', + ); onCommandFinishLabel.text = 'onCommandFinish: $exampleVariable'; }, ); diff --git a/examples/lib/stories/bridge_libraries/flame_lottie/lottie.dart b/examples/lib/stories/bridge_libraries/flame_lottie/lottie.dart index 329ec06b0..426deaa4e 100644 --- a/examples/lib/stories/bridge_libraries/flame_lottie/lottie.dart +++ b/examples/lib/stories/bridge_libraries/flame_lottie/lottie.dart @@ -4,7 +4,9 @@ import 'package:examples/stories/bridge_libraries/flame_lottie/lottie_animation_ import 'package:flame/game.dart'; void addFlameLottieExample(Dashbook dashbook) { - dashbook.storiesOf('FlameLottie').add( + dashbook + .storiesOf('FlameLottie') + .add( 'Lottie Animation example', (_) => GameWidget( game: LottieAnimationExample(), diff --git a/examples/lib/stories/bridge_libraries/flame_spine/flame_spine.dart b/examples/lib/stories/bridge_libraries/flame_spine/flame_spine.dart index 76e3e3d86..7f81ad489 100644 --- a/examples/lib/stories/bridge_libraries/flame_spine/flame_spine.dart +++ b/examples/lib/stories/bridge_libraries/flame_spine/flame_spine.dart @@ -11,8 +11,9 @@ void addFlameSpineExamples(Dashbook dashbook) { (_) => GameWidget( game: FlameSpineExample(), ), - codeLink: - baseLink('bridge_libraries/flame_spine/basic_spine_example.dart'), + codeLink: baseLink( + 'bridge_libraries/flame_spine/basic_spine_example.dart', + ), info: FlameSpineExample.description, ) ..add( diff --git a/examples/lib/stories/camera_and_viewport/camera_and_viewport.dart b/examples/lib/stories/camera_and_viewport/camera_and_viewport.dart index 1f93b17f4..378777aec 100644 --- a/examples/lib/stories/camera_and_viewport/camera_and_viewport.dart +++ b/examples/lib/stories/camera_and_viewport/camera_and_viewport.dart @@ -85,8 +85,9 @@ void addCameraAndViewportStories(Dashbook dashbook) { ..add( 'Follow and World bounds', (_) => GameWidget(game: CameraFollowAndWorldBoundsExample()), - codeLink: - baseLink('camera_and_viewport/camera_follow_and_world_bounds.dart'), + codeLink: baseLink( + 'camera_and_viewport/camera_follow_and_world_bounds.dart', + ), info: CameraFollowAndWorldBoundsExample.description, ); } diff --git a/examples/lib/stories/camera_and_viewport/camera_component_example.dart b/examples/lib/stories/camera_and_viewport/camera_component_example.dart index e48f30c67..1c60d66d2 100644 --- a/examples/lib/stories/camera_and_viewport/camera_component_example.dart +++ b/examples/lib/stories/camera_and_viewport/camera_component_example.dart @@ -36,8 +36,10 @@ class CameraComponentExample extends FlameGame with PanDetector { camera.viewfinder.position = Vector2(center.x, center.y); }); - magnifyingGlass = - CameraComponent(world: world, viewport: CircularViewport(radius)); + magnifyingGlass = CameraComponent( + world: world, + viewport: CircularViewport(radius), + ); magnifyingGlass.viewport.add(Bezel(radius)); magnifyingGlass.viewfinder.zoom = zoom; } @@ -77,10 +79,10 @@ class CameraComponentExample extends FlameGame with PanDetector { class Bezel extends PositionComponent { Bezel(this.radius) - : super( - size: Vector2.all(2 * radius), - position: Vector2.all(radius), - ); + : super( + size: Vector2.all(2 * radius), + position: Vector2.all(radius), + ); final double radius; late final Path rim; @@ -106,23 +108,27 @@ class Bezel extends PositionComponent { rimBorder = Path() ..addOval(Rect.fromLTRB(-outer, -outer, outer, outer)) ..addOval(Rect.fromLTRB(-inner, -inner, inner, inner)); - handle = (Path() - ..addRRect( - RRect.fromLTRBR( - radius, - -handleWidth / 2, - handleLength + radius, - handleWidth / 2, - const Radius.circular(5.0), - ), - )) - .transform32((Matrix4.identity()..rotateZ(pi / 4)).storage); - connector = (Path() - ..addArc(Rect.fromLTRB(-outer, -outer, outer, outer), -0.22, 0.44)) - .transform32((Matrix4.identity()..rotateZ(pi / 4)).storage); - specularHighlight = (Path() - ..addOval(Rect.fromLTWH(-radius * 0.8, -8, 16, radius * 0.3))) - .transform32((Matrix4.identity()..rotateZ(pi / 4)).storage); + handle = + (Path()..addRRect( + RRect.fromLTRBR( + radius, + -handleWidth / 2, + handleLength + radius, + handleWidth / 2, + const Radius.circular(5.0), + ), + )) + .transform32((Matrix4.identity()..rotateZ(pi / 4)).storage); + connector = + (Path()..addArc( + Rect.fromLTRB(-outer, -outer, outer, outer), + -0.22, + 0.44, + )) + .transform32((Matrix4.identity()..rotateZ(pi / 4)).storage); + specularHighlight = + (Path()..addOval(Rect.fromLTWH(-radius * 0.8, -8, 16, radius * 0.3))) + .transform32((Matrix4.identity()..rotateZ(pi / 4)).storage); glassPaint = Paint()..color = const Color(0x1400ffae); rimBorderPaint = Paint() @@ -428,8 +434,9 @@ class Ant extends PositionComponent { 'nextIndex is outside of the bounds of travelPath', ); final nextPosition = travelPath[nextIndex]; - var nextAngle = - angle = -(nextPosition - position).angleToSigned(Vector2(0, -1)); + var nextAngle = angle = -(nextPosition - position).angleToSigned( + Vector2(0, -1), + ); if (nextAngle - angle > tau / 2) { nextAngle -= tau; } @@ -481,9 +488,9 @@ class InsectLeg { this.l2, this.l3, { required bool mirrorBendDirection, - }) : dir = mirrorBendDirection ? -1 : 1, - path = Path(), - foot = Vector2.zero() { + }) : dir = mirrorBendDirection ? -1 : 1, + path = Path(), + foot = Vector2.zero() { final ok = placeFoot(Vector2(x1, y1)); assert(ok, 'The foot was not properly placed'); } diff --git a/examples/lib/stories/camera_and_viewport/camera_component_properties_example.dart b/examples/lib/stories/camera_and_viewport/camera_component_properties_example.dart index 5df2f9302..2c39bb9db 100644 --- a/examples/lib/stories/camera_and_viewport/camera_component_properties_example.dart +++ b/examples/lib/stories/camera_and_viewport/camera_component_properties_example.dart @@ -22,13 +22,14 @@ class CameraComponentPropertiesExample extends FlameGame { '''; CameraComponentPropertiesExample() - : super( - camera: CameraComponent( - viewport: FixedSizeViewport(200, 200)..add(ViewportFrame()), - ) - ..viewfinder.zoom = 5 - ..viewfinder.anchor = const Anchor(0.25, 0.75), - ); + : super( + camera: + CameraComponent( + viewport: FixedSizeViewport(200, 200)..add(ViewportFrame()), + ) + ..viewfinder.zoom = 5 + ..viewfinder.anchor = const Anchor(0.25, 0.75), + ); late RectangleComponent _cullRect; @@ -128,15 +129,15 @@ class Background extends Component with TapCallbacks { class ExpandingCircle extends CircleComponent { ExpandingCircle(Offset center) - : super( - position: Vector2(center.dx, center.dy), - anchor: Anchor.center, - radius: 0, - paint: Paint() - ..color = const Color(0xffffffff) - ..style = PaintingStyle.stroke - ..strokeWidth = 1, - ); + : super( + position: Vector2(center.dx, center.dy), + anchor: Anchor.center, + radius: 0, + paint: Paint() + ..color = const Color(0xffffffff) + ..style = PaintingStyle.stroke + ..strokeWidth = 1, + ); static const maxRadius = 50; diff --git a/examples/lib/stories/camera_and_viewport/camera_follow_and_world_bounds.dart b/examples/lib/stories/camera_and_viewport/camera_follow_and_world_bounds.dart index 5b24773f4..ec1382b8b 100644 --- a/examples/lib/stories/camera_and_viewport/camera_follow_and_world_bounds.dart +++ b/examples/lib/stories/camera_and_viewport/camera_follow_and_world_bounds.dart @@ -31,9 +31,7 @@ class CameraFollowAndWorldBoundsExample extends FlameGame } class Ground extends PositionComponent { - Ground() - : pebbles = [], - super(size: Vector2(1000, 30)) { + Ground() : pebbles = [], super(size: Vector2(1000, 30)) { final random = Random(); for (var i = 0; i < 25; i++) { pebbles.add( @@ -67,19 +65,19 @@ class Ground extends PositionComponent { class Player extends PositionComponent with KeyboardHandler { Player() - : body = Path() - ..moveTo(10, 0) - ..cubicTo(17, 0, 28, 20, 10, 20) - ..cubicTo(-8, 20, 3, 0, 10, 0) - ..close(), - eyes = Path() - ..addOval(const Rect.fromLTWH(12.5, 9, 4, 6)) - ..addOval(const Rect.fromLTWH(6.5, 9, 4, 6)), - pupils = Path() - ..addOval(const Rect.fromLTWH(14, 11, 2, 2)) - ..addOval(const Rect.fromLTWH(8, 11, 2, 2)), - velocity = Vector2.zero(), - super(size: Vector2(20, 20), anchor: Anchor.bottomCenter); + : body = Path() + ..moveTo(10, 0) + ..cubicTo(17, 0, 28, 20, 10, 20) + ..cubicTo(-8, 20, 3, 0, 10, 0) + ..close(), + eyes = Path() + ..addOval(const Rect.fromLTWH(12.5, 9, 4, 6)) + ..addOval(const Rect.fromLTWH(6.5, 9, 4, 6)), + pupils = Path() + ..addOval(const Rect.fromLTWH(14, 11, 2, 2)) + ..addOval(const Rect.fromLTWH(8, 11, 2, 2)), + velocity = Vector2.zero(), + super(size: Vector2(20, 20), anchor: Anchor.bottomCenter); final Path body; final Path eyes; @@ -144,11 +142,14 @@ class Player extends PositionComponent with KeyboardHandler { @override bool onKeyEvent(KeyEvent event, Set keysPressed) { final isKeyDown = event is KeyDownEvent; - final keyLeft = (event.logicalKey == LogicalKeyboardKey.arrowLeft) || + final keyLeft = + (event.logicalKey == LogicalKeyboardKey.arrowLeft) || (event.logicalKey == LogicalKeyboardKey.keyA); - final keyRight = (event.logicalKey == LogicalKeyboardKey.arrowRight) || + final keyRight = + (event.logicalKey == LogicalKeyboardKey.arrowRight) || (event.logicalKey == LogicalKeyboardKey.keyD); - final keyUp = (event.logicalKey == LogicalKeyboardKey.arrowUp) || + final keyUp = + (event.logicalKey == LogicalKeyboardKey.arrowUp) || (event.logicalKey == LogicalKeyboardKey.keyW); if (isKeyDown) { @@ -161,9 +162,11 @@ class Player extends PositionComponent with KeyboardHandler { nJumpsLeft -= 1; } } else { - final hasLeft = keysPressed.contains(LogicalKeyboardKey.arrowLeft) || + final hasLeft = + keysPressed.contains(LogicalKeyboardKey.arrowLeft) || keysPressed.contains(LogicalKeyboardKey.keyA); - final hasRight = keysPressed.contains(LogicalKeyboardKey.arrowRight) || + final hasRight = + keysPressed.contains(LogicalKeyboardKey.arrowRight) || keysPressed.contains(LogicalKeyboardKey.keyD); if (hasLeft && hasRight) { // Leave the current speed unchanged diff --git a/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart b/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart index a72772fd7..5178a4c63 100644 --- a/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart +++ b/examples/lib/stories/camera_and_viewport/fixed_resolution_example.dart @@ -19,10 +19,10 @@ class FixedResolutionExample extends FlameGame '''; FixedResolutionExample() - : super( - camera: CameraComponent.withFixedResolution(width: 600, height: 1024), - world: FixedResolutionWorld(), - ); + : super( + camera: CameraComponent.withFixedResolution(width: 600, height: 1024), + world: FixedResolutionWorld(), + ); @override Future onLoad() async { @@ -118,25 +118,25 @@ class TextButton extends ButtonComponent { super.anchor, TextRenderer? textRenderer, }) : super( - button: RectangleComponent( - size: Vector2(200, 100), - paint: Paint() - ..color = Colors.orange - ..strokeWidth = 2 - ..style = PaintingStyle.stroke, - ), - buttonDown: RectangleComponent( - size: Vector2(200, 100), - paint: Paint() - ..color = BasicPalette.orange.color.withValues(alpha: 0.5), - ), - children: [ - TextComponent( - text: text, - textRenderer: textRenderer, - position: Vector2(100, 50), - anchor: Anchor.center, - ), - ], - ); + button: RectangleComponent( + size: Vector2(200, 100), + paint: Paint() + ..color = Colors.orange + ..strokeWidth = 2 + ..style = PaintingStyle.stroke, + ), + buttonDown: RectangleComponent( + size: Vector2(200, 100), + paint: Paint() + ..color = BasicPalette.orange.color.withValues(alpha: 0.5), + ), + children: [ + TextComponent( + text: text, + textRenderer: textRenderer, + position: Vector2(100, 50), + anchor: Anchor.center, + ), + ], + ); } diff --git a/examples/lib/stories/camera_and_viewport/follow_component_example.dart b/examples/lib/stories/camera_and_viewport/follow_component_example.dart index fd4303dd2..ae0e25fa7 100644 --- a/examples/lib/stories/camera_and_viewport/follow_component_example.dart +++ b/examples/lib/stories/camera_and_viewport/follow_component_example.dart @@ -24,12 +24,12 @@ class FollowComponentExample extends FlameGame '''; FollowComponentExample({required this.viewportResolution}) - : super( - camera: CameraComponent.withFixedResolution( - width: viewportResolution.x, - height: viewportResolution.y, - ), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: viewportResolution.x, + height: viewportResolution.y, + ), + ); late MovableEmber ember; final Vector2 viewportResolution; @@ -182,12 +182,12 @@ class Map extends Component { class Rock extends SpriteComponent with HasGameReference, TapCallbacks { Rock(Vector2 position) - : super( - position: position, - size: Vector2.all(50), - priority: 1, - anchor: Anchor.center, - ); + : super( + position: position, + size: Vector2.all(50), + priority: 1, + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/examples/lib/stories/camera_and_viewport/static_components_example.dart b/examples/lib/stories/camera_and_viewport/static_components_example.dart index 3b0fb1fd7..0866264a9 100644 --- a/examples/lib/stories/camera_and_viewport/static_components_example.dart +++ b/examples/lib/stories/camera_and_viewport/static_components_example.dart @@ -22,12 +22,12 @@ class StaticComponentsExample extends FlameGame StaticComponentsExample({ required Vector2 viewportResolution, }) : super( - camera: CameraComponent.withFixedResolution( - width: viewportResolution.x, - height: viewportResolution.y, - ), - world: _StaticComponentWorld(), - ); + camera: CameraComponent.withFixedResolution( + width: viewportResolution.x, + height: viewportResolution.y, + ), + world: _StaticComponentWorld(), + ); @override Future onLoad() async { diff --git a/examples/lib/stories/collision_detection/circles_example.dart b/examples/lib/stories/collision_detection/circles_example.dart index 4dc288465..6be41741a 100644 --- a/examples/lib/stories/collision_detection/circles_example.dart +++ b/examples/lib/stories/collision_detection/circles_example.dart @@ -12,10 +12,10 @@ class CirclesExample extends FlameGame { '''; CirclesExample() - : super( - camera: CameraComponent.withFixedResolution(width: 600, height: 400), - world: MyWorld(), - ); + : super( + camera: CameraComponent.withFixedResolution(width: 600, height: 400), + world: MyWorld(), + ); } class MyWorld extends World with TapCallbacks, HasCollisionDetection { @@ -30,7 +30,7 @@ class MyWorld extends World with TapCallbacks, HasCollisionDetection { class MyCollidable extends PositionComponent with HasGameReference, CollisionCallbacks { MyCollidable({super.position}) - : super(size: Vector2.all(30), anchor: Anchor.center); + : super(size: Vector2.all(30), anchor: Anchor.center); late Vector2 velocity; final _collisionColor = Colors.amber; diff --git a/examples/lib/stories/collision_detection/collidable_animation_example.dart b/examples/lib/stories/collision_detection/collidable_animation_example.dart index 73d77420f..9bb0af494 100644 --- a/examples/lib/stories/collision_detection/collidable_animation_example.dart +++ b/examples/lib/stories/collision_detection/collidable_animation_example.dart @@ -62,11 +62,11 @@ class AnimatedComponent extends SpriteAnimationComponent Vector2 size, { double angle = -pi / 4, }) : super( - position: position, - size: size, - angle: angle, - anchor: Anchor.center, - ); + position: position, + size: size, + angle: angle, + anchor: Anchor.center, + ); @override Future onLoad() async { @@ -82,15 +82,15 @@ class AnimatedComponent extends SpriteAnimationComponent ..style = PaintingStyle.stroke; add( PolygonHitbox.relative( - [ - Vector2(0.0, -1.0), - Vector2(-1.0, -0.1), - Vector2(-0.2, 0.4), - Vector2(0.2, 0.4), - Vector2(1.0, -0.1), - ], - parentSize: size, - ) + [ + Vector2(0.0, -1.0), + Vector2(-1.0, -0.1), + Vector2(-0.2, 0.4), + Vector2(0.2, 0.4), + Vector2(1.0, -0.1), + ], + parentSize: size, + ) ..paint = hitboxPaint ..renderShape = true, ); diff --git a/examples/lib/stories/collision_detection/collision_detection.dart b/examples/lib/stories/collision_detection/collision_detection.dart index 108f5ecc7..c13383965 100644 --- a/examples/lib/stories/collision_detection/collision_detection.dart +++ b/examples/lib/stories/collision_detection/collision_detection.dart @@ -19,8 +19,9 @@ void addCollisionDetectionStories(Dashbook dashbook) { ..add( 'Collidable AnimationComponent', (_) => GameWidget(game: CollidableAnimationExample()), - codeLink: - baseLink('collision_detection/collidable_animation_example.dart'), + codeLink: baseLink( + 'collision_detection/collidable_animation_example.dart', + ), info: CollidableAnimationExample.description, ) ..add( @@ -74,8 +75,9 @@ void addCollisionDetectionStories(Dashbook dashbook) { ..add( 'Raycasting Max Distance', (_) => GameWidget(game: RaycastMaxDistanceExample()), - codeLink: - baseLink('collision_detection/raycast_max_distance_example.dart'), + codeLink: baseLink( + 'collision_detection/raycast_max_distance_example.dart', + ), info: RaycastMaxDistanceExample.description, ) ..add( diff --git a/examples/lib/stories/collision_detection/multiple_shapes_example.dart b/examples/lib/stories/collision_detection/multiple_shapes_example.dart index 5545a2018..673f29ff8 100644 --- a/examples/lib/stories/collision_detection/multiple_shapes_example.dart +++ b/examples/lib/stories/collision_detection/multiple_shapes_example.dart @@ -25,10 +25,10 @@ class MultipleShapesExample extends FlameGame with HasCollisionDetection { '''; MultipleShapesExample() - : super( - world: MultiShapesWorld(), - camera: CameraComponent()..viewfinder.anchor = Anchor.topLeft, - ); + : super( + world: MultiShapesWorld(), + camera: CameraComponent()..viewfinder.anchor = Anchor.topLeft, + ); } class MultiShapesWorld extends World with HasGameReference { @@ -67,7 +67,8 @@ class MultiShapesWorld extends World with HasGameReference { ScreenHitbox screenHitbox, ) { final collidableSize = Vector2.all(50) + Vector2.random(_rng) * 100; - final isXOverflow = lastCollidable.position.x + + final isXOverflow = + lastCollidable.position.x + lastCollidable.size.x / 2 + _distance.x + collidableSize.x > @@ -223,7 +224,7 @@ class SnowmanPart extends CircleHitbox { final Color hitColor; SnowmanPart(double radius, Vector2 position, this.hitColor) - : super(radius: radius, position: position, anchor: Anchor.center) { + : super(radius: radius, position: position, anchor: Anchor.center) { paint.color = startColor; } @@ -288,12 +289,23 @@ MyCollidable randomCollidable( final rotationSpeed = 0.5 - rng.nextDouble(); final shapeType = Shapes.values[rng.nextInt(Shapes.values.length)]; return switch (shapeType) { - Shapes.circle => CollidableCircle(position, size, velocity, screenHitbox) - ..rotationSpeed = rotationSpeed, - Shapes.rectangle => - CollidableRectangle(position, size, velocity, screenHitbox) - ..rotationSpeed = rotationSpeed, - Shapes.polygon => CollidablePolygon(position, size, velocity, screenHitbox) - ..rotationSpeed = rotationSpeed, + Shapes.circle => CollidableCircle( + position, + size, + velocity, + screenHitbox, + )..rotationSpeed = rotationSpeed, + Shapes.rectangle => CollidableRectangle( + position, + size, + velocity, + screenHitbox, + )..rotationSpeed = rotationSpeed, + Shapes.polygon => CollidablePolygon( + position, + size, + velocity, + screenHitbox, + )..rotationSpeed = rotationSpeed, }; } diff --git a/examples/lib/stories/collision_detection/quadtree_example.dart b/examples/lib/stories/collision_detection/quadtree_example.dart index 98aa77f8e..aacc93e35 100644 --- a/examples/lib/stories/collision_detection/quadtree_example.dart +++ b/examples/lib/stories/collision_detection/quadtree_example.dart @@ -229,8 +229,10 @@ class Player extends SpriteComponent Set intersectionPoints, PositionComponent other, ) { - final myCenter = - Vector2(position.x + tileSize / 2, position.y + tileSize / 2); + final myCenter = Vector2( + position.x + tileSize / 2, + position.y + tileSize / 2, + ); if (other is GameCollidable) { final diffX = myCenter.x - other.cachedCenter.x; if (diffX < 0) { @@ -348,8 +350,10 @@ mixin GameCollidable on PositionComponent { } void initCenter() { - cachedCenter = - Vector2(position.x + tileSize / 2, position.y + tileSize / 2); + cachedCenter = Vector2( + position.x + tileSize / 2, + position.y + tileSize / 2, + ); } late final Vector2 cachedCenter; @@ -430,4 +434,5 @@ class QuadTreeDebugComponent extends PositionComponent with HasPaint { } } } + //#endregion diff --git a/examples/lib/stories/collision_detection/rays_in_shape_example.dart b/examples/lib/stories/collision_detection/rays_in_shape_example.dart index 28f6171f7..24d323e46 100644 --- a/examples/lib/stories/collision_detection/rays_in_shape_example.dart +++ b/examples/lib/stories/collision_detection/rays_in_shape_example.dart @@ -21,13 +21,13 @@ shape it will be gray. '''; RaysInShapeExample() - : super( - world: RaysInShapeWorld(), - camera: CameraComponent.withFixedResolution( - width: playArea.width, - height: playArea.height, - ), - ); + : super( + world: RaysInShapeWorld(), + camera: CameraComponent.withFixedResolution( + width: playArea.width, + height: playArea.height, + ), + ); } final whiteStroke = Paint() @@ -55,13 +55,14 @@ class RaysInShapeWorld extends World List _rays = []; List randomRays(int count) => List.generate( - count, - (index) => Ray2( - origin: (Vector2.random(_rng)) * playArea.size.width - - playArea.size.toVector2() / 2, - direction: (Vector2.random(_rng) - Vector2(0.5, 0.5)).normalized(), - ), - ); + count, + (index) => Ray2( + origin: + (Vector2.random(_rng)) * playArea.size.width - + playArea.size.toVector2() / 2, + direction: (Vector2.random(_rng) - Vector2(0.5, 0.5)).normalized(), + ), + ); int _componentIndex = 0; @@ -84,16 +85,16 @@ class RaysInShapeWorld extends World position: Vector2.zero(), children: [ PolygonHitbox.relative( - [ - Vector2(-0.7, -1), - Vector2(1, -0.4), - Vector2(0.3, 1), - Vector2(-1, 0.6), - ], - parentSize: Vector2(100, 100), - anchor: Anchor.center, - position: Vector2.zero(), - ) + [ + Vector2(-0.7, -1), + Vector2(1, -0.4), + Vector2(0.3, 1), + Vector2(-1, 0.6), + ], + parentSize: Vector2(100, 100), + anchor: Anchor.center, + position: Vector2.zero(), + ) ..paint = whiteStroke ..renderShape = true, ], diff --git a/examples/lib/stories/collision_detection/raytrace_example.dart b/examples/lib/stories/collision_detection/raytrace_example.dart index 9e4efdb95..76a7fe05c 100644 --- a/examples/lib/stories/collision_detection/raytrace_example.dart +++ b/examples/lib/stories/collision_detection/raytrace_example.dart @@ -63,63 +63,62 @@ bounce on will appear. _timePassed = 0; if (extraChildren.isEmpty) { addAll( - extraChildren - ..addAll( - [ - CircleComponent( - position: Vector2(100, 100), - radius: 50, - paint: boxPaint, - children: [CircleHitbox()], - ), - CircleComponent( - position: Vector2(150, 500), - radius: 50, - paint: boxPaint, - anchor: Anchor.center, - children: [CircleHitbox()], - ), - CircleComponent( - position: Vector2(150, 500), - radius: 150, - paint: boxPaint, - anchor: Anchor.center, - children: [CircleHitbox()], - ), - RectangleComponent( - position: Vector2.all(300), - size: Vector2.all(100), - paint: boxPaint, - children: [RectangleHitbox()], - ), - RectangleComponent( - position: Vector2.all(500), - size: Vector2(100, 200), - paint: boxPaint, - children: [RectangleHitbox()], - ), - CircleComponent( - position: Vector2(650, 275), - radius: 50, - paint: boxPaint, - anchor: Anchor.center, - children: [CircleHitbox()], - ), - RectangleComponent( - position: Vector2(550, 200), - size: Vector2(200, 150), - paint: boxPaint, - children: [RectangleHitbox()], - ), - RectangleComponent( - position: Vector2(350, 30), - size: Vector2(200, 150), - paint: boxPaint, - angle: tau / 10, - children: [RectangleHitbox()], - ), - ], - ), + extraChildren..addAll( + [ + CircleComponent( + position: Vector2(100, 100), + radius: 50, + paint: boxPaint, + children: [CircleHitbox()], + ), + CircleComponent( + position: Vector2(150, 500), + radius: 50, + paint: boxPaint, + anchor: Anchor.center, + children: [CircleHitbox()], + ), + CircleComponent( + position: Vector2(150, 500), + radius: 150, + paint: boxPaint, + anchor: Anchor.center, + children: [CircleHitbox()], + ), + RectangleComponent( + position: Vector2.all(300), + size: Vector2.all(100), + paint: boxPaint, + children: [RectangleHitbox()], + ), + RectangleComponent( + position: Vector2.all(500), + size: Vector2(100, 200), + paint: boxPaint, + children: [RectangleHitbox()], + ), + CircleComponent( + position: Vector2(650, 275), + radius: 50, + paint: boxPaint, + anchor: Anchor.center, + children: [CircleHitbox()], + ), + RectangleComponent( + position: Vector2(550, 200), + size: Vector2(200, 150), + paint: boxPaint, + children: [RectangleHitbox()], + ), + RectangleComponent( + position: Vector2(350, 30), + size: Vector2(200, 150), + paint: boxPaint, + angle: tau / 10, + children: [RectangleHitbox()], + ), + ], + ), ); } else { removeAll(extraChildren); diff --git a/examples/lib/stories/components/clip_component_example.dart b/examples/lib/stories/components/clip_component_example.dart index 69253cde8..3a3773e16 100644 --- a/examples/lib/stories/components/clip_component_example.dart +++ b/examples/lib/stories/components/clip_component_example.dart @@ -5,7 +5,7 @@ import 'package:flame/game.dart'; class TappableEmber extends Ember with TapCallbacks { TappableEmber({required Vector2 position, required Vector2 size}) - : super(position: position, size: size); + : super(position: position, size: size); @override bool onTapDown(TapDownEvent event) { diff --git a/examples/lib/stories/components/components.dart b/examples/lib/stories/components/components.dart index ef93fc4e8..12b2c1e9f 100644 --- a/examples/lib/stories/components/components.dart +++ b/examples/lib/stories/components/components.dart @@ -62,8 +62,9 @@ void addComponentsStories(Dashbook dashbook) { ..add( 'Component Notifier (with provider)', (_) => const ComponentsNotifierProviderExampleWidget(), - codeLink: - baseLink('components/components_notifier_provider_example.dart'), + codeLink: baseLink( + 'components/components_notifier_provider_example.dart', + ), info: ComponentsNotifierProviderExampleWidget.description, ) ..add( diff --git a/examples/lib/stories/components/components_notifier_example.dart b/examples/lib/stories/components/components_notifier_example.dart index e2baf807f..39bed1bde 100644 --- a/examples/lib/stories/components/components_notifier_example.dart +++ b/examples/lib/stories/components/components_notifier_example.dart @@ -86,10 +86,10 @@ class GameHud extends StatelessWidget { class Enemy extends CircleComponent with TapCallbacks, Notifier { Enemy({super.position}) - : super( - radius: 20, - paint: Paint()..color = const Color(0xFFFF0000), - ); + : super( + radius: 20, + paint: Paint()..color = const Color(0xFFFF0000), + ); @override void onTapUp(_) { diff --git a/examples/lib/stories/components/components_notifier_provider_example.dart b/examples/lib/stories/components/components_notifier_provider_example.dart index b21bd6180..9d0d50b06 100644 --- a/examples/lib/stories/components/components_notifier_provider_example.dart +++ b/examples/lib/stories/components/components_notifier_provider_example.dart @@ -80,10 +80,10 @@ class GameHud extends StatelessWidget { class Enemy extends CircleComponent with TapCallbacks, Notifier { Enemy({super.position}) - : super( - radius: 20, - paint: Paint()..color = const Color(0xFFFF0000), - ); + : super( + radius: 20, + paint: Paint()..color = const Color(0xFFFF0000), + ); @override void onTapUp(_) { diff --git a/examples/lib/stories/components/composability_example.dart b/examples/lib/stories/components/composability_example.dart index 08eb1b9a6..516b25f0b 100644 --- a/examples/lib/stories/components/composability_example.dart +++ b/examples/lib/stories/components/composability_example.dart @@ -35,11 +35,11 @@ class ParentSquare extends RectangleComponent with HasGameReference { ..style = PaintingStyle.stroke; ParentSquare(Vector2 position, Vector2 size) - : super( - position: position, - size: size, - paint: defaultPaint, - ); + : super( + position: position, + size: size, + paint: defaultPaint, + ); @override Future onLoad() async { diff --git a/examples/lib/stories/components/look_at_example.dart b/examples/lib/stories/components/look_at_example.dart index 5c851045e..947d0def0 100644 --- a/examples/lib/stories/components/look_at_example.dart +++ b/examples/lib/stories/components/look_at_example.dart @@ -12,7 +12,8 @@ import 'package:flutter/services.dart'; class LookAtExample extends FlameGame<_TapWorld> with HasKeyboardHandlerComponents { - static const description = 'This example demonstrates how a component can be ' + static const description = + 'This example demonstrates how a component can be ' 'made to look at a specific target using the lookAt method. Tap anywhere ' 'to change the target point for both the choppers. ' 'It also shows how nativeAngle can be used to make the component ' @@ -168,7 +169,8 @@ class _ChopperParent extends PositionComponent @override void update(double dt) { final angleTo = chopper.angleTo(game.world.target.position); - textBox.text = ''' + textBox.text = + ''' nativeAngle = ${chopper.nativeAngle.toStringAsFixed(2)} angleTo = ${angleTo.toStringAsFixed(2)} absoluteAngle = ${chopper.absoluteAngle.toStringAsFixed(2)} diff --git a/examples/lib/stories/components/look_at_smooth_example.dart b/examples/lib/stories/components/look_at_smooth_example.dart index 7d1e8ee47..9cc7f811f 100644 --- a/examples/lib/stories/components/look_at_smooth_example.dart +++ b/examples/lib/stories/components/look_at_smooth_example.dart @@ -10,7 +10,8 @@ import 'package:flame/sprite.dart'; import 'package:flutter/material.dart'; class LookAtSmoothExample extends FlameGame { - static const description = 'This example demonstrates how a component can be ' + static const description = + 'This example demonstrates how a component can be ' 'made to smoothly rotate towards a target using the angleTo method. ' 'Tap anywhere to change the target point for both the choppers. ' 'It also shows how nativeAngle can be used to make the component ' diff --git a/examples/lib/stories/components/priority_example.dart b/examples/lib/stories/components/priority_example.dart index daa4eef9c..8ecf43aac 100644 --- a/examples/lib/stories/components/priority_example.dart +++ b/examples/lib/stories/components/priority_example.dart @@ -10,24 +10,24 @@ class PriorityExample extends FlameGame { '''; PriorityExample() - : super( - children: [ - Square(Vector2(100, 100)), - Square(Vector2(160, 100)), - Square(Vector2(170, 150)), - Square(Vector2(110, 150)), - ], - ); + : super( + children: [ + Square(Vector2(100, 100)), + Square(Vector2(160, 100)), + Square(Vector2(170, 150)), + Square(Vector2(110, 150)), + ], + ); } class Square extends RectangleComponent with HasGameReference, TapCallbacks { Square(Vector2 position) - : super( - position: position, - size: Vector2.all(100), - paint: PaintExtension.random(withAlpha: 0.9, base: 100), - ); + : super( + position: position, + size: Vector2.all(100), + paint: PaintExtension.random(withAlpha: 0.9, base: 100), + ); @override void onTapDown(TapDownEvent event) { diff --git a/examples/lib/stories/components/spawn_component_example.dart b/examples/lib/stories/components/spawn_component_example.dart index 8f0c763a0..6e6f2acd3 100644 --- a/examples/lib/stories/components/spawn_component_example.dart +++ b/examples/lib/stories/components/spawn_component_example.dart @@ -22,26 +22,26 @@ class SpawnComponentWorld extends World with TapCallbacks { final position = info.localPosition; final shape = switch (shapeType) { Shapes.rectangle => Rectangle.fromCenter( - center: position, - size: Vector2.all(200), - ), + center: position, + size: Vector2.all(200), + ), Shapes.circle => Circle(position, 150), Shapes.polygon => Polygon( - [ - Vector2(-1.0, 0.0), - Vector2(-0.8, 0.6), - Vector2(0.0, 1.0), - Vector2(0.6, 0.9), - Vector2(1.0, 0.0), - Vector2(0.3, -0.2), - Vector2(0.0, -1.0), - Vector2(-0.8, -0.5), - ].map((vertex) { - return vertex - ..scale(200) - ..add(position); - }).toList(), - ), + [ + Vector2(-1.0, 0.0), + Vector2(-0.8, 0.6), + Vector2(0.0, 1.0), + Vector2(0.6, 0.9), + Vector2(1.0, 0.0), + Vector2(0.3, -0.2), + Vector2(0.0, -1.0), + Vector2(-0.8, -0.5), + ].map((vertex) { + return vertex + ..scale(200) + ..add(position); + }).toList(), + ), }; add( diff --git a/examples/lib/stories/components/time_scale_example.dart b/examples/lib/stories/components/time_scale_example.dart index 5c41b9fa0..567ffcbd9 100644 --- a/examples/lib/stories/components/time_scale_example.dart +++ b/examples/lib/stories/components/time_scale_example.dart @@ -15,12 +15,12 @@ class TimeScaleExample extends FlameGame 'This example shows how time scale can be used to control game speed.'; TimeScaleExample() - : super( - camera: CameraComponent.withFixedResolution( - width: 640, - height: 360, - ), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 640, + height: 360, + ), + ); final gameSpeedText = TextComponent( text: 'Time Scale: 1', @@ -82,8 +82,8 @@ class _Chopper extends SpriteAnimationComponent super.size, super.angle, super.anchor, - }) : _moveDirection = Vector2(0, 1)..rotate(angle ?? 0), - _initialPosition = position?.clone() ?? Vector2.zero(); + }) : _moveDirection = Vector2(0, 1)..rotate(angle ?? 0), + _initialPosition = position?.clone() ?? Vector2.zero(); final Vector2 _moveDirection; final _speed = 80.0; diff --git a/examples/lib/stories/effects/color_effect_example.dart b/examples/lib/stories/effects/color_effect_example.dart index de93f2286..e110ec5f5 100644 --- a/examples/lib/stories/effects/color_effect_example.dart +++ b/examples/lib/stories/effects/color_effect_example.dart @@ -20,17 +20,17 @@ class ColorEffectExample extends FlameGame with TapDetector { position: Vector2(180, 230), size: Vector2.all(100), )..add( - ColorEffect( - Colors.blue, - EffectController( - duration: 1.5, - reverseDuration: 1.5, - infinite: true, - ), - // Means, applies from 0% to 80% of the color - opacityTo: 0.8, + ColorEffect( + Colors.blue, + EffectController( + duration: 1.5, + reverseDuration: 1.5, + infinite: true, ), + // Means, applies from 0% to 80% of the color + opacityTo: 0.8, ), + ), ); } } diff --git a/examples/lib/stories/effects/effect_controllers_example.dart b/examples/lib/stories/effects/effect_controllers_example.dart index a79a2c327..97482d693 100644 --- a/examples/lib/stories/effects/effect_controllers_example.dart +++ b/examples/lib/stories/effects/effect_controllers_example.dart @@ -21,13 +21,13 @@ class EffectControllersExample extends FlameGame { '''; EffectControllersExample() - : super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - ), - world: _EffectControllerWorld(), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + ), + world: _EffectControllerWorld(), + ); } class _EffectControllerWorld extends World { @@ -38,11 +38,11 @@ class _EffectControllerWorld extends World { position: Vector2(-140, 0), size: 20, )..add( - MoveEffect.by( - Vector2(0, 20), - InfiniteEffectController(ZigzagEffectController(period: 1)), - ), + MoveEffect.by( + Vector2(0, 20), + InfiniteEffectController(ZigzagEffectController(period: 1)), ), + ), ); add( RectangleComponent.square( @@ -50,15 +50,15 @@ class _EffectControllerWorld extends World { size: 20, paint: Paint()..color = const Color(0xffffbc63), )..addAll([ - MoveEffect.by( - Vector2(0, 20), - InfiniteEffectController(ZigzagEffectController(period: 8 / 7)), - ), - MoveEffect.by( - Vector2(10, 0), - InfiniteEffectController(ZigzagEffectController(period: 2 / 3)), - ), - ]), + MoveEffect.by( + Vector2(0, 20), + InfiniteEffectController(ZigzagEffectController(period: 8 / 7)), + ), + MoveEffect.by( + Vector2(10, 0), + InfiniteEffectController(ZigzagEffectController(period: 2 / 3)), + ), + ]), ); add( @@ -67,11 +67,11 @@ class _EffectControllerWorld extends World { size: 20, paint: Paint()..color = const Color(0xffbeff63), )..add( - MoveEffect.by( - Vector2(0, 20), - InfiniteEffectController(SineEffectController(period: 1)), - ), + MoveEffect.by( + Vector2(0, 20), + InfiniteEffectController(SineEffectController(period: 1)), ), + ), ); add( RectangleComponent.square( @@ -79,16 +79,16 @@ class _EffectControllerWorld extends World { size: 10, paint: Paint()..color = const Color(0xffb663ff), )..addAll([ - MoveEffect.by( - Vector2(0, 20), - InfiniteEffectController(SineEffectController(period: 1)) - ..advance(0.25), - ), - MoveEffect.by( - Vector2(10, 0), - InfiniteEffectController(SineEffectController(period: 1)), - ), - ]), + MoveEffect.by( + Vector2(0, 20), + InfiniteEffectController(SineEffectController(period: 1)) + ..advance(0.25), + ), + MoveEffect.by( + Vector2(10, 0), + InfiniteEffectController(SineEffectController(period: 1)), + ), + ]), ); } } diff --git a/examples/lib/stories/effects/function_effect_example.dart b/examples/lib/stories/effects/function_effect_example.dart index 9820f01f2..7fd64e4e1 100644 --- a/examples/lib/stories/effects/function_effect_example.dart +++ b/examples/lib/stories/effects/function_effect_example.dart @@ -38,15 +38,15 @@ The robot will switch between running and idle animations over the duration of final functionEffect = FunctionEffect>( - (target, progress) { - if (progress > 0.7) { - target.current = RobotState.idle; - } else if (progress > 0.3) { - target.current = RobotState.running; - } - }, - EffectController(duration: 10.0, infinite: true), - ); + (target, progress) { + if (progress > 0.7) { + target.current = RobotState.idle; + } else if (progress > 0.3) { + target.current = RobotState.running; + } + }, + EffectController(duration: 10.0, infinite: true), + ); final component = SpriteAnimationGroupComponent( animations: { RobotState.running: running, diff --git a/examples/lib/stories/effects/glow_effect_example.dart b/examples/lib/stories/effects/glow_effect_example.dart index f66b6201a..47e3cbb52 100644 --- a/examples/lib/stories/effects/glow_effect_example.dart +++ b/examples/lib/stories/effects/glow_effect_example.dart @@ -25,15 +25,15 @@ class GlowEffectExample extends FlameGame with TapDetector { position: Vector2(300, 400), paint: paint, )..add( - GlowEffect( - 10.0, - EffectController( - duration: 3, - reverseDuration: 1.5, - infinite: true, - ), + GlowEffect( + 10.0, + EffectController( + duration: 3, + reverseDuration: 1.5, + infinite: true, ), ), + ), ); } } diff --git a/examples/lib/stories/effects/move_effect_example.dart b/examples/lib/stories/effects/move_effect_example.dart index 0dfe91aa7..7049ed9d1 100644 --- a/examples/lib/stories/effects/move_effect_example.dart +++ b/examples/lib/stories/effects/move_effect_example.dart @@ -23,13 +23,13 @@ class MoveEffectExample extends FlameGame { '''; MoveEffectExample() - : super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - )..viewfinder.anchor = Anchor.topLeft, - world: _MoveEffectWorld(), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + )..viewfinder.anchor = Anchor.topLeft, + world: _MoveEffectWorld(), + ); } class _MoveEffectWorld extends World { @@ -52,25 +52,25 @@ class _MoveEffectWorld extends World { size: 20, paint: paint1, )..add( - MoveEffect.to( - Vector2(380, 50), - EffectController( - duration: 3, - reverseDuration: 3, - infinite: true, - curve: Curves.easeOut, - ), + MoveEffect.to( + Vector2(380, 50), + EffectController( + duration: 3, + reverseDuration: 3, + infinite: true, + curve: Curves.easeOut, ), ), + ), ); // Green square, moving and jumping add( RectangleComponent.square( - position: Vector2(20, 150), - size: 20, - paint: paint2, - ) + position: Vector2(20, 150), + size: 20, + paint: paint2, + ) ..add( MoveEffect.to( Vector2(380, 150), @@ -103,27 +103,27 @@ class _MoveEffectWorld extends World { position: Vector2(40, 240), paint: paint3, )..add( - SequenceEffect( - [ - MoveEffect.by( - Vector2(5, 0), - NoiseEffectController( - duration: 1, - noise: PerlinNoise(frequency: 20), - ), + SequenceEffect( + [ + MoveEffect.by( + Vector2(5, 0), + NoiseEffectController( + duration: 1, + noise: PerlinNoise(frequency: 20), ), - MoveEffect.by(Vector2.zero(), LinearEffectController(2)), - MoveEffect.by( - Vector2(0, 10), - NoiseEffectController( - duration: 1, - noise: PerlinNoise(frequency: 10), - ), + ), + MoveEffect.by(Vector2.zero(), LinearEffectController(2)), + MoveEffect.by( + Vector2(0, 10), + NoiseEffectController( + duration: 1, + noise: PerlinNoise(frequency: 10), ), - ], - infinite: true, - ), + ), + ], + infinite: true, ), + ), ); // A circle of moving rectangles. diff --git a/examples/lib/stories/effects/opacity_effect_example.dart b/examples/lib/stories/effects/opacity_effect_example.dart index 736263438..0d0df2a2d 100644 --- a/examples/lib/stories/effects/opacity_effect_example.dart +++ b/examples/lib/stories/effects/opacity_effect_example.dart @@ -29,14 +29,14 @@ class OpacityEffectExample extends FlameGame with TapDetector { position: Vector2(180, 230), size: Vector2.all(100), )..add( - OpacityEffect.fadeOut( - EffectController( - duration: 1.5, - reverseDuration: 1.5, - infinite: true, - ), + OpacityEffect.fadeOut( + EffectController( + duration: 1.5, + reverseDuration: 1.5, + infinite: true, ), ), + ), ); } diff --git a/examples/lib/stories/effects/remove_effect_example.dart b/examples/lib/stories/effects/remove_effect_example.dart index af7c22ade..0ea430238 100644 --- a/examples/lib/stories/effects/remove_effect_example.dart +++ b/examples/lib/stories/effects/remove_effect_example.dart @@ -13,13 +13,13 @@ class RemoveEffectExample extends FlameGame { '''; RemoveEffectExample() - : super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - )..viewfinder.anchor = Anchor.topLeft, - world: _RemoveEffectWorld(), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + )..viewfinder.anchor = Anchor.topLeft, + world: _RemoveEffectWorld(), + ); } class _RemoveEffectWorld extends World { @@ -35,7 +35,7 @@ class _RemoveEffectWorld extends World { class _RandomCircle extends CircleComponent with TapCallbacks { _RandomCircle(double radius, {super.position, super.paint}) - : super(radius: radius); + : super(radius: radius); factory _RandomCircle.random(Random rng) { final radius = rng.nextDouble() * 30 + 10; diff --git a/examples/lib/stories/effects/rotate_around_effect_example.dart b/examples/lib/stories/effects/rotate_around_effect_example.dart index bf32ca259..d0b0f2f22 100644 --- a/examples/lib/stories/effects/rotate_around_effect_example.dart +++ b/examples/lib/stories/effects/rotate_around_effect_example.dart @@ -15,13 +15,13 @@ around a fixed point. '''; RotateAroundEffectExample() - : super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - ), - world: _RotateAroundEffectWorld(), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + ), + world: _RotateAroundEffectWorld(), + ); } class _RotateAroundEffectWorld extends World { @@ -30,19 +30,20 @@ class _RotateAroundEffectWorld extends World { add(_GlowingBall(position: Vector2.zero(), radius: 30)); final rotatingBalls = List.generate( 4, - (i) => _GlowingBall( - position: Vector2(100 + 10.0 * i, 0), - radius: 10, - )..add( - RotateAroundEffect( - tau, - center: Vector2.zero(), - EffectController( - speed: 0.4 + 1.02 * i, - infinite: true, + (i) => + _GlowingBall( + position: Vector2(100 + 10.0 * i, 0), + radius: 10, + )..add( + RotateAroundEffect( + tau, + center: Vector2.zero(), + EffectController( + speed: 0.4 + 1.02 * i, + infinite: true, + ), ), ), - ), ); addAll(rotatingBalls); } diff --git a/examples/lib/stories/effects/rotate_effect_example.dart b/examples/lib/stories/effects/rotate_effect_example.dart index 2de51f70a..115b5f24f 100644 --- a/examples/lib/stories/effects/rotate_effect_example.dart +++ b/examples/lib/stories/effects/rotate_effect_example.dart @@ -18,13 +18,13 @@ class RotateEffectExample extends FlameGame { '''; RotateEffectExample() - : super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - ), - world: _RotateEffectWorld(), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + ), + world: _RotateEffectWorld(), + ); } class _RotateEffectWorld extends World { @@ -79,11 +79,11 @@ class _RotateEffectWorld extends World { class Compass extends PositionComponent { Compass({required double size}) - : _radius = size / 2, - super( - size: Vector2.all(size), - anchor: Anchor.center, - ); + : _radius = size / 2, + super( + size: Vector2.all(size), + anchor: Anchor.center, + ); late PositionComponent arrow; late PositionComponent rim; @@ -130,10 +130,10 @@ class Compass extends PositionComponent { class CompassArrow extends PositionComponent { CompassArrow({required double width, required double radius}) - : assert(width <= radius, 'The width is larger than the radius'), - _radius = radius, - _width = width, - super(size: Vector2(width, 2 * radius), anchor: Anchor.center); + : assert(width <= radius, 'The width is larger than the radius'), + _radius = radius, + _width = width, + super(size: Vector2(width, 2 * radius), anchor: Anchor.center); final double _radius; final double _width; @@ -165,13 +165,13 @@ class CompassArrow extends PositionComponent { class CompassRim extends PositionComponent { CompassRim({required double radius, required double width}) - : assert(radius > width, 'The width is larger than the radius'), - _radius = radius, - _width = width, - super( - size: Vector2.all(2 * radius), - anchor: Anchor.center, - ); + : assert(radius > width, 'The width is larger than the radius'), + _radius = radius, + _width = width, + super( + size: Vector2.all(2 * radius), + anchor: Anchor.center, + ); static const int numberOfNotches = 144; final double _radius; diff --git a/examples/lib/stories/effects/sequence_effect_example.dart b/examples/lib/stories/effects/sequence_effect_example.dart index ea3f15e73..6da951d26 100644 --- a/examples/lib/stories/effects/sequence_effect_example.dart +++ b/examples/lib/stories/effects/sequence_effect_example.dart @@ -38,17 +38,17 @@ class SequenceEffectExample extends FlameGame { class Player extends PositionComponent { Player() - : path = Path() - ..lineTo(40, 20) - ..lineTo(0, 40) - ..quadraticBezierTo(8, 20, 0, 0) - ..close(), - bodyPaint = Paint()..color = const Color(0x887F99B3), - borderPaint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 3 - ..color = const Color(0xFFFFFD9A), - super(anchor: Anchor.center, size: Vector2(40, 40)); + : path = Path() + ..lineTo(40, 20) + ..lineTo(0, 40) + ..quadraticBezierTo(8, 20, 0, 0) + ..close(), + bodyPaint = Paint()..color = const Color(0x887F99B3), + borderPaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 3 + ..color = const Color(0xFFFFFD9A), + super(anchor: Anchor.center, size: Vector2(40, 40)); final Path path; final Paint borderPaint; diff --git a/examples/lib/stories/experimental/shapes.dart b/examples/lib/stories/experimental/shapes.dart index f08eb3da8..718947782 100644 --- a/examples/lib/stories/experimental/shapes.dart +++ b/examples/lib/stories/experimental/shapes.dart @@ -47,18 +47,18 @@ class ShapesExample extends FlameGame { class ShapesComponent extends Component { ShapesComponent(this.shapes, List colors) - : assert( - shapes.length == colors.length, - 'The shapes and colors lists have to be of the same length', - ), - paints = colors - .map( - (color) => Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 1 - ..color = color, - ) - .toList(); + : assert( + shapes.length == colors.length, + 'The shapes and colors lists have to be of the same length', + ), + paints = colors + .map( + (color) => Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = color, + ) + .toList(); final List shapes; final List paints; @@ -73,10 +73,10 @@ class ShapesComponent extends Component { class DotsComponent extends Component { DotsComponent(this.shapes, this.shapeColors) - : assert( - shapes.length == shapeColors.length, - 'The shapes and shapeColors lists have to be of the same length', - ); + : assert( + shapes.length == shapeColors.length, + 'The shapes and shapeColors lists have to be of the same length', + ); final List shapes; final List shapeColors; diff --git a/examples/lib/stories/input/double_tap_callbacks_example.dart b/examples/lib/stories/input/double_tap_callbacks_example.dart index df8190d81..03a6d3a12 100644 --- a/examples/lib/stories/input/double_tap_callbacks_example.dart +++ b/examples/lib/stories/input/double_tap_callbacks_example.dart @@ -18,9 +18,9 @@ class DoubleTapCallbacksExample extends FlameGame with DoubleTapCallbacks { @override void onGameResize(Vector2 size) { - children - .query() - .forEach((element) => element.removeFromParent()); + children.query().forEach( + (element) => element.removeFromParent(), + ); add(DoubleTappableEmber(position: size / 2)); super.onGameResize(size); @@ -43,10 +43,10 @@ class DoubleTappableEmber extends Ember with DoubleTapCallbacks { bool debugMode = true; DoubleTappableEmber({Vector2? position}) - : super( - position: position ?? Vector2.all(100), - size: Vector2.all(100), - ); + : super( + position: position ?? Vector2.all(100), + size: Vector2.all(100), + ); @override void onDoubleTapUp(DoubleTapEvent event) { diff --git a/examples/lib/stories/input/gesture_hitboxes_example.dart b/examples/lib/stories/input/gesture_hitboxes_example.dart index 817c60719..1c06ddd05 100644 --- a/examples/lib/stories/input/gesture_hitboxes_example.dart +++ b/examples/lib/stories/input/gesture_hitboxes_example.dart @@ -31,14 +31,14 @@ class _GestureHitboxesWorld extends World with TapCallbacks { Shapes.circle => CircleHitbox(), Shapes.rectangle => RectangleHitbox(), Shapes.polygon => PolygonHitbox.relative( - [ - -Vector2.random(_rng), - Vector2.random(_rng)..x *= -1, - Vector2.random(_rng), - Vector2.random(_rng)..y *= -1, - ], - parentSize: shapeSize, - ), + [ + -Vector2.random(_rng), + Vector2.random(_rng)..x *= -1, + Vector2.random(_rng), + Vector2.random(_rng)..y *= -1, + ], + parentSize: shapeSize, + ), }; return MyShapeComponent( hitbox: hitbox, diff --git a/examples/lib/stories/input/hover_callbacks_example.dart b/examples/lib/stories/input/hover_callbacks_example.dart index 4d754e9d0..6440ba12b 100644 --- a/examples/lib/stories/input/hover_callbacks_example.dart +++ b/examples/lib/stories/input/hover_callbacks_example.dart @@ -37,11 +37,11 @@ class HoverSquare extends PositionComponent with HoverCallbacks { static final Paint _grey = Paint()..color = const Color(0xFFA5A5A5); HoverSquare(Vector2 position) - : super( - position: position, - size: Vector2.all(100), - anchor: Anchor.center, - ); + : super( + position: position, + size: Vector2.all(100), + anchor: Anchor.center, + ); @override void render(Canvas canvas) { diff --git a/examples/lib/stories/input/joystick_advanced_example.dart b/examples/lib/stories/input/joystick_advanced_example.dart index 99dd1c38d..fc7b1b65f 100644 --- a/examples/lib/stories/input/joystick_advanced_example.dart +++ b/examples/lib/stories/input/joystick_advanced_example.dart @@ -21,9 +21,9 @@ class JoystickAdvancedExample extends FlameGame with HasCollisionDetection { '''; JoystickAdvancedExample() - : super( - camera: CameraComponent.withFixedResolution(width: 1200, height: 800), - ); + : super( + camera: CameraComponent.withFixedResolution(width: 1200, height: 800), + ); late final JoystickPlayer player; late final JoystickComponent joystick; @@ -200,8 +200,10 @@ class JoystickAdvancedExample extends FlameGame with HasCollisionDetection { void update(double dt) { super.update(dt); speedText.text = 'Speed: ${(joystick.intensity * player.maxSpeed).round()}'; - final direction = - joystick.direction.toString().replaceAll('JoystickDirection.', ''); + final direction = joystick.direction.toString().replaceAll( + 'JoystickDirection.', + '', + ); directionText.text = 'Direction: $direction'; } } diff --git a/examples/lib/stories/input/joystick_player.dart b/examples/lib/stories/input/joystick_player.dart index 363c7e657..d7ca3b286 100644 --- a/examples/lib/stories/input/joystick_player.dart +++ b/examples/lib/stories/input/joystick_player.dart @@ -12,7 +12,7 @@ class JoystickPlayer extends SpriteComponent final JoystickComponent joystick; JoystickPlayer(this.joystick) - : super(size: Vector2.all(100.0), anchor: Anchor.center); + : super(size: Vector2.all(100.0), anchor: Anchor.center); @override Future onLoad() async { diff --git a/examples/lib/stories/input/overlapping_tap_callbacks_example.dart b/examples/lib/stories/input/overlapping_tap_callbacks_example.dart index 1bb5d649d..bc0344035 100644 --- a/examples/lib/stories/input/overlapping_tap_callbacks_example.dart +++ b/examples/lib/stories/input/overlapping_tap_callbacks_example.dart @@ -26,13 +26,13 @@ class OverlappingTapCallbacksExample extends FlameGame { class TapCallbacksSquare extends RectangleComponent with TapCallbacks { TapCallbacksSquare({Vector2? position, this.continuePropagation = false}) - : super( - position: position ?? Vector2.all(100), - size: Vector2.all(100), - paint: continuePropagation - ? (Paint()..color = Colors.green.withValues(alpha: 0.9)) - : PaintExtension.random(withAlpha: 0.9, base: 100), - ); + : super( + position: position ?? Vector2.all(100), + size: Vector2.all(100), + paint: continuePropagation + ? (Paint()..color = Colors.green.withValues(alpha: 0.9)) + : PaintExtension.random(withAlpha: 0.9, base: 100), + ); final bool continuePropagation; diff --git a/examples/lib/stories/input/tap_callbacks_example.dart b/examples/lib/stories/input/tap_callbacks_example.dart index a076e5872..3e95e2b0f 100644 --- a/examples/lib/stories/input/tap_callbacks_example.dart +++ b/examples/lib/stories/input/tap_callbacks_example.dart @@ -25,10 +25,10 @@ class TappableSquare extends PositionComponent with TapCallbacks { bool _beenPressed = false; TappableSquare({Vector2? position}) - : super( - position: position ?? Vector2.all(100), - size: Vector2.all(100), - ); + : super( + position: position ?? Vector2.all(100), + size: Vector2.all(100), + ); @override void render(Canvas canvas) { diff --git a/examples/lib/stories/layout/layout.dart b/examples/lib/stories/layout/layout.dart index 8c46c4cb9..91b27005d 100644 --- a/examples/lib/stories/layout/layout.dart +++ b/examples/lib/stories/layout/layout.dart @@ -4,7 +4,9 @@ import 'package:examples/stories/layout/align_component.dart'; import 'package:flame/game.dart'; void addLayoutStories(Dashbook dashbook) { - dashbook.storiesOf('Layout').add( + dashbook + .storiesOf('Layout') + .add( 'AlignComponent', (_) => GameWidget(game: AlignComponentExample()), codeLink: baseLink('layout/align_component.dart'), diff --git a/examples/lib/stories/rendering/isometric_tile_map_example.dart b/examples/lib/stories/rendering/isometric_tile_map_example.dart index 94ca0ac77..d80cf0751 100644 --- a/examples/lib/stories/rendering/isometric_tile_map_example.dart +++ b/examples/lib/stories/rendering/isometric_tile_map_example.dart @@ -84,10 +84,10 @@ class Selector extends SpriteComponent { bool show = true; Selector(double s, Image image) - : super( - sprite: Sprite(image, srcSize: Vector2.all(32.0)), - size: Vector2.all(s), - ); + : super( + sprite: Sprite(image, srcSize: Vector2.all(32.0)), + size: Vector2.all(s), + ); @override void render(Canvas canvas) { diff --git a/examples/lib/stories/rendering/particles_example.dart b/examples/lib/stories/rendering/particles_example.dart index 29380150b..86aa82aa3 100644 --- a/examples/lib/stories/rendering/particles_example.dart +++ b/examples/lib/stories/rendering/particles_example.dart @@ -327,7 +327,8 @@ class ParticlesExample extends FlameGame { Particle acceleratedParticles() { return Particle.generate( generator: (i) => AcceleratedParticle( - speed: Vector2( + speed: + Vector2( rnd.nextDouble() * 600 - 300, -rnd.nextDouble() * 600, ) * @@ -432,8 +433,9 @@ class ParticlesExample extends FlameGame { renderer: (canvas, particle) { final paint = randomElement(paints); // Override the color to dynamically update opacity - paint.color = - paint.color.withValues(alpha: 1 - particle.progress); + paint.color = paint.color.withValues( + alpha: 1 - particle.progress, + ); canvas.drawCircle( Offset.zero, diff --git a/examples/lib/stories/rendering/particles_interactive_example.dart b/examples/lib/stories/rendering/particles_interactive_example.dart index d491fd67b..c88ebe944 100644 --- a/examples/lib/stories/rendering/particles_interactive_example.dart +++ b/examples/lib/stories/rendering/particles_interactive_example.dart @@ -8,7 +8,8 @@ import 'package:flame/particles.dart'; import 'package:flutter/material.dart'; class ParticlesInteractiveExample extends FlameGame with PanDetector { - static const description = 'An example which shows how ' + static const description = + 'An example which shows how ' 'ParticleSystemComponent can be added in runtime ' 'following an event, in this example, the mouse ' 'dragging'; @@ -21,13 +22,13 @@ class ParticlesInteractiveExample extends FlameGame with PanDetector { required Color from, required Color to, required double zoom, - }) : colorTween = ColorTween(begin: from, end: to), - super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - )..viewfinder.zoom = zoom, - ); + }) : colorTween = ColorTween(begin: from, end: to), + super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + )..viewfinder.zoom = zoom, + ); @override void onPanUpdate(DragUpdateInfo info) { @@ -39,7 +40,8 @@ class ParticlesInteractiveExample extends FlameGame with PanDetector { generator: (i) { return AcceleratedParticle( lifespan: 2, - speed: Vector2( + speed: + Vector2( noise.transform(random.nextDouble()), noise.transform(random.nextDouble()), ) * diff --git a/examples/lib/stories/rendering/rich_text_example.dart b/examples/lib/stories/rendering/rich_text_example.dart index b05c5a137..b9ab45b32 100644 --- a/examples/lib/stories/rendering/rich_text_example.dart +++ b/examples/lib/stories/rendering/rich_text_example.dart @@ -50,8 +50,9 @@ class RichTextExample extends FlameGame { ), ParagraphNode.group([ PlainTextNode( - 'Suddenly, like a lump of submerged wreckage breaking the surface ' - 'of water, the thought burst into his mind: '), + 'Suddenly, like a lump of submerged wreckage breaking the surface ' + 'of water, the thought burst into his mind: ', + ), ItalicTextNode.group([ PlainTextNode('"It doesn\'t really happen. We imagine it. It is '), BoldTextNode.simple('hallucination'), diff --git a/examples/lib/stories/rendering/text_example.dart b/examples/lib/stories/rendering/text_example.dart index 14f5dad3c..41fc17aab 100644 --- a/examples/lib/stories/rendering/text_example.dart +++ b/examples/lib/stories/rendering/text_example.dart @@ -29,12 +29,12 @@ class TextExample extends FlameGame { ..anchor = Anchor.bottomRight ..position.setFrom(size), MyTextBox( - '"This is our world now. The world of the electron and the switch; ' - 'the beauty of the baud. We exist without nationality, skin color, ' - 'or religious bias. You wage wars, murder, cheat, lie to us and try ' - "to make us believe it's for our own good, yet we're the " - 'criminals. Yes, I am a criminal. My crime is that of curiosity."', - ) + '"This is our world now. The world of the electron and the switch; ' + 'the beauty of the baud. We exist without nationality, skin color, ' + 'or religious bias. You wage wars, murder, cheat, lie to us and ' + "try to make us believe it's for our own good, yet we're the " + 'criminals. Yes, I am a criminal. My crime is that of curiosity."', + ) ..anchor = Anchor.bottomLeft ..y = size.y, MyTextBox( @@ -124,15 +124,15 @@ class MyTextBox extends TextBoxComponent { double? timePerChar, double? margins, }) : super( - text: text, - textRenderer: _box, - boxConfig: TextBoxConfig( - maxWidth: 400, - timePerChar: timePerChar ?? 0.05, - growingBox: true, - margins: EdgeInsets.all(margins ?? 25), - ), - ); + text: text, + textRenderer: _box, + boxConfig: TextBoxConfig( + maxWidth: 400, + timePerChar: timePerChar ?? 0.05, + growingBox: true, + margins: EdgeInsets.all(margins ?? 25), + ), + ); @override Future onLoad() { diff --git a/examples/lib/stories/router/router.dart b/examples/lib/stories/router/router.dart index 359bfdc4a..a9daf69c2 100644 --- a/examples/lib/stories/router/router.dart +++ b/examples/lib/stories/router/router.dart @@ -4,7 +4,9 @@ import 'package:examples/stories/router/router_world_example.dart'; import 'package:flame/game.dart'; void addRouterStories(Dashbook dashbook) { - dashbook.storiesOf('Router').add( + dashbook + .storiesOf('Router') + .add( 'Router with multiple worlds', (_) => GameWidget(game: RouterWorldExample()), codeLink: baseLink('router/router_world_example.dart'), diff --git a/examples/lib/stories/router/router_world_example.dart b/examples/lib/stories/router/router_world_example.dart index aa53b9479..f908a721e 100644 --- a/examples/lib/stories/router/router_world_example.dart +++ b/examples/lib/stories/router/router_world_example.dart @@ -92,12 +92,12 @@ class RoundedButton extends PositionComponent with TapCallbacks { super.position, super.anchor = Anchor.center, }) : _textDrawable = TextPaint( - style: const TextStyle( - fontSize: 20, - color: Color(0xFF000000), - fontWeight: FontWeight.w800, - ), - ).toTextPainter(text) { + style: const TextStyle( + fontSize: 20, + color: Color(0xFF000000), + fontWeight: FontWeight.w800, + ), + ).toTextPainter(text) { size = Vector2(150, 40); _textOffset = Offset( (size.x - _textDrawable.width) / 2, @@ -186,15 +186,15 @@ abstract class SimpleButton extends PositionComponent with TapCallbacks { class BackButton extends SimpleButton with HasGameReference { BackButton() - : super( - Path() - ..moveTo(22, 8) - ..lineTo(10, 20) - ..lineTo(22, 32) - ..moveTo(12, 20) - ..lineTo(34, 20), - position: Vector2.all(10), - ); + : super( + Path() + ..moveTo(22, 8) + ..lineTo(10, 20) + ..lineTo(22, 32) + ..moveTo(12, 20) + ..lineTo(34, 20), + position: Vector2.all(10), + ); @override void action() => game.router.pop(); @@ -203,14 +203,14 @@ class BackButton extends SimpleButton class PauseButton extends SimpleButton with HasGameReference { PauseButton() - : super( - Path() - ..moveTo(14, 10) - ..lineTo(14, 30) - ..moveTo(26, 10) - ..lineTo(26, 30), - position: Vector2(60, 10), - ); + : super( + Path() + ..moveTo(14, 10) + ..lineTo(14, 30) + ..moveTo(26, 10) + ..lineTo(26, 30), + position: Vector2(60, 10), + ); bool isPaused = false; @@ -353,12 +353,12 @@ class Orbit extends CircleComponent { required this.planet, required this.revolutionPeriod, }) : super( - children: [planet], - anchor: Anchor.center, - paint: Paint() - ..style = PaintingStyle.stroke - ..color = const Color(0x888888aa), - ); + children: [planet], + anchor: Anchor.center, + paint: Paint() + ..style = PaintingStyle.stroke + ..color = const Color(0x888888aa), + ); final double revolutionPeriod; final Planet planet; diff --git a/examples/lib/stories/sprites/sprite_batch_load_example.dart b/examples/lib/stories/sprites/sprite_batch_load_example.dart index ed242a013..889e48b94 100644 --- a/examples/lib/stories/sprites/sprite_batch_load_example.dart +++ b/examples/lib/stories/sprites/sprite_batch_load_example.dart @@ -21,9 +21,9 @@ class SpriteBatchLoadExample extends FlameGame { class MySpriteBatchComponent extends SpriteBatchComponent with HasGameReference { MySpriteBatchComponent() - : super( - blendMode: BlendMode.srcOver, - ); + : super( + blendMode: BlendMode.srcOver, + ); @override Future onLoad() async { diff --git a/examples/lib/stories/sprites/sprite_sheet_example.dart b/examples/lib/stories/sprites/sprite_sheet_example.dart index 86c592acc..d58d1d23d 100644 --- a/examples/lib/stories/sprites/sprite_sheet_example.dart +++ b/examples/lib/stories/sprites/sprite_sheet_example.dart @@ -15,19 +15,25 @@ class SpriteSheetExample extends FlameGame { srcSize: Vector2(16.0, 18.0), ); - final vampireAnimation = - spriteSheet.createAnimation(row: 0, stepTime: 0.1, to: 7); - - final ghostAnimation = - spriteSheet.createAnimation(row: 1, stepTime: 0.1, to: 7); - - final ghostAnimationVariableStepTimes = - spriteSheet.createAnimationWithVariableStepTimes( - row: 1, + final vampireAnimation = spriteSheet.createAnimation( + row: 0, + stepTime: 0.1, to: 7, - stepTimes: [0.1, 0.1, 0.3, 0.3, 0.5, 0.3, 0.1], ); + final ghostAnimation = spriteSheet.createAnimation( + row: 1, + stepTime: 0.1, + to: 7, + ); + + final ghostAnimationVariableStepTimes = spriteSheet + .createAnimationWithVariableStepTimes( + row: 1, + to: 7, + stepTimes: [0.1, 0.1, 0.3, 0.3, 0.5, 0.3, 0.1], + ); + final customVampireAnimation = SpriteAnimation.fromFrameData( spriteSheet.image, SpriteAnimationData([ diff --git a/examples/lib/stories/structure/levels.dart b/examples/lib/stories/structure/levels.dart index 8dd3d3fc2..90e61f410 100644 --- a/examples/lib/stories/structure/levels.dart +++ b/examples/lib/stories/structure/levels.dart @@ -62,13 +62,12 @@ class ResettableLevel extends Level { @override Future onLoad() async { add( - Ember() - ..add( - ScaleEffect.by( - Vector2.all(3), - EffectController(duration: 1, alternate: true, infinite: true), - ), + Ember()..add( + ScaleEffect.by( + Vector2.all(3), + EffectController(duration: 1, alternate: true, infinite: true), ), + ), ); game.header.text = 'Resettable'; } @@ -110,19 +109,19 @@ class Level extends World with HasGameReference, TapCallbacks { class LevelButton extends ButtonComponent { LevelButton(String text, {super.onPressed, super.position}) - : super( - button: ButtonBackground(Colors.white), - buttonDown: ButtonBackground(Colors.orangeAccent), - children: [ - TextComponent( - text: text, - position: Vector2(60, 20), - anchor: Anchor.center, - ), - ], - size: Vector2(120, 40), - anchor: Anchor.center, - ); + : super( + button: ButtonBackground(Colors.white), + buttonDown: ButtonBackground(Colors.orangeAccent), + children: [ + TextComponent( + text: text, + position: Vector2(60, 20), + anchor: Anchor.center, + ), + ], + size: Vector2(120, 40), + anchor: Anchor.center, + ); } class ButtonBackground extends PositionComponent with HasAncestor { diff --git a/examples/lib/stories/structure/structure.dart b/examples/lib/stories/structure/structure.dart index e49660181..1ed533bbd 100644 --- a/examples/lib/stories/structure/structure.dart +++ b/examples/lib/stories/structure/structure.dart @@ -4,7 +4,9 @@ import 'package:examples/stories/structure/levels.dart'; import 'package:flame/game.dart'; void addStructureStories(Dashbook dashbook) { - dashbook.storiesOf('Structure').add( + dashbook + .storiesOf('Structure') + .add( 'Levels', (_) => GameWidget(game: LevelsExample()), info: LevelsExample.description, diff --git a/examples/lib/stories/svg/svg.dart b/examples/lib/stories/svg/svg.dart index 440a48b52..cb199b1a5 100644 --- a/examples/lib/stories/svg/svg.dart +++ b/examples/lib/stories/svg/svg.dart @@ -4,7 +4,9 @@ import 'package:examples/stories/svg/svg_component.dart'; import 'package:flame/game.dart'; void addSvgStories(Dashbook dashbook) { - dashbook.storiesOf('Svg').add( + dashbook + .storiesOf('Svg') + .add( 'Svg Component', (_) => GameWidget(game: SvgComponentExample()), codeLink: baseLink('svg/svg_component.dart'), diff --git a/examples/lib/stories/svg/svg_component.dart b/examples/lib/stories/svg/svg_component.dart index fa9f62e38..296b40053 100644 --- a/examples/lib/stories/svg/svg_component.dart +++ b/examples/lib/stories/svg/svg_component.dart @@ -36,11 +36,11 @@ class Player extends SvgComponent with HasGameReference { class Background extends SvgComponent with HasGameReference { Background() - : super( - priority: 1, - size: Vector2(745, 415), - anchor: Anchor.center, - ); + : super( + priority: 1, + size: Vector2(745, 415), + anchor: Anchor.center, + ); @override Future? onLoad() async { @@ -52,11 +52,11 @@ class Background extends SvgComponent class Balloons extends SvgComponent with HasGameReference { Balloons({super.position}) - : super( - priority: 2, - size: Vector2(75, 125), - anchor: Anchor.center, - ); + : super( + priority: 2, + size: Vector2(75, 125), + anchor: Anchor.center, + ); @override Future? onLoad() async { @@ -77,13 +77,13 @@ class SvgComponentExample extends FlameGame { '''; SvgComponentExample() - : super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - ), - world: _SvgComponentWorld(), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + ), + world: _SvgComponentWorld(), + ); } class _SvgComponentWorld extends World with TapCallbacks, DoubleTapCallbacks { diff --git a/examples/lib/stories/system/overlays_example.dart b/examples/lib/stories/system/overlays_example.dart index ab4b1453d..deb3fb7aa 100644 --- a/examples/lib/stories/system/overlays_example.dart +++ b/examples/lib/stories/system/overlays_example.dart @@ -24,8 +24,8 @@ class OverlaysExample extends FlameGame with TapDetector { add( SpriteAnimationComponent( - animation: animation, - ) + animation: animation, + ) ..position.y = size.y / 2 ..position.x = 100 ..anchor = Anchor.center @@ -96,10 +96,10 @@ Widget overlayBuilder(DashbookContext ctx) { game: OverlaysExample()..paused = true, overlayBuilderMap: { 'PauseMenu': (context, game) => _pauseMenuBuilder( - context, - game, - () => game.onTap(), - ), + context, + game, + () => game.onTap(), + ), 'SecondaryMenu': _secondaryMenuBuilder, }, initialActiveOverlays: const ['PauseMenu'], diff --git a/examples/lib/stories/system/pause_resume_example.dart b/examples/lib/stories/system/pause_resume_example.dart index f98dce005..f27c79c14 100644 --- a/examples/lib/stories/system/pause_resume_example.dart +++ b/examples/lib/stories/system/pause_resume_example.dart @@ -27,8 +27,8 @@ class PauseResumeExample extends FlameGame with TapDetector, DoubleTapDetector { add( SpriteAnimationComponent( - animation: animation, - ) + animation: animation, + ) ..position = size / 2 ..anchor = Anchor.center ..size = Vector2.all(100), diff --git a/examples/lib/stories/system/resize_example.dart b/examples/lib/stories/system/resize_example.dart index f60458c64..664d1e68f 100644 --- a/examples/lib/stories/system/resize_example.dart +++ b/examples/lib/stories/system/resize_example.dart @@ -5,9 +5,9 @@ import 'package:flame/game.dart'; class ResizingRectangle extends RectangleComponent { ResizingRectangle() - : super( - paint: Paint()..color = const Color(0xFFFE4813), - ); + : super( + paint: Paint()..color = const Color(0xFFFE4813), + ); @override void onGameResize(Vector2 size) { diff --git a/examples/lib/stories/tiled/tiled.dart b/examples/lib/stories/tiled/tiled.dart index 04e732118..0aef6c709 100644 --- a/examples/lib/stories/tiled/tiled.dart +++ b/examples/lib/stories/tiled/tiled.dart @@ -5,7 +5,9 @@ import 'package:examples/stories/tiled/flame_tiled_animation_example.dart'; import 'package:flame/game.dart'; void addTiledStories(Dashbook dashbook) { - dashbook.storiesOf('Tiled').add( + dashbook + .storiesOf('Tiled') + .add( 'Flame Tiled Animation', (_) => GameWidget(game: FlameTiledAnimationExample()), codeLink: baseLink('tiled/flame_tiled_animation_example.dart'), diff --git a/examples/lib/stories/utils/timer_component_example.dart b/examples/lib/stories/utils/timer_component_example.dart index 96a4b8f63..ac44c841f 100644 --- a/examples/lib/stories/utils/timer_component_example.dart +++ b/examples/lib/stories/utils/timer_component_example.dart @@ -37,10 +37,10 @@ class RenderedTimeComponent extends TimerComponent { final double yOffset; RenderedTimeComponent(double period, {this.yOffset = 150}) - : super( - period: period, - removeOnFinish: true, - ); + : super( + period: period, + removeOnFinish: true, + ); @override void render(Canvas canvas) { diff --git a/examples/lib/stories/widgets/sprite_animation_widget_example.dart b/examples/lib/stories/widgets/sprite_animation_widget_example.dart index 8dec8b3ac..ed1e4e665 100644 --- a/examples/lib/stories/widgets/sprite_animation_widget_example.dart +++ b/examples/lib/stories/widgets/sprite_animation_widget_example.dart @@ -21,13 +21,14 @@ Widget spriteAnimationWidgetBuilder(DashbookContext ctx) { anchor: Anchor.valueOf( ctx.listProperty('anchor', 'center', anchorOptions), ), - paint: paintList[paintChoices.indexOf( - ctx.listProperty( - 'paint', - 'none', - paintChoices, - ), - )], + paint: + paintList[paintChoices.indexOf( + ctx.listProperty( + 'paint', + 'none', + paintChoices, + ), + )], ), ); } diff --git a/examples/lib/stories/widgets/sprite_widget_example.dart b/examples/lib/stories/widgets/sprite_widget_example.dart index f00b1d66f..b962882d0 100644 --- a/examples/lib/stories/widgets/sprite_widget_example.dart +++ b/examples/lib/stories/widgets/sprite_widget_example.dart @@ -18,13 +18,14 @@ Widget spriteWidgetBuilder(DashbookContext ctx) { anchor: Anchor.valueOf( ctx.listProperty('anchor', 'center', anchorOptions), ), - paint: paintList[paintChoices.indexOf( - ctx.listProperty( - 'paint', - 'none', - paintChoices, - ), - )], + paint: + paintList[paintChoices.indexOf( + ctx.listProperty( + 'paint', + 'none', + paintChoices, + ), + )], ), ); } diff --git a/examples/pubspec.yaml b/examples/pubspec.yaml index 7558a6972..113f4a9b3 100644 --- a/examples/pubspec.yaml +++ b/examples/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: "none" version: 0.1.0 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame/benchmark/update_components_benchmark.dart b/packages/flame/benchmark/update_components_benchmark.dart index 9914fa8f4..aab1e7b91 100644 --- a/packages/flame/benchmark/update_components_benchmark.dart +++ b/packages/flame/benchmark/update_components_benchmark.dart @@ -18,7 +18,7 @@ class UpdateComponentsBenchmark extends AsyncBenchmarkBase { late final Set _inputTicks; UpdateComponentsBenchmark(this.random) - : super('Updating Components Benchmark'); + : super('Updating Components Benchmark'); static Future main() async { final r = Random(69420); @@ -34,8 +34,9 @@ class UpdateComponentsBenchmark extends AsyncBenchmarkBase { await _game.ready(); - _components = - _game.children.whereType<_BenchmarkComponent>().toList(growable: false); + _components = _game.children.whereType<_BenchmarkComponent>().toList( + growable: false, + ); _dts = List.generate(_amountTicks, (_) => random.nextDouble()); _inputTicks = List.generate( diff --git a/packages/flame/example/lib/main.dart b/packages/flame/example/lib/main.dart index 2fa6228a1..6ba96963d 100644 --- a/packages/flame/example/lib/main.dart +++ b/packages/flame/example/lib/main.dart @@ -42,11 +42,11 @@ class Square extends RectangleComponent with TapCallbacks { static final Paint blue = BasicPalette.blue.paint(); Square(Vector2 position) - : super( - position: position, - size: Vector2.all(squareSize), - anchor: Anchor.center, - ); + : super( + position: position, + size: Vector2.all(squareSize), + anchor: Anchor.center, + ); @override Future onLoad() async { diff --git a/packages/flame/example/pubspec.yaml b/packages/flame/example/pubspec.yaml index bcbb51cd5..6fff1889e 100644 --- a/packages/flame/example/pubspec.yaml +++ b/packages/flame/example/pubspec.yaml @@ -5,7 +5,7 @@ version: 0.1.0 publish_to: 'none' environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame/lib/src/cache/images.dart b/packages/flame/lib/src/cache/images.dart index 9e1638509..ed1e6f938 100644 --- a/packages/flame/lib/src/cache/images.dart +++ b/packages/flame/lib/src/cache/images.dart @@ -10,8 +10,8 @@ class Images { Images({ String prefix = 'assets/images/', AssetBundle? bundle, - }) : _prefix = prefix, - bundle = bundle ?? Flame.bundle; + }) : _prefix = prefix, + bundle = bundle ?? Flame.bundle; final Map _assets = {}; @@ -66,8 +66,9 @@ class Images { String name, Future Function() imageGenerator, ) { - return (_assets[name] ??= _ImageAsset.future(imageGenerator())) - .retrieveAsync(); + return (_assets[name] ??= _ImageAsset.future( + imageGenerator(), + )).retrieveAsync(); } /// Removes the image [name] from the cache. @@ -117,9 +118,9 @@ class Images { /// By default the key in the cache is the [fileName], if another key is /// desired, specify the optional [key] argument. Future load(String fileName, {String? key}) { - return (_assets[key ?? fileName] ??= - _ImageAsset.future(_fetchToMemory(fileName))) - .retrieveAsync(); + return (_assets[key ?? fileName] ??= _ImageAsset.future( + _fetchToMemory(fileName), + )).retrieveAsync(); } /// Loads all images with the specified [fileNames] into the cache. @@ -142,9 +143,12 @@ class Images { Future> loadAllFromPattern(Pattern pattern) async { final manifestContent = await bundle.loadString('AssetManifest.json'); final manifestMap = json.decode(manifestContent) as Map; - final imagePaths = manifestMap.keys.where((path) { - return path.startsWith(_prefix) && path.toLowerCase().contains(pattern); - }).map((path) => path.replaceFirst(_prefix, '')); + final imagePaths = manifestMap.keys + .where((path) { + return path.startsWith(_prefix) && + path.toLowerCase().contains(pattern); + }) + .map((path) => path.replaceFirst(_prefix, '')); return loadAll(imagePaths.toList()); } @@ -166,8 +170,9 @@ class Images { } Future fromBase64(String key, String base64) { - return (_assets[key] ??= _ImageAsset.future(_fetchFromBase64(base64))) - .retrieveAsync(); + return (_assets[key] ??= _ImageAsset.future( + _fetchFromBase64(base64), + )).retrieveAsync(); } Future _fetchFromBase64(String base64Data) { diff --git a/packages/flame/lib/src/camera/behaviors/bounded_position_behavior.dart b/packages/flame/lib/src/camera/behaviors/bounded_position_behavior.dart index 2ed921aef..3d023e80a 100644 --- a/packages/flame/lib/src/camera/behaviors/bounded_position_behavior.dart +++ b/packages/flame/lib/src/camera/behaviors/bounded_position_behavior.dart @@ -24,11 +24,11 @@ class BoundedPositionBehavior extends Component { double precision = 0.5, super.priority, super.key, - }) : assert(precision > 0, 'Precision must be positive: $precision'), - _bounds = bounds, - _target = target, - _previousPosition = Vector2.zero(), - _precision = precision; + }) : assert(precision > 0, 'Precision must be positive: $precision'), + _bounds = bounds, + _target = target, + _previousPosition = Vector2.zero(), + _precision = precision; /// The region within which the target's position must be kept. Shape get bounds => _bounds; diff --git a/packages/flame/lib/src/camera/behaviors/follow_behavior.dart b/packages/flame/lib/src/camera/behaviors/follow_behavior.dart index 2e38dafe0..7d5483044 100644 --- a/packages/flame/lib/src/camera/behaviors/follow_behavior.dart +++ b/packages/flame/lib/src/camera/behaviors/follow_behavior.dart @@ -26,14 +26,14 @@ class FollowBehavior extends Component { this.verticalOnly = false, super.priority, super.key, - }) : _target = target, - _owner = owner, - _speed = maxSpeed, - assert(maxSpeed > 0, 'maxSpeed must be positive: $maxSpeed'), - assert( - !(horizontalOnly && verticalOnly), - 'The behavior cannot be both horizontalOnly and verticalOnly', - ); + }) : _target = target, + _owner = owner, + _speed = maxSpeed, + assert(maxSpeed > 0, 'maxSpeed must be positive: $maxSpeed'), + assert( + !(horizontalOnly && verticalOnly), + 'The behavior cannot be both horizontalOnly and verticalOnly', + ); ReadOnlyPositionProvider get target => _target; final ReadOnlyPositionProvider _target; diff --git a/packages/flame/lib/src/camera/camera_component.dart b/packages/flame/lib/src/camera/camera_component.dart index 8e6eec2e4..974620809 100644 --- a/packages/flame/lib/src/camera/camera_component.dart +++ b/packages/flame/lib/src/camera/camera_component.dart @@ -58,14 +58,14 @@ class CameraComponent extends Component { List? hudComponents, super.children, super.key, - }) : _viewport = (viewport ?? MaxViewport())..addAll(hudComponents ?? []), - _viewfinder = viewfinder ?? Viewfinder(), - _backdrop = backdrop ?? Component(), - // The priority is set to the max here to avoid some bugs for the users, - // if they for example would add any components that modify positions - // before the CameraComponent, since it then will render the positions - // of the last tick each tick. - super(priority: 0x7fffffff) { + }) : _viewport = (viewport ?? MaxViewport())..addAll(hudComponents ?? []), + _viewfinder = viewfinder ?? Viewfinder(), + _backdrop = backdrop ?? Component(), + // The priority is set to the max here to avoid some bugs for the users, + // if they for example would add any components that modify positions + // before the CameraComponent, since it then will render the positions + // of the last tick each tick. + super(priority: 0x7fffffff) { children.register(); addAll([_backdrop, _viewport, _viewfinder]); } @@ -89,14 +89,14 @@ class CameraComponent extends Component { Iterable? children, ComponentKey? key, }) : this( - world: world, - viewport: FixedResolutionViewport(resolution: Vector2(width, height)), - viewfinder: viewfinder ?? Viewfinder(), - backdrop: backdrop, - hudComponents: hudComponents, - children: children, - key: key, - ); + world: world, + viewport: FixedResolutionViewport(resolution: Vector2(width, height)), + viewfinder: viewfinder ?? Viewfinder(), + backdrop: backdrop, + hudComponents: hudComponents, + children: children, + key: key, + ); /// The [viewport] is the "window" through which the game world is observed. /// @@ -255,8 +255,10 @@ class CameraComponent extends Component { /// /// Opposite of [globalToLocal]. Vector2 localToGlobal(Vector2 position, {Vector2? output}) { - final viewfinderPosition = - viewfinder.localToGlobal(position, output: output); + final viewfinderPosition = viewfinder.localToGlobal( + position, + output: output, + ); return viewport.localToGlobal(viewfinderPosition, output: output); } @@ -394,8 +396,8 @@ class CameraComponent extends Component { /// [Circle] shapes. void setBounds(Shape? bounds, {bool considerViewport = false}) { final boundedBehavior = viewfinder.firstChild(); - final viewPortAwareBoundsBehavior = - viewfinder.firstChild(); + final viewPortAwareBoundsBehavior = viewfinder + .firstChild(); if (bounds == null) { // When bounds is null, all bounds-related components need to be dropped. @@ -442,8 +444,9 @@ class CameraComponent extends Component { // in this exact cycle but did not mount into the tree. // We must wait for that component to mount first in order for // ViewportAwareBoundsBehavior to correctly affect the camera. - boundedBehaviorFuture - .whenComplete(() => _addViewPortAwareBoundsBehavior(bounds)); + boundedBehaviorFuture.whenComplete( + () => _addViewPortAwareBoundsBehavior(bounds), + ); } } else { viewPortAwareBoundsBehavior.boundsShape = bounds; @@ -500,10 +503,10 @@ class CameraComponent extends Component { PostProcess? get postProcess => children.query().firstOrNull?.postProcess; set postProcess(PostProcess? postProcess) { - final postProcessComponents = - children.query().toList(); - final queuedPostProcessAdds = findGame() - ?.queue + final postProcessComponents = children + .query() + .toList(); + final queuedPostProcessAdds = findGame()?.queue .where( (event) => event.kind == LifecycleEventKind.add && diff --git a/packages/flame/lib/src/collisions/broadphase/quadtree/quad_tree_broadphase.dart b/packages/flame/lib/src/collisions/broadphase/quadtree/quad_tree_broadphase.dart index 3e5722af8..2c93c01dc 100644 --- a/packages/flame/lib/src/collisions/broadphase/quadtree/quad_tree_broadphase.dart +++ b/packages/flame/lib/src/collisions/broadphase/quadtree/quad_tree_broadphase.dart @@ -3,15 +3,17 @@ import 'dart:collection'; import 'package:flame/collisions.dart'; import 'package:flame/extensions.dart'; -typedef ExternalBroadphaseCheck = bool Function( - ShapeHitbox first, - ShapeHitbox second, -); +typedef ExternalBroadphaseCheck = + bool Function( + ShapeHitbox first, + ShapeHitbox second, + ); -typedef ExternalMinDistanceCheck = bool Function( - Vector2 activeItemCenter, - Vector2 potentialCenter, -); +typedef ExternalMinDistanceCheck = + bool Function( + Vector2 activeItemCenter, + Vector2 potentialCenter, + ); /// Performs Quad Tree broadphase check. /// @@ -25,10 +27,10 @@ class QuadTreeBroadphase extends Broadphase { int maxObjects = 25, int maxDepth = 10, }) : tree = QuadTree( - mainBoxSize: mainBoxSize, - maxObjects: maxObjects, - maxDepth: maxDepth, - ); + mainBoxSize: mainBoxSize, + maxObjects: maxObjects, + maxDepth: maxDepth, + ); final QuadTree tree; diff --git a/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree.dart b/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree.dart index a2abbfcd1..a7d30fa0a 100644 --- a/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree.dart +++ b/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree.dart @@ -332,8 +332,11 @@ class QuadTreeNodeDebugInfo { } class QuadTreeNode> { - final List children = - List.generate(4, (index) => null, growable: false); + final List children = List.generate( + 4, + (index) => null, + growable: false, + ); List hitboxes = []; diff --git a/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree_collision_detection.dart b/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree_collision_detection.dart index aa9eed4be..9a34e8de2 100644 --- a/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree_collision_detection.dart +++ b/packages/flame/lib/src/collisions/broadphase/quadtree/quadtree_collision_detection.dart @@ -14,14 +14,14 @@ class QuadTreeCollisionDetection int maxObjects = 25, int maxDepth = 10, }) : super( - broadphase: QuadTreeBroadphase( - mainBoxSize: mapDimensions, - maxObjects: maxObjects, - maxDepth: maxDepth, - broadphaseCheck: onComponentTypeCheck, - minimumDistanceCheck: minimumDistanceCheck, - ), - ); + broadphase: QuadTreeBroadphase( + mainBoxSize: mapDimensions, + maxObjects: maxObjects, + maxDepth: maxDepth, + broadphaseCheck: onComponentTypeCheck, + minimumDistanceCheck: minimumDistanceCheck, + ), + ); final _listenerCollisionType = {}; final _scheduledUpdate = {}; diff --git a/packages/flame/lib/src/collisions/collision_callbacks.dart b/packages/flame/lib/src/collisions/collision_callbacks.dart index 3452560f9..b3c0e3668 100644 --- a/packages/flame/lib/src/collisions/collision_callbacks.dart +++ b/packages/flame/lib/src/collisions/collision_callbacks.dart @@ -165,10 +165,11 @@ mixin CollisionCallbacks on Component /// Can be used used to implement an `onCollisionCallback` or an /// `onCollisionStartCallback`. -typedef CollisionCallback = void Function( - Set intersectionPoints, - T other, -); +typedef CollisionCallback = + void Function( + Set intersectionPoints, + T other, + ); /// Can be used used to implement an `onCollisionEndCallback`. typedef CollisionEndCallback = void Function(T other); diff --git a/packages/flame/lib/src/collisions/collision_detection.dart b/packages/flame/lib/src/collisions/collision_detection.dart index 94654f06a..c4aef62e1 100644 --- a/packages/flame/lib/src/collisions/collision_detection.dart +++ b/packages/flame/lib/src/collisions/collision_detection.dart @@ -8,8 +8,10 @@ import 'package:flutter/material.dart'; /// /// If the [HasCollisionDetection] mixin is added to the game, [run] is called /// every tick to check for collisions. -abstract class CollisionDetection, - B extends Broadphase> { +abstract class CollisionDetection< + T extends Hitbox, + B extends Broadphase +> { final B broadphase; List get items => broadphase.items; diff --git a/packages/flame/lib/src/collisions/collision_passthrough.dart b/packages/flame/lib/src/collisions/collision_passthrough.dart index cd62acd8d..686079229 100644 --- a/packages/flame/lib/src/collisions/collision_passthrough.dart +++ b/packages/flame/lib/src/collisions/collision_passthrough.dart @@ -15,9 +15,11 @@ mixin CollisionPassthrough on CollisionCallbacks { @mustCallSuper void onMount() { super.onMount(); - passthroughParent = ancestors().firstWhereOrNull( - (c) => c is CollisionCallbacks, - ) as CollisionCallbacks?; + passthroughParent = + ancestors().firstWhereOrNull( + (c) => c is CollisionCallbacks, + ) + as CollisionCallbacks?; } @override diff --git a/packages/flame/lib/src/collisions/hitboxes/circle_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/circle_hitbox.dart index 09d01eb12..03cd627c4 100644 --- a/packages/flame/lib/src/collisions/hitboxes/circle_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/circle_hitbox.dart @@ -32,8 +32,8 @@ class CircleHitbox extends CircleComponent with ShapeHitbox { super.anchor, bool isSolid = false, CollisionType collisionType = CollisionType.active, - }) : shouldFillParent = false, - super.relative() { + }) : shouldFillParent = false, + super.relative() { this.isSolid = isSolid; this.collisionType = collisionType; } @@ -108,11 +108,11 @@ class CircleHitbox extends CircleComponent with ShapeHitbox { ..setFrom(ray.direction) ..reflect(_temporaryNormal); - final reflectionRay = (out?.reflectionRay - ?..setWith( - origin: intersectionPoint, - direction: reflectionDirection, - )) ?? + final reflectionRay = + (out?.reflectionRay?..setWith( + origin: intersectionPoint, + direction: reflectionDirection, + )) ?? Ray2( origin: intersectionPoint, direction: reflectionDirection, diff --git a/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart index 2366b63bd..a79a7e520 100644 --- a/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/rectangle_hitbox.dart @@ -35,10 +35,10 @@ class RectangleHitbox extends RectangleComponent super.anchor, bool isSolid = false, CollisionType collisionType = CollisionType.active, - }) : shouldFillParent = false, - super.relative( - shrinkToBounds: true, - ) { + }) : shouldFillParent = false, + super.relative( + shrinkToBounds: true, + ) { this.isSolid = isSolid; this.collisionType = collisionType; } diff --git a/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart b/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart index 8a5cded14..c30aa909a 100644 --- a/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart +++ b/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart @@ -78,19 +78,24 @@ mixin ShapeHitbox on ShapeComponent implements Hitbox { @override void onMount() { super.onMount(); - _hitboxParent = ancestors().firstWhere( - (c) => c is PositionComponent && c is! CompositeHitbox, - orElse: () { - throw StateError('A ShapeHitbox needs a PositionComponent ancestor'); - }, - ) as PositionComponent; + _hitboxParent = + ancestors().firstWhere( + (c) => c is PositionComponent && c is! CompositeHitbox, + orElse: () { + throw StateError( + 'A ShapeHitbox needs a PositionComponent ancestor', + ); + }, + ) + as PositionComponent; _transformListener = () { _validAabb = false; onAabbChanged?.call(); }; - final positionComponents = - ancestors(includeSelf: true).whereType(); + final positionComponents = ancestors( + includeSelf: true, + ).whereType(); for (final ancestor in positionComponents) { _transformAncestors.add(ancestor.transform); ancestor.transform.addListener(_transformListener); @@ -241,14 +246,17 @@ mixin ShapeHitbox on ShapeComponent implements Hitbox { bool onComponentTypeCheck(PositionComponent other) { final otherHitboxParent = (other as ShapeHitbox).hitboxParent; - final thisCanCollideWithOther = (hitboxParent is! CollisionCallbacks) || - (hitboxParent as CollisionCallbacks) - .onComponentTypeCheck(otherHitboxParent); + final thisCanCollideWithOther = + (hitboxParent is! CollisionCallbacks) || + (hitboxParent as CollisionCallbacks).onComponentTypeCheck( + otherHitboxParent, + ); final otherCanCollideWithThis = (otherHitboxParent is! CollisionCallbacks) || - (otherHitboxParent as CollisionCallbacks) - .onComponentTypeCheck(hitboxParent); + (otherHitboxParent as CollisionCallbacks).onComponentTypeCheck( + hitboxParent, + ); return thisCanCollideWithOther && otherCanCollideWithThis; } @@ -262,5 +270,5 @@ mixin ShapeHitbox on ShapeComponent implements Hitbox { @override CollisionEndCallback? onCollisionEndCallback; -//#endregion + //#endregion } diff --git a/packages/flame/lib/src/collisions/standard_collision_detection.dart b/packages/flame/lib/src/collisions/standard_collision_detection.dart index 6d8048768..6f697ee80 100644 --- a/packages/flame/lib/src/collisions/standard_collision_detection.dart +++ b/packages/flame/lib/src/collisions/standard_collision_detection.dart @@ -13,7 +13,7 @@ import 'package:flame/geometry.dart'; class StandardCollisionDetection> extends CollisionDetection { StandardCollisionDetection({B? broadphase}) - : super(broadphase: broadphase ?? Sweep() as B); + : super(broadphase: broadphase ?? Sweep() as B); /// Check what the intersection points of two collidables are, /// returns an empty list if there are no intersections. @@ -90,8 +90,10 @@ class StandardCollisionDetection> if (!item.aabb.intersectsWithAabb2(_temporaryRayAabb)) { continue; } - final currentResult = - item.rayIntersection(ray, out: _temporaryRaycastResult); + final currentResult = item.rayIntersection( + ray, + out: _temporaryRaycastResult, + ); final possiblyFirstResult = !(finalResult?.isActive ?? false); if (currentResult != null && (possiblyFirstResult || @@ -175,8 +177,9 @@ class StandardCollisionDetection> var currentRay = ray; for (var i = 0; i < maxDepth; i++) { final hasResultObject = (out?.length ?? 0) > i; - final storeResult = - hasResultObject ? out![i] : RaycastResult(); + final storeResult = hasResultObject + ? out![i] + : RaycastResult(); final currentResult = raycast( currentRay, hitboxFilter: hitboxFilter, diff --git a/packages/flame/lib/src/components/clip_component.dart b/packages/flame/lib/src/components/clip_component.dart index 19a8a151a..9233ea51d 100644 --- a/packages/flame/lib/src/components/clip_component.dart +++ b/packages/flame/lib/src/components/clip_component.dart @@ -38,16 +38,16 @@ class ClipComponent extends PositionComponent { int? priority, ComponentKey? key, }) : this( - builder: (size) => Circle(size / 2, size.x / 2), - position: position, - size: size, - scale: scale, - angle: angle, - anchor: anchor, - children: children, - priority: priority, - key: key, - ); + builder: (size) => Circle(size / 2, size.x / 2), + position: position, + size: size, + scale: scale, + angle: angle, + anchor: anchor, + children: children, + priority: priority, + key: key, + ); /// {@macro rectangle_clip_component} /// @@ -62,16 +62,16 @@ class ClipComponent extends PositionComponent { int? priority, ComponentKey? key, }) : this( - builder: (size) => Rectangle.fromRect(size.toRect()), - position: position, - size: size, - scale: scale, - angle: angle, - anchor: anchor, - children: children, - priority: priority, - key: key, - ); + builder: (size) => Rectangle.fromRect(size.toRect()), + position: position, + size: size, + scale: scale, + angle: angle, + anchor: anchor, + children: children, + priority: priority, + key: key, + ); /// {@macro polygon_clip_component} /// @@ -87,16 +87,16 @@ class ClipComponent extends PositionComponent { int? priority, ComponentKey? key, }) : this( - builder: _polygonShapeBuilder(points), - position: position, - size: size, - scale: scale, - angle: angle, - anchor: anchor, - children: children, - priority: priority, - key: key, - ); + builder: _polygonShapeBuilder(points), + position: position, + size: size, + scale: scale, + angle: angle, + anchor: anchor, + children: children, + priority: priority, + key: key, + ); late Path _path; late Shape _shape; diff --git a/packages/flame/lib/src/components/core/component.dart b/packages/flame/lib/src/components/core/component.dart index 9bdb3f4aa..a83c2d79f 100644 --- a/packages/flame/lib/src/components/core/component.dart +++ b/packages/flame/lib/src/components/core/component.dart @@ -419,9 +419,10 @@ class Component { bool Function(T) handler, { bool includeSelf = false, }) { - return descendants(reversed: true, includeSelf: includeSelf) - .whereType() - .every(handler); + return descendants( + reversed: true, + includeSelf: includeSelf, + ).whereType().every(handler); } @internal @@ -1138,7 +1139,8 @@ class Component { if (!_debugPaintCache.isCacheValid([debugColor])) { final paint = Paint() ..color = debugColor - ..strokeWidth = 0 // hairline-width + ..strokeWidth = + 0 // hairline-width ..style = PaintingStyle.stroke; _debugPaintCache.updateCache(paint, [debugColor]); } diff --git a/packages/flame/lib/src/components/core/component_tree_root.dart b/packages/flame/lib/src/components/core/component_tree_root.dart index 5d02eb10f..324fd4823 100644 --- a/packages/flame/lib/src/components/core/component_tree_root.dart +++ b/packages/flame/lib/src/components/core/component_tree_root.dart @@ -14,8 +14,8 @@ class ComponentTreeRoot extends Component { ComponentTreeRoot({ super.children, super.key, - }) : queue = RecycledQueue(LifecycleEvent.new), - _blocked = {}; + }) : queue = RecycledQueue(LifecycleEvent.new), + _blocked = {}; @internal final RecycledQueue queue; diff --git a/packages/flame/lib/src/components/core/recycled_queue.dart b/packages/flame/lib/src/components/core/recycled_queue.dart index b122be4c0..8f0fb6b10 100644 --- a/packages/flame/lib/src/components/core/recycled_queue.dart +++ b/packages/flame/lib/src/components/core/recycled_queue.dart @@ -22,10 +22,10 @@ import 'dart:math'; class RecycledQueue extends Iterable implements Iterator { RecycledQueue(this.factory, {int initialCapacity = 8}) - : _elements = List.generate(initialCapacity, (i) => factory()), - _startIndex = -1, - _endIndex = -1, - _currentIndex = -1; + : _elements = List.generate(initialCapacity, (i) => factory()), + _startIndex = -1, + _endIndex = -1, + _currentIndex = -1; /// Function for creating new elements in the queue. final T Function() factory; @@ -76,8 +76,8 @@ class RecycledQueue extends Iterable return isEmpty ? 0 : _endIndex >= _startIndex - ? _endIndex - _startIndex + 1 - : _elements.length - _startIndex + _endIndex + 1; + ? _endIndex - _startIndex + 1 + : _elements.length - _startIndex + _endIndex + 1; } @override @@ -237,8 +237,8 @@ class RecycledQueue extends Iterable return (i == _endIndex) ? -1 : (i == _elements.length - 1) - ? 0 - : i + 1; + ? 0 + : i + 1; } while (i != -1) { diff --git a/packages/flame/lib/src/components/fps_text_component.dart b/packages/flame/lib/src/components/fps_text_component.dart index 5e86eb8c9..4508d3517 100644 --- a/packages/flame/lib/src/components/fps_text_component.dart +++ b/packages/flame/lib/src/components/fps_text_component.dart @@ -14,10 +14,10 @@ class FpsTextComponent extends TextComponent { super.angle, super.anchor, int? priority, - }) : fpsComponent = FpsComponent(windowSize: windowSize), - super( - priority: priority ?? double.maxFinite.toInt(), - ) { + }) : fpsComponent = FpsComponent(windowSize: windowSize), + super( + priority: priority ?? double.maxFinite.toInt(), + ) { add(fpsComponent); } diff --git a/packages/flame/lib/src/components/input/button_component.dart b/packages/flame/lib/src/components/input/button_component.dart index 81bf1930e..6c313054e 100644 --- a/packages/flame/lib/src/components/input/button_component.dart +++ b/packages/flame/lib/src/components/input/button_component.dart @@ -34,8 +34,8 @@ class ButtonComponent extends PositionComponent with TapCallbacks { super.children, super.priority, }) : super( - size: size ?? button?.size, - ); + size: size ?? button?.size, + ); @override @mustCallSuper diff --git a/packages/flame/lib/src/components/input/hud_button_component.dart b/packages/flame/lib/src/components/input/hud_button_component.dart index 57dcb9d9a..a726785cd 100644 --- a/packages/flame/lib/src/components/input/hud_button_component.dart +++ b/packages/flame/lib/src/components/input/hud_button_component.dart @@ -24,8 +24,8 @@ class HudButtonComponent extends ButtonComponent super.children, super.priority, }) : super( - size: size ?? button?.size, - ) { + size: size ?? button?.size, + ) { this.margin = margin; } } diff --git a/packages/flame/lib/src/components/input/hud_margin_component.dart b/packages/flame/lib/src/components/input/hud_margin_component.dart index 4049a63ca..8d2f328fc 100644 --- a/packages/flame/lib/src/components/input/hud_margin_component.dart +++ b/packages/flame/lib/src/components/input/hud_margin_component.dart @@ -27,9 +27,9 @@ class HudMarginComponent extends PositionComponent { super.priority, super.key, }) : assert( - margin != null || position != null, - 'Either margin or position must be defined', - ); + margin != null || position != null, + 'Either margin or position must be defined', + ); /// Instead of setting a position of the [HudMarginComponent] a margin /// from the edges of the viewport can be used instead. @@ -57,7 +57,8 @@ class HudMarginComponent extends PositionComponent { Anchor.topLeft, scaledSize, ); - final bottomRight = sizeProvider.size - + final bottomRight = + sizeProvider.size - anchor.toOtherAnchorPosition( position, Anchor.bottomRight, diff --git a/packages/flame/lib/src/components/input/joystick_component.dart b/packages/flame/lib/src/components/input/joystick_component.dart index d7c1acf33..47528a1e5 100644 --- a/packages/flame/lib/src/components/input/joystick_component.dart +++ b/packages/flame/lib/src/components/input/joystick_component.dart @@ -54,18 +54,18 @@ class JoystickComponent extends PositionComponent super.children, super.priority, super.key, - }) : assert( - size != null || background != null, - 'Either size or background must be defined', - ), - assert( - (knob?.position.isZero() ?? true) && - (background?.position.isZero() ?? true), - 'Positions should not be set for the knob or the background', - ), - super( - size: background?.size ?? Vector2.all(size ?? 0), - ) { + }) : assert( + size != null || background != null, + 'Either size or background must be defined', + ), + assert( + (knob?.position.isZero() ?? true) && + (background?.position.isZero() ?? true), + 'Positions should not be set for the knob or the background', + ), + super( + size: background?.size ?? Vector2.all(size ?? 0), + ) { this.margin = margin; this.knobRadius = knobRadius ?? this.size.x / 2; } diff --git a/packages/flame/lib/src/components/input/keyboard_listener_component.dart b/packages/flame/lib/src/components/input/keyboard_listener_component.dart index 9330f49fb..5439139aa 100644 --- a/packages/flame/lib/src/components/input/keyboard_listener_component.dart +++ b/packages/flame/lib/src/components/input/keyboard_listener_component.dart @@ -17,8 +17,8 @@ class KeyboardListenerComponent extends Component with KeyboardHandler { Map keyUp = const {}, Map keyDown = const {}, super.key, - }) : _keyUp = keyUp, - _keyDown = keyDown; + }) : _keyUp = keyUp, + _keyDown = keyDown; final Map _keyUp; final Map _keyDown; diff --git a/packages/flame/lib/src/components/input/sprite_button_component.dart b/packages/flame/lib/src/components/input/sprite_button_component.dart index 97eba006f..507f52605 100644 --- a/packages/flame/lib/src/components/input/sprite_button_component.dart +++ b/packages/flame/lib/src/components/input/sprite_button_component.dart @@ -29,12 +29,12 @@ class SpriteButtonComponent extends SpriteGroupComponent super.anchor, super.children, super.priority, - }) : _button = button, - _buttonDown = buttonDown, - super( - current: ButtonState.up, - size: size ?? button?.originalSize, - ); + }) : _button = button, + _buttonDown = buttonDown, + super( + current: ButtonState.up, + size: size ?? button?.originalSize, + ); /// Callback for what should happen when the button is pressed. void Function()? onPressed; diff --git a/packages/flame/lib/src/components/isometric_tile_map_component.dart b/packages/flame/lib/src/components/isometric_tile_map_component.dart index 2ce69cad9..a4f525936 100644 --- a/packages/flame/lib/src/components/isometric_tile_map_component.dart +++ b/packages/flame/lib/src/components/isometric_tile_map_component.dart @@ -147,11 +147,10 @@ class IsometricTileMapComponent extends PositionComponent { /// This is the opposite of [getBlock]. Vector2 getBlockCenterPosition(Block block) { final tile = effectiveTileSize; - return getBlockRenderPosition(block) - ..translate( - (tile.x / 2) * scale.x, - (tile.y - effectiveTileHeight - tile.y / 4) * scale.y, - ); + return getBlockRenderPosition(block)..translate( + (tile.x / 2) * scale.x, + (tile.y - effectiveTileHeight - tile.y / 4) * scale.y, + ); } /// Converts a coordinate from the isometric space to the cartesian space. diff --git a/packages/flame/lib/src/components/mixins/component_viewport_margin.dart b/packages/flame/lib/src/components/mixins/component_viewport_margin.dart index 04b913353..a42f5a2f6 100644 --- a/packages/flame/lib/src/components/mixins/component_viewport_margin.dart +++ b/packages/flame/lib/src/components/mixins/component_viewport_margin.dart @@ -44,7 +44,8 @@ mixin ComponentViewportMargin Anchor.topLeft, scaledSize, ); - final bottomRight = bounds - + final bottomRight = + bounds - anchor.toOtherAnchorPosition( position, Anchor.bottomRight, diff --git a/packages/flame/lib/src/components/mixins/has_paint.dart b/packages/flame/lib/src/components/mixins/has_paint.dart index 2d1c5545f..6b45e9d3b 100644 --- a/packages/flame/lib/src/components/mixins/has_paint.dart +++ b/packages/flame/lib/src/components/mixins/has_paint.dart @@ -230,9 +230,9 @@ class _MultiPaintOpacityProvider implements OpacityProvider { if (includeLayers) { final paintLayersInternal = target.paintLayersInternal; for (var i = 0; i < (paintLayersInternal?.length ?? 0); ++i) { - paintLayersInternal![i].color = paintLayersInternal[i] - .color - .withValues(alpha: value * _layerOpacityRatios![i]); + paintLayersInternal![i].color = paintLayersInternal[i].color.withValues( + alpha: value * _layerOpacityRatios![i], + ); } } } diff --git a/packages/flame/lib/src/components/mixins/has_world.dart b/packages/flame/lib/src/components/mixins/has_world.dart index 0efa66ed7..8bcf54899 100644 --- a/packages/flame/lib/src/components/mixins/has_world.dart +++ b/packages/flame/lib/src/components/mixins/has_world.dart @@ -21,8 +21,10 @@ mixin HasWorldReference on Component { set world(T? value) => _world = value; T? findWorld() { - return ancestors(includeSelf: true) - .firstWhereOrNull((ancestor) => ancestor is T) as T?; + return ancestors( + includeSelf: true, + ).firstWhereOrNull((ancestor) => ancestor is T) + as T?; } T _findWorldAndCheck() { diff --git a/packages/flame/lib/src/components/parallax_component.dart b/packages/flame/lib/src/components/parallax_component.dart index cba36a67c..23c3e5d31 100644 --- a/packages/flame/lib/src/components/parallax_component.dart +++ b/packages/flame/lib/src/components/parallax_component.dart @@ -76,11 +76,11 @@ class ParallaxComponent extends PositionComponent super.children, super.priority, super.key, - }) : _parallax = parallax, - isFullscreen = size == null && !(parallax?.isSized ?? false), - super( - size: size ?? ((parallax?.isSized ?? false) ? parallax?.size : null), - ); + }) : _parallax = parallax, + isFullscreen = size == null && !(parallax?.isSized ?? false), + super( + size: size ?? ((parallax?.isSized ?? false) ? parallax?.size : null), + ); @mustCallSuper @override diff --git a/packages/flame/lib/src/components/position_component.dart b/packages/flame/lib/src/components/position_component.dart index b6af87256..4eb3c2fa0 100644 --- a/packages/flame/lib/src/components/position_component.dart +++ b/packages/flame/lib/src/components/position_component.dart @@ -80,9 +80,9 @@ class PositionComponent extends Component super.children, super.priority, super.key, - }) : transform = Transform2D(), - _anchor = anchor ?? Anchor.topLeft, - _size = NotifyingVector2.copy(size ?? Vector2.zero()) { + }) : transform = Transform2D(), + _anchor = anchor ?? Anchor.topLeft, + _size = NotifyingVector2.copy(size ?? Vector2.zero()) { decorator = Transform2DDecorator(transform); if (position != null) { transform.position = position; @@ -273,9 +273,9 @@ class PositionComponent extends Component Vector2 get _parentAbsoluteScale { return ancestors().whereType().fold( - Vector2.all(1.0), - (totalScale, c) => totalScale..multiply(c.scale), - ); + Vector2.all(1.0), + (totalScale, c) => totalScale..multiply(c.scale), + ); } /// Measure the distance (in parent's coordinate space) between this @@ -417,14 +417,16 @@ class PositionComponent extends Component ); final angleDifference = targetAngle - absoluteAngle - nativeAngle; - final hasOddFlips = parentAbsoluteScale.x.isNegative ^ + final hasOddFlips = + parentAbsoluteScale.x.isNegative ^ parentAbsoluteScale.y.isNegative ^ scale.x.isNegative ^ scale.y.isNegative; final hasSelfYFlip = !parentAbsoluteScale.y.isNegative && scale.y.isNegative; - final result = (hasOddFlips ? -1 : 1) * angleDifference + + final result = + (hasOddFlips ? -1 : 1) * angleDifference + (hasSelfYFlip ? 1 : 0) * math.pi; return result.toNormalizedAngle(); } diff --git a/packages/flame/lib/src/components/raster_sprite_component.dart b/packages/flame/lib/src/components/raster_sprite_component.dart index 4efffaa71..cce22d984 100644 --- a/packages/flame/lib/src/components/raster_sprite_component.dart +++ b/packages/flame/lib/src/components/raster_sprite_component.dart @@ -48,24 +48,24 @@ class RasterSpriteComponent extends SpriteComponent { ComponentKey? key, double? bleed, }) : this( - baseSprite: Sprite( - image, - srcPosition: srcPosition, - srcSize: srcSize, - ), - autoResize: autoResize, - paint: paint, - position: position, - size: size, - scale: scale, - angle: angle, - nativeAngle: nativeAngle, - anchor: anchor, - children: children, - priority: priority, - bleed: bleed, - key: key, - ); + baseSprite: Sprite( + image, + srcPosition: srcPosition, + srcSize: srcSize, + ), + autoResize: autoResize, + paint: paint, + position: position, + size: size, + scale: scale, + angle: angle, + nativeAngle: nativeAngle, + anchor: anchor, + children: children, + priority: priority, + bleed: bleed, + key: key, + ); /// The base sprite to be rasterized. final Sprite baseSprite; diff --git a/packages/flame/lib/src/components/router/overlay_route.dart b/packages/flame/lib/src/components/router/overlay_route.dart index e40383ce9..f59e6bd92 100644 --- a/packages/flame/lib/src/components/router/overlay_route.dart +++ b/packages/flame/lib/src/components/router/overlay_route.dart @@ -19,14 +19,14 @@ class OverlayRoute extends Route { /// registered with the Game's map of overlay builders when this route is /// first activated. OverlayRoute(OverlayBuilder builder, {super.transparent = true}) - : _builder = builder, - super(null); + : _builder = builder, + super(null); /// An overlay route that corresponds to an overlay that was already declared /// within GameWidget's `overlayBuilderMap`. OverlayRoute.existing({super.transparent = true}) - : _builder = null, - super(null); + : _builder = null, + super(null); final OverlayBuilder? _builder; diff --git a/packages/flame/lib/src/components/router/route.dart b/packages/flame/lib/src/components/router/route.dart index e3ae88523..14354e9f6 100644 --- a/packages/flame/lib/src/components/router/route.dart +++ b/packages/flame/lib/src/components/router/route.dart @@ -27,9 +27,9 @@ class Route extends PositionComponent Component Function()? loadingBuilder, this.transparent = false, this.maintainState = true, - }) : _builder = builder, - _loadingBuilder = loadingBuilder, - _renderEffect = Decorator(); + }) : _builder = builder, + _loadingBuilder = loadingBuilder, + _renderEffect = Decorator(); /// If true, then the route below this one will continue to be rendered when /// this route becomes active. If false, then this route is assumed to diff --git a/packages/flame/lib/src/components/router/router_component.dart b/packages/flame/lib/src/components/router/router_component.dart index 92b6598c5..6aecb03d0 100644 --- a/packages/flame/lib/src/components/router/router_component.dart +++ b/packages/flame/lib/src/components/router/router_component.dart @@ -35,8 +35,8 @@ class RouterComponent extends Component { this.onUnknownRoute, super.key, super.priority = 0x7fffffff, - }) : _routes = routes, - _routeFactories = routeFactories ?? {} { + }) : _routes = routes, + _routeFactories = routeFactories ?? {} { routes.forEach((name, route) => route.name = name); } diff --git a/packages/flame/lib/src/components/router/value_route.dart b/packages/flame/lib/src/components/router/value_route.dart index 5e7e4f936..43fc4c40d 100644 --- a/packages/flame/lib/src/components/router/value_route.dart +++ b/packages/flame/lib/src/components/router/value_route.dart @@ -18,9 +18,9 @@ import 'package:meta/meta.dart'; /// [_defaultValue] will be used. abstract class ValueRoute extends Route { ValueRoute({required T value, super.transparent}) - : _defaultValue = value, - _completer = Completer(), - super(null); + : _defaultValue = value, + _completer = Completer(), + super(null); final T _defaultValue; final Completer _completer; diff --git a/packages/flame/lib/src/components/router/world_route.dart b/packages/flame/lib/src/components/router/world_route.dart index 16940d016..6ac7ddf77 100644 --- a/packages/flame/lib/src/components/router/world_route.dart +++ b/packages/flame/lib/src/components/router/world_route.dart @@ -69,12 +69,12 @@ class WorldRoute extends Route { @override @internal void addRenderEffect(Decorator effect) => UnimplementedError( - 'WorldRoute does not support render effects', - ); + 'WorldRoute does not support render effects', + ); @override @internal void removeRenderEffect() => UnimplementedError( - 'WorldRoute does not support render effects', - ); + 'WorldRoute does not support render effects', + ); } diff --git a/packages/flame/lib/src/components/scroll_text_box_component.dart b/packages/flame/lib/src/components/scroll_text_box_component.dart index c8e26efda..397254a82 100644 --- a/packages/flame/lib/src/components/scroll_text_box_component.dart +++ b/packages/flame/lib/src/components/scroll_text_box_component.dart @@ -43,11 +43,11 @@ class ScrollTextBoxComponent extends PositionComponent { super.key, List? children, void Function()? onComplete, - }) : assert( - size.x > 0 && size.y > 0, - 'size must have positive dimensions: $size', - ), - super(size: size) { + }) : assert( + size.x > 0 && size.y > 0, + 'size must have positive dimensions: $size', + ), + super(size: size) { final marginTop = boxConfig?.margins.top ?? 0; final marginBottom = boxConfig?.margins.bottom ?? 0; final innerMargins = EdgeInsets.fromLTRB(0, marginTop, 0, marginBottom); @@ -125,10 +125,10 @@ class _ScrollTextBoxComponent extends TextBoxComponent double super.angle = 0.0, super.onComplete, }) : super( - text: text ?? '', - textRenderer: textRenderer ?? TextPaint(), - boxConfig: boxConfig ?? const TextBoxConfig(), - ); + text: text ?? '', + textRenderer: textRenderer ?? TextPaint(), + boxConfig: boxConfig ?? const TextBoxConfig(), + ); @override Future onLoad() { diff --git a/packages/flame/lib/src/components/spawn_component.dart b/packages/flame/lib/src/components/spawn_component.dart index 74cf3375f..8ff33fb92 100644 --- a/packages/flame/lib/src/components/spawn_component.dart +++ b/packages/flame/lib/src/components/spawn_component.dart @@ -35,17 +35,17 @@ class SpawnComponent extends Component { this.spawnWhenLoaded = false, Random? random, super.key, - }) : assert( - !(selfPositioning && area != null), - "Don't set an area when you are using selfPositioning=true", - ), - assert( - (factory != null) ^ (multiFactory != null), - 'You need to provide either a factory or a multiFactory, not both.', - ), - _period = period, - multiFactory = multiFactory ?? _wrapFactory(factory!), - _random = random ?? randomFallback; + }) : assert( + !(selfPositioning && area != null), + "Don't set an area when you are using selfPositioning=true", + ), + assert( + (factory != null) ^ (multiFactory != null), + 'You need to provide either a factory or a multiFactory, not both.', + ), + _period = period, + multiFactory = multiFactory ?? _wrapFactory(factory!), + _random = random ?? randomFallback; /// Use this constructor if you want your components to spawn within an /// interval time range. @@ -66,14 +66,15 @@ class SpawnComponent extends Component { this.spawnWhenLoaded = false, Random? random, super.key, - }) : assert( - !(selfPositioning && area != null), - "Don't set an area when you are using selfPositioning=true", - ), - _period = minPeriod + - (random ?? randomFallback).nextDouble() * (maxPeriod - minPeriod), - multiFactory = multiFactory ?? _wrapFactory(factory!), - _random = random ?? randomFallback; + }) : assert( + !(selfPositioning && area != null), + "Don't set an area when you are using selfPositioning=true", + ), + _period = + minPeriod + + (random ?? randomFallback).nextDouble() * (maxPeriod - minPeriod), + multiFactory = multiFactory ?? _wrapFactory(factory!), + _random = random ?? randomFallback; /// The function used to create a new component to spawn. /// @@ -86,14 +87,14 @@ class SpawnComponent extends Component { /// factory getter wraps it again to return the first element of the list and /// fails when the list is empty! PositionComponent Function(int amount) get factory => (int amount) { - final result = multiFactory.call(amount); - assert( - result.isNotEmpty, - 'The factory call yielded no result, which is required when calling' - ' the single result factory', - ); - return result.elementAt(0); - }; + final result = multiFactory.call(amount); + assert( + result.isNotEmpty, + 'The factory call yielded no result, which is required when calling' + ' the single result factory', + ); + return result.elementAt(0); + }; set factory(PositionComponent Function(int amount) newFactory) { multiFactory = _wrapFactory(newFactory); @@ -183,7 +184,8 @@ class SpawnComponent extends Component { } else { maybeProvidedPosition = null; } - final targetPosition = maybeProvidedPosition ?? + final targetPosition = + maybeProvidedPosition ?? ancestors().whereType().firstOrNull?.position ?? Vector2.zero(); @@ -198,7 +200,8 @@ class SpawnComponent extends Component { } else { maybeProvidedSize = null; } - final targetSize = maybeProvidedSize ?? + final targetSize = + maybeProvidedSize ?? ancestors().whereType().firstOrNull?.size ?? Vector2.zero(); assert( diff --git a/packages/flame/lib/src/components/sprite_animation_component.dart b/packages/flame/lib/src/components/sprite_animation_component.dart index 07d99c2eb..7305cc1d7 100644 --- a/packages/flame/lib/src/components/sprite_animation_component.dart +++ b/packages/flame/lib/src/components/sprite_animation_component.dart @@ -46,12 +46,12 @@ class SpriteAnimationComponent extends PositionComponent with HasPaint { super.children, super.priority, super.key, - }) : assert( - (size == null) == (autoResize ?? size == null), - '''If size is set, autoResize should be false or size should be null when autoResize is true.''', - ), - _autoResize = autoResize ?? size == null, - _animationTicker = animation?.createTicker() { + }) : assert( + (size == null) == (autoResize ?? size == null), + '''If size is set, autoResize should be false or size should be null when autoResize is true.''', + ), + _autoResize = autoResize ?? size == null, + _animationTicker = animation?.createTicker() { if (paint != null) { this.paint = paint; } @@ -85,22 +85,22 @@ class SpriteAnimationComponent extends PositionComponent with HasPaint { int? priority, ComponentKey? key, }) : this( - animation: SpriteAnimation.fromFrameData(image, data), - autoResize: autoResize, - removeOnFinish: removeOnFinish, - playing: playing, - resetOnRemove: resetOnRemove, - paint: paint, - position: position, - size: size, - scale: scale, - angle: angle, - nativeAngle: nativeAngle, - anchor: anchor, - children: children, - priority: priority, - key: key, - ); + animation: SpriteAnimation.fromFrameData(image, data), + autoResize: autoResize, + removeOnFinish: removeOnFinish, + playing: playing, + resetOnRemove: resetOnRemove, + paint: paint, + position: position, + size: size, + scale: scale, + angle: angle, + nativeAngle: nativeAngle, + anchor: anchor, + children: children, + priority: priority, + key: key, + ); /// Returns current value of auto resize flag. bool get autoResize => _autoResize; @@ -135,10 +135,10 @@ class SpriteAnimationComponent extends PositionComponent with HasPaint { @override void render(Canvas canvas) { _animationTicker?.getSprite().render( - canvas, - size: size, - overridePaint: paint, - ); + canvas, + size: size, + overridePaint: paint, + ); } @mustCallSuper diff --git a/packages/flame/lib/src/components/sprite_animation_group_component.dart b/packages/flame/lib/src/components/sprite_animation_group_component.dart index 7f8c9f1e5..c86a50e7a 100644 --- a/packages/flame/lib/src/components/sprite_animation_group_component.dart +++ b/packages/flame/lib/src/components/sprite_animation_group_component.dart @@ -54,20 +54,20 @@ class SpriteAnimationGroupComponent extends PositionComponent with HasPaint { super.children, super.priority, super.key, - }) : assert( - (size == null) == (autoResize ?? size == null), - '''If size is set, autoResize should be false or size should be null when autoResize is true.''', - ), - _current = current, - _animations = animations, - _autoResize = autoResize ?? size == null, - _animationTickers = animations != null - ? Map.fromEntries( - animations.entries - .map((e) => MapEntry(e.key, e.value.createTicker())) - .toList(), - ) - : null { + }) : assert( + (size == null) == (autoResize ?? size == null), + '''If size is set, autoResize should be false or size should be null when autoResize is true.''', + ), + _current = current, + _animations = animations, + _autoResize = autoResize ?? size == null, + _animationTickers = animations != null + ? Map.fromEntries( + animations.entries + .map((e) => MapEntry(e.key, e.value.createTicker())) + .toList(), + ) + : null { if (paint != null) { this.paint = paint; } @@ -102,30 +102,30 @@ class SpriteAnimationGroupComponent extends PositionComponent with HasPaint { int? priority, ComponentKey? key, }) : this( - animations: data.map((key, value) { - return MapEntry( - key, - SpriteAnimation.fromFrameData( - image, - value, - ), - ); - }), - current: current, - autoResize: autoResize, - removeOnFinish: removeOnFinish, - autoResetTicker: autoResetTicker, - playing: playing, - paint: paint, - position: position, - size: size, - scale: scale, - angle: angle, - anchor: anchor, - nativeAngle: nativeAngle, - priority: priority, - key: key, - ); + animations: data.map((key, value) { + return MapEntry( + key, + SpriteAnimation.fromFrameData( + image, + value, + ), + ); + }), + current: current, + autoResize: autoResize, + removeOnFinish: removeOnFinish, + autoResetTicker: autoResetTicker, + playing: playing, + paint: paint, + position: position, + size: size, + scale: scale, + angle: angle, + anchor: anchor, + nativeAngle: nativeAngle, + priority: priority, + key: key, + ); SpriteAnimation? get animation => _animations?[current]; SpriteAnimationTicker? get animationTicker => _animationTickers?[current]; @@ -201,10 +201,10 @@ class SpriteAnimationGroupComponent extends PositionComponent with HasPaint { @override void render(Canvas canvas) { animationTicker?.getSprite().render( - canvas, - size: size, - overridePaint: paint, - ); + canvas, + size: size, + overridePaint: paint, + ); } @mustCallSuper diff --git a/packages/flame/lib/src/components/sprite_component.dart b/packages/flame/lib/src/components/sprite_component.dart index 2538ad167..fd52f264a 100644 --- a/packages/flame/lib/src/components/sprite_component.dart +++ b/packages/flame/lib/src/components/sprite_component.dart @@ -33,13 +33,13 @@ class SpriteComponent extends PositionComponent with HasPaint { super.priority, this.bleed, super.key, - }) : assert( - (size == null) == (autoResize ?? size == null), - '''If size is set, autoResize should be false or size should be null when autoResize is true.''', - ), - _autoResize = autoResize ?? size == null, - _sprite = sprite, - super(size: size ?? sprite?.srcSize) { + }) : assert( + (size == null) == (autoResize ?? size == null), + '''If size is set, autoResize should be false or size should be null when autoResize is true.''', + ), + _autoResize = autoResize ?? size == null, + _sprite = sprite, + super(size: size ?? sprite?.srcSize) { if (paint != null) { this.paint = paint; } @@ -66,24 +66,24 @@ class SpriteComponent extends PositionComponent with HasPaint { ComponentKey? key, double? bleed, }) : this( - sprite: Sprite( - image, - srcPosition: srcPosition, - srcSize: srcSize, - ), - autoResize: autoResize, - paint: paint, - position: position, - size: size, - scale: scale, - angle: angle, - nativeAngle: nativeAngle, - anchor: anchor, - children: children, - priority: priority, - bleed: bleed, - key: key, - ); + sprite: Sprite( + image, + srcPosition: srcPosition, + srcSize: srcSize, + ), + autoResize: autoResize, + paint: paint, + position: position, + size: size, + scale: scale, + angle: angle, + nativeAngle: nativeAngle, + anchor: anchor, + children: children, + priority: priority, + bleed: bleed, + key: key, + ); /// Returns current value of auto resize flag. bool get autoResize => _autoResize; diff --git a/packages/flame/lib/src/components/sprite_group_component.dart b/packages/flame/lib/src/components/sprite_group_component.dart index e312e4740..76c25ddfd 100644 --- a/packages/flame/lib/src/components/sprite_group_component.dart +++ b/packages/flame/lib/src/components/sprite_group_component.dart @@ -39,14 +39,14 @@ class SpriteGroupComponent extends PositionComponent with HasPaint { super.children, super.priority, super.key, - }) : assert( - (size == null) == (autoResize ?? size == null), - '''If size is set, autoResize should be false or size should be null when autoResize is true.''', - ), - _current = current, - _sprites = sprites, - _autoResize = autoResize ?? size == null, - super(size: size ?? sprites?[current]?.srcSize) { + }) : assert( + (size == null) == (autoResize ?? size == null), + '''If size is set, autoResize should be false or size should be null when autoResize is true.''', + ), + _current = current, + _sprites = sprites, + _autoResize = autoResize ?? size == null, + super(size: size ?? sprites?[current]?.srcSize) { if (paint != null) { this.paint = paint; } diff --git a/packages/flame/lib/src/components/text_box_component.dart b/packages/flame/lib/src/components/text_box_component.dart index c117c9cb6..ac24ebf97 100644 --- a/packages/flame/lib/src/components/text_box_component.dart +++ b/packages/flame/lib/src/components/text_box_component.dart @@ -85,8 +85,9 @@ class TextBoxComponent extends TextComponent { // Notifies when a new line is rendered with the position of the new line. @internal - final ValueNotifier newLinePositionNotifier = - ValueNotifier(0); + final ValueNotifier newLinePositionNotifier = ValueNotifier( + 0, + ); double _currentLinePosition = 0.0; bool _isOnCompleteExecuted = false; @@ -111,11 +112,12 @@ class TextBoxComponent extends TextComponent { super.priority, this.onComplete, super.key, - }) : boxConfig = boxConfig ?? const TextBoxConfig(), - _fixedSize = size != null, - align = align ?? Anchor.topLeft, - pixelRatio = pixelRatio ?? - PlatformDispatcher.instance.views.first.devicePixelRatio; + }) : boxConfig = boxConfig ?? const TextBoxConfig(), + _fixedSize = size != null, + align = align ?? Anchor.topLeft, + pixelRatio = + pixelRatio ?? + PlatformDispatcher.instance.views.first.devicePixelRatio; /// Alignment of the text within its bounding box. /// @@ -169,8 +171,9 @@ class TextBoxComponent extends TextComponent { final maxBoxWidth = _fixedSize ? width : boxConfig.maxWidth; for (final word in text.split(' ')) { final wordLines = word.split('\n'); - final possibleLine = - lines.isEmpty ? wordLines[0] : '${lines.last} ${wordLines[0]}'; + final possibleLine = lines.isEmpty + ? wordLines[0] + : '${lines.last} ${wordLines[0]}'; final metrics = textRenderer.getLineMetrics(possibleLine); lineHeight = max(lineHeight, metrics.height); @@ -244,14 +247,17 @@ class TextBoxComponent extends TextComponent { var totalCharCount = 0; final cachedCurrentChar = currentChar; final cachedCurrentLine = currentLine; - final textWidth = lines.sublist(0, cachedCurrentLine + 1).map((line) { - final charCount = (i < cachedCurrentLine) - ? line.length - : (cachedCurrentChar - totalCharCount); - totalCharCount += line.length; - i++; - return getLineWidth(line, charCount); - }).reduce(math.max); + final textWidth = lines + .sublist(0, cachedCurrentLine + 1) + .map((line) { + final charCount = (i < cachedCurrentLine) + ? line.length + : (cachedCurrentChar - totalCharCount); + totalCharCount += line.length; + i++; + return getLineWidth(line, charCount); + }) + .reduce(math.max); return Vector2( textWidth + boxConfig.margins.horizontal, _lineHeight * lines.length + boxConfig.margins.vertical, @@ -282,9 +288,9 @@ class TextBoxComponent extends TextComponent { c.scale(pixelRatio); _fullRender(c); return recorder.endRecording().toImageSafe( - scaledSize.x.ceil(), - scaledSize.y.ceil(), - ); + scaledSize.x.ceil(), + scaledSize.y.ceil(), + ); } /// Override this method to provide a custom background to the text box. diff --git a/packages/flame/lib/src/components/text_component.dart b/packages/flame/lib/src/components/text_component.dart index 6dc8469c3..3ac38b8df 100644 --- a/packages/flame/lib/src/components/text_component.dart +++ b/packages/flame/lib/src/components/text_component.dart @@ -17,8 +17,8 @@ class TextComponent extends PositionComponent { super.children, super.priority, super.key, - }) : _text = text ?? '', - _textRenderer = textRenderer ?? TextRendererFactory.createDefault() { + }) : _text = text ?? '', + _textRenderer = textRenderer ?? TextRendererFactory.createDefault() { updateBounds(); } diff --git a/packages/flame/lib/src/devtools/connectors/component_tree_connector.dart b/packages/flame/lib/src/devtools/connectors/component_tree_connector.dart index 4bcc9f03f..fb04e1406 100644 --- a/packages/flame/lib/src/devtools/connectors/component_tree_connector.dart +++ b/packages/flame/lib/src/devtools/connectors/component_tree_connector.dart @@ -43,24 +43,24 @@ class ComponentTreeNode { ); ComponentTreeNode.fromComponent(Component component) - : this( - component.hashCode, - component.runtimeType.toString(), - component.toString(), - component is PositionComponent, - component.children.map(ComponentTreeNode.fromComponent).toList(), - ); + : this( + component.hashCode, + component.runtimeType.toString(), + component.toString(), + component is PositionComponent, + component.children.map(ComponentTreeNode.fromComponent).toList(), + ); ComponentTreeNode.fromJson(Map json) - : this( - json['id'] as int, - json['name'] as String, - json['toString'] as String, - json['isPositionComponent'] as bool, - (json['children'] as List) - .map((e) => ComponentTreeNode.fromJson(e as Map)) - .toList(), - ); + : this( + json['id'] as int, + json['name'] as String, + json['toString'] as String, + json['isPositionComponent'] as bool, + (json['children'] as List) + .map((e) => ComponentTreeNode.fromJson(e as Map)) + .toList(), + ); Map toJson() { return { diff --git a/packages/flame/lib/src/effects/anchor_by_effect.dart b/packages/flame/lib/src/effects/anchor_by_effect.dart index 5aa28fe10..8985cabc9 100644 --- a/packages/flame/lib/src/effects/anchor_by_effect.dart +++ b/packages/flame/lib/src/effects/anchor_by_effect.dart @@ -25,8 +25,8 @@ class AnchorByEffect extends AnchorEffect { AnchorProvider? target, void Function()? onComplete, super.key, - }) : _offset = offset.clone(), - super(controller, target, onComplete: onComplete); + }) : _offset = offset.clone(), + super(controller, target, onComplete: onComplete); final Vector2 _offset; diff --git a/packages/flame/lib/src/effects/anchor_effect.dart b/packages/flame/lib/src/effects/anchor_effect.dart index 7fbf0dd2e..4f016b6d2 100644 --- a/packages/flame/lib/src/effects/anchor_effect.dart +++ b/packages/flame/lib/src/effects/anchor_effect.dart @@ -32,14 +32,13 @@ abstract class AnchorEffect extends Effect AnchorProvider? target, void Function()? onComplete, ComponentKey? key, - }) => - AnchorByEffect( - offset, - controller, - target: target, - onComplete: onComplete, - key: key, - ); + }) => AnchorByEffect( + offset, + controller, + target: target, + onComplete: onComplete, + key: key, + ); factory AnchorEffect.to( Anchor destination, @@ -47,12 +46,11 @@ abstract class AnchorEffect extends Effect AnchorProvider? target, void Function()? onComplete, ComponentKey? key, - }) => - AnchorToEffect( - destination, - controller, - target: target, - onComplete: onComplete, - key: key, - ); + }) => AnchorToEffect( + destination, + controller, + target: target, + onComplete: onComplete, + key: key, + ); } diff --git a/packages/flame/lib/src/effects/anchor_to_effect.dart b/packages/flame/lib/src/effects/anchor_to_effect.dart index d6e74b3ad..9f0a2035e 100644 --- a/packages/flame/lib/src/effects/anchor_to_effect.dart +++ b/packages/flame/lib/src/effects/anchor_to_effect.dart @@ -16,8 +16,8 @@ class AnchorToEffect extends AnchorEffect { AnchorProvider? target, void Function()? onComplete, super.key, - }) : _destination = destination, - super(controller, target, onComplete: onComplete); + }) : _destination = destination, + super(controller, target, onComplete: onComplete); final Anchor _destination; late Vector2 _offset; diff --git a/packages/flame/lib/src/effects/color_effect.dart b/packages/flame/lib/src/effects/color_effect.dart index d06b22568..b5cb2b1c0 100644 --- a/packages/flame/lib/src/effects/color_effect.dart +++ b/packages/flame/lib/src/effects/color_effect.dart @@ -24,15 +24,15 @@ class ColorEffect extends ComponentEffect { this.paintId, void Function()? onComplete, super.key, - }) : assert( - opacityFrom >= 0 && - opacityFrom <= 1 && - opacityTo >= 0 && - opacityTo <= 1, - 'Opacity value should be between 0 and 1', - ), - _tween = Tween(begin: opacityFrom, end: opacityTo), - super(controller, onComplete: onComplete); + }) : assert( + opacityFrom >= 0 && + opacityFrom <= 1 && + opacityTo >= 0 && + opacityTo <= 1, + 'Opacity value should be between 0 and 1', + ), + _tween = Tween(begin: opacityFrom, end: opacityTo), + super(controller, onComplete: onComplete); @override Future onMount() async { diff --git a/packages/flame/lib/src/effects/controllers/callback_controller.dart b/packages/flame/lib/src/effects/controllers/callback_controller.dart index 5355cf14a..31f07f7c7 100644 --- a/packages/flame/lib/src/effects/controllers/callback_controller.dart +++ b/packages/flame/lib/src/effects/controllers/callback_controller.dart @@ -11,8 +11,8 @@ class CallbackController extends DurationEffectController { /// ensure that this progress level is contiguous with respect to the progress /// of the overall effect. CallbackController(this.callback, {required double progress}) - : _progress = progress, - super(0.0); + : _progress = progress, + super(0.0); final VoidCallback callback; final double _progress; diff --git a/packages/flame/lib/src/effects/controllers/curved_effect_controller.dart b/packages/flame/lib/src/effects/controllers/curved_effect_controller.dart index 7fba9e2e1..158cd9397 100644 --- a/packages/flame/lib/src/effects/controllers/curved_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/curved_effect_controller.dart @@ -5,8 +5,8 @@ import 'package:flutter/animation.dart'; /// [curve]. The [duration] cannot be 0. class CurvedEffectController extends DurationEffectController { CurvedEffectController(super.duration, Curve curve) - : assert(duration > 0, 'Duration must be positive: $duration'), - _curve = curve; + : assert(duration > 0, 'Duration must be positive: $duration'), + _curve = curve; Curve get curve => _curve; final Curve _curve; diff --git a/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart b/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart index 85a93d238..fa957522f 100644 --- a/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/delayed_effect_controller.dart @@ -5,10 +5,10 @@ import 'package:flame/effects.dart'; class DelayedEffectController extends EffectController with HasSingleChildEffectController { DelayedEffectController(EffectController child, {required this.delay}) - : assert(delay >= 0, 'Delay must be non-negative: $delay'), - _child = child, - _timer = 0, - super.empty(); + : assert(delay >= 0, 'Delay must be non-negative: $delay'), + _child = child, + _timer = 0, + super.empty(); final EffectController _child; final double delay; diff --git a/packages/flame/lib/src/effects/controllers/duration_effect_controller.dart b/packages/flame/lib/src/effects/controllers/duration_effect_controller.dart index 4d2fc5703..96599d6ff 100644 --- a/packages/flame/lib/src/effects/controllers/duration_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/duration_effect_controller.dart @@ -12,9 +12,9 @@ import 'package:meta/meta.dart'; /// [duration] value. abstract class DurationEffectController extends EffectController { DurationEffectController(this.duration) - : assert(duration >= 0, 'Duration cannot be negative: $duration'), - _timer = 0, - super.empty(); + : assert(duration >= 0, 'Duration cannot be negative: $duration'), + _timer = 0, + super.empty(); double _timer; diff --git a/packages/flame/lib/src/effects/controllers/effect_controller.dart b/packages/flame/lib/src/effects/controllers/effect_controller.dart index 1295156bb..1c3f95bb3 100644 --- a/packages/flame/lib/src/effects/controllers/effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/effect_controller.dart @@ -176,7 +176,8 @@ abstract class EffectController { if (hasReverse) { final reverseIsLinear = reverseCurve == Curves.linear || ((reverseCurve == null) && isLinear); - final reverseHasDuration = (reverseDuration != null) || + final reverseHasDuration = + (reverseDuration != null) || (reverseSpeed == null && duration != null); if (reverseIsLinear) { items.add( @@ -214,8 +215,9 @@ abstract class EffectController { } assert(items.isNotEmpty); - var controller = - items.length == 1 ? items[0] : SequenceEffectController(items); + var controller = items.length == 1 + ? items[0] + : SequenceEffectController(items); if (infinite) { controller = InfiniteEffectController(controller); } diff --git a/packages/flame/lib/src/effects/controllers/infinite_effect_controller.dart b/packages/flame/lib/src/effects/controllers/infinite_effect_controller.dart index abfcf3b77..76ae8219c 100644 --- a/packages/flame/lib/src/effects/controllers/infinite_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/infinite_effect_controller.dart @@ -5,8 +5,8 @@ import 'package:flame/effects.dart'; class InfiniteEffectController extends EffectController with HasSingleChildEffectController { InfiniteEffectController(EffectController child) - : _child = child, - super.empty(); + : _child = child, + super.empty(); final EffectController _child; diff --git a/packages/flame/lib/src/effects/controllers/pause_effect_controller.dart b/packages/flame/lib/src/effects/controllers/pause_effect_controller.dart index ea1104bc0..03318f2e6 100644 --- a/packages/flame/lib/src/effects/controllers/pause_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/pause_effect_controller.dart @@ -11,7 +11,7 @@ import 'package:flame/src/effects/controllers/duration_effect_controller.dart'; /// 0->1->0 over a short period of time, then pauses, and this sequence repeats. class PauseEffectController extends DurationEffectController { PauseEffectController(super.duration, {required double progress}) - : _progress = progress; + : _progress = progress; final double _progress; diff --git a/packages/flame/lib/src/effects/controllers/random_effect_controller.dart b/packages/flame/lib/src/effects/controllers/random_effect_controller.dart index 1851562e9..fbf8da127 100644 --- a/packages/flame/lib/src/effects/controllers/random_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/random_effect_controller.dart @@ -15,9 +15,9 @@ import 'package:flame/effects.dart'; class RandomEffectController extends EffectController with HasSingleChildEffectController { RandomEffectController(DurationEffectController child, this.randomGenerator) - : assert(!child.isInfinite, 'Child cannot be infinite'), - _child = child, - super.empty() { + : assert(!child.isInfinite, 'Child cannot be infinite'), + _child = child, + super.empty() { _initializeDuration(); } diff --git a/packages/flame/lib/src/effects/controllers/repeated_effect_controller.dart b/packages/flame/lib/src/effects/controllers/repeated_effect_controller.dart index de3ccd788..74bf98af2 100644 --- a/packages/flame/lib/src/effects/controllers/repeated_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/repeated_effect_controller.dart @@ -8,11 +8,11 @@ import 'package:flame/effects.dart'; class RepeatedEffectController extends EffectController with HasSingleChildEffectController { RepeatedEffectController(EffectController child, this.repeatCount) - : assert(repeatCount > 0, 'repeatCount must be positive'), - assert(!child.isInfinite, 'child cannot be infinite'), - _child = child, - _remainingCount = repeatCount, - super.empty(); + : assert(repeatCount > 0, 'repeatCount must be positive'), + assert(!child.isInfinite, 'child cannot be infinite'), + _child = child, + _remainingCount = repeatCount, + super.empty(); final EffectController _child; final int repeatCount; diff --git a/packages/flame/lib/src/effects/controllers/reverse_curved_effect_controller.dart b/packages/flame/lib/src/effects/controllers/reverse_curved_effect_controller.dart index 7ac4eca78..b9a352d0e 100644 --- a/packages/flame/lib/src/effects/controllers/reverse_curved_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/reverse_curved_effect_controller.dart @@ -5,8 +5,8 @@ import 'package:flutter/animation.dart'; /// [curve]. The [duration] cannot be 0. class ReverseCurvedEffectController extends DurationEffectController { ReverseCurvedEffectController(super.duration, Curve curve) - : assert(duration > 0, 'Duration must be positive: $duration'), - _curve = curve; + : assert(duration > 0, 'Duration must be positive: $duration'), + _curve = curve; Curve get curve => _curve; final Curve _curve; diff --git a/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart b/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart index 165b8e356..54ddaf9da 100644 --- a/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/sequence_effect_controller.dart @@ -5,14 +5,14 @@ import 'package:flame/src/effects/effect.dart'; /// another. class SequenceEffectController extends EffectController { SequenceEffectController(List controllers) - : assert(controllers.isNotEmpty, 'List of controllers cannot be empty'), - assert( - !controllers.any((c) => c.isInfinite), - 'Children controllers cannot be infinite', - ), - children = controllers, - _currentIndex = 0, - super.empty(); + : assert(controllers.isNotEmpty, 'List of controllers cannot be empty'), + assert( + !controllers.any((c) => c.isInfinite), + 'Children controllers cannot be infinite', + ), + children = controllers, + _currentIndex = 0, + super.empty(); /// Individual controllers in the sequence. final List children; diff --git a/packages/flame/lib/src/effects/controllers/sine_effect_controller.dart b/packages/flame/lib/src/effects/controllers/sine_effect_controller.dart index 4b69d7073..c3ec50437 100644 --- a/packages/flame/lib/src/effects/controllers/sine_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/sine_effect_controller.dart @@ -13,8 +13,8 @@ import 'package:flame/src/effects/controllers/repeated_effect_controller.dart'; /// order to create longer waves. class SineEffectController extends DurationEffectController { SineEffectController({required double period}) - : assert(period > 0, 'Period must be positive: $period'), - super(period); + : assert(period > 0, 'Period must be positive: $period'), + super(period); @override double get progress { diff --git a/packages/flame/lib/src/effects/controllers/speed_effect_controller.dart b/packages/flame/lib/src/effects/controllers/speed_effect_controller.dart index 6a77054c1..ea1641ace 100644 --- a/packages/flame/lib/src/effects/controllers/speed_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/speed_effect_controller.dart @@ -16,9 +16,9 @@ import 'package:flame/src/effects/measurable_effect.dart'; class SpeedEffectController extends EffectController with HasSingleChildEffectController { SpeedEffectController(DurationEffectController child, {required this.speed}) - : assert(speed > 0, 'Speed must be positive: $speed'), - _child = child, - super.empty(); + : assert(speed > 0, 'Speed must be positive: $speed'), + _child = child, + super.empty(); final DurationEffectController _child; final double speed; diff --git a/packages/flame/lib/src/effects/controllers/zigzag_effect_controller.dart b/packages/flame/lib/src/effects/controllers/zigzag_effect_controller.dart index a8ef4d9e0..5624cf29a 100644 --- a/packages/flame/lib/src/effects/controllers/zigzag_effect_controller.dart +++ b/packages/flame/lib/src/effects/controllers/zigzag_effect_controller.dart @@ -12,9 +12,9 @@ import 'package:flame/src/effects/controllers/repeated_effect_controller.dart'; /// order to create longer zigzags. class ZigzagEffectController extends DurationEffectController { ZigzagEffectController({required double period}) - : assert(period > 0, 'Period must be positive: $period'), - _quarterPeriod = period / 4, - super(period); + : assert(period > 0, 'Period must be positive: $period'), + _quarterPeriod = period / 4, + super(period); final double _quarterPeriod; diff --git a/packages/flame/lib/src/effects/effect.dart b/packages/flame/lib/src/effects/effect.dart index 7ed3bf6dc..4bb183828 100644 --- a/packages/flame/lib/src/effects/effect.dart +++ b/packages/flame/lib/src/effects/effect.dart @@ -31,10 +31,10 @@ abstract class Effect extends Component { this.controller, { this.onComplete, super.key, - }) : removeOnFinish = true, - _paused = false, - _started = false, - _finished = false { + }) : removeOnFinish = true, + _paused = false, + _started = false, + _finished = false { controller.onMount(this); } @@ -213,5 +213,5 @@ abstract class Effect extends Component { /// This is a main method that MUST be implemented in every derived class. void apply(double progress); -//#endregion + //#endregion } diff --git a/packages/flame/lib/src/effects/move_along_path_effect.dart b/packages/flame/lib/src/effects/move_along_path_effect.dart index d26832cc3..fc4bc8ee1 100644 --- a/packages/flame/lib/src/effects/move_along_path_effect.dart +++ b/packages/flame/lib/src/effects/move_along_path_effect.dart @@ -32,13 +32,13 @@ class MoveAlongPathEffect extends MoveEffect { PositionProvider? target, void Function()? onComplete, super.key, - }) : _isAbsolute = absolute, - _followDirection = oriented, - super( - controller, - target, - onComplete: onComplete, - ) { + }) : _isAbsolute = absolute, + _followDirection = oriented, + super( + controller, + target, + onComplete: onComplete, + ) { final metrics = path.computeMetrics().toList(); if (metrics.length != 1) { throw ArgumentError( diff --git a/packages/flame/lib/src/effects/move_by_effect.dart b/packages/flame/lib/src/effects/move_by_effect.dart index 43052d04b..a84d27831 100644 --- a/packages/flame/lib/src/effects/move_by_effect.dart +++ b/packages/flame/lib/src/effects/move_by_effect.dart @@ -24,8 +24,8 @@ class MoveByEffect extends MoveEffect { PositionProvider? target, void Function()? onComplete, super.key, - }) : _offset = offset.clone(), - super(controller, target, onComplete: onComplete); + }) : _offset = offset.clone(), + super(controller, target, onComplete: onComplete); final Vector2 _offset; diff --git a/packages/flame/lib/src/effects/move_effect.dart b/packages/flame/lib/src/effects/move_effect.dart index acff5968e..dab3d4cec 100644 --- a/packages/flame/lib/src/effects/move_effect.dart +++ b/packages/flame/lib/src/effects/move_effect.dart @@ -32,14 +32,13 @@ abstract class MoveEffect extends Effect PositionProvider? target, void Function()? onComplete, ComponentKey? key, - }) => - MoveByEffect( - offset, - controller, - target: target, - onComplete: onComplete, - key: key, - ); + }) => MoveByEffect( + offset, + controller, + target: target, + onComplete: onComplete, + key: key, + ); factory MoveEffect.to( Vector2 destination, @@ -47,12 +46,11 @@ abstract class MoveEffect extends Effect PositionProvider? target, void Function()? onComplete, ComponentKey? key, - }) => - MoveToEffect( - destination, - controller, - target: target, - onComplete: onComplete, - key: key, - ); + }) => MoveToEffect( + destination, + controller, + target: target, + onComplete: onComplete, + key: key, + ); } diff --git a/packages/flame/lib/src/effects/move_to_effect.dart b/packages/flame/lib/src/effects/move_to_effect.dart index bfaadd974..120293dc8 100644 --- a/packages/flame/lib/src/effects/move_to_effect.dart +++ b/packages/flame/lib/src/effects/move_to_effect.dart @@ -26,9 +26,9 @@ class MoveToEffect extends MoveEffect { PositionProvider? target, void Function()? onComplete, super.key, - }) : _destination = destination.clone(), - _offset = Vector2.zero(), - super(controller, target, onComplete: onComplete); + }) : _destination = destination.clone(), + _offset = Vector2.zero(), + super(controller, target, onComplete: onComplete); final Vector2 _destination; final Vector2 _offset; diff --git a/packages/flame/lib/src/effects/opacity_effect.dart b/packages/flame/lib/src/effects/opacity_effect.dart index 06cc251e3..d40e5e8b5 100644 --- a/packages/flame/lib/src/effects/opacity_effect.dart +++ b/packages/flame/lib/src/effects/opacity_effect.dart @@ -99,11 +99,11 @@ class _OpacityToEffect extends OpacityEffect { void Function()? onComplete, super.key, }) : super.by( - 0.0, - controller, - target: target, - onComplete: onComplete, - ); + 0.0, + controller, + target: target, + onComplete: onComplete, + ); @override void onStart() { diff --git a/packages/flame/lib/src/effects/provider_interfaces.dart b/packages/flame/lib/src/effects/provider_interfaces.dart index ea3a171a8..f7a4e20aa 100644 --- a/packages/flame/lib/src/effects/provider_interfaces.dart +++ b/packages/flame/lib/src/effects/provider_interfaces.dart @@ -20,8 +20,8 @@ class PositionProviderImpl implements PositionProvider { PositionProviderImpl({ Vector2 Function()? getValue, void Function(Vector2)? setValue, - }) : _getter = getValue, - _setter = setValue; + }) : _getter = getValue, + _setter = setValue; final Vector2 Function()? _getter; final void Function(Vector2)? _setter; diff --git a/packages/flame/lib/src/effects/remove_effect.dart b/packages/flame/lib/src/effects/remove_effect.dart index 0dfaa5374..cebe42ced 100644 --- a/packages/flame/lib/src/effects/remove_effect.dart +++ b/packages/flame/lib/src/effects/remove_effect.dart @@ -8,9 +8,9 @@ class RemoveEffect extends ComponentEffect { void Function()? onComplete, super.key, }) : super( - LinearEffectController(delay), - onComplete: onComplete, - ); + LinearEffectController(delay), + onComplete: onComplete, + ); @override void apply(double progress) { diff --git a/packages/flame/lib/src/effects/rotate_effect.dart b/packages/flame/lib/src/effects/rotate_effect.dart index 40a6c19c8..0a72d8aeb 100644 --- a/packages/flame/lib/src/effects/rotate_effect.dart +++ b/packages/flame/lib/src/effects/rotate_effect.dart @@ -63,8 +63,8 @@ class _RotateToEffect extends RotateEffect { EffectController controller, { void Function()? onComplete, super.key, - }) : _destinationAngle = angle, - super.by(0, controller, onComplete: onComplete); + }) : _destinationAngle = angle, + super.by(0, controller, onComplete: onComplete); final double _destinationAngle; diff --git a/packages/flame/lib/src/effects/scale_effect.dart b/packages/flame/lib/src/effects/scale_effect.dart index 7350b16aa..71a6ba162 100644 --- a/packages/flame/lib/src/effects/scale_effect.dart +++ b/packages/flame/lib/src/effects/scale_effect.dart @@ -28,13 +28,12 @@ class ScaleEffect extends Effect with EffectTarget { EffectController controller, { void Function()? onComplete, ComponentKey? key, - }) => - _ScaleToEffect( - targetScale, - controller, - onComplete: onComplete, - key: key, - ); + }) => _ScaleToEffect( + targetScale, + controller, + onComplete: onComplete, + key: key, + ); final Vector2 _scaleFactor; late Vector2 _scaleDelta; @@ -63,12 +62,12 @@ class _ScaleToEffect extends ScaleEffect { EffectController controller, { void Function()? onComplete, super.key, - }) : _targetScale = targetScale.clone(), - super.by( - Vector2.zero(), - controller, - onComplete: onComplete, - ); + }) : _targetScale = targetScale.clone(), + super.by( + Vector2.zero(), + controller, + onComplete: onComplete, + ); @override void onStart() { diff --git a/packages/flame/lib/src/effects/sequence_effect.dart b/packages/flame/lib/src/effects/sequence_effect.dart index 625146dd5..28bd14863 100644 --- a/packages/flame/lib/src/effects/sequence_effect.dart +++ b/packages/flame/lib/src/effects/sequence_effect.dart @@ -53,20 +53,20 @@ class SequenceEffect extends Effect { int repeatCount = 1, super.onComplete, super.key, - }) : assert(effects.isNotEmpty, 'The list of effects cannot be empty'), - assert( - !(infinite && repeatCount != 1), - 'Parameters infinite and repeatCount cannot be specified ' - 'simultaneously', - ), - super( - _createController( - effects: effects, - alternate: alternate, - infinite: infinite, - repeatCount: repeatCount, - ), - ) { + }) : assert(effects.isNotEmpty, 'The list of effects cannot be empty'), + assert( + !(infinite && repeatCount != 1), + 'Parameters infinite and repeatCount cannot be specified ' + 'simultaneously', + ), + super( + _createController( + effects: effects, + alternate: alternate, + infinite: infinite, + repeatCount: repeatCount, + ), + ) { addAll(effects); } diff --git a/packages/flame/lib/src/effects/size_effect.dart b/packages/flame/lib/src/effects/size_effect.dart index c9acb447f..7e50eaf1f 100644 --- a/packages/flame/lib/src/effects/size_effect.dart +++ b/packages/flame/lib/src/effects/size_effect.dart @@ -37,13 +37,12 @@ class SizeEffect extends Effect with EffectTarget { EffectController controller, { void Function()? onComplete, ComponentKey? key, - }) => - _SizeToEffect( - targetSize, - controller, - onComplete: onComplete, - key: key, - ); + }) => _SizeToEffect( + targetSize, + controller, + onComplete: onComplete, + key: key, + ); Vector2 _offset; @@ -64,12 +63,12 @@ class _SizeToEffect extends SizeEffect { EffectController controller, { void Function()? onComplete, super.key, - }) : _targetSize = targetSize.clone(), - super.by( - Vector2.zero(), - controller, - onComplete: onComplete, - ); + }) : _targetSize = targetSize.clone(), + super.by( + Vector2.zero(), + controller, + onComplete: onComplete, + ); @override void onStart() { diff --git a/packages/flame/lib/src/events/flame_game_mixins/double_tap_dispatcher.dart b/packages/flame/lib/src/events/flame_game_mixins/double_tap_dispatcher.dart index 825694702..a3508d87f 100644 --- a/packages/flame/lib/src/events/flame_game_mixins/double_tap_dispatcher.dart +++ b/packages/flame/lib/src/events/flame_game_mixins/double_tap_dispatcher.dart @@ -52,10 +52,10 @@ class DoubleTapDispatcher extends Component with HasGameReference { game.gestureDetectors.add( DoubleTapGestureRecognizer.new, (DoubleTapGestureRecognizer instance) { - instance.onDoubleTapDown = - (details) => _onDoubleTapDown(DoubleTapDownEvent(game, details)); - instance.onDoubleTapCancel = - () => _onDoubleTapCancel(DoubleTapCancelEvent()); + instance.onDoubleTapDown = (details) => + _onDoubleTapDown(DoubleTapDownEvent(game, details)); + instance.onDoubleTapCancel = () => + _onDoubleTapCancel(DoubleTapCancelEvent()); instance.onDoubleTap = () => _onDoubleTapUp(DoubleTapEvent()); }, ); diff --git a/packages/flame/lib/src/events/hardware_keyboard_detector.dart b/packages/flame/lib/src/events/hardware_keyboard_detector.dart index 160b2dbaf..d29ea151c 100644 --- a/packages/flame/lib/src/events/hardware_keyboard_detector.dart +++ b/packages/flame/lib/src/events/hardware_keyboard_detector.dart @@ -33,7 +33,7 @@ import 'package:flutter/services.dart'; /// is removed from the component tree. class HardwareKeyboardDetector extends Component { HardwareKeyboardDetector({void Function(KeyEvent)? onKeyEvent}) - : _onKeyEvent = onKeyEvent; + : _onKeyEvent = onKeyEvent; final List _physicalKeys = []; Set _logicalKeys = {}; diff --git a/packages/flame/lib/src/events/messages/displacement_event.dart b/packages/flame/lib/src/events/messages/displacement_event.dart index 92260fdba..e576f66be 100644 --- a/packages/flame/lib/src/events/messages/displacement_event.dart +++ b/packages/flame/lib/src/events/messages/displacement_event.dart @@ -6,10 +6,7 @@ import 'package:flame/src/game/game.dart'; /// /// This represents a user event that has a start and end locations, as the /// ones that are represented by a [DisplacementEvent]. -typedef DisplacementContext = ({ - Vector2 start, - Vector2 end, -}); +typedef DisplacementContext = ({Vector2 start, Vector2 end}); extension DisplacementContextDelta on DisplacementContext { /// Displacement delta @@ -44,8 +41,9 @@ abstract class DisplacementEvent /// relative to the game canvas. /// /// This could be considered the Flame-level global position. - late final Vector2 canvasStartPosition = - _game.convertGlobalToLocalCoordinate(deviceStartPosition); + late final Vector2 canvasStartPosition = _game.convertGlobalToLocalCoordinate( + deviceStartPosition, + ); /// Event start position in the local coordinate space of the current /// component. @@ -67,8 +65,9 @@ abstract class DisplacementEvent /// relative to the game canvas. /// /// This could be considered the Flame-level global position. - late final Vector2 canvasEndPosition = - _game.convertGlobalToLocalCoordinate(deviceEndPosition); + late final Vector2 canvasEndPosition = _game.convertGlobalToLocalCoordinate( + deviceEndPosition, + ); /// Event end position in the local coordinate space of the current /// component. diff --git a/packages/flame/lib/src/events/messages/double_tap_down_event.dart b/packages/flame/lib/src/events/messages/double_tap_down_event.dart index b1d5d012f..eacc190f1 100644 --- a/packages/flame/lib/src/events/messages/double_tap_down_event.dart +++ b/packages/flame/lib/src/events/messages/double_tap_down_event.dart @@ -6,8 +6,8 @@ class DoubleTapDownEvent extends PositionEvent { final PointerDeviceKind deviceKind; DoubleTapDownEvent(super.game, TapDownDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( - devicePosition: details.globalPosition.toVector2(), - ); + : deviceKind = details.kind ?? PointerDeviceKind.unknown, + super( + devicePosition: details.globalPosition.toVector2(), + ); } diff --git a/packages/flame/lib/src/events/messages/drag_end_event.dart b/packages/flame/lib/src/events/messages/drag_end_event.dart index 1f114dcd3..1e8cc77f0 100644 --- a/packages/flame/lib/src/events/messages/drag_end_event.dart +++ b/packages/flame/lib/src/events/messages/drag_end_event.dart @@ -4,7 +4,7 @@ import 'package:flutter/gestures.dart'; class DragEndEvent extends Event { DragEndEvent(this.pointerId, DragEndDetails details) - : velocity = details.velocity.pixelsPerSecond.toVector2(); + : velocity = details.velocity.pixelsPerSecond.toVector2(); final int pointerId; diff --git a/packages/flame/lib/src/events/messages/drag_start_event.dart b/packages/flame/lib/src/events/messages/drag_start_event.dart index b6998adc3..b69ef0468 100644 --- a/packages/flame/lib/src/events/messages/drag_start_event.dart +++ b/packages/flame/lib/src/events/messages/drag_start_event.dart @@ -10,10 +10,10 @@ import 'package:flutter/gestures.dart'; /// This is a [PositionEvent], where the position is the point of touch. class DragStartEvent extends PositionEvent { DragStartEvent(this.pointerId, super.game, DragStartDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( - devicePosition: details.globalPosition.toVector2(), - ); + : deviceKind = details.kind ?? PointerDeviceKind.unknown, + super( + devicePosition: details.globalPosition.toVector2(), + ); /// The unique identifier of the drag event. /// @@ -25,7 +25,8 @@ class DragStartEvent extends PositionEvent { final PointerDeviceKind deviceKind; @override - String toString() => 'DragStartEvent(canvasPosition: $canvasPosition, ' + String toString() => + 'DragStartEvent(canvasPosition: $canvasPosition, ' 'devicePosition: $devicePosition, ' 'pointedId: $pointerId, deviceKind: $deviceKind)'; } diff --git a/packages/flame/lib/src/events/messages/drag_update_event.dart b/packages/flame/lib/src/events/messages/drag_update_event.dart index c88b67867..3cf17fb09 100644 --- a/packages/flame/lib/src/events/messages/drag_update_event.dart +++ b/packages/flame/lib/src/events/messages/drag_update_event.dart @@ -4,18 +4,19 @@ import 'package:flutter/gestures.dart'; class DragUpdateEvent extends DisplacementEvent { DragUpdateEvent(this.pointerId, super.game, DragUpdateDetails details) - : timestamp = details.sourceTimeStamp ?? Duration.zero, - super( - deviceStartPosition: details.globalPosition.toVector2(), - deviceEndPosition: - details.globalPosition.toVector2() + details.delta.toVector2(), - ); + : timestamp = details.sourceTimeStamp ?? Duration.zero, + super( + deviceStartPosition: details.globalPosition.toVector2(), + deviceEndPosition: + details.globalPosition.toVector2() + details.delta.toVector2(), + ); final int pointerId; final Duration timestamp; @override - String toString() => 'DragUpdateEvent(' + String toString() => + 'DragUpdateEvent(' 'devicePosition: $deviceStartPosition, ' 'canvasPosition: $canvasStartPosition, ' 'delta: $localDelta, ' diff --git a/packages/flame/lib/src/events/messages/event.dart b/packages/flame/lib/src/events/messages/event.dart index 4298b0bb0..3dc41d266 100644 --- a/packages/flame/lib/src/events/messages/event.dart +++ b/packages/flame/lib/src/events/messages/event.dart @@ -27,9 +27,10 @@ abstract class Event { Component rootComponent, void Function(T component) eventHandler, ) { - for (final child in rootComponent - .descendants(reversed: true, includeSelf: true) - .whereType()) { + for (final child + in rootComponent + .descendants(reversed: true, includeSelf: true) + .whereType()) { continuePropagation = false; eventHandler(child); if (!continuePropagation) { diff --git a/packages/flame/lib/src/events/messages/pointer_move_event.dart b/packages/flame/lib/src/events/messages/pointer_move_event.dart index bc9ecead3..1364494fa 100644 --- a/packages/flame/lib/src/events/messages/pointer_move_event.dart +++ b/packages/flame/lib/src/events/messages/pointer_move_event.dart @@ -8,11 +8,11 @@ class PointerMoveEvent extends PositionEvent { this.pointerId, super.game, flutter.PointerHoverEvent rawEvent, - ) : timestamp = rawEvent.timeStamp, - delta = rawEvent.delta.toVector2(), - super( - devicePosition: rawEvent.position.toVector2(), - ); + ) : timestamp = rawEvent.timeStamp, + delta = rawEvent.delta.toVector2(), + super( + devicePosition: rawEvent.position.toVector2(), + ); final int pointerId; final Duration timestamp; @@ -26,7 +26,8 @@ class PointerMoveEvent extends PositionEvent { } @override - String toString() => 'PointerMoveEvent(devicePosition: $devicePosition, ' + String toString() => + 'PointerMoveEvent(devicePosition: $devicePosition, ' 'canvasPosition: $canvasPosition, ' 'delta: $delta, ' 'pointerId: $pointerId, timestamp: $timestamp)'; diff --git a/packages/flame/lib/src/events/messages/position_event.dart b/packages/flame/lib/src/events/messages/position_event.dart index e3844ea81..7885ccb31 100644 --- a/packages/flame/lib/src/events/messages/position_event.dart +++ b/packages/flame/lib/src/events/messages/position_event.dart @@ -23,8 +23,9 @@ abstract class PositionEvent extends LocationContextEvent { /// to the game canvas. /// /// This could be considered the Flame-level global position. - late final Vector2 canvasPosition = - _game.convertGlobalToLocalCoordinate(devicePosition); + late final Vector2 canvasPosition = _game.convertGlobalToLocalCoordinate( + devicePosition, + ); /// Event position in the local coordinate space of the current component. /// diff --git a/packages/flame/lib/src/events/messages/tap_down_event.dart b/packages/flame/lib/src/events/messages/tap_down_event.dart index 6cad4a3c4..8b2697882 100644 --- a/packages/flame/lib/src/events/messages/tap_down_event.dart +++ b/packages/flame/lib/src/events/messages/tap_down_event.dart @@ -14,10 +14,10 @@ import 'package:flutter/gestures.dart'; /// the [TapCallbacks] mixin. class TapDownEvent extends PositionEvent { TapDownEvent(this.pointerId, super.game, TapDownDetails details) - : deviceKind = details.kind ?? PointerDeviceKind.unknown, - super( - devicePosition: details.globalPosition.toVector2(), - ); + : deviceKind = details.kind ?? PointerDeviceKind.unknown, + super( + devicePosition: details.globalPosition.toVector2(), + ); /// The unique identifier of the tap event. /// @@ -29,7 +29,8 @@ class TapDownEvent extends PositionEvent { final PointerDeviceKind deviceKind; @override - String toString() => 'TapDownEvent(canvasPosition: $canvasPosition, ' + String toString() => + 'TapDownEvent(canvasPosition: $canvasPosition, ' 'devicePosition: $devicePosition, ' 'pointerId: $pointerId, deviceKind: $deviceKind)'; } diff --git a/packages/flame/lib/src/events/messages/tap_up_event.dart b/packages/flame/lib/src/events/messages/tap_up_event.dart index 93ed74828..cd36883ca 100644 --- a/packages/flame/lib/src/events/messages/tap_up_event.dart +++ b/packages/flame/lib/src/events/messages/tap_up_event.dart @@ -12,10 +12,10 @@ import 'package:flutter/gestures.dart'; /// The [TapUpEvent] will only occur if there was a previous [TapDownEvent]. class TapUpEvent extends PositionEvent { TapUpEvent(this.pointerId, super.game, TapUpDetails details) - : deviceKind = details.kind, - super( - devicePosition: details.globalPosition.toVector2(), - ); + : deviceKind = details.kind, + super( + devicePosition: details.globalPosition.toVector2(), + ); /// The id of the previous [TapDownEvent] to which this event corresponds. final int pointerId; @@ -23,7 +23,8 @@ class TapUpEvent extends PositionEvent { final PointerDeviceKind deviceKind; @override - String toString() => 'TapUpEvent(canvasPosition: $canvasPosition, ' + String toString() => + 'TapUpEvent(canvasPosition: $canvasPosition, ' 'devicePosition: $devicePosition, ' 'pointerId: $pointerId, deviceKind: $deviceKind)'; } diff --git a/packages/flame/lib/src/experimental/geometry/shapes/circle.dart b/packages/flame/lib/src/experimental/geometry/shapes/circle.dart index 9b7e85916..b09ecede6 100644 --- a/packages/flame/lib/src/experimental/geometry/shapes/circle.dart +++ b/packages/flame/lib/src/experimental/geometry/shapes/circle.dart @@ -18,9 +18,9 @@ import 'package:flame/src/math/random_fallback.dart'; /// this is currently not implemented. class Circle extends Shape { Circle(Vector2 center, double radius) - : assert(radius >= 0, 'Radius cannot be negative: $radius'), - _center = center.clone(), - _radius = radius; + : assert(radius >= 0, 'Radius cannot be negative: $radius'), + _center = center.clone(), + _radius = radius; @override Vector2 get center => _center; diff --git a/packages/flame/lib/src/experimental/geometry/shapes/polygon.dart b/packages/flame/lib/src/experimental/geometry/shapes/polygon.dart index 66b7070a4..3c03c1919 100644 --- a/packages/flame/lib/src/experimental/geometry/shapes/polygon.dart +++ b/packages/flame/lib/src/experimental/geometry/shapes/polygon.dart @@ -26,7 +26,7 @@ class Polygon extends Shape { /// the polygon is convex or not. With this flag the user promises that the /// vertices are already in the correct CCW order. Polygon(this._vertices, {bool? convex}) - : assert(_vertices.length >= 3, 'At least 3 vertices are required') { + : assert(_vertices.length >= 3, 'At least 3 vertices are required') { _initializeEdges(); if (convex == null) { _ensureProperOrientation(); @@ -51,11 +51,13 @@ class Polygon extends Shape { late List _edges; void _initializeEdges() { var previousVertex = _vertices.last; - _edges = _vertices.map((Vector2 vertex) { - final edge = vertex - previousVertex; - previousVertex = vertex; - return edge; - }).toList(growable: false); + _edges = _vertices + .map((Vector2 vertex) { + final edge = vertex - previousVertex; + previousVertex = vertex; + return edge; + }) + .toList(growable: false); } /// Checks whether the vertices are listed in the CCW order, and if not diff --git a/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart b/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart index eaa6cb560..bb599e407 100644 --- a/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart +++ b/packages/flame/lib/src/experimental/geometry/shapes/rectangle.dart @@ -37,7 +37,7 @@ class Rectangle extends Shape { } Rectangle.fromLTWH(double left, double top, double width, double height) - : this.fromLTRB(left, top, left + width, top + height); + : this.fromLTRB(left, top, left + width, top + height); /// Constructs a [Rectangle] from two opposite corners. The points can be in /// any disposition to each other. @@ -147,11 +147,10 @@ class Rectangle extends Shape { @override Vector2 nearestPoint(Vector2 point) { - return _tmpResult - ..setValues( - (point.x).clamp(_left, _right), - (point.y).clamp(_top, _bottom), - ); + return _tmpResult..setValues( + (point.x).clamp(_left, _right), + (point.y).clamp(_top, _bottom), + ); } Rect toRect() => Rect.fromLTWH(left, top, width, height); diff --git a/packages/flame/lib/src/experimental/linear_layout_component.dart b/packages/flame/lib/src/experimental/linear_layout_component.dart index c8e1d507f..998c1ab8d 100644 --- a/packages/flame/lib/src/experimental/linear_layout_component.dart +++ b/packages/flame/lib/src/experimental/linear_layout_component.dart @@ -67,9 +67,9 @@ abstract class LinearLayoutComponent extends LayoutComponent { required super.children, required super.size, super.priority, - }) : _crossAxisAlignment = crossAxisAlignment, - _mainAxisAlignment = mainAxisAlignment, - _gap = gap; + }) : _crossAxisAlignment = crossAxisAlignment, + _mainAxisAlignment = mainAxisAlignment, + _gap = gap; factory LinearLayoutComponent.fromDirection( Direction direction, { @@ -237,17 +237,18 @@ abstract class LinearLayoutComponent extends LayoutComponent { final mainAxisVectorIndex = direction.mainAxisVectorIndex; final componentList = reverse ? components.reversed : components; for (final (index, component) in componentList.indexed) { - final previousChild = - index > 0 ? componentList.elementAt(index - 1) : null; + final previousChild = index > 0 + ? componentList.elementAt(index - 1) + : null; final reference = previousChild == null // Essentially the same as start, but gap is set. ? initialOffset.toVector2() // The "end" at any loop other than the first is the previous // child's top left position minus the gap. : previousChild.topLeftPosition + - (reverse - ? -Vector2.all(gap) - : previousChild.size + Vector2.all(gap)); + (reverse + ? -Vector2.all(gap) + : previousChild.size + Vector2.all(gap)); final positionOffset = reverse ? component.size : Vector2.zero(); final newPosition = Vector2.zero(); newPosition[mainAxisVectorIndex] = @@ -325,7 +326,8 @@ abstract class LinearLayoutComponent extends LayoutComponent { // This should only apply when mainAxisAlignment is start, center, or end. // spaceAround, spaceBetween, and spaceEvenly requires the size as a // constraint. - final cumulativeMainAxisLength = ((positionChildren.length - 1) * gap) + + final cumulativeMainAxisLength = + ((positionChildren.length - 1) * gap) + positionChildren .map((component) => component.size[mainAxisVectorIndex]) .sum; diff --git a/packages/flame/lib/src/experimental/padding_component.dart b/packages/flame/lib/src/experimental/padding_component.dart index 8e62b14c2..3ed5b752f 100644 --- a/packages/flame/lib/src/experimental/padding_component.dart +++ b/packages/flame/lib/src/experimental/padding_component.dart @@ -20,8 +20,8 @@ class PaddingComponent extends LayoutComponent { super.anchor, super.position, PositionComponent? child, - }) : _padding = padding ?? EdgeInsets.zero, - super(size: null) { + }) : _padding = padding ?? EdgeInsets.zero, + super(size: null) { this.child = child; } diff --git a/packages/flame/lib/src/experimental/raycast_result.dart b/packages/flame/lib/src/experimental/raycast_result.dart index 83674b782..b0a99b800 100644 --- a/packages/flame/lib/src/experimental/raycast_result.dart +++ b/packages/flame/lib/src/experimental/raycast_result.dart @@ -17,11 +17,11 @@ class RaycastResult> { Vector2? normal, double? distance, bool isInsideHitbox = false, - }) : _isInsideHitbox = isInsideHitbox, - _hitbox = hitbox, - _reflectionRay = reflectionRay ?? Ray2.zero(), - _normal = normal ?? Vector2.zero(), - _distance = distance ?? double.maxFinite; + }) : _isInsideHitbox = isInsideHitbox, + _hitbox = hitbox, + _reflectionRay = reflectionRay ?? Ray2.zero(), + _normal = normal ?? Vector2.zero(), + _distance = distance ?? double.maxFinite; /// Whether this result has active results in it. /// diff --git a/packages/flame/lib/src/game/flame_game.dart b/packages/flame/lib/src/game/flame_game.dart index 3894bfdbb..1df0a9b91 100644 --- a/packages/flame/lib/src/game/flame_game.dart +++ b/packages/flame/lib/src/game/flame_game.dart @@ -23,13 +23,13 @@ class FlameGame extends ComponentTreeRoot super.children, W? world, CameraComponent? camera, - }) : assert( - world != null || W == World, - 'The generics type $W does not conform to the type of ' - '${world?.runtimeType ?? 'World'}.', - ), - _world = world ?? World() as W, - _camera = camera ?? CameraComponent() { + }) : assert( + world != null || W == World, + 'The generics type $W does not conform to the type of ' + '${world?.runtimeType ?? 'World'}.', + ), + _world = world ?? World() as W, + _camera = camera ?? CameraComponent() { assert( Component.staticGameInstance == null, '$this instantiated, while another game ${Component.staticGameInstance} ' diff --git a/packages/flame/lib/src/game/game.dart b/packages/flame/lib/src/game/game.dart index d044c996a..ddc7e83f4 100644 --- a/packages/flame/lib/src/game/game.dart +++ b/packages/flame/lib/src/game/game.dart @@ -32,8 +32,9 @@ abstract mixin class Game { /// Used internally by various mixins that need to use gesture detection /// functionality in Flutter. - late final GestureDetectorBuilder gestureDetectors = - GestureDetectorBuilder(refreshWidget)..initializeGestures(this); + late final GestureDetectorBuilder gestureDetectors = GestureDetectorBuilder( + refreshWidget, + )..initializeGestures(this); /// Set by the PointerMoveDispatcher to receive mouse events from the /// game widget. diff --git a/packages/flame/lib/src/game/game_widget/game_widget.dart b/packages/flame/lib/src/game/game_widget/game_widget.dart index 0ed197f17..fe279deff 100644 --- a/packages/flame/lib/src/game/game_widget/game_widget.dart +++ b/packages/flame/lib/src/game/game_widget/game_widget.dart @@ -189,14 +189,14 @@ class GameWidgetState extends State> { late T currentGame; Future get loaderFuture => _loaderFuture ??= (() async { - final game = currentGame; - assert(game.hasLayout); - await game.load(); - game.mount(); - if (!game.paused) { - game.update(0); - } - })(); + final game = currentGame; + assert(game.hasLayout); + await game.load(); + game.mount(); + if (!game.paused) { + game.update(0); + } + })(); Future? _loaderFuture; @@ -342,8 +342,9 @@ class GameWidgetState extends State> { 'not receive events', ); - internalGameWidget = - currentGame.gestureDetectors.build(internalGameWidget); + internalGameWidget = currentGame.gestureDetectors.build( + internalGameWidget, + ); if (hasMouseDetectors(currentGame)) { internalGameWidget = applyMouseDetectors( @@ -442,9 +443,10 @@ typedef GameLoadingWidgetBuilder = Widget Function(BuildContext); typedef GameErrorWidgetBuilder = Widget Function(BuildContext, Object error); -typedef OverlayWidgetBuilder = Widget Function( - BuildContext context, - T game, -); +typedef OverlayWidgetBuilder = + Widget Function( + BuildContext context, + T game, + ); typedef GameFactory = T Function(); diff --git a/packages/flame/lib/src/game/game_widget/gesture_detector_builder.dart b/packages/flame/lib/src/game/game_widget/gesture_detector_builder.dart index 1689ef183..2dc66a08c 100644 --- a/packages/flame/lib/src/game/game_widget/gesture_detector_builder.dart +++ b/packages/flame/lib/src/game/game_widget/gesture_detector_builder.dart @@ -16,8 +16,10 @@ class GestureDetectorBuilder { ) { final count = _counters[T]; if (count == null) { - _gestures[T] = - GestureRecognizerFactoryWithHandlers(constructor, initializer); + _gestures[T] = GestureRecognizerFactoryWithHandlers( + constructor, + initializer, + ); _onChange?.call(); } _counters[T] = (count ?? 0) + 1; @@ -189,7 +191,7 @@ Widget applyMouseDetectors(Game game, Widget child) { ), onPointerSignal: (event) => game is ScrollDetector && event is PointerScrollEvent - ? game.onScroll(PointerScrollInfo.fromDetails(game, event)) - : null, + ? game.onScroll(PointerScrollInfo.fromDetails(game, event)) + : null, ); } diff --git a/packages/flame/lib/src/game/overlay_manager.dart b/packages/flame/lib/src/game/overlay_manager.dart index 2b68d4ae6..1204dcb1b 100644 --- a/packages/flame/lib/src/game/overlay_manager.dart +++ b/packages/flame/lib/src/game/overlay_manager.dart @@ -89,8 +89,9 @@ class OverlayManager { /// Hides multiple overlays specified in [overlayNames]. void removeAll(Iterable overlayNames) { final initialCount = _activeOverlays.length; - _activeOverlays - .removeWhere((overlay) => overlayNames.contains(overlay.name)); + _activeOverlays.removeWhere( + (overlay) => overlayNames.contains(overlay.name), + ); if (_activeOverlays.length != initialCount) { _game.refreshWidget(isInternalRefresh: false); } @@ -131,10 +132,11 @@ class OverlayManager { } } -typedef OverlayBuilderFunction = Widget Function( - BuildContext context, - Game game, -); +typedef OverlayBuilderFunction = + Widget Function( + BuildContext context, + Game game, + ); @immutable class _OverlayData { diff --git a/packages/flame/lib/src/game/transform2d.dart b/packages/flame/lib/src/game/transform2d.dart index ebce5418f..8d81ba4ec 100644 --- a/packages/flame/lib/src/game/transform2d.dart +++ b/packages/flame/lib/src/game/transform2d.dart @@ -37,12 +37,12 @@ class Transform2D extends ChangeNotifier { final NotifyingVector2 _offset; Transform2D() - : _transformMatrix = Matrix4.identity(), - _recalculate = true, - _angle = 0, - _position = NotifyingVector2.zero(), - _scale = NotifyingVector2.all(1), - _offset = NotifyingVector2.zero() { + : _transformMatrix = Matrix4.identity(), + _recalculate = true, + _angle = 0, + _position = NotifyingVector2.zero(), + _scale = NotifyingVector2.all(1), + _offset = NotifyingVector2.zero() { _position.addListener(_markAsModified); _scale.addListener(_markAsModified); _offset.addListener(_markAsModified); diff --git a/packages/flame/lib/src/geometry/line.dart b/packages/flame/lib/src/geometry/line.dart index bf48317d8..f5fbbc4dd 100644 --- a/packages/flame/lib/src/geometry/line.dart +++ b/packages/flame/lib/src/geometry/line.dart @@ -14,11 +14,11 @@ class Line { const Line(this.a, this.b, this.c); Line.fromPoints(Vector2 p1, Vector2 p2) - : this( - p2.y - p1.y, - p1.x - p2.x, - p2.y * p1.x - p1.y * p2.x, - ); + : this( + p2.y - p1.y, + p1.x - p2.x, + p2.y * p1.x - p1.y * p2.x, + ); /// Returns an empty list if there is no intersection /// If the lines are concurrent it returns one point in the list. diff --git a/packages/flame/lib/src/geometry/polygon_component.dart b/packages/flame/lib/src/geometry/polygon_component.dart index f59afb7bd..6302fa65d 100644 --- a/packages/flame/lib/src/geometry/polygon_component.dart +++ b/packages/flame/lib/src/geometry/polygon_component.dart @@ -38,12 +38,12 @@ class PolygonComponent extends ShapeComponent { super.paintLayers, super.key, bool? shrinkToBounds, - }) : assert( - _vertices.length > 2, - 'Number of vertices are too few to create a polygon', - ), - shrinkToBounds = shrinkToBounds ?? size == null, - manuallyPositioned = position != null { + }) : assert( + _vertices.length > 2, + 'Number of vertices are too few to create a polygon', + ), + shrinkToBounds = shrinkToBounds ?? size == null, + manuallyPositioned = position != null { refreshVertices(newVertices: _vertices); final verticesLength = _vertices.length; @@ -80,18 +80,18 @@ class PolygonComponent extends ShapeComponent { ComponentKey? key, List? children, }) : this( - normalsToVertices(relation, parentSize), - position: position, - angle: angle, - anchor: anchor, - scale: scale, - priority: priority, - paint: paint, - paintLayers: paintLayers, - shrinkToBounds: shrinkToBounds, - key: key, - children: children, - ); + normalsToVertices(relation, parentSize), + position: position, + angle: angle, + anchor: anchor, + scale: scale, + priority: priority, + paint: paint, + paintLayers: paintLayers, + shrinkToBounds: shrinkToBounds, + key: key, + children: children, + ); @internal static List normalsToVertices( diff --git a/packages/flame/lib/src/geometry/polygon_ray_intersection.dart b/packages/flame/lib/src/geometry/polygon_ray_intersection.dart index 9ae5255cf..b013c23ec 100644 --- a/packages/flame/lib/src/geometry/polygon_ray_intersection.dart +++ b/packages/flame/lib/src/geometry/polygon_ray_intersection.dart @@ -37,8 +37,10 @@ mixin PolygonRayIntersection on PolygonComponent { } } if (crossings > 0) { - final intersectionPoint = - ray.point(closestDistance, out: out?.intersectionPoint); + final intersectionPoint = ray.point( + closestDistance, + out: out?.intersectionPoint, + ); // This is "from" to "to" since it is defined ccw in the canvas // coordinate system _temporaryNormal @@ -57,20 +59,19 @@ mixin PolygonRayIntersection on PolygonComponent { ..setFrom(ray.direction) ..reflect(_temporaryNormal); - final reflectionRay = (out?.reflectionRay - ?..setWith( - origin: intersectionPoint, - direction: reflectionDirection, - )) ?? + final reflectionRay = + (out?.reflectionRay?..setWith( + origin: intersectionPoint, + direction: reflectionDirection, + )) ?? Ray2(origin: intersectionPoint, direction: reflectionDirection); - return (out ?? RaycastResult()) - ..setWith( - hitbox: this as T, - reflectionRay: reflectionRay, - normal: _temporaryNormal, - distance: closestDistance, - isInsideHitbox: isInsideHitbox, - ); + return (out ?? RaycastResult())..setWith( + hitbox: this as T, + reflectionRay: reflectionRay, + normal: _temporaryNormal, + distance: closestDistance, + isInsideHitbox: isInsideHitbox, + ); } out?.reset(); return null; diff --git a/packages/flame/lib/src/geometry/rectangle_component.dart b/packages/flame/lib/src/geometry/rectangle_component.dart index b1eec9264..03dc41414 100644 --- a/packages/flame/lib/src/geometry/rectangle_component.dart +++ b/packages/flame/lib/src/geometry/rectangle_component.dart @@ -38,11 +38,11 @@ class RectangleComponent extends PolygonComponent { super.key, }) : super(sizeToVertices(Vector2.all(size), anchor)) { this.size.addListener( - () => refreshVertices( - newVertices: sizeToVertices(this.size, anchor), - shrinkToBoundsOverride: false, - ), - ); + () => refreshVertices( + newVertices: sizeToVertices(this.size, anchor), + shrinkToBoundsOverride: false, + ), + ); } /// With this constructor you define the [RectangleComponent] in relation to @@ -63,11 +63,11 @@ class RectangleComponent extends PolygonComponent { super.key, super.children, }) : super.relative([ - relation.clone(), - Vector2(relation.x, -relation.y), - -relation, - Vector2(-relation.x, relation.y), - ]) { + relation.clone(), + Vector2(relation.x, -relation.y), + -relation, + Vector2(-relation.x, relation.y), + ]) { size.addListener( () => refreshVertices( newVertices: sizeToVertices(size, anchor), diff --git a/packages/flame/lib/src/geometry/shape_intersections.dart b/packages/flame/lib/src/geometry/shape_intersections.dart index 151650b00..282b20f09 100644 --- a/packages/flame/lib/src/geometry/shape_intersections.dart +++ b/packages/flame/lib/src/geometry/shape_intersections.dart @@ -3,8 +3,10 @@ import 'dart:math'; import 'package:flame/extensions.dart'; import 'package:flame/geometry.dart'; -abstract class Intersections { +abstract class Intersections< + T1 extends ShapeComponent, + T2 extends ShapeComponent +> { Set intersect(T1 shapeA, T2 shapeB); bool supportsShapes(ShapeComponent shapeA, ShapeComponent shapeB) { @@ -54,8 +56,8 @@ class PolygonPolygonIntersections final outerShape = polygonA.containsPoint(polygonB.globalVertices().first) ? polygonA : (polygonB.containsPoint(polygonA.globalVertices().first) - ? polygonB - : null); + ? polygonB + : null); if (outerShape != null && outerShape.isSolid) { final innerShape = outerShape == polygonA ? polygonB : polygonA; return {innerShape.absoluteCenter}; @@ -142,10 +144,12 @@ class CircleCircleIntersections // and we get those points by calculating the [delta] from the // [centerPoint] to the intersection points. // The result is then [centerPoint] +- [delta]. - final lengthA = (pow(radiusA, 2) - pow(radiusB, 2) + pow(distance, 2)) / + final lengthA = + (pow(radiusA, 2) - pow(radiusB, 2) + pow(distance, 2)) / (2 * distance); final lengthB = sqrt((pow(radiusA, 2) - pow(lengthA, 2)).abs()); - final centerPoint = shapeA.absoluteCenter + + final centerPoint = + shapeA.absoluteCenter + (shapeB.absoluteCenter - shapeA.absoluteCenter) * lengthA / distance; final delta = Vector2( lengthB * diff --git a/packages/flame/lib/src/layers/processors.dart b/packages/flame/lib/src/layers/processors.dart index c7fd34971..18b830c2c 100644 --- a/packages/flame/lib/src/layers/processors.dart +++ b/packages/flame/lib/src/layers/processors.dart @@ -14,10 +14,10 @@ class ShadowProcessor extends LayerProcessor { double opacity = 0.9, Color color = const Color(0xFF000000), }) : _shadowPaint = Paint() - ..colorFilter = ColorFilter.mode( - color.withValues(alpha: opacity), - BlendMode.srcATop, - ); + ..colorFilter = ColorFilter.mode( + color.withValues(alpha: opacity), + BlendMode.srcATop, + ); @override void process(Picture pic, Canvas canvas) { diff --git a/packages/flame/lib/src/nine_tile_box.dart b/packages/flame/lib/src/nine_tile_box.dart index 69c5ae365..77ab18626 100644 --- a/packages/flame/lib/src/nine_tile_box.dart +++ b/packages/flame/lib/src/nine_tile_box.dart @@ -41,7 +41,7 @@ class NineTileBox { /// If [destTileSize] is not provided, the evaluated [tileSize] is used /// instead (so no scaling happens). NineTileBox(this.sprite, {int? tileSize, int? destTileSize}) - : tileSize = tileSize ?? sprite.src.width ~/ 3 { + : tileSize = tileSize ?? sprite.src.width ~/ 3 { this.destTileSize = destTileSize ?? this.tileSize; final centerEdge = this.tileSize.toDouble(); center = Rect.fromLTWH(centerEdge, centerEdge, centerEdge, centerEdge); diff --git a/packages/flame/lib/src/parallax.dart b/packages/flame/lib/src/parallax.dart index 9d3234ddb..70293dfdf 100644 --- a/packages/flame/lib/src/parallax.dart +++ b/packages/flame/lib/src/parallax.dart @@ -107,10 +107,10 @@ abstract class ParallaxRenderer { Alignment? alignment, LayerFill? fill, FilterQuality? filterQuality, - }) : repeat = repeat ?? ImageRepeat.repeatX, - alignment = alignment ?? Alignment.bottomLeft, - fill = fill ?? LayerFill.height, - filterQuality = filterQuality ?? FilterQuality.low; + }) : repeat = repeat ?? ImageRepeat.repeatX, + alignment = alignment ?? Alignment.bottomLeft, + fill = fill ?? LayerFill.height, + filterQuality = filterQuality ?? FilterQuality.low; void update(double dt); @@ -203,10 +203,14 @@ class ParallaxAnimation extends ParallaxRenderer { }) async { images ??= Flame.images; - final animation = - await SpriteAnimation.load(path, animationData, images: images); - final prerenderedFrames = - animation.frames.map((frame) => frame.sprite.toImageSync()).toList(); + final animation = await SpriteAnimation.load( + path, + animationData, + images: images, + ); + final prerenderedFrames = animation.frames + .map((frame) => frame.sprite.toImageSync()) + .toList(); return ParallaxAnimation( animation, @@ -510,11 +514,11 @@ class Parallax { final velocityDelta = velocityMultiplierDelta ?? Vector2.all(1.0); final layers = await Future.wait( dataList.mapIndexed((depth, data) async { - final velocityMultiplier = - List.filled(depth, velocityDelta).fold( - velocityDelta, - (previousValue, delta) => previousValue.clone()..multiply(delta), - ); + final velocityMultiplier = List.filled(depth, velocityDelta) + .fold( + velocityDelta, + (previousValue, delta) => previousValue.clone()..multiply(delta), + ); final renderer = await data.load( repeat, alignment, diff --git a/packages/flame/lib/src/particles/accelerated_particle.dart b/packages/flame/lib/src/particles/accelerated_particle.dart index 7a6816800..58029e456 100644 --- a/packages/flame/lib/src/particles/accelerated_particle.dart +++ b/packages/flame/lib/src/particles/accelerated_particle.dart @@ -27,9 +27,9 @@ class AcceleratedParticle extends CurvedParticle with SingleChildParticle { Vector2? speed, Vector2? position, super.lifespan, - }) : acceleration = acceleration ?? Vector2.zero(), - position = position ?? Vector2.zero(), - speed = speed ?? Vector2.zero(); + }) : acceleration = acceleration ?? Vector2.zero(), + position = position ?? Vector2.zero(), + speed = speed ?? Vector2.zero(); @override void render(Canvas canvas) { diff --git a/packages/flame/lib/src/particles/image_particle.dart b/packages/flame/lib/src/particles/image_particle.dart index 7dcf80a53..422488f69 100644 --- a/packages/flame/lib/src/particles/image_particle.dart +++ b/packages/flame/lib/src/particles/image_particle.dart @@ -25,8 +25,12 @@ class ImageParticle extends Particle { final destHeight = size?.y ?? srcHeight; src = Rect.fromLTWH(0, 0, srcWidth, srcHeight); - dest = - Rect.fromLTWH(-destWidth / 2, -destHeight / 2, destWidth, destHeight); + dest = Rect.fromLTWH( + -destWidth / 2, + -destHeight / 2, + destWidth, + destHeight, + ); } @override diff --git a/packages/flame/lib/src/particles/sprite_animation_particle.dart b/packages/flame/lib/src/particles/sprite_animation_particle.dart index 98826d2e3..9afbdaa9f 100644 --- a/packages/flame/lib/src/particles/sprite_animation_particle.dart +++ b/packages/flame/lib/src/particles/sprite_animation_particle.dart @@ -41,12 +41,12 @@ class SpriteAnimationParticle extends Particle { @override void render(Canvas canvas) { animationTicker.getSprite().render( - canvas, - position: position, - size: size, - anchor: anchor, - overridePaint: overridePaint, - ); + canvas, + position: position, + size: size, + anchor: anchor, + overridePaint: overridePaint, + ); } @override diff --git a/packages/flame/lib/src/post_process/post_process.dart b/packages/flame/lib/src/post_process/post_process.dart index 281524a7e..f50871d1f 100644 --- a/packages/flame/lib/src/post_process/post_process.dart +++ b/packages/flame/lib/src/post_process/post_process.dart @@ -54,8 +54,9 @@ import 'package:meta/meta.dart'; /// context from within a component during rendering abstract class PostProcess { PostProcess({double? pixelRatio}) - : pixelRatio = pixelRatio ?? - PlatformDispatcher.instance.views.first.devicePixelRatio; + : pixelRatio = + pixelRatio ?? + PlatformDispatcher.instance.views.first.devicePixelRatio; /// The pixel ratio of the screen. This is used to scale the image generated /// by [rasterizeSubtree] to the correct size. diff --git a/packages/flame/lib/src/post_process/post_process_component.dart b/packages/flame/lib/src/post_process/post_process_component.dart index 2987a3eaf..cfa597b26 100644 --- a/packages/flame/lib/src/post_process/post_process_component.dart +++ b/packages/flame/lib/src/post_process/post_process_component.dart @@ -46,8 +46,9 @@ class PostProcessComponent extends PositionComponent { @override PostProcessComponentRenderContext get renderContext => _renderContext; - final _renderContext = - PostProcessComponentRenderContext(postProcess: null); + final _renderContext = PostProcessComponentRenderContext( + postProcess: null, + ); final T postProcess; @@ -89,8 +90,10 @@ class PostProcessComponent extends PositionComponent { final boundingBox = rectChildren .map((child) => child.toRect()) .reduce((a, b) => a.expandToInclude(b)); - (_maybeBoundingSize ??= NotifyingVector2.zero()) - .setValues(boundingBox.width, boundingBox.height); + (_maybeBoundingSize ??= NotifyingVector2.zero()).setValues( + boundingBox.width, + boundingBox.height, + ); } @override diff --git a/packages/flame/lib/src/rendering/paint_decorator.dart b/packages/flame/lib/src/rendering/paint_decorator.dart index 99535ea00..c808bc0e3 100644 --- a/packages/flame/lib/src/rendering/paint_decorator.dart +++ b/packages/flame/lib/src/rendering/paint_decorator.dart @@ -28,8 +28,10 @@ class PaintDecorator extends Decorator { final _paint = Paint(); void addBlur(double amount, [double? amountY]) { - _paint.imageFilter = - ImageFilter.blur(sigmaX: amount, sigmaY: amountY ?? amount); + _paint.imageFilter = ImageFilter.blur( + sigmaX: amount, + sigmaY: amountY ?? amount, + ); } @override diff --git a/packages/flame/lib/src/rendering/shadow3d_decorator.dart b/packages/flame/lib/src/rendering/shadow3d_decorator.dart index 522062289..aa3a8fc15 100644 --- a/packages/flame/lib/src/rendering/shadow3d_decorator.dart +++ b/packages/flame/lib/src/rendering/shadow3d_decorator.dart @@ -27,14 +27,14 @@ class Shadow3DDecorator extends Decorator { double? blur, double? opacity, Color? baseColor, - }) : _base = base?.clone() ?? Vector2.zero(), - _ascent = ascent ?? 0, - _angle = angle ?? -1.4, - _shift = xShift ?? 100.0, - _scale = yScale ?? 1.0, - _blur = blur ?? 0, - _opacity = opacity ?? 0.6, - _baseColor = baseColor ?? BasicPalette.black.color; + }) : _base = base?.clone() ?? Vector2.zero(), + _ascent = ascent ?? 0, + _angle = angle ?? -1.4, + _shift = xShift ?? 100.0, + _scale = yScale ?? 1.0, + _blur = blur ?? 0, + _opacity = opacity ?? 0.6, + _baseColor = baseColor ?? BasicPalette.black.color; /// Coordinates of the point where the component "touches the ground". If the /// component is airborne (i.e. [ascent] is non-zero), then this should be the diff --git a/packages/flame/lib/src/rendering/transform2d_decorator.dart b/packages/flame/lib/src/rendering/transform2d_decorator.dart index eda1bef73..b73188f04 100644 --- a/packages/flame/lib/src/rendering/transform2d_decorator.dart +++ b/packages/flame/lib/src/rendering/transform2d_decorator.dart @@ -9,7 +9,7 @@ import 'package:flame/src/rendering/decorator.dart'; /// This decorator is used internally by the [PositionComponent]. class Transform2DDecorator extends Decorator { Transform2DDecorator([Transform2D? transform]) - : transform2d = transform ?? Transform2D(); + : transform2d = transform ?? Transform2D(); final Transform2D transform2d; diff --git a/packages/flame/lib/src/sprite_animation.dart b/packages/flame/lib/src/sprite_animation.dart index 29ac117d1..332586db2 100644 --- a/packages/flame/lib/src/sprite_animation.dart +++ b/packages/flame/lib/src/sprite_animation.dart @@ -86,9 +86,9 @@ class SpriteAnimationData { int? amountPerRow, Vector2? texturePosition, this.loop = true, - }) : assert(amountPerRow == null || amount >= amountPerRow), - assert(start <= end && start >= 0 && end <= amount), - assert(stepTimes.length >= end - start + 1) { + }) : assert(amountPerRow == null || amount >= amountPerRow), + assert(start <= end && start >= 0 && end <= amount), + assert(stepTimes.length >= end - start + 1) { amountPerRow ??= amount; texturePosition ??= Vector2.zero(); frames = List.generate(end - start + 1, (index) { @@ -142,11 +142,11 @@ class SpriteAnimationFrame { /// time. class SpriteAnimation { SpriteAnimation(this.frames, {this.loop = true}) - : assert(frames.isNotEmpty, 'There must be at least one animation frame'), - assert( - frames.every((frame) => frame.stepTime > 0), - 'All frames must have positive durations', - ); + : assert(frames.isNotEmpty, 'There must be at least one animation frame'), + assert( + frames.every((frame) => frame.stepTime > 0), + 'All frames must have positive durations', + ); /// Create animation from a list of [sprites] all having the same transition /// time [stepTime]. diff --git a/packages/flame/lib/src/sprite_batch.dart b/packages/flame/lib/src/sprite_batch.dart index 5d8392738..05688db89 100644 --- a/packages/flame/lib/src/sprite_batch.dart +++ b/packages/flame/lib/src/sprite_batch.dart @@ -39,8 +39,8 @@ class BatchItem { required this.transform, Color? color, this.flip = false, - }) : paint = Paint()..color = color ?? const Color(0x00000000), - destination = Offset.zero & source.size; + }) : paint = Paint()..color = color ?? const Color(0x00000000), + destination = Offset.zero & source.size; /// The source rectangle on the [SpriteBatch.atlas]. final Rect source; @@ -60,15 +60,28 @@ class BatchItem { /// /// Since [Canvas.drawAtlas] is not supported on the web we also /// build a `Matrix4` based on the [transform] and [flip] values. - late final Matrix4 matrix = Matrix4( - transform.scos, transform.ssin, 0, 0, // - -transform.ssin, transform.scos, 0, 0, // - 0, 0, 0, 0, // - transform.tx, transform.ty, 0, 1, // - ) - ..translate(source.width / 2, source.height / 2) - ..rotateY(flip ? pi : 0) - ..translate(-source.width / 2, -source.height / 2); + late final Matrix4 matrix = + Matrix4( + transform.scos, + transform.ssin, + 0, + 0, // + -transform.ssin, + transform.scos, + 0, + 0, // + 0, + 0, + 0, + 0, // + transform.tx, + transform.ty, + 0, + 1, // + ) + ..translate(source.width / 2, source.height / 2) + ..rotateY(flip ? pi : 0) + ..translate(-source.width / 2, -source.height / 2); /// Paint object used for the web. final Paint paint; @@ -115,8 +128,8 @@ class SpriteBatch { this.defaultBlendMode, Images? imageCache, String? imageKey, - }) : _imageCache = imageCache, - _imageKey = imageKey; + }) : _imageCache = imageCache, + _imageKey = imageKey; /// Takes a path of an image, and optional arguments for the SpriteBatch. /// diff --git a/packages/flame/lib/src/sprite_sheet.dart b/packages/flame/lib/src/sprite_sheet.dart index 67dd00c93..5ae3748cc 100644 --- a/packages/flame/lib/src/sprite_sheet.dart +++ b/packages/flame/lib/src/sprite_sheet.dart @@ -49,8 +49,8 @@ class SpriteSheet { required this.srcSize, this.margin = 0, this.spacing = 0, - }) : columns = (image.width - 2 * margin + spacing) ~/ (srcSize.x + spacing), - rows = (image.height - 2 * margin + spacing) ~/ (srcSize.y + spacing); + }) : columns = (image.width - 2 * margin + spacing) ~/ (srcSize.x + spacing), + rows = (image.height - 2 * margin + spacing) ~/ (srcSize.y + spacing); SpriteSheet.fromColumnsAndRows({ required this.image, @@ -59,9 +59,9 @@ class SpriteSheet { this.spacing = 0, this.margin = 0, }) : srcSize = Vector2( - (image.width - 2 * margin - (columns - 1) * spacing) / columns, - (image.height - 2 * margin - (rows - 1) * spacing) / rows, - ); + (image.width - 2 * margin - (columns - 1) * spacing) / columns, + (image.height - 2 * margin - (rows - 1) * spacing) / rows, + ); /// Gets the sprite in the position (row, column) on the sprite sheet grid. /// @@ -126,9 +126,10 @@ class SpriteSheet { }) { to ??= columns; - return List.generate(to - from, (i) => from + i) - .map((e) => getSprite(row, e)) - .toList(); + return List.generate( + to - from, + (i) => from + i, + ).map((e) => getSprite(row, e)).toList(); } /// Creates a [SpriteAnimation] from this SpriteSheet, using the sequence diff --git a/packages/flame/lib/src/text/common/glyph.dart b/packages/flame/lib/src/text/common/glyph.dart index 93f5fd899..87098ceae 100644 --- a/packages/flame/lib/src/text/common/glyph.dart +++ b/packages/flame/lib/src/text/common/glyph.dart @@ -31,26 +31,26 @@ class Glyph { double? srcTop, double? srcRight, double? srcBottom, - }) : assert((width ?? 0) >= 0, 'The `width` parameter cannot be negative'), - assert((height ?? 0) >= 0, 'The `height` parameter cannot be negative'), - assert( - (srcLeft == null && - srcTop == null && - srcRight == null && - srcBottom == null) || - (srcLeft != null && - srcTop != null && - srcRight != null && - srcBottom != null), - 'Either all or none of parameters `srcLeft`, `srcTop`, `srcRight` ' - 'and `srcBottom` must be specified', - ), - width = width ?? -1, - height = height ?? -1, - srcLeft = srcLeft ?? -1, - srcTop = srcTop ?? -1, - srcRight = srcRight ?? -1, - srcBottom = srcBottom ?? -1; + }) : assert((width ?? 0) >= 0, 'The `width` parameter cannot be negative'), + assert((height ?? 0) >= 0, 'The `height` parameter cannot be negative'), + assert( + (srcLeft == null && + srcTop == null && + srcRight == null && + srcBottom == null) || + (srcLeft != null && + srcTop != null && + srcRight != null && + srcBottom != null), + 'Either all or none of parameters `srcLeft`, `srcTop`, `srcRight` ' + 'and `srcBottom` must be specified', + ), + width = width ?? -1, + height = height ?? -1, + srcLeft = srcLeft ?? -1, + srcTop = srcTop ?? -1, + srcRight = srcRight ?? -1, + srcBottom = srcBottom ?? -1; final String char; final double left; diff --git a/packages/flame/lib/src/text/common/line_metrics.dart b/packages/flame/lib/src/text/common/line_metrics.dart index 948f514d2..620b7c0fb 100644 --- a/packages/flame/lib/src/text/common/line_metrics.dart +++ b/packages/flame/lib/src/text/common/line_metrics.dart @@ -17,12 +17,12 @@ class LineMetrics { double? ascent, double? descent, double? height, - }) : _left = left, - _baseline = baseline, - _width = width, - _ascent = ascent ?? (height == null ? 0 : height - (descent ?? 0)), - _descent = - descent ?? (height == null ? 0 : height - (ascent ?? height)) { + }) : _left = left, + _baseline = baseline, + _width = width, + _ascent = ascent ?? (height == null ? 0 : height - (descent ?? 0)), + _descent = + descent ?? (height == null ? 0 : height - (ascent ?? height)) { _updateSize(); } @@ -102,6 +102,7 @@ class LineMetrics { Rect toRect() => Rect.fromLTWH(left, top, width, height); @override - String toString() => 'LineMetrics(left: $left, baseline: $baseline, ' + String toString() => + 'LineMetrics(left: $left, baseline: $baseline, ' 'width: $width, ascent: $ascent, descent: $descent)'; } diff --git a/packages/flame/lib/src/text/elements/group_text_element.dart b/packages/flame/lib/src/text/elements/group_text_element.dart index 838b8fa3f..71f2eaab0 100644 --- a/packages/flame/lib/src/text/elements/group_text_element.dart +++ b/packages/flame/lib/src/text/elements/group_text_element.dart @@ -6,9 +6,9 @@ import 'package:meta/meta.dart'; class GroupTextElement extends InlineTextElement { GroupTextElement(List children) - : assert(children.isNotEmpty, 'The children list cannot be empty'), - _children = children, - _metrics = _computeMetrics(children); + : assert(children.isNotEmpty, 'The children list cannot be empty'), + _children = children, + _metrics = _computeMetrics(children); final List _children; final LineMetrics _metrics; diff --git a/packages/flame/lib/src/text/elements/rect_element.dart b/packages/flame/lib/src/text/elements/rect_element.dart index a120971be..c13949047 100644 --- a/packages/flame/lib/src/text/elements/rect_element.dart +++ b/packages/flame/lib/src/text/elements/rect_element.dart @@ -4,7 +4,7 @@ import 'package:flame/text.dart'; class RectElement extends TextElement { RectElement(double width, double height, this._paint) - : _rect = Rect.fromLTWH(0, 0, width, height); + : _rect = Rect.fromLTWH(0, 0, width, height); Rect _rect; final Paint _paint; diff --git a/packages/flame/lib/src/text/elements/text_painter_text_element.dart b/packages/flame/lib/src/text/elements/text_painter_text_element.dart index ea1359ab5..a846b902f 100644 --- a/packages/flame/lib/src/text/elements/text_painter_text_element.dart +++ b/packages/flame/lib/src/text/elements/text_painter_text_element.dart @@ -6,13 +6,13 @@ import 'package:meta/meta.dart'; class TextPainterTextElement extends InlineTextElement { TextPainterTextElement(this._textPainter) - : _box = LineMetrics( - ascent: _textPainter.computeDistanceToActualBaseline( - flutter.TextBaseline.alphabetic, - ), - width: _textPainter.width, - height: _textPainter.height, - ); + : _box = LineMetrics( + ascent: _textPainter.computeDistanceToActualBaseline( + flutter.TextBaseline.alphabetic, + ), + width: _textPainter.width, + height: _textPainter.height, + ); final flutter.TextPainter _textPainter; final LineMetrics _box; diff --git a/packages/flame/lib/src/text/nodes/bold_text_node.dart b/packages/flame/lib/src/text/nodes/bold_text_node.dart index f452dfd0c..084c0bac1 100644 --- a/packages/flame/lib/src/text/nodes/bold_text_node.dart +++ b/packages/flame/lib/src/text/nodes/bold_text_node.dart @@ -10,7 +10,7 @@ class BoldTextNode extends InlineTextNode { BoldTextNode.simple(String text) : child = PlainTextNode(text); BoldTextNode.group(List children) - : child = GroupTextNode(children); + : child = GroupTextNode(children); final InlineTextNode child; diff --git a/packages/flame/lib/src/text/nodes/code_text_node.dart b/packages/flame/lib/src/text/nodes/code_text_node.dart index 43ca1c75e..be2fbeaee 100644 --- a/packages/flame/lib/src/text/nodes/code_text_node.dart +++ b/packages/flame/lib/src/text/nodes/code_text_node.dart @@ -8,7 +8,7 @@ class CodeTextNode extends InlineTextNode { CodeTextNode.simple(String text) : child = PlainTextNode(text); CodeTextNode.group(List children) - : child = GroupTextNode(children); + : child = GroupTextNode(children); final InlineTextNode child; diff --git a/packages/flame/lib/src/text/nodes/column_node.dart b/packages/flame/lib/src/text/nodes/column_node.dart index 2185fb77a..dec83329f 100644 --- a/packages/flame/lib/src/text/nodes/column_node.dart +++ b/packages/flame/lib/src/text/nodes/column_node.dart @@ -37,8 +37,11 @@ abstract class ColumnNode extends BlockNode { final blockHeight = children.isEmpty ? padding.vertical : verticalOffset + collapseMargin(currentMargin, padding.bottom); - final background = - makeBackground(style.background, blockWidth, blockHeight); + final background = makeBackground( + style.background, + blockWidth, + blockHeight, + ); if (background != null) { out.insert(0, background); } diff --git a/packages/flame/lib/src/text/nodes/custom_text_node.dart b/packages/flame/lib/src/text/nodes/custom_text_node.dart index 9898b7458..11c359cc1 100644 --- a/packages/flame/lib/src/text/nodes/custom_text_node.dart +++ b/packages/flame/lib/src/text/nodes/custom_text_node.dart @@ -8,13 +8,14 @@ class CustomInlineTextNode extends InlineTextNode { CustomInlineTextNode(this.child, {required this.styleName}); CustomInlineTextNode.simple(String text, {required this.styleName}) - : child = PlainTextNode(text); + : child = PlainTextNode(text); final InlineTextNode child; @override void fillStyles(DocumentStyle stylesheet, InlineTextStyle parentTextStyle) { - style = FlameTextStyle.merge( + style = + FlameTextStyle.merge( parentTextStyle, stylesheet.getCustomStyle(styleName), ) ?? diff --git a/packages/flame/lib/src/text/nodes/header_node.dart b/packages/flame/lib/src/text/nodes/header_node.dart index 57f318851..dce39dda9 100644 --- a/packages/flame/lib/src/text/nodes/header_node.dart +++ b/packages/flame/lib/src/text/nodes/header_node.dart @@ -7,7 +7,7 @@ class HeaderNode extends TextBlockNode { HeaderNode(super.child, {required this.level}); HeaderNode.simple(String text, {required this.level}) - : super(PlainTextNode(text)); + : super(PlainTextNode(text)); final int level; diff --git a/packages/flame/lib/src/text/nodes/italic_text_node.dart b/packages/flame/lib/src/text/nodes/italic_text_node.dart index 4837b7023..7312d1a24 100644 --- a/packages/flame/lib/src/text/nodes/italic_text_node.dart +++ b/packages/flame/lib/src/text/nodes/italic_text_node.dart @@ -10,7 +10,7 @@ class ItalicTextNode extends InlineTextNode { ItalicTextNode.simple(String text) : child = PlainTextNode(text); ItalicTextNode.group(List children) - : child = GroupTextNode(children); + : child = GroupTextNode(children); final InlineTextNode child; diff --git a/packages/flame/lib/src/text/nodes/paragraph_node.dart b/packages/flame/lib/src/text/nodes/paragraph_node.dart index 2db95ee94..361af8799 100644 --- a/packages/flame/lib/src/text/nodes/paragraph_node.dart +++ b/packages/flame/lib/src/text/nodes/paragraph_node.dart @@ -7,7 +7,7 @@ class ParagraphNode extends TextBlockNode { ParagraphNode.simple(String text) : super(PlainTextNode(text)); ParagraphNode.group(List fragments) - : super(GroupTextNode(fragments)); + : super(GroupTextNode(fragments)); static const defaultStyle = BlockStyle( margin: EdgeInsets.all(6), diff --git a/packages/flame/lib/src/text/nodes/plain_text_node.dart b/packages/flame/lib/src/text/nodes/plain_text_node.dart index bf3198290..93f59cc6e 100644 --- a/packages/flame/lib/src/text/nodes/plain_text_node.dart +++ b/packages/flame/lib/src/text/nodes/plain_text_node.dart @@ -18,8 +18,8 @@ class PlainTextNode extends InlineTextNode { class _PlainTextLayoutBuilder extends TextNodeLayoutBuilder { _PlainTextLayoutBuilder(this.node) - : renderer = node.style.asTextRenderer(), - words = node.text.split(' '); + : renderer = node.style.asTextRenderer(), + words = node.text.split(' '); final PlainTextNode node; final TextRenderer renderer; diff --git a/packages/flame/lib/src/text/nodes/strikethrough_text_node.dart b/packages/flame/lib/src/text/nodes/strikethrough_text_node.dart index 5929a6b50..bb4e2bf83 100644 --- a/packages/flame/lib/src/text/nodes/strikethrough_text_node.dart +++ b/packages/flame/lib/src/text/nodes/strikethrough_text_node.dart @@ -13,7 +13,7 @@ class StrikethroughTextNode extends InlineTextNode { StrikethroughTextNode.simple(String text) : child = PlainTextNode(text); StrikethroughTextNode.group(List children) - : child = GroupTextNode(children); + : child = GroupTextNode(children); final InlineTextNode child; diff --git a/packages/flame/lib/src/text/nodes/text_block_node.dart b/packages/flame/lib/src/text/nodes/text_block_node.dart index 967a1369c..720a73834 100644 --- a/packages/flame/lib/src/text/nodes/text_block_node.dart +++ b/packages/flame/lib/src/text/nodes/text_block_node.dart @@ -42,7 +42,8 @@ abstract class TextBlockNode extends BlockNode { final metrics = element.metrics; assert(metrics.left == 0 && metrics.baseline == 0); - final dx = horizontalOffset + + final dx = + horizontalOffset + (contentWidth - metrics.width) * _relativeOffset(textAlign); final dy = verticalOffset + metrics.ascent; element.translate(dx, dy); @@ -71,8 +72,8 @@ abstract class TextBlockNode extends BlockNode { TextAlign.end => 1, // Not supported by Flame TextAlign.justify => throw UnimplementedError( - 'The text rendering pipeline cannot justify text.', - ), + 'The text rendering pipeline cannot justify text.', + ), }; } } diff --git a/packages/flame/lib/src/text/styles/background_style.dart b/packages/flame/lib/src/text/styles/background_style.dart index fe123b694..5dd7fe445 100644 --- a/packages/flame/lib/src/text/styles/background_style.dart +++ b/packages/flame/lib/src/text/styles/background_style.dart @@ -10,20 +10,20 @@ class BackgroundStyle extends FlameTextStyle { Color? borderColor, double? borderRadius, double? borderWidth, - }) : assert( - paint == null || color == null, - 'Parameters `paint` and `color` are exclusive', - ), - borderWidths = EdgeInsets.all(borderWidth ?? 0), - borderRadius = borderRadius ?? 0, - backgroundPaint = - paint ?? (color != null ? (Paint()..color = color) : null), - borderPaint = borderColor != null - ? (Paint() - ..color = borderColor - ..style = PaintingStyle.stroke - ..strokeWidth = borderWidth ?? 0) - : null; + }) : assert( + paint == null || color == null, + 'Parameters `paint` and `color` are exclusive', + ), + borderWidths = EdgeInsets.all(borderWidth ?? 0), + borderRadius = borderRadius ?? 0, + backgroundPaint = + paint ?? (color != null ? (Paint()..color = color) : null), + borderPaint = borderColor != null + ? (Paint() + ..color = borderColor + ..style = PaintingStyle.stroke + ..strokeWidth = borderWidth ?? 0) + : null; final Paint? backgroundPaint; final Paint? borderPaint; diff --git a/packages/flame/lib/src/text/styles/block_style.dart b/packages/flame/lib/src/text/styles/block_style.dart index abc1e4d3e..1d550f9f2 100644 --- a/packages/flame/lib/src/text/styles/block_style.dart +++ b/packages/flame/lib/src/text/styles/block_style.dart @@ -12,8 +12,8 @@ class BlockStyle extends FlameTextStyle { this.background, this.text, this.textAlign, - }) : _margin = margin, - _padding = padding; + }) : _margin = margin, + _padding = padding; final EdgeInsets? _margin; final EdgeInsets? _padding; diff --git a/packages/flame/lib/src/text/styles/document_style.dart b/packages/flame/lib/src/text/styles/document_style.dart index 1fec50c90..df4254dd3 100644 --- a/packages/flame/lib/src/text/styles/document_style.dart +++ b/packages/flame/lib/src/text/styles/document_style.dart @@ -30,24 +30,25 @@ class DocumentStyle extends FlameTextStyle { BlockStyle? header4, BlockStyle? header5, BlockStyle? header6, - }) : _text = FlameTextStyle.merge(DocumentStyle.defaultTextStyle, text), - _boldText = FlameTextStyle.merge(BoldTextNode.defaultStyle, boldText), - _italicText = - FlameTextStyle.merge(ItalicTextNode.defaultStyle, italicText), - _codeText = FlameTextStyle.merge(CodeTextNode.defaultStyle, codeText), - _strikethroughText = FlameTextStyle.merge( - StrikethroughTextNode.defaultStyle, - strikethroughText, - ), - _customStyles = customStyles, - _paragraph = - FlameTextStyle.merge(ParagraphNode.defaultStyle, paragraph), - _header1 = FlameTextStyle.merge(HeaderNode.defaultStyleH1, header1), - _header2 = FlameTextStyle.merge(HeaderNode.defaultStyleH2, header2), - _header3 = FlameTextStyle.merge(HeaderNode.defaultStyleH3, header3), - _header4 = FlameTextStyle.merge(HeaderNode.defaultStyleH4, header4), - _header5 = FlameTextStyle.merge(HeaderNode.defaultStyleH5, header5), - _header6 = FlameTextStyle.merge(HeaderNode.defaultStyleH6, header6); + }) : _text = FlameTextStyle.merge(DocumentStyle.defaultTextStyle, text), + _boldText = FlameTextStyle.merge(BoldTextNode.defaultStyle, boldText), + _italicText = FlameTextStyle.merge( + ItalicTextNode.defaultStyle, + italicText, + ), + _codeText = FlameTextStyle.merge(CodeTextNode.defaultStyle, codeText), + _strikethroughText = FlameTextStyle.merge( + StrikethroughTextNode.defaultStyle, + strikethroughText, + ), + _customStyles = customStyles, + _paragraph = FlameTextStyle.merge(ParagraphNode.defaultStyle, paragraph), + _header1 = FlameTextStyle.merge(HeaderNode.defaultStyleH1, header1), + _header2 = FlameTextStyle.merge(HeaderNode.defaultStyleH2, header2), + _header3 = FlameTextStyle.merge(HeaderNode.defaultStyleH3, header3), + _header4 = FlameTextStyle.merge(HeaderNode.defaultStyleH4, header4), + _header5 = FlameTextStyle.merge(HeaderNode.defaultStyleH5, header5), + _header6 = FlameTextStyle.merge(HeaderNode.defaultStyleH6, header6); final InlineTextStyle? _text; final InlineTextStyle? _boldText; @@ -152,7 +153,7 @@ class DocumentStyle extends FlameTextStyle { } final Map> - _mergedStylesCache = {}; + _mergedStylesCache = {}; /// Merges two [FlameTextStyle]s together, preferring the properties of /// [style2] if present, falling back to the properties of [style1]. @@ -162,8 +163,9 @@ class DocumentStyle extends FlameTextStyle { } else if (style2 == null) { return style1; } else { - return (_mergedStylesCache[style1] ??= {})[style2] ??= - style1.copyWith(style2); + return (_mergedStylesCache[style1] ??= {})[style2] ??= style1.copyWith( + style2, + ); } } } diff --git a/packages/flame/lib/src/timer.dart b/packages/flame/lib/src/timer.dart index a69fb8178..65a48eccd 100644 --- a/packages/flame/lib/src/timer.dart +++ b/packages/flame/lib/src/timer.dart @@ -24,11 +24,11 @@ class Timer { this.repeat = false, bool autoStart = true, this.tickCount, - }) : assert( - tickCount == null || tickCount > 0, - 'tickCount must be null or bigger than 0', - ), - _running = autoStart; + }) : assert( + tickCount == null || tickCount > 0, + 'tickCount must be null or bigger than 0', + ), + _running = autoStart; /// The current amount of seconds that has passed on this iteration double get current => _current; diff --git a/packages/flame/lib/src/widgets/animation_widget.dart b/packages/flame/lib/src/widgets/animation_widget.dart index 309fc12a5..d236c83df 100644 --- a/packages/flame/lib/src/widgets/animation_widget.dart +++ b/packages/flame/lib/src/widgets/animation_widget.dart @@ -44,8 +44,8 @@ class SpriteAnimationWidget extends StatefulWidget { this.onComplete, this.paint, super.key, - }) : _animationFuture = animation, - _animationTicker = animationTicker; + }) : _animationFuture = animation, + _animationTicker = animationTicker; /// Loads image from the asset [path] and renders it as a widget. /// @@ -64,8 +64,8 @@ class SpriteAnimationWidget extends StatefulWidget { this.onComplete, this.paint, super.key, - }) : _animationFuture = SpriteAnimation.load(path, data, images: images), - _animationTicker = null; + }) : _animationFuture = SpriteAnimation.load(path, data, images: images), + _animationTicker = null; @override State createState() => _SpriteAnimationWidgetState(); @@ -96,7 +96,8 @@ class _SpriteAnimationWidgetState extends State { final oldValue = await oldFutureValue; final newValue = await newFutureValue; - final areFramesDifferent = oldValue != newValue || + final areFramesDifferent = + oldValue != newValue || oldValue.frames.length != newValue.frames.length || oldValue.frames.fold( true, diff --git a/packages/flame/lib/src/widgets/nine_tile_box.dart b/packages/flame/lib/src/widgets/nine_tile_box.dart index c4af2bfa9..66a00d98a 100644 --- a/packages/flame/lib/src/widgets/nine_tile_box.dart +++ b/packages/flame/lib/src/widgets/nine_tile_box.dart @@ -22,10 +22,10 @@ class _Painter extends CustomPainter { required this.tileSize, required this.destTileSize, }) : _nineTileBox = non_widget.NineTileBox( - Sprite(image), - tileSize: tileSize.toInt(), - destTileSize: destTileSize.toInt(), - ); + Sprite(image), + tileSize: tileSize.toInt(), + destTileSize: destTileSize.toInt(), + ); @override void paint(Canvas canvas, Size size) { @@ -67,9 +67,9 @@ class NineTileBoxWidget extends StatefulWidget { this.child, this.padding, super.key, - }) : _imageFuture = image, - errorBuilder = null, - loadingBuilder = null; + }) : _imageFuture = image, + errorBuilder = null, + loadingBuilder = null; /// Loads image from the asset [path] and renders it as a widget. /// diff --git a/packages/flame/lib/src/widgets/sprite_button.dart b/packages/flame/lib/src/widgets/sprite_button.dart index ae1ac8843..c5919a3ba 100644 --- a/packages/flame/lib/src/widgets/sprite_button.dart +++ b/packages/flame/lib/src/widgets/sprite_button.dart @@ -74,10 +74,10 @@ class SpriteButton extends StatelessWidget { this.loadingBuilder, super.key, }) : _buttonsFuture = [ - sprite, - pressedSprite, - if (disabledSprite != null) disabledSprite, - ]; + sprite, + pressedSprite, + if (disabledSprite != null) disabledSprite, + ]; SpriteButton.future({ required Future sprite, @@ -98,10 +98,10 @@ class SpriteButton extends StatelessWidget { this.loadingBuilder, super.key, }) : _buttonsFuture = Future.wait([ - sprite, - pressedSprite, - if (disabledSprite != null) disabledSprite, - ]); + sprite, + pressedSprite, + if (disabledSprite != null) disabledSprite, + ]); /// Loads the images from the asset [path] and [pressedPath] and renders /// it as a widget. @@ -129,49 +129,50 @@ class SpriteButton extends StatelessWidget { this.errorBuilder, this.loadingBuilder, super.key, - }) : _buttonsFuture = (images ?? Flame.images).containsKey(path) && - (images ?? Flame.images).containsKey(pressedPath) && - (disabledPath == null || - (images ?? Flame.images).containsKey(disabledPath)) - ? [ - Sprite( - (images ?? Flame.images).fromCache(path), - srcPosition: srcPosition, - srcSize: srcSize, - ), - Sprite( - (images ?? Flame.images).fromCache(pressedPath), - srcPosition: pressedSrcPosition, - srcSize: pressedSrcSize, - ), - if (disabledPath != null) - Sprite( - (images ?? Flame.images).fromCache(disabledPath), - srcPosition: disabledSrcPosition, - srcSize: disabledSrcSize, - ), - ] - : Future.wait([ - Sprite.load( - path, - srcPosition: srcPosition, - srcSize: srcSize, - images: images, - ), - Sprite.load( - pressedPath, - srcPosition: pressedSrcPosition, - srcSize: pressedSrcSize, - images: images, - ), - if (disabledPath != null) - Sprite.load( - disabledPath, - srcPosition: disabledSrcPosition, - srcSize: disabledSrcSize, - images: images, - ), - ]); + }) : _buttonsFuture = + (images ?? Flame.images).containsKey(path) && + (images ?? Flame.images).containsKey(pressedPath) && + (disabledPath == null || + (images ?? Flame.images).containsKey(disabledPath)) + ? [ + Sprite( + (images ?? Flame.images).fromCache(path), + srcPosition: srcPosition, + srcSize: srcSize, + ), + Sprite( + (images ?? Flame.images).fromCache(pressedPath), + srcPosition: pressedSrcPosition, + srcSize: pressedSrcSize, + ), + if (disabledPath != null) + Sprite( + (images ?? Flame.images).fromCache(disabledPath), + srcPosition: disabledSrcPosition, + srcSize: disabledSrcSize, + ), + ] + : Future.wait([ + Sprite.load( + path, + srcPosition: srcPosition, + srcSize: srcSize, + images: images, + ), + Sprite.load( + pressedPath, + srcPosition: pressedSrcPosition, + srcSize: pressedSrcSize, + images: images, + ), + if (disabledPath != null) + Sprite.load( + disabledPath, + srcPosition: disabledSrcPosition, + srcSize: disabledSrcSize, + images: images, + ), + ]); @override Widget build(BuildContext context) { diff --git a/packages/flame/lib/src/widgets/sprite_painter.dart b/packages/flame/lib/src/widgets/sprite_painter.dart index 1cad06f36..c1cb82473 100644 --- a/packages/flame/lib/src/widgets/sprite_painter.dart +++ b/packages/flame/lib/src/widgets/sprite_painter.dart @@ -12,7 +12,7 @@ class SpritePainter extends CustomPainter { final double _angle; SpritePainter(this._sprite, this._anchor, this._paint, {double angle = 0}) - : _angle = angle; + : _angle = angle; @override bool shouldRepaint(SpritePainter oldDelegate) { diff --git a/packages/flame/lib/src/widgets/sprite_widget.dart b/packages/flame/lib/src/widgets/sprite_widget.dart index 724937b06..8e31ee6b4 100644 --- a/packages/flame/lib/src/widgets/sprite_widget.dart +++ b/packages/flame/lib/src/widgets/sprite_widget.dart @@ -67,11 +67,11 @@ class SpriteWidget extends StatefulWidget { this.rasterize = false, super.key, }) : _spriteFuture = Sprite.load( - path, - srcSize: srcSize, - srcPosition: srcPosition, - images: images, - ); + path, + srcSize: srcSize, + srcPosition: srcPosition, + images: images, + ); @override State createState() => _SpriteWidgetState(); diff --git a/packages/flame/pubspec.yaml b/packages/flame/pubspec.yaml index 12d108b96..732396119 100644 --- a/packages/flame/pubspec.yaml +++ b/packages/flame/pubspec.yaml @@ -14,7 +14,7 @@ topics: - animations environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame/test/_resources/custom_flame_game.dart b/packages/flame/test/_resources/custom_flame_game.dart index 062a20cc8..f064354c7 100644 --- a/packages/flame/test/_resources/custom_flame_game.dart +++ b/packages/flame/test/_resources/custom_flame_game.dart @@ -5,8 +5,8 @@ class CustomFlameGame extends FlameGame { super.children, Future? Function(FlameGame)? onLoad, void Function(FlameGame)? onMount, - }) : _onLoad = onLoad, - _onMount = onMount; + }) : _onLoad = onLoad, + _onMount = onMount; final Future? Function(FlameGame)? _onLoad; final void Function(FlameGame)? _onMount; diff --git a/packages/flame/test/camera/camera_test_helpers.dart b/packages/flame/test/camera/camera_test_helpers.dart index 40da4452c..784259f9c 100644 --- a/packages/flame/test/camera/camera_test_helpers.dart +++ b/packages/flame/test/camera/camera_test_helpers.dart @@ -4,7 +4,7 @@ import 'package:flame/components.dart'; class CrossHair extends PositionComponent { CrossHair({super.size, super.position, this.color = const Color(0xFFFF0000)}) - : super(anchor: Anchor.center); + : super(anchor: Anchor.center); final Color color; Paint get _paint => Paint() diff --git a/packages/flame/test/camera/viewfinder_test.dart b/packages/flame/test/camera/viewfinder_test.dart index 7a4429b68..12d79760c 100644 --- a/packages/flame/test/camera/viewfinder_test.dart +++ b/packages/flame/test/camera/viewfinder_test.dart @@ -213,18 +213,19 @@ void main() { }); testWithFlameGame( - 'can change visibleGameSize directly with FixedAspectRatioViewport', - (game) async { - final world = World()..addToParent(game); - final cameraComponent = CameraComponent( - world: world, - viewport: FixedAspectRatioViewport(aspectRatio: 0.2), - )..addToParent(game); - expect( - () => cameraComponent.viewfinder.visibleGameSize = Vector2(100, 100), - returnsNormally, - ); - }); + 'can change visibleGameSize directly with FixedAspectRatioViewport', + (game) async { + final world = World()..addToParent(game); + final cameraComponent = CameraComponent( + world: world, + viewport: FixedAspectRatioViewport(aspectRatio: 0.2), + )..addToParent(game); + expect( + () => cameraComponent.viewfinder.visibleGameSize = Vector2(100, 100), + returnsNormally, + ); + }, + ); }); } diff --git a/packages/flame/test/camera/viewports/fixed_resolution_viewport_test.dart b/packages/flame/test/camera/viewports/fixed_resolution_viewport_test.dart index 1b9709c1f..5a62b9f88 100644 --- a/packages/flame/test/camera/viewports/fixed_resolution_viewport_test.dart +++ b/packages/flame/test/camera/viewports/fixed_resolution_viewport_test.dart @@ -21,22 +21,23 @@ void main() { }); testWithFlameGame( - 'children components receive virtualSize in onParentResize', - (game) async { - final fixedResolution = Vector2(800, 600); - final viewport = FixedResolutionViewport(resolution: fixedResolution); - game.camera.viewport = viewport; + 'children components receive virtualSize in onParentResize', + (game) async { + final fixedResolution = Vector2(800, 600); + final viewport = FixedResolutionViewport(resolution: fixedResolution); + game.camera.viewport = viewport; - final child = _OnParentResizeTesterComponent(); - await child.addToParent(viewport); + final child = _OnParentResizeTesterComponent(); + await child.addToParent(viewport); - await game.ready(); + await game.ready(); - expect(child._parentSize, fixedResolution); + expect(child._parentSize, fixedResolution); - game.onGameResize(Vector2(400, 300)); - expect(child._parentSize, fixedResolution); - }); + game.onGameResize(Vector2(400, 300)); + expect(child._parentSize, fixedResolution); + }, + ); }); } diff --git a/packages/flame/test/camera/viewports/fixed_size_viewport_test.dart b/packages/flame/test/camera/viewports/fixed_size_viewport_test.dart index 4577b51c8..40d50b2f5 100644 --- a/packages/flame/test/camera/viewports/fixed_size_viewport_test.dart +++ b/packages/flame/test/camera/viewports/fixed_size_viewport_test.dart @@ -49,13 +49,14 @@ void main() { 'Clipping behavior', (game, tester) async { final world = World(); - final camera = CameraComponent( - world: world, - viewport: FixedSizeViewport(500, 200), - ) - ..viewport.position = Vector2(400, 300) - ..viewport.anchor = Anchor.center - ..viewfinder.position = Vector2.zero(); + final camera = + CameraComponent( + world: world, + viewport: FixedSizeViewport(500, 200), + ) + ..viewport.position = Vector2(400, 300) + ..viewport.anchor = Anchor.center + ..viewfinder.position = Vector2.zero(); world.add( CircleComponent( position: Vector2.zero(), diff --git a/packages/flame/test/camera/viewports/max_viewport_test.dart b/packages/flame/test/camera/viewports/max_viewport_test.dart index 3e14f779b..04c5c6069 100644 --- a/packages/flame/test/camera/viewports/max_viewport_test.dart +++ b/packages/flame/test/camera/viewports/max_viewport_test.dart @@ -47,17 +47,20 @@ void main() { }); testWithGame( - 'check that onViewportResize is called with game CameraComponent', () { - return FlameGame( - camera: CameraComponent(viewport: _MyMaxViewport()), - ); - }, (game) async { - final viewport = game.camera.viewport; - expect(viewport, isA<_MyMaxViewport>()); - expect((viewport as _MyMaxViewport).onViewportResizeCalled, 3); - game.onGameResize(Vector2(200, 200)); - expect(viewport.onViewportResizeCalled, 5); - }); + 'check that onViewportResize is called with game CameraComponent', + () { + return FlameGame( + camera: CameraComponent(viewport: _MyMaxViewport()), + ); + }, + (game) async { + final viewport = game.camera.viewport; + expect(viewport, isA<_MyMaxViewport>()); + expect((viewport as _MyMaxViewport).onViewportResizeCalled, 3); + game.onGameResize(Vector2(200, 200)); + expect(viewport.onViewportResizeCalled, 5); + }, + ); }); } diff --git a/packages/flame/test/collisions/collision_callback_benchmark_test.dart b/packages/flame/test/collisions/collision_callback_benchmark_test.dart index 24aa03e45..69827f22e 100644 --- a/packages/flame/test/collisions/collision_callback_benchmark_test.dart +++ b/packages/flame/test/collisions/collision_callback_benchmark_test.dart @@ -13,10 +13,10 @@ class _TestBlock extends PositionComponent with CollisionCallbacks { static int collisionCounter = 0; _TestBlock(Vector2 position, Vector2 size, this.velocity) - : super( - position: position, - size: size, - ) { + : super( + position: position, + size: size, + ) { add(CircleHitbox()); } @@ -62,7 +62,8 @@ void main() { for (var i = 0; i < ticks; i++) { game.update(1 / 60); } - final totalTime = DateTime.now().millisecondsSinceEpoch - + final totalTime = + DateTime.now().millisecondsSinceEpoch - startTime.millisecondsSinceEpoch; // ignore:avoid_print print( diff --git a/packages/flame/test/collisions/collision_callback_test.dart b/packages/flame/test/collisions/collision_callback_test.dart index a0fa0caed..f00c86c71 100644 --- a/packages/flame/test/collisions/collision_callback_test.dart +++ b/packages/flame/test/collisions/collision_callback_test.dart @@ -51,29 +51,29 @@ void main() { }, 'collidable callbacks are called when removing a Collidable': (game) async { - final blockA = TestBlock( - Vector2.zero(), - Vector2.all(10), - ); - final blockB = TestBlock( - Vector2.all(1), - Vector2.all(10), - ); - await game.ensureAddAll([blockA, blockB]); - game.update(0); - expect(blockA.collidingWith(blockB), true); - expect(blockB.collidingWith(blockA), true); - expect(blockA.activeCollisions.length, 1); - expect(blockB.activeCollisions.length, 1); - game.remove(blockA); - game.update(0); - expect(blockA.endCounter, 1); - expect(blockB.endCounter, 1); - expect(blockA.collidingWith(blockB), false); - expect(blockB.collidingWith(blockA), false); - expect(blockA.activeCollisions.length, 0); - expect(blockB.activeCollisions.length, 0); - }, + final blockA = TestBlock( + Vector2.zero(), + Vector2.all(10), + ); + final blockB = TestBlock( + Vector2.all(1), + Vector2.all(10), + ); + await game.ensureAddAll([blockA, blockB]); + game.update(0); + expect(blockA.collidingWith(blockB), true); + expect(blockB.collidingWith(blockA), true); + expect(blockA.activeCollisions.length, 1); + expect(blockB.activeCollisions.length, 1); + game.remove(blockA); + game.update(0); + expect(blockA.endCounter, 1); + expect(blockB.endCounter, 1); + expect(blockA.collidingWith(blockB), false); + expect(blockB.collidingWith(blockA), false); + expect(blockA.activeCollisions.length, 0); + expect(blockB.activeCollisions.length, 0); + }, 'hitbox callbacks are called': (game) async { final blockA = TestBlock( Vector2.zero(), @@ -143,28 +143,28 @@ void main() { }, 'hitboxParent is PositionComponent but not CollisionCallbacks': (game) async { - final player = PositionComponent( - position: Vector2.all(0), - size: Vector2.all(10), - children: [ - Component( + final player = PositionComponent( + position: Vector2.all(0), + size: Vector2.all(10), children: [ - Component(children: [TestHitbox()]), + Component( + children: [ + Component(children: [TestHitbox()]), + ], + ), ], - ), - ], - ); - final block = TestBlock(Vector2.all(100), Vector2.all(10)); + ); + final block = TestBlock(Vector2.all(100), Vector2.all(10)); - await game.ensureAddAll([player, block]); + await game.ensureAddAll([player, block]); - block.position = Vector2.all(5); - game.update(0); + block.position = Vector2.all(5); + game.update(0); - expect(block.startCounter, 1); - expect(block.onCollisionCounter, 1); - expect(block.endCounter, 0); - }, + expect(block.startCounter, 1); + expect(block.onCollisionCounter, 1); + expect(block.endCounter, 0); + }, }); }); @@ -197,52 +197,52 @@ void main() { }, 'hitbox end callbacks are called when hitbox is moved away fast': (game) async { - final blockA = TestBlock( - Vector2.zero(), - Vector2.all(10), - ); - final blockB = TestBlock( - Vector2.all(1), - Vector2.all(10), - ); - final hitboxA = blockA.hitbox; - final hitboxB = blockB.hitbox; - await game.ensureAddAll([blockA, blockB]); - game.update(0); - expect(hitboxA.collidingWith(hitboxB), true); - expect(hitboxB.collidingWith(hitboxA), true); - expect(hitboxA.activeCollisions.length, 1); - expect(hitboxB.activeCollisions.length, 1); - blockB.position = Vector2.all(1000); - game.update(0); - expect(hitboxA.collidingWith(hitboxB), false); - expect(hitboxB.collidingWith(hitboxA), false); - expect(hitboxA.activeCollisions.length, 0); - expect(hitboxB.activeCollisions.length, 0); - expect(hitboxA.endCounter, 1); - expect(hitboxB.endCounter, 1); - }, + final blockA = TestBlock( + Vector2.zero(), + Vector2.all(10), + ); + final blockB = TestBlock( + Vector2.all(1), + Vector2.all(10), + ); + final hitboxA = blockA.hitbox; + final hitboxB = blockB.hitbox; + await game.ensureAddAll([blockA, blockB]); + game.update(0); + expect(hitboxA.collidingWith(hitboxB), true); + expect(hitboxB.collidingWith(hitboxA), true); + expect(hitboxA.activeCollisions.length, 1); + expect(hitboxB.activeCollisions.length, 1); + blockB.position = Vector2.all(1000); + game.update(0); + expect(hitboxA.collidingWith(hitboxB), false); + expect(hitboxB.collidingWith(hitboxA), false); + expect(hitboxA.activeCollisions.length, 0); + expect(hitboxB.activeCollisions.length, 0); + expect(hitboxA.endCounter, 1); + expect(hitboxB.endCounter, 1); + }, 'onCollisionEnd is only called when there previously was a collision': (game) async { - final blockA = TestBlock( - Vector2.zero(), - Vector2.all(10), - ); - final blockB = TestBlock( - Vector2(5, 11), - Vector2.all(10), - ); - await game.ensureAddAll([blockA, blockB]); - game.update(0); - blockB.position.x += 2 * blockA.size.x; - game.update(0); - expect(blockA.startCounter, 0); - expect(blockB.startCounter, 0); - expect(blockA.onCollisionCounter, 0); - expect(blockB.onCollisionCounter, 0); - expect(blockA.endCounter, 0); - expect(blockB.endCounter, 0); - }, + final blockA = TestBlock( + Vector2.zero(), + Vector2.all(10), + ); + final blockB = TestBlock( + Vector2(5, 11), + Vector2.all(10), + ); + await game.ensureAddAll([blockA, blockB]); + game.update(0); + blockB.position.x += 2 * blockA.size.x; + game.update(0); + expect(blockA.startCounter, 0); + expect(blockB.startCounter, 0); + expect(blockA.onCollisionCounter, 0); + expect(blockB.onCollisionCounter, 0); + expect(blockA.endCounter, 0); + expect(blockB.endCounter, 0); + }, 'callbacks are only called once for hitboxes on each other': (game) async { final blockA = TestBlock( Vector2.zero(), @@ -299,110 +299,116 @@ void main() { }, 'callbacks return the parent of the composite hitbox on collisions': (game) async { - final size = Vector2.all(10); - final hitboxA = TestHitbox(); - final compositeA = CompositeTestHitbox(size: size, children: [hitboxA]); - final blockA = TestBlock( - Vector2.zero(), - size, - children: [compositeA], - addTestHitbox: false, - ); - final hitboxB = TestHitbox(); - final compositeB = CompositeTestHitbox(size: size, children: [hitboxB]); - final blockB = TestBlock( - Vector2.all(15), - size, - children: [compositeB], - addTestHitbox: false, - ); - await game.ensureAddAll([blockA, blockB]); + final size = Vector2.all(10); + final hitboxA = TestHitbox(); + final compositeA = CompositeTestHitbox( + size: size, + children: [hitboxA], + ); + final blockA = TestBlock( + Vector2.zero(), + size, + children: [compositeA], + addTestHitbox: false, + ); + final hitboxB = TestHitbox(); + final compositeB = CompositeTestHitbox( + size: size, + children: [hitboxB], + ); + final blockB = TestBlock( + Vector2.all(15), + size, + children: [compositeB], + addTestHitbox: false, + ); + await game.ensureAddAll([blockA, blockB]); - game.update(0); - expect(blockA.startCounter, 0); - expect(blockB.startCounter, 0); - expect(blockA.onCollisionCounter, 0); - expect(blockB.onCollisionCounter, 0); - expect(blockA.endCounter, 0); - expect(blockB.endCounter, 0); + game.update(0); + expect(blockA.startCounter, 0); + expect(blockB.startCounter, 0); + expect(blockA.onCollisionCounter, 0); + expect(blockB.onCollisionCounter, 0); + expect(blockA.endCounter, 0); + expect(blockB.endCounter, 0); - blockB.position = Vector2.all(5); - game.update(0); - expect(blockA.startCounter, 1); - expect(blockB.startCounter, 1); - expect(blockA.onCollisionCounter, 1); - expect(blockB.onCollisionCounter, 1); - expect(blockA.endCounter, 0); - expect(blockB.endCounter, 0); - expect(blockA.collidingWith(blockB), isTrue); - expect(blockB.collidingWith(blockA), isTrue); + blockB.position = Vector2.all(5); + game.update(0); + expect(blockA.startCounter, 1); + expect(blockB.startCounter, 1); + expect(blockA.onCollisionCounter, 1); + expect(blockB.onCollisionCounter, 1); + expect(blockA.endCounter, 0); + expect(blockB.endCounter, 0); + expect(blockA.collidingWith(blockB), isTrue); + expect(blockB.collidingWith(blockA), isTrue); - blockB.position.y += 20; - game.update(0); - expect(blockA.startCounter, 1); - expect(blockB.startCounter, 1); - expect(blockA.onCollisionCounter, 1); - expect(blockB.onCollisionCounter, 1); - expect(blockA.endCounter, 1); - expect(blockB.endCounter, 1); - expect(blockA.collidingWith(blockB), isFalse); - expect(blockB.collidingWith(blockA), isFalse); - }, + blockB.position.y += 20; + game.update(0); + expect(blockA.startCounter, 1); + expect(blockB.startCounter, 1); + expect(blockA.onCollisionCounter, 1); + expect(blockB.onCollisionCounter, 1); + expect(blockA.endCounter, 1); + expect(blockB.endCounter, 1); + expect(blockA.collidingWith(blockB), isFalse); + expect(blockB.collidingWith(blockA), isFalse); + }, 'end and start callbacks are only called once for hitboxes sharing a side': (game) async { - final blockA = TestBlock( - Vector2.all(10), - Vector2.all(10), - ); - final blockB = TestBlock( - Vector2.all(21), - Vector2.all(12), - ); - await game.ensureAddAll([blockA, blockB]); + final blockA = TestBlock( + Vector2.all(10), + Vector2.all(10), + ); + final blockB = TestBlock( + Vector2.all(21), + Vector2.all(12), + ); + await game.ensureAddAll([blockA, blockB]); - game.update(0); - expect(blockA.startCounter, 0); - expect(blockB.startCounter, 0); - expect(blockA.onCollisionCounter, 0); - expect(blockB.onCollisionCounter, 0); - expect(blockA.endCounter, 0); - expect(blockB.endCounter, 0); + game.update(0); + expect(blockA.startCounter, 0); + expect(blockB.startCounter, 0); + expect(blockA.onCollisionCounter, 0); + expect(blockB.onCollisionCounter, 0); + expect(blockA.endCounter, 0); + expect(blockB.endCounter, 0); - blockB.position = Vector2(10, 14); - game.update(0); - expect(blockA.startCounter, 1); - expect(blockB.startCounter, 1); - expect(blockA.onCollisionCounter, 1); - expect(blockB.onCollisionCounter, 1); - expect(blockA.endCounter, 0); - expect(blockB.endCounter, 0); + blockB.position = Vector2(10, 14); + game.update(0); + expect(blockA.startCounter, 1); + expect(blockB.startCounter, 1); + expect(blockA.onCollisionCounter, 1); + expect(blockB.onCollisionCounter, 1); + expect(blockA.endCounter, 0); + expect(blockB.endCounter, 0); - game.update(0); - expect(blockA.startCounter, 1); - expect(blockB.startCounter, 1); - expect(blockA.onCollisionCounter, 2); - expect(blockB.onCollisionCounter, 2); - expect(blockA.endCounter, 0); - expect(blockB.endCounter, 0); + game.update(0); + expect(blockA.startCounter, 1); + expect(blockB.startCounter, 1); + expect(blockA.onCollisionCounter, 2); + expect(blockB.onCollisionCounter, 2); + expect(blockA.endCounter, 0); + expect(blockB.endCounter, 0); - game.update(0); - expect(blockA.startCounter, 1); - expect(blockB.startCounter, 1); - expect(blockA.onCollisionCounter, 3); - expect(blockB.onCollisionCounter, 3); - expect(blockA.endCounter, 0); - expect(blockB.endCounter, 0); + game.update(0); + expect(blockA.startCounter, 1); + expect(blockB.startCounter, 1); + expect(blockA.onCollisionCounter, 3); + expect(blockB.onCollisionCounter, 3); + expect(blockA.endCounter, 0); + expect(blockB.endCounter, 0); - blockB.position = - blockA.positionOfAnchor(Anchor.topRight) + Vector2(1, 0); - game.update(0); - expect(blockA.startCounter, 1); - expect(blockB.startCounter, 1); - expect(blockA.onCollisionCounter, 3); - expect(blockB.onCollisionCounter, 3); - expect(blockA.endCounter, 1); - expect(blockB.endCounter, 1); - }, + blockB.position = + blockA.positionOfAnchor(Anchor.topRight) + Vector2(1, 0); + game.update(0); + expect(blockA.startCounter, 1); + expect(blockB.startCounter, 1); + expect(blockA.onCollisionCounter, 3); + expect(blockB.onCollisionCounter, 3); + expect(blockA.endCounter, 1); + expect(blockB.endCounter, 1); + }, 'component collision callbacks are not called with hitbox ' 'triggersParentCollision option': (game) async { final utilityHitboxA = TestHitbox('hitboxA') diff --git a/packages/flame/test/collisions/collision_detection_test.dart b/packages/flame/test/collisions/collision_detection_test.dart index 23fb304e6..068e52082 100644 --- a/packages/flame/test/collisions/collision_detection_test.dart +++ b/packages/flame/test/collisions/collision_detection_test.dart @@ -488,8 +488,10 @@ void main() { ); rectangleB.flipVerticallyAroundCenter(); - final flippedIntersections = - geometry.intersections(rectangleA, rectangleB); + final flippedIntersections = geometry.intersections( + rectangleA, + rectangleB, + ); expect( flippedIntersections, @@ -506,8 +508,10 @@ void main() { ); rectangleB.flipHorizontallyAroundCenter(); - final doubleFlippedIntersections = - geometry.intersections(rectangleA, rectangleB); + final doubleFlippedIntersections = geometry.intersections( + rectangleA, + rectangleB, + ); expect( doubleFlippedIntersections, @@ -551,8 +555,10 @@ void main() { ); rectangleB.flipVerticallyAroundCenter(); - final flippedIntersections = - geometry.intersections(rectangleA, rectangleB); + final flippedIntersections = geometry.intersections( + rectangleA, + rectangleB, + ); expect( flippedIntersections, @@ -569,8 +575,10 @@ void main() { ); rectangleB.flipHorizontallyAroundCenter(); - final doubleFlippedIntersections = - geometry.intersections(rectangleA, rectangleB); + final doubleFlippedIntersections = geometry.intersections( + rectangleA, + rectangleB, + ); expect( doubleFlippedIntersections, @@ -951,8 +959,10 @@ void main() { size: Vector2.all(2), anchor: Anchor.center, )..isSolid = true; - final intersections = - geometry.intersections(outerRectangle, innerRectangle); + final intersections = geometry.intersections( + outerRectangle, + innerRectangle, + ); expect( intersections, {innerRectangle.position}, @@ -969,8 +979,10 @@ void main() { size: Vector2.all(2), anchor: Anchor.center, )..isSolid = true; - final intersections = - geometry.intersections(outerRectangle, innerRectangle); + final intersections = geometry.intersections( + outerRectangle, + innerRectangle, + ); expect( intersections.isEmpty, isTrue, @@ -987,8 +999,10 @@ void main() { size: Vector2.all(2), anchor: Anchor.center, ); - final intersections = - geometry.intersections(outerRectangle, innerRectangle); + final intersections = geometry.intersections( + outerRectangle, + innerRectangle, + ); expect( intersections, {innerRectangle.position}, @@ -1211,8 +1225,10 @@ void main() { children: [outerPolygon], ), ]); - final intersections = - game.collisionDetection.intersections(innerCircle, outerPolygon); + final intersections = game.collisionDetection.intersections( + innerCircle, + outerPolygon, + ); expect( intersections.isNotEmpty, isTrue, @@ -1272,68 +1288,68 @@ void main() { }, 'multiple hitboxes after each other with one ignored': (collisionSystem) async { - final game = collisionSystem as FlameGame; - final world = game.world; - await world.ensureAddAll([ - for (var i = 0.0; i < 10; i++) - PositionComponent( - position: Vector2.all(100 + i * 10), - size: Vector2.all(20 - i), - anchor: Anchor.center, - )..add(RectangleHitbox()), - ]); - await game.ready(); - final ray = Ray2( - origin: Vector2.zero(), - direction: Vector2.all(1)..normalize(), - ); - final result = collisionSystem.collisionDetection.raycast( - ray, - ignoreHitboxes: [ - world.children.first.children.first as ShapeHitbox, - ], - ); - expect(result?.hitbox?.parent, game.world.children.toList()[1]); - expect( - result?.reflectionRay?.origin, - closeToVector(Vector2.all(100.5)), - ); - expect( - result?.reflectionRay?.direction, - closeToVector(Vector2(-1, 1)..normalize()), - ); - }, + final game = collisionSystem as FlameGame; + final world = game.world; + await world.ensureAddAll([ + for (var i = 0.0; i < 10; i++) + PositionComponent( + position: Vector2.all(100 + i * 10), + size: Vector2.all(20 - i), + anchor: Anchor.center, + )..add(RectangleHitbox()), + ]); + await game.ready(); + final ray = Ray2( + origin: Vector2.zero(), + direction: Vector2.all(1)..normalize(), + ); + final result = collisionSystem.collisionDetection.raycast( + ray, + ignoreHitboxes: [ + world.children.first.children.first as ShapeHitbox, + ], + ); + expect(result?.hitbox?.parent, game.world.children.toList()[1]); + expect( + result?.reflectionRay?.origin, + closeToVector(Vector2.all(100.5)), + ); + expect( + result?.reflectionRay?.direction, + closeToVector(Vector2(-1, 1)..normalize()), + ); + }, 'multiple hitboxes after each other with filter': (collisionSystem) async { - final game = collisionSystem as FlameGame; - final world = game.world; - await world.ensureAddAll([ - for (var i = 0.0; i < 10; i++) - PositionComponent( - position: Vector2.all(100 + i * 10), - size: Vector2.all(20 - i), - anchor: Anchor.center, - )..add(RectangleHitbox()), - ]); - await game.ready(); - final ray = Ray2( - origin: Vector2.zero(), - direction: Vector2.all(1)..normalize(), - ); - final result = collisionSystem.collisionDetection.raycast( - ray, - hitboxFilter: (hitbox) => hitbox.parent != world.children.first, - ); - expect(result?.hitbox?.parent, game.world.children.toList()[1]); - expect( - result?.reflectionRay?.origin, - closeToVector(Vector2.all(100.5)), - ); - expect( - result?.reflectionRay?.direction, - closeToVector(Vector2(-1, 1)..normalize()), - ); - }, + final game = collisionSystem as FlameGame; + final world = game.world; + await world.ensureAddAll([ + for (var i = 0.0; i < 10; i++) + PositionComponent( + position: Vector2.all(100 + i * 10), + size: Vector2.all(20 - i), + anchor: Anchor.center, + )..add(RectangleHitbox()), + ]); + await game.ready(); + final ray = Ray2( + origin: Vector2.zero(), + direction: Vector2.all(1)..normalize(), + ); + final result = collisionSystem.collisionDetection.raycast( + ray, + hitboxFilter: (hitbox) => hitbox.parent != world.children.first, + ); + expect(result?.hitbox?.parent, game.world.children.toList()[1]); + expect( + result?.reflectionRay?.origin, + closeToVector(Vector2.all(100.5)), + ); + expect( + result?.reflectionRay?.direction, + closeToVector(Vector2(-1, 1)..normalize()), + ); + }, 'ray with origin on hitbox corner': (collisionSystem) async { final game = collisionSystem as FlameGame; final world = game.world; @@ -1520,56 +1536,59 @@ void main() { }, 'ray from bottom-right to top-left within CircleHitbox': (collisionSystem) async { - final game = collisionSystem as FlameGame; - final world = game.world; - await world.ensureAddAll([ - PositionComponent( - position: Vector2.zero(), - size: Vector2.all(10), - )..add(CircleHitbox()), - ]); - await game.ready(); - final ray = Ray2( - origin: Vector2.all(6), - direction: Vector2.all(-1)..normalize(), - ); - final result = collisionSystem.collisionDetection.raycast(ray); - expect(result?.hitbox?.parent, world.children.first); - expect(result?.normal, closeToVector(Vector2.all(0.707106781186547))); - expect( - result?.intersectionPoint, - closeToVector(Vector2.all(1.4644660940672631)), - ); - expect( - result?.reflectionRay?.direction, - closeToVector(Vector2.all(1)..normalize()), - ); - }, + final game = collisionSystem as FlameGame; + final world = game.world; + await world.ensureAddAll([ + PositionComponent( + position: Vector2.zero(), + size: Vector2.all(10), + )..add(CircleHitbox()), + ]); + await game.ready(); + final ray = Ray2( + origin: Vector2.all(6), + direction: Vector2.all(-1)..normalize(), + ); + final result = collisionSystem.collisionDetection.raycast(ray); + expect(result?.hitbox?.parent, world.children.first); + expect( + result?.normal, + closeToVector(Vector2.all(0.707106781186547)), + ); + expect( + result?.intersectionPoint, + closeToVector(Vector2.all(1.4644660940672631)), + ); + expect( + result?.reflectionRay?.direction, + closeToVector(Vector2.all(1)..normalize()), + ); + }, 'ray from bottom within CircleHitbox going down': (collisionSystem) async { - final game = collisionSystem as FlameGame; - final world = game.world; - await world.ensureAddAll([ - PositionComponent( - position: Vector2.zero(), - size: Vector2.all(10), - )..add(CircleHitbox()), - ]); - await game.ready(); - final direction = Vector2(0, 1); - final ray = Ray2(origin: Vector2(5, 6), direction: direction); - final result = collisionSystem.collisionDetection.raycast(ray); - expect(result?.hitbox?.parent, world.children.first); - expect(result?.normal, closeToVector(Vector2(0, -1))); - expect( - result?.intersectionPoint, - closeToVector(Vector2(5, 10)), - ); - expect( - result?.reflectionRay?.direction, - closeToVector(direction.inverted()), - ); - }, + final game = collisionSystem as FlameGame; + final world = game.world; + await world.ensureAddAll([ + PositionComponent( + position: Vector2.zero(), + size: Vector2.all(10), + )..add(CircleHitbox()), + ]); + await game.ready(); + final direction = Vector2(0, 1); + final ray = Ray2(origin: Vector2(5, 6), direction: direction); + final result = collisionSystem.collisionDetection.raycast(ray); + expect(result?.hitbox?.parent, world.children.first); + expect(result?.normal, closeToVector(Vector2(0, -1))); + expect( + result?.intersectionPoint, + closeToVector(Vector2(5, 10)), + ); + expect( + result?.reflectionRay?.direction, + closeToVector(direction.inverted()), + ); + }, 'ray from the left of CircleHitbox': (collisionSystem) async { final game = collisionSystem as FlameGame; final world = game.world; @@ -1934,8 +1953,9 @@ void main() { final reflectionRay1 = results[0].reflectionRay; expect(reflectionRay1?.origin, Vector2(10, 20)); expect(reflectionRay1?.direction, Vector2(-1, 1)..normalize()); - final results2 = - game.collisionDetection.raytrace(reflectionRay1!).toList(); + final results2 = game.collisionDetection + .raytrace(reflectionRay1!) + .toList(); expect(results2.length, 1); // Second box expect(results[1].intersectionPoint, Vector2(-10, 40)); @@ -1964,7 +1984,8 @@ void main() { final ignoreHitbox = world.children.toList()[1].children.first as ShapeHitbox; final results = game.collisionDetection - .raytrace(ray, ignoreHitboxes: [ignoreHitbox]).toList(); + .raytrace(ray, ignoreHitboxes: [ignoreHitbox]) + .toList(); expect(results.length, 1); expect(results.every((e) => e.isActive), isTrue); expect(results.every((e) => e.isInsideHitbox), isFalse); @@ -1974,8 +1995,9 @@ void main() { final reflectionRay1 = results[0].reflectionRay; expect(reflectionRay1?.origin, Vector2(10, 20)); expect(reflectionRay1?.direction, Vector2(-1, 1)..normalize()); - final results2 = - game.collisionDetection.raytrace(reflectionRay1!).toList(); + final results2 = game.collisionDetection + .raytrace(reflectionRay1!) + .toList(); expect(results2.length, 1); }, 'on a rectangle within another': (game) async { @@ -2003,8 +2025,9 @@ void main() { final reflectionRay1 = results[0].reflectionRay; expect(reflectionRay1?.origin, Vector2(30, 20)); expect(reflectionRay1?.direction, Vector2(1, -1)..normalize()); - final results2 = - game.collisionDetection.raytrace(reflectionRay1!).toList(); + final results2 = game.collisionDetection + .raytrace(reflectionRay1!) + .toList(); expect(results2.length, 10); // Second box expect(results[1].intersectionPoint, Vector2(50, 0)); @@ -2045,10 +2068,15 @@ void main() { runCollisionTestRegistry({ 'collisionsCompletedNotifier calls listeners': (game) async { var calledTimes = 0; - final listeners = List.generate(10, (_) => () => calledTimes++); + final listeners = List.generate( + 10, + (_) => + () => calledTimes++, + ); for (final listener in listeners) { - game.collisionDetection.collisionsCompletedNotifier - .addListener(listener); + game.collisionDetection.collisionsCompletedNotifier.addListener( + listener, + ); } game.update(0); expect(calledTimes, listeners.length); diff --git a/packages/flame/test/collisions/collision_passthrough_test.dart b/packages/flame/test/collisions/collision_passthrough_test.dart index 107c35b71..5c74bfa77 100644 --- a/packages/flame/test/collisions/collision_passthrough_test.dart +++ b/packages/flame/test/collisions/collision_passthrough_test.dart @@ -14,9 +14,11 @@ void main() { runCollisionTestRegistry({ 'Passing collisions to parent': (game) async { final passthrough = _Passthrough(); - final hitboxParent = - TestBlock(Vector2.zero(), Vector2.all(10), addTestHitbox: false) - ..add(passthrough); + final hitboxParent = TestBlock( + Vector2.zero(), + Vector2.all(10), + addTestHitbox: false, + )..add(passthrough); final collisionBlock = TestBlock(Vector2.all(1), Vector2.all(10)); game.add(collisionBlock); game.add(hitboxParent); diff --git a/packages/flame/test/collisions/collision_test_helpers.dart b/packages/flame/test/collisions/collision_test_helpers.dart index fe220af18..96730261d 100644 --- a/packages/flame/test/collisions/collision_test_helpers.dart +++ b/packages/flame/test/collisions/collision_test_helpers.dart @@ -110,11 +110,11 @@ class TestBlock extends PositionComponent with CollisionCallbacks { super.children, this.name, bool Function(PositionComponent other)? onComponentTypeCheck, - }) : _onComponentTypeCheck = onComponentTypeCheck, - super( - position: position, - size: size, - ) { + }) : _onComponentTypeCheck = onComponentTypeCheck, + super( + position: position, + size: size, + ) { children.register(); if (addTestHitbox) { add(hitbox..collisionType = type); diff --git a/packages/flame/test/components/advanced_button_component_test.dart b/packages/flame/test/components/advanced_button_component_test.dart index 9d70f439f..c5120ff80 100644 --- a/packages/flame/test/components/advanced_button_component_test.dart +++ b/packages/flame/test/components/advanced_button_component_test.dart @@ -99,8 +99,9 @@ void main() { size: componentSize, ), ); - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; @@ -145,8 +146,9 @@ void main() { ), ); button.isDisabled = true; - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; diff --git a/packages/flame/test/components/button_component_test.dart b/packages/flame/test/components/button_component_test.dart index a399158b0..24793149f 100644 --- a/packages/flame/test/components/button_component_test.dart +++ b/packages/flame/test/components/button_component_test.dart @@ -93,8 +93,9 @@ void main() { size: componentSize, ), ); - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; diff --git a/packages/flame/test/components/clip_component_test.dart b/packages/flame/test/components/clip_component_test.dart index 6d5b34a1e..6225db7b8 100644 --- a/packages/flame/test/components/clip_component_test.dart +++ b/packages/flame/test/components/clip_component_test.dart @@ -5,11 +5,11 @@ import 'package:flutter_test/flutter_test.dart'; class _Rectangle extends RectangleComponent { _Rectangle() - : super( - size: Vector2(200, 200), - anchor: Anchor.center, - paint: Paint()..color = Colors.blue, - ); + : super( + size: Vector2(200, 200), + anchor: Anchor.center, + paint: Paint()..color = Colors.blue, + ); } void main() { diff --git a/packages/flame/test/components/component_test.dart b/packages/flame/test/components/component_test.dart index f3fa7b70d..4110ecc5b 100644 --- a/packages/flame/test/components/component_test.dart +++ b/packages/flame/test/components/component_test.dart @@ -83,8 +83,9 @@ void main() { }, ); - testWithFlameGame('remove parent of child that has removed set', - (game) async { + testWithFlameGame('remove parent of child that has removed set', ( + game, + ) async { final parent = _LifecycleComponent('parent')..addToParent(game); final child = _LifecycleComponent('child')..addToParent(parent); await game.ready(); @@ -375,16 +376,18 @@ void main() { expect(game.hasLifecycleEvents, isFalse); }); - testWithFlameGame("doesn't block when there are no events", - (game) async { + testWithFlameGame("doesn't block when there are no events", ( + game, + ) async { await game.ready(); expect(game.hasLifecycleEvents, isFalse); await game.lifecycleEventsProcessed; expect(game.hasLifecycleEvents, isFalse); }); - testWithFlameGame('guarantees addition even with heavy onLoad', - (game) async { + testWithFlameGame('guarantees addition even with heavy onLoad', ( + game, + ) async { await game.ready(); final component = _SlowComponent('heavy', 0.1); final child = _SlowComponent('child', 0.1); @@ -982,8 +985,9 @@ void main() { game.update(0); expect(game.world.children.length, 5); expect( - game.world.children - .every((c) => (c as _IdentifiableComponent).id.isOdd), + game.world.children.every( + (c) => (c as _IdentifiableComponent).id.isOdd, + ), true, ); }, @@ -1143,8 +1147,10 @@ void main() { var total = 0; void waitFor(int milliseconds, Future Function() fn) { total++; - Future.delayed(Duration(milliseconds: milliseconds), fn) - .whenComplete(() => completed++); + Future.delayed( + Duration(milliseconds: milliseconds), + fn, + ).whenComplete(() => completed++); } Future start() async { @@ -1447,8 +1453,9 @@ void main() { }); group('findRootGame()', () { - testWithFlameGame('finds root game in nested game structure', - (game) async { + testWithFlameGame('finds root game in nested game structure', ( + game, + ) async { final component = Component(); await game.ensureAdd( FlameGame( @@ -1460,8 +1467,9 @@ void main() { expect(component.findRootGame(), game); }); - testWithFlameGame('finds root game in non-nested game structure', - (game) async { + testWithFlameGame('finds root game in non-nested game structure', ( + game, + ) async { final component = Component(); await game.ensureAdd(component); expect(component.findRootGame(), game); @@ -1474,10 +1482,10 @@ void main() { expect(component0.children.strictMode, false); Component.childrenFactory = () => OrderedSet.mapping( - (e) => e.priority, - // ignore: avoid_redundant_argument_values - strictMode: true, - ); + (e) => e.priority, + // ignore: avoid_redundant_argument_values + strictMode: true, + ); final component1 = Component(); final component2 = Component(); component1.add(component2); diff --git a/packages/flame/test/components/components_notifier_test.dart b/packages/flame/test/components/components_notifier_test.dart index 1619e43be..cccfd2b6f 100644 --- a/packages/flame/test/components/components_notifier_test.dart +++ b/packages/flame/test/components/components_notifier_test.dart @@ -79,8 +79,8 @@ void main() { var called = 0; game.componentsNotifier().addListener( - () => parentCalled++, - ); + () => parentCalled++, + ); game.componentsNotifier<_Enemy>().addListener(() => called++); expect(game.notifiers.length, equals(2)); diff --git a/packages/flame/test/components/hud_button_component_test.dart b/packages/flame/test/components/hud_button_component_test.dart index d1a856c17..e072bafde 100644 --- a/packages/flame/test/components/hud_button_component_test.dart +++ b/packages/flame/test/components/hud_button_component_test.dart @@ -51,7 +51,8 @@ void main() { tapDispatcher.handleTapDown( 1, TapDownDetails( - globalPosition: initialGameSize.toOffset() + + globalPosition: + initialGameSize.toOffset() + margin.bottomRight - const Offset(1, 1), ), @@ -73,7 +74,8 @@ void main() { tapDispatcher.handleTapDown( 1, TapDownDetails( - globalPosition: initialGameSize.toOffset() + + globalPosition: + initialGameSize.toOffset() + margin.bottomRight - const Offset(1, 1), ), @@ -103,8 +105,9 @@ void main() { margin: margin, ), ); - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; diff --git a/packages/flame/test/components/input/sprite_button_component_test.dart b/packages/flame/test/components/input/sprite_button_component_test.dart index b879db53a..697287bc0 100644 --- a/packages/flame/test/components/input/sprite_button_component_test.dart +++ b/packages/flame/test/components/input/sprite_button_component_test.dart @@ -106,8 +106,9 @@ Future main() async { ), ); - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; @@ -249,8 +250,9 @@ Future main() async { expect(component.current, _ButtonState.up); }); - testWithFlameGame('correctly registers taps onGameResize (custom button)', - (game) async { + testWithFlameGame('correctly registers taps onGameResize (custom button)', ( + game, + ) async { final initialGameSize = Vector2.all(100); final componentSize = Vector2.all(10); final buttonPosition = Vector2.all(100); @@ -281,8 +283,9 @@ Future main() async { ), ); - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; diff --git a/packages/flame/test/components/joystick_component_test.dart b/packages/flame/test/components/joystick_component_test.dart index 59451cf13..bda5d20c5 100644 --- a/packages/flame/test/components/joystick_component_test.dart +++ b/packages/flame/test/components/joystick_component_test.dart @@ -54,8 +54,10 @@ void main() { testWithFlameGame( 'properly re-positions with FixedResolutionViewport', (game) async { - game.camera = - CameraComponent.withFixedResolution(width: 100, height: 200); + game.camera = CameraComponent.withFixedResolution( + width: 100, + height: 200, + ); game.onGameResize(Vector2(100, 200)); final joystick = JoystickComponent( knob: CircleComponent(radius: 5.0), diff --git a/packages/flame/test/components/mixins/component_viewport_margin_test.dart b/packages/flame/test/components/mixins/component_viewport_margin_test.dart index 707a4565c..455de0588 100644 --- a/packages/flame/test/components/mixins/component_viewport_margin_test.dart +++ b/packages/flame/test/components/mixins/component_viewport_margin_test.dart @@ -30,7 +30,8 @@ void main() { final actualNewPosition = component.position.toOffset(); - final expectedNewPosition = game.size.toOffset() + + final expectedNewPosition = + game.size.toOffset() + margin.bottomRight - componentSize.toOffset(); diff --git a/packages/flame/test/components/mixins/gesture_hitboxes_test.dart b/packages/flame/test/components/mixins/gesture_hitboxes_test.dart index f72fcee03..0201bd5cc 100644 --- a/packages/flame/test/components/mixins/gesture_hitboxes_test.dart +++ b/packages/flame/test/components/mixins/gesture_hitboxes_test.dart @@ -26,29 +26,32 @@ void main() { }); testWithFlameGame( - 'hitbox is larger than the component and the point is outside ' - "of the component's size", (game) async { - final component = _HitboxComponent(); - component.position.setValues(1.0, 1.0); - component.anchor = Anchor.topLeft; - component.size.setValues(2.0, 2.0); + 'hitbox is larger than the component and the point is outside ' + "of the component's size", + (game) async { + final component = _HitboxComponent(); + component.position.setValues(1.0, 1.0); + component.anchor = Anchor.topLeft; + component.size.setValues(2.0, 2.0); - final hitbox = PolygonHitbox([ - Vector2(10, 0), - Vector2(0, -10), - Vector2(-10, 0), - Vector2(0, 10), - ]); + final hitbox = PolygonHitbox([ + Vector2(10, 0), + Vector2(0, -10), + Vector2(-10, 0), + Vector2(0, 10), + ]); - component.add(hitbox); - await game.ensureAdd(component); + component.add(hitbox); + await game.ensureAdd(component); - final point = Vector2(9, 0); - expect(component.containsPoint(point), isTrue); - }); + final point = Vector2(9, 0); + expect(component.containsPoint(point), isTrue); + }, + ); - testWithFlameGame('CircleHitbox is displaced within the parent component', - (game) async { + testWithFlameGame('CircleHitbox is displaced within the parent component', ( + game, + ) async { final component = _HitboxComponent(); component.position.setAll(10); component.size.setValues(2.0, 2.0); @@ -69,26 +72,27 @@ void main() { }); testWithFlameGame( - 'RectangleHitbox is displaced within the parent component', - (game) async { - final component = _HitboxComponent(); - component.position.setAll(10); - component.size.setValues(2.0, 2.0); + 'RectangleHitbox is displaced within the parent component', + (game) async { + final component = _HitboxComponent(); + component.position.setAll(10); + component.size.setValues(2.0, 2.0); - final hitbox = RectangleHitbox( - position: Vector2(1.0, 1.5), - size: Vector2.all(1.0), - anchor: Anchor.center, - ); + final hitbox = RectangleHitbox( + position: Vector2(1.0, 1.5), + size: Vector2.all(1.0), + anchor: Anchor.center, + ); - component.add(hitbox); - await game.ensureAdd(component); + component.add(hitbox); + await game.ensureAdd(component); - final point = component.position + hitbox.position; - expect(component.containsPoint(point), isTrue); - final outsidePoint = component.position + Vector2(1.0, 0.99); - expect(component.containsPoint(outsidePoint), isFalse); - }); + final point = component.position + hitbox.position; + expect(component.containsPoint(point), isTrue); + final outsidePoint = component.position + Vector2(1.0, 0.99); + expect(component.containsPoint(outsidePoint), isFalse); + }, + ); testWithFlameGame('get component hitboxes', (game) async { final component = _HitboxComponent(); diff --git a/packages/flame/test/components/mixins/has_decorator_test.dart b/packages/flame/test/components/mixins/has_decorator_test.dart index 2b9d2db86..c8513d983 100644 --- a/packages/flame/test/components/mixins/has_decorator_test.dart +++ b/packages/flame/test/components/mixins/has_decorator_test.dart @@ -31,7 +31,7 @@ void main() { class _DecoratedComponent extends PositionComponent { _DecoratedComponent({super.position, super.size}) - : super(anchor: Anchor.center); + : super(anchor: Anchor.center); final paint = Paint()..color = const Color(0xff30ccd2); diff --git a/packages/flame/test/components/parallax_test.dart b/packages/flame/test/components/parallax_test.dart index 2fa535eb9..b5be02c2a 100644 --- a/packages/flame/test/components/parallax_test.dart +++ b/packages/flame/test/components/parallax_test.dart @@ -92,21 +92,25 @@ void main() { ); testWithGame<_ParallaxGame>( - 'can have fullscreen ParallaxComponent', _ParallaxGame.new, - (game) async { - expect(game.parallaxComponent.size, game.size); - }); + 'can have fullscreen ParallaxComponent', + _ParallaxGame.new, + (game) async { + expect(game.parallaxComponent.size, game.size); + }, + ); testWithGame<_SlowLoadParallaxGame>( - 'can have layers with different loading times', - _SlowLoadParallaxGame.new, (game) async { - final parallax = game.parallaxComponent.parallax!; - var lastLength = 0.0; - for (final layer in parallax.layers) { - final velocityLength = layer.velocityMultiplier.length; - expect(velocityLength > lastLength, isTrue); - lastLength = velocityLength; - } - }); + 'can have layers with different loading times', + _SlowLoadParallaxGame.new, + (game) async { + final parallax = game.parallaxComponent.parallax!; + var lastLength = 0.0; + for (final layer in parallax.layers) { + final velocityLength = layer.velocityMultiplier.length; + expect(velocityLength > lastLength, isTrue); + lastLength = velocityLength; + } + }, + ); }); } diff --git a/packages/flame/test/components/position_component_test.dart b/packages/flame/test/components/position_component_test.dart index 03b226e64..6b3c80baa 100644 --- a/packages/flame/test/components/position_component_test.dart +++ b/packages/flame/test/components/position_component_test.dart @@ -171,8 +171,9 @@ void main() { expect(component.containsPoint(point), true); }); - testWithFlameGame('component with hitbox with position contains point', - (game) async { + testWithFlameGame('component with hitbox with position contains point', ( + game, + ) async { final component = _MyHitboxComponent(); component.position.setValues(1.0, 1.0); component.anchor = Anchor.topLeft; @@ -194,30 +195,33 @@ void main() { expect(component.containsPoint(point), true); }); - testWithFlameGame('component with hitbox with position just misses point', - (game) async { - final component = _MyHitboxComponent(); - component.position.setValues(1.0, 1.0); - component.anchor = Anchor.topLeft; - component.size.setValues(2.0, 2.0); - final hitbox = PolygonHitbox( - [ - Vector2(1, 0), - Vector2(0, -1), - Vector2(-1, 0), - Vector2(0, 1), - ], - position: Vector2(5, 6), - ); - component.add(hitbox); - await game.ensureAdd(component); + testWithFlameGame( + 'component with hitbox with position just misses point', + (game) async { + final component = _MyHitboxComponent(); + component.position.setValues(1.0, 1.0); + component.anchor = Anchor.topLeft; + component.size.setValues(2.0, 2.0); + final hitbox = PolygonHitbox( + [ + Vector2(1, 0), + Vector2(0, -1), + Vector2(-1, 0), + Vector2(0, 1), + ], + position: Vector2(5, 6), + ); + component.add(hitbox); + await game.ensureAdd(component); - final point = component.position + - (component.size / 4) - - Vector2(0.01, 0) + - hitbox.position; - expect(component.containsPoint(point), false); - }); + final point = + component.position + + (component.size / 4) - + Vector2(0.01, 0) + + hitbox.position; + expect(component.containsPoint(point), false); + }, + ); testWithFlameGame( 'component with anchor topLeft contains point on edge', @@ -868,8 +872,10 @@ void main() { testWithFlameGame('auxiliary getters/setters', (game) async { final parent = PositionComponent(position: Vector2(12, 19)); - final child = - PositionComponent(position: Vector2(11, -1), size: Vector2(4, 6)); + final child = PositionComponent( + position: Vector2(11, -1), + size: Vector2(4, 6), + ); parent.add(child); game.add(parent); await game.ready(); @@ -1269,8 +1275,9 @@ void main() { expect(child.absoluteAngle, 3 * pi / 4); }); - testWithFlameGame('absoluteAngle with parent and child rotated', - (game) async { + testWithFlameGame('absoluteAngle with parent and child rotated', ( + game, + ) async { final parent = PositionComponent()..angle = pi / 8; final child = PositionComponent()..angle = pi / 8; parent.add(child); @@ -1311,8 +1318,9 @@ void main() { expect(child.absoluteAngle, (pi / 4 + pi).toNormalizedAngle()); }); - testWithFlameGame('absoluteAngle with flipped child and parent', - (game) async { + testWithFlameGame('absoluteAngle with flipped child and parent', ( + game, + ) async { final parent = PositionComponent()..angle = pi / 8; final child = PositionComponent()..angle = pi / 8; parent.add(child); diff --git a/packages/flame/test/components/post_process_component_test.dart b/packages/flame/test/components/post_process_component_test.dart index 9a0e5bbac..520149ab7 100644 --- a/packages/flame/test/components/post_process_component_test.dart +++ b/packages/flame/test/components/post_process_component_test.dart @@ -17,25 +17,31 @@ Future main() async { }); testWithFlameGame( - 'renders post process with the bounding box of the children', - (game) async { - final postProcess = PostProcessComponent( - postProcess: PostProcessGroup(postProcesses: []), - children: [ - PositionComponent(size: Vector2.all(50)), - PositionComponent(position: Vector2.all(100), size: Vector2.all(50)), - ], - ); - await game.ensureAdd(postProcess); + 'renders post process with the bounding box of the children', + (game) async { + final postProcess = PostProcessComponent( + postProcess: PostProcessGroup(postProcesses: []), + children: [ + PositionComponent(size: Vector2.all(50)), + PositionComponent( + position: Vector2.all(100), + size: Vector2.all(50), + ), + ], + ); + await game.ensureAdd(postProcess); - expect(game.children, contains(postProcess)); - expect(postProcess.size, Vector2.all(150)); - }); + expect(game.children, contains(postProcess)); + expect(postProcess.size, Vector2.all(150)); + }, + ); testWithFlameGame('changes size when children change', (game) async { final componentA = PositionComponent(size: Vector2.all(50)); - final componentB = - PositionComponent(position: Vector2.all(100), size: Vector2.all(50)); + final componentB = PositionComponent( + position: Vector2.all(100), + size: Vector2.all(50), + ); final postProcess = PostProcessComponent( postProcess: PostProcessGroup(postProcesses: []), children: [componentA, componentB], diff --git a/packages/flame/test/components/route_test.dart b/packages/flame/test/components/route_test.dart index 3af95ff79..73a47672d 100644 --- a/packages/flame/test/components/route_test.dart +++ b/packages/flame/test/components/route_test.dart @@ -523,10 +523,10 @@ class _CustomRoute extends Route { void Function(Route, Route?)? onPush, void Function(Route, Route)? onPop, Component Function(Route)? build, - }) : _onPush = onPush, - _onPop = onPop, - _build = build, - super(builder); + }) : _onPush = onPush, + _onPop = onPop, + _build = build, + super(builder); final void Function(Route, Route?)? _onPush; final void Function(Route, Route)? _onPop; diff --git a/packages/flame/test/components/router_component_test.dart b/packages/flame/test/components/router_component_test.dart index b3f334653..88685eea8 100644 --- a/packages/flame/test/components/router_component_test.dart +++ b/packages/flame/test/components/router_component_test.dart @@ -100,12 +100,12 @@ void main() { expect( router.routes.values.whereType<_TestRoute>().every( - (e) => - e.onPopTimes == 0 && - e.didPopTimes == 0 && - (e.name == initialRouteName || - (e.onPushTimes == 0 && e.didPushTimes == 0)), - ), + (e) => + e.onPopTimes == 0 && + e.didPopTimes == 0 && + (e.name == initialRouteName || + (e.onPushTimes == 0 && e.didPushTimes == 0)), + ), isTrue, ); diff --git a/packages/flame/test/components/spawn_component_test.dart b/packages/flame/test/components/spawn_component_test.dart index 40fbc8eb3..17baadc70 100644 --- a/packages/flame/test/components/spawn_component_test.dart +++ b/packages/flame/test/components/spawn_component_test.dart @@ -35,9 +35,9 @@ void main() { game.update(random.nextDouble()); } expect( - world.children - .query() - .every((c) => shape.containsPoint(c.position)), + world.children.query().every( + (c) => shape.containsPoint(c.position), + ), isTrue, ); }); @@ -51,8 +51,11 @@ void main() { size: Vector2.all(200), ); final spawn = SpawnComponent( - multiFactory: (_) => - [PositionComponent(), PositionComponent(), PositionComponent()], + multiFactory: (_) => [ + PositionComponent(), + PositionComponent(), + PositionComponent(), + ], period: 1, area: shape, random: random, @@ -72,9 +75,9 @@ void main() { game.update(random.nextDouble()); } expect( - world.children - .query() - .every((c) => shape.containsPoint(c.position)), + world.children.query().every( + (c) => shape.containsPoint(c.position), + ), isTrue, ); }, @@ -105,9 +108,9 @@ void main() { game.update(random.nextDouble()); } expect( - world.children - .query() - .every((c) => shape.containsPoint(c.position)), + world.children.query().every( + (c) => shape.containsPoint(c.position), + ), isTrue, ); }); @@ -143,9 +146,9 @@ void main() { game.update(random.nextDouble()); } expect( - world.children - .query() - .every((c) => shape.containsPoint(c.position)), + world.children.query().every( + (c) => shape.containsPoint(c.position), + ), isTrue, ); }); @@ -173,9 +176,9 @@ void main() { game.update(random.nextDouble()); } expect( - world.children - .query() - .every((c) => c.position == Vector2.all(1000)), + world.children.query().every( + (c) => c.position == Vector2.all(1000), + ), isTrue, ); }); @@ -207,9 +210,9 @@ void main() { game.update(random.nextDouble()); } expect( - world.children - .query() - .every((c) => c.position == Vector2.all(1000)), + world.children.query().every( + (c) => c.position == Vector2.all(1000), + ), isTrue, ); }); @@ -293,8 +296,9 @@ void main() { }, ); - testWithFlameGame('Spawns components within irregular period', - (game) async { + testWithFlameGame('Spawns components within irregular period', ( + game, + ) async { final random = Random(0); // The first two periods will be ~4.3 and ~3.85 final spawn = SpawnComponent.periodRange( @@ -424,8 +428,8 @@ void main() { expect(target.children.whereType(), hasLength(1)); expect( target.children.query().every( - (c) => target.toAbsoluteRect().containsPoint(c.position), - ), + (c) => target.toAbsoluteRect().containsPoint(c.position), + ), isTrue, ); @@ -434,8 +438,8 @@ void main() { expect(target.children.whereType(), hasLength(2)); expect( target.children.query().every( - (c) => target.toAbsoluteRect().containsPoint(c.position), - ), + (c) => target.toAbsoluteRect().containsPoint(c.position), + ), isTrue, ); }, @@ -465,8 +469,8 @@ void main() { expect(target.children.whereType(), hasLength(3)); expect( target.children.query().every( - (c) => target.toAbsoluteRect().containsPoint(c.position), - ), + (c) => target.toAbsoluteRect().containsPoint(c.position), + ), isTrue, ); @@ -475,8 +479,8 @@ void main() { expect(target.children.whereType(), hasLength(6)); expect( target.children.query().every( - (c) => target.toAbsoluteRect().containsPoint(c.position), - ), + (c) => target.toAbsoluteRect().containsPoint(c.position), + ), isTrue, ); }, @@ -503,8 +507,8 @@ void main() { expect(target.children.whereType(), hasLength(1)); expect( target.children.query().every( - (c) => c.position == Vector2(100, 100), - ), + (c) => c.position == Vector2(100, 100), + ), isTrue, ); @@ -513,8 +517,8 @@ void main() { expect(target.children.whereType(), hasLength(2)); expect( target.children.query().every( - (c) => c.position == Vector2(100, 100), - ), + (c) => c.position == Vector2(100, 100), + ), isTrue, ); }, diff --git a/packages/flame/test/components/sprite_animation_group_component_test.dart b/packages/flame/test/components/sprite_animation_group_component_test.dart index 3e2f58040..f94f5985e 100644 --- a/packages/flame/test/components/sprite_animation_group_component_test.dart +++ b/packages/flame/test/components/sprite_animation_group_component_test.dart @@ -58,8 +58,9 @@ Future main() async { }); group('SpriteAnimationGroupComponent.shouldRemove', () { - testWithFlameGame('removeOnFinish is true and there is no any state yet', - (game) async { + testWithFlameGame('removeOnFinish is true and there is no any state yet', ( + game, + ) async { final animation = SpriteAnimation.spriteList( [ Sprite(image), @@ -116,97 +117,100 @@ Future main() async { ); testWithFlameGame( - 'removeOnFinish is true and current animation#loop is true', - (game) async { - final animation = SpriteAnimation.spriteList( - [ - Sprite(image), - Sprite(image), - ], - stepTime: 1, - // ignore: avoid_redundant_argument_values - loop: true, - ); - final component = SpriteAnimationGroupComponent<_AnimationState>( - animations: {_AnimationState.idle: animation}, - removeOnFinish: {_AnimationState.idle: true}, - current: _AnimationState.idle, - ); + 'removeOnFinish is true and current animation#loop is true', + (game) async { + final animation = SpriteAnimation.spriteList( + [ + Sprite(image), + Sprite(image), + ], + stepTime: 1, + // ignore: avoid_redundant_argument_values + loop: true, + ); + final component = SpriteAnimationGroupComponent<_AnimationState>( + animations: {_AnimationState.idle: animation}, + removeOnFinish: {_AnimationState.idle: true}, + current: _AnimationState.idle, + ); - final world = game.world; - await world.ensureAdd(component); - expect(component.parent, world); - expect(world.children.length, 1); + final world = game.world; + await world.ensureAdd(component); + expect(component.parent, world); + expect(world.children.length, 1); - game.update(2); - expect(component.parent, world); + game.update(2); + expect(component.parent, world); - // runs a cycle to remove the component, but failed - game.update(0.1); - expect(world.children.length, 1); - }); + // runs a cycle to remove the component, but failed + game.update(0.1); + expect(world.children.length, 1); + }, + ); testWithFlameGame( - 'removeOnFinish is false and current animation#loop is false', - (game) async { - final animation = SpriteAnimation.spriteList( - [ - Sprite(image), - Sprite(image), - ], - stepTime: 1, - loop: false, - ); - final component = SpriteAnimationGroupComponent<_AnimationState>( - animations: {_AnimationState.idle: animation}, - current: _AnimationState.idle, - // when omitted, removeOnFinish is false for all states - ); + 'removeOnFinish is false and current animation#loop is false', + (game) async { + final animation = SpriteAnimation.spriteList( + [ + Sprite(image), + Sprite(image), + ], + stepTime: 1, + loop: false, + ); + final component = SpriteAnimationGroupComponent<_AnimationState>( + animations: {_AnimationState.idle: animation}, + current: _AnimationState.idle, + // when omitted, removeOnFinish is false for all states + ); - final world = game.world; - await world.ensureAdd(component); - expect(component.parent, world); - expect(world.children.length, 1); + final world = game.world; + await world.ensureAdd(component); + expect(component.parent, world); + expect(world.children.length, 1); - game.update(2); - expect(component.parent, world); + game.update(2); + expect(component.parent, world); - // runs a cycle to remove the component, but failed - game.update(0.1); - expect(world.children.length, 1); - }); + // runs a cycle to remove the component, but failed + game.update(0.1); + expect(world.children.length, 1); + }, + ); testWithFlameGame( - 'removeOnFinish is false and current animation#loop is true', - (game) async { - final animation = SpriteAnimation.spriteList( - [ - Sprite(image), - Sprite(image), - ], - stepTime: 1, - // ignore: avoid_redundant_argument_values - loop: true, - ); - final component = SpriteAnimationGroupComponent<_AnimationState>( - animations: {_AnimationState.idle: animation}, - // when omitted, removeOnFinish is false for all states - current: _AnimationState.idle, - ); + 'removeOnFinish is false and current animation#loop is true', + (game) async { + final animation = SpriteAnimation.spriteList( + [ + Sprite(image), + Sprite(image), + ], + stepTime: 1, + // ignore: avoid_redundant_argument_values + loop: true, + ); + final component = SpriteAnimationGroupComponent<_AnimationState>( + animations: {_AnimationState.idle: animation}, + // when omitted, removeOnFinish is false for all states + current: _AnimationState.idle, + ); - final world = game.world; - await world.ensureAdd(component); + final world = game.world; + await world.ensureAdd(component); - expect(component.parent, world); - expect(world.children.length, 1); + expect(component.parent, world); + expect(world.children.length, 1); - game.update(2); - expect(component.parent, world); + game.update(2); + expect(component.parent, world); - // runs a cycle to remove the component, but failed - game.update(0.1); - expect(world.children.length, 1); - }); + // runs a cycle to remove the component, but failed + game.update(0.1); + expect(world.children.length, 1); + }, + ); }); group('SpriteAnimationGroupComponent.currentAnimationNotifier', () { diff --git a/packages/flame/test/components/text_box_component_test.dart b/packages/flame/test/components/text_box_component_test.dart index 9b8176311..e3df4d79b 100644 --- a/packages/flame/test/components/text_box_component_test.dart +++ b/packages/flame/test/components/text_box_component_test.dart @@ -111,12 +111,11 @@ void main() { game.render(canvas); // this should render the cache expect( canvas, - MockCanvas(mode: AssertionMode.containsAnyOrder) - ..drawImage( - null, - Offset.zero, - BasicPalette.white.paint(), - ), + MockCanvas(mode: AssertionMode.containsAnyOrder)..drawImage( + null, + Offset.zero, + BasicPalette.white.paint(), + ), ); }); @@ -156,28 +155,30 @@ void main() { ); testWithFlameGame( - 'TextBoxComponent notifies if a new line is added and requires space', - (game) async { - var lineSize = 0.0; - final textBoxComponent = TextBoxComponent( - size: Vector2(50, 50), - text: '''This + 'TextBoxComponent notifies if a new line is added and requires space', + (game) async { + var lineSize = 0.0; + final textBoxComponent = TextBoxComponent( + size: Vector2(50, 50), + text: '''This test has five lines.''', - ); - expect(textBoxComponent.newLinePositionNotifier.value, equals(0)); + ); + expect(textBoxComponent.newLinePositionNotifier.value, equals(0)); - textBoxComponent.newLinePositionNotifier.addListener(() { - lineSize += textBoxComponent.newLinePositionNotifier.value; - }); - await game.ensureAdd(textBoxComponent); - expect(lineSize, greaterThan(0)); - }); + textBoxComponent.newLinePositionNotifier.addListener(() { + lineSize += textBoxComponent.newLinePositionNotifier.value; + }); + await game.ensureAdd(textBoxComponent); + expect(lineSize, greaterThan(0)); + }, + ); - testWithFlameGame('TextBoxComponent skips to the end of text', - (game) async { + testWithFlameGame('TextBoxComponent skips to the end of text', ( + game, + ) async { final textBoxComponent1 = TextBoxComponent( text: 'aaa', boxConfig: const TextBoxConfig(timePerChar: 1.0), @@ -229,21 +230,24 @@ lines.''', ), _FramedTextBox( // cSpell:ignore runn'st (old english) - text: 'To move is to stir, and to be valiant is to stand. ' + text: + 'To move is to stir, and to be valiant is to stand. ' "Therefore, if thou art moved, thou runn'st away.", position: Vector2(10, 370), size: Vector2(390, 220), align: Anchor.bottomRight, ), _FramedTextBox( - text: 'A dog of that house shall move me to stand. I will take ' + text: + 'A dog of that house shall move me to stand. I will take ' 'the wall of any man or maid of Montague‘s.', position: Vector2(410, 10), size: Vector2(380, 300), align: Anchor.center, ), _FramedTextBox( - text: 'That shows thee a weak slave; for the weakest goes to the ' + text: + 'That shows thee a weak slave; for the weakest goes to the ' 'wall.', position: Vector2(410, 320) + Vector2(380, 270), size: Vector2(380, 270), @@ -279,8 +283,8 @@ class _FramedTextBox extends TextBoxComponent { super.size, super.anchor, }) : super( - textRenderer: DebugTextRenderer(fontSize: 22), - ); + textRenderer: DebugTextRenderer(fontSize: 22), + ); final Paint _borderPaint = Paint() ..style = PaintingStyle.stroke diff --git a/packages/flame/test/components/timer_component_test.dart b/packages/flame/test/components/timer_component_test.dart index 00e3bafc5..1ee93954b 100644 --- a/packages/flame/test/components/timer_component_test.dart +++ b/packages/flame/test/components/timer_component_test.dart @@ -6,11 +6,11 @@ class _MyTimerComponent extends TimerComponent { int count = 0; _MyTimerComponent() - : super( - period: 1, - repeat: true, - removeOnFinish: false, - ); + : super( + period: 1, + repeat: true, + removeOnFinish: false, + ); @override void onTick() { @@ -22,12 +22,12 @@ class _MyTickOnLoadTimerComponent extends TimerComponent { int count = 0; _MyTickOnLoadTimerComponent() - : super( - period: 1, - repeat: true, - removeOnFinish: false, - tickWhenLoaded: true, - ); + : super( + period: 1, + repeat: true, + removeOnFinish: false, + tickWhenLoaded: true, + ); @override void onTick() { @@ -37,11 +37,11 @@ class _MyTickOnLoadTimerComponent extends TimerComponent { class _NonRepeatingTimerComponent extends TimerComponent { _NonRepeatingTimerComponent() - : super( - period: 1, - repeat: false, - removeOnFinish: true, - ); + : super( + period: 1, + repeat: false, + removeOnFinish: true, + ); } void main() { @@ -58,8 +58,9 @@ void main() { expect(timer.count, equals(1)); }); - testWithFlameGame('never remove from the game when is repeating', - (game) async { + testWithFlameGame('never remove from the game when is repeating', ( + game, + ) async { final world = game.world; world.add(_MyTimerComponent()); await game.ready(); @@ -71,8 +72,9 @@ void main() { expect(world.children.length, equals(1)); }); - testWithFlameGame('is removed from the game when is finished', - (game) async { + testWithFlameGame('is removed from the game when is finished', ( + game, + ) async { final world = game.world; world.add(_NonRepeatingTimerComponent()); game.update(0); @@ -117,40 +119,42 @@ void main() { }, ); - testWithFlameGame('when tickCount is provided, stops after that many times', - (game) async { - var x = 0; - final timer = TimerComponent( - period: 1, - repeat: true, - tickCount: 2, - onTick: () { - x++; - }, - ); - game.add(timer); - await game.ready(); - game.update(0); + testWithFlameGame( + 'when tickCount is provided, stops after that many times', + (game) async { + var x = 0; + final timer = TimerComponent( + period: 1, + repeat: true, + tickCount: 2, + onTick: () { + x++; + }, + ); + game.add(timer); + await game.ready(); + game.update(0); - game.update(1.2); + game.update(1.2); - game.update(0); - expect(x, equals(1)); + game.update(0); + expect(x, equals(1)); - game.update(1.2); + game.update(1.2); - game.update(0); - expect(x, equals(2)); + game.update(0); + expect(x, equals(2)); - game.update(1.2); + game.update(1.2); - game.update(0); - expect(x, equals(2)); + game.update(0); + expect(x, equals(2)); - await game.ready(); + await game.ready(); - expect(timer.timer.isRunning(), isFalse); - expect(timer.isRemoved, isFalse); - }); + expect(timer.timer.isRunning(), isFalse); + expect(timer.isRemoved, isFalse); + }, + ); }); } diff --git a/packages/flame/test/components/toogle_button_component_test.dart b/packages/flame/test/components/toogle_button_component_test.dart index 6624f8383..2930e63a2 100644 --- a/packages/flame/test/components/toogle_button_component_test.dart +++ b/packages/flame/test/components/toogle_button_component_test.dart @@ -74,8 +74,9 @@ void main() { size: componentSize, ), ); - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; @@ -116,8 +117,9 @@ void main() { ), ); button.isDisabled = true; - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; @@ -157,8 +159,9 @@ void main() { size: componentSize, ), ); - final previousPosition = - button.positionOfAnchor(Anchor.center).toOffset(); + final previousPosition = button + .positionOfAnchor(Anchor.center) + .toOffset(); game.onGameResize(initialGameSize * 2); final tapDispatcher = game.firstChild()!; diff --git a/packages/flame/test/custom_component.dart b/packages/flame/test/custom_component.dart index 690ef3f71..0fafadce8 100644 --- a/packages/flame/test/custom_component.dart +++ b/packages/flame/test/custom_component.dart @@ -15,12 +15,12 @@ class CustomComponent extends Component { void Function(CustomComponent, Canvas)? onRender, super.priority, super.children, - }) : _onGameResize = onGameResize, - _onLoad = onLoad, - _onMount = onMount, - _onRemove = onRemove, - _onUpdate = onUpdate, - _onRender = onRender; + }) : _onGameResize = onGameResize, + _onLoad = onLoad, + _onMount = onMount, + _onRemove = onRemove, + _onUpdate = onUpdate, + _onRender = onRender; final void Function(CustomComponent, Vector2)? _onGameResize; final FutureOr Function(CustomComponent)? _onLoad; diff --git a/packages/flame/test/effects/color_effect_test.dart b/packages/flame/test/effects/color_effect_test.dart index ee8db5358..1ddbadbf2 100644 --- a/packages/flame/test/effects/color_effect_test.dart +++ b/packages/flame/test/effects/color_effect_test.dart @@ -28,9 +28,11 @@ void main() { game.update(0.5); expect( component.paint.colorFilter.toString(), - equals('ColorFilter.mode(Color(alpha: 0.5000, red: 0.9569, green: ' - '0.2627, blue: 0.2118, colorSpace: ColorSpace.sRGB), ' - 'BlendMode.srcATop)'), + equals( + 'ColorFilter.mode(Color(alpha: 0.5000, red: 0.9569, green: ' + '0.2627, blue: 0.2118, colorSpace: ColorSpace.sRGB), ' + 'BlendMode.srcATop)', + ), ); }); diff --git a/packages/flame/test/effects/controllers/mixins/has_single_child_effect_controller_test.dart b/packages/flame/test/effects/controllers/mixins/has_single_child_effect_controller_test.dart index dd7e9c793..8218e3e1e 100644 --- a/packages/flame/test/effects/controllers/mixins/has_single_child_effect_controller_test.dart +++ b/packages/flame/test/effects/controllers/mixins/has_single_child_effect_controller_test.dart @@ -11,13 +11,15 @@ void main() { expect(controller.child, equals(childController)); }); - test('setToStart should call setToStart on the child effect controller', - () { - final childController = _MockEffectController(); - final controller = _TestEffectController(childController); - controller.setToStart(); - verify(childController.setToStart).called(1); - }); + test( + 'setToStart should call setToStart on the child effect controller', + () { + final childController = _MockEffectController(); + final controller = _TestEffectController(childController); + controller.setToStart(); + verify(childController.setToStart).called(1); + }, + ); test('setToEnd should call setToEnd on the child effect controller', () { final childController = _MockEffectController(); diff --git a/packages/flame/test/effects/controllers/sine_effect_controller_test.dart b/packages/flame/test/effects/controllers/sine_effect_controller_test.dart index 3c9c2cac3..97d4f7915 100644 --- a/packages/flame/test/effects/controllers/sine_effect_controller_test.dart +++ b/packages/flame/test/effects/controllers/sine_effect_controller_test.dart @@ -17,8 +17,10 @@ void main() { test('progression', () { final ec = SineEffectController(period: 3); - final expectedProgress = - List.generate(101, (i) => sin(i * 0.01 * 2 * pi)); + final expectedProgress = List.generate( + 101, + (i) => sin(i * 0.01 * 2 * pi), + ); for (final p in expectedProgress) { expect(ec.progress, closeTo(p, 2e-14)); ec.advance(0.01 * 3); diff --git a/packages/flame/test/effects/controllers/speed_effect_controller_test.dart b/packages/flame/test/effects/controllers/speed_effect_controller_test.dart index 1d2cfd673..5a17cd044 100644 --- a/packages/flame/test/effects/controllers/speed_effect_controller_test.dart +++ b/packages/flame/test/effects/controllers/speed_effect_controller_test.dart @@ -43,8 +43,10 @@ void main() { group('applied to various effects', () { testWithFlameGame('speed on MoveEffect', (game) async { - final effect = - MoveEffect.to(Vector2(8, 12), EffectController(speed: 1)); + final effect = MoveEffect.to( + Vector2(8, 12), + EffectController(speed: 1), + ); final component = PositionComponent(position: Vector2(5, 8)); component.add(effect); await game.ensureAdd(component); diff --git a/packages/flame/test/effects/move_along_path_effect_test.dart b/packages/flame/test/effects/move_along_path_effect_test.dart index d5f1378be..04e4399d0 100644 --- a/packages/flame/test/effects/move_along_path_effect_test.dart +++ b/packages/flame/test/effects/move_along_path_effect_test.dart @@ -224,8 +224,9 @@ void main() { } }); - testWithFlameGame('non-absolute oriented path with nativeAngle', - (game) async { + testWithFlameGame('non-absolute oriented path with nativeAngle', ( + game, + ) async { final component = PositionComponent( position: Vector2.zero(), angle: -30.5, diff --git a/packages/flame/test/effects/opacity_effect_test.dart b/packages/flame/test/effects/opacity_effect_test.dart index d82b1591b..d809a2e95 100644 --- a/packages/flame/test/effects/opacity_effect_test.dart +++ b/packages/flame/test/effects/opacity_effect_test.dart @@ -160,8 +160,9 @@ void main() { // Repeat the test 3 times for (var i = 0; i < 3; ++i) { - await component - .add(OpacityEffect.fadeOut(EffectController(duration: 3))); + await component.add( + OpacityEffect.fadeOut(EffectController(duration: 3)), + ); var timeElapsed = 0.0; while (timeElapsed < 3) { @@ -236,8 +237,9 @@ void main() { ); await game.ensureAdd(component); - await component - .add(OpacityEffect.fadeOut(EffectController(duration: 1))); + await component.add( + OpacityEffect.fadeOut(EffectController(duration: 1)), + ); game.update(1); @@ -260,20 +262,17 @@ void main() { final component = _CustomPaintComponent<_PaintTypes>( { _PaintTypes.paint1: BasicPalette.red.paint() - ..color = BasicPalette.green - .paint() - .color - .withValues(alpha: redInitialOpacity), + ..color = BasicPalette.green.paint().color.withValues( + alpha: redInitialOpacity, + ), _PaintTypes.paint2: BasicPalette.green.paint() - ..color = BasicPalette.green - .paint() - .color - .withValues(alpha: greenInitialOpacity), + ..color = BasicPalette.green.paint().color.withValues( + alpha: greenInitialOpacity, + ), _PaintTypes.paint3: BasicPalette.blue.paint() - ..color = BasicPalette.blue - .paint() - .color - .withValues(alpha: blueInitialOpacity), + ..color = BasicPalette.blue.paint().color.withValues( + alpha: blueInitialOpacity, + ), }, ); await game.ensureAdd(component); @@ -314,20 +313,17 @@ void main() { final component = _CustomPaintComponent<_PaintTypes>( { _PaintTypes.paint1: BasicPalette.red.paint() - ..color = BasicPalette.green - .paint() - .color - .withValues(alpha: redInitialOpacity), + ..color = BasicPalette.green.paint().color.withValues( + alpha: redInitialOpacity, + ), _PaintTypes.paint2: BasicPalette.green.paint() - ..color = BasicPalette.green - .paint() - .color - .withValues(alpha: greenInitialOpacity), + ..color = BasicPalette.green.paint().color.withValues( + alpha: greenInitialOpacity, + ), _PaintTypes.paint3: BasicPalette.blue.paint() - ..color = BasicPalette.blue - .paint() - .color - .withValues(alpha: blueInitialOpacity), + ..color = BasicPalette.blue.paint().color.withValues( + alpha: blueInitialOpacity, + ), }, ); await game.ensureAdd(component); diff --git a/packages/flame/test/events/component_mixins/drag_callbacks_test.dart b/packages/flame/test/events/component_mixins/drag_callbacks_test.dart index 5f47fb526..edc7146c2 100644 --- a/packages/flame/test/events/component_mixins/drag_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/drag_callbacks_test.dart @@ -27,12 +27,12 @@ void main() { expect(game.children.whereType().length, 1); game.firstChild()!.onDragStart( - createDragStartEvents( - game: game, - localPosition: const Offset(12, 12), - globalPosition: const Offset(12, 12), - ), - ); + createDragStartEvents( + game: game, + localPosition: const Offset(12, 12), + globalPosition: const Offset(12, 12), + ), + ); expect(component.containsLocalPoint(Vector2(10, 10)), false); }); @@ -451,9 +451,9 @@ class _DragWithCallbacksComponent extends PositionComponent with DragCallbacks { void Function(DragEndEvent)? onDragEnd, super.position, super.size, - }) : _onDragStart = onDragStart, - _onDragUpdate = onDragUpdate, - _onDragEnd = onDragEnd; + }) : _onDragStart = onDragStart, + _onDragUpdate = onDragUpdate, + _onDragEnd = onDragEnd; final void Function(DragStartEvent)? _onDragStart; final void Function(DragUpdateEvent)? _onDragUpdate; diff --git a/packages/flame/test/events/component_mixins/hover_callbacks_test.dart b/packages/flame/test/events/component_mixins/hover_callbacks_test.dart index f1fa0e5bc..061b3bc77 100644 --- a/packages/flame/test/events/component_mixins/hover_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/hover_callbacks_test.dart @@ -7,13 +7,14 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('HoverCallbacks', () { testWithFlameGame( - 'make sure HoverCallbacks components can be added to a FlameGame', - (game) async { - await game.ensureAdd(_HoverCallbacksComponent()); - await game.ready(); + 'make sure HoverCallbacks components can be added to a FlameGame', + (game) async { + await game.ensureAdd(_HoverCallbacksComponent()); + await game.ready(); - _hasDispatcher(game); - }); + _hasDispatcher(game); + }, + ); testWithFlameGame('receive hover events', (game) async { final component = _HoverCallbacksComponent( @@ -57,11 +58,11 @@ void main() { void _mouseEvent(FlameGame game, Vector2 position) { game.firstChild()!.onMouseMove( - createMouseMoveEvent( - game: game, - position: position, - ), - ); + createMouseMoveEvent( + game: game, + position: position, + ), + ); } void _hasDispatcher(FlameGame game) { diff --git a/packages/flame/test/events/component_mixins/ignore_events_test.dart b/packages/flame/test/events/component_mixins/ignore_events_test.dart index d7242bebf..cee792978 100644 --- a/packages/flame/test/events/component_mixins/ignore_events_test.dart +++ b/packages/flame/test/events/component_mixins/ignore_events_test.dart @@ -139,5 +139,5 @@ mixin _TapCounter on TapCallbacks { class _IgnoreTapCallbacksComponent extends PositionComponent with TapCallbacks, _TapCounter, IgnoreEvents { _IgnoreTapCallbacksComponent({super.position, super.children}) - : super(size: Vector2.all(10)); + : super(size: Vector2.all(10)); } diff --git a/packages/flame/test/events/component_mixins/pointer_move_callbacks_test.dart b/packages/flame/test/events/component_mixins/pointer_move_callbacks_test.dart index 816e28f28..681c28816 100644 --- a/packages/flame/test/events/component_mixins/pointer_move_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/pointer_move_callbacks_test.dart @@ -7,13 +7,14 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('PointerMoveCallbacks', () { testWithFlameGame( - 'make sure PointerMoveCallbacks components can be added to a FlameGame', - (game) async { - await game.ensureAdd(_PointerMoveCallbacksComponent()); - await game.ready(); + 'make sure PointerMoveCallbacks components can be added to a FlameGame', + (game) async { + await game.ensureAdd(_PointerMoveCallbacksComponent()); + await game.ready(); - _hasDispatcher(game); - }); + _hasDispatcher(game); + }, + ); testWithFlameGame('receive pointer move events on component', (game) async { final c1 = _PointerMoveCallbacksComponent( @@ -72,11 +73,11 @@ void main() { void _mouseEvent(FlameGame game, Vector2 position) { game.firstChild()!.onMouseMove( - createMouseMoveEvent( - game: game, - position: position, - ), - ); + createMouseMoveEvent( + game: game, + position: position, + ), + ); } void _hasDispatcher(FlameGame game) { diff --git a/packages/flame/test/events/component_mixins/tap_callbacks_test.dart b/packages/flame/test/events/component_mixins/tap_callbacks_test.dart index e1176b570..6c87562d6 100644 --- a/packages/flame/test/events/component_mixins/tap_callbacks_test.dart +++ b/packages/flame/test/events/component_mixins/tap_callbacks_test.dart @@ -7,12 +7,13 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('TapCallbacks', () { testWithFlameGame( - 'make sure TapCallback components can be added to a FlameGame', - (game) async { - await game.ensureAdd(_TapCallbacksComponent()); - await game.ready(); - expect(game.children.toList()[2], isA()); - }); + 'make sure TapCallback components can be added to a FlameGame', + (game) async { + await game.ensureAdd(_TapCallbacksComponent()); + await game.ready(); + expect(game.children.toList()[2], isA()); + }, + ); testWithFlameGame('tap event start', (game) async { final component = _TapCallbacksComponent() @@ -25,12 +26,12 @@ void main() { expect(game.children.whereType().length, equals(1)); game.firstChild()!.onTapDown( - createTapDownEvents( - game: game, - localPosition: const Offset(12, 12), - globalPosition: const Offset(12, 12), - ), - ); + createTapDownEvents( + game: game, + localPosition: const Offset(12, 12), + globalPosition: const Offset(12, 12), + ), + ); expect(component.containsLocalPoint(Vector2(10, 10)), false); }); @@ -449,10 +450,10 @@ class _TapWithCallbacksComponent extends PositionComponent with TapCallbacks { void Function(TapDownEvent)? onLongTapDown, void Function(TapUpEvent)? onTapUp, void Function(TapCancelEvent)? onTapCancel, - }) : _onTapDown = onTapDown, - _onLongTapDown = onLongTapDown, - _onTapUp = onTapUp, - _onTapCancel = onTapCancel; + }) : _onTapDown = onTapDown, + _onLongTapDown = onLongTapDown, + _onTapUp = onTapUp, + _onTapCancel = onTapCancel; final void Function(TapDownEvent)? _onTapDown; final void Function(TapDownEvent)? _onLongTapDown; diff --git a/packages/flame/test/events/game_mixins/multi_touch_drag_detector_test.dart b/packages/flame/test/events/game_mixins/multi_touch_drag_detector_test.dart index 8b3e675e4..31ac3c3a3 100644 --- a/packages/flame/test/events/game_mixins/multi_touch_drag_detector_test.dart +++ b/packages/flame/test/events/game_mixins/multi_touch_drag_detector_test.dart @@ -7,8 +7,9 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - final withMultiTouchFragDetector = - GameTester(_MultiTouchDragDetectorGame.new); + final withMultiTouchFragDetector = GameTester( + _MultiTouchDragDetectorGame.new, + ); group('MultiTouchDragDetector', () { testWidgets( diff --git a/packages/flame/test/events/game_mixins/multi_touch_tap_detector_test.dart b/packages/flame/test/events/game_mixins/multi_touch_tap_detector_test.dart index 06508d670..a9e265a02 100644 --- a/packages/flame/test/events/game_mixins/multi_touch_tap_detector_test.dart +++ b/packages/flame/test/events/game_mixins/multi_touch_tap_detector_test.dart @@ -6,8 +6,9 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - final withMultiTouchTapDetector = - GameTester(_GameWithMultiTouchTapDetector.new); + final withMultiTouchTapDetector = GameTester( + _GameWithMultiTouchTapDetector.new, + ); group('MultiTouchTapDetector', () { testWidgets( diff --git a/packages/flame/test/experimental/linear_layout_component_test.dart b/packages/flame/test/experimental/linear_layout_component_test.dart index 18a2de151..8178d7a75 100644 --- a/packages/flame/test/experimental/linear_layout_component_test.dart +++ b/packages/flame/test/experimental/linear_layout_component_test.dart @@ -74,8 +74,11 @@ void main() { ); await game.ensureAdd(layoutComponent); final mainAxis = direction.mainAxis; - final occupiedSpace = - [circle.size, rectangle.size, text.size].map(mainAxis).sum; + final occupiedSpace = [ + circle.size, + rectangle.size, + text.size, + ].map(mainAxis).sum; const gapSpace = gap * 2; final centerOffset = (mainAxis(layoutComponentSize) - occupiedSpace - gapSpace) / 2; @@ -102,8 +105,11 @@ void main() { ); await game.ensureAdd(layoutComponent); final mainAxis = direction.mainAxis; - final occupiedSpace = - [circle.size, rectangle.size, text.size].map(mainAxis).sum; + final occupiedSpace = [ + circle.size, + rectangle.size, + text.size, + ].map(mainAxis).sum; final expectedGap = (mainAxis(layoutComponentSize) - occupiedSpace) / 2; expect(layoutComponent.gap, expectedGap); @@ -132,8 +138,11 @@ void main() { ); await game.ensureAdd(layoutComponent); final mainAxis = direction.mainAxis; - final occupiedSpace = - [circle.size, rectangle.size, text.size].map(mainAxis).sum; + final occupiedSpace = [ + circle.size, + rectangle.size, + text.size, + ].map(mainAxis).sum; final expectedGap = (mainAxis(layoutComponentSize) - occupiedSpace) / 3; expect(layoutComponent.gap, expectedGap); @@ -168,8 +177,11 @@ void main() { ); await game.ensureAdd(layoutComponent); final mainAxis = direction.mainAxis; - final occupiedSpace = - [circle.size, rectangle.size, text.size].map(mainAxis).sum; + final occupiedSpace = [ + circle.size, + rectangle.size, + text.size, + ].map(mainAxis).sum; final expectedGap = (mainAxis(layoutComponentSize) - occupiedSpace) / 4; expect(layoutComponent.gap, expectedGap); @@ -293,34 +305,46 @@ void main() { }, 'size=null respects supported crossAxisAlignments': (game, direction) async { - final circle = CircleComponent(radius: 20); - final rectangle = RectangleComponent(size: Vector2(100, 50)); - final text = TextComponent(text: 'testing'); - final layoutComponent = LinearLayoutComponent.fromDirection( - direction, - children: [circle, rectangle, text], - crossAxisAlignment: CrossAxisAlignment.center, - ); - await game.ensureAdd(layoutComponent); - expect(layoutComponent.crossAxisAlignment, CrossAxisAlignment.center); - layoutComponent.crossAxisAlignment = CrossAxisAlignment.end; - expect(layoutComponent.crossAxisAlignment, CrossAxisAlignment.end); - layoutComponent.crossAxisAlignment = CrossAxisAlignment.start; - expect(layoutComponent.crossAxisAlignment, CrossAxisAlignment.start); - }, + final circle = CircleComponent(radius: 20); + final rectangle = RectangleComponent(size: Vector2(100, 50)); + final text = TextComponent(text: 'testing'); + final layoutComponent = LinearLayoutComponent.fromDirection( + direction, + children: [circle, rectangle, text], + crossAxisAlignment: CrossAxisAlignment.center, + ); + await game.ensureAdd(layoutComponent); + expect( + layoutComponent.crossAxisAlignment, + CrossAxisAlignment.center, + ); + layoutComponent.crossAxisAlignment = CrossAxisAlignment.end; + expect( + layoutComponent.crossAxisAlignment, + CrossAxisAlignment.end, + ); + layoutComponent.crossAxisAlignment = CrossAxisAlignment.start; + expect( + layoutComponent.crossAxisAlignment, + CrossAxisAlignment.start, + ); + }, "size=null doesn't respect CrossAxisAlignment.stretch": (game, direction) async { - final circle = CircleComponent(radius: 20); - final rectangle = RectangleComponent(size: Vector2(100, 50)); - final text = TextComponent(text: 'testing'); - final layoutComponent = LinearLayoutComponent.fromDirection( - direction, - children: [circle, rectangle, text], - crossAxisAlignment: CrossAxisAlignment.stretch, - ); - await game.ensureAdd(layoutComponent); - expect(layoutComponent.crossAxisAlignment, CrossAxisAlignment.start); - }, + final circle = CircleComponent(radius: 20); + final rectangle = RectangleComponent(size: Vector2(100, 50)); + final text = TextComponent(text: 'testing'); + final layoutComponent = LinearLayoutComponent.fromDirection( + direction, + children: [circle, rectangle, text], + crossAxisAlignment: CrossAxisAlignment.stretch, + ); + await game.ensureAdd(layoutComponent); + expect( + layoutComponent.crossAxisAlignment, + CrossAxisAlignment.start, + ); + }, }); }); group('children', () { @@ -328,28 +352,27 @@ void main() { { 'size responds when children are added and then resized': (game, direction) async { - final circle = CircleComponent(radius: 20); - final rectangle2 = RectangleComponent(size: Vector2(100, 50)); - // final rectangle2 = RectangleComponent(size: Vector2(200, 70)); - final layoutComponent = LinearLayoutComponent.fromDirection( - direction, - crossAxisAlignment: CrossAxisAlignment.stretch, - ); - await game.ensureAdd(layoutComponent); - expect(layoutComponent.size, Vector2.zero()); - await layoutComponent.ensureAddAll([ - circle, - rectangle2, - ]); - rectangle2.size = Vector2(200, 70); - expect( - layoutComponent.size, - switch (direction) { - Direction.horizontal => Vector2(40 + 200, 70), - Direction.vertical => Vector2(200, 70 + 40), + final circle = CircleComponent(radius: 20); + final rectangle2 = RectangleComponent(size: Vector2(100, 50)); + final layoutComponent = LinearLayoutComponent.fromDirection( + direction, + crossAxisAlignment: CrossAxisAlignment.stretch, + ); + await game.ensureAdd(layoutComponent); + expect(layoutComponent.size, Vector2.zero()); + await layoutComponent.ensureAddAll([ + circle, + rectangle2, + ]); + rectangle2.size = Vector2(200, 70); + expect( + layoutComponent.size, + switch (direction) { + Direction.horizontal => Vector2(40 + 200, 70), + Direction.vertical => Vector2(200, 70 + 40), + }, + ); }, - ); - }, }, ); }); diff --git a/packages/flame/test/experimental/padding_component_test.dart b/packages/flame/test/experimental/padding_component_test.dart index 14b4cacea..789d58262 100644 --- a/packages/flame/test/experimental/padding_component_test.dart +++ b/packages/flame/test/experimental/padding_component_test.dart @@ -27,8 +27,9 @@ void main() { padding.topLeft.toVector2(), ); }); - testWithFlameGame('properly sizes self and positions after child is set', - (game) async { + testWithFlameGame('properly sizes self and positions after child is set', ( + game, + ) async { const padding = EdgeInsets.all(16); final circle = CircleComponent(radius: 20); final paddingComponent = PaddingComponent( @@ -56,31 +57,33 @@ void main() { padding.topLeft.toVector2(), ); }); - testWithFlameGame('properly sizes self and positions after padding is set', - (game) async { - final circle = CircleComponent(radius: 20); - final paddingComponent = PaddingComponent(child: circle); - await game.ensureAdd(paddingComponent); - expect( - paddingComponent.size, - circle.size, - ); - const padding = EdgeInsets.symmetric( - vertical: 16, - horizontal: 24, - ); - paddingComponent.padding = padding; - expect( - paddingComponent.size, - Vector2( - circle.size.x + padding.horizontal, - circle.size.y + padding.vertical, - ), - ); - expect( - paddingComponent.child?.topLeftPosition, - padding.topLeft.toVector2(), - ); - }); + testWithFlameGame( + 'properly sizes self and positions after padding is set', + (game) async { + final circle = CircleComponent(radius: 20); + final paddingComponent = PaddingComponent(child: circle); + await game.ensureAdd(paddingComponent); + expect( + paddingComponent.size, + circle.size, + ); + const padding = EdgeInsets.symmetric( + vertical: 16, + horizontal: 24, + ); + paddingComponent.padding = padding; + expect( + paddingComponent.size, + Vector2( + circle.size.x + padding.horizontal, + circle.size.y + padding.vertical, + ), + ); + expect( + paddingComponent.child?.topLeftPosition, + padding.topLeft.toVector2(), + ); + }, + ); }); } diff --git a/packages/flame/test/extensions/canvas_test.dart b/packages/flame/test/extensions/canvas_test.dart index 6168b0787..5b406b5e2 100644 --- a/packages/flame/test/extensions/canvas_test.dart +++ b/packages/flame/test/extensions/canvas_test.dart @@ -42,8 +42,7 @@ void main() { verify(canvas.restore).called(1); }); - test( - 'renderRotated saves, translates, rotates, draws, translatesBack' + test('renderRotated saves, translates, rotates, draws, translatesBack' ' and then restores', () { final canvas = _MocktailCanvas(); when(canvas.save).thenReturn(null); diff --git a/packages/flame/test/extensions/matrix4_test.dart b/packages/flame/test/extensions/matrix4_test.dart index 7f33c76c9..40ff58ba4 100644 --- a/packages/flame/test/extensions/matrix4_test.dart +++ b/packages/flame/test/extensions/matrix4_test.dart @@ -31,8 +31,9 @@ void main() { test('test m43', () => expect(matrix4.m43, matrix4.storage[14])); test('test m44', () => expect(matrix4.m44, matrix4.storage[15])); - testRandom('translate2 calls translate on the matrix with a vector', - (Random r) { + testRandom('translate2 calls translate on the matrix with a vector', ( + Random r, + ) { final matrix4 = _MockMatrix4(); final v = Vector2(r.nextDouble(), r.nextDouble()); matrix4.translate2(v); diff --git a/packages/flame/test/extensions/offset_test.dart b/packages/flame/test/extensions/offset_test.dart index 5687f38c1..912cf3ea9 100644 --- a/packages/flame/test/extensions/offset_test.dart +++ b/packages/flame/test/extensions/offset_test.dart @@ -22,8 +22,9 @@ void main() { ); }); - testRandom('toSize has width to offset.dx and height to offset.dy', - (Random r) { + testRandom('toSize has width to offset.dx and height to offset.dy', ( + Random r, + ) { final offset = Offset(r.nextDouble(), r.nextDouble()); final size = offset.toSize(); @@ -40,15 +41,16 @@ void main() { }); testRandom( - 'toRect has left: 0, top: 0, width: offset.dx, height: offset.dy', - (Random r) { - final offset = Offset(r.nextDouble(), r.nextDouble()); - final rect = offset.toRect(); + 'toRect has left: 0, top: 0, width: offset.dx, height: offset.dy', + (Random r) { + final offset = Offset(r.nextDouble(), r.nextDouble()); + final rect = offset.toRect(); - expect(rect.left, 0, reason: 'left should be 0 as init'); - expect(rect.top, 0, reason: 'top should be 0 as init'); - expect(rect.width, offset.dx, reason: 'width dx does not match'); - expect(rect.height, offset.dy, reason: 'height dy does not match'); - }); + expect(rect.left, 0, reason: 'left should be 0 as init'); + expect(rect.top, 0, reason: 'top should be 0 as init'); + expect(rect.width, offset.dx, reason: 'width dx does not match'); + expect(rect.height, offset.dy, reason: 'height dy does not match'); + }, + ); }); } diff --git a/packages/flame/test/extensions/paint_test.dart b/packages/flame/test/extensions/paint_test.dart index 7f5ad8f0f..1044361dd 100644 --- a/packages/flame/test/extensions/paint_test.dart +++ b/packages/flame/test/extensions/paint_test.dart @@ -40,169 +40,171 @@ void main() { }); testRandom( - 'using fromRGBHexString returns a new Paint with the right Color', - (Random r) { - // As documentation says - // valid inputs are : ccc, CCC, #ccc, #CCC, #c1c1c1, #C1C1C1, c1c1c1, - // C1C1C1 - final color = ColorExtension.random(); - final sixHexColor = - (color.r * 255).toInt().toRadixString(16).padLeft(2, '0') + - (color.g * 255).toInt().toRadixString(16).padLeft(2, '0') + - (color.b * 255).toInt().toRadixString(16).padLeft(2, '0'); + 'using fromRGBHexString returns a new Paint with the right Color', + (Random r) { + // As documentation says + // valid inputs are : ccc, CCC, #ccc, #CCC, #c1c1c1, #C1C1C1, c1c1c1, + // C1C1C1 + final color = ColorExtension.random(); + final sixHexColor = + (color.r * 255).toInt().toRadixString(16).padLeft(2, '0') + + (color.g * 255).toInt().toRadixString(16).padLeft(2, '0') + + (color.b * 255).toInt().toRadixString(16).padLeft(2, '0'); - // C1C1C1 - final sixUpperCaseColor = sixHexColor.toUpperCase(); - // c1c1c1 - final sixLowerCaseColor = sixHexColor.toLowerCase(); - // #C1C1C1 - final hashtagSixUpperCaseColor = '#$sixUpperCaseColor'; - // #c1c1c1 - final hashtagSixLowerCaseColor = '#$sixLowerCaseColor'; + // C1C1C1 + final sixUpperCaseColor = sixHexColor.toUpperCase(); + // c1c1c1 + final sixLowerCaseColor = sixHexColor.toLowerCase(); + // #C1C1C1 + final hashtagSixUpperCaseColor = '#$sixUpperCaseColor'; + // #c1c1c1 + final hashtagSixLowerCaseColor = '#$sixLowerCaseColor'; - expectColor( - PaintExtension.fromRGBHexString(hashtagSixUpperCaseColor).color, - color, - reason: 'C1C1C1 does not generates the good paint', - ); - expectColor( - PaintExtension.fromRGBHexString(sixLowerCaseColor).color, - color, - reason: 'c1c1c1 does not generates the good paint', - ); - expectColor( - PaintExtension.fromRGBHexString(hashtagSixUpperCaseColor).color, - color, - reason: '#C1C1C1 does not generates the good paint', - ); - expectColor( - PaintExtension.fromRGBHexString(hashtagSixLowerCaseColor).color, - color, - reason: '#c1c1c1 does not generates the good paint', - ); + expectColor( + PaintExtension.fromRGBHexString(hashtagSixUpperCaseColor).color, + color, + reason: 'C1C1C1 does not generates the good paint', + ); + expectColor( + PaintExtension.fromRGBHexString(sixLowerCaseColor).color, + color, + reason: 'c1c1c1 does not generates the good paint', + ); + expectColor( + PaintExtension.fromRGBHexString(hashtagSixUpperCaseColor).color, + color, + reason: '#C1C1C1 does not generates the good paint', + ); + expectColor( + PaintExtension.fromRGBHexString(hashtagSixLowerCaseColor).color, + color, + reason: '#c1c1c1 does not generates the good paint', + ); - // Let's generate a new color from only 3 digits - final threeHexColor = - (color.r ~/ 255).toRadixString(16).padLeft(1, '0')[0] + - (color.g ~/ 255).toRadixString(16).padLeft(1, '0')[0] + - (color.b ~/ 255).toRadixString(16).padLeft(1, '0')[0]; - final threeDigitsColor = ColorExtension.fromRGBHexString(threeHexColor); + // Let's generate a new color from only 3 digits + final threeHexColor = + (color.r ~/ 255).toRadixString(16).padLeft(1, '0')[0] + + (color.g ~/ 255).toRadixString(16).padLeft(1, '0')[0] + + (color.b ~/ 255).toRadixString(16).padLeft(1, '0')[0]; + final threeDigitsColor = ColorExtension.fromRGBHexString(threeHexColor); - // CCC - final threeUpperCaseColor = threeHexColor.toUpperCase(); - // ccc - final threeLowerCaseColor = threeHexColor.toLowerCase(); - // #CCC - final hashtagThreeUpperCaseColor = '#$threeUpperCaseColor'; - // #ccc - final hashtagThreeLowerCaseColor = '#$threeLowerCaseColor'; + // CCC + final threeUpperCaseColor = threeHexColor.toUpperCase(); + // ccc + final threeLowerCaseColor = threeHexColor.toLowerCase(); + // #CCC + final hashtagThreeUpperCaseColor = '#$threeUpperCaseColor'; + // #ccc + final hashtagThreeLowerCaseColor = '#$threeLowerCaseColor'; - expectColor( - PaintExtension.fromRGBHexString(threeUpperCaseColor).color, - threeDigitsColor, - reason: 'CCC does not generates the good paint', - ); - expectColor( - PaintExtension.fromRGBHexString(threeLowerCaseColor).color, - threeDigitsColor, - reason: 'ccc does not generates the good paint', - ); - expectColor( - PaintExtension.fromRGBHexString(hashtagThreeUpperCaseColor).color, - threeDigitsColor, - reason: '#CCC does not generates the good paint', - ); - expectColor( - PaintExtension.fromRGBHexString(hashtagThreeLowerCaseColor).color, - threeDigitsColor, - reason: '#ccc does not generates the good paint', - ); - }); + expectColor( + PaintExtension.fromRGBHexString(threeUpperCaseColor).color, + threeDigitsColor, + reason: 'CCC does not generates the good paint', + ); + expectColor( + PaintExtension.fromRGBHexString(threeLowerCaseColor).color, + threeDigitsColor, + reason: 'ccc does not generates the good paint', + ); + expectColor( + PaintExtension.fromRGBHexString(hashtagThreeUpperCaseColor).color, + threeDigitsColor, + reason: '#CCC does not generates the good paint', + ); + expectColor( + PaintExtension.fromRGBHexString(hashtagThreeLowerCaseColor).color, + threeDigitsColor, + reason: '#ccc does not generates the good paint', + ); + }, + ); testRandom( - 'using fromARGBHexString returns a new Paint with the right Color', - (Random r) { - // used as an example hex color code on the tests below - // cSpell:ignore fccc + 'using fromARGBHexString returns a new Paint with the right Color', + (Random r) { + // used as an example hex color code on the tests below + // cSpell:ignore fccc - // As documentation says - // valid inputs are : fccc, FCCC, #fccc, #FCCC, #ffc1c1c1, #FFC1C1C1, - // ffc1c1c1, FFC1C1C1 - var color = ColorExtension.random(rng: r); - final sixHexColor = - (color.a * 255).toInt().toRadixString(16).padLeft(2, '0') + - (color.r * 255).toInt().toRadixString(16).padLeft(2, '0') + - (color.g * 255).toInt().toRadixString(16).padLeft(2, '0') + - (color.b * 255).toInt().toRadixString(16).padLeft(2, '0'); + // As documentation says + // valid inputs are : fccc, FCCC, #fccc, #FCCC, #ffc1c1c1, #FFC1C1C1, + // ffc1c1c1, FFC1C1C1 + var color = ColorExtension.random(rng: r); + final sixHexColor = + (color.a * 255).toInt().toRadixString(16).padLeft(2, '0') + + (color.r * 255).toInt().toRadixString(16).padLeft(2, '0') + + (color.g * 255).toInt().toRadixString(16).padLeft(2, '0') + + (color.b * 255).toInt().toRadixString(16).padLeft(2, '0'); - // FFC1C1C1 - final sixUpperCaseColor = sixHexColor.toUpperCase(); - // ffc1c1c1 - final sixLowerCaseColor = sixHexColor.toLowerCase(); - // #FFC1C1C1 - final hashtagSixUpperCaseColor = '#$sixUpperCaseColor'; - // #ffc1c1c1 - final hashtagSixLowerCaseColor = '#$sixLowerCaseColor'; + // FFC1C1C1 + final sixUpperCaseColor = sixHexColor.toUpperCase(); + // ffc1c1c1 + final sixLowerCaseColor = sixHexColor.toLowerCase(); + // #FFC1C1C1 + final hashtagSixUpperCaseColor = '#$sixUpperCaseColor'; + // #ffc1c1c1 + final hashtagSixLowerCaseColor = '#$sixLowerCaseColor'; - expectColor( - PaintExtension.fromARGBHexString(hashtagSixUpperCaseColor).color, - color, - reason: 'FFC1C1C1 does not generates the good paint', - ); - expectColor( - PaintExtension.fromARGBHexString(sixLowerCaseColor).color, - color, - reason: 'ffc1c1c1 does not generates the good paint', - ); - expectColor( - PaintExtension.fromARGBHexString(hashtagSixUpperCaseColor).color, - color, - reason: '#FFC1C1C1 does not generates the good paint', - ); - expectColor( - PaintExtension.fromARGBHexString(hashtagSixLowerCaseColor).color, - color, - reason: '#ffc1c1c1 does not generates the good paint', - ); + expectColor( + PaintExtension.fromARGBHexString(hashtagSixUpperCaseColor).color, + color, + reason: 'FFC1C1C1 does not generates the good paint', + ); + expectColor( + PaintExtension.fromARGBHexString(sixLowerCaseColor).color, + color, + reason: 'ffc1c1c1 does not generates the good paint', + ); + expectColor( + PaintExtension.fromARGBHexString(hashtagSixUpperCaseColor).color, + color, + reason: '#FFC1C1C1 does not generates the good paint', + ); + expectColor( + PaintExtension.fromARGBHexString(hashtagSixLowerCaseColor).color, + color, + reason: '#ffc1c1c1 does not generates the good paint', + ); - // Let's generate a new color from only 3 digits - final threeHexColor = - (color.a ~/ 255).toRadixString(16).padLeft(1, '0')[0] + - (color.r ~/ 255).toRadixString(16).padLeft(1, '0')[0] + - (color.g ~/ 255).toRadixString(16).padLeft(1, '0')[0] + - (color.b ~/ 255).toRadixString(16).padLeft(1, '0')[0]; - color = ColorExtension.fromARGBHexString(threeHexColor); + // Let's generate a new color from only 3 digits + final threeHexColor = + (color.a ~/ 255).toRadixString(16).padLeft(1, '0')[0] + + (color.r ~/ 255).toRadixString(16).padLeft(1, '0')[0] + + (color.g ~/ 255).toRadixString(16).padLeft(1, '0')[0] + + (color.b ~/ 255).toRadixString(16).padLeft(1, '0')[0]; + color = ColorExtension.fromARGBHexString(threeHexColor); - // FCCC - final threeUpperCaseColor = threeHexColor.toUpperCase(); - // fccc - final threeLowerCaseColor = threeHexColor.toLowerCase(); - // #FCCC - final hashtagThreeUpperCaseColor = '#$threeUpperCaseColor'; - // #fccc - final hashtagThreeLowerCaseColor = '#$threeLowerCaseColor'; + // FCCC + final threeUpperCaseColor = threeHexColor.toUpperCase(); + // fccc + final threeLowerCaseColor = threeHexColor.toLowerCase(); + // #FCCC + final hashtagThreeUpperCaseColor = '#$threeUpperCaseColor'; + // #fccc + final hashtagThreeLowerCaseColor = '#$threeLowerCaseColor'; - expect( - PaintExtension.fromARGBHexString(threeUpperCaseColor).color, - color, - reason: 'FCCC does not generates the good paint', - ); - expect( - PaintExtension.fromARGBHexString(threeLowerCaseColor).color, - color, - reason: 'fccc does not generates the good paint', - ); - expect( - PaintExtension.fromARGBHexString(hashtagThreeUpperCaseColor).color, - color, - reason: '#FCCC does not generates the good paint', - ); - expect( - PaintExtension.fromARGBHexString(hashtagThreeLowerCaseColor).color, - color, - reason: '#fccc does not generates the good paint', - ); - }); + expect( + PaintExtension.fromARGBHexString(threeUpperCaseColor).color, + color, + reason: 'FCCC does not generates the good paint', + ); + expect( + PaintExtension.fromARGBHexString(threeLowerCaseColor).color, + color, + reason: 'fccc does not generates the good paint', + ); + expect( + PaintExtension.fromARGBHexString(hashtagThreeUpperCaseColor).color, + color, + reason: '#FCCC does not generates the good paint', + ); + expect( + PaintExtension.fromARGBHexString(hashtagThreeLowerCaseColor).color, + color, + reason: '#fccc does not generates the good paint', + ); + }, + ); testRandom('random returns a new Paint with the right Color', (Random r) { // withAlpha is used by Color.fromRGBO witch takes an argument between 0 @@ -210,8 +212,11 @@ void main() { final withAlpha = r.nextDouble(); final base = r.nextInt(256); - final paint = - PaintExtension.random(withAlpha: withAlpha, base: base, rng: r); + final paint = PaintExtension.random( + withAlpha: withAlpha, + base: base, + rng: r, + ); final color = ColorExtension.random(withAlpha: withAlpha, rng: r); // As explained in the documentation diff --git a/packages/flame/test/extensions/rect_test.dart b/packages/flame/test/extensions/rect_test.dart index 387e07bbe..2c17d5782 100644 --- a/packages/flame/test/extensions/rect_test.dart +++ b/packages/flame/test/extensions/rect_test.dart @@ -123,8 +123,9 @@ void main() { expect(rect.intersectsSegment(under, nearUnder), false); }); - testRandom('intersectsLineSegment is the same as intersectsSegment', - (Random r) { + testRandom('intersectsLineSegment is the same as intersectsSegment', ( + Random r, + ) { final rect = Rect.fromLTWH( r.nextDouble(), r.nextDouble(), @@ -138,37 +139,39 @@ void main() { }); testRandom( - 'toVertices returns an array of [topLeft, topRight, bottomRight, ' - 'bottomLeft]', (Random r) { - final left = r.nextDouble(); - final top = r.nextDouble(); - final right = r.nextDouble(); - final bottom = r.nextDouble(); + 'toVertices returns an array of [topLeft, topRight, bottomRight, ' + 'bottomLeft]', + (Random r) { + final left = r.nextDouble(); + final top = r.nextDouble(); + final right = r.nextDouble(); + final bottom = r.nextDouble(); - final rect = Rect.fromLTRB(left, top, right, bottom); - final vertices = rect.toVertices(); - expect(vertices.length, 4); - expect( - vertices[0], - Vector2(left, top), - reason: 'topLeft value is not right', - ); - expect( - vertices[1], - Vector2(right, top), - reason: 'topRight value is not right', - ); - expect( - vertices[2], - Vector2(right, bottom), - reason: 'bottomRight value is not right', - ); - expect( - vertices[3], - Vector2(left, bottom), - reason: 'bottomLeft value is not right', - ); - }); + final rect = Rect.fromLTRB(left, top, right, bottom); + final vertices = rect.toVertices(); + expect(vertices.length, 4); + expect( + vertices[0], + Vector2(left, top), + reason: 'topLeft value is not right', + ); + expect( + vertices[1], + Vector2(right, top), + reason: 'topRight value is not right', + ); + expect( + vertices[2], + Vector2(right, bottom), + reason: 'bottomRight value is not right', + ); + expect( + vertices[3], + Vector2(left, bottom), + reason: 'bottomLeft value is not right', + ); + }, + ); test('test transform', () { final matrix4 = Matrix4.translation(Vector3(10, 10, 0)); const input = Rect.fromLTWH(0, 0, 10, 10); diff --git a/packages/flame/test/extensions/size_test.dart b/packages/flame/test/extensions/size_test.dart index 974af6e89..2fd0f0966 100644 --- a/packages/flame/test/extensions/size_test.dart +++ b/packages/flame/test/extensions/size_test.dart @@ -39,15 +39,20 @@ void main() { }); testRandom( - 'toRect has left to 0, top to 0, width: size.dx and height: size.dy', - (Random r) { - final size = Size(r.nextDouble(), r.nextDouble()); - final rect = size.toRect(); + 'toRect has left to 0, top to 0, width: size.dx and height: size.dy', + (Random r) { + final size = Size(r.nextDouble(), r.nextDouble()); + final rect = size.toRect(); - expect(rect.left, 0, reason: 'left should be 0 as init'); - expect(rect.top, 0, reason: 'top should be 0 as init'); - expect(rect.width, size.width, reason: 'width width does not match'); - expect(rect.height, size.height, reason: 'height height does not match'); - }); + expect(rect.left, 0, reason: 'left should be 0 as init'); + expect(rect.top, 0, reason: 'top should be 0 as init'); + expect(rect.width, size.width, reason: 'width width does not match'); + expect( + rect.height, + size.height, + reason: 'height height does not match', + ); + }, + ); }); } diff --git a/packages/flame/test/extensions/vector2_test.dart b/packages/flame/test/extensions/vector2_test.dart index 0c1d789bb..a31a379ae 100644 --- a/packages/flame/test/extensions/vector2_test.dart +++ b/packages/flame/test/extensions/vector2_test.dart @@ -7,16 +7,18 @@ import 'package:test/test.dart'; void main() { group('Vector2Extension', () { - testRandom('Converting a vector to an offset matches x/dx and y/dy', - (Random r) { + testRandom('Converting a vector to an offset matches x/dx and y/dy', ( + Random r, + ) { final vector = Vector2(r.nextDouble(), r.nextDouble()); final offset = vector.toOffset(); expectDouble(offset.dx, vector.x, reason: 'dx and x are not matching'); expectDouble(offset.dy, vector.y, reason: 'dy and y are not matching'); }); - testRandom('Converting a vector to a Size matches x/width and y/height', - (Random r) { + testRandom('Converting a vector to a Size matches x/width and y/height', ( + Random r, + ) { final vector = Vector2(r.nextDouble(), r.nextDouble()); final size = vector.toSize(); expectDouble( @@ -31,8 +33,9 @@ void main() { ); }); - testRandom('Converting a vector to a Point matches x/x and y/y', - (Random r) { + testRandom('Converting a vector to a Point matches x/x and y/y', ( + Random r, + ) { final vector = Vector2(r.nextDouble(), r.nextDouble()); final point = vector.toPoint(); expectDouble( @@ -58,8 +61,9 @@ void main() { expect(actual.right, expected.right); }); - testRandom('toPositionedRect creates a rect with correct coordinates', - (Random r) { + testRandom('toPositionedRect creates a rect with correct coordinates', ( + Random r, + ) { final v1 = Vector2(r.nextDouble(), r.nextDouble()); final size = Vector2(r.nextDouble(), r.nextDouble()); final rect = v1.toPositionedRect(size); @@ -106,8 +110,9 @@ void main() { expect(vNotZero.isZero(), false, reason: '(x,x) is not zero'); }); - testRandom('isIdentity returns true with 1,1 and false otherwise', - (Random r) { + testRandom('isIdentity returns true with 1,1 and false otherwise', ( + Random r, + ) { // nextDouble is never 1 final vIdentity = Vector2(1, 1); final vIdentityX = Vector2(1, r.nextDouble()); @@ -443,8 +448,9 @@ void main() { ); }); - testRandom('Cloning a vector gives a vector with the exact same x and y', - (Random r) { + testRandom('Cloning a vector gives a vector with the exact same x and y', ( + Random r, + ) { final original = Vector2(r.nextDouble(), r.nextDouble()); final clone = original.clone(); @@ -523,8 +529,9 @@ void main() { }); }); - testRandom('Creating a Vector2 fromRadians points to the correct direction', - (Random r) { + testRandom('Creating a Vector2 fromRadians points to the correct direction', ( + Random r, + ) { // See more on https://en.wikipedia.org/wiki/Rotation_matrix // TL;DR; // (x', y') = (x cos(p) - y sin(p) , x sin(p) + y cos(p)) @@ -546,8 +553,9 @@ void main() { expectDouble(pointingVector.y, -math.cos(angleInRadians)); }); - testRandom('Creating a Vector2 fromDegrees points to the correct direction', - (Random r) { + testRandom('Creating a Vector2 fromDegrees points to the correct direction', ( + Random r, + ) { // See more on https://en.wikipedia.org/wiki/Rotation_matrix // TL;DR; // (x', y') = (x cos(p) - y sin(p) , x sin(p) + y cos(p)) diff --git a/packages/flame/test/game/game_widget/game_widget_controlled_lifecycle_test.dart b/packages/flame/test/game/game_widget/game_widget_controlled_lifecycle_test.dart index 27e614d8f..046420323 100644 --- a/packages/flame/test/game/game_widget/game_widget_controlled_lifecycle_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_controlled_lifecycle_test.dart @@ -179,8 +179,10 @@ void main() { await tester.pump(); expect(events, ['onGameResize']); // no onRemove - final game = - tester.allWidgets.whereType>().first.game; + final game = tester.allWidgets + .whereType>() + .first + .game; expect(game?.children, everyElement((Component c) => c.parent == game)); }); diff --git a/packages/flame/test/game/game_widget/game_widget_lifecycle_test.dart b/packages/flame/test/game/game_widget/game_widget_lifecycle_test.dart index d9850942c..81ff4fe10 100644 --- a/packages/flame/test/game/game_widget/game_widget_lifecycle_test.dart +++ b/packages/flame/test/game/game_widget/game_widget_lifecycle_test.dart @@ -232,8 +232,10 @@ void main() { 'render', ], ); // no onRemove - final game = - tester.allWidgets.whereType>().first.game; + final game = tester.allWidgets + .whereType>() + .first + .game; expect(game?.children, everyElement((Component c) => c.parent == game)); }); diff --git a/packages/flame/test/game/transform2d_test.dart b/packages/flame/test/game/transform2d_test.dart index c27ae23fc..002f0d158 100644 --- a/packages/flame/test/game/transform2d_test.dart +++ b/packages/flame/test/game/transform2d_test.dart @@ -24,15 +24,16 @@ void main() { const epsilon = 1 / (1 << 23); // Calculate indicative condition number - final matrixNorm = - math.sqrt(m[0] * m[0] + m[1] * m[1] + m[4] * m[4] + m[5] * m[5]); + final matrixNorm = math.sqrt( + m[0] * m[0] + m[1] * m[1] + m[4] * m[4] + m[5] * m[5], + ); double conditionFactor; if (det.abs() > 1e-10) { // Calculate condition number final invMatrixNorm = math.sqrt(m[5] * m[5] + m[1] * m[1] + m[4] * m[4] + m[0] * m[0]) / - det.abs(); + det.abs(); conditionFactor = matrixNorm * invMatrixNorm; } else { // For ~singular matrices, small input change -> large output change @@ -46,7 +47,8 @@ void main() { const double numOperations = 14; // Standard deviation (1-σ) - final sigma = epsilon * + final sigma = + epsilon * math.sqrt(numVariables) * math.sqrt(numOperations) * conditionFactor; @@ -237,10 +239,13 @@ void main() { ); } // Check round-trip conversion between local and global - final point1 = - Vector2((rnd.nextDouble() - 0.5) * 5, (rnd.nextDouble() - 0.5) * 5); - final point2 = - transform2d.globalToLocal(transform2d.localToGlobal(point1)); + final point1 = Vector2( + (rnd.nextDouble() - 0.5) * 5, + (rnd.nextDouble() - 0.5) * 5, + ); + final point2 = transform2d.globalToLocal( + transform2d.localToGlobal(point1), + ); final tolerance = transform2dRoundTripUncertainty(transform2d, point1); expect( diff --git a/packages/flame/test/geometry/ray2_test.dart b/packages/flame/test/geometry/ray2_test.dart index c96a6c8fb..c44b3c8c4 100644 --- a/packages/flame/test/geometry/ray2_test.dart +++ b/packages/flame/test/geometry/ray2_test.dart @@ -59,8 +59,10 @@ void main() { group('intersectsWithAabb2', () { test('Ray from the east', () { final direction = Vector2(1.0, 0.0); - final ray = - Ray2(origin: Vector2.zero(), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.zero(), + direction: direction.normalized(), + ); expect( ray.intersectsWithAabb2(Aabb2.minMax(Vector2(1, -1), Vector2(2, 1))), isTrue, @@ -69,8 +71,10 @@ void main() { test('Ray from the north', () { final direction = Vector2(0.0, 1.0); - final ray = - Ray2(origin: Vector2.zero(), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.zero(), + direction: direction.normalized(), + ); expect( ray.intersectsWithAabb2(Aabb2.minMax(Vector2(-1, 1), Vector2(1, 2))), isTrue, @@ -79,8 +83,10 @@ void main() { test('Ray from the west', () { final direction = Vector2(-1.0, 0.0); - final ray = - Ray2(origin: Vector2.zero(), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.zero(), + direction: direction.normalized(), + ); expect( ray.intersectsWithAabb2( Aabb2.minMax(Vector2(-2, -1), Vector2(-1, 1)), @@ -91,8 +97,10 @@ void main() { test('Ray from the south', () { final direction = Vector2(0.0, -1.0); - final ray = - Ray2(origin: Vector2.zero(), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.zero(), + direction: direction.normalized(), + ); expect( ray.intersectsWithAabb2( Aabb2.minMax(Vector2(-1, -2), Vector2(1, -1)), @@ -103,8 +111,10 @@ void main() { test('Ray from the northEast', () { final direction = Vector2(0.5, 0.5); - final ray = - Ray2(origin: Vector2.zero(), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.zero(), + direction: direction.normalized(), + ); expect( ray.intersectsWithAabb2(Aabb2.minMax(Vector2(1, 1), Vector2(2, 2))), isTrue, @@ -113,8 +123,10 @@ void main() { test('Ray from the northWest', () { final direction = Vector2(-0.5, 0.5); - final ray = - Ray2(origin: Vector2.zero(), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.zero(), + direction: direction.normalized(), + ); expect( ray.intersectsWithAabb2(Aabb2.minMax(Vector2(-2, 1), Vector2(-1, 2))), isTrue, @@ -123,8 +135,10 @@ void main() { test('Ray from the southWest', () { final direction = Vector2(-0.5, -0.5); - final ray = - Ray2(origin: Vector2.zero(), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.zero(), + direction: direction.normalized(), + ); expect( ray.intersectsWithAabb2( Aabb2.minMax(Vector2(-2, -2), Vector2(-1, -1)), @@ -135,8 +149,10 @@ void main() { test('Ray from the southEast', () { final direction = Vector2(0.5, -0.5); - final ray = - Ray2(origin: Vector2.zero(), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.zero(), + direction: direction.normalized(), + ); expect( ray.intersectsWithAabb2(Aabb2.minMax(Vector2(1, -2), Vector2(2, -1))), isTrue, @@ -150,8 +166,10 @@ void main() { const numberOfDirections = 16; for (var i = 0; i < numberOfDirections; i++) { direction.rotate(tau * (i / numberOfDirections)); - final ray = - Ray2(origin: Vector2.all(5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2.all(5), + direction: direction.normalized(), + ); final aabb2 = Aabb2.minMax(Vector2.zero(), Vector2.all(10)); expect( ray.intersectsWithAabb2(aabb2), @@ -171,8 +189,10 @@ void main() { final angle = (tau / 2 - 2 * epsilon) * (i / numberOfDirections) + epsilon; direction.rotate(angle); - final ray = - Ray2(origin: Vector2(10, 5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(10, 5), + direction: direction.normalized(), + ); final aabb2 = Aabb2.minMax(Vector2.zero(), Vector2.all(10)); expect( ray.intersectsWithAabb2(aabb2), @@ -192,8 +212,10 @@ void main() { final angle = (tau / 2 - 2 * epsilon) * (i / numberOfDirections) + epsilon; direction.rotate(-angle); - final ray = - Ray2(origin: Vector2(10, 5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(10, 5), + direction: direction.normalized(), + ); final aabb2 = Aabb2.minMax(Vector2.zero(), Vector2.all(10)); expect( ray.intersectsWithAabb2(aabb2), @@ -206,15 +228,19 @@ void main() { test( 'Rays that originates and follows a box edge does intersects', () { - final rayVertical = - Ray2(origin: Vector2(10, 5), direction: Vector2(0, 1)); + final rayVertical = Ray2( + origin: Vector2(10, 5), + direction: Vector2(0, 1), + ); final aabb2 = Aabb2.minMax(Vector2.zero(), Vector2.all(10)); expect( rayVertical.intersectsWithAabb2(aabb2), isTrue, ); - final rayHorizontal = - Ray2(origin: Vector2(5, 0), direction: Vector2(1, 0)); + final rayHorizontal = Ray2( + origin: Vector2(5, 0), + direction: Vector2(1, 0), + ); expect( rayHorizontal.intersectsWithAabb2(aabb2), isTrue, @@ -225,15 +251,19 @@ void main() { test( 'Rays that originates in a corner intersects', () { - final rayZero = - Ray2(origin: Vector2.zero(), direction: Vector2(0, 1)); + final rayZero = Ray2( + origin: Vector2.zero(), + direction: Vector2(0, 1), + ); final aabb2 = Aabb2.minMax(Vector2.zero(), Vector2.all(10)); expect( rayZero.intersectsWithAabb2(aabb2), isTrue, ); - final rayTen = - Ray2(origin: Vector2.all(10), direction: Vector2(0, -1)); + final rayTen = Ray2( + origin: Vector2.all(10), + direction: Vector2(0, -1), + ); expect( rayTen.intersectsWithAabb2(aabb2), isTrue, @@ -245,8 +275,10 @@ void main() { 'Ray in the opposite direction does not intersect', () { final direction = Vector2(1, 0); - final ray = - Ray2(origin: Vector2(15, 5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(15, 5), + direction: direction.normalized(), + ); final aabb2 = Aabb2.minMax(Vector2.zero(), Vector2.all(10)); expect( ray.intersectsWithAabb2(aabb2), @@ -261,8 +293,10 @@ void main() { 'Correct intersection point length on ray going east', () { final direction = Vector2(1, 0); - final ray = - Ray2(origin: Vector2(5, 5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(5, 5), + direction: direction.normalized(), + ); final segment = LineSegment(Vector2(10, 0), Vector2.all(10)); expect(ray.lineSegmentIntersection(segment), 5); }, @@ -272,8 +306,10 @@ void main() { 'Correct intersection point length on ray going west', () { final direction = Vector2(-1, 0); - final ray = - Ray2(origin: Vector2(5, 5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(5, 5), + direction: direction.normalized(), + ); final segment = LineSegment(Vector2(0, 0), Vector2(0, 10)); expect(ray.lineSegmentIntersection(segment), 5); }, @@ -283,8 +319,10 @@ void main() { 'Correct intersection point length on ray going south', () { final direction = Vector2(0, 1); - final ray = - Ray2(origin: Vector2(5, 5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(5, 5), + direction: direction.normalized(), + ); final segment = LineSegment(Vector2(0, 10), Vector2(10, 10)); expect(ray.lineSegmentIntersection(segment), 5); }, @@ -294,8 +332,10 @@ void main() { 'Correct intersection point length on ray going north', () { final direction = Vector2(0, -1); - final ray = - Ray2(origin: Vector2(5, 5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(5, 5), + direction: direction.normalized(), + ); final segment = LineSegment(Vector2(0, 0), Vector2(10, 0)); expect(ray.lineSegmentIntersection(segment), 5); }, @@ -305,8 +345,10 @@ void main() { 'Origin as intersection point when ray originates on segment', () { final direction = Vector2(0, -1); - final ray = - Ray2(origin: Vector2(5, 0), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(5, 0), + direction: direction.normalized(), + ); final segment = LineSegment(Vector2(0, 0), Vector2(10, 0)); expect(ray.lineSegmentIntersection(segment), 0); }, @@ -316,8 +358,10 @@ void main() { 'No intersection when ray is parallel and originates on segment', () { final direction = Vector2(1, 0); - final ray = - Ray2(origin: Vector2(5, 0), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(5, 0), + direction: direction.normalized(), + ); final segment = LineSegment(Vector2(0, 0), Vector2(10, 0)); expect(ray.lineSegmentIntersection(segment), null); }, @@ -327,8 +371,10 @@ void main() { 'No intersection point when ray is parallel to the segment', () { final direction = Vector2(1, 0); - final ray = - Ray2(origin: Vector2(-5, 0), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(-5, 0), + direction: direction.normalized(), + ); final segment = LineSegment(Vector2(0, 0), Vector2(10, 0)); expect(ray.lineSegmentIntersection(segment), null); }, @@ -338,8 +384,10 @@ void main() { 'No intersection point when ray is parallel without intersection', () { final direction = Vector2(1, 0); - final ray = - Ray2(origin: Vector2(5, 5), direction: direction.normalized()); + final ray = Ray2( + origin: Vector2(5, 5), + direction: direction.normalized(), + ); final segment = LineSegment(Vector2(0, 0), Vector2(10, 0)); expect(ray.lineSegmentIntersection(segment), null); }, diff --git a/packages/flame/test/gestures/detectors_test.dart b/packages/flame/test/gestures/detectors_test.dart index 6e828c165..085ad09a4 100644 --- a/packages/flame/test/gestures/detectors_test.dart +++ b/packages/flame/test/gestures/detectors_test.dart @@ -286,8 +286,10 @@ void main() { longPressGame.testGameWidget( 'can register moving longPress', setUp: (game, tester) async { - final gesture = - await tester.startGesture(const Offset(10, 10), pointer: 7); + final gesture = await tester.startGesture( + const Offset(10, 10), + pointer: 7, + ); await Future.delayed(kLongPressTimeout); @@ -305,8 +307,10 @@ void main() { longPressGame.testGameWidget( 'can register longPressCancel', setUp: (game, tester) async { - final gesture = - await tester.startGesture(const Offset(10, 10), pointer: 7); + final gesture = await tester.startGesture( + const Offset(10, 10), + pointer: 7, + ); await gesture.moveTo(const Offset(20, 10)); @@ -742,8 +746,9 @@ void main() { mouseMoveGame.testGameWidget( 'Can register Mouse movements', setUp: (game, tester) async { - final gesture = - await tester.createGesture(kind: PointerDeviceKind.mouse); + final gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); await gesture.addPointer(location: Offset.zero); await gesture.moveTo(const Offset(10, 10)); }, @@ -762,8 +767,9 @@ void main() { const scrollEventLocation = Offset(0, 300); final testPointer = TestPointer(1, PointerDeviceKind.mouse); testPointer.hover(scrollEventLocation); - await tester - .sendEventToBinding(testPointer.scroll(const Offset(0.0, -300.0))); + await tester.sendEventToBinding( + testPointer.scroll(const Offset(0.0, -300.0)), + ); expect(game.registeredScrolling, isTrue); }, diff --git a/packages/flame/test/particles/circle_particle_test.dart b/packages/flame/test/particles/circle_particle_test.dart index 6831ddf68..36c221528 100644 --- a/packages/flame/test/particles/circle_particle_test.dart +++ b/packages/flame/test/particles/circle_particle_test.dart @@ -20,22 +20,23 @@ void main() { }); testWithFlameGame( - 'Consider composing this with other Particle to achieve needed effects', - (game) async { - final childParticle = CircleParticle( - paint: Paint()..color = Colors.red, - lifespan: 2, - ); + 'Consider composing this with other Particle to achieve needed effects', + (game) async { + final childParticle = CircleParticle( + paint: Paint()..color = Colors.red, + lifespan: 2, + ); - final component = ParticleSystemComponent( - particle: childParticle, - ); + final component = ParticleSystemComponent( + particle: childParticle, + ); - game.add(component); - await game.ready(); - game.update(1); + game.add(component); + await game.ready(); + game.update(1); - expect(childParticle.progress, 0.5); - }); + expect(childParticle.progress, 0.5); + }, + ); }); } diff --git a/packages/flame/test/particles/composed_particle_test.dart b/packages/flame/test/particles/composed_particle_test.dart index b49987a0a..d428b8018 100644 --- a/packages/flame/test/particles/composed_particle_test.dart +++ b/packages/flame/test/particles/composed_particle_test.dart @@ -6,8 +6,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('ComposedParticle', () { - testWithFlameGame('particles with parent lifespan applied to children', - (game) async { + testWithFlameGame('particles with parent lifespan applied to children', ( + game, + ) async { final childParticle1 = CircleParticle( paint: Paint()..color = Colors.red, lifespan: 1, @@ -46,8 +47,9 @@ void main() { expect(particle.children.length, 2); }); - testWithFlameGame('particles without parent lifespan applied to children', - (game) async { + testWithFlameGame('particles without parent lifespan applied to children', ( + game, + ) async { final childParticle1 = CircleParticle( paint: Paint()..color = Colors.red, lifespan: 1, diff --git a/packages/flame/test/particles/computed_particle_test.dart b/packages/flame/test/particles/computed_particle_test.dart index d2820bbb6..6081b6ff5 100644 --- a/packages/flame/test/particles/computed_particle_test.dart +++ b/packages/flame/test/particles/computed_particle_test.dart @@ -7,39 +7,40 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('ComputedParticle', () { testWithFlameGame( - 'Particle container which delegates rendering particle on each frame', - (game) async { - final cellSize = game.size / 5.0; - final halfCellSize = cellSize / 2; + 'Particle container which delegates rendering particle on each frame', + (game) async { + final cellSize = game.size / 5.0; + final halfCellSize = cellSize / 2; - final particle = ComputedParticle( - renderer: (canvas, particle) { - canvas.drawCircle( - Offset.zero, - particle.progress * halfCellSize.x, - Paint() - ..color = Color.lerp( - Colors.red, - Colors.blue, - particle.progress, - )!, - ); - }, - lifespan: 2, - ); + final particle = ComputedParticle( + renderer: (canvas, particle) { + canvas.drawCircle( + Offset.zero, + particle.progress * halfCellSize.x, + Paint() + ..color = Color.lerp( + Colors.red, + Colors.blue, + particle.progress, + )!, + ); + }, + lifespan: 2, + ); - final component = ParticleSystemComponent( - particle: particle, - ); + final component = ParticleSystemComponent( + particle: particle, + ); - game.add(component); - await game.ready(); - game.update(1); - expect(particle.progress, 0.5); + game.add(component); + await game.ready(); + game.update(1); + expect(particle.progress, 0.5); - game.update(1); - expect(particle.progress, 1); - }); + game.update(1); + expect(particle.progress, 1); + }, + ); testWithFlameGame('Particle to use custom tweening', (game) async { final cellSize = game.size / 5.0; diff --git a/packages/flame/test/particles/curved_particle_test.dart b/packages/flame/test/particles/curved_particle_test.dart index 87b1e8bf1..a197edd11 100644 --- a/packages/flame/test/particles/curved_particle_test.dart +++ b/packages/flame/test/particles/curved_particle_test.dart @@ -19,19 +19,21 @@ void main() { }); testWithFlameGame( - 'A Particle which applies certain Curve for easing or other purposes' - ' to its progress getter.', (game) async { - final particle = CurvedParticle(lifespan: 2); - final component = ParticleSystemComponent( - particle: particle, - ); + 'A Particle which applies certain Curve for easing or other purposes' + ' to its progress getter.', + (game) async { + final particle = CurvedParticle(lifespan: 2); + final component = ParticleSystemComponent( + particle: particle, + ); - game.add(component); - await game.ready(); - game.update(1); + game.add(component); + await game.ready(); + game.update(1); - expect(particle.curve, Curves.linear); - expect(particle.progress, 0.5); - }); + expect(particle.curve, Curves.linear); + expect(particle.progress, 0.5); + }, + ); }); } diff --git a/packages/flame/test/particles/moving_particle_test.dart b/packages/flame/test/particles/moving_particle_test.dart index 5c72dcc39..4a4eec3fe 100644 --- a/packages/flame/test/particles/moving_particle_test.dart +++ b/packages/flame/test/particles/moving_particle_test.dart @@ -9,27 +9,28 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('MovingParticle', () { testWithFlameGame( - 'Particle which is moving from one predefined position to another one', - (game) async { - final childParticle = CircleParticle( - paint: Paint()..color = Colors.red, - lifespan: 2, - ); + 'Particle which is moving from one predefined position to another one', + (game) async { + final childParticle = CircleParticle( + paint: Paint()..color = Colors.red, + lifespan: 2, + ); - final particle = MovingParticle( - from: Vector2(-20, -20), - to: Vector2(20, 20), - child: childParticle, - ); + final particle = MovingParticle( + from: Vector2(-20, -20), + to: Vector2(20, 20), + child: childParticle, + ); - final component = ParticleSystemComponent( - particle: particle, - ); + final component = ParticleSystemComponent( + particle: particle, + ); - game.add(component); - await game.ready(); - game.update(1); - expect(particle.progress, 1.0); - }); + game.add(component); + await game.ready(); + game.update(1); + expect(particle.progress, 1.0); + }, + ); }); } diff --git a/packages/flame/test/particles/scaled_particle_test.dart b/packages/flame/test/particles/scaled_particle_test.dart index 1bfb59775..5125a7526 100644 --- a/packages/flame/test/particles/scaled_particle_test.dart +++ b/packages/flame/test/particles/scaled_particle_test.dart @@ -11,32 +11,34 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('ScaledParticle', () { testWithFlameGame( - 'A particle which rotates its child over the lifespan between two ' - 'given bounds in radians', (game) async { - final paint = Paint()..color = Colors.red; - final rect = ComputedParticle( - renderer: (canvas, _) => canvas.drawRect( - Rect.fromCenter(center: Offset.zero, width: 10, height: 10), - paint, - ), - ); + 'A particle which rotates its child over the lifespan between two ' + 'given bounds in radians', + (game) async { + final paint = Paint()..color = Colors.red; + final rect = ComputedParticle( + renderer: (canvas, _) => canvas.drawRect( + Rect.fromCenter(center: Offset.zero, width: 10, height: 10), + paint, + ), + ); - final particle = ScaledParticle( - lifespan: 2, - child: rect.rotating(to: pi / 2), - ); + final particle = ScaledParticle( + lifespan: 2, + child: rect.rotating(to: pi / 2), + ); - final component = ParticleSystemComponent( - particle: particle, - ); + final component = ParticleSystemComponent( + particle: particle, + ); - game.add(component); - await game.ready(); - game.update(1); + game.add(component); + await game.ready(); + game.update(1); - expect(particle.scale, 1.0); - expect(particle.child, isInstanceOf()); - expect(particle.child.progress, 0.5); - }); + expect(particle.scale, 1.0); + expect(particle.child, isInstanceOf()); + expect(particle.child.progress, 0.5); + }, + ); }); } diff --git a/packages/flame/test/particles/scaling_particle_test.dart b/packages/flame/test/particles/scaling_particle_test.dart index aad8e26ed..93cd316ce 100644 --- a/packages/flame/test/particles/scaling_particle_test.dart +++ b/packages/flame/test/particles/scaling_particle_test.dart @@ -6,8 +6,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('ScalingParticle', () { - testWithFlameGame( - 'A particle which scale its child over the lifespan ' + testWithFlameGame('A particle which scale its child over the lifespan ' 'between 1 and a provided scale', (game) async { final paint = Paint()..color = Colors.red; final rect = ComputedParticle( diff --git a/packages/flame/test/particles/sprite_particle_test.dart b/packages/flame/test/particles/sprite_particle_test.dart index 8b87a9edf..99287e023 100644 --- a/packages/flame/test/particles/sprite_particle_test.dart +++ b/packages/flame/test/particles/sprite_particle_test.dart @@ -24,22 +24,23 @@ Future main() async { final sprite = Sprite(image); testWithFlameGame( - 'SpriteParticle allows easily embed Flames Sprite into the effect', - (game) async { - final particle = SpriteParticle( - sprite: sprite, - size: Vector2(50, 50), - lifespan: 2, - ); + 'SpriteParticle allows easily embed Flames Sprite into the effect', + (game) async { + final particle = SpriteParticle( + sprite: sprite, + size: Vector2(50, 50), + lifespan: 2, + ); - final component = ParticleSystemComponent( - particle: particle, - ); + final component = ParticleSystemComponent( + particle: particle, + ); - game.add(component); - await game.ready(); - game.update(1); - expect(particle.progress, 0.5); - }); + game.add(component); + await game.ready(); + game.update(1); + expect(particle.progress, 0.5); + }, + ); }); } diff --git a/packages/flame/test/sprite_animation_test.dart b/packages/flame/test/sprite_animation_test.dart index 447363b5c..6196336de 100644 --- a/packages/flame/test/sprite_animation_test.dart +++ b/packages/flame/test/sprite_animation_test.dart @@ -30,8 +30,11 @@ void main() { test('Throw assertion error when setting non-positive step time', () { final sprite = _MockSprite(); - final animation = - SpriteAnimation.spriteList([sprite, sprite, sprite], stepTime: 1); + final animation = SpriteAnimation.spriteList([ + sprite, + sprite, + sprite, + ], stepTime: 1); expect( () => animation.stepTime = 0, failsAssert('Step time must be positive'), diff --git a/packages/flame/test/sprite_animation_ticker_test.dart b/packages/flame/test/sprite_animation_ticker_test.dart index d01bddd16..b9eb9eff2 100644 --- a/packages/flame/test/sprite_animation_ticker_test.dart +++ b/packages/flame/test/sprite_animation_ticker_test.dart @@ -7,10 +7,11 @@ void main() { test('onStart called for single-frame animation', () { var counter = 0; final sprite = _MockSprite(); - final animationTicker = - SpriteAnimation.spriteList([sprite], stepTime: 1, loop: false) - .createTicker() - ..onStart = () => counter++; + final animationTicker = SpriteAnimation.spriteList( + [sprite], + stepTime: 1, + loop: false, + ).createTicker()..onStart = () => counter++; expect(counter, 0); animationTicker.update(0.5); @@ -22,10 +23,11 @@ void main() { test('onComplete called for single-frame animation', () { var counter = 0; final sprite = _MockSprite(); - final animationTicker = - SpriteAnimation.spriteList([sprite], stepTime: 1, loop: false) - .createTicker() - ..onComplete = () => counter++; + final animationTicker = SpriteAnimation.spriteList( + [sprite], + stepTime: 1, + loop: false, + ).createTicker()..onComplete = () => counter++; expect(counter, 0); animationTicker.update(0.5); expect(counter, 0); @@ -36,35 +38,40 @@ void main() { }); test( - 'verify call is being made at first of frame for multi-frame animation', - () { - var timePassed = 0.0; - const dt = 0.03; - var timesCalled = 0; - final sprite = _MockSprite(); - final spriteList = [sprite, sprite, sprite]; - final animationTicker = - SpriteAnimation.spriteList(spriteList, stepTime: 1, loop: false) - .createTicker(); - animationTicker.onFrame = (index) { - expect(timePassed, closeTo(index * 1.0, dt)); - timesCalled++; - }; - while (timePassed <= spriteList.length) { - timePassed += dt; - animationTicker.update(dt); - } - expect(timesCalled, spriteList.length); - }); + 'verify call is being made at first of frame for multi-frame animation', + () { + var timePassed = 0.0; + const dt = 0.03; + var timesCalled = 0; + final sprite = _MockSprite(); + final spriteList = [sprite, sprite, sprite]; + final animationTicker = SpriteAnimation.spriteList( + spriteList, + stepTime: 1, + loop: false, + ).createTicker(); + animationTicker.onFrame = (index) { + expect(timePassed, closeTo(index * 1.0, dt)); + timesCalled++; + }; + while (timePassed <= spriteList.length) { + timePassed += dt; + animationTicker.update(dt); + } + expect(timesCalled, spriteList.length); + }, + ); test('test sequence of event lifecycle for an animation', () { var animationStarted = false; var animationRunning = false; var animationComplete = false; final sprite = _MockSprite(); - final animationTicker = - SpriteAnimation.spriteList([sprite], stepTime: 1, loop: false) - .createTicker(); + final animationTicker = SpriteAnimation.spriteList( + [sprite], + stepTime: 1, + loop: false, + ).createTicker(); animationTicker.onStart = () { expect(animationStarted, false); expect(animationRunning, false); @@ -112,22 +119,25 @@ void main() { expectLater(animationTicker.completed, completes); }); - test("completed doesn't complete when the animation is yet to complete", - () { - final sprite = _MockSprite(); - final animationTicker = SpriteAnimation.spriteList( - [sprite], - stepTime: 1, - loop: false, - ).createTicker(); + test( + "completed doesn't complete when the animation is yet to complete", + () { + final sprite = _MockSprite(); + final animationTicker = SpriteAnimation.spriteList( + [sprite], + stepTime: 1, + loop: false, + ).createTicker(); - expectLater(animationTicker.completed, doesNotComplete); - }); + expectLater(animationTicker.completed, doesNotComplete); + }, + ); test("completed doesn't complete when animation is looping", () { final sprite = _MockSprite(); - final animationTicker = - SpriteAnimation.spriteList([sprite], stepTime: 1).createTicker(); + final animationTicker = SpriteAnimation.spriteList([ + sprite, + ], stepTime: 1).createTicker(); expectLater(animationTicker.completed, doesNotComplete); }); @@ -136,8 +146,9 @@ void main() { "completed doesn't complete when animation is looping and on last frame", () { final sprite = _MockSprite(); - final animationTicker = - SpriteAnimation.spriteList([sprite], stepTime: 1).createTicker(); + final animationTicker = SpriteAnimation.spriteList([ + sprite, + ], stepTime: 1).createTicker(); animationTicker.update(1); expectLater(animationTicker.completed, doesNotComplete); diff --git a/packages/flame/test/spritesheet_test.dart b/packages/flame/test/spritesheet_test.dart index e99aec577..9760243c7 100644 --- a/packages/flame/test/spritesheet_test.dart +++ b/packages/flame/test/spritesheet_test.dart @@ -54,10 +54,12 @@ void main() { srcSize: Vector2(50, 50), ); - final animationTicker = spriteSheet.createAnimationWithVariableStepTimes( - row: 1, - stepTimes: [2.0, 3.0], - ).createTicker(); + final animationTicker = spriteSheet + .createAnimationWithVariableStepTimes( + row: 1, + stepTimes: [2.0, 3.0], + ) + .createTicker(); expect(animationTicker.totalDuration(), 5.0); }); diff --git a/packages/flame/test/text/sprite_font_renderer_test.dart b/packages/flame/test/text/sprite_font_renderer_test.dart index 6955ba0c5..185b0a844 100644 --- a/packages/flame/test/text/sprite_font_renderer_test.dart +++ b/packages/flame/test/text/sprite_font_renderer_test.dart @@ -267,7 +267,8 @@ void main() { }); } -const _textSample = 'We hold these truths to be self-evident, that all men are ' +const _textSample = + 'We hold these truths to be self-evident, that all men are ' 'created equal, that they are endowed by their Creator with certain ' 'unalienable Rights, that among these are Life, Liberty and the pursuit of ' 'Happiness. — That to secure these rights, Governments are instituted ' diff --git a/packages/flame/test/text/text_paint_test.dart b/packages/flame/test/text/text_paint_test.dart index 83e75f55e..262243894 100644 --- a/packages/flame/test/text/text_paint_test.dart +++ b/packages/flame/test/text/text_paint_test.dart @@ -8,8 +8,9 @@ void main() { group('TextPaint', () { test('copyWith returns a new instance with the new values', () { const style = flutter.TextStyle(fontSize: 12, fontFamily: 'Times'); - final tp = TextPaint(style: style) - .copyWith((t) => t.copyWith(fontFamily: 'Helvetica')); + final tp = TextPaint( + style: style, + ).copyWith((t) => t.copyWith(fontFamily: 'Helvetica')); expect(tp.style.fontSize, 12); expect(tp.style.fontFamily, 'Helvetica'); }); diff --git a/packages/flame/test/widgets/nine_tile_box_widget_test.dart b/packages/flame/test/widgets/nine_tile_box_widget_test.dart index 865bfd862..ba3aa5f9a 100644 --- a/packages/flame/test/widgets/nine_tile_box_widget_test.dart +++ b/packages/flame/test/widgets/nine_tile_box_widget_test.dart @@ -12,8 +12,9 @@ Future main() async { final image = await generateImage(); group('NineTileBoxWidget', () { - testWidgets('has no FutureBuilder when passed an animation', - (tester) async { + testWidgets('has no FutureBuilder when passed an animation', ( + tester, + ) async { await tester.pumpWidget( NineTileBoxWidget( image: image, @@ -108,16 +109,18 @@ Future main() async { await tester.pumpAndSettle(); - var internalWidget = tester - .widget(find.byType(InternalNineTileBox)); + var internalWidget = tester.widget( + find.byType(InternalNineTileBox), + ); expect(internalWidget.image, image); await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); - internalWidget = tester - .widget(find.byType(InternalNineTileBox)); + internalWidget = tester.widget( + find.byType(InternalNineTileBox), + ); expect(internalWidget.image, image2); }); diff --git a/packages/flame/test/widgets/sprite_animation_widget_test.dart b/packages/flame/test/widgets/sprite_animation_widget_test.dart index a56c59a45..8b6992b2e 100644 --- a/packages/flame/test/widgets/sprite_animation_widget_test.dart +++ b/packages/flame/test/widgets/sprite_animation_widget_test.dart @@ -12,8 +12,9 @@ Future main() async { final image = await generateImage(); group('SpriteAnimationWidget', () { - testWidgets('has no FutureBuilder when passed an animation', - (tester) async { + testWidgets('has no FutureBuilder when passed an animation', ( + tester, + ) async { final sprite1 = Sprite(image); final sprite2 = Sprite(image); final spriteAnimation = SpriteAnimation.spriteList( @@ -55,8 +56,9 @@ Future main() async { ); final futureBuilderFinder = find.byType(FutureBuilder); - final spriteAnimationWidgetFinder = - find.byType(InternalSpriteAnimationWidget); + final spriteAnimationWidgetFinder = find.byType( + InternalSpriteAnimationWidget, + ); final loadingWidgetFinder = find.byType(LoadingWidget); expect(futureBuilderFinder, findsOneWidget); diff --git a/packages/flame/test/widgets/sprite_button_test.dart b/packages/flame/test/widgets/sprite_button_test.dart index 25878b606..56342d092 100644 --- a/packages/flame/test/widgets/sprite_button_test.dart +++ b/packages/flame/test/widgets/sprite_button_test.dart @@ -15,8 +15,9 @@ Future main() async { final image = await generateImage(); group('SpriteButton', () { - testWidgets('has no FutureBuilder when passed an animation', - (tester) async { + testWidgets('has no FutureBuilder when passed an animation', ( + tester, + ) async { final sprite1 = Sprite(image); final sprite2 = Sprite(image); diff --git a/packages/flame/test/widgets/sprite_widget_test.dart b/packages/flame/test/widgets/sprite_widget_test.dart index 5eced36f3..ccdb7f22e 100644 --- a/packages/flame/test/widgets/sprite_widget_test.dart +++ b/packages/flame/test/widgets/sprite_widget_test.dart @@ -93,16 +93,18 @@ Future main() async { await tester.pumpAndSettle(); - var internalSpriteWidgetFinder = tester - .widget(find.byType(InternalSpriteWidget)); + var internalSpriteWidgetFinder = tester.widget( + find.byType(InternalSpriteWidget), + ); expect(internalSpriteWidgetFinder.sprite.srcPosition, Vector2(0, 0)); await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); - internalSpriteWidgetFinder = tester - .widget(find.byType(InternalSpriteWidget)); + internalSpriteWidgetFinder = tester.widget( + find.byType(InternalSpriteWidget), + ); expect(internalSpriteWidgetFinder.sprite.srcPosition, Vector2(10, 10)); }); diff --git a/packages/flame_3d/bin/build_shaders.dart b/packages/flame_3d/bin/build_shaders.dart index 442f76739..7bb7d3bee 100644 --- a/packages/flame_3d/bin/build_shaders.dart +++ b/packages/flame_3d/bin/build_shaders.dart @@ -109,8 +109,9 @@ Uri findEngineArtifactsDir({String? dartPath}) { } // We should now have a path of `/path/to/flutter/bin/cache/`. - final engineArtifactsDir = cacheDir - .resolve('./artifacts/engine/'); // Note: The final slash is important. + final engineArtifactsDir = cacheDir.resolve( + './artifacts/engine/', + ); // Note: The final slash is important. return engineArtifactsDir; } diff --git a/packages/flame_3d/example/lib/components/player.dart b/packages/flame_3d/example/lib/components/player.dart index ce26d9be6..72341a243 100644 --- a/packages/flame_3d/example/lib/components/player.dart +++ b/packages/flame_3d/example/lib/components/player.dart @@ -27,15 +27,15 @@ class Player extends MeshComponent Vector3 get lookAt => Vector3(sin(_lookAngle), 0.0, cos(_lookAngle)); Player({required Vector3 position}) - : super( - position: position, - mesh: CuboidMesh( - size: Vector3(1, 2, 1), - material: SpatialMaterial( - albedoTexture: ColorTexture(BasicPalette.yellow.color), - ), + : super( + position: position, + mesh: CuboidMesh( + size: Vector3(1, 2, 1), + material: SpatialMaterial( + albedoTexture: ColorTexture(BasicPalette.yellow.color), ), - ); + ), + ); @override bool onKeyEvent(KeyEvent event, Set keysPressed) { diff --git a/packages/flame_3d/example/lib/components/rotating_light.dart b/packages/flame_3d/example/lib/components/rotating_light.dart index 8ba9cb048..f1eb7609f 100644 --- a/packages/flame_3d/example/lib/components/rotating_light.dart +++ b/packages/flame_3d/example/lib/components/rotating_light.dart @@ -6,11 +6,11 @@ import 'package:flame_3d/game.dart'; class RotatingLight extends LightComponent { RotatingLight() - : super.point( - position: Vector3.zero(), - color: const Color(0xFF00FF00), - intensity: 20.0, - ); + : super.point( + position: Vector3.zero(), + color: const Color(0xFF00FF00), + intensity: 20.0, + ); @override void update(double dt) { diff --git a/packages/flame_3d/example/lib/example_camera_3d.dart b/packages/flame_3d/example/lib/example_camera_3d.dart index 4e3e99709..2f940d07c 100644 --- a/packages/flame_3d/example/lib/example_camera_3d.dart +++ b/packages/flame_3d/example/lib/example_camera_3d.dart @@ -12,14 +12,14 @@ class ExampleCamera3D extends CameraComponent3D Vector2 delta = Vector2.zero(); ExampleCamera3D() - : super( - position: Vector3(0, 2, 4), - projection: CameraProjection.perspective, - viewport: FixedResolutionViewport( - resolution: v64.Vector2(800, 600), - ), - hudComponents: [SimpleHud()], - ); + : super( + position: Vector3(0, 2, 4), + projection: CameraProjection.perspective, + viewport: FixedResolutionViewport( + resolution: v64.Vector2(800, 600), + ), + hudComponents: [SimpleHud()], + ); CameraMode get mode => _mode; diff --git a/packages/flame_3d/example/lib/example_game_3d.dart b/packages/flame_3d/example/lib/example_game_3d.dart index 7c1d6db7d..a482802d9 100644 --- a/packages/flame_3d/example/lib/example_game_3d.dart +++ b/packages/flame_3d/example/lib/example_game_3d.dart @@ -16,10 +16,10 @@ class ExampleGame3D extends FlameGame3D late final Player player; ExampleGame3D() - : super( - world: World3D(clearColor: const Color(0xFFFFFFFF)), - camera: ExampleCamera3D(), - ); + : super( + world: World3D(clearColor: const Color(0xFFFFFFFF)), + camera: ExampleCamera3D(), + ); @override KeyEventResult onKeyEvent( diff --git a/packages/flame_3d/example/pubspec.yaml b/packages/flame_3d/example/pubspec.yaml index fcae84036..fb364e226 100644 --- a/packages/flame_3d/example/pubspec.yaml +++ b/packages/flame_3d/example/pubspec.yaml @@ -5,7 +5,7 @@ version: 0.0.1+1 publish_to: none environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_3d/lib/src/camera/camera_component_3d.dart b/packages/flame_3d/lib/src/camera/camera_component_3d.dart index 1f96ac8cf..fbcd7d3da 100644 --- a/packages/flame_3d/lib/src/camera/camera_component_3d.dart +++ b/packages/flame_3d/lib/src/camera/camera_component_3d.dart @@ -20,10 +20,10 @@ class CameraComponent3D extends CameraComponent { super.viewfinder, super.backdrop, super.hudComponents, - }) : position = position?.clone() ?? Vector3.zero(), - rotation = rotation ?? Quaternion.identity(), - target = target?.clone() ?? Vector3(0, 0, -1), - _up = up?.clone() ?? Vector3(0, 1, 0); + }) : position = position?.clone() ?? Vector3.zero(), + rotation = rotation ?? Quaternion.identity(), + target = target?.clone() ?? Vector3(0, 0, -1), + _up = up?.clone() ?? Vector3(0, 1, 0); @override World3D? get world => super.world as World3D?; @@ -68,21 +68,21 @@ class CameraComponent3D extends CameraComponent { /// The projection matrix of the camera. Matrix4 get projectionMatrix => switch (projection) { - CameraProjection.perspective => _projectionMatrix - ..setAsPerspective( - fovY, - viewport.virtualSize.x / viewport.virtualSize.y, - distanceNear, - distanceFar, - ), - CameraProjection.orthographic => _projectionMatrix - ..setAsOrthographic( - fovY, - viewport.virtualSize.x / viewport.virtualSize.y, - distanceNear, - distanceFar, - ) - }; + CameraProjection.perspective => + _projectionMatrix..setAsPerspective( + fovY, + viewport.virtualSize.x / viewport.virtualSize.y, + distanceNear, + distanceFar, + ), + CameraProjection.orthographic => + _projectionMatrix..setAsOrthographic( + fovY, + viewport.virtualSize.x / viewport.virtualSize.y, + distanceNear, + distanceFar, + ), + }; final Matrix4 _projectionMatrix = Matrix4.zero(); /// The view projection matrix used for rendering. diff --git a/packages/flame_3d/lib/src/components/component_3d.dart b/packages/flame_3d/lib/src/components/component_3d.dart index 3ada2bdb9..8d8249df5 100644 --- a/packages/flame_3d/lib/src/components/component_3d.dart +++ b/packages/flame_3d/lib/src/components/component_3d.dart @@ -38,11 +38,11 @@ abstract class Component3D extends Component with HasWorldReference { Vector3? scale, Quaternion? rotation, List children = const [], - }) : transform = Transform3D() - ..position = position ?? Vector3.zero() - ..rotation = rotation ?? Quaternion.euler(0, 0, 0) - ..scale = scale ?? Vector3.all(1), - super(children: children); + }) : transform = Transform3D() + ..position = position ?? Vector3.zero() + ..rotation = rotation ?? Quaternion.euler(0, 0, 0) + ..scale = scale ?? Vector3.all(1), + super(children: children); /// The total transformation matrix for the component. This matrix combines /// translation, rotation and scale transforms into a single entity. The diff --git a/packages/flame_3d/lib/src/components/light_component.dart b/packages/flame_3d/lib/src/components/light_component.dart index 095d8b6ad..20a91fc69 100644 --- a/packages/flame_3d/lib/src/components/light_component.dart +++ b/packages/flame_3d/lib/src/components/light_component.dart @@ -17,22 +17,22 @@ class LightComponent extends Component3D { Color color = const Color(0xFFFFFFFF), double intensity = 1.0, }) : this( - source: PointLight( - color: color, - intensity: intensity, - ), - position: position, - ); + source: PointLight( + color: color, + intensity: intensity, + ), + position: position, + ); LightComponent.ambient({ Color color = const Color(0xFFFFFFFF), double intensity = 0.2, }) : this( - source: AmbientLight( - color: color, - intensity: intensity, - ), - ); + source: AmbientLight( + color: color, + intensity: intensity, + ), + ); final LightSource source; diff --git a/packages/flame_3d/lib/src/components/line_3d.dart b/packages/flame_3d/lib/src/components/line_3d.dart index eb1c6a92d..e379df153 100644 --- a/packages/flame_3d/lib/src/components/line_3d.dart +++ b/packages/flame_3d/lib/src/components/line_3d.dart @@ -11,12 +11,12 @@ class Line3D extends MeshComponent { required double height, required Color color, }) : super( - mesh: CylinderMesh( - radius: radius, - height: height, - material: SpatialMaterial()..albedoColor = color, - ), - ); + mesh: CylinderMesh( + radius: radius, + height: height, + material: SpatialMaterial()..albedoColor = color, + ), + ); factory Line3D.generate({ required Vector3 start, @@ -78,8 +78,8 @@ class Line3D extends MeshComponent { } static Matrix4 _rotateAroundPoint(Matrix4 rotation, Vector3 point) { - return Matrix4.translation(point) - .multiplied(rotation) - .multiplied(Matrix4.translation(-point)); + return Matrix4.translation( + point, + ).multiplied(rotation).multiplied(Matrix4.translation(-point)); } } diff --git a/packages/flame_3d/lib/src/components/object_3d.dart b/packages/flame_3d/lib/src/components/object_3d.dart index eff41e323..46248c696 100644 --- a/packages/flame_3d/lib/src/components/object_3d.dart +++ b/packages/flame_3d/lib/src/components/object_3d.dart @@ -46,8 +46,7 @@ abstract class Object3D extends Component3D { // // Note(wolfenrain): we should optimize this in the long run it currently // sucks. - priority = -(CameraComponent3D.currentCamera!.position - position) - .length + priority = -(CameraComponent3D.currentCamera!.position - position).length .abs() .toInt(); diff --git a/packages/flame_3d/lib/src/extensions/color.dart b/packages/flame_3d/lib/src/extensions/color.dart index c613f276c..98a181b45 100644 --- a/packages/flame_3d/lib/src/extensions/color.dart +++ b/packages/flame_3d/lib/src/extensions/color.dart @@ -4,9 +4,9 @@ import 'dart:ui'; extension ColorExtension on Color { /// Returns a Float32List that represents the color as a vector. Float32List get storage => Float32List.fromList([ - a, - r, - g, - b, - ]); + a, + r, + g, + b, + ]); } diff --git a/packages/flame_3d/lib/src/game/flame_game_3d.dart b/packages/flame_3d/lib/src/game/flame_game_3d.dart index 1ec37a35e..db66b3c8b 100644 --- a/packages/flame_3d/lib/src/game/flame_game_3d.dart +++ b/packages/flame_3d/lib/src/game/flame_game_3d.dart @@ -10,9 +10,9 @@ class FlameGame3D W? world, C? camera, }) : super( - world: world ?? World3D(clearColor: const Color(0xFFFFFFFF)) as W, - camera: camera ?? CameraComponent3D() as C, - ); + world: world ?? World3D(clearColor: const Color(0xFFFFFFFF)) as W, + camera: camera ?? CameraComponent3D() as C, + ); @override C get camera => super.camera as C; diff --git a/packages/flame_3d/lib/src/game/transform_3d.dart b/packages/flame_3d/lib/src/game/transform_3d.dart index e15b67c69..ebc559efc 100644 --- a/packages/flame_3d/lib/src/game/transform_3d.dart +++ b/packages/flame_3d/lib/src/game/transform_3d.dart @@ -29,11 +29,11 @@ import 'package:flutter/foundation.dart' show ChangeNotifier; class Transform3D extends ChangeNotifier { /// {@macro transform_3d} Transform3D() - : _recalculate = true, - _position = NotifyingVector3.zero(), - _rotation = NotifyingQuaternion(0, 0, 0, 0), - _scale = NotifyingVector3.all(1), - _transformMatrix = Matrix4.zero() { + : _recalculate = true, + _position = NotifyingVector3.zero(), + _rotation = NotifyingQuaternion(0, 0, 0, 0), + _scale = NotifyingVector3.all(1), + _transformMatrix = Matrix4.zero() { _position.addListener(_markAsModified); _scale.addListener(_markAsModified); _rotation.addListener(_markAsModified); diff --git a/packages/flame_3d/lib/src/model/model.dart b/packages/flame_3d/lib/src/model/model.dart index 18b0b10b3..25902d450 100644 --- a/packages/flame_3d/lib/src/model/model.dart +++ b/packages/flame_3d/lib/src/model/model.dart @@ -18,13 +18,13 @@ class Model { Model.simple({ required Mesh mesh, - }) : nodes = { - 0: ModelNode.simple( - nodeIndex: 0, - mesh: mesh, - ), - }, - animations = []; + }) : nodes = { + 0: ModelNode.simple( + nodeIndex: 0, + mesh: mesh, + ), + }, + animations = []; Aabb3 get aabb => _aabb ??= _calculateBoundingBox(); Aabb3? _aabb; diff --git a/packages/flame_3d/lib/src/model/model_animation.dart b/packages/flame_3d/lib/src/model/model_animation.dart index c88122f23..778bc2e96 100644 --- a/packages/flame_3d/lib/src/model/model_animation.dart +++ b/packages/flame_3d/lib/src/model/model_animation.dart @@ -27,8 +27,8 @@ abstract class AnimationSpline { required List times, required List values, }) : values = List.generate(times.length, (index) { - return (time: times[index], value: values[index]); - }); + return (time: times[index], value: values[index]); + }); T lerp(T a, T b, double t); void transform(Matrix4 matrix, T value); diff --git a/packages/flame_3d/lib/src/model/model_node.dart b/packages/flame_3d/lib/src/model/model_node.dart index 887d02c6f..b80fb2a04 100644 --- a/packages/flame_3d/lib/src/model/model_node.dart +++ b/packages/flame_3d/lib/src/model/model_node.dart @@ -23,17 +23,17 @@ class ModelNode { }); List get dependencies => [ - if (parentNodeIndex != null) parentNodeIndex!, - ...joints.values.map((e) => e.nodeIndex), - ]; + if (parentNodeIndex != null) parentNodeIndex!, + ...joints.values.map((e) => e.nodeIndex), + ]; ModelNode.simple({ required this.nodeIndex, required this.mesh, - }) : name = null, - parentNodeIndex = null, - transform = Matrix4.identity(), - joints = {}; + }) : name = null, + parentNodeIndex = null, + transform = Matrix4.identity(), + joints = {}; void processNode( Map processedNodes, @@ -71,24 +71,26 @@ class ModelNode { continue; } - final jointTransforms = (globalToLocalJointMap.entries.toList() - ..sort(Comparing.on((a) => a.value))) - .map((e) => e.key) - .map((jointIndex) { - final joint = joints[jointIndex]; - if (joint == null) { - throw StateError('Missing joint $jointIndex'); - } + final jointTransforms = + (globalToLocalJointMap.entries.toList() + ..sort(Comparing.on((a) => a.value))) + .map((e) => e.key) + .map((jointIndex) { + final joint = joints[jointIndex]; + if (joint == null) { + throw StateError('Missing joint $jointIndex'); + } - final jointNodeIndex = joint.nodeIndex; - final jointNode = processedNodes[jointNodeIndex]; + final jointNodeIndex = joint.nodeIndex; + final jointNode = processedNodes[jointNodeIndex]; - final transform = Matrix4.identity() - ..multiply(jointNode?.combinedTransform ?? Matrix4.identity()) - ..multiply(joint.inverseBindMatrix); + final transform = Matrix4.identity() + ..multiply(jointNode?.combinedTransform ?? Matrix4.identity()) + ..multiply(joint.inverseBindMatrix); - return transform; - }).toList(); + return transform; + }) + .toList(); jointTransformsPerSurface[index] = jointTransforms; } diff --git a/packages/flame_3d/lib/src/parser/gltf/accessor.dart b/packages/flame_3d/lib/src/parser/gltf/accessor.dart index 72b4405d8..0d04718b1 100644 --- a/packages/flame_3d/lib/src/parser/gltf/accessor.dart +++ b/packages/flame_3d/lib/src/parser/gltf/accessor.dart @@ -92,9 +92,11 @@ class RawAccessor extends GltfNode { ); } - for (var cursor = byteOffset; - cursor < bytes.lengthInBytes; - cursor += step) { + for ( + var cursor = byteOffset; + cursor < bytes.lengthInBytes; + cursor += step + ) { yield componentType.parseData(byteData, cursor: cursor); } } @@ -151,9 +153,9 @@ class RawAccessor extends GltfNode { Vector3Accessor asVector3() => Vector3Accessor(root: root, accessor: this); Vector4Accessor asVector4() => Vector4Accessor(root: root, accessor: this); QuaternionAccessor asQuaternion() => QuaternionAccessor( - root: root, - accessor: this, - ); + root: root, + accessor: this, + ); Matrix4Accessor asMatrix4() => Matrix4Accessor(root: root, accessor: this); RawAccessor({ @@ -173,17 +175,17 @@ class RawAccessor extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - bufferView: Parser.ref(root, map, 'bufferView')!, - byteOffset: Parser.integer(map, 'byteOffset') ?? 0, - componentType: ComponentType.parse(map, 'componentType')!, - normalized: Parser.boolean(map, 'normalized') ?? false, - count: Parser.integer(map, 'count')!, - type: AccessorType.parse(map, 'type')!, - max: Parser.floatList(map, 'max'), - min: Parser.floatList(map, 'min'), - sparse: Parser.object(root, map, 'sparse', SparseAccessor.parse), - ); + root: root, + bufferView: Parser.ref(root, map, 'bufferView')!, + byteOffset: Parser.integer(map, 'byteOffset') ?? 0, + componentType: ComponentType.parse(map, 'componentType')!, + normalized: Parser.boolean(map, 'normalized') ?? false, + count: Parser.integer(map, 'count')!, + type: AccessorType.parse(map, 'type')!, + max: Parser.floatList(map, 'max'), + min: Parser.floatList(map, 'min'), + sparse: Parser.object(root, map, 'sparse', SparseAccessor.parse), + ); } abstract class TypedAccessor extends GltfNode { diff --git a/packages/flame_3d/lib/src/parser/gltf/animation.dart b/packages/flame_3d/lib/src/parser/gltf/animation.dart index 4be5bd5be..bae567294 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation.dart @@ -32,21 +32,21 @@ class Animation extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - name: Parser.string(map, 'name'), - channels: Parser.objectList( - root, - map, - 'channels', - AnimationChannel.parse, - )!, - samplers: Parser.objectList( - root, - map, - 'samplers', - AnimationSampler.parse, - )!, - ); + root: root, + name: Parser.string(map, 'name'), + channels: Parser.objectList( + root, + map, + 'channels', + AnimationChannel.parse, + )!, + samplers: Parser.objectList( + root, + map, + 'samplers', + AnimationSampler.parse, + )!, + ); ModelAnimation toFlameAnimation() { final controllers = >{}; @@ -57,24 +57,26 @@ class Animation extends GltfNode { final times = sampler.input.get().typedData(); final values = sampler.output.get(); - final spline = switch (path) { - AnimationPath.translation => TranslationAnimationSpline.from( - interpolation: sampler.interpolation, - times: times, - values: values.asVector3().typedData(), - ), - AnimationPath.scale => ScaleAnimationSpline.from( - interpolation: sampler.interpolation, - times: times, - values: values.asVector3().typedData(), - ), - AnimationPath.rotation => RotationAnimationSpline.from( - interpolation: sampler.interpolation, - times: times, - values: values.asQuaternion().typedData(), - ), - AnimationPath.weights => throw UnimplementedError(), - } as AnimationSpline; + final spline = + switch (path) { + AnimationPath.translation => TranslationAnimationSpline.from( + interpolation: sampler.interpolation, + times: times, + values: values.asVector3().typedData(), + ), + AnimationPath.scale => ScaleAnimationSpline.from( + interpolation: sampler.interpolation, + times: times, + values: values.asVector3().typedData(), + ), + AnimationPath.rotation => RotationAnimationSpline.from( + interpolation: sampler.interpolation, + times: times, + values: values.asQuaternion().typedData(), + ), + AnimationPath.weights => throw UnimplementedError(), + } + as AnimationSpline; final nodeIdx = channel.target.node.index; (controllers[nodeIdx] ??= []).add( diff --git a/packages/flame_3d/lib/src/parser/gltf/animation_channel.dart b/packages/flame_3d/lib/src/parser/gltf/animation_channel.dart index 83f9b58fb..6443abbd3 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation_channel.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation_channel.dart @@ -20,8 +20,8 @@ class AnimationChannel extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - sampler: Parser.integer(map, 'sampler')!, - target: Parser.object(root, map, 'target', AnimationTarget.parse)!, - ); + root: root, + sampler: Parser.integer(map, 'sampler')!, + target: Parser.object(root, map, 'target', AnimationTarget.parse)!, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/animation_sampler.dart b/packages/flame_3d/lib/src/parser/gltf/animation_sampler.dart index ff7e7c665..170dad257 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation_sampler.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation_sampler.dart @@ -30,10 +30,11 @@ class AnimationSampler extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - input: Parser.ref(root, map, 'input')!, - interpolation: AnimationInterpolation.parse(map, 'interpolation') ?? - AnimationInterpolation.linear, - output: Parser.ref(root, map, 'output')!, - ); + root: root, + input: Parser.ref(root, map, 'input')!, + interpolation: + AnimationInterpolation.parse(map, 'interpolation') ?? + AnimationInterpolation.linear, + output: Parser.ref(root, map, 'output')!, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/animation_target.dart b/packages/flame_3d/lib/src/parser/gltf/animation_target.dart index 1833b7213..feb8fb080 100644 --- a/packages/flame_3d/lib/src/parser/gltf/animation_target.dart +++ b/packages/flame_3d/lib/src/parser/gltf/animation_target.dart @@ -30,8 +30,8 @@ class AnimationTarget extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - node: Parser.ref(root, map, 'node')!, - path: AnimationPath.parse(map, 'path')!, - ); + root: root, + node: Parser.ref(root, map, 'node')!, + path: AnimationPath.parse(map, 'path')!, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/buffer.dart b/packages/flame_3d/lib/src/parser/gltf/buffer.dart index a67159c6f..1e25ab568 100644 --- a/packages/flame_3d/lib/src/parser/gltf/buffer.dart +++ b/packages/flame_3d/lib/src/parser/gltf/buffer.dart @@ -19,8 +19,8 @@ class Buffer extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - byteLength: Parser.integer(map, 'byteLength')!, - uri: Parser.string(map, 'uri'), - ); + root: root, + byteLength: Parser.integer(map, 'byteLength')!, + uri: Parser.string(map, 'uri'), + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/buffer_view.dart b/packages/flame_3d/lib/src/parser/gltf/buffer_view.dart index fcd66c1ee..2110d0f0d 100644 --- a/packages/flame_3d/lib/src/parser/gltf/buffer_view.dart +++ b/packages/flame_3d/lib/src/parser/gltf/buffer_view.dart @@ -42,13 +42,13 @@ class BufferView extends GltfNode with GltfNodeWithData { GltfRoot root, Map map, ) : this( - root: root, - buffer: Parser.ref(root, map, 'buffer')!, - byteLength: Parser.integer(map, 'byteLength')!, - byteOffset: Parser.integer(map, 'byteOffset') ?? 0, - byteStride: Parser.integer(map, 'byteStride'), - target: BufferViewTarget.parse(map, 'target'), - ); + root: root, + buffer: Parser.ref(root, map, 'buffer')!, + byteLength: Parser.integer(map, 'byteLength')!, + byteOffset: Parser.integer(map, 'byteOffset') ?? 0, + byteStride: Parser.integer(map, 'byteStride'), + target: BufferViewTarget.parse(map, 'target'), + ); @override Future loadData() async { diff --git a/packages/flame_3d/lib/src/parser/gltf/camera.dart b/packages/flame_3d/lib/src/parser/gltf/camera.dart index 42802fb08..c79b31288 100644 --- a/packages/flame_3d/lib/src/parser/gltf/camera.dart +++ b/packages/flame_3d/lib/src/parser/gltf/camera.dart @@ -35,19 +35,19 @@ class Camera extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - type: CameraType.parse(map, 'type')!, - orthographic: Parser.object( - root, - map, - 'orthographic', - CameraOrthographic.parse, - ), - perspective: Parser.object( - root, - map, - 'perspective', - CameraPerspective.parse, - ), - ); + root: root, + type: CameraType.parse(map, 'type')!, + orthographic: Parser.object( + root, + map, + 'orthographic', + CameraOrthographic.parse, + ), + perspective: Parser.object( + root, + map, + 'perspective', + CameraPerspective.parse, + ), + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/camera_orthographic.dart b/packages/flame_3d/lib/src/parser/gltf/camera_orthographic.dart index ef02528b9..2da34c4f6 100644 --- a/packages/flame_3d/lib/src/parser/gltf/camera_orthographic.dart +++ b/packages/flame_3d/lib/src/parser/gltf/camera_orthographic.dart @@ -34,10 +34,10 @@ class CameraOrthographic extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - xMag: Parser.float(map, 'xmag')!, // cSpell:ignore xmag - yMag: Parser.float(map, 'ymag')!, // cSpell:ignore ymag - xFar: Parser.float(map, 'zfar')!, // cSpell:ignore zfar - zNear: Parser.float(map, 'znear')!, // cSpell:ignore znear - ); + root: root, + xMag: Parser.float(map, 'xmag')!, // cSpell:ignore xmag + yMag: Parser.float(map, 'ymag')!, // cSpell:ignore ymag + xFar: Parser.float(map, 'zfar')!, // cSpell:ignore zfar + zNear: Parser.float(map, 'znear')!, // cSpell:ignore znear + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/camera_perspective.dart b/packages/flame_3d/lib/src/parser/gltf/camera_perspective.dart index d7dbd2ea2..faba0100c 100644 --- a/packages/flame_3d/lib/src/parser/gltf/camera_perspective.dart +++ b/packages/flame_3d/lib/src/parser/gltf/camera_perspective.dart @@ -34,10 +34,10 @@ class CameraPerspective extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - aspectRatio: Parser.float(map, 'aspectRatio'), - yFov: Parser.float(map, 'yfov')!, // cSpell:ignore yfov - zFar: Parser.float(map, 'zfar'), // cSpell:ignore zfar - zNear: Parser.float(map, 'znear')!, // cSpell:ignore znear - ); + root: root, + aspectRatio: Parser.float(map, 'aspectRatio'), + yFov: Parser.float(map, 'yfov')!, // cSpell:ignore yfov + zFar: Parser.float(map, 'zfar'), // cSpell:ignore zfar + zNear: Parser.float(map, 'znear')!, // cSpell:ignore znear + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/gltf_node.dart b/packages/flame_3d/lib/src/parser/gltf/gltf_node.dart index 504f9ef60..5d387599b 100644 --- a/packages/flame_3d/lib/src/parser/gltf/gltf_node.dart +++ b/packages/flame_3d/lib/src/parser/gltf/gltf_node.dart @@ -175,8 +175,9 @@ class Parser { Map map, String key, ) { - return (map[key] as Map?) - ?.map((key, value) => MapEntry(key, value! as int)); + return (map[key] as Map?)?.map( + (key, value) => MapEntry(key, value! as int), + ); } } diff --git a/packages/flame_3d/lib/src/parser/gltf/gltf_root.dart b/packages/flame_3d/lib/src/parser/gltf/gltf_root.dart index 4b449fb4e..6c68fce4a 100644 --- a/packages/flame_3d/lib/src/parser/gltf/gltf_root.dart +++ b/packages/flame_3d/lib/src/parser/gltf/gltf_root.dart @@ -78,28 +78,29 @@ class GltfRoot { T resolve(int index) { return switch (T) { - const (Scene) => scenes[index], - const (Node) => nodes[index], - const (Mesh) => meshes[index], - const (Material) => materials[index], - const (Camera) => cameras[index], - const (Skin) => skins[index], - const (BufferView) => bufferViews[index], - const (Buffer) => buffers[index], - const (Texture) => textures[index], - const (Animation) => animations[index], - const (Sampler) => samplers[index], - const (Image) => images[index], - const (IntAccessor) => accessors[index].asInt(), - const (FloatAccessor) => accessors[index].asFloat(), - const (Vector2Accessor) => accessors[index].asVector2(), - const (Vector3Accessor) => accessors[index].asVector3(), - const (Vector4Accessor) => accessors[index].asVector4(), - const (QuaternionAccessor) => accessors[index].asQuaternion(), - const (Matrix4Accessor) => accessors[index].asMatrix4(), - const (RawAccessor) => accessors[index], - _ => throw UnimplementedError('Cannot resolve type $T') - } as T; + const (Scene) => scenes[index], + const (Node) => nodes[index], + const (Mesh) => meshes[index], + const (Material) => materials[index], + const (Camera) => cameras[index], + const (Skin) => skins[index], + const (BufferView) => bufferViews[index], + const (Buffer) => buffers[index], + const (Texture) => textures[index], + const (Animation) => animations[index], + const (Sampler) => samplers[index], + const (Image) => images[index], + const (IntAccessor) => accessors[index].asInt(), + const (FloatAccessor) => accessors[index].asFloat(), + const (Vector2Accessor) => accessors[index].asVector2(), + const (Vector3Accessor) => accessors[index].asVector3(), + const (Vector4Accessor) => accessors[index].asVector4(), + const (QuaternionAccessor) => accessors[index].asQuaternion(), + const (Matrix4Accessor) => accessors[index].asMatrix4(), + const (RawAccessor) => accessors[index], + _ => throw UnimplementedError('Cannot resolve type $T'), + } + as T; } static Future from({ @@ -150,8 +151,9 @@ class GltfRoot { Model toFlameModel([int? scene]) { return Model( nodes: toFlameNodes(scene), - animations: - animations.map((animation) => animation.toFlameAnimation()).toList(), + animations: animations + .map((animation) => animation.toFlameAnimation()) + .toList(), ); } } diff --git a/packages/flame_3d/lib/src/parser/gltf/image.dart b/packages/flame_3d/lib/src/parser/gltf/image.dart index ee4d1c58b..662e5b8c4 100644 --- a/packages/flame_3d/lib/src/parser/gltf/image.dart +++ b/packages/flame_3d/lib/src/parser/gltf/image.dart @@ -39,11 +39,11 @@ class Image extends GltfNode with GltfNodeWithData { GltfRoot root, Map map, ) : this( - root: root, - uri: Parser.string(map, 'uri'), - mimeType: MimeType.parse(map, 'mimeType'), - bufferView: Parser.ref(root, map, 'bufferView'), - ); + root: root, + uri: Parser.string(map, 'uri'), + mimeType: MimeType.parse(map, 'mimeType'), + bufferView: Parser.ref(root, map, 'bufferView'), + ); Future data() async { final uri = this.uri; diff --git a/packages/flame_3d/lib/src/parser/gltf/material.dart b/packages/flame_3d/lib/src/parser/gltf/material.dart index 1ae4a6e3d..c099ba924 100644 --- a/packages/flame_3d/lib/src/parser/gltf/material.dart +++ b/packages/flame_3d/lib/src/parser/gltf/material.dart @@ -78,33 +78,37 @@ class Material extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - name: Parser.string(map, 'name'), - pbrMetallicRoughness: Parser.object( - root, - map, - 'pbrMetallicRoughness', - PBRMetallicRoughness.parse, - ), - normalTexture: Parser.object( - root, - map, - 'normalTexture', - NormalTextureInfo.parse, - ), - occlusionTexture: Parser.object( - root, - map, - 'occlusionTexture', - OcclusionTextureInfo.parse, - ), - emissiveTexture: - Parser.object(root, map, 'emissiveTexture', TextureInfo.parse), - emissiveFactor: - Parser.vector3(root, map, 'emissiveFactor') ?? Vector3.all(0), - alphaMode: AlphaMode.parse(map, 'alphaMode') ?? AlphaMode.opaque, - doubleSided: Parser.boolean(map, 'doubleSided') ?? false, - ); + root: root, + name: Parser.string(map, 'name'), + pbrMetallicRoughness: Parser.object( + root, + map, + 'pbrMetallicRoughness', + PBRMetallicRoughness.parse, + ), + normalTexture: Parser.object( + root, + map, + 'normalTexture', + NormalTextureInfo.parse, + ), + occlusionTexture: Parser.object( + root, + map, + 'occlusionTexture', + OcclusionTextureInfo.parse, + ), + emissiveTexture: Parser.object( + root, + map, + 'emissiveTexture', + TextureInfo.parse, + ), + emissiveFactor: + Parser.vector3(root, map, 'emissiveFactor') ?? Vector3.all(0), + alphaMode: AlphaMode.parse(map, 'alphaMode') ?? AlphaMode.opaque, + doubleSided: Parser.boolean(map, 'doubleSided') ?? false, + ); flame_3d.Material? toFlameMaterial() { return pbrMetallicRoughness?.toFlameSpatialMaterial(); diff --git a/packages/flame_3d/lib/src/parser/gltf/mesh.dart b/packages/flame_3d/lib/src/parser/gltf/mesh.dart index 42c572ab5..46548443e 100644 --- a/packages/flame_3d/lib/src/parser/gltf/mesh.dart +++ b/packages/flame_3d/lib/src/parser/gltf/mesh.dart @@ -25,11 +25,11 @@ class Mesh extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - primitives: - Parser.objectList(root, map, 'primitives', Primitive.parse) ?? [], - weights: Parser.floatList(map, 'weights'), - ); + root: root, + primitives: + Parser.objectList(root, map, 'primitives', Primitive.parse) ?? [], + weights: Parser.floatList(map, 'weights'), + ); // TODO(luan): remove the transform parameter flame_3d.Mesh toFlameMesh([Matrix4? transform]) { diff --git a/packages/flame_3d/lib/src/parser/gltf/morph_target.dart b/packages/flame_3d/lib/src/parser/gltf/morph_target.dart index 1254661cf..3ae58f60f 100644 --- a/packages/flame_3d/lib/src/parser/gltf/morph_target.dart +++ b/packages/flame_3d/lib/src/parser/gltf/morph_target.dart @@ -21,14 +21,14 @@ class MorphTarget extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - attributes: map.map( - (key, value) => MapEntry( - MorphTargetType.valueOf(key), - GltfRef(root: root, index: value! as int), - ), + root: root, + attributes: map.map( + (key, value) => MapEntry( + MorphTargetType.valueOf(key), + GltfRef(root: root, index: value! as int), ), - ); + ), + ); } enum MorphTargetType { diff --git a/packages/flame_3d/lib/src/parser/gltf/node.dart b/packages/flame_3d/lib/src/parser/gltf/node.dart index d6b56e36e..66757209b 100644 --- a/packages/flame_3d/lib/src/parser/gltf/node.dart +++ b/packages/flame_3d/lib/src/parser/gltf/node.dart @@ -88,20 +88,20 @@ class Node extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - camera: Parser.ref(root, map, 'camera'), - children: Parser.refList(root, map, 'children') ?? [], - skeletons: Parser.refList(root, map, 'skeletons') ?? [], - skin: Parser.ref(root, map, 'skin'), - jointName: Parser.string(map, 'jointName'), - matrix: Parser.matrix4(root, map, 'matrix'), - mesh: Parser.ref(root, map, 'mesh'), - rotation: Parser.quaternion(root, map, 'rotation'), - scale: Parser.vector3(root, map, 'scale'), - translation: Parser.vector3(root, map, 'translation'), - weights: Parser.floatList(map, 'weights'), - name: Parser.string(map, 'name'), - ); + root: root, + camera: Parser.ref(root, map, 'camera'), + children: Parser.refList(root, map, 'children') ?? [], + skeletons: Parser.refList(root, map, 'skeletons') ?? [], + skin: Parser.ref(root, map, 'skin'), + jointName: Parser.string(map, 'jointName'), + matrix: Parser.matrix4(root, map, 'matrix'), + mesh: Parser.ref(root, map, 'mesh'), + rotation: Parser.quaternion(root, map, 'rotation'), + scale: Parser.vector3(root, map, 'scale'), + translation: Parser.vector3(root, map, 'translation'), + weights: Parser.floatList(map, 'weights'), + name: Parser.string(map, 'name'), + ); Matrix4? get _trs { if (translation == null && rotation == null && scale == null) { diff --git a/packages/flame_3d/lib/src/parser/gltf/normal_texture_info.dart b/packages/flame_3d/lib/src/parser/gltf/normal_texture_info.dart index e53fd07df..f1470f06d 100644 --- a/packages/flame_3d/lib/src/parser/gltf/normal_texture_info.dart +++ b/packages/flame_3d/lib/src/parser/gltf/normal_texture_info.dart @@ -26,9 +26,9 @@ class NormalTextureInfo extends TextureInfo { GltfRoot root, Map map, ) : this( - root: root, - index: Parser.ref(root, map, 'index')!, - texCoord: Parser.integer(map, 'texCoord'), - scale: Parser.float(map, 'scale') ?? 1.0, - ); + root: root, + index: Parser.ref(root, map, 'index')!, + texCoord: Parser.integer(map, 'texCoord'), + scale: Parser.float(map, 'scale') ?? 1.0, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/occlusion_texture_info.dart b/packages/flame_3d/lib/src/parser/gltf/occlusion_texture_info.dart index 77e1ad4d8..0bb7223b3 100644 --- a/packages/flame_3d/lib/src/parser/gltf/occlusion_texture_info.dart +++ b/packages/flame_3d/lib/src/parser/gltf/occlusion_texture_info.dart @@ -26,9 +26,9 @@ class OcclusionTextureInfo extends TextureInfo { GltfRoot root, Map map, ) : this( - root: root, - index: Parser.ref(root, map, 'index')!, - texCoord: Parser.integer(map, 'texCoord'), - strength: Parser.float(map, 'strength') ?? 1.0, - ); + root: root, + index: Parser.ref(root, map, 'index')!, + texCoord: Parser.integer(map, 'texCoord'), + strength: Parser.float(map, 'strength') ?? 1.0, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/pbr_metallic_roughness.dart b/packages/flame_3d/lib/src/parser/gltf/pbr_metallic_roughness.dart index 795d95437..9bb5eb428 100644 --- a/packages/flame_3d/lib/src/parser/gltf/pbr_metallic_roughness.dart +++ b/packages/flame_3d/lib/src/parser/gltf/pbr_metallic_roughness.dart @@ -62,23 +62,23 @@ class PBRMetallicRoughness extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - baseColorFactor: Parser.vector4(root, map, 'baseColorFactor'), - baseColorTexture: Parser.object( - root, - map, - 'baseColorTexture', - TextureInfo.parse, - ), - metallicFactor: Parser.float(map, 'metallicFactor') ?? 1.0, - roughnessFactor: Parser.float(map, 'roughnessFactor') ?? 1.0, - metallicRoughnessTexture: Parser.object( - root, - map, - 'metallicRoughnessTexture', - TextureInfo.parse, - ), - ); + root: root, + baseColorFactor: Parser.vector4(root, map, 'baseColorFactor'), + baseColorTexture: Parser.object( + root, + map, + 'baseColorTexture', + TextureInfo.parse, + ), + metallicFactor: Parser.float(map, 'metallicFactor') ?? 1.0, + roughnessFactor: Parser.float(map, 'roughnessFactor') ?? 1.0, + metallicRoughnessTexture: Parser.object( + root, + map, + 'metallicRoughnessTexture', + TextureInfo.parse, + ), + ); flame_3d.SpatialMaterial? toFlameSpatialMaterial() { return flame_3d.SpatialMaterial( diff --git a/packages/flame_3d/lib/src/parser/gltf/primitive.dart b/packages/flame_3d/lib/src/parser/gltf/primitive.dart index 1c5f19d33..bf1a35e57 100644 --- a/packages/flame_3d/lib/src/parser/gltf/primitive.dart +++ b/packages/flame_3d/lib/src/parser/gltf/primitive.dart @@ -71,11 +71,13 @@ class Primitive extends GltfNode { assert(mode == PrimitiveMode.triangles); final positions = this.positions!.get().typedData(); - final indices = this.indices?.get().typedData() ?? + final indices = + this.indices?.get().typedData() ?? // for non-indexed geometries List.generate(positions.length, (i) => i); final texCoords = this.texCoords?.get().typedData(); - final normals = this.normals?.get().typedData() ?? + final normals = + this.normals?.get().typedData() ?? flame_3d.Vertex.calculateVertexNormals(positions, indices); Vector3? process(Vector3? v) { @@ -114,7 +116,8 @@ class Primitive extends GltfNode { vertices: vertices.toList(), indices: indices, jointMap: jointData.jointMap, - material: material?.get().toFlameMaterial() ?? + material: + material?.get().toFlameMaterial() ?? flame_3d.SpatialMaterial( albedoColor: const Color(0xFFFF00FF), ), @@ -172,19 +175,20 @@ class Primitive extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - mode: PrimitiveMode.parse(map, 'mode') ?? PrimitiveMode.triangles, - attributes: Parser.mapInt(map, 'attributes') ?? {}, - indices: Parser.ref(root, map, 'indices'), - material: Parser.ref(root, map, 'material'), - targets: Parser.objectList( - root, - map, - 'targets', - MorphTarget.parse, - ) ?? - [], - ); + root: root, + mode: PrimitiveMode.parse(map, 'mode') ?? PrimitiveMode.triangles, + attributes: Parser.mapInt(map, 'attributes') ?? {}, + indices: Parser.ref(root, map, 'indices'), + material: Parser.ref(root, map, 'material'), + targets: + Parser.objectList( + root, + map, + 'targets', + MorphTarget.parse, + ) ?? + [], + ); } class JointData { diff --git a/packages/flame_3d/lib/src/parser/gltf/sampler.dart b/packages/flame_3d/lib/src/parser/gltf/sampler.dart index 5d0bda246..45c9eba49 100644 --- a/packages/flame_3d/lib/src/parser/gltf/sampler.dart +++ b/packages/flame_3d/lib/src/parser/gltf/sampler.dart @@ -30,11 +30,11 @@ class Sampler extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - magFilter: MagFilter.parse(map, 'magFilter') ?? MagFilter.linear, - minFilter: MinFilter.parse(map, 'minFilter') ?? - MinFilter.nearestMipmapLinear, - wrapS: WrapMode.parse(map, 'wrapS') ?? WrapMode.repeat, - wrapT: WrapMode.parse(map, 'wrapT') ?? WrapMode.repeat, - ); + root: root, + magFilter: MagFilter.parse(map, 'magFilter') ?? MagFilter.linear, + minFilter: + MinFilter.parse(map, 'minFilter') ?? MinFilter.nearestMipmapLinear, + wrapS: WrapMode.parse(map, 'wrapS') ?? WrapMode.repeat, + wrapT: WrapMode.parse(map, 'wrapT') ?? WrapMode.repeat, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/scene.dart b/packages/flame_3d/lib/src/parser/gltf/scene.dart index 825cc405e..ab0db2406 100644 --- a/packages/flame_3d/lib/src/parser/gltf/scene.dart +++ b/packages/flame_3d/lib/src/parser/gltf/scene.dart @@ -19,9 +19,9 @@ class Scene extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - nodes: Parser.refList(root, map, 'nodes')!, - ); + root: root, + nodes: Parser.refList(root, map, 'nodes')!, + ); Map toFlameNodes() { final nodes = {}; diff --git a/packages/flame_3d/lib/src/parser/gltf/skin.dart b/packages/flame_3d/lib/src/parser/gltf/skin.dart index aef22318e..89eff12bf 100644 --- a/packages/flame_3d/lib/src/parser/gltf/skin.dart +++ b/packages/flame_3d/lib/src/parser/gltf/skin.dart @@ -32,9 +32,9 @@ class Skin extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - inverseBindMatrices: Parser.ref(root, map, 'inverseBindMatrices'), - skeleton: Parser.ref(root, map, 'skeleton'), - joints: Parser.refList(root, map, 'joints') ?? [], - ); + root: root, + inverseBindMatrices: Parser.ref(root, map, 'inverseBindMatrices'), + skeleton: Parser.ref(root, map, 'skeleton'), + joints: Parser.refList(root, map, 'joints') ?? [], + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor.dart b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor.dart index 2f23a261a..8f062c4b9 100644 --- a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor.dart +++ b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor.dart @@ -30,19 +30,19 @@ class SparseAccessor extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - count: Parser.integer(map, 'count') ?? 0, - indices: Parser.object( - root, - map, - 'indices', - SparseAccessorIndices.parse, - )!, - values: Parser.object( - root, - map, - 'values', - SparseAccessorValues.parse, - )!, - ); + root: root, + count: Parser.integer(map, 'count') ?? 0, + indices: Parser.object( + root, + map, + 'indices', + SparseAccessorIndices.parse, + )!, + values: Parser.object( + root, + map, + 'values', + SparseAccessorValues.parse, + )!, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_indices.dart b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_indices.dart index 3ce35562c..3f90bb784 100644 --- a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_indices.dart +++ b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_indices.dart @@ -33,9 +33,9 @@ class SparseAccessorIndices extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - bufferView: Parser.ref(root, map, 'bufferView')!, - byteOffset: Parser.integer(map, 'byteOffset') ?? 0, - componentType: ComponentType.parse(map, 'componentType')!, - ); + root: root, + bufferView: Parser.ref(root, map, 'bufferView')!, + byteOffset: Parser.integer(map, 'byteOffset') ?? 0, + componentType: ComponentType.parse(map, 'componentType')!, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_values.dart b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_values.dart index 679f4a493..5e8c6f96a 100644 --- a/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_values.dart +++ b/packages/flame_3d/lib/src/parser/gltf/sparse_accessor_values.dart @@ -29,8 +29,8 @@ class SparseAccessorValues extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - bufferView: Parser.ref(root, map, 'bufferView')!, - byteOffset: Parser.integer(map, 'byteOffset') ?? 0, - ); + root: root, + bufferView: Parser.ref(root, map, 'bufferView')!, + byteOffset: Parser.integer(map, 'byteOffset') ?? 0, + ); } diff --git a/packages/flame_3d/lib/src/parser/gltf/texture.dart b/packages/flame_3d/lib/src/parser/gltf/texture.dart index cdd4d73e3..ca51b88af 100644 --- a/packages/flame_3d/lib/src/parser/gltf/texture.dart +++ b/packages/flame_3d/lib/src/parser/gltf/texture.dart @@ -43,15 +43,15 @@ class Texture extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - format: TextureFormat.parse(map, 'format') ?? TextureFormat.rgba, - internalFormat: - TextureFormat.parse(map, 'internalFormat') ?? TextureFormat.rgba, - sampler: Parser.ref(root, map, 'sampler'), - source: Parser.ref(root, map, 'source')!, - target: TextureTarget.parse(map, 'target') ?? TextureTarget.texture2d, - type: TextureType.parse(map, 'type') ?? TextureType.unsignedByte, - ); + root: root, + format: TextureFormat.parse(map, 'format') ?? TextureFormat.rgba, + internalFormat: + TextureFormat.parse(map, 'internalFormat') ?? TextureFormat.rgba, + sampler: Parser.ref(root, map, 'sampler'), + source: Parser.ref(root, map, 'source')!, + target: TextureTarget.parse(map, 'target') ?? TextureTarget.texture2d, + type: TextureType.parse(map, 'type') ?? TextureType.unsignedByte, + ); flame_3d.Texture toFlameTexture() { // TODO(luan): consider other parameters, such as sampler, type, etc diff --git a/packages/flame_3d/lib/src/parser/gltf/texture_info.dart b/packages/flame_3d/lib/src/parser/gltf/texture_info.dart index 8cad9ba00..831351129 100644 --- a/packages/flame_3d/lib/src/parser/gltf/texture_info.dart +++ b/packages/flame_3d/lib/src/parser/gltf/texture_info.dart @@ -31,10 +31,10 @@ class TextureInfo extends GltfNode { GltfRoot root, Map map, ) : this( - root: root, - index: Parser.ref(root, map, 'index')!, - texCoord: Parser.integer(map, 'texCoord'), - ); + root: root, + index: Parser.ref(root, map, 'index')!, + texCoord: Parser.integer(map, 'texCoord'), + ); flame_3d.Texture toFlameTexture() { return index.get().toFlameTexture(); diff --git a/packages/flame_3d/lib/src/parser/obj/surface_tool.dart b/packages/flame_3d/lib/src/parser/obj/surface_tool.dart index 904da815a..b999829a5 100644 --- a/packages/flame_3d/lib/src/parser/obj/surface_tool.dart +++ b/packages/flame_3d/lib/src/parser/obj/surface_tool.dart @@ -93,13 +93,12 @@ class SurfaceTool { Mesh apply([Mesh? mesh]) { index(); mesh ??= Mesh(); - return mesh - ..addSurface( - Surface( - vertices: _vertices, - indices: _indices, - material: _lastMaterial, - ), - ); + return mesh..addSurface( + Surface( + vertices: _vertices, + indices: _indices, + material: _lastMaterial, + ), + ); } } diff --git a/packages/flame_3d/lib/src/parser/obj_parser.dart b/packages/flame_3d/lib/src/parser/obj_parser.dart index 1959c748b..797316574 100644 --- a/packages/flame_3d/lib/src/parser/obj_parser.dart +++ b/packages/flame_3d/lib/src/parser/obj_parser.dart @@ -163,8 +163,5 @@ class Face { final List texCoord; final List normal; - Face.empty() - : vertex = [], - texCoord = [], - normal = []; + Face.empty() : vertex = [], texCoord = [], normal = []; } diff --git a/packages/flame_3d/lib/src/resources/material/material.dart b/packages/flame_3d/lib/src/resources/material/material.dart index 86e1d2350..9f8715887 100644 --- a/packages/flame_3d/lib/src/resources/material/material.dart +++ b/packages/flame_3d/lib/src/resources/material/material.dart @@ -11,8 +11,8 @@ abstract class Material extends Resource { Material({ required Shader vertexShader, required Shader fragmentShader, - }) : _vertexShader = vertexShader, - _fragmentShader = fragmentShader; + }) : _vertexShader = vertexShader, + _fragmentShader = fragmentShader; @override gpu.RenderPipeline createResource() { diff --git a/packages/flame_3d/lib/src/resources/material/spatial_material.dart b/packages/flame_3d/lib/src/resources/material/spatial_material.dart index d7d9582b2..b2b035529 100644 --- a/packages/flame_3d/lib/src/resources/material/spatial_material.dart +++ b/packages/flame_3d/lib/src/resources/material/spatial_material.dart @@ -10,38 +10,38 @@ class SpatialMaterial extends Material { Color albedoColor = const Color(0xFFFFFFFF), this.metallic = 0.8, this.roughness = 0.6, - }) : albedoTexture = albedoTexture ?? Texture.standard, - super( - vertexShader: Shader.vertex( - asset: - 'packages/flame_3d/assets/shaders/spatial_material.shaderbundle', - slots: [ - UniformSlot.value('VertexInfo', { - 'model', - 'view', - 'projection', - }), - UniformSlot.value( - 'JointMatrices', - List.generate(_maxJoints, (index) => 'joint$index').toSet(), - ), - ], - ), - fragmentShader: Shader.fragment( - asset: - 'packages/flame_3d/assets/shaders/spatial_material.shaderbundle', - slots: [ - UniformSlot.sampler('albedoTexture'), - UniformSlot.value('Material', { - 'albedoColor', - 'metallic', - 'roughness', - }), - ...LightingInfo.shaderSlots, - UniformSlot.value('Camera', {'position'}), - ], - ), - ) { + }) : albedoTexture = albedoTexture ?? Texture.standard, + super( + vertexShader: Shader.vertex( + asset: + 'packages/flame_3d/assets/shaders/spatial_material.shaderbundle', + slots: [ + UniformSlot.value('VertexInfo', { + 'model', + 'view', + 'projection', + }), + UniformSlot.value( + 'JointMatrices', + List.generate(_maxJoints, (index) => 'joint$index').toSet(), + ), + ], + ), + fragmentShader: Shader.fragment( + asset: + 'packages/flame_3d/assets/shaders/spatial_material.shaderbundle', + slots: [ + UniformSlot.sampler('albedoTexture'), + UniformSlot.value('Material', { + 'albedoColor', + 'metallic', + 'roughness', + }), + ...LightingInfo.shaderSlots, + UniformSlot.value('Camera', {'position'}), + ], + ), + ) { this.albedoColor = albedoColor; } diff --git a/packages/flame_3d/lib/src/resources/mesh/surface.dart b/packages/flame_3d/lib/src/resources/mesh/surface.dart index f92578780..089e007b6 100644 --- a/packages/flame_3d/lib/src/resources/mesh/surface.dart +++ b/packages/flame_3d/lib/src/resources/mesh/surface.dart @@ -75,9 +75,9 @@ class Surface extends Resource { final sizeInBytes = _vertices.lengthInBytes + _indices.lengthInBytes; resourceSizeInByes = sizeInBytes; return GpuContextWrapper(gpu.gpuContext).createDeviceBuffer( - gpu.StorageMode.hostVisible, - sizeInBytes, - ) + gpu.StorageMode.hostVisible, + sizeInBytes, + ) ..overwrite(_vertices.asByteData()) ..overwrite( _indices.asByteData(), diff --git a/packages/flame_3d/lib/src/resources/mesh/vertex.dart b/packages/flame_3d/lib/src/resources/mesh/vertex.dart index 06efc48fc..540fbc625 100644 --- a/packages/flame_3d/lib/src/resources/mesh/vertex.dart +++ b/packages/flame_3d/lib/src/resources/mesh/vertex.dart @@ -20,19 +20,19 @@ class Vertex { Vector3? normal, Vector4? joints, Vector4? weights, - }) : position = position.immutable, - texCoord = texCoord.immutable, - normal = normal?.immutable, - joints = joints?.immutable, - weights = weights?.immutable, - _storage = Float32List.fromList([ - ...position.storage, // 1, 2, 3 - ...texCoord.storage, // 4, 5 - ...[color.r, color.g, color.b, color.a], // 6, 7, 8, 9 - ...(normal ?? Vector3.zero()).storage, // 10, 11, 12 - ...(joints ?? Vector4.zero()).storage, // 13, 14, 15, 16 - ...(weights ?? Vector4.zero()).storage, // 17, 18, 19, 20 - ]); + }) : position = position.immutable, + texCoord = texCoord.immutable, + normal = normal?.immutable, + joints = joints?.immutable, + weights = weights?.immutable, + _storage = Float32List.fromList([ + ...position.storage, // 1, 2, 3 + ...texCoord.storage, // 4, 5 + ...[color.r, color.g, color.b, color.a], // 6, 7, 8, 9 + ...(normal ?? Vector3.zero()).storage, // 10, 11, 12 + ...(joints ?? Vector4.zero()).storage, // 13, 14, 15, 16 + ...(weights ?? Vector4.zero()).storage, // 17, 18, 19, 20 + ]); Float32List get storage => _storage; final Float32List _storage; @@ -67,13 +67,13 @@ class Vertex { @override int get hashCode => Object.hashAll([ - position, - texCoord, - normal, - color, - joints, - weights, - ]); + position, + texCoord, + normal, + color, + joints, + weights, + ]); Vertex copyWith({ Vector3? position, diff --git a/packages/flame_3d/lib/src/resources/shader/shader.dart b/packages/flame_3d/lib/src/resources/shader/shader.dart index d512bf4e1..e0de18047 100644 --- a/packages/flame_3d/lib/src/resources/shader/shader.dart +++ b/packages/flame_3d/lib/src/resources/shader/shader.dart @@ -53,10 +53,10 @@ class Shader { }); Shader.vertex({required String asset, required List slots}) - : this(asset: asset, name: 'TextureVertex', slots: slots); + : this(asset: asset, name: 'TextureVertex', slots: slots); Shader.fragment({required String asset, required List slots}) - : this(asset: asset, name: 'TextureFragment', slots: slots); + : this(asset: asset, name: 'TextureFragment', slots: slots); /// Set a [Texture] at the given [key] on the buffer. void setTexture(String key, Texture texture) => _setTypedValue(key, texture); @@ -121,13 +121,15 @@ class Shader { throw StateError('Uniform "$key" is missing an object'); } - final instance = instances.putIfAbsent(object, () { - final slot = slots.firstWhere( - (e) => e.name == object, - orElse: () => throw StateError('Uniform "$object" is unmapped'), - ); - return slot.create(); - }) as UniformInstance; + final instance = + instances.putIfAbsent(object, () { + final slot = slots.firstWhere( + (e) => e.name == object, + orElse: () => throw StateError('Uniform "$object" is unmapped'), + ); + return slot.create(); + }) + as UniformInstance; final k = instance.makeKey(index, field); instance.set(k, value); diff --git a/packages/flame_3d/lib/src/resources/shader/uniform_array.dart b/packages/flame_3d/lib/src/resources/shader/uniform_array.dart index eee9bbb3f..d632de8d2 100644 --- a/packages/flame_3d/lib/src/resources/shader/uniform_array.dart +++ b/packages/flame_3d/lib/src/resources/shader/uniform_array.dart @@ -4,10 +4,7 @@ import 'dart:typed_data'; import 'package:flame_3d/graphics.dart'; import 'package:flame_3d/resources.dart'; -typedef UniformArrayKey = ({ - int idx, - String field, -}); +typedef UniformArrayKey = ({int idx, String field}); /// {@template uniform_value} /// Instance of a uniform array. Represented by a [ByteBuffer]. @@ -25,8 +22,9 @@ class UniformArray extends UniformInstance { var previousIndex = -1; for (final entry in element.entries) { if (previousIndex + 1 != entry.key) { - final field = - slot.fields.indexed.firstWhere((e) => e.$1 == previousIndex + 1); + final field = slot.fields.indexed.firstWhere( + (e) => e.$1 == previousIndex + 1, + ); throw StateError( 'Uniform ${slot.name}.${field.$2} was not set', ); diff --git a/packages/flame_3d/lib/src/resources/shader/uniform_slot.dart b/packages/flame_3d/lib/src/resources/shader/uniform_slot.dart index 4ce59378f..b82636c62 100644 --- a/packages/flame_3d/lib/src/resources/shader/uniform_slot.dart +++ b/packages/flame_3d/lib/src/resources/shader/uniform_slot.dart @@ -10,7 +10,7 @@ import 'package:flutter_gpu/gpu.dart' as gpu; /// {@endtemplate} class UniformSlot extends Resource { UniformSlot._(this.name, this.fields, this._instanceCreator) - : _fieldIndices = {for (var (index, key) in fields.indexed) key: index}; + : _fieldIndices = {for (var (index, key) in fields.indexed) key: index}; /// {@macro uniform_slot} /// @@ -18,7 +18,7 @@ class UniformSlot extends Resource { /// /// The [fields] should be defined in order as they appear in the struct. UniformSlot.value(String name, Set fields) - : this._(name, fields, UniformValue.new); + : this._(name, fields, UniformValue.new); /// {@macro uniform_slot} /// @@ -26,7 +26,7 @@ class UniformSlot extends Resource { /// /// The [fields] should be defined in order as they appear in the struct. UniformSlot.array(String name, Set fields) - : this._(name, fields, UniformArray.new); + : this._(name, fields, UniformArray.new); /// {@macro uniform_slot} /// diff --git a/packages/flame_3d/lib/src/resources/shader/uniform_value.dart b/packages/flame_3d/lib/src/resources/shader/uniform_value.dart index 1953325af..e956628bb 100644 --- a/packages/flame_3d/lib/src/resources/shader/uniform_value.dart +++ b/packages/flame_3d/lib/src/resources/shader/uniform_value.dart @@ -24,8 +24,9 @@ class UniformValue extends UniformInstance { final entries = _storage.entries.toList()..sort(Comparing.on((c) => c.key)); final data = entries.fold>([], (p, e) { if (previousIndex + 1 != e.key) { - final field = - slot.fields.indexed.firstWhere((e) => e.$1 == previousIndex + 1); + final field = slot.fields.indexed.firstWhere( + (e) => e.$1 == previousIndex + 1, + ); throw StateError('Uniform ${slot.name}.${field.$2} was not set'); } previousIndex = e.key; diff --git a/packages/flame_3d/lib/src/resources/texture/color_texture.dart b/packages/flame_3d/lib/src/resources/texture/color_texture.dart index 4b4d161de..2f1c324f1 100644 --- a/packages/flame_3d/lib/src/resources/texture/color_texture.dart +++ b/packages/flame_3d/lib/src/resources/texture/color_texture.dart @@ -9,19 +9,19 @@ import 'package:flame_3d/resources.dart'; class ColorTexture extends Texture { /// {@macro color_texture} ColorTexture(Color color, {int width = 1, int height = 1}) - : super( - Uint32List.fromList( - List.filled( - width * height, - // Convert to a 32 bit value representing this color. - (color.a * 255).round() << 24 | - (color.r * 255).round() << 16 | - (color.g * 255).round() << 8 | - (color.b * 255).round(), - ), - ).buffer.asByteData(), - width: width, - height: height, - format: PixelFormat.bgra8888, - ); + : super( + Uint32List.fromList( + List.filled( + width * height, + // Convert to a 32 bit value representing this color. + (color.a * 255).round() << 24 | + (color.r * 255).round() << 16 | + (color.g * 255).round() << 8 | + (color.b * 255).round(), + ), + ).buffer.asByteData(), + width: width, + height: height, + format: PixelFormat.bgra8888, + ); } diff --git a/packages/flame_3d/pubspec.yaml b/packages/flame_3d/pubspec.yaml index 2b5870477..d40a0f6fa 100644 --- a/packages/flame_3d/pubspec.yaml +++ b/packages/flame_3d/pubspec.yaml @@ -9,7 +9,7 @@ funding: - https://patreon.com/bluefireoss environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_audio/example/pubspec.yaml b/packages/flame_audio/example/pubspec.yaml index 3f2d1603d..66ff28b1f 100644 --- a/packages/flame_audio/example/pubspec.yaml +++ b/packages/flame_audio/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_audio/lib/bgm.dart b/packages/flame_audio/lib/bgm.dart index ca2455fab..80c53985c 100644 --- a/packages/flame_audio/lib/bgm.dart +++ b/packages/flame_audio/lib/bgm.dart @@ -21,8 +21,8 @@ class Bgm extends WidgetsBindingObserver { /// {@macro _bgm} Bgm({AudioCache? audioCache}) - : audioPlayer = AudioPlayer() - ..audioCache = audioCache ?? AudioCache.instance; + : audioPlayer = AudioPlayer() + ..audioCache = audioCache ?? AudioCache.instance; /// Registers a [WidgetsBinding] observer. /// diff --git a/packages/flame_audio/pubspec.yaml b/packages/flame_audio/pubspec.yaml index 287553895..062201889 100644 --- a/packages/flame_audio/pubspec.yaml +++ b/packages/flame_audio/pubspec.yaml @@ -13,7 +13,7 @@ topics: - audio environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/composites/selector.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/composites/selector.dart index a4a12cad8..842657246 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/composites/selector.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/composites/selector.dart @@ -4,7 +4,7 @@ import 'package:behavior_tree/behavior_tree.dart'; class Selector extends BaseNode implements NodeInterface { /// Creates a selector node for given [children] nodes. Selector({List? children}) - : _children = children ?? []; + : _children = children ?? []; final List _children; diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/composites/sequence.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/composites/sequence.dart index 8e32b01b7..d859a603b 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/composites/sequence.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/composites/sequence.dart @@ -4,7 +4,7 @@ import 'package:behavior_tree/behavior_tree.dart'; class Sequence extends BaseNode implements NodeInterface { /// Creates a sequence node for given [children] nodes. Sequence({List? children}) - : _children = children ?? []; + : _children = children ?? []; final List _children; diff --git a/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/limiter.dart b/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/limiter.dart index 57086f604..70b807ed4 100644 --- a/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/limiter.dart +++ b/packages/flame_behavior_tree/behavior_tree/lib/src/decorators/limiter.dart @@ -13,8 +13,9 @@ class Limiter extends BaseNode implements NodeInterface { this.limit, { NodeStatus? statusAfterLimit, }) : _statusAfterLimit = statusAfterLimit { - status = - (_tickCount < limit) ? child.status : _statusAfterLimit ?? child.status; + status = (_tickCount < limit) + ? child.status + : _statusAfterLimit ?? child.status; } var _tickCount = 0; @@ -35,8 +36,9 @@ class Limiter extends BaseNode implements NodeInterface { child.tick(); ++_tickCount; } - status = - (_tickCount < limit) ? child.status : _statusAfterLimit ?? child.status; + status = (_tickCount < limit) + ? child.status + : _statusAfterLimit ?? child.status; } @override diff --git a/packages/flame_behavior_tree/behavior_tree/pubspec.yaml b/packages/flame_behavior_tree/behavior_tree/pubspec.yaml index 2e7520432..00a91e656 100644 --- a/packages/flame_behavior_tree/behavior_tree/pubspec.yaml +++ b/packages/flame_behavior_tree/behavior_tree/pubspec.yaml @@ -9,7 +9,7 @@ funding: - https://patreon.com/bluefireoss environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: meta: ^1.12.0 diff --git a/packages/flame_behavior_tree/example/lib/main.dart b/packages/flame_behavior_tree/example/lib/main.dart index dbf3f83c2..ad7665434 100644 --- a/packages/flame_behavior_tree/example/lib/main.dart +++ b/packages/flame_behavior_tree/example/lib/main.dart @@ -72,7 +72,7 @@ class GameWorld extends World with HasGameReference { class Door extends RectangleComponent with TapCallbacks { Door({super.position, super.size, super.anchor}) - : super(paint: BasicPalette.brown.paint()); + : super(paint: BasicPalette.brown.paint()); bool isOpen = false; bool _isInProgress = false; @@ -117,8 +117,8 @@ class Door extends RectangleComponent with TapCallbacks { class Agent extends PositionComponent with HasBehaviorTree { Agent({required this.door, required this.house, required Vector2 position}) - : _startPosition = position.clone(), - super(position: position); + : _startPosition = position.clone(), + super(position: position); final Door door; final PositionComponent house; diff --git a/packages/flame_behavior_tree/example/pubspec.yaml b/packages/flame_behavior_tree/example/pubspec.yaml index 093982090..a1acbb9a1 100644 --- a/packages/flame_behavior_tree/example/pubspec.yaml +++ b/packages/flame_behavior_tree/example/pubspec.yaml @@ -9,7 +9,7 @@ funding: - https://patreon.com/bluefireoss environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_behavior_tree/pubspec.yaml b/packages/flame_behavior_tree/pubspec.yaml index 6233f2158..14d2cdd12 100644 --- a/packages/flame_behavior_tree/pubspec.yaml +++ b/packages/flame_behavior_tree/pubspec.yaml @@ -11,7 +11,7 @@ topics: - flame environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_behavior_tree/test/has_behavior_tree_test.dart b/packages/flame_behavior_tree/test/has_behavior_tree_test.dart index c7f0d36ec..ec2c33cd7 100644 --- a/packages/flame_behavior_tree/test/has_behavior_tree_test.dart +++ b/packages/flame_behavior_tree/test/has_behavior_tree_test.dart @@ -51,8 +51,9 @@ void main() { 'updates without errors with a valid tree.', (game) async { final component = _BehaviorTreeComponent() - ..treeRoot = - Sequence(children: [alwaysSuccess, alwaysFailure, alwaysRunning]); + ..treeRoot = Sequence( + children: [alwaysSuccess, alwaysFailure, alwaysRunning], + ); expect(() async => await game.add(component), returnsNormally); @@ -69,8 +70,9 @@ void main() { 'tree updates at a slower rate.', (game) async { final component = _BehaviorTreeComponent() - ..treeRoot = - Sequence(children: [alwaysSuccess, alwaysFailure, alwaysRunning]) + ..treeRoot = Sequence( + children: [alwaysSuccess, alwaysFailure, alwaysRunning], + ) ..tickInterval = 1; await game.add(component); diff --git a/packages/flame_bloc/example/lib/src/game/components/enemy.dart b/packages/flame_bloc/example/lib/src/game/components/enemy.dart index 47954d7ea..2a9c64f2a 100644 --- a/packages/flame_bloc/example/lib/src/game/components/enemy.dart +++ b/packages/flame_bloc/example/lib/src/game/components/enemy.dart @@ -11,7 +11,7 @@ class EnemyComponent extends SpriteAnimationComponent bool destroyed = false; EnemyComponent(double x, double y) - : super(position: Vector2(x, y), size: Vector2.all(25)) { + : super(position: Vector2(x, y), size: Vector2.all(25)) { add(RectangleHitbox(collisionType: CollisionType.passive)); } diff --git a/packages/flame_bloc/example/lib/src/game/components/explosion.dart b/packages/flame_bloc/example/lib/src/game/components/explosion.dart index 23f5981a4..a92430ede 100644 --- a/packages/flame_bloc/example/lib/src/game/components/explosion.dart +++ b/packages/flame_bloc/example/lib/src/game/components/explosion.dart @@ -5,11 +5,11 @@ import 'package:flame_bloc_example/src/game/game.dart'; class ExplosionComponent extends SpriteAnimationComponent with HasGameReference { ExplosionComponent(double x, double y) - : super( - position: Vector2(x, y), - size: Vector2.all(50), - removeOnFinish: true, - ); + : super( + position: Vector2(x, y), + size: Vector2.all(50), + removeOnFinish: true, + ); @override Future onLoad() async { diff --git a/packages/flame_bloc/example/lib/src/game/components/player.dart b/packages/flame_bloc/example/lib/src/game/components/player.dart index 27ac8a76a..a69c5f356 100644 --- a/packages/flame_bloc/example/lib/src/game/components/player.dart +++ b/packages/flame_bloc/example/lib/src/game/components/player.dart @@ -38,7 +38,7 @@ class PlayerComponent extends SpriteAnimationComponent late Timer bulletCreator; PlayerComponent() - : super(size: Vector2(50, 75), position: Vector2(100, 500)) { + : super(size: Vector2(50, 75), position: Vector2(100, 500)) { bulletCreator = Timer(0.5, repeat: true, onTick: _createBullet); add(RectangleHitbox()); diff --git a/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_state.dart b/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_state.dart index 1e547a2e0..8fea2020e 100644 --- a/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_state.dart +++ b/packages/flame_bloc/example/lib/src/game_stats/bloc/game_stats_state.dart @@ -19,11 +19,11 @@ class GameStatsState extends Equatable { }); const GameStatsState.empty() - : this( - score: 0, - lives: 3, - status: GameStatus.initial, - ); + : this( + score: 0, + lives: 3, + status: GameStatus.initial, + ); GameStatsState copyWith({ int? score, diff --git a/packages/flame_bloc/example/pubspec.yaml b/packages/flame_bloc/example/pubspec.yaml index a55e0713e..0514549fa 100644 --- a/packages/flame_bloc/example/pubspec.yaml +++ b/packages/flame_bloc/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_bloc/lib/src/flame_bloc_listener.dart b/packages/flame_bloc/lib/src/flame_bloc_listener.dart index 3f0dfd6ec..7359ad668 100644 --- a/packages/flame_bloc/lib/src/flame_bloc_listener.dart +++ b/packages/flame_bloc/lib/src/flame_bloc_listener.dart @@ -15,9 +15,9 @@ class FlameBlocListener, S> extends Component B? bloc, bool Function(S previousState, S newState)? listenWhen, super.key, - }) : _onNewState = onNewState, - _onInitialState = onInitialState, - _listenWhen = listenWhen { + }) : _onNewState = onNewState, + _onInitialState = onInitialState, + _listenWhen = listenWhen { if (bloc != null) { this.bloc = bloc; } diff --git a/packages/flame_bloc/lib/src/flame_bloc_provider.dart b/packages/flame_bloc/lib/src/flame_bloc_provider.dart index d08f1d35d..9db0e5b5a 100644 --- a/packages/flame_bloc/lib/src/flame_bloc_provider.dart +++ b/packages/flame_bloc/lib/src/flame_bloc_provider.dart @@ -15,8 +15,8 @@ class FlameBlocProvider, S> extends Component { required B Function() create, List? children, super.key, - }) : _bloc = create(), - _created = true { + }) : _bloc = create(), + _created = true { _addChildren(children); } @@ -27,8 +27,8 @@ class FlameBlocProvider, S> extends Component { FlameBlocProvider.value({ required B value, List? children, - }) : _bloc = value, - _created = false { + }) : _bloc = value, + _created = false { _addChildren(children); } diff --git a/packages/flame_bloc/lib/src/flame_multi_bloc_provider.dart b/packages/flame_bloc/lib/src/flame_multi_bloc_provider.dart index e1108891e..ba06151df 100644 --- a/packages/flame_bloc/lib/src/flame_multi_bloc_provider.dart +++ b/packages/flame_bloc/lib/src/flame_multi_bloc_provider.dart @@ -12,9 +12,9 @@ class FlameMultiBlocProvider extends Component { required List providers, List? children, super.key, - }) : _providers = providers, - _initialChildren = children, - assert(providers.isNotEmpty, 'At least one provider must be given') { + }) : _providers = providers, + _initialChildren = children, + assert(providers.isNotEmpty, 'At least one provider must be given') { _addProviders(); } diff --git a/packages/flame_bloc/pubspec.yaml b/packages/flame_bloc/pubspec.yaml index 39d25032e..7fbd1ab73 100644 --- a/packages/flame_bloc/pubspec.yaml +++ b/packages/flame_bloc/pubspec.yaml @@ -12,7 +12,7 @@ topics: - state-management environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_bloc/test/src/flame_bloc_listenable_test.dart b/packages/flame_bloc/test/src/flame_bloc_listenable_test.dart index 444329edc..b3af47acd 100644 --- a/packages/flame_bloc/test/src/flame_bloc_listenable_test.dart +++ b/packages/flame_bloc/test/src/flame_bloc_listenable_test.dart @@ -57,8 +57,8 @@ void main() { final bloc = InventoryCubit(); final provider = FlameBlocProvider.value( - value: bloc, - ); + value: bloc, + ); await game.ensureAdd(provider); final component = _PlayerListener(); @@ -131,76 +131,77 @@ void main() { ); testWithFlameGame( - 'successfully revisit previously visited route with bloc listener', - (game) async { - var playerPushCalled = 0; - var playerPopCalled = 0; - var sadPushCalled = 0; - var sadPopCalled = 0; - final router = RouterComponent( - routes: { - 'start': Route(Component.new), - 'playerRoute': _CustomBlocRoute( - onPush: (self, prevRoute) { - playerPushCalled++; - }, - onPop: (self, prevRoute) { - playerPopCalled++; - }, - build: (self) => _PlayerListener(), - ), - 'sadRoute': _CustomBlocRoute( - onPush: (self, prevRoute) { - sadPushCalled++; - }, - onPop: (self, prevRoute) { - sadPopCalled++; - }, - build: (self) => _SadPlayerListener(), - ), - }, - initialRoute: 'start', - ); + 'successfully revisit previously visited route with bloc listener', + (game) async { + var playerPushCalled = 0; + var playerPopCalled = 0; + var sadPushCalled = 0; + var sadPopCalled = 0; + final router = RouterComponent( + routes: { + 'start': Route(Component.new), + 'playerRoute': _CustomBlocRoute( + onPush: (self, prevRoute) { + playerPushCalled++; + }, + onPop: (self, prevRoute) { + playerPopCalled++; + }, + build: (self) => _PlayerListener(), + ), + 'sadRoute': _CustomBlocRoute( + onPush: (self, prevRoute) { + sadPushCalled++; + }, + onPop: (self, prevRoute) { + sadPopCalled++; + }, + build: (self) => _SadPlayerListener(), + ), + }, + initialRoute: 'start', + ); - final bloc = PlayerCubit(); - final provider = FlameBlocProvider.value( - value: bloc, - children: [router], - ); + final bloc = PlayerCubit(); + final provider = FlameBlocProvider.value( + value: bloc, + children: [router], + ); - await game.ensureAdd(provider); + await game.ensureAdd(provider); - //Visit routes first time - router.pushNamed('playerRoute'); - await game.ready(); - expect(router.currentRoute.name, 'playerRoute'); - expect(playerPushCalled, 1); - router.pop(); - await game.ready(); - expect(playerPushCalled, 1); - expect(playerPopCalled, 1); - router.pushNamed('sadRoute'); - await game.ready(); - expect(sadPushCalled, 1); - expect(router.currentRoute.name, 'sadRoute'); - router.pop(); + //Visit routes first time + router.pushNamed('playerRoute'); + await game.ready(); + expect(router.currentRoute.name, 'playerRoute'); + expect(playerPushCalled, 1); + router.pop(); + await game.ready(); + expect(playerPushCalled, 1); + expect(playerPopCalled, 1); + router.pushNamed('sadRoute'); + await game.ready(); + expect(sadPushCalled, 1); + expect(router.currentRoute.name, 'sadRoute'); + router.pop(); - //Revisit playerRoute - await game.ready(); - expect(sadPushCalled, 1); - expect(sadPopCalled, 1); - router.pushNamed('playerRoute'); + //Revisit playerRoute + await game.ready(); + expect(sadPushCalled, 1); + expect(sadPopCalled, 1); + router.pushNamed('playerRoute'); - await game.ready(); - expect(playerPushCalled, 2); - router.pop(); + await game.ready(); + expect(playerPushCalled, 2); + router.pop(); - //Revisit sadRoute - await game.ready(); - router.pushNamed('sadRoute'); - await game.ready(); - expect(sadPushCalled, 2); - }); + //Revisit sadRoute + await game.ready(); + router.pushNamed('sadRoute'); + await game.ready(); + expect(sadPushCalled, 2); + }, + ); }); } @@ -210,10 +211,10 @@ class _CustomBlocRoute extends Route { void Function(Route, Route?)? onPush, void Function(Route, Route)? onPop, Component Function(Route)? build, - }) : _onPush = onPush, - _onPop = onPop, - _build = build, - super(builder); + }) : _onPush = onPush, + _onPop = onPop, + _build = build, + super(builder); final void Function(Route, Route?)? _onPush; final void Function(Route, Route)? _onPop; diff --git a/packages/flame_bloc/test/src/flame_bloc_provider_test.dart b/packages/flame_bloc/test/src/flame_bloc_provider_test.dart index e002493e9..1359a664c 100644 --- a/packages/flame_bloc/test/src/flame_bloc_provider_test.dart +++ b/packages/flame_bloc/test/src/flame_bloc_provider_test.dart @@ -63,11 +63,11 @@ void main() { late _InventoryReader component; final provider = FlameBlocProvider.value( - value: bloc, - children: [ - component = _InventoryReader(), - ], - ); + value: bloc, + children: [ + component = _InventoryReader(), + ], + ); await game.ensureAdd(provider); expect(component.bloc, bloc); @@ -80,11 +80,11 @@ void main() { late _InventoryListener component; final provider = FlameBlocProvider.value( - value: bloc, - children: [ - component = _InventoryListener(), - ], - ); + value: bloc, + children: [ + component = _InventoryListener(), + ], + ); await game.ensureAdd(provider); expect(component.lastState, equals(InventoryState.sword)); }, @@ -94,11 +94,11 @@ void main() { late _InventoryListener component; final provider = FlameBlocProvider.value( - value: bloc, - children: [ - component = _InventoryListener(), - ], - ); + value: bloc, + children: [ + component = _InventoryListener(), + ], + ); await game.ensureAdd(provider); bloc.selectBow(); @@ -128,8 +128,8 @@ void main() { final bloc = InventoryCubit(); final provider = FlameBlocProvider.value( - value: bloc, - ); + value: bloc, + ); await game.ensureAdd(provider); expect(provider.bloc.isClosed, isFalse); diff --git a/packages/flame_bloc/test/src/flame_bloc_reader_test.dart b/packages/flame_bloc/test/src/flame_bloc_reader_test.dart index 385f5a61d..117a5fe4c 100644 --- a/packages/flame_bloc/test/src/flame_bloc_reader_test.dart +++ b/packages/flame_bloc/test/src/flame_bloc_reader_test.dart @@ -17,8 +17,8 @@ void main() { final bloc = InventoryCubit(); final provider = FlameBlocProvider.value( - value: bloc, - ); + value: bloc, + ); await game.ensureAdd(provider); final component = _PlayerReader(); diff --git a/packages/flame_bloc/test/src/flame_multi_bloc_provider_test.dart b/packages/flame_bloc/test/src/flame_multi_bloc_provider_test.dart index d706859f4..4fbdbbc53 100644 --- a/packages/flame_bloc/test/src/flame_multi_bloc_provider_test.dart +++ b/packages/flame_bloc/test/src/flame_multi_bloc_provider_test.dart @@ -90,8 +90,9 @@ void main() { expect(inventory.lastState, equals(InventoryState.bow)); }); - testWithFlameGame('Add and remove a child with two providers', - (game) async { + testWithFlameGame('Add and remove a child with two providers', ( + game, + ) async { final inventoryCubit = InventoryCubit(); final playerCubit = PlayerCubit(); @@ -102,12 +103,12 @@ void main() { providers: [ inventoryCubitProvider = FlameBlocProvider.value( - value: inventoryCubit, - ), + value: inventoryCubit, + ), playerCubitProvider = FlameBlocProvider.value( - value: playerCubit, - ), + value: playerCubit, + ), ], ); await game.ensureAdd(provider); @@ -125,8 +126,9 @@ void main() { }); group('when using children on constructor', () { - testWithFlameGame('Provides multiple blocs down on the tree', - (game) async { + testWithFlameGame('Provides multiple blocs down on the tree', ( + game, + ) async { final inventoryCubit = InventoryCubit(); final playerCubit = PlayerCubit(); diff --git a/packages/flame_console/example/lib/main.dart b/packages/flame_console/example/lib/main.dart index c9aca1fcf..c29e0dd01 100644 --- a/packages/flame_console/example/lib/main.dart +++ b/packages/flame_console/example/lib/main.dart @@ -32,13 +32,12 @@ class _MyGameAppState extends State { game: _game, overlayBuilderMap: { 'console': (BuildContext context, MyGame game) => FlameConsoleView( - game: game, - customCommands: - customCommandsProvider.map((it) => it()).toList(), - onClose: () { - _game.overlays.remove('console'); - }, - ), + game: game, + customCommands: customCommandsProvider.map((it) => it()).toList(), + onClose: () { + _game.overlays.remove('console'); + }, + ), }, ), floatingActionButton: FloatingActionButton( diff --git a/packages/flame_console/example/pubspec.yaml b/packages/flame_console/example/pubspec.yaml index c3de3731d..84ccea8c8 100644 --- a/packages/flame_console/example/pubspec.yaml +++ b/packages/flame_console/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_console/pubspec.yaml b/packages/flame_console/pubspec.yaml index a5de0bc18..819a404e7 100644 --- a/packages/flame_console/pubspec.yaml +++ b/packages/flame_console/pubspec.yaml @@ -13,7 +13,7 @@ topics: - utils environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_devtools/lib/providers/position_component_attributes_provider.dart b/packages/flame_devtools/lib/providers/position_component_attributes_provider.dart index 34e3a5d3e..a38dbfe53 100644 --- a/packages/flame_devtools/lib/providers/position_component_attributes_provider.dart +++ b/packages/flame_devtools/lib/providers/position_component_attributes_provider.dart @@ -1,9 +1,9 @@ import 'package:flame_devtools/repository.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -final positionComponentAttributesProvider = - FutureProvider.autoDispose.family( - (ref, id) async { - return Repository.getPositionComponentAttributes(id: id); - }, -); +final positionComponentAttributesProvider = FutureProvider.autoDispose + .family( + (ref, id) async { + return Repository.getPositionComponentAttributes(id: id); + }, + ); diff --git a/packages/flame_devtools/lib/repository.dart b/packages/flame_devtools/lib/repository.dart index 7a69bcf6d..148443904 100644 --- a/packages/flame_devtools/lib/repository.dart +++ b/packages/flame_devtools/lib/repository.dart @@ -5,28 +5,28 @@ sealed class Repository { Repository._(); static Future getComponentCount() async { - final componentCountResponse = - await serviceManager.callServiceExtensionOnMainIsolate( - 'ext.flame_devtools.getComponentCount', - ); + final componentCountResponse = await serviceManager + .callServiceExtensionOnMainIsolate( + 'ext.flame_devtools.getComponentCount', + ); return componentCountResponse.json!['component_count'] as int; } static Future getComponentTree() async { - final componentTreeResponse = - await serviceManager.callServiceExtensionOnMainIsolate( - 'ext.flame_devtools.getComponentTree', - ); + final componentTreeResponse = await serviceManager + .callServiceExtensionOnMainIsolate( + 'ext.flame_devtools.getComponentTree', + ); return ComponentTreeNode.fromJson( componentTreeResponse.json!['component_tree'] as Map, ); } static Future> getOverlays() async { - final overlaysResponse = - await serviceManager.callServiceExtensionOnMainIsolate( - 'ext.flame_devtools.getOverlays', - ); + final overlaysResponse = await serviceManager + .callServiceExtensionOnMainIsolate( + 'ext.flame_devtools.getOverlays', + ); return List.from(overlaysResponse.json!['overlays'] as List); } @@ -50,11 +50,11 @@ sealed class Repository { } static Future getDebugMode({int? id}) async { - final debugModeResponse = - await serviceManager.callServiceExtensionOnMainIsolate( - 'ext.flame_devtools.getDebugMode', - args: {'id': id}, - ); + final debugModeResponse = await serviceManager + .callServiceExtensionOnMainIsolate( + 'ext.flame_devtools.getDebugMode', + args: {'id': id}, + ); return debugModeResponse.json!['debug_mode'] as bool; } @@ -68,10 +68,10 @@ sealed class Repository { } static Future getPaused() async { - final getPausedResponse = - await serviceManager.callServiceExtensionOnMainIsolate( - 'ext.flame_devtools.getPaused', - ); + final getPausedResponse = await serviceManager + .callServiceExtensionOnMainIsolate( + 'ext.flame_devtools.getPaused', + ); return getPausedResponse.json!['paused'] as bool; } @@ -84,22 +84,22 @@ sealed class Repository { } static Future snapshot({String? id}) async { - final snapshotResponse = - await serviceManager.callServiceExtensionOnMainIsolate( - 'ext.flame_devtools.getComponentSnapshot', - args: {'id': id}, - ); + final snapshotResponse = await serviceManager + .callServiceExtensionOnMainIsolate( + 'ext.flame_devtools.getComponentSnapshot', + args: {'id': id}, + ); return snapshotResponse.json!['snapshot'] as String?; } static Future getPositionComponentAttributes({ int? id, }) async { - final potentialPositionComponentResponse = - await serviceManager.callServiceExtensionOnMainIsolate( - 'ext.flame_devtools.getPositionComponentAttributes', - args: {'id': id}, - ); + final potentialPositionComponentResponse = await serviceManager + .callServiceExtensionOnMainIsolate( + 'ext.flame_devtools.getPositionComponentAttributes', + args: {'id': id}, + ); return PositionComponentAttributes.fromJson( potentialPositionComponentResponse.json!, diff --git a/packages/flame_devtools/lib/widgets/component_tree_model.dart b/packages/flame_devtools/lib/widgets/component_tree_model.dart index 0dced8c3f..8915fc103 100644 --- a/packages/flame_devtools/lib/widgets/component_tree_model.dart +++ b/packages/flame_devtools/lib/widgets/component_tree_model.dart @@ -4,8 +4,9 @@ import 'package:flame_devtools/repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -final selectedTreeNodeProvider = - StateProvider?>((_) => null); +final selectedTreeNodeProvider = StateProvider?>( + (_) => null, +); // This is in a separate provider due to the fact that the tree can't keep // track of whether it has been changed or not since the nodes don't implement @@ -16,8 +17,9 @@ final loadedTreeModelProvider = StateProvider( final componentTreeLoaderProvider = FutureProvider((ref) async { final previousTreeModel = ref.watch(loadedTreeModelProvider); - final updatedModel = - await ComponentTreeModel.refreshComponentTree(previousTreeModel); + final updatedModel = await ComponentTreeModel.refreshComponentTree( + previousTreeModel, + ); if (updatedModel != null) { ref.read(loadedTreeModelProvider.notifier).state = updatedModel; } diff --git a/packages/flame_devtools/pubspec.yaml b/packages/flame_devtools/pubspec.yaml index 767d090db..a9248b23e 100644 --- a/packages/flame_devtools/pubspec.yaml +++ b/packages/flame_devtools/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 0.1.0 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: animated_tree_view: ^2.3.0 diff --git a/packages/flame_fire_atlas/example/lib/main.dart b/packages/flame_fire_atlas/example/lib/main.dart index c5bf7ac8d..b24d7dcbe 100644 --- a/packages/flame_fire_atlas/example/lib/main.dart +++ b/packages/flame_fire_atlas/example/lib/main.dart @@ -27,9 +27,9 @@ class ExampleGame extends FlameGame with TapDetector { add( SpriteAnimationComponent( - size: Vector2(150, 100), - animation: _atlas.getAnimation('bomb_ptero'), - ) + size: Vector2(150, 100), + animation: _atlas.getAnimation('bomb_ptero'), + ) ..y = 50 ..x = 200, ); @@ -56,10 +56,10 @@ class ExampleGame extends FlameGame with TapDetector { void onTapUp(TapUpInfo info) { add( SpriteAnimationComponent( - size: Vector2(100, 100), - animation: _atlas.getAnimation('explosion'), - removeOnFinish: true, - ) + size: Vector2(100, 100), + animation: _atlas.getAnimation('explosion'), + removeOnFinish: true, + ) ..anchor = Anchor.center ..position = info.eventPosition.widget, ); diff --git a/packages/flame_fire_atlas/example/pubspec.yaml b/packages/flame_fire_atlas/example/pubspec.yaml index bfae5b4ed..bf4b87cac 100644 --- a/packages/flame_fire_atlas/example/pubspec.yaml +++ b/packages/flame_fire_atlas/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_fire_atlas/pubspec.yaml b/packages/flame_fire_atlas/pubspec.yaml index c417b899e..757983455 100644 --- a/packages/flame_fire_atlas/pubspec.yaml +++ b/packages/flame_fire_atlas/pubspec.yaml @@ -13,7 +13,7 @@ topics: - tools environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_forge2d/example/lib/main.dart b/packages/flame_forge2d/example/lib/main.dart index 4307fcad1..2c7aa8b03 100644 --- a/packages/flame_forge2d/example/lib/main.dart +++ b/packages/flame_forge2d/example/lib/main.dart @@ -37,20 +37,20 @@ class Forge2DExample extends Forge2DGame { class Ball extends BodyComponent with TapCallbacks { Ball({Vector2? initialPosition}) - : super( - fixtureDefs: [ - FixtureDef( - CircleShape()..radius = 5, - restitution: 0.8, - friction: 0.4, - ), - ], - bodyDef: BodyDef( - angularDamping: 0.8, - position: initialPosition ?? Vector2.zero(), - type: BodyType.dynamic, + : super( + fixtureDefs: [ + FixtureDef( + CircleShape()..radius = 5, + restitution: 0.8, + friction: 0.4, ), - ); + ], + bodyDef: BodyDef( + angularDamping: 0.8, + position: initialPosition ?? Vector2.zero(), + type: BodyType.dynamic, + ), + ); @override void onTapDown(_) { diff --git a/packages/flame_forge2d/example/pubspec.yaml b/packages/flame_forge2d/example/pubspec.yaml index 9027da4c4..449eb0896 100644 --- a/packages/flame_forge2d/example/pubspec.yaml +++ b/packages/flame_forge2d/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_forge2d/lib/contact_callbacks.dart b/packages/flame_forge2d/lib/contact_callbacks.dart index f18edf001..050327843 100644 --- a/packages/flame_forge2d/lib/contact_callbacks.dart +++ b/packages/flame_forge2d/lib/contact_callbacks.dart @@ -44,8 +44,8 @@ mixin class ContactCallbacks { void Function(Object other, Contact contact)? onEndContact; void Function(Object other, Contact contact, Manifold oldManifold)? - onPreSolve; + onPreSolve; void Function(Object other, Contact contact, ContactImpulse impulse)? - onPostSolve; + onPostSolve; } diff --git a/packages/flame_forge2d/lib/forge2d_game.dart b/packages/flame_forge2d/lib/forge2d_game.dart index 5ba665b8c..6ac3b5bb9 100644 --- a/packages/flame_forge2d/lib/forge2d_game.dart +++ b/packages/flame_forge2d/lib/forge2d_game.dart @@ -12,13 +12,15 @@ class Forge2DGame extends FlameGame { ContactListener? contactListener, double zoom = 10, }) : super( - world: ((world?..gravity = gravity ?? world.gravity) ?? - Forge2DWorld( - gravity: gravity, - contactListener: contactListener, - )) as T, - camera: (camera ?? CameraComponent())..viewfinder.zoom = zoom, - ); + world: + ((world?..gravity = gravity ?? world.gravity) ?? + Forge2DWorld( + gravity: gravity, + contactListener: contactListener, + )) + as T, + camera: (camera ?? CameraComponent())..viewfinder.zoom = zoom, + ); /// Takes a point in world coordinates and returns it in screen coordinates. Vector2 worldToScreen(Vector2 position) { diff --git a/packages/flame_forge2d/lib/forge2d_world.dart b/packages/flame_forge2d/lib/forge2d_world.dart index dfc10139a..53888ab6a 100644 --- a/packages/flame_forge2d/lib/forge2d_world.dart +++ b/packages/flame_forge2d/lib/forge2d_world.dart @@ -12,7 +12,7 @@ class Forge2DWorld extends World { forge2d.ContactListener? contactListener, super.children, }) : physicsWorld = forge2d.World(gravity ?? defaultGravity) - ..setContactListener(contactListener ?? WorldContactListener()); + ..setContactListener(contactListener ?? WorldContactListener()); static final Vector2 defaultGravity = Vector2(0, 10.0); diff --git a/packages/flame_forge2d/pubspec.yaml b/packages/flame_forge2d/pubspec.yaml index 9de467a50..e40a1735e 100644 --- a/packages/flame_forge2d/pubspec.yaml +++ b/packages/flame_forge2d/pubspec.yaml @@ -13,7 +13,7 @@ topics: - physics environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_forge2d/test/forge2d_game_test.dart b/packages/flame_forge2d/test/forge2d_game_test.dart index 74a3e9957..197d7532c 100644 --- a/packages/flame_forge2d/test/forge2d_game_test.dart +++ b/packages/flame_forge2d/test/forge2d_game_test.dart @@ -10,74 +10,91 @@ void main() { group( 'Test corresponding position on screen and in the Forge2D world', () { - testWithGame('Center positioned camera should be zero in world', - _TestForge2dGame.new, (game) async { - final size = Vector2.all(100); - game.update(0); - game.onGameResize(size); - expect( - game.screenToWorld(size / 2), - Vector2.zero(), - ); - }); - - testWithGame('Top left position should be converted correctly to world', - _TestForge2dGame.new, (game) async { - final size = Vector2.all(100); - game.onGameResize(size); - expect( - game.screenToWorld(Vector2.zero()), - -(size / 2) / game.camera.viewfinder.zoom, - ); - }); - - testWithGame('Non-zero position should be converted correctly to world', - _TestForge2dGame.new, (game) async { - final size = Vector2.all(100); - final screenPosition = Vector2(10, 20); - game.onGameResize(size); - expect( - game.screenToWorld(screenPosition), - (-size / 2 + screenPosition) / game.camera.viewfinder.zoom, - ); - }); - - testWithGame('Converts a vector in the world space to the screen space', - _TestForge2dGame.new, (game) async { - final size = Vector2.all(100); - game.onGameResize(size); - expect( - game.worldToScreen(Vector2.zero()), - size / 2, - ); - }); + testWithGame( + 'Center positioned camera should be zero in world', + _TestForge2dGame.new, + (game) async { + final size = Vector2.all(100); + game.update(0); + game.onGameResize(size); + expect( + game.screenToWorld(size / 2), + Vector2.zero(), + ); + }, + ); testWithGame( - 'Converts a non-zero vector in the world space to the screen space', - _TestForge2dGame.new, (game) async { - final size = Vector2.all(100); - final worldPosition = Vector2.all(10); - game.onGameResize(size); - expect( - game.worldToScreen(worldPosition), - (size / 2) + worldPosition * game.camera.viewfinder.zoom, - ); - }); + 'Top left position should be converted correctly to world', + _TestForge2dGame.new, + (game) async { + final size = Vector2.all(100); + game.onGameResize(size); + expect( + game.screenToWorld(Vector2.zero()), + -(size / 2) / game.camera.viewfinder.zoom, + ); + }, + ); - testWithGame('Converts worldToScreen correctly with moved viewfinder', - _TestForge2dGame.new, (game) async { - final size = Vector2.all(100); - final worldPosition = Vector2(10, 30); - final viewfinderPosition = Vector2(20, 10); - game.onGameResize(size); - game.camera.viewfinder.position = viewfinderPosition; - expect( - game.worldToScreen(worldPosition), - (size / 2) + - (worldPosition - viewfinderPosition) * - game.camera.viewfinder.zoom, - ); - }); + testWithGame( + 'Non-zero position should be converted correctly to world', + _TestForge2dGame.new, + (game) async { + final size = Vector2.all(100); + final screenPosition = Vector2(10, 20); + game.onGameResize(size); + expect( + game.screenToWorld(screenPosition), + (-size / 2 + screenPosition) / game.camera.viewfinder.zoom, + ); + }, + ); + + testWithGame( + 'Converts a vector in the world space to the screen space', + _TestForge2dGame.new, + (game) async { + final size = Vector2.all(100); + game.onGameResize(size); + expect( + game.worldToScreen(Vector2.zero()), + size / 2, + ); + }, + ); + + testWithGame( + 'Converts a non-zero vector in the world space to the screen space', + _TestForge2dGame.new, + (game) async { + final size = Vector2.all(100); + final worldPosition = Vector2.all(10); + game.onGameResize(size); + expect( + game.worldToScreen(worldPosition), + (size / 2) + worldPosition * game.camera.viewfinder.zoom, + ); + }, + ); + + testWithGame( + 'Converts worldToScreen correctly with moved viewfinder', + _TestForge2dGame.new, + (game) async { + final size = Vector2.all(100); + final worldPosition = Vector2(10, 30); + final viewfinderPosition = Vector2(20, 10); + game.onGameResize(size); + game.camera.viewfinder.position = viewfinderPosition; + expect( + game.worldToScreen(worldPosition), + (size / 2) + + (worldPosition - viewfinderPosition) * + game.camera.viewfinder.zoom, + ); + }, + ); test("Game does not override World's gravity with null", () { final game = Forge2DGame(world: Forge2DWorld(gravity: Vector2(10, 0))); diff --git a/packages/flame_isolate/example/lib/brains/worker_overmind.dart b/packages/flame_isolate/example/lib/brains/worker_overmind.dart index 1b78c0837..71b38f272 100755 --- a/packages/flame_isolate/example/lib/brains/worker_overmind.dart +++ b/packages/flame_isolate/example/lib/brains/worker_overmind.dart @@ -75,12 +75,14 @@ class WorkerOvermind extends Component final shortestQueue = min(idleWorkers.length, _queuedTasks.length); // I know this is not proper handling of lists, but this is just for demo - final localQueue = _queuedTasks - .map((task) => task.first.tilePosition) - .toList(growable: false) - ..shuffle(); - final subQueue = - localQueue.getRange(0, shortestQueue).toList(growable: false); + final localQueue = + _queuedTasks + .map((task) => task.first.tilePosition) + .toList(growable: false) + ..shuffle(); + final subQueue = localQueue + .getRange(0, shortestQueue) + .toList(growable: false); // Commented out since I want to keep jobs in queue for demo // _queuedTasks.removeRange(0, shortestQueue); @@ -97,16 +99,16 @@ class WorkerOvermind extends Component final paths = switch (isolateHud.computeType) { ComputeType.isolate => await isolateCompute( - _calculateWork, - calculateWorkData, - ), + _calculateWork, + calculateWorkData, + ), ComputeType.synchronous => _calculateWork( - calculateWorkData, - ), + calculateWorkData, + ), ComputeType.compute => await compute( - _calculateWork, - calculateWorkData, - ), + _calculateWork, + calculateWorkData, + ), }; for (var i = 0; i < paths.length; i++) { diff --git a/packages/flame_isolate/example/lib/colonists_game.dart b/packages/flame_isolate/example/lib/colonists_game.dart index 693cd326d..760dc2bff 100755 --- a/packages/flame_isolate/example/lib/colonists_game.dart +++ b/packages/flame_isolate/example/lib/colonists_game.dart @@ -18,12 +18,12 @@ class ColonistsGame extends FlameGame with KeyboardEvents { final PositionComponent _cameraPosition = PositionComponent(); late final GameMap _currentMap; ColonistsGame() - : super( - camera: CameraComponent.withFixedResolution( - width: 400, - height: 600, - ), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 400, + height: 600, + ), + ); @override Future onLoad() async { diff --git a/packages/flame_isolate/example/lib/game_map/game_map.dart b/packages/flame_isolate/example/lib/game_map/game_map.dart index 37d6b2f54..b6adcde4c 100755 --- a/packages/flame_isolate/example/lib/game_map/game_map.dart +++ b/packages/flame_isolate/example/lib/game_map/game_map.dart @@ -51,7 +51,8 @@ class GameMap extends Component with HasGameReference { Worker( mapPositions[0] ~/ mapSizeX, mapPositions.removeAt(0) % mapSizeY, - speed: Random().nextDouble() * (workerMaxSpeed - workerMinSpeed) + + speed: + Random().nextDouble() * (workerMaxSpeed - workerMinSpeed) + workerMinSpeed, ), ]; @@ -91,9 +92,9 @@ class GameMap extends Component with HasGameReference { } PathFinderData get pathFinderData => PathFinderData.fromWorld( - terrain: _terrain, - worldObjects: game.worldObjects, - ); + terrain: _terrain, + worldObjects: game.worldObjects, + ); Terrain tileAtPosition(int x, int y) { return _terrain[IntVector2(x, y)]!; diff --git a/packages/flame_isolate/example/lib/objects/colonists_object.dart b/packages/flame_isolate/example/lib/objects/colonists_object.dart index 5b85d14f1..37d1a5da4 100644 --- a/packages/flame_isolate/example/lib/objects/colonists_object.dart +++ b/packages/flame_isolate/example/lib/objects/colonists_object.dart @@ -6,9 +6,9 @@ mixin ColonistsObject on PositionComponent { IntVector2 get tileSize; IntVector2 get tilePosition => IntVector2( - x ~/ Constants.tileSize, - y ~/ Constants.tileSize, - ); + x ~/ Constants.tileSize, + y ~/ Constants.tileSize, + ); } abstract class StaticColonistsObject extends SpriteComponent @@ -22,9 +22,9 @@ abstract class StaticColonistsObject extends SpriteComponent @override IntVector2 get tilePosition => IntVector2( - x ~/ Constants.tileSize, - y ~/ Constants.tileSize, - ); + x ~/ Constants.tileSize, + y ~/ Constants.tileSize, + ); StaticColonistsObject(int x, int y) { sprite = objectSprite; diff --git a/packages/flame_isolate/example/lib/units/actions/movable.dart b/packages/flame_isolate/example/lib/units/actions/movable.dart index 474356277..d7e35f655 100755 --- a/packages/flame_isolate/example/lib/units/actions/movable.dart +++ b/packages/flame_isolate/example/lib/units/actions/movable.dart @@ -115,11 +115,10 @@ class PathLine extends ShapeComponent { } static Path _toPath(List points) { - return Path() - ..addPolygon( - points.map((p) => p.toOffset()).toList(growable: false), - false, - ); + return Path()..addPolygon( + points.map((p) => p.toOffset()).toList(growable: false), + false, + ); } void getGone() { diff --git a/packages/flame_isolate/example/pubspec.yaml b/packages/flame_isolate/example/pubspec.yaml index 7e69c7161..de247917a 100755 --- a/packages/flame_isolate/example/pubspec.yaml +++ b/packages/flame_isolate/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_isolate/pubspec.yaml b/packages/flame_isolate/pubspec.yaml index 23555b0e0..fbfc47888 100644 --- a/packages/flame_isolate/pubspec.yaml +++ b/packages/flame_isolate/pubspec.yaml @@ -8,7 +8,7 @@ topics: - isolate environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_jenny/jenny/lib/src/command_storage.dart b/packages/flame_jenny/jenny/lib/src/command_storage.dart index febb3a073..a1bfbbf2f 100644 --- a/packages/flame_jenny/jenny/lib/src/command_storage.dart +++ b/packages/flame_jenny/jenny/lib/src/command_storage.dart @@ -42,8 +42,10 @@ class CommandStorage { /// Registers a 2-arguments function [fn] as a custom yarn command [name]. void addCommand2(String name, FutureOr Function(T1, T2) fn) { _checkName(name); - _commands[name] = - _Cmd(name, [T1, T2], (List args) => fn(args[0] as T1, args[1] as T2)); + _commands[name] = _Cmd(name, [ + T1, + T2, + ], (List args) => fn(args[0] as T1, args[1] as T2)); } /// Registers a 3-arguments function [fn] as a custom yarn command [name]. @@ -163,10 +165,11 @@ class CommandStorage { /// dynamically from the Yarn runtime. class _Cmd { _Cmd(this.name, List types, this._wrappedFn) - : _signature = _unpackTypes(types), - _arguments = List.filled(types.length, null) { - numTrailingBooleans = - _signature.reversed.takeWhile((type) => type == _Type.boolean).length; + : _signature = _unpackTypes(types), + _arguments = List.filled(types.length, null) { + numTrailingBooleans = _signature.reversed + .takeWhile((type) => type == _Type.boolean) + .length; } final String name; diff --git a/packages/flame_jenny/jenny/lib/src/dialogue_runner.dart b/packages/flame_jenny/jenny/lib/src/dialogue_runner.dart index 9f112de79..82a919f1f 100644 --- a/packages/flame_jenny/jenny/lib/src/dialogue_runner.dart +++ b/packages/flame_jenny/jenny/lib/src/dialogue_runner.dart @@ -39,8 +39,8 @@ class DialogueRunner { DialogueRunner({ required YarnProject yarnProject, required List dialogueViews, - }) : project = yarnProject, - _dialogueViews = dialogueViews; + }) : project = yarnProject, + _dialogueViews = dialogueViews; final List _dialogueViews; _LineDeliveryPipeline? _linePipeline; @@ -255,8 +255,8 @@ class DialogueRunner { class _LineDeliveryPipeline { _LineDeliveryPipeline(this.line, this.views) - : _completer = Completer(), - _futures = List.generate(views.length, (i) => null, growable: false); + : _completer = Completer(), + _futures = List.generate(views.length, (i) => null, growable: false); final DialogueLine line; final List views; diff --git a/packages/flame_jenny/jenny/lib/src/function_storage.dart b/packages/flame_jenny/jenny/lib/src/function_storage.dart index cc036de4c..b06b9f11f 100644 --- a/packages/flame_jenny/jenny/lib/src/function_storage.dart +++ b/packages/flame_jenny/jenny/lib/src/function_storage.dart @@ -59,8 +59,10 @@ class FunctionStorage { /// Registers a two-argument function [fn] with the given [name]. void addFunction2(String name, T0 Function(T1, T2) fn) { _checkName(name); - _functions[name] = - Udf(name, T0, [T1, T2], (args) => fn(args[0] as T1, args[1] as T2)); + _functions[name] = Udf(name, T0, [ + T1, + T2, + ], (args) => fn(args[0] as T1, args[1] as T2)); } /// Registers a three-argument function [fn] with the given [name]. @@ -142,10 +144,10 @@ class FunctionStorage { @internal class Udf { Udf(this.name, Type returnType, List types, this._wrappedFn) - : _returnType = _convertReturnType(returnType), - _argumentTypes = _convertArgumentTypes(types), - _nOptionalArguments = _countOptionalArguments(types), - _preparedArguments = List.filled(types.length, null); + : _returnType = _convertReturnType(returnType), + _argumentTypes = _convertArgumentTypes(types), + _nOptionalArguments = _countOptionalArguments(types), + _preparedArguments = List.filled(types.length, null); final String name; final ExpressionType _returnType; @@ -189,7 +191,8 @@ class Udf { for (var i = 0; i < args.length; i++) { final argType = args[i].expression.type; final expectedType = _argumentTypes[i + i0]; - final typesAreCompatible = false || + final typesAreCompatible = + false || (argType == ExpressionType.boolean && expectedType == _Type.boolean) || (argType == ExpressionType.numeric && @@ -281,7 +284,8 @@ class Udf { static int _countOptionalArguments(List types) { var nOptionalArguments = 0; for (final type in types) { - final isOptional = false || + final isOptional = + false || (type == _maybeInt) || (type == _maybeBool) || (type == _maybeDouble) || diff --git a/packages/flame_jenny/jenny/lib/src/parse/parse.dart b/packages/flame_jenny/jenny/lib/src/parse/parse.dart index 0cb883201..f142467f6 100644 --- a/packages/flame_jenny/jenny/lib/src/parse/parse.dart +++ b/packages/flame_jenny/jenny/lib/src/parse/parse.dart @@ -571,8 +571,9 @@ class _Parser { } else { nameError('variable $variableName has not been declared'); } - final variableExpression = - variableStorage.getVariableAsExpression(variableName); + final variableExpression = variableStorage.getVariableAsExpression( + variableName, + ); position += 1; final assignmentToken = peekToken(); @@ -630,7 +631,7 @@ class _Parser { nameError( isLocal ? 'variable $variableName shadows a global variable with the ' - 'same name' + 'same name' : 'variable $variableName has already been declared', ); } diff --git a/packages/flame_jenny/jenny/lib/src/parse/token.dart b/packages/flame_jenny/jenny/lib/src/parse/token.dart index d2d30a132..1d8873d27 100644 --- a/packages/flame_jenny/jenny/lib/src/parse/token.dart +++ b/packages/flame_jenny/jenny/lib/src/parse/token.dart @@ -49,8 +49,9 @@ class Token { static const operatorDivide = Token._(TokenType.operatorDivide); static const operatorDivideAssign = Token._(TokenType.operatorDivideAssign); static const operatorEqual = Token._(TokenType.operatorEqual); - static const operatorGreaterOrEqual = - Token._(TokenType.operatorGreaterOrEqual); + static const operatorGreaterOrEqual = Token._( + TokenType.operatorGreaterOrEqual, + ); static const operatorGreaterThan = Token._(TokenType.operatorGreaterThan); static const operatorLessOrEqual = Token._(TokenType.operatorLessOrEqual); static const operatorLessThan = Token._(TokenType.operatorLessThan); @@ -59,8 +60,9 @@ class Token { static const operatorModulo = Token._(TokenType.operatorModulo); static const operatorModuloAssign = Token._(TokenType.operatorModuloAssign); static const operatorMultiply = Token._(TokenType.operatorMultiply); - static const operatorMultiplyAssign = - Token._(TokenType.operatorMultiplyAssign); + static const operatorMultiplyAssign = Token._( + TokenType.operatorMultiplyAssign, + ); static const operatorNotEqual = Token._(TokenType.operatorNotEqual); static const operatorNot = Token._(TokenType.operatorNot); static const operatorOr = Token._(TokenType.operatorOr); diff --git a/packages/flame_jenny/jenny/lib/src/parse/tokenize.dart b/packages/flame_jenny/jenny/lib/src/parse/tokenize.dart index bb19f419a..5043e5884 100644 --- a/packages/flame_jenny/jenny/lib/src/parse/tokenize.dart +++ b/packages/flame_jenny/jenny/lib/src/parse/tokenize.dart @@ -30,18 +30,18 @@ List tokenize(String input, {int addErrorTokenAtIndex = -2}) { /// produce the same output. class _Lexer { _Lexer(this.text, this.addErrorTokenAtIndex) - : position = 0, - lineNumber = 1, - lineStart = 0, - tokens = [], - modeStack = [], - indentStack = [], - assert( - commandTokens.length == - simpleCommands.length + - bareExpressionCommands.length + - nodeTargetingCommands.length, - ); + : position = 0, + lineNumber = 1, + lineStart = 0, + tokens = [], + modeStack = [], + indentStack = [], + assert( + commandTokens.length == + simpleCommands.length + + bareExpressionCommands.length + + nodeTargetingCommands.length, + ); final String text; final List tokens; @@ -239,8 +239,10 @@ class _Lexer { (eatId() || (eatExpressionStart() && pushMode(modeTextExpression)) || - error('an ID or an expression in curly braces ' - 'expected'))) || + error( + 'an ID or an expression in curly braces ' + 'expected', + ))) || (tokens.last.isCommand && // user-defined commands pushMode(modeCommandText)))) || (eatCommandEnd() && popMode(modeCommand)) || diff --git a/packages/flame_jenny/jenny/lib/src/structure/dialogue_line.dart b/packages/flame_jenny/jenny/lib/src/structure/dialogue_line.dart index f7ba14859..643bbd4ec 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/dialogue_line.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/dialogue_line.dart @@ -46,10 +46,10 @@ class DialogueLine extends DialogueEntry { required LineContent content, Character? character, List? tags, - }) : _content = content, - _character = character, - _tags = tags, - _value = content.isConst ? content.text : null; + }) : _content = content, + _character = character, + _tags = tags, + _value = content.isConst ? content.text : null; final Character? _character; final List? _tags; diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/_common.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/_common.dart index 73454244f..9d5a4fb20 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/_common.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/_common.dart @@ -28,11 +28,12 @@ class FunctionArgument { final int position; } -typedef FunctionBuilder = Expression Function( - List, - YarnProject, - ErrorFn, -); +typedef FunctionBuilder = + Expression Function( + List, + YarnProject, + ErrorFn, + ); /// This is a complete list of all builtin functions in Jenny. /// diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/ceil.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/ceil.dart index 8045d97f2..a61b428ee 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/ceil.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/ceil.dart @@ -12,8 +12,7 @@ class CeilFn extends NumExpression { List args, YarnProject yarnProject, ErrorFn errorFn, - ) => - num1Builder('ceil', CeilFn.new, args, errorFn); + ) => num1Builder('ceil', CeilFn.new, args, errorFn); @override num get value => arg.value.ceil(); diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dec.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dec.dart index 199f28d72..ed6246a0a 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dec.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/dec.dart @@ -13,8 +13,7 @@ class DecFn extends NumExpression { List args, YarnProject yarnProject, ErrorFn errorFn, - ) => - num1Builder('dec', DecFn.new, args, errorFn); + ) => num1Builder('dec', DecFn.new, args, errorFn); @override num get value { diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/decimal.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/decimal.dart index f6e5d36a0..56f563357 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/decimal.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/decimal.dart @@ -16,8 +16,7 @@ class DecimalFn extends NumExpression { List args, YarnProject yarnProject, ErrorFn errorFn, - ) => - num1Builder('decimal', DecimalFn.new, args, errorFn); + ) => num1Builder('decimal', DecimalFn.new, args, errorFn); @override num get value { diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/floor.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/floor.dart index 23dc0632f..497bd6fc4 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/floor.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/floor.dart @@ -12,8 +12,7 @@ class FloorFn extends NumExpression { List args, YarnProject yarnProject, ErrorFn errorFn, - ) => - num1Builder('floor', FloorFn.new, args, errorFn); + ) => num1Builder('floor', FloorFn.new, args, errorFn); @override num get value => arg.value.floor(); diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/inc.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/inc.dart index 89489c308..b55ab026a 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/inc.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/inc.dart @@ -13,8 +13,7 @@ class IncFn extends NumExpression { List args, YarnProject yarnProject, ErrorFn errorFn, - ) => - num1Builder('inc', IncFn.new, args, errorFn); + ) => num1Builder('inc', IncFn.new, args, errorFn); @override num get value { diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/int.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/int.dart index c386a7e8f..4687810ae 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/int.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/int.dart @@ -12,8 +12,7 @@ class IntFn extends NumExpression { List args, YarnProject yarnProject, ErrorFn errorFn, - ) => - num1Builder('int', IntFn.new, args, errorFn); + ) => num1Builder('int', IntFn.new, args, errorFn); @override num get value => arg.value.truncate(); diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round.dart index 72de3405d..e534aeb05 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/functions/round.dart @@ -12,8 +12,7 @@ class RoundFn extends NumExpression { List args, YarnProject yarnProject, ErrorFn errorFn, - ) => - num1Builder('round', RoundFn.new, args, errorFn); + ) => num1Builder('round', RoundFn.new, args, errorFn); @override num get value => arg.value.round(); diff --git a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/_common.dart b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/_common.dart index fb0a541be..4e6a73585 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/_common.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/expressions/operators/_common.dart @@ -16,12 +16,13 @@ import 'package:jenny/src/structure/expressions/operators/subtract.dart'; import 'package:jenny/src/structure/expressions/operators/xor.dart'; typedef ErrorFn = Never Function(String message, [int? position]); -typedef BinaryOperatorBuilder = Expression Function( - Expression lhs, - Expression rhs, - int operatorPosition, - ErrorFn errorFn, -); +typedef BinaryOperatorBuilder = + Expression Function( + Expression lhs, + Expression rhs, + int operatorPosition, + ErrorFn errorFn, + ); /// Static constructor of expressions involving binary operators. Used by /// parse.dart. diff --git a/packages/flame_jenny/jenny/lib/src/structure/markup_attribute.dart b/packages/flame_jenny/jenny/lib/src/structure/markup_attribute.dart index 9b64db83b..00a558750 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/markup_attribute.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/markup_attribute.dart @@ -9,12 +9,12 @@ class MarkupAttribute { int startSubIndex = 0, int endSubIndex = 1, Map? parameters, - ]) : _startTextPosition = startTextPosition + startSubIndex * _subFactor, - _endTextPosition = endTextPosition + endSubIndex * _subFactor, - _start = 0, - _end = 0, - _parameterExpressions = parameters, - _parameterValues = parameters == null ? null : {} { + ]) : _startTextPosition = startTextPosition + startSubIndex * _subFactor, + _endTextPosition = endTextPosition + endSubIndex * _subFactor, + _start = 0, + _end = 0, + _parameterExpressions = parameters, + _parameterValues = parameters == null ? null : {} { reset(); } diff --git a/packages/flame_jenny/jenny/lib/src/structure/node.dart b/packages/flame_jenny/jenny/lib/src/structure/node.dart index c9e7dc221..d312ac883 100644 --- a/packages/flame_jenny/jenny/lib/src/structure/node.dart +++ b/packages/flame_jenny/jenny/lib/src/structure/node.dart @@ -9,9 +9,9 @@ class Node extends Iterable { required Block content, Map? tags, VariableStorage? variables, - }) : _content = content, - _tags = tags, - _variables = variables; + }) : _content = content, + _tags = tags, + _variables = variables; final String title; final Map? _tags; diff --git a/packages/flame_jenny/jenny/lib/src/variable_storage.dart b/packages/flame_jenny/jenny/lib/src/variable_storage.dart index 30ce4c11f..0a8de9fe2 100644 --- a/packages/flame_jenny/jenny/lib/src/variable_storage.dart +++ b/packages/flame_jenny/jenny/lib/src/variable_storage.dart @@ -23,9 +23,9 @@ class VariableStorage { num() => NumericVariable(name, this), bool() => BooleanVariable(name, this), _ => throw DialogueError( - 'Cannot convert variable $name with type ${value.runtimeType} to ' - 'an expression', - ), + 'Cannot convert variable $name with type ${value.runtimeType} to ' + 'an expression', + ), }; } diff --git a/packages/flame_jenny/jenny/lib/src/yarn_project.dart b/packages/flame_jenny/jenny/lib/src/yarn_project.dart index a87ce8289..8eaea1e5b 100644 --- a/packages/flame_jenny/jenny/lib/src/yarn_project.dart +++ b/packages/flame_jenny/jenny/lib/src/yarn_project.dart @@ -20,12 +20,12 @@ import 'package:meta/meta.dart'; /// class YarnProject { YarnProject() - : nodes = {}, - variables = VariableStorage(), - functions = FunctionStorage(), - commands = CommandStorage(), - characters = CharacterStorage(), - random = Random() { + : nodes = {}, + variables = VariableStorage(), + functions = FunctionStorage(), + commands = CommandStorage(), + characters = CharacterStorage(), + random = Random() { locale = 'en'; } diff --git a/packages/flame_jenny/jenny/pubspec.yaml b/packages/flame_jenny/jenny/pubspec.yaml index f09d54d59..adbe228f8 100644 --- a/packages/flame_jenny/jenny/pubspec.yaml +++ b/packages/flame_jenny/jenny/pubspec.yaml @@ -13,7 +13,7 @@ topics: - text environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: meta: ^1.12.0 diff --git a/packages/flame_jenny/jenny/test/dialogue_runner_test.dart b/packages/flame_jenny/jenny/test/dialogue_runner_test.dart index 45de437df..218105eac 100644 --- a/packages/flame_jenny/jenny/test/dialogue_runner_test.dart +++ b/packages/flame_jenny/jenny/test/dialogue_runner_test.dart @@ -67,11 +67,13 @@ void main() { test('DialogueViews with delays', () async { final yarn = YarnProject() ..strictCharacterNames = false - ..parse('title: The Robot and the Mattress\n' - '---\n' - 'Zem: Hello, robot\n' - 'Marvin: Blah\n' - '===\n'); + ..parse( + 'title: The Robot and the Mattress\n' + '---\n' + 'Zem: Hello, robot\n' + 'Marvin: Blah\n' + '===\n', + ); final events = []; final view1 = _DelayedDialogueView( target: events, @@ -123,14 +125,16 @@ void main() { test('dialogue with choices', () async { final yarn = YarnProject() - ..parse('title: X\n---\n' - 'Question?\n' - '-> Hi there\n' - '-> Howdy\n' - ' Greetings to you too\n' - '-> Yo! <>\n' - 'Kk-thx-bye\n' - '===\n'); + ..parse( + 'title: X\n---\n' + 'Question?\n' + '-> Hi there\n' + '-> Howdy\n' + ' Greetings to you too\n' + '-> Yo! <>\n' + 'Kk-thx-bye\n' + '===\n', + ); final view = _RecordingDialogueView(choices: [1]); final dialogue = DialogueRunner(yarnProject: yarn, dialogueViews: [view]); await dialogue.startDialogue('X'); @@ -174,10 +178,12 @@ void main() { test('invalid dialogue choices', () async { final yarn = YarnProject() - ..parse('title:A\n---\n' - '-> Only one\n' - '-> Only two <>\n' - '===\n'); + ..parse( + 'title:A\n---\n' + '-> Only one\n' + '-> Only two <>\n' + '===\n', + ); final view = _RecordingDialogueView(choices: [2, 1]); final dialogue = DialogueRunner(yarnProject: yarn, dialogueViews: [view]); await expectLater( @@ -359,9 +365,9 @@ class _RecordingDialogueView extends DialogueView { List? target, String? name, List? choices, - }) : events = target ?? [], - name = name ?? '*', - choices = choices ?? []; + }) : events = target ?? [], + name = name ?? '*', + choices = choices ?? []; final List events; final String name; diff --git a/packages/flame_jenny/jenny/test/dialogue_view_test.dart b/packages/flame_jenny/jenny/test/dialogue_view_test.dart index 7d8018302..8e03d064b 100644 --- a/packages/flame_jenny/jenny/test/dialogue_view_test.dart +++ b/packages/flame_jenny/jenny/test/dialogue_view_test.dart @@ -257,8 +257,9 @@ class _RecordingDialogueView extends DialogueView { @override Future onChoiceStart(DialogueChoice choice) async { - final options = - [for (final option in choice.options) '[-> ${option.text}]'].join(); + final options = [ + for (final option in choice.options) '[-> ${option.text}]', + ].join(); events.add('onChoiceStart($options)'); return 1; } @@ -331,8 +332,9 @@ class _RecordingDialogueViewAsMixin extends _SomeOtherBaseClass @override Future onChoiceStart(DialogueChoice choice) async { - final options = - [for (final option in choice.options) '[-> ${option.text}]'].join(); + final options = [ + for (final option in choice.options) '[-> ${option.text}]', + ].join(); events.add('onChoiceStart($options)'); return 1; } diff --git a/packages/flame_jenny/jenny/test/function_storage_test.dart b/packages/flame_jenny/jenny/test/function_storage_test.dart index c13d0ded2..b7a0b1d7f 100644 --- a/packages/flame_jenny/jenny/test/function_storage_test.dart +++ b/packages/flame_jenny/jenny/test/function_storage_test.dart @@ -205,9 +205,10 @@ void main() { ), ); expect( - () => YarnProject() - .functions - .addFunction1('test', (int x) => x > 0 ? x : null), + () => YarnProject().functions.addFunction1( + 'test', + (int x) => x > 0 ? x : null, + ), hasTypeError( 'TypeError: Unsupported return type , expected one of: ' 'bool, int, double, num, or String', @@ -233,8 +234,10 @@ void main() { test('misplaced YarnProject argument', () { expect( - () => FunctionStorage() - .addFunction2('test', (int x, YarnProject yarn) => 0), + () => FunctionStorage().addFunction2( + 'test', + (int x, YarnProject yarn) => 0, + ), hasTypeError( 'TypeError: Argument of type YarnProject must be the first in a ' 'function', diff --git a/packages/flame_jenny/jenny/test/parse/parse_test.dart b/packages/flame_jenny/jenny/test/parse/parse_test.dart index e5c12a87d..f6c1e6fb9 100644 --- a/packages/flame_jenny/jenny/test/parse/parse_test.dart +++ b/packages/flame_jenny/jenny/test/parse/parse_test.dart @@ -51,12 +51,14 @@ void main() { test('node with tags', () { // cSpell:ignore Montagues, Capulets final yarn = YarnProject(); - yarn.parse('title: Romeo_v_Juliette\n' - 'requires: Montagues and Capulets\n' - '\n' - '// comment\n' - 'location: fair Verona\n' - '---\n===\n'); + yarn.parse( + 'title: Romeo_v_Juliette\n' + 'requires: Montagues and Capulets\n' + '\n' + '// comment\n' + 'location: fair Verona\n' + '---\n===\n', + ); final node = yarn.nodes['Romeo_v_Juliette']; expect(node, isNotNull); expect(node!.title, 'Romeo_v_Juliette'); @@ -68,44 +70,54 @@ void main() { test('multiple colons', () { expect( () => YarnProject().parse('title:: Hamlet\n---\n===\n'), - hasSyntaxError('SyntaxError: unexpected token\n' - '> at line 1 column 7:\n' - '> title:: Hamlet\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: unexpected token\n' + '> at line 1 column 7:\n' + '> title:: Hamlet\n' + '> ^\n', + ), ); }); test('node without a title', () { expect( () => YarnProject().parse('Title: Despicable Me!\n---\n===\n'), - hasSyntaxError('SyntaxError: node does not have a title\n' - '> at line 2 column 1:\n' - '> ---\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: node does not have a title\n' + '> at line 2 column 1:\n' + '> ---\n' + '> ^\n', + ), ); }); test('node with multiple titles', () { expect( - () => YarnProject().parse('\n' - 'title: one\n' - 'keyword: value\n' - 'title: two\n' - '---\n===\n'), - hasSyntaxError('SyntaxError: a node can only have one title\n' - '> at line 4 column 1:\n' - '> title: two\n' - '> ^\n'), + () => YarnProject().parse( + '\n' + 'title: one\n' + 'keyword: value\n' + 'title: two\n' + '---\n===\n', + ), + hasSyntaxError( + 'SyntaxError: a node can only have one title\n' + '> at line 4 column 1:\n' + '> title: two\n' + '> ^\n', + ), ); }); test('multiple nodes with same titles', () { expect( - () => YarnProject().parse('\n' - 'title: xyz\n' - '---\n===\n' - 'title: xyz\n' - '---\n===\n'), + () => YarnProject().parse( + '\n' + 'title: xyz\n' + '---\n===\n' + 'title: xyz\n' + '---\n===\n', + ), hasNameError( 'NameError: node with title "xyz" has already been defined\n' '> at line 5 column 1:\n' @@ -174,10 +186,12 @@ void main() { test('indent in a body', () { expect( () => YarnProject().parse('title:a\n---\n hi\n===\n'), - hasSyntaxError('SyntaxError: unexpected indent\n' - '> at line 3 column 1:\n' - '> hi\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: unexpected indent\n' + '> at line 3 column 1:\n' + '> hi\n' + '> ^\n', + ), ); }); }); @@ -185,12 +199,14 @@ void main() { group('parseStatementList', () { test('multiple lines', () { final yarn = YarnProject() - ..parse('title: test\n' - '---\n' - 'Jupyter\n' - 'Saturn\n\n' - 'Uranus // LOL\n' - '===\n'); + ..parse( + 'title: test\n' + '---\n' + 'Jupyter\n' + 'Saturn\n\n' + 'Uranus // LOL\n' + '===\n', + ); final lines = yarn.nodes['test']!.lines; expect(lines.length, 3); for (var i = 0; i < 3; i++) { @@ -238,9 +254,11 @@ void main() { test('line starting with an escaped character', () { final yarn = YarnProject() - ..parse('title:A\n---\n' - '\\{ curly text \\}\n' - '===\n'); + ..parse( + 'title:A\n---\n' + '\\{ curly text \\}\n' + '===\n', + ); expect( (yarn.nodes['A']!.lines[0] as DialogueLine).text, '{ curly text }', @@ -251,20 +269,23 @@ void main() { expect( () => YarnProject().parse('title:A\n---\nz <>\n===\n'), hasSyntaxError( - 'SyntaxError: commands are not allowed on a dialogue line\n' - '> at line 3 column 3:\n' - '> z <>\n' - '> ^\n'), + 'SyntaxError: commands are not allowed on a dialogue line\n' + '> at line 3 column 3:\n' + '> z <>\n' + '> ^\n', + ), ); }); test('line with no content but a hashtag', () { expect( () => YarnProject().parse('title:A\n---\n#tag\n===\n'), - hasSyntaxError('SyntaxError: unexpected token\n' - '> at line 3 column 1:\n' - '> #tag\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: unexpected token\n' + '> at line 3 column 1:\n' + '> #tag\n' + '> ^\n', + ), ); }); }); @@ -272,11 +293,13 @@ void main() { group('parseOption', () { test('simple options', () { final yarn = YarnProject() - ..parse('title: test\n---\n' - '-> Alpha\n' - '-> Beta\n' - '-> Gamma\n' - '===\n'); + ..parse( + 'title: test\n---\n' + '-> Alpha\n' + '-> Beta\n' + '-> Gamma\n' + '===\n', + ); final node = yarn.nodes['test']!; expect(node.lines.length, 1); final choiceSet = node.lines.first as DialogueChoice; @@ -294,10 +317,12 @@ void main() { test('speakers in options', () { final yarn = YarnProject() ..strictCharacterNames = false - ..parse('title:A\n---\n' - '-> Alice: Hello!\n' - '-> Bob: Hi: there!\n' - '===\n'); + ..parse( + 'title:A\n---\n' + '-> Alice: Hello!\n' + '-> Bob: Hi: there!\n' + '===\n', + ); final node = yarn.nodes['A']!; final choice = node.lines[0] as DialogueChoice; final option0 = choice.options[0]; @@ -311,13 +336,15 @@ void main() { test('option with a followup dialogue', () { final yarn = YarnProject() - ..parse('title:A\n---\n' - '-> choice one\n' - ' Nice one, James!\n' - ' Back to ya!\n' - '-> choice two\n' - ' My condolences...\n' - '===\n'); + ..parse( + 'title:A\n---\n' + '-> choice one\n' + ' Nice one, James!\n' + ' Back to ya!\n' + '-> choice two\n' + ' My condolences...\n' + '===\n', + ); final node = yarn.nodes['A']!; final choiceSet = node.lines[0] as DialogueChoice; expect(choiceSet.options.length, 2); @@ -349,10 +376,11 @@ void main() { 'title:A\n---\n-> ok! <>\n===\n', ), hasSyntaxError( - 'SyntaxError: only "if" command is allowed for an option\n' - '> at line 3 column 10:\n' - '> -> ok! <>\n' - '> ^\n'), + 'SyntaxError: only "if" command is allowed for an option\n' + '> at line 3 column 10:\n' + '> -> ok! <>\n' + '> ^\n', + ), ); }); @@ -363,10 +391,12 @@ void main() { '-> ok! <>\n' '===\n', ), - hasTypeError('TypeError: the condition in "if" should be boolean\n' - '> at line 3 column 13:\n' - '> -> ok! <>\n' - '> ^\n'), + hasTypeError( + 'TypeError: the condition in "if" should be boolean\n' + '> at line 3 column 13:\n' + '> -> ok! <>\n' + '> ^\n', + ), ); }); @@ -378,11 +408,12 @@ void main() { '===\n', ), hasSyntaxError( - 'SyntaxError: multiple commands are not allowed on an option ' - 'line\n' - '> at line 3 column 20:\n' - '> -> ok! <> <>\n' - '> ^\n'), + 'SyntaxError: multiple commands are not allowed on an option ' + 'line\n' + '> at line 3 column 20:\n' + '> -> ok! <> <>\n' + '> ^\n', + ), ); }); }); @@ -397,11 +428,13 @@ void main() { test('complicated expressions', () { final yarn = YarnProject() - ..parse('title: test\n---\n' - '{(4 - 5)}\n' - '{ 2 + 7 * 3 - 1 }\n' - '{ 44 / (3 - 1) % 15 }\n' - '===\n'); + ..parse( + 'title: test\n---\n' + '{(4 - 5)}\n' + '{ 2 + 7 * 3 - 1 }\n' + '{ 44 / (3 - 1) % 15 }\n' + '===\n', + ); final node = yarn.nodes['test']!; expect(node.lines.length, 3); expect( @@ -441,10 +474,12 @@ void main() { '{ 1 + * 5 }\n' '===\n', ), - hasSyntaxError('SyntaxError: unexpected expression\n' - '> at line 3 column 7:\n' - '> { 1 + * 5 }\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: unexpected expression\n' + '> at line 3 column 7:\n' + '> { 1 + * 5 }\n' + '> ^\n', + ), ); }); @@ -455,10 +490,12 @@ void main() { '{ (12 }\n' '===\n', ), - hasSyntaxError('SyntaxError: missing closing ")"\n' - '> at line 3 column 7:\n' - '> { (12 }\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: missing closing ")"\n' + '> at line 3 column 7:\n' + '> { (12 }\n' + '> ^\n', + ), ); }); @@ -469,10 +506,12 @@ void main() { '{ random_range(1, 3 ()) }\n' '===\n', ), - hasSyntaxError('SyntaxError: unexpected token\n' - '> at line 3 column 21:\n' - '> { random_range(1, 3 ()) }\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: unexpected token\n' + '> at line 3 column 21:\n' + '> { random_range(1, 3 ()) }\n' + '> ^\n', + ), ); }); }); @@ -480,13 +519,15 @@ void main() { group('parseCommand', () { test('<>', () { final yarn = YarnProject() - ..parse('title:A\n---\n' - '< 0>>\n' - ' First!\n' - '<>\n' - ' Second\n' - '<>\n' - '===\n'); + ..parse( + 'title:A\n---\n' + '< 0>>\n' + ' First!\n' + '<>\n' + ' Second\n' + '<>\n' + '===\n', + ); final node = yarn.nodes['A']!; expect(node.lines.length, 1); expect(node.lines[0], isA()); @@ -507,15 +548,17 @@ void main() { test('<>s', () { final yarn = YarnProject() - ..parse('title:A\n---\n' - '<>\n' - ' First!\n' - '<>\n' - ' Second\n' - '<>\n' - ' Third\n' - '<>\n' - '===\n'); + ..parse( + 'title:A\n---\n' + '<>\n' + ' First!\n' + '<>\n' + ' Second\n' + '<>\n' + ' Third\n' + '<>\n' + '===\n', + ); final node = yarn.nodes['A']!; final command = node.lines[0] as IfCommand; expect(command.ifs.length, 3); @@ -527,77 +570,95 @@ void main() { test('no <> 1', () { expect( () => YarnProject() - ..parse('title:A\n---\n' - '<>\n' - ' ha\n' - '===\n'), - hasSyntaxError('SyntaxError: <> expected\n' - '> at line 5 column 1:\n' - '> ===\n' - '> ^\n'), + ..parse( + 'title:A\n---\n' + '<>\n' + ' ha\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: <> expected\n' + '> at line 5 column 1:\n' + '> ===\n' + '> ^\n', + ), ); }); test('no <> 2', () { expect( () => YarnProject() - ..parse('title:A\n---\n' - '<>\n' - '<>\n' - '===\n'), - hasSyntaxError('SyntaxError: <> expected\n' - '> at line 4 column 1:\n' - '> <>\n' - '> ^\n'), + ..parse( + 'title:A\n---\n' + '<>\n' + '<>\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: <> expected\n' + '> at line 4 column 1:\n' + '> <>\n' + '> ^\n', + ), ); }); test('double <>', () { expect( () => YarnProject() - ..parse('title:A\n---\n' - '<>\n' - '<>\n' - '<>\n' - '<>\n' - '===\n'), - hasSyntaxError('SyntaxError: only one <> is allowed\n' - '> at line 5 column 1:\n' - '> <>\n' - '> ^\n'), + ..parse( + 'title:A\n---\n' + '<>\n' + '<>\n' + '<>\n' + '<>\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: only one <> is allowed\n' + '> at line 5 column 1:\n' + '> <>\n' + '> ^\n', + ), ); }); test('no indentation in <>', () { expect( () => YarnProject() - ..parse('title:A\n---\n' - '<>\n' - 'text\n' - '<>\n' - '===\n'), + ..parse( + 'title:A\n---\n' + '<>\n' + 'text\n' + '<>\n' + '===\n', + ), hasSyntaxError( - 'SyntaxError: the body of the <> command must be indented\n' - '> at line 4 column 1:\n' - '> text\n' - '> ^\n'), + 'SyntaxError: the body of the <> command must be indented\n' + '> at line 4 column 1:\n' + '> text\n' + '> ^\n', + ), ); }); test('no indentation in <>', () { expect( () => YarnProject() - ..parse('title:A\n---\n' - '<>\n' - '<>\n' - 'text\n' - '<>\n' - '===\n'), + ..parse( + 'title:A\n---\n' + '<>\n' + '<>\n' + 'text\n' + '<>\n' + '===\n', + ), hasSyntaxError( - 'SyntaxError: the body of the <> command must be indented\n' - '> at line 5 column 1:\n' - '> text\n' - '> ^\n'), + 'SyntaxError: the body of the <> command must be indented\n' + '> at line 5 column 1:\n' + '> text\n' + '> ^\n', + ), ); }); @@ -609,10 +670,12 @@ void main() { '<> <>\n' '===\n', ), - hasSyntaxError('SyntaxError: expected end of line\n' - '> at line 3 column 12:\n' - '> <> <>\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: expected end of line\n' + '> at line 3 column 12:\n' + '> <> <>\n' + '> ^\n', + ), ); }); }); @@ -620,9 +683,11 @@ void main() { group('parseMarkupTag', () { test('parse simple markup tag', () { final yarn = YarnProject() - ..parse('title: A\n---\n' - 'Hello, [big]world[/big]!\n' - '===\n'); + ..parse( + 'title: A\n---\n' + 'Hello, [big]world[/big]!\n' + '===\n', + ); expect(yarn.nodes['A']!.lines.length, 1); final line = yarn.nodes['A']!.lines[0] as DialogueLine; expect(line.text, 'Hello, world!'); @@ -638,9 +703,11 @@ void main() { test('parse self-closing tag', () { final yarn = YarnProject() - ..parse('title: A\n---\n' - 'Hello, [wave /] world!\n' - '===\n'); + ..parse( + 'title: A\n---\n' + 'Hello, [wave /] world!\n' + '===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; final attribute = line.attributes[0]; // Note that the space after the tag was removed @@ -654,9 +721,11 @@ void main() { test('parse nested tags', () { final yarn = YarnProject() ..strictCharacterNames = false - ..parse('title: A\n---\n' - 'Warning: [a]Spinning [b][c]Je[/c]nny[/b][/a]\n' - '===\n'); + ..parse( + 'title: A\n---\n' + 'Warning: [a]Spinning [b][c]Je[/c]nny[/b][/a]\n' + '===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; expect(line.character, isA()); expect(line.character!.name, 'Warning'); @@ -676,9 +745,11 @@ void main() { test('markup tags at start of line', () { final yarn = YarnProject() - ..parse('title: A\n---\n' - '[blue]wave[/blue]\n' - '===\n'); + ..parse( + 'title: A\n---\n' + '[blue]wave[/blue]\n' + '===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; final attribute = line.attributes[0]; expect(line.text, 'wave'); @@ -689,9 +760,11 @@ void main() { test('close-all tag [/]', () { final yarn = YarnProject() - ..parse('title: A\n---\n' - '[a][b][c] hello [/]\n' - '===\n'); + ..parse( + 'title: A\n---\n' + '[a][b][c] hello [/]\n' + '===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; expect(line.text, ' hello '); for (final attribute in line.attributes) { @@ -703,9 +776,11 @@ void main() { test('markup tag with parameters', () { final yarn = YarnProject() - ..parse('title: A\n---\n' - '[color r=0 g=false b=100 name="BLUE"]wave[/color]\n' - '===\n'); + ..parse( + 'title: A\n---\n' + '[color r=0 g=false b=100 name="BLUE"]wave[/color]\n' + '===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; final attr = line.attributes[0]; expect(line.text, 'wave'); @@ -724,9 +799,11 @@ void main() { test('markup tag with bare parameters', () { final yarn = YarnProject() - ..parse('title: A\n---\n' - '[color blue]wave[/color]\n' - '===\n'); + ..parse( + 'title: A\n---\n' + '[color blue]wave[/color]\n' + '===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; final attr = line.attributes[0]; expect(attr.parameters, isNotNull); @@ -738,9 +815,11 @@ void main() { test('markup tags with inline expressions', () { final yarn = YarnProject() ..variables.setVariable(r'$x', 'world') - ..parse('title: A\n---\n' - 'Hello [color]{\$x}[/color]\n' - '===\n'); + ..parse( + 'title: A\n---\n' + 'Hello [color]{\$x}[/color]\n' + '===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; line.evaluate(); expect(line.text, 'Hello world'); @@ -764,9 +843,11 @@ void main() { ..variables.setVariable(r'$x', 'citizen') ..variables.setVariable(r'$y', 'Paradise City') ..variables.setVariable(r'$z', '...') - ..parse('title: A\n---\n' - 'Hello {\$x}, and [color]{\$w} to {\$y}[/color] {\$z}\n' - '===\n'); + ..parse( + 'title: A\n---\n' + 'Hello {\$x}, and [color]{\$w} to {\$y}[/color] {\$z}\n' + '===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; line.evaluate(); expect(line.text, 'Hello citizen, and welcome to Paradise City ...'); @@ -795,9 +876,11 @@ void main() { ..variables.setVariable(r'$x', 'arbitrary ') ..variables.setVariable(r'$y', 'text') ..variables.setVariable(r'$z', '?') - ..parse('title: A\n---\n' - r'{$w}[wavy]{$x}{$y}[/]{$z}' - '\n===\n'); + ..parse( + 'title: A\n---\n' + r'{$w}[wavy]{$x}{$y}[/]{$z}' + '\n===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; line.evaluate(); expect(line.text, 'some arbitrary text?'); @@ -812,9 +895,11 @@ void main() { ..variables.setVariable(r'$x1', 'One') ..variables.setVariable(r'$x2', 'Double') ..variables.setVariable(r'$x3', 'Three') - ..parse('title: A\n---\n' - r'{$x1}[a/]{$x2}[b/]{$x3}' - '\n===\n'); + ..parse( + 'title: A\n---\n' + r'{$x1}[a/]{$x2}[b/]{$x3}' + '\n===\n', + ); final line = yarn.nodes['A']!.lines[0] as DialogueLine; line.evaluate(); expect(line.text, 'OneDoubleThree'); diff --git a/packages/flame_jenny/jenny/test/parse/tokenize_test.dart b/packages/flame_jenny/jenny/test/parse/tokenize_test.dart index d7cca9ce1..c9afd5887 100644 --- a/packages/flame_jenny/jenny/test/parse/tokenize_test.dart +++ b/packages/flame_jenny/jenny/test/parse/tokenize_test.dart @@ -19,11 +19,13 @@ void main() { expect(tokenize('// hello'), const []); expect(tokenize('// world\n\n'), [Token.newline, Token.newline]); expect( - tokenize('\n' - '//--------------------\n' - '// BOILER PLATE \n' - '//--------------------\n' - '\n'), + tokenize( + '\n' + '//--------------------\n' + '// BOILER PLATE \n' + '//--------------------\n' + '\n', + ), const [ Token.newline, Token.newline, @@ -37,10 +39,12 @@ void main() { test('only header separator', () { expect( () => tokenize('---\n'), - hasSyntaxError('SyntaxError: incomplete node body\n' - '> at line 2 column 1:\n' - '> \n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: incomplete node body\n' + '> at line 2 column 1:\n' + '> \n' + '> ^\n', + ), ); }); @@ -82,31 +86,36 @@ void main() { test('simple header', () { expect( - tokenize('\n' - 'title: node: 1\n' - '\n' - '---\n===\n'), - const [ - Token.newline, - Token.startHeader, - Token.id('title'), - Token.colon, - Token.text('node: 1'), - Token.newline, - Token.newline, - Token.endHeader, - Token.startBody, - Token.endBody, - ]); + tokenize( + '\n' + 'title: node: 1\n' + '\n' + '---\n===\n', + ), + const [ + Token.newline, + Token.startHeader, + Token.id('title'), + Token.colon, + Token.text('node: 1'), + Token.newline, + Token.newline, + Token.endHeader, + Token.startBody, + Token.endBody, + ], + ); }); test('multi-line header', () { expect( - tokenize('\n' - 'title: Some Long title\n' - 'title : Another title\n' - 'some_other_keyword:1\n' - '---\n===\n'), + tokenize( + '\n' + 'title: Some Long title\n' + 'title : Another title\n' + 'some_other_keyword:1\n' + '---\n===\n', + ), const [ Token.newline, Token.startHeader, @@ -188,30 +197,36 @@ void main() { test('extra whitespace', () { expect( () => tokenize(' title: this\n---\n===\n'), - hasSyntaxError('SyntaxError: unexpected indentation\n' - '> at line 1 column 3:\n' - '> title: this\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: unexpected indentation\n' + '> at line 1 column 3:\n' + '> title: this\n' + '> ^\n', + ), ); }); test('without id', () { expect( () => tokenize(':\n---\n===\n'), - hasSyntaxError('SyntaxError: expected end-of-header marker "---"\n' - '> at line 1 column 1:\n' - '> :\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: expected end-of-header marker "---"\n' + '> at line 1 column 1:\n' + '> :\n' + '> ^\n', + ), ); }); test('short separator', () { expect( () => tokenize('--\n===\n'), - hasSyntaxError('SyntaxError: expected end-of-header marker "---"\n' - '> at line 1 column 1:\n' - '> --\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: expected end-of-header marker "---"\n' + '> at line 1 column 1:\n' + '> --\n' + '> ^\n', + ), ); }); @@ -275,11 +290,13 @@ void main() { test('whitespace in body', () { expect( - tokenize('---\n---\n' - '\n' - ' \t \r\n' - ' // also could be some comments here\n' - '==='), + tokenize( + '---\n---\n' + '\n' + ' \t \r\n' + ' // also could be some comments here\n' + '===', + ), [ Token.startHeader, Token.endHeader, @@ -294,12 +311,14 @@ void main() { test('indentation', () { expect( - tokenize('---\n---\n' - ' alpha\n' - ' beta\n' - '\t gamma\n' - ' delta\n' - '===\n'), + tokenize( + '---\n---\n' + ' alpha\n' + ' beta\n' + '\t gamma\n' + ' delta\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -325,25 +344,31 @@ void main() { test('invalid indentation', () { expect( - () => tokenize('---\n---\n' - ' alpha\n' - ' beta\n' - ' gamma\n' - '===\n'), - hasSyntaxError('SyntaxError: inconsistent indentation\n' - '> at line 5 column 3:\n' - '> gamma\n' - '> ^\n'), + () => tokenize( + '---\n---\n' + ' alpha\n' + ' beta\n' + ' gamma\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: inconsistent indentation\n' + '> at line 5 column 3:\n' + '> gamma\n' + '> ^\n', + ), ); }); test('de-indents at end of body', () { expect( - tokenize('---\n---\n' - 'one\n' - ' two\n' - ' three\n' - '==='), + tokenize( + '---\n---\n' + 'one\n' + ' two\n' + ' three\n' + '===', + ), const [ Token.startHeader, Token.endHeader, @@ -366,10 +391,12 @@ void main() { test('invalid body end', () { expect( () => tokenize('---\n---\n===='), - hasSyntaxError('SyntaxError: incomplete node body\n' - '> at line 3 column 5:\n' - '> ====\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: incomplete node body\n' + '> at line 3 column 5:\n' + '> ====\n' + '> ^\n', + ), ); }); }); @@ -377,10 +404,12 @@ void main() { group('modeNodeBodyLine', () { test('option lines', () { expect( - tokenize('---\n---\n' - '->something\n' - ' -> other\n' - '===\n'), + tokenize( + '---\n---\n' + '->something\n' + ' -> other\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -400,10 +429,12 @@ void main() { test('commands', () { expect( - tokenize('---\n---\n' - '<< >>\n' - '<< stop >>\n' - '===\n'), + tokenize( + '---\n---\n' + '<< >>\n' + '<< stop >>\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -423,13 +454,15 @@ void main() { test('line speakers', () { // cSpell:ignore Пан_Голова, Ḟḷḁṃḙ expect( - tokenize('---\n---\n' - 'Marge: Hello!\n' - 'Mr Smith: You too\n' - 'Пан_Голова :...\n' - 'Ḟḷḁṃḙ: // nothing\n' - '𐀆𒐰ï︮𒐜 :::\n' - '===\n'), + tokenize( + '---\n---\n' + 'Marge: Hello!\n' + 'Mr Smith: You too\n' + 'Пан_Голова :...\n' + 'Ḟḷḁṃḙ: // nothing\n' + '𐀆𒐰ï︮𒐜 :::\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -458,9 +491,11 @@ void main() { test('repeated arrow', () { expect( - tokenize('---\n---\n' - '-> -> -> \n' - '===\n'), + tokenize( + '---\n---\n' + '-> -> -> \n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -476,9 +511,11 @@ void main() { test('repeated character name', () { expect( - tokenize('---\n---\n' - 'Pig: Horse: Moo!\n' - '===\n'), + tokenize( + '---\n---\n' + 'Pig: Horse: Moo!\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -494,9 +531,11 @@ void main() { test('line with hash tags', () { expect( - tokenize('---\n---\n' - 'Some text #with-tag\n' - '===\n'), + tokenize( + '---\n---\n' + 'Some text #with-tag\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -513,10 +552,12 @@ void main() { group('modeText', () { test('text with comment', () { expect( - tokenize('---\n---\n' - 'some text // here be dragons\n' - 'other text \t\n' - '===\n'), + tokenize( + '---\n---\n' + 'some text // here be dragons\n' + 'other text \t\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -532,14 +573,16 @@ void main() { test('escape sequences', () { expect( - tokenize('---\n---\n' - r'\<\{ inside \}\>' - '\n' - 'very long \\\n' - ' text\n' - 'line with a newline:\\n ok\n' - '\\-> text with arrow\n' - '===\n'), + tokenize( + '---\n---\n' + r'\<\{ inside \}\>' + '\n' + 'very long \\\n' + ' text\n' + 'line with a newline:\\n ok\n' + '\\-> text with arrow\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -567,10 +610,12 @@ void main() { test('escaped colon', () { expect( - tokenize('---\n---\n' - 'One\\: two\n' - 'One two three\\:\n' - '===\n'), + tokenize( + '---\n---\n' + 'One\\: two\n' + 'One two three\\:\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -589,29 +634,36 @@ void main() { test('">>" sequence', () { expect( - tokenize('---\n---\n' - '>> hello\n' - '===\n'), - const [ - Token.startHeader, - Token.endHeader, - Token.startBody, - Token.text('>>'), - Token.text(' hello'), - Token.newline, - Token.endBody, - ]); + tokenize( + '---\n---\n' + '>> hello\n' + '===\n', + ), + const [ + Token.startHeader, + Token.endHeader, + Token.startBody, + Token.text('>>'), + Token.text(' hello'), + Token.newline, + Token.endBody, + ], + ); }); test('invalid escape sequence', () { expect( - () => tokenize('---\n---\n' - 'some text \\a\n' - '===\n'), - hasSyntaxError('SyntaxError: invalid escape sequence\n' - '> at line 3 column 12:\n' - '> some text \\a\n' - '> ^\n'), + () => tokenize( + '---\n---\n' + 'some text \\a\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: invalid escape sequence\n' + '> at line 3 column 12:\n' + '> some text \\a\n' + '> ^\n', + ), ); }); @@ -620,19 +672,22 @@ void main() { expect( () => tokenize('---\n---\ntext $ch\n'), hasSyntaxError( - 'SyntaxError: special character needs to be escaped\n' - '> at line 3 column 6:\n' - '> text $ch\n' - '> ^\n'), + 'SyntaxError: special character needs to be escaped\n' + '> at line 3 column 6:\n' + '> text $ch\n' + '> ^\n', + ), ); } }); test('expressions', () { expect( - tokenize('---\n---\n' - '{ } // noop\n' - '===\n'), + tokenize( + '---\n---\n' + '{ } // noop\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -649,9 +704,11 @@ void main() { group('modeExpression', () { test('expression with assorted tokens', () { expect( - tokenize('---\n---\n' - '{ \$x += 33 - 7/random() }\n' - '===\n'), + tokenize( + '---\n---\n' + '{ \$x += 33 - 7/random() }\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -675,9 +732,11 @@ void main() { test('expression with keywords', () { expect( - tokenize('---\n---\n' - '{ true * false as String }\n' - '===\n'), + tokenize( + '---\n---\n' + '{ true * false as String }\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -697,11 +756,13 @@ void main() { test('expression with strings', () { expect( - tokenize('---\n---\n' - '{ \$x = "hello" + ", world" }\n' - '{ "one\' two", \'"\' }\n' - '{ "last \\\' \\" \\\\ one\\n" }\n' - '===\n'), + tokenize( + '---\n---\n' + '{ \$x = "hello" + ", world" }\n' + '{ "one\' two", \'"\' }\n' + '{ "last \\\' \\" \\\\ one\\n" }\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -731,9 +792,11 @@ void main() { test('expression with numbers', () { expect( - tokenize('---\n---\n' - '{ 0 -1 239444 0.5 17.1 2. 3.1415926535 111}\n' - '===\n'), + tokenize( + '---\n---\n' + '{ 0 -1 239444 0.5 17.1 2. 3.1415926535 111}\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -757,9 +820,11 @@ void main() { test('close command within a plain text expression', () { expect( - tokenize('---\n---\n' - '{ a >> b }\n' - '===\n'), + tokenize( + '---\n---\n' + '{ a >> b }\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -778,39 +843,50 @@ void main() { test('invalid variable name', () { expect( - () => tokenize('---\n---\n' - '{ \$a = \$7b }\n' - '===\n'), - hasSyntaxError('SyntaxError: invalid variable name\n' - '> at line 3 column 8:\n' - '> { \$a = \$7b }\n' - '> ^\n'), + () => tokenize( + '---\n---\n' + '{ \$a = \$7b }\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: invalid variable name\n' + '> at line 3 column 8:\n' + '> { \$a = \$7b }\n' + '> ^\n', + ), ); }); test('unicode variable names', () { // cSpell:ignore эксперимент expect( - () => tokenize('---\n---\n' - '{ \$эксперимент }\n' - '===\n'), - hasSyntaxError('SyntaxError: invalid variable name\n' - '> at line 3 column 3:\n' - '> { \$эксперимент }\n' - '> ^\n'), + () => tokenize( + '---\n---\n' + '{ \$эксперимент }\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: invalid variable name\n' + '> at line 3 column 3:\n' + '> { \$эксперимент }\n' + '> ^\n', + ), ); }); test('invalid string', () { expect( - () => tokenize('---\n---\n' - '{ "starting... }\n' - '===\n'), + () => tokenize( + '---\n---\n' + '{ "starting... }\n' + '===\n', + ), hasSyntaxError( - 'SyntaxError: unexpected end of line while parsing a string\n' - '> at line 3 column 17:\n' - '> { "starting... }\n' - '> ^\n'), + 'SyntaxError: unexpected end of line while parsing a string\n' + '> at line 3 column 17:\n' + '> { "starting... }\n' + '> ^\n', + ), ); }); }); @@ -818,13 +894,15 @@ void main() { group('modeCommand', () { test('normal commands', () { expect( - tokenize('---\n---\n' - '<< stop >>\n' - '<< fullStop >>\n' - '<< jump places >>\n' - '<>\n' - '<< set \$n = 2 >> // simple\n' - '===\n'), + tokenize( + '---\n---\n' + '<< stop >>\n' + '<< fullStop >>\n' + '<< jump places >>\n' + '<>\n' + '<< set \$n = 2 >> // simple\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -865,11 +943,13 @@ void main() { test('if-else', () { expect( - tokenize('---\n---\n' - '<>\n' - " Baker: Well, you can't afford one!\n" - '<>\n' - '===\n'), + tokenize( + '---\n---\n' + '<>\n' + " Baker: Well, you can't afford one!\n" + '<>\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -900,9 +980,11 @@ void main() { test('user-defined commands', () { expect( - tokenize('---\n---\n' - '<>\n' - '===\n'), + tokenize( + '---\n---\n' + '<>\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -919,25 +1001,33 @@ void main() { test('closing brace', () { expect( - () => tokenize('---\n---\n' - '<< hello } >>\n' - '===\n'), - hasSyntaxError('SyntaxError: special character needs to be escaped\n' - '> at line 3 column 10:\n' - '> << hello } >>\n' - '> ^\n'), + () => tokenize( + '---\n---\n' + '<< hello } >>\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: special character needs to be escaped\n' + '> at line 3 column 10:\n' + '> << hello } >>\n' + '> ^\n', + ), ); }); test('incomplete command', () { expect( - () => tokenize('---\n---\n' - '<< stop\n' - '===\n'), - hasSyntaxError('SyntaxError: missing command close token ">>"\n' - '> at line 3 column 8:\n' - '> << stop\n' - '> ^\n'), + () => tokenize( + '---\n---\n' + '<< stop\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: missing command close token ">>"\n' + '> at line 3 column 8:\n' + '> << stop\n' + '> ^\n', + ), ); }); }); @@ -995,9 +1085,11 @@ void main() { test('tokenize complex markup tag', () { expect( - tokenize('---\n---\n' - 'One [red shade=12 hex="#ff0000"]color[/red]\n' - '===\n'), + tokenize( + '---\n---\n' + 'One [red shade=12 hex="#ff0000"]color[/red]\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -1025,9 +1117,11 @@ void main() { test('whitespace after self-closing command', () { expect( - tokenize('---\n---\n' - 'Hello [yes/] world!\n' - '===\n'), + tokenize( + '---\n---\n' + 'Hello [yes/] world!\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -1060,10 +1154,12 @@ void main() { group('modeTextEnd', () { test('hashtags in lines', () { expect( - tokenize('---\n---\n' - 'line1 #tag #some:other@tag! // whatever\n' - 'line2 { 33 } #here-be-dragons//2\n' - '===\n'), + tokenize( + '---\n---\n' + 'line1 #tag #some:other@tag! // whatever\n' + 'line2 { 33 } #here-be-dragons//2\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -1085,9 +1181,11 @@ void main() { test('comments in lines', () { expect( - tokenize('---\n---\n' - 'line1 // whatever\n' - '===\n'), + tokenize( + '---\n---\n' + 'line1 // whatever\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -1101,10 +1199,12 @@ void main() { test('commands in lines', () { expect( - tokenize('---\n---\n' - '-> Sure I am! The boss knows me! < 10>>\n' - '-> Please?\n' - '===\n'), + tokenize( + '---\n---\n' + '-> Sure I am! The boss knows me! < 10>>\n' + '-> Please?\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -1130,9 +1230,11 @@ void main() { test('multiple commands and hashtags', () { expect( - tokenize('---\n---\n' - '#one <> <> #four\n' - '===\n'), + tokenize( + '---\n---\n' + '#one <> <> #four\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -1153,9 +1255,11 @@ void main() { test('text with escaped content', () { expect( - tokenize('---\n---\n' - 'One \\{ two\n' - '===\n'), + tokenize( + '---\n---\n' + 'One \\{ two\n' + '===\n', + ), const [ Token.startHeader, Token.endHeader, @@ -1175,44 +1279,56 @@ void main() { group('errors', () { test('long line, error near the start', () { expect( - () => tokenize('---\n---\n' - '<>\n' - '===\n'), - hasSyntaxError('SyntaxError: invalid token\n' - '> at line 3 column 38:\n' - '> < ^\n'), + () => tokenize( + '---\n---\n' + '<>\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: invalid token\n' + '> at line 3 column 38:\n' + '> < ^\n', + ), ); }); test('long line, error near the end', () { expect( - () => tokenize('---\n---\n' - '<>\n' - '===\n'), - hasSyntaxError('SyntaxError: invalid token\n' - '> at line 3 column 95:\n' - '> ...theta iota kappa lambda mu nu xi omicron pi rho @ sigma ' - 'tau upsilon phi chi>>\n' - '> ^\n'), + () => tokenize( + '---\n---\n' + '<>\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: invalid token\n' + '> at line 3 column 95:\n' + '> ...theta iota kappa lambda mu nu xi omicron pi rho @ sigma ' + 'tau upsilon phi chi>>\n' + '> ^\n', + ), ); }); test('long line, error in the middle', () { expect( - () => tokenize('---\n---\n' - '<>\n' - '===\n'), - hasSyntaxError('SyntaxError: invalid token\n' - '> at line 3 column 71:\n' - '> ...on zeta eta theta iota kappa lambda ` mu nu xi omicron ' - 'pi rho sigma tau...\n' - '> ^\n'), + () => tokenize( + '---\n---\n' + '<>\n' + '===\n', + ), + hasSyntaxError( + 'SyntaxError: invalid token\n' + '> at line 3 column 71:\n' + '> ...on zeta eta theta iota kappa lambda ` mu nu xi omicron ' + 'pi rho sigma tau...\n' + '> ^\n', + ), ); }); diff --git a/packages/flame_jenny/jenny/test/structure/commands/character_command_test.dart b/packages/flame_jenny/jenny/test/structure/commands/character_command_test.dart index b619509e0..70344d46b 100644 --- a/packages/flame_jenny/jenny/test/structure/commands/character_command_test.dart +++ b/packages/flame_jenny/jenny/test/structure/commands/character_command_test.dart @@ -111,30 +111,36 @@ void main() { test('invalid syntax', () { expect( () => YarnProject()..parse(r'<>'), - hasSyntaxError('SyntaxError: unexpected token\n' - '> at line 1 column 18:\n' - '> <>\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: unexpected token\n' + '> at line 1 column 18:\n' + '> <>\n' + '> ^\n', + ), ); }); test('no character name or ids', () { expect( () => YarnProject()..parse('<>'), - hasSyntaxError('SyntaxError: at least one character id is required\n' - '> at line 1 column 12:\n' - '> <>\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: at least one character id is required\n' + '> at line 1 column 12:\n' + '> <>\n' + '> ^\n', + ), ); }); test('only character name', () { expect( () => YarnProject()..parse('<>'), - hasSyntaxError('SyntaxError: at least one character id is required\n' - '> at line 1 column 19:\n' - '> <>\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: at least one character id is required\n' + '> at line 1 column 19:\n' + '> <>\n' + '> ^\n', + ), ); }); diff --git a/packages/flame_jenny/jenny/test/structure/commands/declare_command_test.dart b/packages/flame_jenny/jenny/test/structure/commands/declare_command_test.dart index dbbc317dd..e0e022f41 100644 --- a/packages/flame_jenny/jenny/test/structure/commands/declare_command_test.dart +++ b/packages/flame_jenny/jenny/test/structure/commands/declare_command_test.dart @@ -116,28 +116,34 @@ void main() { test('missing variable name', () { expect( () => YarnProject()..parse('<>'), - hasSyntaxError('SyntaxError: variable name expected\n' - '> at line 1 column 11:\n' - '> <>\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: variable name expected\n' + '> at line 1 column 11:\n' + '> <>\n' + '> ^\n', + ), ); }); test('no assignment', () { expect( () => YarnProject()..parse(r'<>'), - hasSyntaxError('SyntaxError: expected `= value` or `as Type`\n' - '> at line 1 column 17:\n' - '> <>\n' - '> ^\n'), + hasSyntaxError( + 'SyntaxError: expected `= value` or `as Type`\n' + '> at line 1 column 17:\n' + '> <>\n' + '> ^\n', + ), ); }); test('variable redeclaration', () { expect( () => YarnProject() - ..parse('<>\n' - '<>\n'), + ..parse( + '<>\n' + '<>\n', + ), hasNameError( 'NameError: variable \$error has already been declared\n' '> at line 2 column 11:\n' diff --git a/packages/flame_jenny/jenny/test/structure/commands/if_command_test.dart b/packages/flame_jenny/jenny/test/structure/commands/if_command_test.dart index f29610fab..4b4e4a40a 100644 --- a/packages/flame_jenny/jenny/test/structure/commands/if_command_test.dart +++ b/packages/flame_jenny/jenny/test/structure/commands/if_command_test.dart @@ -41,16 +41,19 @@ void main() { test('non-boolean condition in <>', () { expect( () => YarnProject() - ..parse('title:A\n---\n' - '<>\n' - ' text\n' - '<>\n' - '===\n'), + ..parse( + 'title:A\n---\n' + '<>\n' + ' text\n' + '<>\n' + '===\n', + ), hasTypeError( - 'TypeError: expression in an <> command must be boolean\n' - '> at line 3 column 6:\n' - '> <>\n' - '> ^\n'), + 'TypeError: expression in an <> command must be boolean\n' + '> at line 3 column 6:\n' + '> <>\n' + '> ^\n', + ), ); }); diff --git a/packages/flame_jenny/jenny/test/structure/commands/jump_command_test.dart b/packages/flame_jenny/jenny/test/structure/commands/jump_command_test.dart index da0ddeee4..50ad44b81 100644 --- a/packages/flame_jenny/jenny/test/structure/commands/jump_command_test.dart +++ b/packages/flame_jenny/jenny/test/structure/commands/jump_command_test.dart @@ -9,10 +9,12 @@ void main() { test('<> command', () { final yarn = YarnProject() ..variables.setVariable(r'$target', 'DOWN') - ..parse('title:A\n---\n' - '<>\n' - '<>\n' - '===\n'); + ..parse( + 'title:A\n---\n' + '<>\n' + '<>\n' + '===\n', + ); final node = yarn.nodes['A']!; expect(node.lines.length, 2); expect(node.lines[0], isA()); @@ -113,8 +115,10 @@ void main() { '===\n', ); expect( - () => DialogueRunner(yarnProject: yarn, dialogueViews: []) - .startDialogue('A'), + () => DialogueRunner( + yarnProject: yarn, + dialogueViews: [], + ).startDialogue('A'), hasNameError('NameError: Node "Up" could not be found'), ); }); diff --git a/packages/flame_jenny/jenny/test/structure/commands/user_defined_command_test.dart b/packages/flame_jenny/jenny/test/structure/commands/user_defined_command_test.dart index 3cc04f9ff..1a2ee6225 100644 --- a/packages/flame_jenny/jenny/test/structure/commands/user_defined_command_test.dart +++ b/packages/flame_jenny/jenny/test/structure/commands/user_defined_command_test.dart @@ -10,9 +10,11 @@ void main() { group('UserDefinedCommand', () { test('tokenization', () { expect( - tokenize('---\n---\n' - '<>\n' - '==='), + tokenize( + '---\n---\n' + '<>\n' + '===', + ), const [ Token.startHeader, Token.endHeader, @@ -33,9 +35,11 @@ void main() { test('parse simple dialogue command', () { final project = YarnProject() ..commands.addOrphanedCommand('hello') - ..parse('title: start\n---\n' - '<>\n' - '==='); + ..parse( + 'title: start\n---\n' + '<>\n' + '===', + ); expect(project.nodes['start']!.lines.length, 1); expect(project.nodes['start']!.lines[0], isA()); final cmd = project.nodes['start']!.lines[0] as UserDefinedCommand; @@ -52,9 +56,11 @@ void main() { x = a; y = b; }) - ..parse('title: start\n---\n' - '<>\n' - '==='); + ..parse( + 'title: start\n---\n' + '<>\n' + '===', + ); final runner = DialogueRunner(yarnProject: project, dialogueViews: []); expect(project.nodes['start']!.lines.length, 1); expect(project.nodes['start']!.lines[0], isA()); diff --git a/packages/flame_jenny/jenny/test/structure/commands/visit_command_test.dart b/packages/flame_jenny/jenny/test/structure/commands/visit_command_test.dart index 2c12e6e7a..581138b30 100644 --- a/packages/flame_jenny/jenny/test/structure/commands/visit_command_test.dart +++ b/packages/flame_jenny/jenny/test/structure/commands/visit_command_test.dart @@ -37,10 +37,12 @@ void main() { test('<> command parsing', () { final yarn = YarnProject() ..variables.setVariable(r'$target', 'Y') - ..parse('title:A\n---\n' - '<>\n' - '<>\n' - '===\n'); + ..parse( + 'title:A\n---\n' + '<>\n' + '<>\n' + '===\n', + ); final node = yarn.nodes['A']!; expect(node.lines.length, 2); expect(node.lines[0], isA()); @@ -212,8 +214,10 @@ void main() { '===\n', ); expect( - () => DialogueRunner(yarnProject: yarn, dialogueViews: []) - .startDialogue('A'), + () => DialogueRunner( + yarnProject: yarn, + dialogueViews: [], + ).startDialogue('A'), hasNameError('NameError: Node "Somewhere" could not be found'), ); }); diff --git a/packages/flame_jenny/jenny/test/structure/expressions/functions/round_places_test.dart b/packages/flame_jenny/jenny/test/structure/expressions/functions/round_places_test.dart index 1c60bc201..ba7cea371 100644 --- a/packages/flame_jenny/jenny/test/structure/expressions/functions/round_places_test.dart +++ b/packages/flame_jenny/jenny/test/structure/expressions/functions/round_places_test.dart @@ -44,8 +44,9 @@ void main() { test('too many arguments', () { expect( - () => YarnProject() - ..parse('title:A\n---\n{round_places(3, 6, 1, 7)}\n===\n'), + () => + YarnProject() + ..parse('title:A\n---\n{round_places(3, 6, 1, 7)}\n===\n'), hasTypeError( 'TypeError: function round_places() requires two arguments\n' '> at line 3 column 21:\n' @@ -57,8 +58,9 @@ void main() { test('first argument not numeric', () { expect( - () => YarnProject() - ..parse('title:A\n---\n{round_places("one", 1)}\n===\n'), + () => + YarnProject() + ..parse('title:A\n---\n{round_places("one", 1)}\n===\n'), hasTypeError( 'TypeError: first argument in round_places() should be numeric\n' '> at line 3 column 15:\n' @@ -70,8 +72,9 @@ void main() { test('second argument not numeric', () { expect( - () => YarnProject() - ..parse('title:A\n---\n{round_places(3, "one")}\n===\n'), + () => + YarnProject() + ..parse('title:A\n---\n{round_places(3, "one")}\n===\n'), hasTypeError( 'TypeError: second argument in round_places() should be numeric\n' '> at line 3 column 18:\n' diff --git a/packages/flame_jenny/jenny/test/structure/expressions/functions/visit_count_test.dart b/packages/flame_jenny/jenny/test/structure/expressions/functions/visit_count_test.dart index f7aadc5a3..e5c0e5ef4 100644 --- a/packages/flame_jenny/jenny/test/structure/expressions/functions/visit_count_test.dart +++ b/packages/flame_jenny/jenny/test/structure/expressions/functions/visit_count_test.dart @@ -116,10 +116,12 @@ void main() { test('visit_count() with an unknown node', () { final yarn = YarnProject() - ..parse('title:A\n' - '---\n' - '{visit_count("Africa")}\n' - '===\n'); + ..parse( + 'title:A\n' + '---\n' + '{visit_count("Africa")}\n' + '===\n', + ); final line = yarn.nodes['A']!.lines.first as DialogueLine; expect( line.evaluate, @@ -141,8 +143,9 @@ void main() { test('too many arguments', () { expect( - () => YarnProject() - ..parse('title:A\n---\n{visit_count("Start", "Finish")}\n===\n'), + () => + YarnProject() + ..parse('title:A\n---\n{visit_count("Start", "Finish")}\n===\n'), hasTypeError( 'TypeError: function visit_count() requires a single argument\n' '> at line 3 column 23:\n' diff --git a/packages/flame_jenny/jenny/test/structure/expressions/functions/visited_test.dart b/packages/flame_jenny/jenny/test/structure/expressions/functions/visited_test.dart index 949f30d27..fda44ecca 100644 --- a/packages/flame_jenny/jenny/test/structure/expressions/functions/visited_test.dart +++ b/packages/flame_jenny/jenny/test/structure/expressions/functions/visited_test.dart @@ -54,10 +54,12 @@ void main() { test('visited() with an unknown node', () { final yarn = YarnProject() - ..parse('title:A\n' - '---\n' - '{visited("Africa")}\n' - '===\n'); + ..parse( + 'title:A\n' + '---\n' + '{visited("Africa")}\n' + '===\n', + ); final line = yarn.nodes['A']!.lines.first as DialogueLine; expect( line.evaluate, @@ -79,8 +81,9 @@ void main() { test('too many arguments', () { expect( - () => YarnProject() - ..parse('title:A\n---\n{visited("Start", "Finish")}\n===\n'), + () => + YarnProject() + ..parse('title:A\n---\n{visited("Start", "Finish")}\n===\n'), hasTypeError( 'TypeError: function visited() requires a single argument\n' '> at line 3 column 19:\n' diff --git a/packages/flame_jenny/jenny/test/test_scenario.dart b/packages/flame_jenny/jenny/test/test_scenario.dart index 60499653b..cc0a012af 100644 --- a/packages/flame_jenny/jenny/test/test_scenario.dart +++ b/packages/flame_jenny/jenny/test/test_scenario.dart @@ -141,12 +141,12 @@ class _TestPlan extends DialogueView { final option2 = choice.options[i]; final text1 = (option1.character == null ? '' : '${option1.character}: ') + - option1.text + - (option1.enabled ? '' : ' [disabled]'); + option1.text + + (option1.enabled ? '' : ' [disabled]'); final text2 = (option2.character == null ? '' : '${option2.character!.name}: ') + - option2.text + - (option2.isAvailable ? '' : ' [disabled]'); + option2.text + + (option2.isAvailable ? '' : ' [disabled]'); assert( text1 == text2, '\n' diff --git a/packages/flame_jenny/jenny/test/utils.dart b/packages/flame_jenny/jenny/test/utils.dart index d051d583a..16d1e5016 100644 --- a/packages/flame_jenny/jenny/test/utils.dart +++ b/packages/flame_jenny/jenny/test/utils.dart @@ -21,8 +21,11 @@ Matcher hasTypeError(String message) { Matcher hasDialogueError(String message) { return throwsA( - isA() - .having((e) => e.toString(), 'toString', 'DialogueError: $message'), + isA().having( + (e) => e.toString(), + 'toString', + 'DialogueError: $message', + ), ); } diff --git a/packages/flame_jenny/pubspec.yaml b/packages/flame_jenny/pubspec.yaml index 89b97a5b6..6091e09f9 100644 --- a/packages/flame_jenny/pubspec.yaml +++ b/packages/flame_jenny/pubspec.yaml @@ -12,7 +12,7 @@ topics: - flame environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_kenney_xml/example/pubspec.yaml b/packages/flame_kenney_xml/example/pubspec.yaml index d0f57d6a1..8ef07de00 100644 --- a/packages/flame_kenney_xml/example/pubspec.yaml +++ b/packages/flame_kenney_xml/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: "none" version: 1.0.0 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_kenney_xml/pubspec.yaml b/packages/flame_kenney_xml/pubspec.yaml index 84564cdcd..0b11838ea 100644 --- a/packages/flame_kenney_xml/pubspec.yaml +++ b/packages/flame_kenney_xml/pubspec.yaml @@ -14,7 +14,7 @@ topics: - tilemap environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_lint/pubspec.yaml b/packages/flame_lint/pubspec.yaml index f574d1dfb..ccccef30b 100644 --- a/packages/flame_lint/pubspec.yaml +++ b/packages/flame_lint/pubspec.yaml @@ -12,7 +12,7 @@ topics: - lints environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: lints: ^5.1.1 diff --git a/packages/flame_lottie/example/pubspec.yaml b/packages/flame_lottie/example/pubspec.yaml index 5455bc918..5297feeed 100644 --- a/packages/flame_lottie/example/pubspec.yaml +++ b/packages/flame_lottie/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 0.0.1+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_lottie/lib/src/lottie_renderer.dart b/packages/flame_lottie/lib/src/lottie_renderer.dart index 8e1a5e392..e042bef49 100644 --- a/packages/flame_lottie/lib/src/lottie_renderer.dart +++ b/packages/flame_lottie/lib/src/lottie_renderer.dart @@ -24,17 +24,18 @@ class LottieRenderer { LottieDelegates? delegates, bool? enableMergePaths, FrameRate? frameRate, - }) : assert(progress >= 0.0 && progress <= 1.0), - boundingRect = size.toRect(), - drawable = LottieDrawable(composition, frameRate: frameRate) - ..setProgress(progress) - ..delegates = delegates - ..enableMergePaths = enableMergePaths ?? false, - _controller = controller ?? - EffectController( - duration: duration ?? composition.duration.inMilliseconds / 1000, - infinite: repeating ?? false, - ) { + }) : assert(progress >= 0.0 && progress <= 1.0), + boundingRect = size.toRect(), + drawable = LottieDrawable(composition, frameRate: frameRate) + ..setProgress(progress) + ..delegates = delegates + ..enableMergePaths = enableMergePaths ?? false, + _controller = + controller ?? + EffectController( + duration: duration ?? composition.duration.inMilliseconds / 1000, + infinite: repeating ?? false, + ) { size.addListener(() { boundingRect = size.toRect(); }); diff --git a/packages/flame_lottie/pubspec.yaml b/packages/flame_lottie/pubspec.yaml index 3c308c35f..442f2d081 100644 --- a/packages/flame_lottie/pubspec.yaml +++ b/packages/flame_lottie/pubspec.yaml @@ -13,7 +13,7 @@ topics: - animations environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_lottie/test/flame_lottie_test.dart b/packages/flame_lottie/test/flame_lottie_test.dart index 82a770ab6..13abf7a35 100644 --- a/packages/flame_lottie/test/flame_lottie_test.dart +++ b/packages/flame_lottie/test/flame_lottie_test.dart @@ -27,8 +27,9 @@ void main() { testWithFlameGame( 'Load composition as AssetBundle and use loadLottie function by library', (game) async { - final logoData = - Future.value(_bytesForFile('example/assets/LottieLogo1.json')); + final logoData = Future.value( + _bytesForFile('example/assets/LottieLogo1.json'), + ); final mockAsset = _FakeAssetBundle({'logo.json': logoData}); diff --git a/packages/flame_markdown/example/pubspec.yaml b/packages/flame_markdown/example/pubspec.yaml index 505a2b1a2..ba3eefc75 100644 --- a/packages/flame_markdown/example/pubspec.yaml +++ b/packages/flame_markdown/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 0.1.0 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_markdown/lib/custom_attribute_syntax.dart b/packages/flame_markdown/lib/custom_attribute_syntax.dart index b9485e4c7..df1cd3b33 100644 --- a/packages/flame_markdown/lib/custom_attribute_syntax.dart +++ b/packages/flame_markdown/lib/custom_attribute_syntax.dart @@ -28,10 +28,10 @@ class _Chars { class CustomAttributeSyntax extends LinkSyntax { /// Creates a new custom attribute syntax. CustomAttributeSyntax() - : super( - pattern: r'\[', - startCharacter: _Chars.leftBracket, - ); + : super( + pattern: r'\[', + startCharacter: _Chars.leftBracket, + ); @override Iterable? close( diff --git a/packages/flame_markdown/lib/flame_markdown.dart b/packages/flame_markdown/lib/flame_markdown.dart index bffa2e4d0..798edda9e 100644 --- a/packages/flame_markdown/lib/flame_markdown.dart +++ b/packages/flame_markdown/lib/flame_markdown.dart @@ -64,20 +64,21 @@ class FlameMarkdown { } return switch (element.tag) { - 'span' => child, - 'h1' => HeaderNode(child, level: 1), - 'h2' => HeaderNode(child, level: 2), - 'h3' => HeaderNode(child, level: 3), - 'h4' => HeaderNode(child, level: 4), - 'h5' => HeaderNode(child, level: 5), - 'h6' => HeaderNode(child, level: 6), - 'p' => ParagraphNode(child), - 'em' || 'i' => ItalicTextNode(child), - 'strong' || 'b' => BoldTextNode(child), - 'code' => CodeTextNode(child), - 'del' => StrikethroughTextNode(child), - _ => throw Exception('Unknown element tag: ${element.tag}'), - } as TextNode; + 'span' => child, + 'h1' => HeaderNode(child, level: 1), + 'h2' => HeaderNode(child, level: 2), + 'h3' => HeaderNode(child, level: 3), + 'h4' => HeaderNode(child, level: 4), + 'h5' => HeaderNode(child, level: 5), + 'h6' => HeaderNode(child, level: 6), + 'p' => ParagraphNode(child), + 'em' || 'i' => ItalicTextNode(child), + 'strong' || 'b' => BoldTextNode(child), + 'code' => CodeTextNode(child), + 'del' => StrikethroughTextNode(child), + _ => throw Exception('Unknown element tag: ${element.tag}'), + } + as TextNode; } static PlainTextNode _convertText(Text text) { diff --git a/packages/flame_markdown/pubspec.yaml b/packages/flame_markdown/pubspec.yaml index 0aebcd3bf..de1b442d7 100644 --- a/packages/flame_markdown/pubspec.yaml +++ b/packages/flame_markdown/pubspec.yaml @@ -13,7 +13,7 @@ topics: - markdown environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_markdown/test/flame_markdown_test.dart b/packages/flame_markdown/test/flame_markdown_test.dart index 1ea2b7c2b..200d565fa 100644 --- a/packages/flame_markdown/test/flame_markdown_test.dart +++ b/packages/flame_markdown/test/flame_markdown_test.dart @@ -27,14 +27,14 @@ void main() { _expectElementGroup(element, [ (el) => _expectElementGroup(el, [ - (el) => _expectElementTextPainter( - el, - 'Hello world!', - const TextStyle( - fontSize: 12, - ), - ), - ]), + (el) => _expectElementTextPainter( + el, + 'Hello world!', + const TextStyle( + fontSize: 12, + ), + ), + ]), ]); }); @@ -43,13 +43,13 @@ void main() { _expectDocument(doc, [ (node) => _expectParagraph(node, (p) { - _expectGroup(p, [ - (node) => _expectBold(node, 'Flame'), - (node) => _expectPlain(node, ': Hello, '), - (node) => _expectItalic(node, 'world'), - (node) => _expectPlain(node, '!'), - ]); - }), + _expectGroup(p, [ + (node) => _expectBold(node, 'Flame'), + (node) => _expectPlain(node, ': Hello, '), + (node) => _expectItalic(node, 'world'), + (node) => _expectPlain(node, '!'), + ]); + }), ]); final element = doc.format( @@ -69,39 +69,39 @@ void main() { _expectElementGroup(element, [ (el) => _expectElementGroup(el, [ - (el) => _expectElementGroupText(el, [ - (el) => _expectElementTextPainter( - el, - 'Flame', - const TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - ), - ), - (el) => _expectElementTextPainter( - el, - ': Hello, ', - const TextStyle( - fontSize: 12, - ), - ), - (el) => _expectElementTextPainter( - el, - 'world', - const TextStyle( - fontSize: 12, - fontStyle: FontStyle.italic, - ), - ), - (el) => _expectElementTextPainter( - el, - '!', - const TextStyle( - fontSize: 12, - ), - ), - ]), - ]), + (el) => _expectElementGroupText(el, [ + (el) => _expectElementTextPainter( + el, + 'Flame', + const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + (el) => _expectElementTextPainter( + el, + ': Hello, ', + const TextStyle( + fontSize: 12, + ), + ), + (el) => _expectElementTextPainter( + el, + 'world', + const TextStyle( + fontSize: 12, + fontStyle: FontStyle.italic, + ), + ), + (el) => _expectElementTextPainter( + el, + '!', + const TextStyle( + fontSize: 12, + ), + ), + ]), + ]), ]); }); @@ -110,11 +110,11 @@ void main() { _expectDocument(doc, [ (node) => _expectParagraph(node, (p) { - _expectGroup(p, [ - (node) => _expectPlain(node, 'Flame: '), - (node) => _expectCode(node, 'var game = FlameGame();'), - ]); - }), + _expectGroup(p, [ + (node) => _expectPlain(node, 'Flame: '), + (node) => _expectCode(node, 'var game = FlameGame();'), + ]); + }), ]); final element = doc.format( @@ -131,24 +131,24 @@ void main() { _expectElementGroup(element, [ (el) => _expectElementGroup(el, [ - (el) => _expectElementGroupText(el, [ - (el) => _expectElementTextPainter( - el, - 'Flame: ', - const TextStyle( - fontSize: 12, - ), - ), - (el) => _expectElementTextPainter( - el, - 'var game = FlameGame();', - const TextStyle( - fontSize: 12, - fontFamily: 'monospace', - ), - ), - ]), - ]), + (el) => _expectElementGroupText(el, [ + (el) => _expectElementTextPainter( + el, + 'Flame: ', + const TextStyle( + fontSize: 12, + ), + ), + (el) => _expectElementTextPainter( + el, + 'var game = FlameGame();', + const TextStyle( + fontSize: 12, + fontFamily: 'monospace', + ), + ), + ]), + ]), ]); }); @@ -159,16 +159,16 @@ void main() { _expectDocument(doc, [ (node) => _expectParagraph(node, (p) { - _expectBoldGroup(p, [ - (node) => _expectPlain(node, 'This '), - (node) => _expectItalicGroup(node, [ - (node) => _expectPlain(node, 'is '), - (node) => _expectCode(node, 'code'), - (node) => _expectPlain(node, ' inside italics'), - ]), - (node) => _expectPlain(node, ' inside bold.'), - ]); - }), + _expectBoldGroup(p, [ + (node) => _expectPlain(node, 'This '), + (node) => _expectItalicGroup(node, [ + (node) => _expectPlain(node, 'is '), + (node) => _expectCode(node, 'code'), + (node) => _expectPlain(node, ' inside italics'), + ]), + (node) => _expectPlain(node, ' inside bold.'), + ]); + }), ]); final element = doc.format( @@ -191,55 +191,55 @@ void main() { _expectElementGroup(element, [ (el) => _expectElementGroup(el, [ - (el) => _expectElementGroupText(el, [ - (el) => _expectElementTextPainter( - el, - 'This ', - const TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - ), - ), - (el) => _expectElementGroupText(el, [ - (el) => _expectElementTextPainter( - el, - 'is ', - const TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - fontStyle: FontStyle.italic, - ), - ), - (el) => _expectElementTextPainter( - el, - 'code', - const TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - fontStyle: FontStyle.italic, - fontFamily: 'monospace', - ), - ), - (el) => _expectElementTextPainter( - el, - ' inside italics', - const TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - fontStyle: FontStyle.italic, - ), - ), - ]), - (el) => _expectElementTextPainter( - el, - ' inside bold.', - const TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - ), - ), - ]), + (el) => _expectElementGroupText(el, [ + (el) => _expectElementTextPainter( + el, + 'This ', + const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + (el) => _expectElementGroupText(el, [ + (el) => _expectElementTextPainter( + el, + 'is ', + const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + fontStyle: FontStyle.italic, + ), + ), + (el) => _expectElementTextPainter( + el, + 'code', + const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + fontStyle: FontStyle.italic, + fontFamily: 'monospace', + ), + ), + (el) => _expectElementTextPainter( + el, + ' inside italics', + const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + fontStyle: FontStyle.italic, + ), + ), ]), + (el) => _expectElementTextPainter( + el, + ' inside bold.', + const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ]), + ]), ]); }); @@ -264,46 +264,47 @@ void main() { }); test('several paragraphs with header', () { - final markdown = - File('example/assets/fire_and_ice.md').readAsStringSync(); + final markdown = File( + 'example/assets/fire_and_ice.md', + ).readAsStringSync(); final doc = FlameMarkdown.toDocument(markdown); _expectDocument(doc, [ (node) => _expectHeader(node, 1, 'Fire & Ice'), (node) => _expectParagraph(node, (p) { - _expectGroup(p, [ - (node) => _expectPlain( - node, - // note: strike-trough is only parsed if enabled - 'Some say the world will ~~end~~ in ', - ), - (node) => _expectBold(node, 'fire'), - (node) => _expectPlain(node, ','), - ]); - }), + _expectGroup(p, [ + (node) => _expectPlain( + node, + // note: strike-trough is only parsed if enabled + 'Some say the world will ~~end~~ in ', + ), + (node) => _expectBold(node, 'fire'), + (node) => _expectPlain(node, ','), + ]); + }), (node) => _expectParagraph( - node, - (p) => _expectGroup(p, [ - (node) => _expectPlain(node, 'Some say in '), - (node) => _expectItalic(node, 'ice'), - (node) => _expectPlain(node, '.'), - ]), - ), + node, + (p) => _expectGroup(p, [ + (node) => _expectPlain(node, 'Some say in '), + (node) => _expectItalic(node, 'ice'), + (node) => _expectPlain(node, '.'), + ]), + ), (node) => _expectSimpleParagraph( - node, - "From what I've tasted of >desire<,", - ), + node, + "From what I've tasted of >desire<,", + ), (node) => _expectParagraph(node, (p) { - _expectGroup(p, [ - (node) => _expectPlain(node, 'I hold with those who favor '), - (node) => _expectBold(node, 'fire'), - (node) => _expectPlain(node, '.'), - ]); - }), + _expectGroup(p, [ + (node) => _expectPlain(node, 'I hold with those who favor '), + (node) => _expectBold(node, 'fire'), + (node) => _expectPlain(node, '.'), + ]); + }), // note: custom attribute is only parsed if enabled (node) => _expectParagraph(node, (p) { - _expectPlain(p, '[- by Robert Frost]{.author}'); - }), + _expectPlain(p, '[- by Robert Frost]{.author}'); + }), ]); }); @@ -321,12 +322,12 @@ void main() { _expectDocument(doc, [ (node) => _expectParagraph(node, (p) { - _expectGroup(p, [ - (node) => _expectPlain(node, 'Flame '), - (node) => _expectStrikethrough(node, 'will be'), - (node) => _expectPlain(node, ' is a great game engine!'), - ]); - }), + _expectGroup(p, [ + (node) => _expectPlain(node, 'Flame '), + (node) => _expectStrikethrough(node, 'will be'), + (node) => _expectPlain(node, ' is a great game engine!'), + ]); + }), ]); }); @@ -345,14 +346,14 @@ void main() { _expectDocument(doc, [ (node) => _expectParagraph(node, (p) { - _expectGroup(p, [ - (node) => _expectPlain(node, 'This one will be '), - (node) => _expectCustom(node, 'red', styleName: 'red'), - (node) => _expectPlain(node, ' and this one will be '), - (node) => _expectCustom(node, 'blue', styleName: 'blue'), - (node) => _expectPlain(node, '.'), - ]); - }), + _expectGroup(p, [ + (node) => _expectPlain(node, 'This one will be '), + (node) => _expectCustom(node, 'red', styleName: 'red'), + (node) => _expectPlain(node, ' and this one will be '), + (node) => _expectCustom(node, 'blue', styleName: 'blue'), + (node) => _expectPlain(node, '.'), + ]); + }), ]); final element = doc.format( @@ -374,46 +375,46 @@ void main() { _expectElementGroup(element, [ (el) => _expectElementGroup(el, [ - (el) => _expectElementGroupText(el, [ - (el) => _expectElementTextPainter( - el, - 'This one will be ', - const TextStyle( - fontSize: 12, - ), - ), - (el) => _expectElementTextPainter( - el, - 'red', - const TextStyle( - fontSize: 12, - color: Color(0xFFFF0000), - ), - ), - (el) => _expectElementTextPainter( - el, - ' and this one will be ', - const TextStyle( - fontSize: 12, - ), - ), - (el) => _expectElementTextPainter( - el, - 'blue', - const TextStyle( - fontSize: 12, - color: Color(0xFF0000FF), - ), - ), - (el) => _expectElementTextPainter( - el, - '.', - const TextStyle( - fontSize: 12, - ), - ), - ]), - ]), + (el) => _expectElementGroupText(el, [ + (el) => _expectElementTextPainter( + el, + 'This one will be ', + const TextStyle( + fontSize: 12, + ), + ), + (el) => _expectElementTextPainter( + el, + 'red', + const TextStyle( + fontSize: 12, + color: Color(0xFFFF0000), + ), + ), + (el) => _expectElementTextPainter( + el, + ' and this one will be ', + const TextStyle( + fontSize: 12, + ), + ), + (el) => _expectElementTextPainter( + el, + 'blue', + const TextStyle( + fontSize: 12, + color: Color(0xFF0000FF), + ), + ), + (el) => _expectElementTextPainter( + el, + '.', + const TextStyle( + fontSize: 12, + ), + ), + ]), + ]), ]); }); }); diff --git a/packages/flame_network_assets/example/pubspec.yaml b/packages/flame_network_assets/example/pubspec.yaml index 627efee48..7eff906a7 100644 --- a/packages/flame_network_assets/example/pubspec.yaml +++ b/packages/flame_network_assets/example/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_network_assets/lib/src/flame_network_assets.dart b/packages/flame_network_assets/lib/src/flame_network_assets.dart index 11d2d947c..efd2e136f 100644 --- a/packages/flame_network_assets/lib/src/flame_network_assets.dart +++ b/packages/flame_network_assets/lib/src/flame_network_assets.dart @@ -10,10 +10,11 @@ import 'package:path/path.dart' as path; import 'package:path_provider/path_provider.dart'; /// Function signature used by Flame Network Assets to fetch assets. -typedef GetAssetFunction = Future Function( - String url, { - Map? headers, -}); +typedef GetAssetFunction = + Future Function( + String url, { + Map? headers, + }); /// Function signature used by Flame Network Assets to decode assets from a /// raw format. @@ -88,20 +89,20 @@ abstract class FlameNetworkAssets { GetAppDirectoryFunction? getAppDirectory, this.cacheInMemory = true, this.cacheInStorage = true, - }) : _isWeb = kIsWeb, - _decode = decodeAsset, - _encode = encodeAsset { - _get = get ?? + }) : _isWeb = kIsWeb, + _decode = decodeAsset, + _encode = encodeAsset { + _get = + get ?? ( String url, { Map? headers, - }) => - http.get(Uri.parse(url), headers: headers).then((response) { - return FlameAssetResponse( - statusCode: response.statusCode, - bytes: response.bodyBytes, - ); - }); + }) => http.get(Uri.parse(url), headers: headers).then((response) { + return FlameAssetResponse( + statusCode: response.statusCode, + bytes: response.bodyBytes, + ); + }); _getAppDirectory = getAppDirectory ?? getApplicationDocumentsDirectory; } diff --git a/packages/flame_network_assets/lib/src/flame_network_images.dart b/packages/flame_network_assets/lib/src/flame_network_images.dart index ed438d1c7..20d25420a 100644 --- a/packages/flame_network_assets/lib/src/flame_network_images.dart +++ b/packages/flame_network_assets/lib/src/flame_network_images.dart @@ -17,11 +17,11 @@ class FlameNetworkImages extends FlameNetworkAssets { super.cacheInMemory, super.cacheInStorage, }) : super( - decodeAsset: decodeImageFromList, - encodeAsset: (Image image) async { - final data = await image.toByteData(format: ImageByteFormat.png); + decodeAsset: decodeImageFromList, + encodeAsset: (Image image) async { + final data = await image.toByteData(format: ImageByteFormat.png); - return data!.buffer.asUint8List(); - }, - ); + return data!.buffer.asUint8List(); + }, + ); } diff --git a/packages/flame_network_assets/pubspec.yaml b/packages/flame_network_assets/pubspec.yaml index 1a2ca47d7..2e9520121 100644 --- a/packages/flame_network_assets/pubspec.yaml +++ b/packages/flame_network_assets/pubspec.yaml @@ -13,7 +13,7 @@ topics: - network-assets environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_network_assets/test/flame_network_image_test.dart b/packages/flame_network_assets/test/flame_network_image_test.dart index 607939328..ba0333823 100644 --- a/packages/flame_network_assets/test/flame_network_image_test.dart +++ b/packages/flame_network_assets/test/flame_network_image_test.dart @@ -67,8 +67,9 @@ void main() { final pngImage = await image.toByteData(format: ImageByteFormat.png); - when(() => httpClient.get(any(), headers: any(named: 'headers'))) - .thenAnswer( + when( + () => httpClient.get(any(), headers: any(named: 'headers')), + ).thenAnswer( (_) async => FlameAssetResponse( statusCode: 200, bytes: pngImage!.buffer.asUint8List(), diff --git a/packages/flame_noise/lib/src/effects/noise_effect_controller.dart b/packages/flame_noise/lib/src/effects/noise_effect_controller.dart index 7fefce9d2..c5790140e 100644 --- a/packages/flame_noise/lib/src/effects/noise_effect_controller.dart +++ b/packages/flame_noise/lib/src/effects/noise_effect_controller.dart @@ -20,8 +20,8 @@ class NoiseEffectController extends DurationEffectController { required double duration, this.taperingCurve = Curves.easeInOutCubic, Noise2? noise, - }) : noise = noise ?? PerlinNoise(), - super(duration); + }) : noise = noise ?? PerlinNoise(), + super(duration); @override double get progress { diff --git a/packages/flame_noise/pubspec.yaml b/packages/flame_noise/pubspec.yaml index 7d86126f0..06bcf399e 100644 --- a/packages/flame_noise/pubspec.yaml +++ b/packages/flame_noise/pubspec.yaml @@ -12,7 +12,7 @@ topics: - noise environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_oxygen/example/lib/main.dart b/packages/flame_oxygen/example/lib/main.dart index 510f82d86..5e20cbc24 100644 --- a/packages/flame_oxygen/example/lib/main.dart +++ b/packages/flame_oxygen/example/lib/main.dart @@ -33,11 +33,11 @@ class ExampleGame extends OxygenGame { final random = Random(); for (var i = 0; i < 10; i++) { createEntity( - name: 'Entity $i', - position: size / 2, - size: Vector2.all(64), - angle: 0, - ) + name: 'Entity $i', + position: size / 2, + size: Vector2.all(64), + angle: 0, + ) ..add( SpriteInit(await loadSprite('pizza.png')), ) diff --git a/packages/flame_oxygen/example/lib/system/kawabunga_system.dart b/packages/flame_oxygen/example/lib/system/kawabunga_system.dart index f592b5d12..b77589ecb 100644 --- a/packages/flame_oxygen/example/lib/system/kawabunga_system.dart +++ b/packages/flame_oxygen/example/lib/system/kawabunga_system.dart @@ -6,9 +6,9 @@ import 'package:flutter/material.dart'; class KawabungaSystem extends BaseSystem with UpdateSystem { @override List> get filters => [ - Has(), - Has(), - ]; + Has(), + Has(), + ]; @override void renderEntity(Canvas canvas, Entity entity) { @@ -16,8 +16,9 @@ class KawabungaSystem extends BaseSystem with UpdateSystem { final textComponent = entity.get()!; final textRenderer = TextPaint( style: textComponent.style.copyWith( - color: - textComponent.style.color!.withValues(alpha: 1 - timer.percentage), + color: textComponent.style.color!.withValues( + alpha: 1 - timer.percentage, + ), ), ); diff --git a/packages/flame_oxygen/example/lib/system/move_system.dart b/packages/flame_oxygen/example/lib/system/move_system.dart index 31eba7967..571f86aac 100644 --- a/packages/flame_oxygen/example/lib/system/move_system.dart +++ b/packages/flame_oxygen/example/lib/system/move_system.dart @@ -36,11 +36,11 @@ class MoveSystem extends System with UpdateSystem, GameRef { velocity.setFrom(-velocity); game!.createEntity( - name: '${entity.name} says', - position: position + size / 2, - size: Vector2.zero(), - anchor: Anchor.topCenter, - ) + name: '${entity.name} says', + position: position + size / 2, + size: Vector2.zero(), + anchor: Anchor.topCenter, + ) ..add( TextInit( 'Kawabunga', diff --git a/packages/flame_oxygen/example/pubspec.yaml b/packages/flame_oxygen/example/pubspec.yaml index a03003570..37f336837 100644 --- a/packages/flame_oxygen/example/pubspec.yaml +++ b/packages/flame_oxygen/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_oxygen/lib/src/flame_world.dart b/packages/flame_oxygen/lib/src/flame_world.dart index c35d9f03e..985149c7b 100644 --- a/packages/flame_oxygen/lib/src/flame_world.dart +++ b/packages/flame_oxygen/lib/src/flame_world.dart @@ -28,6 +28,6 @@ class FlameWorld extends World { @override void execute(double delta) => throw Exception( - 'FlameWorld.execute is not supported in flame_oxygen', - ); + 'FlameWorld.execute is not supported in flame_oxygen', + ); } diff --git a/packages/flame_oxygen/pubspec.yaml b/packages/flame_oxygen/pubspec.yaml index e0971259c..99a6d1b26 100644 --- a/packages/flame_oxygen/pubspec.yaml +++ b/packages/flame_oxygen/pubspec.yaml @@ -11,7 +11,7 @@ topics: - flame environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_rive/example/lib/main.dart b/packages/flame_rive/example/lib/main.dart index 8e9262340..421e57a2e 100644 --- a/packages/flame_rive/example/lib/main.dart +++ b/packages/flame_rive/example/lib/main.dart @@ -10,8 +10,9 @@ void main() { class RiveExampleGame extends FlameGame { @override Future onLoad() async { - final skillsArtboard = - await loadArtboard(RiveFile.asset('assets/skills.riv')); + final skillsArtboard = await loadArtboard( + RiveFile.asset('assets/skills.riv'), + ); add(SkillsAnimationComponent(skillsArtboard)); } } diff --git a/packages/flame_rive/example/pubspec.yaml b/packages/flame_rive/example/pubspec.yaml index 0fa4ff43c..0769fa9ac 100644 --- a/packages/flame_rive/example/pubspec.yaml +++ b/packages/flame_rive/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_rive/lib/src/rive_component.dart b/packages/flame_rive/lib/src/rive_component.dart index dd48d317c..00f2a1f83 100644 --- a/packages/flame_rive/lib/src/rive_component.dart +++ b/packages/flame_rive/lib/src/rive_component.dart @@ -29,13 +29,13 @@ class RiveComponent extends PositionComponent { super.children, super.priority, super.key, - }) : _renderer = RiveArtboardRenderer( - antialiasing: antialiasing, - fit: fit, - alignment: alignment, - artboard: artboard, - ), - super(size: size ?? Vector2(artboard.width, artboard.height)) { + }) : _renderer = RiveArtboardRenderer( + antialiasing: antialiasing, + fit: fit, + alignment: alignment, + artboard: artboard, + ), + super(size: size ?? Vector2(artboard.width, artboard.height)) { void updateRenderSize() { _renderSize = this.size.toSize(); } @@ -93,10 +93,12 @@ class RiveArtboardRenderer { return; } - final x = -1 * bounds[0] - + final x = + -1 * bounds[0] - contentWidth / 2.0 - (alignment.x * contentWidth / 2.0); - final y = -1 * bounds[1] - + final y = + -1 * bounds[1] - contentHeight / 2.0 - (alignment.y * contentHeight / 2.0); @@ -113,12 +115,16 @@ class RiveArtboardRenderer { scaleX = size.width / contentWidth; scaleY = size.height / contentHeight; case BoxFit.contain: - final minScale = - min(size.width / contentWidth, size.height / contentHeight); + final minScale = min( + size.width / contentWidth, + size.height / contentHeight, + ); scaleX = scaleY = minScale; case BoxFit.cover: - final maxScale = - max(size.width / contentWidth, size.height / contentHeight); + final maxScale = max( + size.width / contentWidth, + size.height / contentHeight, + ); scaleX = scaleY = maxScale; case BoxFit.fitHeight: final minScale = size.height / contentHeight; @@ -129,8 +135,10 @@ class RiveArtboardRenderer { case BoxFit.none: scaleX = scaleY = 1.0; case BoxFit.scaleDown: - final minScale = - min(size.width / contentWidth, size.height / contentHeight); + final minScale = min( + size.width / contentWidth, + size.height / contentHeight, + ); scaleX = scaleY = minScale < 1.0 ? minScale : 1.0; } diff --git a/packages/flame_rive/pubspec.yaml b/packages/flame_rive/pubspec.yaml index f65ca24e2..5ec3c9bf1 100644 --- a/packages/flame_rive/pubspec.yaml +++ b/packages/flame_rive/pubspec.yaml @@ -13,7 +13,7 @@ topics: - animations environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_rive/test/flame_rive_test.dart b/packages/flame_rive/test/flame_rive_test.dart index d8ab51428..cedfc2d07 100644 --- a/packages/flame_rive/test/flame_rive_test.dart +++ b/packages/flame_rive/test/flame_rive_test.dart @@ -74,8 +74,9 @@ void main() { }); group('RiveAnimation', () { - testWithFlameGame('Does not Animate when no controller is attach', - (game) async { + testWithFlameGame('Does not Animate when no controller is attach', ( + game, + ) async { final skillsArtboard = await loadArtboard(riveFile); final riveComponent = _RiveComponent(artboard: skillsArtboard); diff --git a/packages/flame_riverpod/example/lib/main.dart b/packages/flame_riverpod/example/lib/main.dart index e2cca1544..e522b7f0d 100644 --- a/packages/flame_riverpod/example/lib/main.dart +++ b/packages/flame_riverpod/example/lib/main.dart @@ -46,10 +46,9 @@ class FlutterCountingComponent extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final textStyle = Theme.of(context) - .textTheme - .headlineSmall - ?.copyWith(color: Colors.white); + final textStyle = Theme.of( + context, + ).textTheme.headlineSmall?.copyWith(color: Colors.white); final stream = ref.watch(countingStreamProvider); return Material( diff --git a/packages/flame_riverpod/example/pubspec.yaml b/packages/flame_riverpod/example/pubspec.yaml index ffa3e97f9..ce2ae86df 100644 --- a/packages/flame_riverpod/example/pubspec.yaml +++ b/packages/flame_riverpod/example/pubspec.yaml @@ -4,7 +4,7 @@ description: Showcasing the flame_riverpod functionality. publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 flame_riverpod: ^5.4.17 diff --git a/packages/flame_riverpod/example/test/widget_test.dart b/packages/flame_riverpod/example/test/widget_test.dart index 9f2d697aa..ebd01d243 100644 --- a/packages/flame_riverpod/example/test/widget_test.dart +++ b/packages/flame_riverpod/example/test/widget_test.dart @@ -6,8 +6,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('Test equality of Flutter Text Widget and Flame Text Component', - (widgetTester) async { + testWidgets('Test equality of Flutter Text Widget and Flame Text Component', ( + widgetTester, + ) async { await widgetTester.pumpWidget( const ProviderScope(child: MyApp()), ); @@ -26,15 +27,17 @@ void main() { // separate [Text] widget. expect(flutterCounterTextFinder, findsNWidgets(2)); - final flutterCounterTextWidgets = - widgetTester.widgetList(flutterCounterTextFinder); + final flutterCounterTextWidgets = widgetTester.widgetList( + flutterCounterTextFinder, + ); // Expect RiverpodAwareGameWidget to exist final riverpodGameWidgetFinder = find.byType(RiverpodAwareGameWidget); expect(riverpodGameWidgetFinder, findsOneWidget); - final gameWidget = widgetTester.widget(riverpodGameWidgetFinder) - as RiverpodAwareGameWidget; + final gameWidget = + widgetTester.widget(riverpodGameWidgetFinder) + as RiverpodAwareGameWidget; // GameWidget contains a FutureBuilder, which calls setState when a Future // completes. We therefore need to pump / re-render the widget to ensure @@ -59,11 +62,12 @@ void main() { // Current count of the stream from the [Text] widget. This is best // retrieved after all pumps. - final flutterCounterTextWidgetOfInterest = - flutterCounterTextWidgets.elementAt(1); + final flutterCounterTextWidgetOfInterest = flutterCounterTextWidgets + .elementAt(1); - final currentCount = - int.parse((flutterCounterTextWidgetOfInterest as Text).data!); + final currentCount = int.parse( + (flutterCounterTextWidgetOfInterest as Text).data!, + ); // Expect equality (in the presented string value) // of the Text Component and the Text Widget diff --git a/packages/flame_riverpod/lib/src/widget.dart b/packages/flame_riverpod/lib/src/widget.dart index 1a1aa691c..a7dbfc0f4 100644 --- a/packages/flame_riverpod/lib/src/widget.dart +++ b/packages/flame_riverpod/lib/src/widget.dart @@ -47,7 +47,7 @@ class RiverpodAwareGameWidgetState extends GameWidgetState var _dependencies = , ProviderSubscription>{}; Map, ProviderSubscription>? - _oldDependencies; + _oldDependencies; final _listeners = >[]; List<_ListenManual>? _manualListeners; @@ -150,20 +150,21 @@ class RiverpodAwareGameWidgetState extends GameWidgetState Res watch(ProviderListenable target) { _assertNotDisposed(); return _dependencies.putIfAbsent(target, () { - final oldDependency = _oldDependencies?.remove(target); + final oldDependency = _oldDependencies?.remove(target); - if (oldDependency != null) { - return oldDependency; - } + if (oldDependency != null) { + return oldDependency; + } - return _container.listen( - target, - // setState call has been replaced with forceBuild, - // to prevent setState calls while the widget is - // building, which throws a framework error. - (_, __) => forceBuild(), - ); - }).read() as Res; + return _container.listen( + target, + // setState call has been replaced with forceBuild, + // to prevent setState calls while the widget is + // building, which throws a framework error. + (_, __) => forceBuild(), + ); + }).read() + as Res; } @override diff --git a/packages/flame_riverpod/pubspec.yaml b/packages/flame_riverpod/pubspec.yaml index 9a1620e8e..8519bfe8d 100644 --- a/packages/flame_riverpod/pubspec.yaml +++ b/packages/flame_riverpod/pubspec.yaml @@ -12,7 +12,7 @@ topics: - state-management environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_riverpod/test/widget_test.dart b/packages/flame_riverpod/test/widget_test.dart index 0f2aebd8b..7f0f9d8f7 100644 --- a/packages/flame_riverpod/test/widget_test.dart +++ b/packages/flame_riverpod/test/widget_test.dart @@ -43,58 +43,60 @@ class WatchingComponent extends Component with RiverpodComponentMixin { void main() { testWidgets( - 'Test registration and de-registration of GameWidget build callbacks', - (widgetTester) async { - final game = MyGame(); - final component = EmptyComponent(); - final key = GlobalKey(); + 'Test registration and de-registration of GameWidget build callbacks', + (widgetTester) async { + final game = MyGame(); + final component = EmptyComponent(); + final key = GlobalKey(); - await widgetTester.pumpWidget( - ProviderScope( - child: MaterialApp( - home: RiverpodAwareGameWidget( - game: game, - key: key, + await widgetTester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: RiverpodAwareGameWidget( + game: game, + key: key, + ), ), ), - ), - ); - await widgetTester.pump(const Duration(seconds: 5)); + ); + await widgetTester.pump(const Duration(seconds: 5)); - expect(game.hasBuildCallbacks, false); + expect(game.hasBuildCallbacks, false); - // Add the custom component - game.add(component); + // Add the custom component + game.add(component); - // Expect the game is ready to play - expect(game.isAttached, true); - expect(game.isMounted, true); - expect(game.isLoaded, true); + // Expect the game is ready to play + expect(game.isAttached, true); + expect(game.isMounted, true); + expect(game.isLoaded, true); - // Pump to ensure the custom component's lifecycle events are handled - await widgetTester.pump(const Duration(seconds: 1)); + // Pump to ensure the custom component's lifecycle events are handled + await widgetTester.pump(const Duration(seconds: 1)); - // Expect the component has added a callback for the game widget's build - // method. - expect(game.hasBuildCallbacks, true); + // Expect the component has added a callback for the game widget's build + // method. + expect(game.hasBuildCallbacks, true); - // Remove the custom component. - game.remove(component); + // Remove the custom component. + game.remove(component); - // Pump to ensure the component has been removed. - await widgetTester.pump(Duration.zero); + // Pump to ensure the component has been removed. + await widgetTester.pump(Duration.zero); - // When the component is removed there should be no onBuild callbacks - // remaining. - expect(game.hasBuildCallbacks, false); + // When the component is removed there should be no onBuild callbacks + // remaining. + expect(game.hasBuildCallbacks, false); - // When the component is removed, there should be no game reference on the - // component. - expect(component.ref.game == null, true); - }); + // When the component is removed, there should be no game reference on the + // component. + expect(component.ref.game == null, true); + }, + ); - testWidgets('Test registration and de-registration of Provider listeners', - (widgetTester) async { + testWidgets('Test registration and de-registration of Provider listeners', ( + widgetTester, + ) async { final game = MyGame(); final component = WatchingComponent(); final key = GlobalKey(); @@ -148,43 +150,44 @@ void main() { }); testWidgets( - 'Test registration and de-registration of Game Provider listeners', - (widgetTester) async { - final game = MyGameWithRefAccess(); - final key = GlobalKey(); + 'Test registration and de-registration of Game Provider listeners', + (widgetTester) async { + final game = MyGameWithRefAccess(); + final key = GlobalKey(); - await widgetTester.pumpWidget( - ProviderScope( - child: MaterialApp( - home: RiverpodAwareGameWidget( - game: game, - key: key, + await widgetTester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: RiverpodAwareGameWidget( + game: game, + key: key, + ), ), ), - ), - ); - await widgetTester.pump(Duration.zero); + ); + await widgetTester.pump(Duration.zero); - // Expect the game is ready to play - expect(game.isAttached, true); - expect(game.isMounted, true); - expect(game.isLoaded, true); + // Expect the game is ready to play + expect(game.isAttached, true); + expect(game.isMounted, true); + expect(game.isLoaded, true); - // Pump to ensure the custom component's lifecycle events are handled - await widgetTester.pump(Duration.zero); + // Pump to ensure the custom component's lifecycle events are handled + await widgetTester.pump(Duration.zero); - // Expect that the GameWidget is initially listening to - // numberProvider - expect(key.currentState?.exists(numberProvider), true); + // Expect that the GameWidget is initially listening to + // numberProvider + expect(key.currentState?.exists(numberProvider), true); - // Replace the widget tree so that the GameWidget gets disposed - await widgetTester.pumpWidget(Container()); - await widgetTester.pumpAndSettle(); + // Replace the widget tree so that the GameWidget gets disposed + await widgetTester.pumpWidget(Container()); + await widgetTester.pumpAndSettle(); - // Expect that the component has been removed from the game. - expect(game.isAttached, false); + // Expect that the component has been removed from the game. + expect(game.isAttached, false); - // Expect that the key no longer has access to a state. - expect(key.currentState, null); - }); + // Expect that the key no longer has access to a state. + expect(key.currentState, null); + }, + ); } diff --git a/packages/flame_spine/example/pubspec.yaml b/packages/flame_spine/example/pubspec.yaml index 43d6ddec8..9a452cda9 100644 --- a/packages/flame_spine/example/pubspec.yaml +++ b/packages/flame_spine/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_spine/lib/src/spine_component.dart b/packages/flame_spine/lib/src/spine_component.dart index b7eca4431..ceaa7ec43 100644 --- a/packages/flame_spine/lib/src/spine_component.dart +++ b/packages/flame_spine/lib/src/spine_component.dart @@ -21,8 +21,8 @@ class SpineComponent extends PositionComponent { super.children, super.priority, super.key, - }) : _ownsDrawable = ownsDrawable, - _boundsProvider = boundsProvider { + }) : _ownsDrawable = ownsDrawable, + _boundsProvider = boundsProvider { _drawable.update(0); _bounds = _boundsProvider.computeBounds(_drawable); size = Vector2(_bounds.width, _bounds.height); diff --git a/packages/flame_spine/pubspec.yaml b/packages/flame_spine/pubspec.yaml index c1cf0a601..6a69da8f0 100644 --- a/packages/flame_spine/pubspec.yaml +++ b/packages/flame_spine/pubspec.yaml @@ -12,7 +12,7 @@ topics: - animations environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_splash_screen/example/pubspec.yaml b/packages/flame_splash_screen/example/pubspec.yaml index 11f877fdc..a6170984e 100644 --- a/packages/flame_splash_screen/example/pubspec.yaml +++ b/packages/flame_splash_screen/example/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: none version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_splash_screen/lib/src/controller.dart b/packages/flame_splash_screen/lib/src/controller.dart index 4999928b2..c5a61b9ca 100644 --- a/packages/flame_splash_screen/lib/src/controller.dart +++ b/packages/flame_splash_screen/lib/src/controller.dart @@ -9,12 +9,12 @@ class FlameSplashController { Duration waitDuration = const Duration(seconds: 2), Duration fadeOutDuration = const Duration(milliseconds: 450), this.autoStart = true, - }) : stepController = FlameSplashControllerStep(0), - durations = FlameSplashDurations( - fadeInDuration, - waitDuration, - fadeOutDuration, - ); + }) : stepController = FlameSplashControllerStep(0), + durations = FlameSplashDurations( + fadeInDuration, + waitDuration, + fadeOutDuration, + ); /// Defines if you want to start the animations right after widget mount. final bool autoStart; diff --git a/packages/flame_splash_screen/lib/src/splash.dart b/packages/flame_splash_screen/lib/src/splash.dart index b94d86451..9e74887c8 100644 --- a/packages/flame_splash_screen/lib/src/splash.dart +++ b/packages/flame_splash_screen/lib/src/splash.dart @@ -72,7 +72,8 @@ class FlameSplashScreenState extends State { @override void didUpdateWidget(FlameSplashScreen oldWidget) { super.didUpdateWidget(oldWidget); - final hasStepsChanged = widget.showBefore != oldWidget.showBefore || + final hasStepsChanged = + widget.showBefore != oldWidget.showBefore || widget.showAfter != oldWidget.showAfter || widget.theme.logoBuilder != oldWidget.theme.logoBuilder; if (hasStepsChanged && diff --git a/packages/flame_splash_screen/pubspec.yaml b/packages/flame_splash_screen/pubspec.yaml index 31b6fd4c8..3d9921c09 100644 --- a/packages/flame_splash_screen/pubspec.yaml +++ b/packages/flame_splash_screen/pubspec.yaml @@ -11,7 +11,7 @@ topics: - flame environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_sprite_fusion/example/pubspec.yaml b/packages/flame_sprite_fusion/example/pubspec.yaml index 8f5f0a63e..cfa3456cd 100644 --- a/packages/flame_sprite_fusion/example/pubspec.yaml +++ b/packages/flame_sprite_fusion/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: "none" version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_component.dart b/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_component.dart index f6824e536..9268aeddb 100644 --- a/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_component.dart +++ b/packages/flame_sprite_fusion/lib/src/sprite_fusion_tilemap_component.dart @@ -34,11 +34,11 @@ class SpriteFusionTilemapComponent extends PositionComponent { super.priority, super.key, }) : super( - size: Vector2( - tilemapData.mapWidth * tilemapData.tileSize, - tilemapData.mapHeight * tilemapData.tileSize, - ), - ) { + size: Vector2( + tilemapData.mapWidth * tilemapData.tileSize, + tilemapData.mapHeight * tilemapData.tileSize, + ), + ) { _spriteBatch = SpriteBatch(spriteSheet.image, useAtlas: useAtlas); for (final data in tilemapData.layers.reversed) { @@ -84,8 +84,9 @@ class SpriteFusionTilemapComponent extends PositionComponent { int? priority, ComponentKey? key, }) async { - final content = await (assetBundle ?? Flame.bundle) - .loadString('$tilemapPrefix$mapJsonFile'); + final content = await (assetBundle ?? Flame.bundle).loadString( + '$tilemapPrefix$mapJsonFile', + ); final json = jsonDecode(content) as Map; diff --git a/packages/flame_sprite_fusion/pubspec.yaml b/packages/flame_sprite_fusion/pubspec.yaml index ecaaf4a46..fefaa88f0 100644 --- a/packages/flame_sprite_fusion/pubspec.yaml +++ b/packages/flame_sprite_fusion/pubspec.yaml @@ -12,7 +12,7 @@ topics: - tilemap environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_sprite_fusion/test/test_asset_bundle.dart b/packages/flame_sprite_fusion/test/test_asset_bundle.dart index a8d4bc20c..fe7ff0e07 100644 --- a/packages/flame_sprite_fusion/test/test_asset_bundle.dart +++ b/packages/flame_sprite_fusion/test/test_asset_bundle.dart @@ -38,9 +38,9 @@ class TestAssetBundle extends CachingAssetBundle { 'No $fileName found in the TestAssetBundle. Did you forget to add it?', ); } - return File(fileName) - .readAsBytes() - .then((bytes) => ByteData.view(Uint8List.fromList(bytes).buffer)); + return File(fileName).readAsBytes().then( + (bytes) => ByteData.view(Uint8List.fromList(bytes).buffer), + ); } @override diff --git a/packages/flame_studio/lib/src/core/component_tree.dart b/packages/flame_studio/lib/src/core/component_tree.dart index 60e750689..b21220c54 100644 --- a/packages/flame_studio/lib/src/core/component_tree.dart +++ b/packages/flame_studio/lib/src/core/component_tree.dart @@ -6,9 +6,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; final componentTreeProvider = StateNotifierProvider((ref) { - final gameState = ref.watch(gameControllerProvider); - return ComponentTreeObserver(gameState.game as FlameGame?); -}); + final gameState = ref.watch(gameControllerProvider); + return ComponentTreeObserver(gameState.game as FlameGame?); + }); @immutable class ComponentTreeNode { @@ -41,9 +41,9 @@ class ComponentTreeNode { @immutable class ComponentTreeState { ComponentTreeState(Component? rootComponent) - : root = rootComponent == null - ? null - : ComponentTreeNode.fromComponent(rootComponent); + : root = rootComponent == null + ? null + : ComponentTreeNode.fromComponent(rootComponent); final ComponentTreeNode? root; @@ -57,7 +57,7 @@ class ComponentTreeState { class ComponentTreeObserver extends StateNotifier { ComponentTreeObserver(Component? rootComponent) - : super(ComponentTreeState(rootComponent)) { + : super(ComponentTreeState(rootComponent)) { if (rootComponent != null) { _refresh(); } diff --git a/packages/flame_studio/lib/src/core/game_controller.dart b/packages/flame_studio/lib/src/core/game_controller.dart index a54549785..5eeb01d96 100644 --- a/packages/flame_studio/lib/src/core/game_controller.dart +++ b/packages/flame_studio/lib/src/core/game_controller.dart @@ -4,8 +4,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; final gameControllerProvider = StateNotifierProvider<_GameController, _GameState>( - (ref) => _GameController(), -); + (ref) => _GameController(), + ); @immutable class _GameState { diff --git a/packages/flame_studio/lib/src/widgets/left_panel.dart b/packages/flame_studio/lib/src/widgets/left_panel.dart index a68a36818..aa91976eb 100644 --- a/packages/flame_studio/lib/src/widgets/left_panel.dart +++ b/packages/flame_studio/lib/src/widgets/left_panel.dart @@ -44,5 +44,6 @@ class _WidthNotifier extends StateNotifier { } } -final leftPanelWidthProvider = - StateNotifierProvider<_WidthNotifier, double>((ref) => _WidthNotifier()); +final leftPanelWidthProvider = StateNotifierProvider<_WidthNotifier, double>( + (ref) => _WidthNotifier(), +); diff --git a/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart b/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart index 777744a43..1acb16179 100644 --- a/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart +++ b/packages/flame_studio/lib/src/widgets/panels/hierarchy_view.dart @@ -69,7 +69,7 @@ class HierarchyViewState extends ConsumerState { class _ListItem extends StatelessWidget { _ListItem(this.state, this.node, this.indent, {required this.isFirst}) - : super(key: ObjectKey(node.component)); + : super(key: ObjectKey(node.component)); final HierarchyViewState state; final ComponentTreeNode node; diff --git a/packages/flame_studio/pubspec.yaml b/packages/flame_studio/pubspec.yaml index c163489d5..1b694fae2 100644 --- a/packages/flame_studio/pubspec.yaml +++ b/packages/flame_studio/pubspec.yaml @@ -10,7 +10,7 @@ funding: - https://patreon.com/bluefireoss environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_svg/example/pubspec.yaml b/packages/flame_svg/example/pubspec.yaml index 8fce85da4..fb87d6ff1 100644 --- a/packages/flame_svg/example/pubspec.yaml +++ b/packages/flame_svg/example/pubspec.yaml @@ -7,7 +7,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_svg/lib/svg.dart b/packages/flame_svg/lib/svg.dart index 636889c35..3d4e4b937 100644 --- a/packages/flame_svg/lib/svg.dart +++ b/packages/flame_svg/lib/svg.dart @@ -13,9 +13,14 @@ class Svg { /// Creates an [Svg] with the received [pictureInfo]. /// Default [pixelRatio] is the device pixel ratio. Svg(this.pictureInfo, {double? pixelRatio}) - : pixelRatio = pixelRatio ?? - WidgetsBinding - .instance.platformDispatcher.views.first.devicePixelRatio; + : pixelRatio = + pixelRatio ?? + WidgetsBinding + .instance + .platformDispatcher + .views + .first + .devicePixelRatio; /// The [PictureInfo] that this [Svg] represents. final PictureInfo pictureInfo; diff --git a/packages/flame_svg/pubspec.yaml b/packages/flame_svg/pubspec.yaml index 2ce0f89ea..17a357777 100644 --- a/packages/flame_svg/pubspec.yaml +++ b/packages/flame_svg/pubspec.yaml @@ -13,7 +13,7 @@ topics: - vector-graphics environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_test/example/pubspec.yaml b/packages/flame_test/example/pubspec.yaml index d0586d25d..28449af3c 100644 --- a/packages/flame_test/example/pubspec.yaml +++ b/packages/flame_test/example/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_test/lib/src/debug_text_renderer.dart b/packages/flame_test/lib/src/debug_text_renderer.dart index fd9035fc8..3135358ca 100644 --- a/packages/flame_test/lib/src/debug_text_renderer.dart +++ b/packages/flame_test/lib/src/debug_text_renderer.dart @@ -87,8 +87,12 @@ class _DebugTextElement extends InlineTextElement { i1 += 1; } rects.add( - Rect.fromLTRB(i0 * charWidth, 0, i1 * charWidth, charHeight) - .deflate(paint.strokeWidth / 2), + Rect.fromLTRB( + i0 * charWidth, + 0, + i1 * charWidth, + charHeight, + ).deflate(paint.strokeWidth / 2), ); i0 = i1; } diff --git a/packages/flame_test/lib/src/flame_test.dart b/packages/flame_test/lib/src/flame_test.dart index a78a70eff..9fd5b3a81 100644 --- a/packages/flame_test/lib/src/flame_test.dart +++ b/packages/flame_test/lib/src/flame_test.dart @@ -45,21 +45,25 @@ extension FlameGameExtension on Component { typedef GameCreateFunction = T Function(); typedef VerifyFunction = dynamic Function(T); -typedef GameWidgetCreateFunction = GameWidget Function( - T game, -); -typedef WidgetVerifyFunction = Future Function( - T, - WidgetTester, -); -typedef WidgetSetupFunction = Future Function( - T, - WidgetTester, -); -typedef PumpWidgetFunction = Future Function( - GameWidget, - WidgetTester tester, -); +typedef GameWidgetCreateFunction = + GameWidget Function( + T game, + ); +typedef WidgetVerifyFunction = + Future Function( + T, + WidgetTester, + ); +typedef WidgetSetupFunction = + Future Function( + T, + WidgetTester, + ); +typedef PumpWidgetFunction = + Future Function( + GameWidget, + WidgetTester tester, + ); /// Customize this class with your specific Game type [T] and a custom /// provider `() -> T`, plus some additional configurations including a game @@ -120,7 +124,8 @@ class GameTester { final gameWidget = createGameWidget?.call(game) ?? GameWidget(game: game); - final pump = pumpWidget ?? + final pump = + pumpWidget ?? (GameWidget pumpWidget, WidgetTester tester) => tester.pumpWidget(pumpWidget); diff --git a/packages/flame_test/lib/src/mock_image.dart b/packages/flame_test/lib/src/mock_image.dart index dd6b95662..fb08230b2 100644 --- a/packages/flame_test/lib/src/mock_image.dart +++ b/packages/flame_test/lib/src/mock_image.dart @@ -23,24 +23,24 @@ Future generateImage([int width = 1, int height = 1]) { } ByteData generatePNGByteData() => ByteData.sublistView( - Uint8List.fromList([ - 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG file signature - 0x00, 0x00, 0x00, 0x0D, // IHDR chunk length - 0x49, 0x48, 0x44, 0x52, // IHDR chunk type - 0x00, 0x00, 0x00, 0x01, // Width: 1 - 0x00, 0x00, 0x00, 0x01, // Height: 1 - 0x08, // Bit depth: 8 - 0x02, // Color type: Truecolor - 0x00, // Compression method: Deflate - 0x00, // Filter method: Adaptive - 0x00, // Interlace method: No interlace - 0x90, 0x77, 0x53, 0xDE, // CRC - 0x00, 0x00, 0x00, 0x0A, // IDAT chunk length - 0x49, 0x44, 0x41, 0x54, // IDAT chunk type - 0x08, 0xD7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, - 0xBC, 0x33, // IDAT data and CRC - 0x00, 0x00, 0x00, 0x00, // IEND chunk length - 0x49, 0x45, 0x4E, 0x44, // IEND chunk type - 0xAE, 0x42, 0x60, 0x82, // CRC - ]), - ); + Uint8List.fromList([ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG file signature + 0x00, 0x00, 0x00, 0x0D, // IHDR chunk length + 0x49, 0x48, 0x44, 0x52, // IHDR chunk type + 0x00, 0x00, 0x00, 0x01, // Width: 1 + 0x00, 0x00, 0x00, 0x01, // Height: 1 + 0x08, // Bit depth: 8 + 0x02, // Color type: Truecolor + 0x00, // Compression method: Deflate + 0x00, // Filter method: Adaptive + 0x00, // Interlace method: No interlace + 0x90, 0x77, 0x53, 0xDE, // CRC + 0x00, 0x00, 0x00, 0x0A, // IDAT chunk length + 0x49, 0x44, 0x41, 0x54, // IDAT chunk type + 0x08, 0xD7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, + 0xBC, 0x33, // IDAT data and CRC + 0x00, 0x00, 0x00, 0x00, // IEND chunk length + 0x49, 0x45, 0x4E, 0x44, // IEND chunk type + 0xAE, 0x42, 0x60, 0x82, // CRC + ]), +); diff --git a/packages/flame_test/lib/src/random_test.dart b/packages/flame_test/lib/src/random_test.dart index c2d5358eb..4f7363cdb 100644 --- a/packages/flame_test/lib/src/random_test.dart +++ b/packages/flame_test/lib/src/random_test.dart @@ -58,10 +58,11 @@ void testRandom( } } -typedef TestWidgetsCallback = Future Function( - Random random, - WidgetTester widgetTester, -); +typedef TestWidgetsCallback = + Future Function( + Random random, + WidgetTester widgetTester, + ); /// This function is equivalent to `testWidgets(name, body)`, except that /// it is better suited for randomized testing: it will create a Random diff --git a/packages/flame_test/lib/src/test_golden.dart b/packages/flame_test/lib/src/test_golden.dart index 29e857f15..4843bc53d 100644 --- a/packages/flame_test/lib/src/test_golden.dart +++ b/packages/flame_test/lib/src/test_golden.dart @@ -41,7 +41,8 @@ void testGolden( testWidgets( testName, (tester) async { - final gameInstance = game ?? + final gameInstance = + game ?? (backgroundColor != null ? GameWithBackgroundColor(backgroundColor) : FlameGame()); @@ -76,10 +77,11 @@ void testGolden( ); } -typedef PrepareFunction = Future Function( - FlameGame game, - WidgetTester tester, -); +typedef PrepareFunction = + Future Function( + FlameGame game, + WidgetTester tester, + ); class GameWithBackgroundColor extends FlameGame { final Color _backgroundColor; diff --git a/packages/flame_test/pubspec.yaml b/packages/flame_test/pubspec.yaml index b53a4cbeb..3738650a0 100644 --- a/packages/flame_test/pubspec.yaml +++ b/packages/flame_test/pubspec.yaml @@ -13,7 +13,7 @@ topics: - testing environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_test/test/close_to_matrix4_test.dart b/packages/flame_test/test/close_to_matrix4_test.dart index 7276b6c5e..2ac79787b 100644 --- a/packages/flame_test/test/close_to_matrix4_test.dart +++ b/packages/flame_test/test/close_to_matrix4_test.dart @@ -18,10 +18,22 @@ void main() { ); expect( Matrix4( - -14, 99, -99, 0, // - 0, 0, 0, 0, // - 1e-20, -1e-16, 0, 0, // - 0, 0, 0, 0, // + -14, + 99, + -99, + 0, // + 0, + 0, + 0, + 0, // + 1e-20, + -1e-16, + 0, + 0, // + 0, + 0, + 0, + 0, // ), closeToMatrix4( Matrix4.columns( diff --git a/packages/flame_test/test/debug_text_formatter_test.dart b/packages/flame_test/test/debug_text_formatter_test.dart index b8577c142..a8c62fb12 100644 --- a/packages/flame_test/test/debug_text_formatter_test.dart +++ b/packages/flame_test/test/debug_text_formatter_test.dart @@ -16,9 +16,9 @@ void main() { DebugTextRenderer().format(' x ')..translate(5, 25), DebugTextRenderer().format(' ')..translate(5, 45), DebugTextRenderer().format('')..translate(25, 45), - DebugTextRenderer(color: const Color(0xFFFF88AA)) - .format('Flame Engine') - ..translate(5, 65), + DebugTextRenderer( + color: const Color(0xFFFF88AA), + ).format('Flame Engine')..translate(5, 65), DebugTextRenderer(fontWeight: FontWeight.bold).format('Blue Fire') ..translate(5, 85), DebugTextRenderer(fontWeight: FontWeight.w900).format('Blue Fire') @@ -29,8 +29,7 @@ void main() { fontWeight: FontWeight.bold, fontStyle: FontStyle.italic, color: const Color(0xFF0088FF), - ).format('a b c d e f g h i') - ..translate(5, 145), + ).format('a b c d e f g h i')..translate(5, 145), DebugTextRenderer(fontSize: 10).format('www.flame-engine.org') ..translate(5, 165), ]), diff --git a/packages/flame_test/test/epsilon_test.dart b/packages/flame_test/test/epsilon_test.dart index dc39a722f..becebadf9 100644 --- a/packages/flame_test/test/epsilon_test.dart +++ b/packages/flame_test/test/epsilon_test.dart @@ -196,7 +196,8 @@ void main() { expect( actualPursuer, closeToVector(targetPosition, tolerance), - reason: 'Pursuer position should be close to target position' + reason: + 'Pursuer position should be close to target position' ' at iteration $i', ); } diff --git a/packages/flame_texturepacker/example/pubspec.yaml b/packages/flame_texturepacker/example/pubspec.yaml index 84ed09312..cbed33a10 100644 --- a/packages/flame_texturepacker/example/pubspec.yaml +++ b/packages/flame_texturepacker/example/pubspec.yaml @@ -5,7 +5,7 @@ version: 1.0.0 publish_to: none environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_texturepacker/lib/flame_texturepacker.dart b/packages/flame_texturepacker/lib/flame_texturepacker.dart index 832717d93..a2cd90dbe 100644 --- a/packages/flame_texturepacker/lib/flame_texturepacker.dart +++ b/packages/flame_texturepacker/lib/flame_texturepacker.dart @@ -17,15 +17,14 @@ extension TexturepackerLoader on Game { bool useOriginalSize = true, List whiteList = const [], String assetsPrefix = 'images', - }) async => - TexturePackerAtlas.load( - assetsPath, - images: images ?? this.images, - assets: assets ?? this.assets, - useOriginalSize: useOriginalSize, - whiteList: whiteList, - assetsPrefix: assetsPrefix, - ); + }) async => TexturePackerAtlas.load( + assetsPath, + images: images ?? this.images, + assets: assets ?? this.assets, + useOriginalSize: useOriginalSize, + whiteList: whiteList, + assetsPrefix: assetsPrefix, + ); /// Loads the specified pack file from storage /// Uses the parent directory of the pack file to find the page images. @@ -34,12 +33,11 @@ extension TexturepackerLoader on Game { Images? images, bool useOriginalSize = true, List whiteList = const [], - }) async => - TexturePackerAtlas.load( - storagePath, - fromStorage: true, - images: images ?? this.images, - useOriginalSize: useOriginalSize, - whiteList: whiteList, - ); + }) async => TexturePackerAtlas.load( + storagePath, + fromStorage: true, + images: images ?? this.images, + useOriginalSize: useOriginalSize, + whiteList: whiteList, + ); } diff --git a/packages/flame_texturepacker/lib/src/texture_packer_atlas.dart b/packages/flame_texturepacker/lib/src/texture_packer_atlas.dart index 98636b5fb..4a3d69a2a 100644 --- a/packages/flame_texturepacker/lib/src/texture_packer_atlas.dart +++ b/packages/flame_texturepacker/lib/src/texture_packer_atlas.dart @@ -193,8 +193,9 @@ Future _parse( assetsPrefix != null, 'When reading from storage, the assetsPrefix needs to be provided.', ); - fileAsString = - await (assets ?? Flame.assets).readFile('$assetsPrefix/$path'); + fileAsString = await (assets ?? Flame.assets).readFile( + '$assetsPrefix/$path', + ); } final iterator = LineSplitter.split(fileAsString).iterator; @@ -366,7 +367,7 @@ Future _parse( final entry = []; entry.add(trimmedLine.substring(0, colonIndex).trim()); - for (var i = 1, lastMatch = colonIndex + 1;; i++) { + for (var i = 1, lastMatch = colonIndex + 1; ; i++) { final commaIndex = trimmedLine.indexOf(',', lastMatch); if (commaIndex == -1) { diff --git a/packages/flame_texturepacker/lib/src/texture_packer_sprite.dart b/packages/flame_texturepacker/lib/src/texture_packer_sprite.dart index 14c699e25..cc27f3b52 100644 --- a/packages/flame_texturepacker/lib/src/texture_packer_sprite.dart +++ b/packages/flame_texturepacker/lib/src/texture_packer_sprite.dart @@ -12,25 +12,25 @@ import 'package:flame_texturepacker/src/model/region.dart'; class TexturePackerSprite extends Sprite { /// {@macro _texture_packer_sprite} TexturePackerSprite(Region region, {this.useOriginalSize = true}) - : _region = region, - name = region.name, - index = region.index, - offsetX = region.offsetX, - offsetY = region.offsetY, - packedWidth = region.width, - packedHeight = region.height, - originalWidth = region.originalWidth, - originalHeight = region.originalHeight, - rotate = region.rotate, - degrees = region.degrees, - super( - region.page.texture, - srcPosition: Vector2(region.left, region.top), - srcSize: Vector2( - useOriginalSize ? region.originalWidth : region.width, - useOriginalSize ? region.originalHeight : region.height, - ), - ) { + : _region = region, + name = region.name, + index = region.index, + offsetX = region.offsetX, + offsetY = region.offsetY, + packedWidth = region.width, + packedHeight = region.height, + originalWidth = region.originalWidth, + originalHeight = region.originalHeight, + rotate = region.rotate, + degrees = region.degrees, + super( + region.page.texture, + srcPosition: Vector2(region.left, region.top), + srcSize: Vector2( + useOriginalSize ? region.originalWidth : region.width, + useOriginalSize ? region.originalHeight : region.height, + ), + ) { if (region.rotate) { final transform = Transform2D()..angle = math.pi / 2; _decorator = Transform2DDecorator(transform); diff --git a/packages/flame_texturepacker/pubspec.yaml b/packages/flame_texturepacker/pubspec.yaml index b13ed023c..715344585 100644 --- a/packages/flame_texturepacker/pubspec.yaml +++ b/packages/flame_texturepacker/pubspec.yaml @@ -12,7 +12,7 @@ topics: - spritesheet environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_texturepacker/test/flame_texturepacker_test.dart b/packages/flame_texturepacker/test/flame_texturepacker_test.dart index 82bd04582..fb3c06e5a 100644 --- a/packages/flame_texturepacker/test/flame_texturepacker_test.dart +++ b/packages/flame_texturepacker/test/flame_texturepacker_test.dart @@ -34,8 +34,9 @@ void main() { test('load atlas from assets', () async { final bundle = _MockAssetBundle(); - when(() => bundle.loadString(any())) - .thenAnswer((_) async => File(atlasPath).readAsString()); + when( + () => bundle.loadString(any()), + ).thenAnswer((_) async => File(atlasPath).readAsString()); when(() => bundle.load(any())).thenAnswer( (_) async => ByteData.sublistView( File(atlasImage1).readAsBytesSync(), diff --git a/packages/flame_tiled/example/lib/main.dart b/packages/flame_tiled/example/lib/main.dart index 639cab92a..5474d03d0 100644 --- a/packages/flame_tiled/example/lib/main.dart +++ b/packages/flame_tiled/example/lib/main.dart @@ -13,12 +13,12 @@ class TiledGame extends FlameGame { late TiledComponent mapComponent; TiledGame() - : super( - camera: CameraComponent.withFixedResolution( - width: 16 * 28, - height: 16 * 14, - ), - ); + : super( + camera: CameraComponent.withFixedResolution( + width: 16 * 28, + height: 16 * 14, + ), + ); @override Future onLoad() async { @@ -39,8 +39,9 @@ class TiledGame extends FlameGame { mapComponent = await TiledComponent.load('map.tmx', Vector2.all(16)); world.add(mapComponent); - final objectGroup = - mapComponent.tileMap.getLayer('AnimatedCoins'); + final objectGroup = mapComponent.tileMap.getLayer( + 'AnimatedCoins', + ); final coins = await Flame.images.load('coins.png'); // We are 100% sure that an object layer named `AnimatedCoins` diff --git a/packages/flame_tiled/example/pubspec.yaml b/packages/flame_tiled/example/pubspec.yaml index f8f10c92e..3e90e7001 100644 --- a/packages/flame_tiled/example/pubspec.yaml +++ b/packages/flame_tiled/example/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dependencies: flame: ^1.30.1 diff --git a/packages/flame_tiled/lib/src/mutable_rect.dart b/packages/flame_tiled/lib/src/mutable_rect.dart index 10a6e6e4f..3fa92f253 100644 --- a/packages/flame_tiled/lib/src/mutable_rect.dart +++ b/packages/flame_tiled/lib/src/mutable_rect.dart @@ -4,7 +4,7 @@ import 'dart:ui' show Rect; class MutableRect extends Rect { /// Construct a rectangle from its left, top, right, and bottom edges. MutableRect.fromLTRB(this.left, this.top, this.right, this.bottom) - : super.fromLTRB(left, top, right, bottom); + : super.fromLTRB(left, top, right, bottom); /// Create a new instance from [other]. factory MutableRect.fromRect(Rect other) => diff --git a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/tile_layer.dart b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/tile_layer.dart index f1d1b168c..4dbf871ff 100644 --- a/packages/flame_tiled/lib/src/renderable_layers/tile_layers/tile_layer.dart +++ b/packages/flame_tiled/lib/src/renderable_layers/tile_layers/tile_layer.dart @@ -73,49 +73,49 @@ abstract class FlameTileLayer extends RenderableLayer { return switch (mapOrientation) { MapOrientation.isometric => IsometricTileLayer( - layer: layer, - parent: parent, - map: map, - destTileSize: destTileSize, - tiledAtlas: atlas, - animationFrames: animationFrames, - ignoreFlip: ignoreFlip, - filterQuality: filterQuality, - layerPaintFactory: layerPaintFactory, - ), + layer: layer, + parent: parent, + map: map, + destTileSize: destTileSize, + tiledAtlas: atlas, + animationFrames: animationFrames, + ignoreFlip: ignoreFlip, + filterQuality: filterQuality, + layerPaintFactory: layerPaintFactory, + ), MapOrientation.staggered => StaggeredTileLayer( - layer: layer, - parent: parent, - map: map, - destTileSize: destTileSize, - tiledAtlas: atlas, - animationFrames: animationFrames, - ignoreFlip: ignoreFlip, - filterQuality: filterQuality, - layerPaintFactory: layerPaintFactory, - ), + layer: layer, + parent: parent, + map: map, + destTileSize: destTileSize, + tiledAtlas: atlas, + animationFrames: animationFrames, + ignoreFlip: ignoreFlip, + filterQuality: filterQuality, + layerPaintFactory: layerPaintFactory, + ), MapOrientation.hexagonal => HexagonalTileLayer( - layer: layer, - parent: parent, - map: map, - destTileSize: destTileSize, - tiledAtlas: atlas, - animationFrames: animationFrames, - ignoreFlip: ignoreFlip, - filterQuality: filterQuality, - layerPaintFactory: layerPaintFactory, - ), + layer: layer, + parent: parent, + map: map, + destTileSize: destTileSize, + tiledAtlas: atlas, + animationFrames: animationFrames, + ignoreFlip: ignoreFlip, + filterQuality: filterQuality, + layerPaintFactory: layerPaintFactory, + ), MapOrientation.orthogonal => OrthogonalTileLayer( - layer: layer, - parent: parent, - map: map, - destTileSize: destTileSize, - tiledAtlas: atlas, - animationFrames: animationFrames, - ignoreFlip: ignoreFlip, - filterQuality: filterQuality, - layerPaintFactory: layerPaintFactory, - ), + layer: layer, + parent: parent, + map: map, + destTileSize: destTileSize, + tiledAtlas: atlas, + animationFrames: animationFrames, + ignoreFlip: ignoreFlip, + filterQuality: filterQuality, + layerPaintFactory: layerPaintFactory, + ), }; } diff --git a/packages/flame_tiled/lib/src/renderable_tile_map.dart b/packages/flame_tiled/lib/src/renderable_tile_map.dart index 93e839a4e..f812cd1ef 100644 --- a/packages/flame_tiled/lib/src/renderable_tile_map.dart +++ b/packages/flame_tiled/lib/src/renderable_tile_map.dart @@ -210,7 +210,8 @@ class RenderableTiledMap { y, named: named, ids: ids, - all: all || + all: + all || named.contains(layer.layer.name) || ids.contains(layer.layer.id), ), @@ -257,8 +258,9 @@ class RenderableTiledMap { double atlasPackingSpacingX = 0, double atlasPackingSpacingY = 0, }) async { - final contents = - await (bundle ?? Flame.bundle).loadString('$prefix$fileName'); + final contents = await (bundle ?? Flame.bundle).loadString( + '$prefix$fileName', + ); return fromString( contents, destTileSize, diff --git a/packages/flame_tiled/lib/src/tile_atlas.dart b/packages/flame_tiled/lib/src/tile_atlas.dart index ad54f4996..b02192e7c 100644 --- a/packages/flame_tiled/lib/src/tile_atlas.dart +++ b/packages/flame_tiled/lib/src/tile_atlas.dart @@ -40,12 +40,12 @@ class TiledAtlas { required this.key, this.useAtlas = true, }) : batch = atlas == null - ? null - : SpriteBatch( - atlas, - imageKey: key, - useAtlas: useAtlas, - ); + ? null + : SpriteBatch( + atlas, + imageKey: key, + useAtlas: useAtlas, + ); /// Returns whether or not this atlas contains [source]. bool contains(String? source) => offsets.containsKey(source); @@ -53,11 +53,11 @@ class TiledAtlas { /// Create a new atlas from this object with the intent of getting a new /// [SpriteBatch]. TiledAtlas clone() => TiledAtlas._( - atlas: atlas?.clone(), - offsets: offsets, - key: key, - useAtlas: useAtlas, - ); + atlas: atlas?.clone(), + offsets: offsets, + key: key, + useAtlas: useAtlas, + ); /// Maps of tilesets compiled to [TiledAtlas]. /// diff --git a/packages/flame_tiled/lib/src/tiled_component.dart b/packages/flame_tiled/lib/src/tiled_component.dart index 6f08224d9..1a4ceff68 100644 --- a/packages/flame_tiled/lib/src/tiled_component.dart +++ b/packages/flame_tiled/lib/src/tiled_component.dart @@ -54,16 +54,16 @@ class TiledComponent extends PositionComponent super.priority, super.key, }) : super( - size: computeSize( - tileMap.map.orientation, - tileMap.destTileSize, - tileMap.map.tileWidth, - tileMap.map.tileHeight, - tileMap.map.width, - tileMap.map.height, - tileMap.map.staggerAxis, - ), - ); + size: computeSize( + tileMap.map.orientation, + tileMap.destTileSize, + tileMap.map.tileWidth, + tileMap.map.tileHeight, + tileMap.map.width, + tileMap.map.height, + tileMap.map.staggerAxis, + ), + ); @override Future? onLoad() async { diff --git a/packages/flame_tiled/pubspec.yaml b/packages/flame_tiled/pubspec.yaml index 054ac405f..35b8f553c 100644 --- a/packages/flame_tiled/pubspec.yaml +++ b/packages/flame_tiled/pubspec.yaml @@ -13,7 +13,7 @@ topics: - tilemap environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: diff --git a/packages/flame_tiled/test/test_asset_bundle.dart b/packages/flame_tiled/test/test_asset_bundle.dart index a8d4bc20c..fe7ff0e07 100644 --- a/packages/flame_tiled/test/test_asset_bundle.dart +++ b/packages/flame_tiled/test/test_asset_bundle.dart @@ -38,9 +38,9 @@ class TestAssetBundle extends CachingAssetBundle { 'No $fileName found in the TestAssetBundle. Did you forget to add it?', ); } - return File(fileName) - .readAsBytes() - .then((bytes) => ByteData.view(Uint8List.fromList(bytes).buffer)); + return File(fileName).readAsBytes().then( + (bytes) => ByteData.view(Uint8List.fromList(bytes).buffer), + ); } @override diff --git a/packages/flame_tiled/test/tile_atlas_test.dart b/packages/flame_tiled/test/tile_atlas_test.dart index a465192e0..3bb787820 100644 --- a/packages/flame_tiled/test/tile_atlas_test.dart +++ b/packages/flame_tiled/test/tile_atlas_test.dart @@ -207,42 +207,43 @@ void main() { }); test( - '''Two maps with a same tileset but different tile alignment should be rendered differently''', - () async { - final components = await Future.wait([ - TiledComponent.load( - 'single_tile_map_1.tmx', - Vector2(16, 16), - bundle: bundle, - images: Images(bundle: bundle), - ), - TiledComponent.load( - 'single_tile_map_2.tmx', - Vector2(16, 16), - bundle: bundle, - images: Images(bundle: bundle), - ), - ]); + '''Two maps with a same tileset but different tile alignment should be rendered differently''', + () async { + final components = await Future.wait([ + TiledComponent.load( + 'single_tile_map_1.tmx', + Vector2(16, 16), + bundle: bundle, + images: Images(bundle: bundle), + ), + TiledComponent.load( + 'single_tile_map_2.tmx', + Vector2(16, 16), + bundle: bundle, + images: Images(bundle: bundle), + ), + ]); - final atlas = TiledAtlas.atlasMap.values.first; - final imageRendered_1 = renderMapToPng(components[0]); - final imageRendered_2 = renderMapToPng(components[1]); + final atlas = TiledAtlas.atlasMap.values.first; + final imageRendered_1 = renderMapToPng(components[0]); + final imageRendered_2 = renderMapToPng(components[1]); - expect(TiledAtlas.atlasMap.length, 1); - expect( - await imageToPng(atlas.atlas!), - matchesGoldenFile('goldens/single_tile_atlas.png'), - ); - expect(imageRendered_1, isNot(same(imageRendered_2))); - expect( - imageRendered_1, - matchesGoldenFile('goldens/single_tile_map_1.png'), - ); - expect( - imageRendered_2, - matchesGoldenFile('goldens/single_tile_map_2.png'), - ); - }); + expect(TiledAtlas.atlasMap.length, 1); + expect( + await imageToPng(atlas.atlas!), + matchesGoldenFile('goldens/single_tile_atlas.png'), + ); + expect(imageRendered_1, isNot(same(imageRendered_2))); + expect( + imageRendered_1, + matchesGoldenFile('goldens/single_tile_map_1.png'), + ); + expect( + imageRendered_2, + matchesGoldenFile('goldens/single_tile_map_2.png'), + ); + }, + ); }); }); } diff --git a/packages/flame_tiled/test/tiled_test.dart b/packages/flame_tiled/test/tiled_test.dart index b6575f861..0f3ed524c 100644 --- a/packages/flame_tiled/test/tiled_test.dart +++ b/packages/flame_tiled/test/tiled_test.dart @@ -215,7 +215,8 @@ void main() { var allRed = true; for (var i = 0; i < rightTilePixels.length; i += pixel) { - allRed &= rightTilePixels[i] == 255 && + allRed &= + rightTilePixels[i] == 255 && rightTilePixels[i + 1] == 0 && rightTilePixels[i + 2] == 0 && rightTilePixels[i + 3] == 255; @@ -239,7 +240,8 @@ void main() { var allGreen = true; for (var i = 0; i < leftTilePixels.length; i += pixel) { - allGreen &= leftTilePixels[i] == 0 && + allGreen &= + leftTilePixels[i] == 0 && leftTilePixels[i + 1] == 255 && leftTilePixels[i + 2] == 0 && leftTilePixels[i + 3] == 255; @@ -286,16 +288,20 @@ void main() { test('[useAtlas = true] Green tile pixels are in correct spots', () { const oneColorRect = 8; final leftTilePixels = []; - for (var i = 65 * oneColorRect * pixel; - i < ((64 * 23) + (oneColorRect * 3)) * pixel; - i += 64 * pixel) { - leftTilePixels - .addAll(pixelsAfterFlipApplied.getRange(i, i + (16 * pixel))); + for ( + var i = 65 * oneColorRect * pixel; + i < ((64 * 23) + (oneColorRect * 3)) * pixel; + i += 64 * pixel + ) { + leftTilePixels.addAll( + pixelsAfterFlipApplied.getRange(i, i + (16 * pixel)), + ); } var allGreen = true; for (var i = 0; i < leftTilePixels.length; i += pixel) { - allGreen &= leftTilePixels[i] == 0 && + allGreen &= + leftTilePixels[i] == 0 && leftTilePixels[i + 1] == 255 && leftTilePixels[i + 2] == 0 && leftTilePixels[i + 3] == 255; @@ -303,15 +309,19 @@ void main() { expect(allGreen, true); final rightTilePixels = []; - for (var i = 69 * 8 * pixel; - i < ((64 * 23) + (8 * 7)) * pixel; - i += 64 * pixel) { - rightTilePixels - .addAll(pixelsAfterFlipApplied.getRange(i, i + (16 * pixel))); + for ( + var i = 69 * 8 * pixel; + i < ((64 * 23) + (8 * 7)) * pixel; + i += 64 * pixel + ) { + rightTilePixels.addAll( + pixelsAfterFlipApplied.getRange(i, i + (16 * pixel)), + ); } for (var i = 0; i < rightTilePixels.length; i += pixel) { - allGreen &= rightTilePixels[i] == 0 && + allGreen &= + rightTilePixels[i] == 0 && rightTilePixels[i + 1] == 255 && rightTilePixels[i + 2] == 0 && rightTilePixels[i + 3] == 255; @@ -321,16 +331,20 @@ void main() { test('[useAtlas = false] Green tile pixels are in correct spots', () { final leftTilePixels = []; - for (var i = 65 * 8 * pixel; - i < ((64 * 23) + (8 * 3)) * pixel; - i += 64 * pixel) { - leftTilePixels - .addAll(pixelsBeforeFlipApplied.getRange(i, i + (16 * pixel))); + for ( + var i = 65 * 8 * pixel; + i < ((64 * 23) + (8 * 3)) * pixel; + i += 64 * pixel + ) { + leftTilePixels.addAll( + pixelsBeforeFlipApplied.getRange(i, i + (16 * pixel)), + ); } var allGreen = true; for (var i = 0; i < leftTilePixels.length; i += pixel) { - allGreen &= leftTilePixels[i] == 0 && + allGreen &= + leftTilePixels[i] == 0 && leftTilePixels[i + 1] == 255 && leftTilePixels[i + 2] == 0 && leftTilePixels[i + 3] == 255; @@ -338,15 +352,19 @@ void main() { expect(allGreen, true); final rightTilePixels = []; - for (var i = 69 * 8 * pixel; - i < ((64 * 23) + (8 * 7)) * pixel; - i += 64 * pixel) { - rightTilePixels - .addAll(pixelsBeforeFlipApplied.getRange(i, i + (16 * pixel))); + for ( + var i = 69 * 8 * pixel; + i < ((64 * 23) + (8 * 7)) * pixel; + i += 64 * pixel + ) { + rightTilePixels.addAll( + pixelsBeforeFlipApplied.getRange(i, i + (16 * pixel)), + ); } for (var i = 0; i < rightTilePixels.length; i += pixel) { - allGreen &= rightTilePixels[i] == 0 && + allGreen &= + rightTilePixels[i] == 0 && rightTilePixels[i + 1] == 255 && rightTilePixels[i + 2] == 0 && rightTilePixels[i + 3] == 255; @@ -1098,8 +1116,11 @@ void main() { test('same TileData is found by layerId and layerIndex', () { final tileData1 = renderableTiledMap.getTileData(layerId: 6, x: 5, y: 3); - final tileData2 = - renderableTiledMap.getTileDataByLayerIndex(layerIndex: 4, x: 5, y: 3); + final tileData2 = renderableTiledMap.getTileDataByLayerIndex( + layerIndex: 4, + x: 5, + y: 3, + ); expect(tileData1, isNotNull); expect(tileData2, isNotNull); expect(tileData1, equals(tileData2)); diff --git a/pubspec.yaml b/pubspec.yaml index ed3ae8028..d89bea8ae 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -65,7 +65,7 @@ workspace: - examples environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" dev_dependencies: melos: ^7.0.0-dev.7 @@ -82,7 +82,7 @@ melos: bootstrap: environment: - sdk: ">=3.6.0 <4.0.0" + sdk: ">=3.8.0 <4.0.0" flutter: ">=3.27.1" dependencies: meta: ^1.12.0