Android NDK 앱에서 Depth 사용

Depth API를 사용하면 기기의 카메라가 장면에 있는 실제 객체의 크기와 모양을 파악할 수 있습니다. 카메라를 사용하여 깊이 이미지 또는 깊이 지도를 만들어 앱에 AR의 사실감을 더합니다. 깊이 이미지로 제공되는 정보를 사용하여 가상 객체가 실제 객체 앞이나 뒤에 정확하게 표시되도록 하여 몰입도 높고 사실적인 사용자 환경을 만들 수 있습니다.

심도 정보는 움직임을 통해 계산되며, 가능한 경우 ToF (Time-Of-ToF) 센서와 같은 하드웨어 깊이 센서의 정보와 결합될 수 있습니다. Depth API를 지원하기 위해 기기에 ToF 센서가 필요하지 않음.

기본 요건

계속 진행하기 전에 기본 AR 개념ARCore 세션 구성 방법을 이해해야 합니다.

심도 지원 기기에 대한 액세스 제한

앱에 Depth API 지원이 필요한 경우 AR 환경의 핵심 부분이 깊이에 의존하거나 깊이를 사용하는 앱 부분에 적절한 대체가 없기 때문에 Depth API를 지원하는 기기로 앱 배포를 제한할 수 있습니다. 가이드에 설명된 AndroidManifest.xml 변경사항 외에도 ARCore를 사용 설정합니다.AndroidManifest.xml

<uses-feature android:name="com.google.ar.core.depth" />

깊이 사용 설정

새 ARCore 세션에서 사용자 기기가 깊이를 지원하는지 확인합니다. 처리 성능 제약으로 인해 일부 ARCore 호환 기기는 Depth API를 지원하지 않습니다. 리소스를 절약하기 위해 ARCore에서는 깊이가 기본적으로 사용 중지됩니다. 앱에서 Depth API를 사용하도록 깊이 모드를 사용 설정합니다.

// Check whether the user's device supports the Depth API.
int32_t is_depth_supported = 0;
ArSession_isDepthModeSupported(ar_session, AR_DEPTH_MODE_AUTOMATIC,
                               &is_depth_supported);

// Configure the session for AR_DEPTH_MODE_AUTOMATIC.
ArConfig* ar_config = NULL;
ArConfig_create(ar_session, &ar_config);
if (is_depth_supported) {
  ArConfig_setDepthMode(ar_session, ar_config, AR_DEPTH_MODE_AUTOMATIC);
}
CHECK(ArSession_configure(ar_session, ar_config) == AR_SUCCESS);
ArConfig_destroy(ar_config);

깊이 이미지 획득

ArFrame_acquireDepthImage16Bits()를 호출하여 현재 프레임의 깊이 이미지를 가져옵니다.

// Retrieve the depth image for the current frame, if available.
ArImage* depth_image = NULL;
// If a depth image is available, use it here.
if (ArFrame_acquireDepthImage16Bits(ar_session, ar_frame, &depth_image) !=
    AR_SUCCESS) {
  // No depth image received for this frame.
  // This normally means that depth data is not available yet.
  // Depth data will not be available if there are no tracked
  // feature points. This can happen when there is no motion, or when the
  // camera loses its ability to track objects in the surrounding
  // environment.
  return;
}

반환된 이미지는 원시 이미지 버퍼를 제공합니다. 원시 이미지 버퍼는 프래그먼트 셰이더에 전달되어 오클루드될 렌더링된 각 객체에 대해 GPU에서 사용할 수 있습니다. AR_COORDINATES_2D_OPENGL_NORMALIZED_DEVICE_COORDINATES 방향이며 ArFrame_transformCoordinates2d()를 호출하여 AR_COORDINATES_2D_TEXTURE_NORMALIZED로 변경할 수 있습니다. 객체 셰이더 내에서 깊이 이미지에 액세스할 수 있게 되면 오클루전 처리를 위해 이러한 깊이 측정에 직접 액세스할 수 있습니다.

깊이 값 이해

관찰된 실제 도형에 있는 점 A과 깊이 이미지의 같은 지점을 나타내는 2D 점 a이 있으면 a의 Depth API에서 지정된 값은 주축에 투영된 CA의 길이와 같습니다. 카메라 원점(C)을 기준으로 한 A의 z 좌표라고도 합니다. Depth API를 사용할 때는 깊이 값이 광선 CA 자체의 길이가 아니라 광선의 투영임을 이해하는 것이 중요합니다.

셰이더의 깊이 사용

현재 프레임의 깊이 정보 파싱

프래그먼트 셰이더에서 도우미 함수 DepthGetMillimeters()DepthGetVisibility()를 사용하여 현재 화면 위치의 깊이 정보에 액세스합니다. 그런 다음 이 정보를 사용하여 렌더링된 객체의 일부를 선택적으로 가립니다.

// Use DepthGetMillimeters() and DepthGetVisibility() to parse the depth image
// for a given pixel, and compare against the depth of the object to render.
float DepthGetMillimeters(in sampler2D depth_texture, in vec2 depth_uv) {
  // Depth is packed into the red and green components of its texture.
  // The texture is a normalized format, storing millimeters.
  vec3 packedDepthAndVisibility = texture2D(depth_texture, depth_uv).xyz;
  return dot(packedDepthAndVisibility.xy, vec2(255.0, 256.0 * 255.0));
}

// Return a value representing how visible or occluded a pixel is relative
// to the depth image. The range is 0.0 (not visible) to 1.0 (completely
// visible).
float DepthGetVisibility(in sampler2D depth_texture, in vec2 depth_uv,
                         in float asset_depth_mm) {
  float depth_mm = DepthGetMillimeters(depth_texture, depth_uv);

  // Instead of a hard Z-buffer test, allow the asset to fade into the
  // background along a 2 * kDepthTolerancePerMm * asset_depth_mm
  // range centered on the background depth.
  const float kDepthTolerancePerMm = 0.015f;
  float visibility_occlusion = clamp(0.5 * (depth_mm - asset_depth_mm) /
    (kDepthTolerancePerMm * asset_depth_mm) + 0.5, 0.0, 1.0);

 // Use visibility_depth_near to set the minimum depth value. If using
 // this value for occlusion, avoid setting it too close to zero. A depth value
 // of zero signifies that there is no depth data to be found.
  float visibility_depth_near = 1.0 - InverseLerp(
      depth_mm, /*min_depth_mm=*/150.0, /*max_depth_mm=*/200.0);

  // Use visibility_depth_far to set the maximum depth value. If the depth
  // value is too high (outside the range specified by visibility_depth_far),
  // the virtual object may get inaccurately occluded at further distances
  // due to too much noise.
  float visibility_depth_far = InverseLerp(
      depth_mm, /*min_depth_mm=*/7500.0, /*max_depth_mm=*/8000.0);

  const float kOcclusionAlpha = 0.0f;
  float visibility =
      max(max(visibility_occlusion, kOcclusionAlpha),
          max(visibility_depth_near, visibility_depth_far));

  return visibility;
}

가상 객체 제외

프래그먼트 셰이더 본문에서 가상 객체를 제외합니다. 깊이에 따라 객체의 알파 채널을 업데이트합니다. 이렇게 하면 가려진 객체가 렌더링됩니다.

// Occlude virtual objects by updating the object’s alpha channel based on its depth.
const float kMetersToMillimeters = 1000.0;

float asset_depth_mm = v_ViewPosition.z * kMetersToMillimeters * -1.;

// Compute the texture coordinates to sample from the depth image.
vec2 depth_uvs = (u_DepthUvTransform * vec3(v_ScreenSpacePosition.xy, 1)).xy;

gl_FragColor.a *= DepthGetVisibility(u_DepthTexture, depth_uvs, asset_depth_mm);

2 패스 렌더링 또는 객체별 정방향 전달 렌더링을 사용하여 오클루전을 렌더링할 수 있습니다. 각 접근 방식의 효율성은 장면의 복잡성과 기타 앱 관련 고려사항에 따라 다릅니다.

객체별, 정방향 전달 렌더링

객체별 정방향 전달 렌더링은 머티리얼 셰이더에서 객체의 각 픽셀의 오클루전을 결정합니다. 픽셀이 보이지 않으면 일반적으로 알파 블렌딩을 통해 잘리므로 사용자 기기에서 오클루전을 시뮬레이션합니다.

2 패스 렌더링

투 패스 렌더링을 사용하면 첫 번째 패스가 모든 가상 콘텐츠를 중간 버퍼로 렌더링합니다. 두 번째 패스는 실제 깊이와 가상 장면 깊이의 차이에 따라 가상 장면을 배경에 블렌딩합니다. 이 접근 방식은 객체별 추가 셰이더 작업이 필요하지 않으며 일반적으로 정방향 전달 메서드보다 더 균일한 결과를 생성합니다.

카메라 이미지와 깊이 이미지 간 좌표 변환

ArFrame_acquireCameraImage()를 사용하여 얻은 이미지는 깊이 이미지와 가로세로 비율이 다를 수 있습니다. 이 경우 깊이 이미지는 카메라 이미지의 일부이며, 카메라 이미지의 모든 픽셀에 상응하는 유효한 깊이 추정치가 있는 것은 아닙니다.

CPU 이미지의 좌표에 대한 깊이 이미지 좌표를 가져오는 방법은 다음과 같습니다.

const float cpu_image_coordinates[] = {(float)cpu_coordinate_x,
                                 (float)cpu_coordinate_y};
float texture_coordinates[2];
ArFrame_transformCoordinates2d(
    ar_session, ar_frame, AR_COORDINATES_2D_IMAGE_PIXELS, 1,
    cpu_image_coordinates, AR_COORDINATES_2D_TEXTURE_NORMALIZED,
    texture_coordinates);
if (texture_coordinates[0] < 0 || texture_coordinates[1] < 0) {
  // There are no valid depth coordinates, because the coordinates in the CPU
  // image are in the cropped area of the depth image.
} else {
  int depth_image_width = 0;
  ArImage_getWidth(ar_session, depth_image, &depth_image_width);
  int depth_image_height = 0;
  ArImage_getHeight(ar_session, depth_image, &depth_image_height);

  int depth_coordinate_x = (int)(texture_coordinates[0] * depth_image_width);
  int depth_coordinate_y = (int)(texture_coordinates[1] * depth_image_height);
}

깊이 이미지 좌표의 CPU 이미지 좌표를 가져오는 방법은 다음과 같습니다.

int depth_image_width = 0;
ArImage_getWidth(ar_session, depth_image, &depth_image_width);
int depth_image_height = 0;
ArImage_getHeight(ar_session, depth_image, &depth_image_height);

float texture_coordinates[] = {
    (float)depth_coordinate_x / (float)depth_image_width,
    (float)depth_coordinate_y / (float)depth_image_height};
float cpu_image_coordinates[2];
ArFrame_transformCoordinates2d(
    ar_session, ar_frame, AR_COORDINATES_2D_TEXTURE_NORMALIZED, 1,
    texture_coordinates, AR_COORDINATES_2D_IMAGE_PIXELS,
    cpu_image_coordinates);

int cpu_image_coordinate_x = (int)cpu_image_coordinates[0];
int cpu_image_coordinate_y = (int)cpu_image_coordinates[1];

깊이 히트 테스트

히트 테스트를 통해 사용자는 장면의 실제 위치에 객체를 배치할 수 있습니다. 이전에는 감지된 평면에서만 히트 테스트를 실행할 수 있었기 때문에 초록색 Android에 표시되는 결과와 같이 크고 평평한 표면으로 위치를 제한했습니다. 깊이 히트 테스트는 매끄러운 깊이와 원시 깊이 정보를 모두 활용하여 비평면 및 낮은 텍스처 표면에서도 더 정확한 히트 결과를 제공합니다. 빨간색 Android로 표시되어 있습니다.

깊이 지원 히트 테스트를 사용하려면 ArFrame_hitTest()를 호출하고 반환 목록에서 AR_TRACKABLE_DEPTH_POINT를 확인합니다.

// Create a hit test using the Depth API.
ArHitResultList* hit_result_list = NULL;
ArHitResultList_create(ar_session, &hit_result_list);
ArFrame_hitTest(ar_session, ar_frame, hit_x, hit_y, hit_result_list);

int32_t hit_result_list_size = 0;
ArHitResultList_getSize(ar_session, hit_result_list, &hit_result_list_size);

ArHitResult* ar_hit_result = NULL;
for (int32_t i = 0; i < hit_result_list_size; ++i) {
  ArHitResult* ar_hit = NULL;
  ArHitResult_create(ar_session, &ar_hit);
  ArHitResultList_getItem(ar_session, hit_result_list, i, ar_hit);

  ArTrackable* ar_trackable = NULL;
  ArHitResult_acquireTrackable(ar_session, ar_hit, &ar_trackable);
  ArTrackableType ar_trackable_type = AR_TRACKABLE_NOT_VALID;
  ArTrackable_getType(ar_session, ar_trackable, &ar_trackable_type);
  // Creates an anchor if a plane or an oriented point was hit.
  if (AR_TRACKABLE_DEPTH_POINT == ar_trackable_type) {
    // Do something with the hit result.
  }
  ArTrackable_release(ar_trackable);
  ArHitResult_destroy(ar_hit);
}

ArHitResultList_destroy(hit_result_list);

다음 단계

  • Raw Depth API를 사용하여 더 정확하게 감지할 수 있습니다.
  • 깊이 데이터에 액세스하는 다양한 방법을 보여주는 ARCore Depth Lab을 확인하세요.