openfl / openfl

The Open Flash Library for creative expression on the web, desktop, mobile and consoles.
http://www.openfl.org
MIT License
1.91k stars 434 forks source link

Threading with bitmap datas converted to textures silent crashes the game #2698

Open SomeGuyWhoLovesCoding opened 8 months ago

SomeGuyWhoLovesCoding commented 8 months ago

Describe the bug So, someone helped me with how I would reduce memory usage when loading an image by converting it to a texture, simply with this function:

public static function toTexture(source:BitmapData):BitmapData
{
    if (source.readable && !GL.isContextLost())
    {
        var context:Context3D = Lib.current.stage.context3D;
        var texture:TextureBase = source.getTexture(context);
        return source = BitmapData.fromTexture(texture);
    }

    return source;
}

(All the classes were imported for this btw) And then, when I tried it out while also threading, it silent crashes the game. I was so shocked that it happened. I did make the thread handler function safer by adding a mutex which acquires before the call, and releases the mutex after that.

OpenFL and Lime versions: Latest

To Reproduce Steps to reproduce the behavior:

  1. Basically add this:
    
    // Add this
    import lime.graphics.Image;
    import openfl.display.BitmapData;

class Main extends openfl.display.Sprite { public function new():Void { super(); new sys.thread.FixedThreadPool(1).run(function() { var img:Image = toTexture(Image.fromBitmapData(BitmapData.fromFile('image.png'))); }); }

// See "Describe the bug" for the function

}


2. Test it out

**Expected behavior**
I wanted the bitmap data to successfully convert to a texture (``toTexture`` function) while also using threading (``sys.thread.FixedThreadPool``), and I expected the texture to not crash the game.

**Screenshots**
[No screenshot available, just a silent game crash]

**OpenFL Targets**
Windows (Tested), any other target (Not tested).

**Additional context**
N/A
joshtynjala commented 7 months ago

As I understand it, all Stage 3D code is required to remain in the main thread (and that is not considered a bug). You can use threads for other things, though.

barisyild commented 7 months ago

toTexture method costs almost nothing, for thread-safety you should run this method in the main thread. OpenGL is single thread supported, so you can't make gl calls in another thread.