vuforia android 教程(3) 替换vofuria模型 替换成自己的模型

系列教程:

vuforia android 教程(1)
https://www.jianshu.com/p/37b158175b04
vuforia android 教程(2)
https://www.jianshu.com/p/2d70974857b8
vuforia android 教程(4)
https://www.jianshu.com/p/281a1e31a73c

在上一篇文章中,我们了解了如何替换识别图片

那么接下来,我们来替换 vuforia 模型

1. 准备工作

image.png
  • 执行以后会生成model.h
image.png

2. 替换方式

其实替换两种方式,一个是像demo一样直接把数据放进去,另一个是通过.h文件来加载出来

2.1直接放的方式,可以参考teapot

/*===============================================================================
Copyright (c) 2016 PTC Inc. All Rights Reserved.

Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.

Vuforia is a trademark of PTC Inc., registered in the United States and other 
countries.
===============================================================================*/

package com.vuforia.samples.SampleApplication.utils;

import java.nio.Buffer;


public class Teapot extends MeshObject
{
    
    private Buffer mVertBuff;
    private Buffer mTexCoordBuff;
    private Buffer mNormBuff;
    private Buffer mIndBuff;
    
    private int indicesNumber = 0;
    private int verticesNumber = 0;
    
    
    public Teapot()
    {
        setVerts();
        setTexCoords();
        setNorms();
        setIndices();
    }
    
    
    private void setVerts()
    {
        double[] TEAPOT_VERTS = { 11.222200, 0.110300, .......};
        mVertBuff = fillBuffer(TEAPOT_VERTS);
        verticesNumber = TEAPOT_VERTS.length / 3;
    }
    
    
    private void setTexCoords()
    {
        double[] TEAPOT_TEX_COORDS = { 0.608828, 0.354913,.... };
        mTexCoordBuff = fillBuffer(TEAPOT_TEX_COORDS);
        
    }
    
    
    private void setNorms()
    {
        double[] TEAPOT_NORMS = { -0.964496, 0.067011,.....};
        mNormBuff = fillBuffer(TEAPOT_NORMS);
    }
    
    
    private void setIndices()
    {
        short[] TEAPOT_INDICES = { 0, 1, 2, 2, 3.....};
        mIndBuff = fillBuffer(TEAPOT_INDICES);
        indicesNumber = TEAPOT_INDICES.length;
    }
    
    
    public int getNumObjectIndex()
    {
        return indicesNumber;
    }
    
    
    @Override
    public int getNumObjectVertex()
    {
        return verticesNumber;
    }
    
    
    @Override
    public Buffer getBuffer(BUFFER_TYPE bufferType)
    {
        Buffer result = null;
        switch (bufferType)
        {
            case BUFFER_TYPE_VERTEX:
                result = mVertBuff;
                break;
            case BUFFER_TYPE_TEXTURE_COORD:
                result = mTexCoordBuff;
                break;
            case BUFFER_TYPE_NORMALS:
                result = mNormBuff;
                break;
            case BUFFER_TYPE_INDICES:
                result = mIndBuff;
            default:
                break;
        
        }
        
        return result;
    }
    
}

2.2文件读取

  • 先把model.h文件中modelVerts , modelNormals , modelTexCoords,单独提取出来,放入三个.txt文件中
image.png
  • 每个文件的结构都是复制出来的数据
image.png
  • 然后放入assets文件里
image.png
  • 最后就是写文件读取,我这里写了一个,大家可以参考一下
package com.vuforia.samples.SampleApplication.utils;

import android.content.res.AssetManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.Buffer;

/**
 * Created by Admin on 2017/11/21.
 */

public class TestModel extends MeshObject {
    private  static final String TAG="modelTest";

    private Buffer mVertBuff;//顶点
    private Buffer mTexCoordBuff;//纹理坐标
    private Buffer mNormBuff;//normal
    private int verticesNumber = 0;
    private AssetManager assetManager;

    public TestModel(AssetManager inputassetManager){
        this.assetManager = inputassetManager;
        setVerts();
        setTexCoords();
        setNorms();
    }
    double[] model_VERTS;
    double[] model_TEX_COORDS;
    double[] model_NORMS;

    InputStream inputFile = null;

    private int loadVertsFromModel(String fileName) throws IOException {
        try{
            inputFile = assetManager.open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputFile));
            String line = reader.readLine();
            int floatsToRead = 99519;
            model_VERTS = new double[3*floatsToRead];
            for(int i=0;i<floatsToRead;i++){
                String curline = reader.readLine();
                if(curline.indexOf('/')>=0){
                    i--;
                    continue;
                }
//                将一行分成3个数据
                String floatStrs[] = curline.split(",");
                model_VERTS[3 * i] = Float.parseFloat(floatStrs[0]);
                model_VERTS[3 * i + 1] = Float.parseFloat(floatStrs[1]);
                model_VERTS[3 * i + 2] = Float.parseFloat(floatStrs[2]);

            }
            return floatsToRead;
        } finally {
            if(inputFile !=null){
                inputFile.close();
            }
        }
    }
    private int loadTexCoordsFromModel(String fileName)
            throws IOException
    {
        try
        {
            inputFile = assetManager.open(fileName);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputFile));

            String line = reader.readLine();

            int floatsToRead = 99519;
            model_TEX_COORDS = new double[2*floatsToRead];


            for (int i = 0; i < floatsToRead; i++)
            {

                String curline = reader.readLine();
                if( curline.indexOf('/') >= 0 ){
                    i--;
                    continue;
                }

                //将一行分成两个数据
                String floatStrs[] = curline.split(",");


                model_TEX_COORDS[2*i] = Float.parseFloat("".equals(floatStrs[0].replaceAll(" ","")) ? "0" : floatStrs[0]);
                model_TEX_COORDS[2*i+1] = Float.parseFloat("".equals(floatStrs[1].replaceAll(" ","")) ? "0" : floatStrs[1]);
            }
            return floatsToRead;
        } finally
        {
            if (inputFile != null)
                inputFile.close();
        }
    }

    private int loadNormsFromModel(String fileName)
            throws IOException
    {
        try
        {
            inputFile = assetManager.open(fileName);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputFile));

            String line = reader.readLine();
            int floatsToRead = 99519;
            model_NORMS = new double[3*floatsToRead];


            for (int i = 0; i < floatsToRead; i++)
            {

                String curline = reader.readLine();
                if( curline.indexOf('/') >= 0 ){
                    i--;
                    continue;
                }

                //将一行分成三个数据
                String floatStrs[] = curline.split(",");

                model_NORMS[3*i] = Float.parseFloat(floatStrs[0]);
                model_NORMS[3*i+1] = Float.parseFloat(floatStrs[1]);
                model_NORMS[3*i+2] = Float.parseFloat(floatStrs[2]);
            }

            return floatsToRead;

        } finally
        {
            if (inputFile != null)
                inputFile.close();
        }
    }

    private void setVerts(){
        int num = 0;
        try{
            num = loadVertsFromModel("ImageTargets/model/verts.txt");

        } catch(IOException e){
            e.printStackTrace();
        }
        mVertBuff = fillBuffer(model_VERTS);
        verticesNumber = num;
    }
    private void setTexCoords()
    {
        int num = 0;
        try {
            num = loadTexCoordsFromModel("ImageTargets/model/texcoords.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        mTexCoordBuff = fillBuffer(model_TEX_COORDS);

    }
    private void setNorms()
    {
        int num = 0;
        try {
            num = loadNormsFromModel("ImageTargets/model/norms.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        mNormBuff = fillBuffer(model_NORMS);
    }
    public int getNumObjectIndex()
    {
        return 0;
    }


    @Override
    public int getNumObjectVertex()
    {
        return verticesNumber;
    }
    @Override
    public Buffer getBuffer(BUFFER_TYPE bufferType)
    {
        Buffer result = null;
        switch (bufferType)
        {
            case BUFFER_TYPE_VERTEX:
                result = mVertBuff;
                break;
            case BUFFER_TYPE_TEXTURE_COORD:
                result = mTexCoordBuff;
                break;
            case BUFFER_TYPE_NORMALS:
                result = mNormBuff;
                break;
            default:
                break;

        }

        return result;
    }
}



注意 : int floatsToRead = 99519; 这个值是model.h里面的值

image.png

3. 开始替换

3.1 修改ImageTargetRenderer.java的文件

  • 首先新建一个TestModel 变量
    private TestModel testModel;

  • 然后在initRendering方法给testmodel初始化
    // Function for initializing the renderer.
    private void initRendering()
    {
        testModel = new TestModel(mActivity.getResources().getAssets());
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, Vuforia.requiresAlpha() ? 0.0f
                : 1.0f);

        for (Texture t : mTextures)
        {
            GLES20.glGenTextures(1, t.mTextureID, 0);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t.mTextureID[0]);
            GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
            GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
            GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA,
                t.mWidth, t.mHeight, 0, GLES20.GL_RGBA,
                GLES20.GL_UNSIGNED_BYTE, t.mData);
        }

        shaderProgramID = SampleUtils.createProgramFromShaderSrc(
            CubeShaders.CUBE_MESH_VERTEX_SHADER,
            CubeShaders.CUBE_MESH_FRAGMENT_SHADER);

        vertexHandle = GLES20.glGetAttribLocation(shaderProgramID,
            "vertexPosition");
        textureCoordHandle = GLES20.glGetAttribLocation(shaderProgramID,
            "vertexTexCoord");
        mvpMatrixHandle = GLES20.glGetUniformLocation(shaderProgramID,
            "modelViewProjectionMatrix");
        texSampler2DHandle = GLES20.glGetUniformLocation(shaderProgramID,
            "texSampler2D");

        if(!mModelIsLoaded) {
            mTeapot = new Teapot();

            try {
                mBuildingsModel = new SampleApplication3DModel();
                mBuildingsModel.loadModel(mActivity.getResources().getAssets(),
                        "ImageTargets/Buildings.txt");
                mModelIsLoaded = true;
            } catch (IOException e) {
                Log.e(LOGTAG, "Unable to load buildings");
            }

            // Hide the Loading Dialog
            mActivity.loadingDialogHandler
                    .sendEmptyMessage(LoadingDialogHandler.HIDE_LOADING_DIALOG);
        }

    }

  • 接着是在renderFrame方法加载进来
       // The render function called from SampleAppRendering by using RenderingPrimitives views.
    // The state is owned by SampleAppRenderer which is controlling it's lifecycle.
    // State should not be cached outside this method.
    public void renderFrame(State state, float[] projectionMatrix)
    {
        .....
        .....

            if (!mActivity.isExtendedTrackingActive()) {
                GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT,
                        false, 0, testModel.getVertices());
                        //false, 0, mTeapot.getVertices());
                GLES20.glVertexAttribPointer(textureCoordHandle, 2,
                        GLES20.GL_FLOAT, false, 0, testModel.getTexCoords());
                        //GLES20.GL_FLOAT, false, 0, mTeapot.getTexCoords());


                GLES20.glEnableVertexAttribArray(vertexHandle);
                GLES20.glEnableVertexAttribArray(textureCoordHandle);

                // activate texture 0, bind it, and pass to shader
                GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
                GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,
                        mTextures.get(textureIndex).mTextureID[0]);
                GLES20.glUniform1i(texSampler2DHandle, 0);

                // pass the model view matrix to the shader
                GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
                        modelViewProjection, 0);

                // finally draw the teapot
                GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0,
                        testModel.getNumObjectVertex());
                //GLES20.glDrawElements(GLES20.GL_TRIANGLES,
                        //mTeapot.getNumObjectIndex(), GLES20.GL_UNSIGNED_SHORT,
                        //mTeapot.getIndices());

                // disable the enabled arrays
                GLES20.glDisableVertexAttribArray(vertexHandle);
                GLES20.glDisableVertexAttribArray(textureCoordHandle);
            } else {
                GLES20.glDisable(GLES20.GL_CULL_FACE);
                GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT,
                        false, 0, testModel.getVertices());
                        //false, 0, mBuildingsModel.getVertices());
                GLES20.glVertexAttribPointer(textureCoordHandle, 2,
                        GLES20.GL_FLOAT, false, 0, testModel.getTexCoords());
                        //GLES20.GL_FLOAT, false, 0, mBuildingsModel.getTexCoords());

                GLES20.glEnableVertexAttribArray(vertexHandle);
                GLES20.glEnableVertexAttribArray(textureCoordHandle);

                GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
                GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,
                        mTextures.get(3).mTextureID[0]);
                GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
                        modelViewProjection, 0);
                GLES20.glUniform1i(texSampler2DHandle, 0);
                GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0,
                        testModel.getNumObjectVertex());
                        //mBuildingsModel.getNumObjectVertex());

                SampleUtils.checkGLError("Renderer DrawBuildings");
            }

            SampleUtils.checkGLError("Render Frame");

        }

        GLES20.glDisable(GLES20.GL_DEPTH_TEST);

    }

3.2替换贴图 , 修改ImageTargets.java的代码

  • 修改贴图loadTextures方法
    // We want to load specific textures from the APK, which we will later use
    // for rendering.

    private void loadTextures()
    {

        mTextures.add(Texture.loadTextureFromApk("testmodel.jpg",
                getAssets()));
//     mTextures.add(Texture.loadTextureFromApk("TextureTeapotBrass.png",
//        getAssets()));;
       /* mTextures.add(Texture.loadTextureFromApk("001.jpg",
                getAssets()));;*/


//        mTextures.add(Texture.loadTextureFromApk("TextureTeapotBrass.png",
//            getAssets()));;
//
//        mTextures.add(Texture.loadTextureFromApk("TextureTeapotBlue.png",
//            getAssets()));
//        mTextures.add(Texture.loadTextureFromApk("TextureTeapotRed.png",
//            getAssets()));
        mTextures.add(Texture.loadTextureFromApk("ImageTargets/Buildings.jpeg",
                getAssets()));

    }

大功告成

Screenshot_2017-12-27-20-26-33-939.jpeg

参考:

http://blog.csdn.net/zhimou/article/details/43865377

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,839评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,543评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,116评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,371评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,384评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,111评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,416评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,053评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,558评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,007评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,117评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,756评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,324评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,315评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,539评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,578评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,877评论 2 345