AR 엔진과 인간의 균형 잡기

14785 단어


소개



HUAWEI AR Engine tiene soporte para detectar objetos en el mundo real que se llama "Seguimiento del entorno"y con él puede registrar iluminación, plano, imagen, objeto, superficie y otra información ambiental para ayudar a sus aplicaciones a fusionar objetos virtuales en escenarios físicos . 문도.

신체 추적



Esta función identifica y rastrea ubicaciones 2D para 23 puntos del esqueleto corporal (o ubicaciones 3D de 15 puntos del esqueleto corporal) y entere el seguimiento de una o dos personas a la vez.
AR Engine reconoce cuerpos humanos y genera coordenadas 2D y 3D (basadas en SLAM) de puntos del esqueleto, y es capaz de cambiar entre las camaras delantera y trasera.
La capacidad de seguimiento del cuerpo le permite superponer objetos virtuales en el cuerpo con un alto grado de precision, como en el hombro izquierdo o el tobillo derecho. 현실화할 수 있는 시장은 자신의 아바타에 정확하게 접근할 수 있으며, AR은 다양한 기능을 사용할 수 있습니다.

Android의 응용 프로그램 예



Para este ejemplo, trabajaremos en el seguimiento del entorno para que podamos detector una mano e interactuar con ella.

처리 과정


응용 프로그램 만들기



Cree는 AppGallery Connect 프로젝트 생성 및 프로젝트에 앱 추가에 대한 지침을 적용합니다.
플랫폼: Android
Dispositivo: 휴대폰
앱 카테고리: 앱 또는 게임

HUAWEI AR 엔진 SDK 통합



Antes del desarrollo, integre HUAWEI AR Engine SDK a través del repositorio de Maven en su entorno de desarrollo.
Abra el archivo build.gradle en el directorio raíz de su proyecto de Android Studio.

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
        maven {url 'https://developer.huawei.com/repo/'}
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"
        classpath 'com.huawei.agconnect:agcp:1.3.2.301'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven {url 'https://developer.huawei.com/repo/'}
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


Abra el archivo build.gradle en el directorio de la aplicación de su proyecto

apply plugin: 'com.android.application'
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"
defaultConfig {
        applicationId "com.vsm.myarapplication"
        minSdkVersion 27
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.12'
    //
    implementation 'com.huawei.agconnect:agconnect-core:1.4.2.301'
    //
    implementation 'com.huawei.hms:arenginesdk:2.15.0.1'
    //
    implementation 'de.javagl:obj:0.3.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
apply plugin: 'com.huawei.agconnect'


활동을 활성화하기 위한 활동(activity_body.xml):

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".body.BodyActivity">
<android.opengl.GLSurfaceView
        android:id="@+id/bodySurfaceview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="top"
        tools:ignore="MissingConstraints" />
<TextView
        android:id="@+id/bodyTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="@color/red"
        tools:layout_editor_absoluteX="315dp"
        tools:layout_editor_absoluteY="4dp"
        tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>


AR Engine no es para todos los dispositivos, por lo que primero debemos validar si el dispositivo es compatible con AR Engine y está disponible, aquí está la lista de dispositivos compatibles


Utilizará estos métodos para comprobar si un dispositivo es compatible:

메토도스



private void setMessageWhenError(Exception catchException) {
    if (catchException instanceof ARUnavailableServiceNotInstalledException) {
        startActivity(new Intent(getApplicationContext(), ConnectAppMarketActivity.class));
    } else if (catchException instanceof ARUnavailableServiceApkTooOldException) {
        message = "Please update HuaweiARService.apk";
    } else if (catchException instanceof ARUnavailableClientSdkTooOldException) {
        message = "Please update this app";
    } else if (catchException instanceof ARUnSupportedConfigurationException) {
        message = "The configuration is not supported by the device!";
    } else {
        message = "exception throw";
    }
}

En nuestro BodyActivity.java llamarás a la detección de superficie:

package com.vsm.myarapplication.body;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.huawei.hiar.ARBodyTrackingConfig;
import com.huawei.hiar.ARConfigBase;
import com.huawei.hiar.AREnginesApk;
import com.huawei.hiar.ARSession;
import com.huawei.hiar.exceptions.ARCameraNotAvailableException;
import com.huawei.hiar.exceptions.ARUnSupportedConfigurationException;
import com.huawei.hiar.exceptions.ARUnavailableClientSdkTooOldException;
import com.huawei.hiar.exceptions.ARUnavailableServiceApkTooOldException;
import com.huawei.hiar.exceptions.ARUnavailableServiceNotInstalledException;
import com.vsm.myarapplication.R;
import com.vsm.myarapplication.body.rendering.BodyRenderManager;
import com.vsm.myarapplication.common.ConnectAppMarketActivity;
import com.vsm.myarapplication.common.DisplayRotationManager;
public class BodyActivity extends AppCompatActivity {
    private static final String TAG = BodyActivity.class.getSimpleName();
private ARSession mArSession;
private GLSurfaceView mSurfaceView;
private BodyRenderManager mBodyRenderManager;
private DisplayRotationManager mDisplayRotationManager;
// Used for the display of recognition data.
    private TextView mTextView;
private String message = null;
private boolean isRemindInstall = false;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_body);
        mTextView = findViewById(R.id.bodyTextView);
        mSurfaceView = findViewById(R.id.bodySurfaceview);
        mDisplayRotationManager = new DisplayRotationManager(this);
// Keep the OpenGL ES running context.
        mSurfaceView.setPreserveEGLContextOnPause(true);
// Set the OpenGLES version.
        mSurfaceView.setEGLContextClientVersion(2);
// Set the EGL configuration chooser, including for the
        // number of bits of the color buffer and the number of depth bits.
        mSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
mBodyRenderManager = new BodyRenderManager(this);
        mBodyRenderManager.setDisplayRotationManage(mDisplayRotationManager);
        mBodyRenderManager.setTextView(mTextView);
mSurfaceView.setRenderer(mBodyRenderManager);
        mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }
@Override
    protected void onResume() {
        Log.d(TAG, "onResume");
        super.onResume();
        Exception exception = null;
        message = null;
        if (mArSession == null) {
            try {
                if (!arEngineAbilityCheck()) {
                    finish();
                    return;
                }
                mArSession = new ARSession(this);
                ARBodyTrackingConfig config = new ARBodyTrackingConfig(mArSession);
                config.setEnableItem(ARConfigBase.ENABLE_DEPTH | ARConfigBase.ENABLE_MASK);
                mArSession.configure(config);
                mBodyRenderManager.setArSession(mArSession);
            } catch (Exception capturedException) {
                exception = capturedException;
                setMessageWhenError(capturedException);
            }
            if (message != null) {
                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
                Log.e(TAG, "Creating session", exception);
                if (mArSession != null) {
                    mArSession.stop();
                    mArSession = null;
                }
                return;
            }
        }
        try {
            mArSession.resume();
        } catch (ARCameraNotAvailableException e) {
            Toast.makeText(this, "Camera open failed, please restart the app", Toast.LENGTH_LONG).show();
            mArSession = null;
            return;
        }
        mSurfaceView.onResume();
        mDisplayRotationManager.registerDisplayListener();
    }
/**
     * Check whether HUAWEI AR Engine server (com.huawei.arengine.service) is installed on the current device.
     * If not, redirect the user to HUAWEI AppGallery for installation.
     */
    private boolean arEngineAbilityCheck() {
        boolean isInstallArEngineApk = AREnginesApk.isAREngineApkReady(this);
        if (!isInstallArEngineApk && isRemindInstall) {
            Toast.makeText(this, "Please agree to install.", Toast.LENGTH_LONG).show();
            finish();
        }
        Log.d(TAG, "Is Install AR Engine Apk: " + isInstallArEngineApk);
        if (!isInstallArEngineApk) {
            startActivity(new Intent(this, ConnectAppMarketActivity.class));
            isRemindInstall = true;
        }
        return AREnginesApk.isAREngineApkReady(this);
    }
private void setMessageWhenError(Exception catchException) {
        if (catchException instanceof ARUnavailableServiceNotInstalledException) {
            startActivity(new Intent(this, ConnectAppMarketActivity.class));
        } else if (catchException instanceof ARUnavailableServiceApkTooOldException) {
            message = "Please update HuaweiARService.apk";
        } else if (catchException instanceof ARUnavailableClientSdkTooOldException) {
            message = "Please update this app";
        } else if (catchException instanceof ARUnSupportedConfigurationException) {
            message = "The configuration is not supported by the device!";
        } else {
            message = "exception throw";
        }
    }
@Override
    protected void onPause() {
        Log.i(TAG, "onPause start.");
        super.onPause();
        if (mArSession != null) {
            mDisplayRotationManager.unregisterDisplayListener();
            mSurfaceView.onPause();
            mArSession.pause();
        }
        Log.i(TAG, "onPause end.");
    }
@Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy start.");
        super.onDestroy();
        if (mArSession != null) {
            mArSession.stop();
            mArSession = null;
        }
        Log.i(TAG, "onDestroy end.");
    }
@Override
    public void onWindowFocusChanged(boolean isHasFocus) {
        Log.d(TAG, "onWindowFocusChanged");
        super.onWindowFocusChanged(isHasFocus);
        if (isHasFocus) {
            getWindow().getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
}




결론



Con HUAWEI AR Engine puedes identificar puntos del esqueleto del cuerpo y características del cuerpo humano de salida, como puntos finales de las extremidades, postura corporal y esqueleto.
Documentación
Codelab
Code Sample
Explora más artículos
Conviértete en Huawei Developer es gratis.

좋은 웹페이지 즐겨찾기