Sceneform для метода создания бокса ARCore

Я пытаюсь создать простой красный прямоугольник в Sceneform для Android ARCore с помощью ShapeFactory. Я не смог найти такого примера, самый близкий из них - изменение материалов на существующем объекте. Ниже я думаю, что у меня есть код в основном правильный с попыткой создать узел для блока, который создается и прикрепляется к узлу привязки, при этом фактический материал, геометрия и положение блока также создаются и прикрепляются в качестве рендеринга узла. Ошибка показывает, что "boxo" никогда не используется и что "boxo" не распознается при попытке setRenderable ()

package com.google.ar.sceneform.samples.hellosceneform;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.Toast;
import com.google.ar.core.Anchor;
import com.google.ar.core.HitResult;
import com.google.ar.core.Plane;
import com.google.ar.sceneform.AnchorNode;
import com.google.ar.sceneform.math.Vector3;
import com.google.ar.sceneform.rendering.Color;
import com.google.ar.sceneform.rendering.MaterialFactory;
import com.google.ar.sceneform.rendering.ModelRenderable;
import com.google.ar.sceneform.rendering.Renderable;
import com.google.ar.sceneform.rendering.ShapeFactory;
import com.google.ar.sceneform.ux.ArFragment;
import com.google.ar.sceneform.ux.TransformableNode;

import static com.google.ar.sceneform.rendering.ShapeFactory.makeCube;

/**
 * This is an example activity that uses the Sceneform UX package to make common AR tasks easier.
 */
public class HelloSceneformActivity extends AppCompatActivity {
  private static final String TAG = HelloSceneformActivity.class.getSimpleName();
  private static final double MIN_OPENGL_VERSION = 3.0;

  private ArFragment arFragment;
  private ModelRenderable pipesRenderable;

  @Override
  @SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"})
  // CompletableFuture requires api level 24
  // FutureReturnValueIgnored is not valid
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!checkIsSupportedDeviceOrFinish(this)) {
      return;
    }

    setContentView(R.layout.activity_ux);
    arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);

    // When you build a Renderable, Sceneform loads its resources in the background while returning
    // a CompletableFuture. Call thenAccept(), handle(), or check isDone() before calling get().
    ModelRenderable.builder()
        .setSource(this, Uri.parse("pipes.sfb"))
        .build()
        .thenAccept(renderable -> pipesRenderable = renderable)
        .exceptionally(
            throwable -> {
              Toast toast =
                  Toast.makeText(this, "Unable to load pipes renderable", Toast.LENGTH_LONG);
              toast.setGravity(Gravity.CENTER, 0, 0);
              toast.show();
              return null;
            });

    arFragment.setOnTapArPlaneListener(
        (HitResult hitResult, Plane plane, MotionEvent motionEvent) -> {
          if (pipesRenderable == null) {
            return;
          }

          // Create the Anchor.
          Anchor anchor = hitResult.createAnchor();
          AnchorNode anchorNode = new AnchorNode(anchor);
          anchorNode.setParent(arFragment.getArSceneView().getScene());

          // Create the transformable andy and add it to the anchor.
          TransformableNode pipes = new TransformableNode(arFragment.getTransformationSystem());
          pipes.setParent(anchorNode);
          pipes.setRenderable(pipesRenderable);
          pipes.select();

          TransformableNode cube = new TransformableNode(arFragment.getTransformationSystem());
          cube.setParent(anchorNode);
         // MaterialFactory
         // ModelRenderable box = ShapeFactory.makeCube(new Vector3(1f, 1f, 1f), new Vector3(0.0f, 0.15f, 0.0f), boxMat);
            //
            MaterialFactory.makeOpaqueWithColor(this, new Color(android.graphics.Color.RED))
                    .thenAccept(
                            material -> {
                               ModelRenderable boxo = ShapeFactory.makeCube(new Vector3(1f, 1f, 1f), new Vector3(1f, 1f, 1f), material); });
          cube.setRenderable(boxo);
          cube.select();

        });
  }

}

  */

  /**
   * Returns false and displays an error message if Sceneform can not run, true if Sceneform can run
   * on this device.
   *
   * <p>Sceneform requires Android N on the device as well as OpenGL 3.0 capabilities.
   *
   * <p>Finishes the activity if Sceneform can not run
   */
  public static boolean checkIsSupportedDeviceOrFinish(final Activity activity) {
    if (Build.VERSION.SDK_INT < VERSION_CODES.N) {
      Log.e(TAG, "Sceneform requires Android N or later");
      Toast.makeText(activity, "Sceneform requires Android N or later", Toast.LENGTH_LONG).show();
      activity.finish();
      return false;
    }
    String openGlVersionString =
        ((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE))
            .getDeviceConfigurationInfo()
            .getGlEsVersion();
    if (Double.parseDouble(openGlVersionString) < MIN_OPENGL_VERSION) {
      Log.e(TAG, "Sceneform requires OpenGL ES 3.0 later");
      Toast.makeText(activity, "Sceneform requires OpenGL ES 3.0 or later", Toast.LENGTH_LONG)
          .show();
      activity.finish();
      return false;
    }
    return true;
  }
}

person MurServ    schedule 17.08.2018    source источник


Ответы (2)


Вот как это сделать:

arFragment.setOnTapArPlaneListener(
            (HitResult hitResult, Plane plane, MotionEvent motionEvent) -> {

                if (andyRenderable == null) {
                    return;
                }

                // Create the Anchor.
                Anchor anchor = hitResult.createAnchor();
                AnchorNode anchorNode = new AnchorNode(anchor);
                anchorNode.setParent(arFragment.getArSceneView().getScene());


                MaterialFactory.makeTransparentWithColor(getApplicationContext(), new Color(244, 244, 244))
                        .thenAccept(
                                material -> {

                                    Vector3 vector3 = new Vector3(0.05f, 0.05f,0.05f);
                                    ModelRenderable model = ShapeFactory.makeCube(vector3,
                                            Vector3.zero(), material);
                                    model.setShadowCaster(false);
                                    model.setShadowReceiver(false);

                                    TransformableNode transformableNode = new TransformableNode(arFragment.getTransformationSystem());
                                    transformableNode.setParent(anchorNode);
                                    transformableNode.setRenderable(model);
                                    transformableNode.select();
            });
}
person Shubham Agrawal    schedule 10.10.2018

Ваша переменная boxo действительна только в лямбде. Измените его на:

MaterialFactory.makeOpaqueWithColor(this, new Color(android.graphics.Color.RED))
                .thenAccept(
                        material -> {
                           ModelRenderable boxo = ShapeFactory.makeCube(new Vector3(1f, 1f, 1f), new Vector3(1f, 1f, 1f), material); 
                           cube.setRenderable(boxo);
                           cube.select();
                           });

и это будет работать

person Steven Mohr    schedule 20.08.2018