# BabylonReactNative throws exception when adding anchor

**URL:** <https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716>\
**Category:** Bugs\
**Tags:** babylon-native, react-native\
**Created:** [May 21, 2024, 8:36am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716 "2024-05-21T08:36:12Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![dnrn](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dnrn/32/4723_2.png) [@dnrn](https://forum.babylonjs.com/u/dnrn)\
**Post date:** [May 21, 2024, 8:36am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/1 "2024-05-21T08:36:12Z")

</div>

I’m building a native iOS webxr experience, where we load a scene and a user is able to place the scene on the floor. Everything works in Chrome on Android 🙂

Now we’re porting it to iOS, so we can show the same experience in an app clip. It seems their could be a bug when calling `addAnchorPointUsingHitTestResultAsync`, in rare occasions it does work but often we get an exception in:

```auto
Anchor System::Session::Frame::CreateAnchor(Pose pose, NativeTrackablePtr) const {
    return m_impl->sessionImpl.CreateAnchor(pose);
}

```

The exception:

```auto
sessionImpl -> com.facebook.react.JavaScript (15): EXC_BAD_ACCESS (code=1, address=0x0)

```

App.tsx:

```auto
/**
 * Generated with the TypeScript template
 * https://github.com/react-native-community/react-native-template-typescript
 *
 * @format
 */

import React, { useState, FunctionComponent, useEffect, useCallback } from 'react';
import { SafeAreaView, StatusBar, Button, View, Text, ViewProps, Image, Alert } from 'react-native';

import { EngineView, useEngine, EngineViewCallbacks } from '@babylonjs/react-native';
import { Scene, Vector3, ArcRotateCamera, Camera, WebXRSessionManager, SceneLoader, TransformNode, DeviceSourceManager, DeviceType, PointerInput, WebXRTrackingState, IMouseEvent, WebXRFeatureName, IWebXRHitResult, CreateTorus, Quaternion, WebXRHitTest, FreeCamera, WebXRAnchorSystem, IPointerEvent, PickingInfo, WebXRState, DirectionalLight, ShadowGenerator } from '@babylonjs/core';
import '@babylonjs/loaders';
import Slider from '@react-native-community/slider';

const EngineScreen: FunctionComponent<ViewProps> = (props: ViewProps) => {
	const defaultScale = 1;
	const enableSnapshots = false;

	const engine = useEngine();

	const [toggleView, setToggleView] = useState(false);
	const [camera, setCamera] = useState<Camera>();
	const [rootNode, setRootNode] = useState<TransformNode>();
	const [scene, setScene] = useState<Scene>();
	const [xrSession, setXrSession] = useState<WebXRSessionManager>();
	const [scale, setScale] = useState<number>(defaultScale);
	const [snapshotData, setSnapshotData] = useState<string>();
	const [engineViewCallbacks, setEngineViewCallbacks] = useState<EngineViewCallbacks>();
	const [trackingState, setTrackingState] = useState<WebXRTrackingState>();

	useEffect(() => {
		if (engine) {
			const scene = new Scene(engine);
			console.log('Hallo');
			setScene(scene);
			// scene.createDefaultCamera(true);
			// (scene.activeCamera as ArcRotateCamera).beta -= Math.PI / 8;
			var camera = new FreeCamera('webxr-camera', new Vector3(0, 1, -5), scene);
			camera.setTarget(Vector3.Zero());
			camera.minZ = 0.01;

			setCamera(scene.activeCamera!);
			scene.createDefaultLight(true);
			const rootNode = new TransformNode('Root Container', scene);
			setRootNode(rootNode);

			const deviceSourceManager = new DeviceSourceManager(engine);
			const handlePointerInput = (event: IMouseEvent) => {
				if (event.inputIndex === PointerInput.Move && event.movementX) {
					rootNode.rotate(Vector3.Down(), event.movementX * 0.005);
				};
			};

			deviceSourceManager.onDeviceConnectedObservable.add(device => {
				if (device.deviceType === DeviceType.Touch) {
					const touch = deviceSourceManager.getDeviceSource(device.deviceType, device.deviceSlot)!;
					touch.onInputChangedObservable.add(touchEvent => {
						handlePointerInput(touchEvent);
					});
				} else if (device.deviceType === DeviceType.Mouse) {
					const mouse = deviceSourceManager.getDeviceSource(device.deviceType, device.deviceSlot)!;
					mouse.onInputChangedObservable.add(mouseEvent => {
						if (mouse.getInput(PointerInput.LeftClick)) {
							handlePointerInput(mouseEvent);
						}
					});
				}
			});

			const transformContainer = new TransformNode('Transform Container', scene);
			transformContainer.parent = rootNode;
			transformContainer.scaling.scaleInPlace(0.2);
			transformContainer.position.y -= .2;

			scene.beforeRender = function () {
				transformContainer.rotate(Vector3.Up(), 0.005 * scene.getAnimationRatio());
			};

			SceneLoader.ImportMeshAsync('', 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/BoxAnimated/glTF-Binary/BoxAnimated.glb').then(result => {
				const mesh = result.meshes[0];
				mesh.parent = transformContainer;
			});
		}
	}, [engine]);

	useEffect(() => {
		if (rootNode) {
			rootNode.scaling = new Vector3(scale, scale, scale);
		}
	}, [rootNode, scale]);

	const startXR = () => {
		(async () => {
			console.log('Start XR');
			if (!scene || !rootNode) return;

			rootNode.getChildMeshes().forEach(m => m.isVisible = false);
			rootNode.rotationQuaternion = new Quaternion();

			const xr = await scene.createDefaultXRExperienceAsync({ disableDefaultUI: true, disableTeleportation: true });
			console.log('XR')

			const fm = xr.baseExperience.featuresManager;
			const xrTest = fm.enableFeature(WebXRFeatureName.HIT_TEST, 'latest')as WebXRHitTest;
			const xrPlanes = fm.enableFeature(WebXRFeatureName.PLANE_DETECTION, 'latest');
			const anchors = fm.enableFeature(WebXRFeatureName.ANCHOR_SYSTEM, 'latest') as WebXRAnchorSystem;
			const xrBackgroundRemover = fm.enableFeature(WebXRFeatureName.BACKGROUND_REMOVER, 'latest');

			var isPlaced = false;

			var marker = CreateTorus(
				'marker',
				{
					diameter: 0.15,
					thickness: 0.05,
				},
				scene
			);
			marker.rotationQuaternion = new Quaternion();
			marker.isVisible = false;

			var hitTest: IWebXRHitResult;
			xrTest.onHitTestResultObservable.add((result) => {
				if (result.length) {
					marker.isVisible = !isPlaced;
					// marker.isVisible = true;
					hitTest = result[0];
					marker.position = hitTest.position;
					marker.rotationQuaternion = hitTest.rotationQuaternion;

					rootNode.position = hitTest.position;
					rootNode.rotationQuaternion = hitTest.rotationQuaternion;
				} else {
					marker.isVisible = false;
				}
			});

			if (anchors) {
				anchors.onAnchorAddedObservable.add((anchor) => {
					console.log('Anchor added');
					rootNode.getChildMeshes().forEach((m) => (m.isVisible = true));
					// model.isVisible = true;
					// model.isEnabled(true);
					anchor.attachedNode = rootNode;
					// shadowGenerator.addShadowCaster(model.attached)
				});
			}

			scene.onPointerDown = (evt: IPointerEvent, pickInfo: PickingInfo) => {
				if (hitTest && anchors && xr.baseExperience.state === WebXRState.IN_XR) {
					console.log('hittest', hitTest);
					console.log('session.inXRSession', session.inXRSession);
					anchors.addAnchorPointUsingHitTestResultAsync(hitTest);
					marker.isVisible = false;
					isPlaced = true;
				}
			};
		
		

			const session = await xr.baseExperience.enterXRAsync('immersive-ar', 'unbounded', xr.renderTarget);
			session.onXRSessionInit.addOnce(() => {
				console.log('Session Init');
			})
	})();
	}

	const onInitialized = useCallback(async (engineViewCallbacks: EngineViewCallbacks) => {
		setEngineViewCallbacks(engineViewCallbacks);
	}, [engine]);

	const onSnapshot = useCallback(async () => {
		if (engineViewCallbacks) {
			setSnapshotData('data:image/jpeg;base64,' + await engineViewCallbacks.takeSnapshot());
		}
	}, [engineViewCallbacks]);

	return (
		<>
			<View style={props.style}>
				<Button title="Start" onPress={ () => startXR() } />
				<EngineView camera={camera} onInitialized={onInitialized} displayFrameRate={true} antiAliasing={2} />
			</View>
		</>
	);
};

const App = () => {
	const [toggleScreen, setToggleScreen] = useState(false);

	return (
		<>
			<StatusBar barStyle="dark-content" />
			<SafeAreaView style={{ flex: 1, backgroundColor: 'white' }}>
				<EngineScreen style={{ flex: 1 }} />
			</SafeAreaView>
		</>
	);
};

export default App;

```

I mentioned it in a discussion about a problem I had [starting XR on ios](https://forum.babylonjs.com/t/babylonjs-native-xr-issue-on-ios/50044/19), I don’t think these are related. The XR issue is solved 🙂

---

<div class="post-metadata">

**Author:** ![RaananW](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/raananw/32/28955_2.png) [@RaananW](https://forum.babylonjs.com/u/RaananW)\
**Post date:** [May 21, 2024, 12:26pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/2 "2024-05-21T12:26:48Z")

</div>

pinging [@BabylonNative](https://forum.babylonjs.com/groups/babylonnative)

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [May 21, 2024, 12:37pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/3 "2024-05-21T12:37:33Z")

</div>

Does it repro easily? Can you repro with a small sample?

---

<div class="post-metadata">

**Author:** ![dnrn](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dnrn/32/4723_2.png) [@dnrn](https://forum.babylonjs.com/u/dnrn)\
**Post date:** [May 21, 2024, 8:31pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/4 "2024-05-21T20:31:19Z")

</div>

I forked the BabylonReactNative repo, and configured it like this:

Started by installed dependencies

```auto
npm ci
npm run select 0.71

```

Then I build the ios workspace with ruby 3.3.1 using chruby

```auto
gem install cocoapods

```

Opened the project in xcode and build it. Which gave me two issues. After some reading it seems related to a my version of xcode (13.4) and the version of react native (0.71). Is solved in 0.74.

1. `No template named 'unary_function' in namespace 'std'; did you mean '__unary_function'?`:  
Changed it to: `__unary_function`
2. Error in FlipperTransportTypes:  
Added `#include <functional>`

I’ve only tested it for 0.71, and here the issue seems quite consistant.  
After pressing the “start” button a simple “marker” is shown, which locate the floor plane. When pressing the screen the model is added at the anchor. Which results in the exception.

If it does work the first time it does crash after pressing the screen again, which tries to create a new anchor.

Please let me know if I can do anything to help. I do feel a bit guilty, submitting issues. I really love your commitment and the BabylonJS is a blast!

> **[GitHub - DNRN/BabylonReactNativeFork: Build React Native applications with...](https://github.com/DNRN/BabylonReactNativeFork)**
>
> Build React Native applications with the power of Babylon Native - DNRN/BabylonReactNativeFork

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [May 22, 2024, 9:33am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/5 "2024-05-22T09:33:32Z")

</div>



---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [May 22, 2024, 9:39am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/6 "2024-05-22T09:39:20Z")

</div>

I remember having the \_\_unary\_function build issue but I don’t remember the details. I’ll try to repro the crash in the coming days.

---

<div class="post-metadata">

**Author:** ![dnrn](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dnrn/32/4723_2.png) [@dnrn](https://forum.babylonjs.com/u/dnrn)\
**Post date:** [May 22, 2024, 9:57am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/7 "2024-05-22T09:57:30Z")

</div>

Your are a true hero!

I was able to solve the build issues. I think they are related to a combination between xcode 13.4 and react native 0.71. I tried to setup a react native project with version 0.74, and the issues was solved, but not sure how to set this up with Babylon react native (this is another topic)…

However I don’t think my problem with adding anchors throwing `EXC_BAD_ACCESS` is related though.

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [May 22, 2024, 12:42pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/8 "2024-05-22T12:42:58Z")

</div>

I’m working on an updated version of Babylon Native inside BRN.  
My branch is here : [Update BN and BJS version to 7.6.2 by CedricGuillemet · Pull Request #645 · BabylonJS/BabylonReactNative · GitHub](https://github.com/BabylonJS/BabylonReactNative/pull/645)  
Can you please test it on iOS and let me know if it fixes your issue?

---

<div class="post-metadata">

**Author:** ![dnrn](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dnrn/32/4723_2.png) [@dnrn](https://forum.babylonjs.com/u/dnrn)\
**Post date:** [May 23, 2024, 8:50am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/9 "2024-05-23T08:50:29Z")

</div>

I testet the branch and I still get the same exception, when I try to add an anchor with a call to:

```auto
addAnchorPointUsingHitTestResultAsync

```

I did however find another issue. In the newest branch of BabylonNative I found this issue where one of the boxes in the glb [BoxAnimated.glb](https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/BoxAnimated/glTF-Binary/BoxAnimated.glb) is drawn inverted. Should I file this issue in the BN repo?

The blue box have a hole which matches the red box.

 ![IMG_0011](https://us1.discourse-cdn.com/flex024/uploads/babylonjs/original/3X/4/c/4c18d927d666f61d0bd5b740f92e067121a404ef.png)  
 ![IMG_0012](https://us1.discourse-cdn.com/flex024/uploads/babylonjs/original/3X/3/f/3fba0b477f490bc7b0d35864086655cd3473554e.png)

In the newest version og BabylonNative the inside of the blue box is drawn instead:

 ![IMG_0010](https://us1.discourse-cdn.com/flex024/uploads/babylonjs/original/3X/9/4/940d556b461f53b0a28113097af1c2b3153df96e.png)

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [May 23, 2024, 8:57am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/10 "2024-05-23T08:57:16Z")

</div>

no need to open an issue for that. it was a known problem fixed with [Support non-normalized, non-float vertex buffers and unaligned vertex buffers by bghgary · Pull Request #1382 · BabylonJS/BabylonNative · GitHub](https://github.com/BabylonJS/BabylonNative/pull/1382)  
The BRN PR has been updated this morning.

---

<div class="post-metadata">

**Author:** ![dnrn](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dnrn/32/4723_2.png) [@dnrn](https://forum.babylonjs.com/u/dnrn)\
**Post date:** [May 23, 2024, 11:05am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/11 "2024-05-23T11:05:11Z")

</div>

That was effective 👏

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [May 23, 2024, 12:24pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/12 "2024-05-23T12:24:27Z")

</div>

yes but the add an anchor issue is still there 🙂

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [May 27, 2024, 3:23pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/13 "2024-05-27T15:23:23Z")

</div>

Good news: I can repro…now looking for a fix!

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [May 28, 2024, 3:09pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/14 "2024-05-28T15:09:13Z")

</div>

It’s a bit more clear about what happens. No valid fix yet but I’ve opened a GH issue to write down my investigations.

> <https://github.com/BabylonJS/BabylonNative/issues/1383>
>
> forum thread https://forum.babylonjs.com/t/babylonreactnative-throws-exception-w…hen-adding-anchor/50716/13
> 
> \`addAnchorPointUsingHitTestResultAsync\` kicks an exception.
> 
> call stack with a bunch of printf:
> !\[image\](https://github.com/BabylonJS/BabylonNative/assets/1312968/3a73dd73-408e-4a2d-a4ae-e024728dfcc7)
> Frame is destroyed before being used for adding an anchor. 
> 
> This is not an issue until the allocator returns the same allocated pointer. When the pointer is different (an allocation occured in the meantime), then the pointer is invalid. memory is cleared to zero after deallocation.
> 
> Investigations:
> \- drawFrame happens in dtor for frame. Keeping a smartpointer will make rendering stutter for a few frames.
> \-

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [June 12, 2024, 2:02pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/15 "2024-06-12T14:02:11Z")

</div>

Hi @dnrn  
I may have a valid fix : [Fix XR Frame alloc by CedricGuillemet · Pull Request #1386 · BabylonJS/BabylonNative · GitHub](https://github.com/BabylonJS/BabylonNative/pull/1386)  
Tested w/o crash on my side. Let me know how it runs

---

<div class="post-metadata">

**Author:** ![dnrn](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dnrn/32/4723_2.png) [@dnrn](https://forum.babylonjs.com/u/dnrn)\
**Post date:** [June 13, 2024, 12:29pm UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/16 "2024-06-13T12:29:18Z")

</div>

I works!

Just pulled and tested. I do not get the exception anymore, and is able to add anchors.  
Thanks a lot!

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [June 14, 2024, 8:45am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/17 "2024-06-14T08:45:14Z")

</div>

Hi @dnrn  
Sorry to bug you again. I’ve updated the PR with a simpler fix. No issue/crash on my side. Can you please test it as well? Thanks in advance!

---

<div class="post-metadata">

**Author:** ![dnrn](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dnrn/32/4723_2.png) [@dnrn](https://forum.babylonjs.com/u/dnrn)\
**Post date:** [June 14, 2024, 9:18am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/18 "2024-06-14T09:18:01Z")

</div>

It works 🙂

And no problem bugging me. I’m glad I can help, it’s an amazing work you do!

---

<div class="post-metadata">

**Author:** ![Cedric](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/cedric/32/2742_2.png) [@Cedric](https://forum.babylonjs.com/u/Cedric)\
**Post date:** [June 20, 2024, 9:54am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/19 "2024-06-20T09:54:42Z")

</div>

@dnrn really sorry, this fix takes ages to merge because of simplification, refactor and such can you please try the fix again? [Fix XR Frame alloc by CedricGuillemet · Pull Request #1386 · BabylonJS/BabylonNative · GitHub](https://github.com/BabylonJS/BabylonNative/pull/1386)

---

<div class="post-metadata">

**Author:** ![dnrn](https://sea2.discourse-cdn.com/flex024/user_avatar/forum.babylonjs.com/dnrn/32/4723_2.png) [@dnrn](https://forum.babylonjs.com/u/dnrn)\
**Post date:** [June 21, 2024, 9:42am UTC](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716/20 "2024-06-21T09:42:20Z")

</div>

@Cedric Just testet it, and it works 🙂  
Thanks for your great work!

[Next page](https://forum.babylonjs.com/t/babylonreactnative-throws-exception-when-adding-anchor/50716.md?page=2)
