Metal Error : Command encoder released without endEncoding

Hello :slight_smile:

In my PROD environment I am getting this issue with BabylonJS React Native :

-[_MTLCommandEncoder dealloc] > -[_MTLCommandEncoder dealloc]:131: failed assertion `Command encoder released without endEncoding'
 > : failed assertion `%s'
 > Command encoder released without endEncoding > error

Here is a more detailed stack trace :

0   ???                           	       0x107725a78 ???
1   ???                           	       0x10c0b403c ???
2   libsystem_pthread.dylib       	       0x11a34febd pthread_kill + 262
3   libsystem_c.dylib             	       0x1162446b7 abort + 130
4   libsystem_c.dylib             	       0x116243a34 __assert_rtn + 314
5   Metal                         	       0x11584435c MTLReportFailure.cold.1 + 43
6   Metal                         	       0x11582ba89 MTLReportFailure + 529
7   MetalTools                    	       0x14f8ef955 -[MTLDebugRenderCommandEncoder dealloc] + 229
8   libobjc.A.dylib               	       0x1111a57b7 objc_object::sidetable_release(bool, bool) + 177
9   libobjc.A.dylib               	       0x1111a6f96 AutoreleasePoolPage::releaseUntil(objc_object**) + 172
10  libobjc.A.dylib               	       0x1111a6e89 objc_autoreleasePoolPop + 192
11  CoreFoundation                	       0x1146cf8be _CFAutoreleasePoolPop + 22
12  Foundation                    	       0x1132e5217 -[NSAutoreleasePool release] + 133
13  App                         	       0x105334930 bgfx::NSAutoreleasePoolScope::~NSAutoreleasePoolScope() + 32
14  App                           	       0x10532faae bgfx::Context::renderFrame(int) + 510
15  App                            	       0x1053330f0 bgfx::Context::swap() + 384
16  App                          	       0x1053314b7 bgfx::Context::frame(bool) + 919
17  App                            	       0x1048b64d4 Babylon::Graphics::DeviceImpl::Frame() + 228
18  App                            	       0x1048b602f Babylon::Graphics::DeviceImpl::FinishRenderingCurrentFrame() + 367
19  App                            	       0x1047ccf1b BabylonNative::RenderView() + 155
20  App                          	       0x1056ba845 +[BabylonNativeInterop renderView] + 21 (BabylonNativeInterop.mm:71)
21  App                           	       0x1056bedc9 -[EngineView drawRect:] + 521 (EngineViewManager.mm:84)
22  MetalKit                      	       0x1109f3157 -[MTKView draw] + 142
23  MetalKit                      	       0x1109ef5a9 -[MTKViewDisplayLinkTarget draw] + 34
24  QuartzCore                    	       0x113e33917 CA::Display::DisplayLink::dispatch_items(unsigned long long, unsigned long long, unsigned long long) + 915
25  QuartzCore                    	       0x113f32aa6 display_timer_callback(__CFMachPort*, void*, long, void*) + 395
26  CoreFoundation                	       0x1145f98ae __CFMachPortPerform + 157
27  CoreFoundation                	       0x11462dd99 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
28  CoreFoundation                	       0x11462d140 __CFRunLoopDoSource1 + 617
29  CoreFoundation                	       0x114627575 __CFRunLoopRun + 2420
30  CoreFoundation                	       0x114626704 CFRunLoopRunSpecific + 562
31  GraphicsServices              	       0x11cfb5c8e GSEventRunModal + 139
32  UIKitCore                     	       0x12e34965a -[UIApplication _run] + 928
33  UIKitCore                     	       0x12e34e2b5 UIApplicationMain + 101
34  App                           	       0x1047c2518 main + 104 (main.m:7)
35  dyld_sim                      	       0x110002f21 start_sim + 10
36  dyld                          	       0x207ab5345 start + 1909

I am using this packages :

    "@babylonjs/loaders": "^6.40.0",
    "@babylonjs/react-native": "^1.8.6",
    "@babylonjs/react-native-iosandroid-0-71": "^1.8.6",
    "@babylonjs/core": "^6.40.0",
    "babylonjs": "^7.25.1",

It crashes from version 14.3 up to 15.8.2 of IOS (working well on Android or other versions of IOS).

The repo is private, so I can’t share it, but I may be able to share small portions of code.

Any help / ideas are welcome !! :slight_smile:

Hi @Mathias welcome to the forum

At first, it looks like a bug in bgfx, so it should be reproductible in BabylonNative.
Can you please try to reduce the scope of your app to get the crash with the minimal amount of code?
Then, as a second step, copy/paste code in BabylonNative playground BabylonNative/Apps/Playground/Scripts/experience.js at master · BabylonJS/BabylonNative · GitHub

Does it happen during a special event (resizing/rotating device)? Does it happen with Metal exception disabled in Xcode? Is there any glitch/ rendering issue appearing before crashing? Does it happen with a particular asset? like a .gltf, custom shader,… ?

cc @BabylonNative

Hello @Cedric ,

Thank you for the quick reply.

The crash happens when we use this function while trying to load a .glb asset :

BABYLON.SceneLoader.ImportMeshAsync(null, '', assetUrl, currentScene)

There isn’t any glitch / rendering issue before crashing.

I’ll try to disable Metal in Xcode and will try to create a simple the BabylonNative playground.

1 Like

Re-hello,

While trying to reduce as much as possible the scene, I observed that it’s not directly the importMeshAsync that creates the crash.

        const currentCamera = new BABYLON.UniversalCamera('camera', new BABYLON.Vector3(3, 0, 0), currentScene);
        currentCamera.target = new BABYLON.Vector3(0, 0, 0);

When I remove the currentCamera.target and keep the importMeshAsync, the scene doesn’t crash
When I remove the importMeshAsync and keep the currentCamera.target, the scene doesn’t crash either

Update ! :sweat_smile:

Unfortunately, disabling Metal doesn’t seem to fix anything in my playground.

I’ve seen a slightly more complex behavior. In fact, it crashes when an object is in the camera’s field of vision. (IOS 15.5, iPhone 12)

Here is my playground inside my react-native App :

import React, { useEffect, useState } from 'react';

import * as BABYLON from '@babylonjs/core';
import { MeshBuilder, Vector3 } from '@babylonjs/core';
import { EngineView, useEngine } from '@babylonjs/react-native';

const EngineTest = () => {
  const engine = useEngine();
  const [camera, setCamera] = useState();

  useEffect(() => {
    if (!engine) {
      return;
    }

    const currentScene = new BABYLON.Scene(engine);

    currentScene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
    currentScene.collisionsEnabled = false;

    currentScene.addLight(new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(1, 1, 0), currentScene));

    // To check with camera movement
    const currentCamera = new BABYLON.ArcRotateCamera('camera', 1, 1, 3, new BABYLON.Vector3(0, 0, 0), currentScene);

    const rotateCamera = () => {
      console.log('currentCamera.alpha', currentCamera.alpha);
      currentCamera.alpha -= 0.01;
    };

    currentScene.onBeforeRenderObservable.add(rotateCamera);

    // To check without camera movement
    // const currentCamera = new BABYLON.UniversalCamera('camera', new BABYLON.Vector3(3, 3, 3), currentScene);
    // currentCamera.target = new BABYLON.Vector3(0, 0, 0);

    setCamera(currentCamera);

    const box = MeshBuilder.CreateBox('box', {}, currentScene);
    box.position = new Vector3(0, 0, 0); // update to (0, 0, 0) for the crash and to (0, 10, 0) for the working scene

    return () => {};
  }, [engine]);

  return <EngineView camera={camera} displayFrameRate={true} isTransparent={false} />;
};

export default EngineTest;

Thanks in advance for any help ! :slight_smile:

Do you experience the crash when building and running BabylonNative playground?

Hello @Cedric , I hope you are well ! :slight_smile:

Yes, I have the same issue running the experience.js playground.
You can test it with this steps (tested on macOS) :

  • git clone --recurse-submodules https://github.com/BabylonJS/BabylonNative.git
  • cd BabylonNative
  • mkdir Build-iOS
  • cd Build-iOS
  • cmake .. -G Xcode -DCMAKE_SYSTEM_NAME=iOS
  • open BabylonNative.xcodeproj
  • Select the target “Playground”
  • Create a configuration iPhone 7, with IOS 15.5
  • Lunch the app
  • It should instantly crash like on the picture

Maybe it’s related to : Prevent Metal from crashing when a still-open encoder is deallocated, resolve issue #2077. by bradwerth · Pull Request #4023 · gfx-rs/wgpu · GitHub that fixes this other issue Command encoder released without endEncoding · Issue #2077 · gfx-rs/wgpu · GitHub

But it’s quite old PRs (August 2023)
I haven’t checked if these fixes have been released or added to BabylonJS yet.

I will come back to you if I find more informations.

I didn’t find any mention (code or issue) related to end_encoding in GitHub - bkaradzic/bgfx: Cross-platform, graphics API agnostic, "Bring Your Own Engine/Framework" style rendering library.
Did you try to add end_encoding call to the command encode in bgfx?

Thanks for your quick reply

I am sorry, but I don’t understand what you mean by :
“Did you try to add end_encoding call to the command encode in bgfx?”

On my side, I didn’t change anything yet.

Sorry, I missed your message. The same change in gfx-rs should be applied to bgfx. First, I suggest you to try any bgfx example on your ios device to verify it crashes. if it does, then I can try to guide you for the second step that consists in patching bgfx and submit a PR.