Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
3babca9
feat: Add optional id to BatchItem and methods for managing items by …
gnarhard Jul 21, 2025
c474ad1
refactor: Simplify logic for adding and replacing BatchItems
gnarhard Jul 21, 2025
15942a5
feat: Add tests for new BatchItem ID management functionality
gnarhard Jul 21, 2025
ff42f75
docs: Add documentation about ID management in SpriteBatch section of…
gnarhard Jul 21, 2025
f7e5329
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Jul 21, 2025
a1afe6d
perf: Remove redundant lookup
gnarhard Jul 22, 2025
b843c45
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Jul 22, 2025
1804a88
fix: Add suggested code change to get keys from _idToIndex map keys
gnarhard Jul 27, 2025
5c2752c
fix: Add Free List Strategy for managing indices to prevent race cond…
gnarhard Jul 27, 2025
0c4f4ff
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Aug 4, 2025
8996ede
perf: optimize getting transforms, sources, and colors list while avo…
gnarhard Aug 4, 2025
e964abc
refactor: Rip out id functionality and transform, source, and color l…
gnarhard Aug 6, 2025
05d792b
feat: Add method to retrieve a BatchItem at a given index
gnarhard Aug 16, 2025
33a09db
fix: Update SpriteBatch tests
gnarhard Aug 16, 2025
a06a16b
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Aug 16, 2025
025cd11
docs: Remove ID reference in docs
gnarhard Aug 16, 2025
0b51063
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
spydon Aug 18, 2025
312dda2
Fix formatting
spydon Aug 18, 2025
0c7aace
perf: Move list creation inside if statement that uses those objects
gnarhard Aug 18, 2025
a577478
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
spydon Aug 23, 2025
071e7b2
Merge branch 'feat/manage_sprite_batch_items_by_id' of https://github…
gnarhard Aug 23, 2025
a81322d
refactor: Don't create a new paint reference each render cycle, organ…
gnarhard Aug 23, 2025
39ebfd4
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Aug 23, 2025
69ae8a4
feat: Use a Free List Strategy on BatchItem indexes within SpriteBatc…
gnarhard Jul 21, 2025
0e0479d
Merge branch 'feat/manage_sprite_batch_items_by_id' of https://github…
gnarhard Sep 16, 2025
a9df9e3
perf: add color property to BatchItem to optimize color getting so we…
gnarhard Oct 2, 2025
e29e8b4
Merge branch 'main' into feat/manage_sprite_batch_items_by_id
gnarhard Oct 2, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 105 additions & 83 deletions packages/flame/lib/src/sprite_batch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ extension SpriteBatchExtension on Game {
/// its options.
Future<SpriteBatch> loadSpriteBatch(
String path, {
Color? defaultColor,
BlendMode? defaultBlendMode,
Color defaultColor = const Color(0x00000000),
BlendMode defaultBlendMode = BlendMode.srcOver,
RSTransform? defaultTransform,
Images? imageCache,
bool useAtlas = true,
Expand All @@ -37,9 +37,9 @@ class BatchItem {
BatchItem({
required this.source,
required this.transform,
Color? color,
this.color = const Color(0x00000000),
this.flip = false,
}) : paint = Paint()..color = color ?? const Color(0x00000000),
}) : paint = Paint()..color = color,
destination = Offset.zero & source.size;

/// The source rectangle on the [SpriteBatch.atlas].
Expand Down Expand Up @@ -85,6 +85,9 @@ class BatchItem {

/// Paint object used for the web.
final Paint paint;

/// The color of the batch item.
final Color color;
}

@internal
Expand Down Expand Up @@ -124,7 +127,7 @@ class SpriteBatch {
this.atlas, {
this.defaultTransform,
this.useAtlas = true,
this.defaultColor,
this.defaultColor = const Color(0x00000000),
this.defaultBlendMode,
Images? imageCache,
String? imageKey,
Expand All @@ -146,7 +149,7 @@ class SpriteBatch {
return SpriteBatch(
await imagesCache.load(path),
defaultTransform: defaultTransform ?? RSTransform(1, 0, 0, 0),
defaultColor: defaultColor,
defaultColor: defaultColor ?? const Color(0x00000000),
defaultBlendMode: defaultBlendMode,
useAtlas: useAtlas,
imageCache: imagesCache,
Expand All @@ -156,37 +159,38 @@ class SpriteBatch {

FlippedAtlasStatus _flippedAtlasStatus = FlippedAtlasStatus.none;

/// List of all the existing batch items.
final _batchItems = <BatchItem>[];
/// Stack of available (freed) indices using ListQueue as a stack.
final Queue<int> _freeIndices = Queue<int>();

/// The sources to use on the [atlas].
final _sources = <Rect>[];
/// Returns the total number of indices that have been allocated.
int get allocatedCount => _nextIndex;

/// The sources list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add sources use the
/// [add] or [addTransform] method.
UnmodifiableListView<Rect> get sources {
return UnmodifiableListView<Rect>(_sources);
}
/// Returns the number of currently free indices.
int get freeCount => _freeIndices.length;

/// The transforms that should be applied on the [_sources].
final _transforms = <RSTransform>[];
/// The next index to allocate if no free indices are available.
int _nextIndex = 0;

/// The transforms list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add transforms use the
/// [add] or [addTransform] method.
UnmodifiableListView<RSTransform> get transforms {
return UnmodifiableListView<RSTransform>(_transforms);
}
/// Sparse array of batch items, indexed by allocated indices.
final Map<int, BatchItem> _batchItems = {};

/// The background color for the [_sources].
final _colors = <Color>[];
/// Returns the number of active batch items.
int get length => _batchItems.length;

/// The colors list shouldn't be modified directly, that is why an
/// [UnmodifiableListView] is used. If you want to add colors use the
/// [add] or [addTransform] method.
UnmodifiableListView<Color> get colors {
return UnmodifiableListView<Color>(_colors);
/// Returns the number of indices currently in use.
int get usedCount => _nextIndex - _freeIndices.length;

/// Allocates a new index, reusing freed indices when possible.
int _allocateIndex() {
if (_freeIndices.isNotEmpty) {
return _freeIndices.removeFirst();
}
return _nextIndex++;
}

/// Frees an index to be reused later.
void _freeIndex(int index) {
_freeIndices.addFirst(index);
}

/// The atlas used by the [SpriteBatch].
Expand All @@ -210,7 +214,7 @@ class SpriteBatch {
'image[${identityHashCode(atlas)}]';

/// The default color, used as a background color for a [BatchItem].
final Color? defaultColor;
final Color defaultColor;

/// The default transform, used when a transform was not supplied for a
/// [BatchItem].
Expand All @@ -234,6 +238,10 @@ class SpriteBatch {
/// Does this batch contain any operations?
bool get isEmpty => _batchItems.isEmpty;

// Used to not create new Paint objects in [render] and
// [generateFlippedAtlas].
final _emptyPaint = Paint();

Future<void> _makeFlippedAtlas() async {
_flippedAtlasStatus = FlippedAtlasStatus.generating;
final key = '$imageKey#with-flips';
Expand All @@ -255,12 +263,10 @@ class SpriteBatch {
return picture.toImageSafe(image.width * 2, image.height);
}

int get length => _sources.length;

/// Replace provided values of a batch item at the [index], when a parameter
/// is not provided, the original value of the batch item will be used.
///
/// Throws an [ArgumentError] if the [index] is out of bounds.
/// Throws an [ArgumentError] if the [index] doesn't exist.
/// At least one of the parameters must be different from null.
void replace(
int index, {
Expand All @@ -273,11 +279,11 @@ class SpriteBatch {
'At least one of the parameters must be different from null.',
);

if (index < 0 || index >= length) {
throw ArgumentError('Index out of bounds: $index');
if (!_batchItems.containsKey(index)) {
throw ArgumentError('Index does not exist: $index');
}

final currentBatchItem = _batchItems[index];
final currentBatchItem = _batchItems[index]!;
final newBatchItem = BatchItem(
source: source ?? currentBatchItem.source,
transform: transform ?? currentBatchItem.transform,
Expand All @@ -286,10 +292,14 @@ class SpriteBatch {
);

_batchItems[index] = newBatchItem;
}

_sources[index] = newBatchItem.source;
_transforms[index] = newBatchItem.transform;
_colors[index] = color ?? _defaultColor;
/// Returns the [BatchItem] at the given [index].
BatchItem getBatchItem(int index) {
if (!_batchItems.containsKey(index)) {
throw ArgumentError('Index does not exist: $index');
}
return _batchItems[index]!;
}

/// Add a new batch item using a RSTransform.
Expand All @@ -307,26 +317,15 @@ class SpriteBatch {
/// cosine of the rotation so that they can be reused over multiple calls to
/// this constructor, it may be more efficient to directly use this method
/// instead.
void addTransform({
int addTransform({
required Rect source,
RSTransform? transform,
bool flip = false,
Color? color,
}) {
final index = _allocateIndex();
final batchItem = BatchItem(
source: source,
transform: transform ??= defaultTransform ?? RSTransform(1, 0, 0, 0),
flip: flip,
color: color ?? defaultColor,
);

if (flip && useAtlas && _flippedAtlasStatus.isNone) {
_makeFlippedAtlas();
}

_batchItems.add(batchItem);
_sources.add(
flip
source: flip
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @gnarhard, I took a quick look at the failing tests and I suspect it has something to do with the flip and source rects. Before your change, addTransform was always creating BatchItem with the original source. flip was considered only while adding to _sources list.

I modified the addTransform method to create BatchItem with default source and some of the tests started passing.

int addTransform({
  required Rect source,
  RSTransform? transform,
  bool flip = false,
  Color? color,
}) {
  final index = _allocateIndex();
  final batchItem = BatchItem(
    source: source,
    transform: transform ??= defaultTransform ?? RSTransform(1, 0, 0, 0),
    flip: flip,
    color: color ?? defaultColor,
  );

  if (flip && useAtlas && _flippedAtlasStatus.isNone) {
    _makeFlippedAtlas();
  }

  _batchItems[index] = batchItem;

  return index;
}

I didn't get enough time to look further into this, but I hope this helps you to narrow down the root cause 🙂

? Rect.fromLTWH(
// The atlas is twice as wide when the flipped atlas is generated.
(atlas.width * (_flippedAtlasStatus.isGenerated ? 1 : 2)) -
Expand All @@ -335,10 +334,19 @@ class SpriteBatch {
source.width,
source.height,
)
: batchItem.source,
: source,
transform: transform ??= defaultTransform ?? RSTransform(1, 0, 0, 0),
flip: flip,
color: color ?? defaultColor,
);
_transforms.add(batchItem.transform);
_colors.add(color ?? _defaultColor);

if (flip && useAtlas && _flippedAtlasStatus.isNone) {
_makeFlippedAtlas();
}

_batchItems[index] = batchItem;

return index;
}

/// Add a new batch item.
Expand All @@ -359,7 +367,7 @@ class SpriteBatch {
/// multiple [RSTransform] objects,
/// it may be more efficient to directly use the more direct [addTransform]
/// method instead.
void add({
int add({
required Rect source,
double scale = 1.0,
Vector2? anchor,
Expand Down Expand Up @@ -389,26 +397,31 @@ class SpriteBatch {
);
}

addTransform(
return addTransform(
source: source,
transform: transform,
flip: flip,
color: color,
);
}

/// Removes a batch item at the given [index].
void removeAt(int index) {
if (!_batchItems.containsKey(index)) {
throw ArgumentError('Index does not exist: $index');
}

_batchItems.remove(index);
_freeIndex(index);
}

/// Clear the SpriteBatch so it can be reused.
void clear() {
_sources.clear();
_transforms.clear();
_colors.clear();
_batchItems.clear();
_freeIndices.clear();
_nextIndex = 0;
}

// Used to not create new Paint objects in [render] and
// [generateFlippedAtlas].
final _emptyPaint = Paint();

void render(
Canvas canvas, {
BlendMode? blendMode,
Expand All @@ -419,27 +432,38 @@ class SpriteBatch {
return;
}

final renderPaint = paint ?? _emptyPaint;

final hasNoColors = _colors.every((c) => c == _defaultColor);
final actualBlendMode = blendMode ?? defaultBlendMode;
if (!hasNoColors && actualBlendMode == null) {
throw 'When setting any colors, a blend mode must be provided.';
}
paint ??= _emptyPaint;

if (useAtlas && !_flippedAtlasStatus.isGenerating) {
final transforms = _batchItems.values
.map((e) => e.transform)
.toList(growable: false);
final sources = _batchItems.values
.map((e) => e.source)
.toList(growable: false);
final colors = _batchItems.values
.map((e) => e.color)
.toList(growable: false);

final hasNoColors = colors.every((c) => c == defaultColor);
final actualBlendMode = blendMode ?? defaultBlendMode;
if (!hasNoColors && actualBlendMode == null) {
throw 'When setting any colors, a blend mode must be provided.';
}

canvas.drawAtlas(
atlas,
_transforms,
_sources,
hasNoColors ? null : _colors,
transforms,
sources,
hasNoColors ? null : colors,
actualBlendMode,
cullRect,
renderPaint,
paint,
);
} else {
for (final batchItem in _batchItems) {
renderPaint.blendMode = blendMode ?? renderPaint.blendMode;
for (final index in _batchItems.keys) {
final batchItem = _batchItems[index]!;
paint.blendMode = blendMode ?? paint.blendMode;

canvas
..save()
Expand All @@ -449,12 +473,10 @@ class SpriteBatch {
atlas,
batchItem.source,
batchItem.destination,
renderPaint,
paint,
)
..restore();
}
}
}

static const _defaultColor = Color(0x00000000);
}
Loading
Loading