MZ Disposing of bitmaps correctly

Hi, I just released my first plugin.

However I'm not certain that I'm handling the disposal of bitmaps correctly.
My plugin renders both images and text.
The text rendering works fine when I dispose of the bitmap with:

this.bitmap.destroy();

However for the image rendering, the command above alone causes images only to be displayed the first time.
I don't get errors, but the image never appears on the screen.
The main difference as far as I can see is that for the text render I'm creating a new bitmap:

this.bitmap = new Bitmap(Graphics.width, Graphics.height);

However for images its:

ImageManager.loadPicture(image_name).addLoadListener(
bmp => {
}

I've kind of got around this by doing the following:

this.bitmap = new Bitmap(1, 1);
SceneManager._scene.removeChild(this);
this.bitmap.destroy();

Which seems like a fudge, although from testing it does significantly reduce (or possibly remove) the memory leak that I was having when removing the destroy entirely.

It will likely be useful to have the plugin code to see why the destroy on it's own is causing problems for my images.
It's available here:

KOG_TextMage.js

For context, here is the post of what the plugin does:

Forum Post

Hopefully an expert here might have an idea, as currently I have no clue.
I think this is related to the engine's image cache. By calling destroy on the image, you destroy its cache entry, but do not remove it from ImageManager._cache. So the next time something tries to get the bitmap data from cache, there's nothing to fetch: the canvas has already been disposed.

Typically you should only call destroy on modified bitmaps. This includes anything to which you're blitting text or partial images. (If you want a bitmap comprising an image with text on top, consider calling blt to blit the loaded image to a new Bitmap, then drawText on top. Or perhaps use a child sprite for the text, something like that.)

Scenes are disposed post-termination, whereupon they also destroy all their immediate children (SceneManager.onBeforeSceneStart -> Stage.prototype.destroy). The standard Sprite wrapper does not call bitmap.destroy(), so you'd want to hook into that too. E.g. that's why the title scene manually destroys the bitmap of its title sprite, but not its backgrounds (Scene_Title.prototype.terminate).


Based on a skim-read, I think points 2~5 from my post in SangHendrix's thread may still apply to your plugin:
👋
Spoiler: v1.0.1
  1. ShowTextSprite does not release its modified textures from memory.
    • Suggestion: patch the sprite's destroy method to call this.bitmap.destroy().

  2. Text disappears on scene changes, e.g. change map or open pause menu.
    • Suggestion: create a game object to represent the text, which the sprite references.

  3. Text gets removed from the current scene (no effect if sprite is absent).
    • Suggestion: implement the timers in the scene's update method instead of using setTimeout. This will also ensure your plugin's text updates at exactly the same rate as the rest of the game, rather than potentially desynchronising from the core game loop (fluid timestep).

  4. The fade in/out timers can outlast the applicable sprite instance, e.g. point 2.
    • The suggested fix for point 3 should automatically cover this.

  5. I notice the plugin command is an async function. Thoughts:
    • If it is slow, async permits a change of scene before the text shows.
    • If it is fast, async is unnecessary.

  6. The default arg value GameFont is for RMMV.
    • Suggestion: consider rmmz-mainfont instead.

  7. I don't know where PluginManager.convText is defined, but hopefully you do!
E.g. for point 3: the game engine implements a fluid-timestep algorithm that attempts to keep the mechanical framerate at ~60 fps. You could easily keep your sprite fade in lockstep with the engine by updating the opacity in your class's update method, rather than via setInterval. To illustrate what I mean (untested):
Spoiler: rough example, update + destroy
JavaScript:
class ShowTextOrImageSprite extends Sprite {
  // ...
  update() {
    super();
    if (this._fadingOut) {
      this.opacity -= 255 / (fadeOutDuration * 60);
      if (this.opacity <= 0) {
        this.parent.removeChild(this);
        this.destroy();
      }
    } else {
      if (this.opacity >= 255) {
        this._holdDuration ??= 0;
        if (++this._holdDuration >= duration) {
          this._fadingOut = true;
        }
      } else {
        this.opacity += 255 / (fadeInDuration * 60);
      }
    }
  },
  destroy() {
    if (this._isText) {  // new value assigned on construction
      this.bitmap.destroy();
    }
    super();
  },
  // ...
}
A scene calls the update method of each of its children every mechanical frame.

Also, a couple of personal suggestions:
  • Consider maintaining a consistent code style: you use various naming conventions (PascalCase, camelCase, snake_case) irrespective of how you are using the identifiers.
  • Make use of properties/methods instead of doing everything in the constructor. Class syntax supports private properties, if that's a concern.
I think this is related to the engine's image cache. By calling destroy on the image, you destroy its cache entry, but do not remove it from ImageManager._cache. So the next time something tries to get the bitmap data from cache, there's nothing to fetch: the canvas has already been disposed.

Typically you should only call destroy on modified bitmaps. This includes anything to which you're blitting text or partial images. (If you want a bitmap comprising an image with text on top, consider calling blt to blit the loaded image to a new Bitmap, then drawText on top. Or perhaps use a child sprite for the text, something like that.)

Scenes are disposed post-termination, whereupon they also destroy all their immediate children (SceneManager.onBeforeSceneStart -> Stage.prototype.destroy). The standard Sprite wrapper does not call bitmap.destroy(), so you'd want to hook into that too. E.g. that's why the title scene manually destroys the bitmap of its title sprite, but not its backgrounds (Scene_Title.prototype.terminate).


Based on a skim-read, I think points 2~5 from my post in SangHendrix's thread may still apply to your plugin:

E.g. for point 3: the game engine implements a fluid-timestep algorithm that attempts to keep the mechanical framerate at ~60 fps. You could easily keep your sprite fade in lockstep with the engine by updating the opacity in your class's update method, rather than via setInterval. To illustrate what I mean (untested):
Spoiler: rough example, update + destroy
JavaScript:
class ShowTextOrImageSprite extends Sprite {
  // ...
  update() {
    super();
    if (this._fadingOut) {
      this.opacity -= 255 / (fadeOutDuration * 60);
      if (this.opacity <= 0) {
        this.parent.removeChild(this);
        this.destroy();
      }
    } else {
      if (this.opacity >= 255) {
        this._holdDuration ??= 0;
        if (++this._holdDuration >= duration) {
          this._fadingOut = true;
        }
      } else {
        this.opacity += 255 / (fadeInDuration * 60);
      }
    }
  },
  destroy() {
    if (this._isText) {  // new value assigned on construction
      this.bitmap.destroy();
    }
    super();
  },
  // ...
}
A scene calls the update method of each of its children every mechanical frame.

Also, a couple of personal suggestions:
  • Consider maintaining a consistent code style: you use various naming conventions (PascalCase, camelCase, snake_case) irrespective of how you are using the identifiers.
  • Make use of properties/methods instead of doing everything in the constructor. Class syntax supports private properties, if that's a concern.
Thanks caethyril. Just want to say I appreciate you using your precious time to answer questions from a newbie. I did originally read your comments on the SangHendrix post.

However I was too early in my RMMZ journey for any of it to make much sense. This time around a lot more of it does.

Now I understand how RMMZ will cache the images, I can see why the destroy creates an issue for the images, but not the text.

Thanks for the update example, I will play around with that and hopefully remove the timers.

Fair point in on mixed naming convensions, its a long and bad habit.

Although I've been coding a long time, RMMZ and Javascript are two areas that I'm only just getting to grips with.

I think I understand most of what you've said, except number 2 where you say "create a game object to represent the text". No idea what that is at all, so I'll have to dig into that. Do you have a plugin or know of one that implements the "game object"?
You're welcome! JavaScript shouldn't be too bad if you're familiar with OOP. MZ's engine structure can take some getting used to, but it is mainly MVC:
  • Model: rmmz_objects, e.g. Game_Picture;
  • View: rmmz_sprites, e.g. Sprite_Picture;
  • Controller: rmmz_managers, e.g. SceneManager.
I think I understand most of what you've said, except number 2 where you say "create a game object to represent the text". No idea what that is at all, so I'll have to dig into that. Do you have a plugin or know of one that implements the "game object"?
Point 2 would require more work than the others. There are various examples in the core scripts (rmmz_objects, rmmz_sprites), e.g.
  • Sprite_Picture updates based on the corresponding Game_Picture.
  • Sprite_Character updates based on the corresponding Game_Character.
  • Sprite_Actor (battler) updates based on the corresponding Game_Actor.
Pictures, for example:
  • Stored under Game_Screen, fetched as $gameScreen.picture(id).
  • Game_Screen persists through scene transitions, e.g. menu, battle, map transfer.
  • The Show, Move, and Rotate Picture commands modify the appropriate Game_Picture.
  • Sprite_Picture updates its transform, opacity, etc based on the Game_Picture with the same ID.
Also, most Game_ objects, including $gameScreen, are included in save files (DataManager.createGameObjects, DataManager.makeSaveContents, DataManager.extractSaveContents). This means they should only contain values that can be serialised to JSON. Sprites have no such restriction, though, so you can store a reference to the game object on the corresponding sprite, like Sprite_Character does.

Hopefully that helps~ 👋
You're welcome! JavaScript shouldn't be too bad if you're familiar with OOP. MZ's engine structure can take some getting used to, but it is mainly MVC:
  • Model: rmmz_objects, e.g. Game_Picture;
  • View: rmmz_sprites, e.g. Sprite_Picture;
  • Controller: rmmz_managers, e.g. SceneManager.

Point 2 would require more work than the others. There are various examples in the core scripts (rmmz_objects, rmmz_sprites), e.g.
  • Sprite_Picture updates based on the corresponding Game_Picture.
  • Sprite_Character updates based on the corresponding Game_Character.
  • Sprite_Actor (battler) updates based on the corresponding Game_Actor.
Pictures, for example:
  • Stored under Game_Screen, fetched as $gameScreen.picture(id).
  • Game_Screen persists through scene transitions, e.g. menu, battle, map transfer.
  • The Show, Move, and Rotate Picture commands modify the appropriate Game_Picture.
  • Sprite_Picture updates its transform, opacity, etc based on the Game_Picture with the same ID.
Also, most Game_ objects, including $gameScreen, are included in save files (DataManager.createGameObjects, DataManager.makeSaveContents, DataManager.extractSaveContents). This means they should only contain values that can be serialised to JSON. Sprites have no such restriction, though, so you can store a reference to the game object on the corresponding sprite, like Sprite_Character does.

Hopefully that helps~ 👋
So I've been digging into the game object stuff, but this is a very deep rabbit hole for a newbie. I can understand some of this. I can see that $gameScreen.showPicture is in rmmz_objects.js at line 1057:
Game_Screen.prototype.showPicture = function(

That creates a new instance of Game_Picture:

const picture = new Game_Picture();

I think a key issue I have right now, is that my plugin is heavily centered around the manipulation of bitmaps. Specifically by extending Sprite. I don't have to use sprite though, I could use other objects, as long as they have a bitmap I can manipulate and persist on the screen. Maybe it's possible, but I can't see anything in the definition of Game_Picture that would give me access to a bitmap.

So far I think the strongest candidate for what I need looks to be Sprite_Picture.
It has bitmaps and is using the $gameScreen.picture

I'm not sure yet though if I should be using Sprite_Picture or extending upon it, or if I should use Sprite_Picture as the basis for an entirely new object for my use case?

I'm not necessarily expecting an actual answer as such, although I'd appreciate any input. I'm more just recording my current thoughts here, so I have something to reference.
Mh, I overlooked how much "more work than the others" it would need. Particularly if you're not familiar with this kind of thing. Definitely check out the other stuff first! 😴

The Model component, what I've been referring to as a "game object", is designed to house all the important information. The View component, i.e. the sprite, should then be able to be reliably recreated based on that Model.

Each pair, game object (henceforth "GO") and sprite, is specialised to its purpose, e.g.
  • Picture (ID: number): position, scale, origin, etc; movement to target over a duration.
  • Character (ID: object): filename/index, move speed, stepping pattern, position, etc.
Your sprites have stuff like text, colour, and hold/fade durations. I don't think those really fit any current GO class, hence my suggestion to make a new one. Which would yield something like:
  • The GO, e.g. Game_TextMage, inheriting from Object.
  • The sprite, e.g. Sprite_TextMage, inheriting from Sprite.
(The names don't really matter, these are just examples.) The GO would handle all business logic and value storage: text content and style, screen position, timer updates, status (e.g. holding/fading), etc. Then the sprite can just look at it every update and say "OK so I go here and set my opacity to that".

You can pass each sprite a GO reference on construction, like Sprite_Character does, then allow the sprite to update itself based on that reference:
JavaScript:
Spriteset_Map.prototype.createCharacters = function() {
    this._characterSprites = [];
    for (const event of $gameMap.events()) {
        this._characterSprites.push(new Sprite_Character(event));

(For the map scene, you may want to consider adding the sprites as children of its spriteset, SceneManager._scene._spriteset, instead of directly to the scene itself. For example, that would allow them to be affected by things like Shake Screen.)

One option would be to create the GO alongside the sprite, in the plugin command. The GO's would be stored on a persistent object, e.g. a new array property on Game_Screen. (Storing the GO on something that is independent of the scene instance and its sprites ensures persistence through scene changes, like opening/closing the pause menu, transferring between maps, and loading from a save.) You'd probably also want a check in the spriteset's initialize method to immediately create sprites for any existing GO's.

Alternatively, you could go all the way and set up a system like what exists for animations: Game_Temp#requestAnimation -> Spriteset_Base#processAnimationRequests -> etc. That would make the spriteset responsible for adding the corresponding sprites to itself, so the plugin command just has to create the GO. It would also resemble cleaner code, avoiding things like SceneManager._scene (underscore-prefix, e.g. _scene, indicates that the property is designed to be private/internal).

Original thread: https://forums.rpgmakerweb.com/threads/disposing-of-bitmaps-correctly.166444/