SceneView / sceneview-android

SceneView is a 3D and AR Android Composable and View with Google Filament and ARCore. This is a Sceneform replacement in Kotlin
Apache License 2.0
758 stars 151 forks source link

How to change texture of 3d model at runtime #433

Closed Somendra121 closed 1 month ago

Somendra121 commented 4 months ago

Please let us know how to change texture of 3d model at runtime, in sceneform we use this code to change texture at runtime :

` public void LoadTexture(Context context, Bitmap colorImageBitmap) { Log.d("LoadTexture", "LoadTexture : @@@@@@@1 renderableInstance.size() : " + renderableInstances.size()); for (RenderableInstance renderableInstance : renderableInstances) { Texture.builder() .setSource(colorImageBitmap) .setSampler( Texture.Sampler.builder() .setWrapMode(Texture.Sampler.WrapMode.REPEAT) .build() ) .build() .thenAccept(texture -> { MaterialFactory.makeOpaqueWithTexture(context, texture) .thenAccept(material -> { material.setFloat("roughness", 0.5f); // Set roughness material.setFloat("ao", 1.0f); // Set AO Log.d("LoadTexture", "LoadTexture :@@@@@@2 renderableInstance.getMaterialsCount() : " + renderableInstance.getMaterialsCount());

                                renderableInstance.setMaterial(0, material);
                            });
                });
        Log.d("LoadTexture", "LoadTexture @@@@@@@3 : renderableInstance.getEntity() : " + renderableInstance.getEntity());
    }
}`
EvergreenTree97 commented 2 months ago

I solved it as follows

private fun createTextureFromBitmap(engine: Engine, bitmap: Bitmap): Texture {
    val texture = Texture.Builder()
        .width(bitmap.width)
        .height(bitmap.height)
        .levels(1)
        .sampler(Texture.Sampler.SAMPLER_2D)
        .format(Texture.InternalFormat.SRGB8_A8)
        .build(engine)

    val buffer = ByteBuffer.allocateDirect(bitmap.byteCount)
    bitmap.copyPixelsToBuffer(buffer)
    buffer.flip()
    texture.setImage(
        engine, 0, Texture.PixelBufferDescriptor(
            buffer,
            Texture.Format.RGBA,
            Texture.Type.UBYTE
        )
    )
    buffer.clear()
    return texture
}

texture = createTextureFromBitmap(engine, bitmap)
(modelNodes[0] as ModelNode).materialInstances[0][0] = setBaseColorMap(texture)