Load local stl file from assets in react native

I’ve never tried the RNFS approach, but if you are already embedding the original file into the app, then it seems like you should be able to just load a URI via app://. If you are trying to make this work for multiple platforms (e.g. iOS and Android), then this can be a hassle because the paths can be different.

Another option as @DarraghBurke pointed out is to embed the base64 encoded model as a .json file. This will for sure work, the downside is the extra file size and loading cost dealing with the base64 decoding. If people use this approach frequently, we could perhaps make it easier by exposing a Babylon React Native NPM script to do the encoding for you using the Buffer class from Node.js (so you could run a command like npx @babylonjs/react-native base64Encode SomeModel.stl).

Another option yet would be to rely on the React Native method of embedding asset files in the app via require. You can see an example of this here: importing a .glb file fails if only local path is provided and not served through HTTP · Issue #165 · BabylonJS/BabylonReactNative · GitHub. In this example, expo-asset is used, but you should be able to achieve the same thing without taking a dependency on Expo by doing this:

import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
const stlUri = resolveAssetSource(require('./SomeModel.stl')).uri;
SceneLoader.ImportMeshAsync('', stlUri);

Whether you use expo-asset or the React Native libs directly, you will need to tell the metro bundler to bundle .stl files as assets by modifying the metro.config.js file with these changes:

const defaultAssetExts = require("metro-config/src/defaults/defaults").assetExts;
...
module.exports = {
  ...
  assetExts: [...defaultAssetExts, 'stl'],
};

It would be great if someone could validate these steps and document them here: BabylonReactNative/README.md at master · BabylonJS/BabylonReactNative (github.com)

2 Likes