我有一个增强现实应用程序,其中的 ARObject
是一个POJO。
class ARObject {
CompletableFuture<Texture> texture;
CompletableFuture<Material> material;
ModelRenderable renderable;
void setTexture(CompletableFuture<Texture> texture) {
this.texture = texture;
}
CompletableFuture<Texture> getTexture() {
return texture;
}
void setMaterial(CompletableFuture<Material> material) {
this.material = material;
}
CompletableFuture<Material> getMaterial() {
return material;
}
}
场景是实时组成的。在这个过程中 Texture
对象,然后需要建立 Material
对象,基于 Texture
对象。一旦 Material
好了,那么 ShapeFactory
可以用来生成实际的AR对象(作为一种形式的 Renderable
). 这意味着构建逻辑包含两个 CompletableFuture
嵌套到每个AR对象中。
for (ARObject arObject : arObjects) {
Texture.Builder textureBuilder = Texture.builder();
textureBuilder.setSource(context, arObject.resourceId);
CompletableFuture<Texture> texturePromise = textureBuilder.build(); // Future #1
arObject.setTexture(texturePromise);
texturePromise.thenAccept(texture -> {
CompletableFuture<Material> materialPromise =
MaterialFactory.makeOpaqueWithTexture(context, texture); // Future #2
arObject.setMaterial(materialPromise);
});
}
一个完成场景构建的方法是等到所有的AR对象都被嵌套在一起 CompletableFuture
s完成,然后 ShapeFactory
步可以来。
我试着用 .get()
在...上 Future
的,但这不仅会完全破坏异步调用所提供的并行性,而且也会锁定应用程序,因为我认为它造成了UI线程的等待。
Arrays.stream(arObjectList).forEach(a -> {
try {
a.getTexture().get();
} catch (ExecutionException | InterruptedException e) {
Log.e(TAG, "Texture CompletableFuture waiting problem " + e.toString());
}
});
Arrays.stream(arObjectList).forEach(a -> {
try {
a.getMaterial().get();
} catch (ExecutionException | InterruptedException e) {
Log.e(TAG, "Material CompletableFuture waiting problem " + e.toString());
}
});
我将构建过程分解为几个函数,这些函数以调用链的形式相互调用。这个链是如下的。
populateScene
afterTexturesLoaded
afterTexturesSet
waitForMaterials
afterMaterialsLoaded
private void afterMaterialsLoaded() {
// Step 3: composing scene objects
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());
for (ARObject arObject : arObjectList) {
try {
Material textureMaterial = arObject.getMaterial().get();
RunnableShapeBuilder shapeBuilder = new RunnableShapeBuilder(arObject, this, textureMaterial);
mainHandler.post(shapeBuilder);
}
catch (ExecutionException | InterruptedException e) {
Log.e(TAG, "Scene populating exception " + e.toString());
}
}
}
private Long waitForMaterials() {
while (!Stream.of(arObjectList).allMatch(arObject -> arObject.getMaterial() != null)) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
return 0L;
}
private void afterTexturesSet() {
boolean materialsDone = Stream.of(arObjectList).allMatch(arObject -> arObject.getMaterial() != null && arObject.getMaterial().isDone());
// If any of the materials are not loaded, then recurse until all are loaded.
if (!materialsDone) {
CompletableFuture<Texture>[] materialPromises =
Stream.of(arObjectList).map(ARObject::getMaterial).toArray(CompletableFuture[]::new);
CompletableFuture.allOf(materialPromises)
.thenAccept((Void aVoid) -> afterMaterialsLoaded())
.exceptionally(
throwable -> {
Log.e(TAG, "Exception building scene", throwable);
return null;
});
} else {
afterMaterialsLoaded();
}
}
private void afterTexturesLoaded() {
// Step 2: material loading
CompletableFuture materialsSetPromise = CompletableFuture.supplyAsync(this::waitForMaterials);
CompletableFuture.allOf(materialsSetPromise)
.thenAccept((Void aVoid) -> afterTexturesSet())
.exceptionally(
throwable -> {
Log.e(TAG, "Exception building scene", throwable);
return null;
});
}
/**
* Called when the AugmentedImage is detected and should be rendered. A Sceneform node tree is
* created based on an Anchor created from the image.
*/
@SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"})
void populateScene() {
// Step 1: texture loading
boolean texturesDone = Stream.of(arObjectList).allMatch(arObject -> arObject.getTexture() != null && arObject.getTexture().isDone());
// If any of the textures are not loaded, then recurse until all are loaded.
if (!texturesDone) {
CompletableFuture<Texture>[] texturePromises =
Stream.of(arObjectList).map(ARObject::getTexture).toArray(CompletableFuture[]::new);
CompletableFuture.allOf(texturePromises)
.thenAccept((Void aVoid) -> afterTexturesLoaded())
.exceptionally(
throwable -> {
Log.e(TAG, "Exception building scene", throwable);
return null;
});
} else {
afterTexturesLoaded();
}
}
这样做有几个问题 第一:它还是有点拙劣的异步性质。在理想的情况下,一个对应的材质纹理对会被独立加载,并从其他对中生成。在这个最新的版本中,执行流程中有很多会合点,这并不符合理想中的独立情况。第二:我甚至无法避免 waitForMaterials
丑步 Thread.sleep()
. 第三:这段代码总体上还是失败的,因为在最后一步,当最终从加载的纹理和材料中构建形状时,我得到了一个错误信息 java.lang.IllegalStateException: Must be called from the UI thread.
. 正因为如此,我又加了一个转折。RunnableShapeBuilder
. 这样一来,就没有异常了,但场景上还是什么都没有显示出来,同时代码也变得更加复杂。
class RunnableShapeBuilder implements Runnable {
ARObject arObject;
AnchorNode parentNode;
Material textureMaterial;
RunnableShapeBuilder(ARObject arObject, AnchorNode parentNode, Material textureMaterial) {
this.arObject = arObject;
this.parentNode = parentNode;
this.textureMaterial = textureMaterial;
}
@Override
public void run() {
arObject.renderable = ShapeFactory.makeCube(
new Vector3(0.5f, 1, 0.01f),
new Vector3(0.0f, 0.0f, 0.0f),
textureMaterial
);
...
}
}
答案是:我不需要等待这些嵌套的 CompletableFuture
s. 当我的方案变得更加复杂时,我以为我必须等到3D材质和纹理的构建完成。问题出在一个题外话的地方:虽然我设置了AR对象的锚。AR对象的锚是由命中测试得出的,我需要将锚的父体设置为AR场景。这最后一步在一些重构过程中丢失了,如果发生这种情况,没有任何警告,只是在AR场景上没有任何显示。
专注于问题本身。我非常不建议你在任何问题上等待,因为这会导致痛苦和折磨。寻求不同的解决巷子。