Loading 3D model in Jetpack Compose app
In order to load a 3D model into an AR/VR Android app built on Jetpack Compose UI, it's best to use the SceneView library by Thomas Gorisse. To implement AR/VR SceneView, paste the following code into build.gradle.kts (Module :app) file.
dependencies { // Virtual Reality View
implementation("io.github.sceneview:sceneview:2.2.1")
}
dependencies { // Augmented Reality View
implementation("io.github.sceneview:arsceneview:2.2.1")
}
When using SceneView, .glb (GL Transmission Format Binary file) models are ideal. .glb is a binary version of .gltf format, and it can contain an hierarchy of polygonal geometry, lighting, materials, and animations in a single compressed file. You can find many .glb models on the sketchfab.com.
The Kotlin code to load a VR scene is as simple as that:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
VRSceneViewTheme {
val engine = rememberEngine()
val modelLoader = rememberModelLoader(engine)
val cameraNode = rememberCameraNode(engine)
cameraNode.position = Position(z = 2.5f)
Scene(
modifier = Modifier.fillMaxSize(),
engine = engine,
modelLoader = modelLoader,
cameraNode = cameraNode,
childNodes = listOf(
ModelNode(
modelInstance = modelLoader
.createModelInstance("pigeon.glb"),
scaleToUnits = 1.25f
)
)
)
}
}
}
}
