feat: Package for loading XML spritesheets by kenney.nl (#3205)

A parsing package for https://kenney.nl spritesheets.
This commit is contained in:
Lukas Klingsbo
2024-06-24 23:42:45 +02:00
committed by GitHub
parent 6e517fa229
commit fd6719a677
18 changed files with 463 additions and 0 deletions

View File

@ -6,6 +6,7 @@ erickzanardo # github.com/erickzanardo
feroult # github.com/feroult
fröber # github.com/Brixto
gnarhard # github.com/gnarhard
kenney # kenney.nl
Klingsbo # github.com/spydon
luanpotter # github.com/luanpotter
Lukas # github.com/spydon

View File

@ -0,0 +1,10 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "7482962148e8d758338d8a28f589f317e1e42ba4"
channel: "stable"
project_type: package

View File

@ -0,0 +1,4 @@
## 0.1.0
- **FEAT**: Add initial version of `flame_kenney_xml`.

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Blue Fire
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,41 @@
<!-- markdownlint-disable MD013 -->
<p align="center">
<a href="https://flame-engine.org">
<img alt="flame" width="200px" src="https://user-images.githubusercontent.com/6718144/101553774-3bc7b000-39ad-11eb-8a6a-de2daa31bd64.png">
</a>
</p>
<p align="center">
Adds support for parsing XML sprite sheets from https://kenney.nl, and other sprite sheets on the same format.
</p>
<p align="center">
<a title="Pub" href="https://pub.dev/packages/flame_kenney_xml" ><img src="https://img.shields.io/pub/v/flame_kenney_xml.svg?style=popout" /></a>
<a title="Test" href="https://github.com/flame-engine/flame/actions?query=workflow%3Acicd+branch%3Amain"><img src="https://github.com/flame-engine/flame/workflows/cicd/badge.svg?branch=main&event=push"/></a>
<a title="Discord" href="https://discord.gg/pxrBmy4"><img src="https://img.shields.io/discord/509714518008528896.svg"/></a>
<a title="Melos" href="https://github.com/invertase/melos"><img src="https://img.shields.io/badge/maintained%20with-melos-f700ff.svg"/></a>
</p>
---
<!-- markdownlint-enable MD013 -->
## Getting started
To get started, first add `flame_kenney_xml` as a dependency in your flutter project.
```bash
flutter pub add flame_kenney_xml
```
Then place the `spritesheet.json` in `assets/` and `spritesheet.png` in `assets/images/`
(or whatever the names of the files are).
Then load the image and the spritesheet using:
```dart
final spritesheet = await XmlSpriteSheet.load(
image: 'spritesheet.png',
xml: 'spritesheet.xml`,
);
```

View File

@ -0,0 +1 @@
include: package:flame_lint/analysis_options.yaml

View File

@ -0,0 +1,43 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release

View File

@ -0,0 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "761747bfc538b5af34aa0d3fac380f1bc331ec49"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- platform: linux
create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'

View File

@ -0,0 +1,3 @@
# flame_kenney_xml example
An example of how to use the flame_kenney_xml package.

View File

@ -0,0 +1 @@
include: package:flame_lint/analysis_options.yaml

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

View File

@ -0,0 +1,14 @@
###############################################################################
Physics asset pack by Kenney Vleugels (www.kenney.nl)
------------------------------
License (CC0)
http://creativecommons.org/publicdomain/zero/1.0/
You may use these graphics in personal and commercial projects.
Credit (Kenney or www.kenney.nl) would be nice but is not mandatory.
###############################################################################

View File

@ -0,0 +1,57 @@
<TextureAtlas imagePath="sheet.png">
<SubTexture name="elementStone000.png" x="220" y="720" width="140" height="70"/>
<SubTexture name="elementStone001.png" x="570" y="640" width="70" height="70"/>
<SubTexture name="elementStone002.png" x="710" y="930" width="70" height="70"/>
<SubTexture name="elementStone003.png" x="500" y="70" width="140" height="70"/>
<SubTexture name="elementStone004.png" x="710" y="640" width="70" height="70"/>
<SubTexture name="elementStone005.png" x="710" y="570" width="70" height="70"/>
<SubTexture name="elementStone006.png" x="360" y="500" width="140" height="70"/>
<SubTexture name="elementStone007.png" x="710" y="360" width="70" height="70"/>
<SubTexture name="elementStone008.png" x="710" y="290" width="70" height="70"/>
<SubTexture name="elementStone009.png" x="360" y="710" width="140" height="70"/>
<SubTexture name="elementStone010.png" x="710" y="0" width="70" height="70"/>
<SubTexture name="elementStone011.png" x="640" y="940" width="70" height="70"/>
<SubTexture name="elementStone012.png" x="500" y="570" width="140" height="70"/>
<SubTexture name="elementStone013.png" x="0" y="70" width="220" height="70"/>
<SubTexture name="elementStone014.png" x="640" y="580" width="70" height="70"/>
<SubTexture name="elementStone015.png" x="500" y="280" width="140" height="70"/>
<SubTexture name="elementStone016.png" x="0" y="280" width="220" height="70"/>
<SubTexture name="elementStone017.png" x="640" y="220" width="70" height="140"/>
<SubTexture name="elementStone018.png" x="500" y="140" width="140" height="140"/>
<SubTexture name="elementStone019.png" x="0" y="630" width="220" height="140"/>
<SubTexture name="elementStone020.png" x="710" y="710" width="70" height="220"/>
<SubTexture name="elementStone021.png" x="500" y="350" width="140" height="220"/>
<SubTexture name="elementStone022.png" x="710" y="430" width="70" height="140"/>
<SubTexture name="elementStone023.png" x="360" y="360" width="140" height="140"/>
<SubTexture name="elementStone024.png" x="0" y="840" width="220" height="140"/>
<SubTexture name="elementStone025.png" x="640" y="0" width="70" height="220"/>
<SubTexture name="elementStone026.png" x="360" y="780" width="140" height="220"/>
<SubTexture name="elementStone027.png" x="500" y="640" width="70" height="70"/>
<SubTexture name="elementStone028.png" x="360" y="70" width="140" height="70"/>
<SubTexture name="elementStone029.png" x="220" y="0" width="220" height="70"/>
<SubTexture name="elementStone030.png" x="500" y="780" width="70" height="70"/>
<SubTexture name="elementStone031.png" x="440" y="0" width="140" height="70"/>
<SubTexture name="elementStone032.png" x="0" y="770" width="220" height="70"/>
<SubTexture name="elementStone033.png" x="500" y="850" width="70" height="140"/>
<SubTexture name="elementStone034.png" x="360" y="570" width="140" height="140"/>
<SubTexture name="elementStone035.png" x="0" y="490" width="220" height="140"/>
<SubTexture name="elementStone036.png" x="710" y="70" width="70" height="220"/>
<SubTexture name="elementStone037.png" x="360" y="140" width="140" height="220"/>
<SubTexture name="elementStone038.png" x="570" y="780" width="70" height="140"/>
<SubTexture name="elementStone039.png" x="220" y="860" width="140" height="140"/>
<SubTexture name="elementStone040.png" x="0" y="140" width="220" height="140"/>
<SubTexture name="elementStone041.png" x="640" y="720" width="70" height="220"/>
<SubTexture name="elementStone042.png" x="220" y="500" width="140" height="220"/>
<SubTexture name="elementStone043.png" x="500" y="710" width="70" height="70"/>
<SubTexture name="elementStone044.png" x="220" y="290" width="140" height="70"/>
<SubTexture name="elementStone045.png" x="570" y="710" width="70" height="70"/>
<SubTexture name="elementStone046.png" x="570" y="920" width="70" height="70"/>
<SubTexture name="elementStone047.png" x="220" y="790" width="140" height="70"/>
<SubTexture name="elementStone048.png" x="0" y="0" width="220" height="70"/>
<SubTexture name="elementStone049.png" x="780" y="0" width="70" height="140"/>
<SubTexture name="elementStone050.png" x="220" y="360" width="140" height="140"/>
<SubTexture name="elementStone051.png" x="0" y="350" width="220" height="140"/>
<SubTexture name="elementStone052.png" x="640" y="360" width="70" height="220"/>
<SubTexture name="elementStone053.png" x="220" y="70" width="140" height="220"/>
<SubTexture name="elementStone054.png" x="640" y="650" width="70" height="70"/>
</TextureAtlas>

View File

@ -0,0 +1,45 @@
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame_kenney_xml/xml_sprite_sheet.dart';
import 'package:flutter/material.dart';
/// A simple game that adds a random sprite component created from a kenney.nl
/// sprite sheet to the screen when tapped.
void main() {
runApp(
GameWidget.controlled(
gameFactory: () => FlameGame(world: KenneyWorld()),
),
);
}
class KenneyWorld extends World with TapCallbacks {
late final XmlSpriteSheet spritesheet;
@override
Future<void> onLoad() async {
spritesheet = await XmlSpriteSheet.load(
imagePath: 'spritesheet_stone.png',
xmlPath: 'spritesheet_stone.xml',
);
add(randomSpriteComponent());
}
@override
void onTapDown(TapDownEvent event) {
add(randomSpriteComponent(position: event.localPosition));
}
SpriteComponent randomSpriteComponent({Vector2? position}) {
final name = spritesheet.spriteNames.random();
return SpriteComponent(
sprite: spritesheet.getSprite(name),
position: position,
anchor: Anchor.center,
);
}
}

View File

@ -0,0 +1,23 @@
name: flame_kenney_xml_example
description: "An example for the `XmlSpriteSheet` used to load kenney.nl assets."
publish_to: "none"
version: 1.0.0
environment:
sdk: ">=3.4.0 <4.0.0"
dependencies:
flame: ^1.18.0
flame_kenney_xml: ^0.1.2
flutter:
sdk: flutter
dev_dependencies:
flame_lint: ^1.2.0
flutter:
assets:
- assets/
- assets/images/

View File

@ -0,0 +1,66 @@
import 'package:flame/cache.dart';
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/flame.dart';
import 'package:xml/xml.dart';
import 'package:xml/xpath.dart';
/// A sprite sheet loaded from an XML file and an image.
///
/// The XML file must be in the format of a ShoeBox XML file, formatted in the
/// same way as the Kenney.nl sprite sheets.
/// https://twitter.com/KenneyNL/status/1777429120936202344
class XmlSpriteSheet {
XmlSpriteSheet({
required this.image,
required String xml,
}) {
final document = XmlDocument.parse(xml);
for (final node in document.xpath('//TextureAtlas/SubTexture')) {
final name = node.getAttribute('name')!;
final x = double.parse(node.getAttribute('x')!);
final y = double.parse(node.getAttribute('y')!);
final width = double.parse(node.getAttribute('width')!);
final height = double.parse(node.getAttribute('height')!);
_spriteBoundaries[name] = Rect.fromLTWH(x, y, width, height);
}
}
/// Load an [XmlSpriteSheet] from an image and an XML file.
///
/// The [imagePath] should be in relation to `assets/images/`.
/// The [xmlPath] should be in relation to `assets/`.
static Future<XmlSpriteSheet> load({
required String imagePath,
required String xmlPath,
Images? imageCache,
AssetsCache? assetsCache,
}) async {
final image = await (imageCache ?? Flame.images).load(imagePath);
final xml = await (assetsCache ?? Flame.assets).readFile(xmlPath);
return XmlSpriteSheet(image: image, xml: xml);
}
final Image image;
final _spriteBoundaries = <String, Rect>{};
late final List<String> spriteNames = _spriteBoundaries.keys.toList();
/// Get a sprite from the sprite sheet by its name.
///
/// Throws an [ArgumentError] if the sprite is not found.
Sprite getSprite(String name) {
final rect = _spriteBoundaries[name];
if (rect == null) {
throw ArgumentError('Sprite $name not found');
}
return Sprite(
image,
srcPosition: rect.topLeft.toVector2(),
srcSize: rect.size.toVector2(),
);
}
/// Get a random sprite from the sprite sheet.
Sprite getRandomSprite() => getSprite(spriteNames.random());
}

View File

@ -0,0 +1,30 @@
name: flame_kenney_xml
description: "Support for Kenney XML spritesheets for the Flame game engine. This package parses XML files produced by Kenney."
version: 0.1.2
homepage: https://github.com/flame-engine/flame/tree/main/packages/flame_kenney_xml
funding:
- https://opencollective.com/blue-fire
- https://github.com/sponsors/bluefireteam
- https://patreon.com/bluefireoss
topics:
- flame
- spritesheet
- kenney
- tilemap
environment:
sdk: ">=3.4.0 <4.0.0"
flutter: ">=3.22.0"
dependencies:
flame: ^1.18.0
flutter:
sdk: flutter
xml: ^6.5.0
dev_dependencies:
build_runner: ^2.4.11
flame_lint: ^1.2.0
flutter_test:
sdk: flutter
mockito: ^5.4.4

View File

@ -0,0 +1,73 @@
import 'dart:ui';
import 'package:flame/cache.dart';
import 'package:flame_kenney_xml/xml_sprite_sheet.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class _MockImage extends Mock implements Image {
@override
int get width => 100;
@override
int get height => 100;
}
class _MockImages extends Mock implements Images {
@override
Future<Image> load(String fileName, {String? key}) async {
return _MockImage();
}
}
class _MockAssetsCache extends Mock implements AssetsCache {
@override
Future<String> readFile(String fileName) async {
return '''
<TextureAtlas imagePath="spritesheet.png">
<SubTexture name="sprite1" x="0" y="0" width="32" height="32"/>
<SubTexture name="sprite2" x="32" y="0" width="32" height="32"/>
</TextureAtlas>
''';
}
}
void main() {
group('XmlSpriteSheet', () {
test('creation from constructor', () {
final spritesheet = XmlSpriteSheet(
image: _MockImage(),
xml: '''
<TextureAtlas imagePath="spritesheet.png">
<SubTexture name="sprite1" x="0" y="0" width="32" height="32"/>
<SubTexture name="sprite2" x="32" y="0" width="32" height="32"/>
</TextureAtlas>
''',
);
expect(spritesheet.spriteNames, equals(['sprite1', 'sprite2']));
final sprite1 = spritesheet.getSprite('sprite1');
expect(sprite1.src, equals(const Rect.fromLTWH(0, 0, 32, 32)));
final sprite2 = spritesheet.getSprite('sprite2');
expect(sprite2.src, equals(const Rect.fromLTWH(32, 0, 32, 32)));
});
test('creation from load method', () async {
final mockImages = _MockImages();
final mockAssetsCache = _MockAssetsCache();
final spritesheet = await XmlSpriteSheet.load(
imagePath: 'spritesheet_stone.png',
xmlPath: 'spritesheet_stone.xml',
imageCache: mockImages,
assetsCache: mockAssetsCache,
);
expect(spritesheet.spriteNames, equals(['sprite1', 'sprite2']));
final sprite1 = spritesheet.getSprite('sprite1');
expect(sprite1.src, equals(const Rect.fromLTWH(0, 0, 32, 32)));
final sprite2 = spritesheet.getSprite('sprite2');
expect(sprite2.src, equals(const Rect.fromLTWH(32, 0, 32, 32)));
});
});
}