1. 首先需要一个OSG for android的环境

(1)NDK 现在Eclipse 对NDK已经相当友好了,已经不需要另外cygwin的参与,具体可以参考

Android NDK开发篇(一):新版NDK环境搭建(免Cygwin,超级快)

(2).OSG for android的编译,参考 osg for android学习之一:windows下编译(亲测通过)  建议编译OpenGL ES2版本.

 

2.然后加载OSG自带的Example:osgAndroidExampleGLES2

(1)点击菜单键加载文件路径,输入/sdcard/osg/cow.osg(必须先往sdcard创建文件夹osg并把cow.osg放到该文件夹里边)

(2)接着经典的牛出现了:)

3.自带的example太多的代码,这样的代码无论对于NDK的初学者或OSG很不直观,所以本人重写了一个HelloWolrd for 

osg的例子。例子很简单,就是简单加载一个四边形并附上颜色。

(1)java代码

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
package com.example.helloosg;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView.Renderer;

public class NDKRenderer implements Renderer{

NDKRenderer(){
    }
    
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        // TODO Auto-generated method stub
        gl.glEnable(GL10.GL_DEPTH_TEST);
    }

@Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        // TODO Auto-generated method stub
        osgNativeLib.init(width, height);
    }

@Override
    public void onDrawFrame(GL10 gl) {
        // TODO Auto-generated method stub
        osgNativeLib.step();
    }
}

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
package com.example.helloosg;
public class osgNativeLib {
    
    static {
        System.loadLibrary("osgNativeLib");
    }

/**
    * @param width the current view width
    * @param height the current view height
    */
    public static native void       init(int width, int height);
    public static native void       step();
}

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 
package com.example.helloosg;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

private GLSurfaceView mGLSurfaceView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGLSurfaceView = new GLSurfaceView(this);
        mGLSurfaceView.setEGLContextClientVersion(2);
        NDKRenderer renderer = new NDKRenderer();
        this.mGLSurfaceView.setRenderer(renderer);
        this.setContentView(mGLSurfaceView);
    }

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

@Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mGLSurfaceView.onResume();
    }

@Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mGLSurfaceView.onPause();
    }

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

(2)JNI代码

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
 
/ *  Created on: 2014-10-19
 *      Author: VCC
 */

#include "OsgMainApp.h"

OsgMainApp::OsgMainApp() {
}

void OsgMainApp::initOsgWindow(int x, int y, int width, int height) {
    __android_log_write(ANDROID_LOG_ERROR, "OSGANDROID", "Init geometry");

_viewer = new osgViewer::Viewer();
    _viewer->setUpViewerAsEmbeddedInWindow(x, y, width, height);
    _viewer->setThreadingModel(osgViewer::ViewerBase::SingleThreaded);

_root = new osg::Group();

_viewer->realize();
    _viewer->addEventHandler(new osgViewer::StatsHandler);
    _viewer->addEventHandler(
            new osgGA::StateSetManipulator(
                    _viewer->getCamera()->getOrCreateStateSet()));
    _viewer->addEventHandler(new osgViewer::ThreadingHandler);
    _viewer->addEventHandler(new osgViewer::LODScaleHandler);

_manipulator = new osgGA::KeySwitchMatrixManipulator;
    _manipulator->addMatrixManipulator('1', "Trackball",
            new osgGA::TrackballManipulator());
    _viewer->setCameraManipulator(_manipulator.get());

_viewer->getViewerStats()->collectStats("scene", true);

loadModels();
}

void OsgMainApp::draw() {
    _viewer->frame();
}

void OsgMainApp::loadModels() {
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(
            "/sdcard/osg/cow.osg");
    loadedModel->setName("cow");
    if (loadedModel != NULL) {
        __android_log_print(ANDROID_LOG_ERROR, "OSGANDROID", "Not NULL");
    }
    osg::Shader * vshader = new osg::Shader(osg::Shader::VERTEX, gVertexShader);
    osg::Shader * fshader = new osg::Shader(osg::Shader::FRAGMENT,
            gFragmentShader);

osg::Program * prog = new osg::Program;
    prog->addShader(vshader);
    prog->addShader(fshader);

osg::ref_ptr<osg::Node> node = createNode();
    //loadedModel->getOrCreateStateSet()->setAttribute(prog);
    node->getOrCreateStateSet()->setAttribute(prog);
    //_root->addChild(loadedModel);
    _root->addChild(node);
    osgViewer::Viewer::Windows windows;
    _viewer->getWindows(windows);
    for (osgViewer::Viewer::Windows::iterator itr = windows.begin();
            itr != windows.end(); ++itr) {
        (*itr)->getState()->setUseModelViewAndProjectionUniforms(true);
        (*itr)->getState()->setUseVertexAttributeAliasing(true);
    }

_viewer->setSceneData(NULL);
    _viewer->setSceneData(_root.get());
    _manipulator->getNode();
    _viewer->home();

_viewer->getDatabasePager()->clear();
    _viewer->getDatabasePager()->registerPagedLODs(_root.get());
    _viewer->getDatabasePager()->setUpThreads(3, 1);
    _viewer->getDatabasePager()->setTargetMaximumNumberOfPageLOD(2);
    _viewer->getDatabasePager()->setUnrefImageDataAfterApplyPolicy(true, true);
}

//创建一个四边形节点
osg::ref_ptr<osg::Node> OsgMainApp::createNode() {

//创建一个叶节点对象
    osg::ref_ptr<osg::Geode> geode = new osg::Geode();
    //创建一个几何体对象
    osg::ref_ptr<osg::Geometry> geom = new osg::Geometry();
    //添加顶点数据 注意顶点的添加顺序是逆时针
    osg::ref_ptr<osg::Vec3Array> v = new osg::Vec3Array();
    //添加数据
    v->push_back(osg::Vec3(0, 0, 0));
    v->push_back(osg::Vec3(1, 0, 0));
    v->push_back(osg::Vec3(1, 0, 1));
    v->push_back(osg::Vec3(0, 0, 1));

//设置顶点数据
    geom->setVertexArray(v.get());

//创建纹理订点数据
    osg::ref_ptr<osg::Vec2Array> vt = new osg::Vec2Array();
    //添加纹理坐标
    vt->push_back(osg::Vec2(0, 0));
    vt->push_back(osg::Vec2(1, 0));
    vt->push_back(osg::Vec2(1, 1));
    vt->push_back(osg::Vec2(0, 1));

//设置纹理坐标
    geom->setTexCoordArray(0, vt.get());

//创建颜色数组
    osg::ref_ptr<osg::Vec4Array> vc = new osg::Vec4Array();
    //添加数据
    vc->push_back(osg::Vec4(1, 0, 0, 1));
    vc->push_back(osg::Vec4(0, 1, 0, 1));
    vc->push_back(osg::Vec4(0, 0, 1, 1));
    vc->push_back(osg::Vec4(1, 1, 0, 1));

//设置颜色数组
    geom->setColorArray(vc.get());
    //设置颜色的绑定方式为单个顶点
    geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);

//创建法线数组
    osg::ref_ptr<osg::Vec3Array> nc = new osg::Vec3Array();
    //添加法线
    nc->push_back(osg::Vec3(0, -1, 0));
    //设置法线
    geom->setNormalArray(nc.get());
    //设置法绑定为全部顶点
    geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
    //添加图元
    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4));

//添加到叶子节点
    geode->addDrawable(geom.get());

return geode.get();
}

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
 
/*
 * OsgMainApp.h
 *
 *  Created on: 2014-10-19
 *      Author: VCC
 */

#ifndef OSGMAINAPP_H_
#define OSGMAINAPP_H_

//android log
#include <android/log.h>
#include <iostream>
#include <cstdlib>
#include <math.h>

#include <string>

//osg
#include <osg/GL>
#include <osg/GLExtensions>
#include <osg/Depth>
#include <osg/Program>
#include <osg/Shader>
#include <osg/Node>
#include <osg/Notify>
#include <osg/ShapeDrawable>

#include <osgText/Text>

//osgDB
#include <osgDB/DatabasePager>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>

//osg_viewer
#include <osgViewer/Viewer>
#include <osgViewer/Renderer>
#include <osgViewer/ViewerEventHandlers>
//osgGA

#include <osgGA/GUIEventAdapter>
#include <osgGA/MultiTouchTrackballManipulator>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>
#include <osgGA/SphericalManipulator>

//Static plugins Macro
USE_OSGPLUGIN(ive)
USE_OSGPLUGIN(osg)
USE_OSGPLUGIN(osg2)
USE_OSGPLUGIN(terrain)
USE_OSGPLUGIN(rgb)
USE_OSGPLUGIN(OpenFlight)
USE_OSGPLUGIN(dds)
//Static DOTOSG
USE_DOTOSGWRAPPER_LIBRARY(osg)
USE_DOTOSGWRAPPER_LIBRARY(osgFX)
USE_DOTOSGWRAPPER_LIBRARY(osgParticle)
USE_DOTOSGWRAPPER_LIBRARY(osgTerrain)
USE_DOTOSGWRAPPER_LIBRARY(osgText)
USE_DOTOSGWRAPPER_LIBRARY(osgViewer)
USE_DOTOSGWRAPPER_LIBRARY(osgVolume)
//Static serializer
USE_SERIALIZER_WRAPPER_LIBRARY(osg)
USE_SERIALIZER_WRAPPER_LIBRARY(osgAnimation)
USE_SERIALIZER_WRAPPER_LIBRARY(osgFX)
USE_SERIALIZER_WRAPPER_LIBRARY(osgManipulator)
USE_SERIALIZER_WRAPPER_LIBRARY(osgParticle)
USE_SERIALIZER_WRAPPER_LIBRARY(osgTerrain)
USE_SERIALIZER_WRAPPER_LIBRARY(osgText)
USE_SERIALIZER_WRAPPER_LIBRARY(osgVolume)

#define LOG_TAG "osgNativeLib"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)

static const char gVertexShader[] =
    "void main() {                                                          \n"
    "    gl_Position  = gl_ModelViewProjectionMatrix * gl_Vertex;          \n"
    "}                                                                      \n";
static const char gFragmentShader[] =
    "void main() {                             \n"
    "  gl_FragColor =vec4(0.4,0.4,0.8,1.0);    \n"
    "}                                                                      \n";

class OsgMainApp {
private:
    osg::ref_ptr<osgViewer::Viewer>                 _viewer;
    osg::ref_ptr<osg::Group>                        _root;
    osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> _manipulator;
public:
    OsgMainApp();
    void initOsgWindow(int x,int y,int width,int height);
    void draw();
private:
    osg::ref_ptr<osg::Node> createNode();
    void loadModels();

};

#endif /* OSGMAINAPP_H_ */

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
#include <jni.h>
#include <string.h>
#include <osg/Node>

#include <iostream>

#include "OsgMainApp.h"

OsgMainApp mainApp;

extern "C"{
    JNIEXPORT void JNICALL Java_com_example_helloosg_osgNativeLib_init(JNIEnv* env, jobject obj, jint width, jint height);
    JNIEXPORT void JNICALL Java_com_example_helloosg_osgNativeLib_step(JNIEnv* env, jobject obj);
}
JNIEXPORT void JNICALL Java_com_example_helloosg_osgNativeLib_init(JNIEnv* env, jobject obj, jint width, jint height)
{
    mainApp.initOsgWindow(0, 0, width, height);
}

JNIEXPORT void JNICALL Java_com_example_helloosg_osgNativeLib_step(JNIEnv* env, jobject obj){
    mainApp.draw();
}

(3).mk文件

android.mk

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
 
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := osgNativeLib
### Main Install dir
OSG_ANDROID_DIR := C:/Develop/osggles2
LIBDIR          := $(OSG_ANDROID_DIR)/obj/local/armeabi

ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)
    LOCAL_ARM_NEON  := true
    LIBDIR          := $(OSG_ANDROID_DIR)/obj/local/armeabi-v7a
endif

### Add all source file names to be included in lib separated by a whitespace

LOCAL_C_INCLUDES:= $(OSG_ANDROID_DIR)/include
LOCAL_CFLAGS    := -fno-short-enums
LOCAL_CPPFLAGS  := -DOSG_LIBRARY_STATIC

LOCAL_LDLIBS := -lGLESv2 -lz -llog

LOCAL_SRC_FILES := osgNativeLib.cpp OsgMainApp.cpp

LOCAL_LDFLAGS   := -L $(LIBDIR) \
-losgdb_dds \
-losgdb_openflight \
-losgdb_tga \
-losgdb_rgb \
-losgdb_osgterrain \
-losgdb_osg \
-losgdb_ive \
-losgdb_deprecated_osgviewer \
-losgdb_deprecated_osgvolume \
-losgdb_deprecated_osgtext \
-losgdb_deprecated_osgterrain \
-losgdb_deprecated_osgsim \
-losgdb_deprecated_osgshadow \
-losgdb_deprecated_osgparticle \
-losgdb_deprecated_osgfx \
-losgdb_deprecated_osganimation \
-losgdb_deprecated_osg \
-losgdb_serializers_osgvolume \
-losgdb_serializers_osgtext \
-losgdb_serializers_osgterrain \
-losgdb_serializers_osgsim \
-losgdb_serializers_osgshadow \
-losgdb_serializers_osgparticle \
-losgdb_serializers_osgmanipulator \
-losgdb_serializers_osgfx \
-losgdb_serializers_osganimation \
-losgdb_serializers_osg \
-losgViewer \
-losgVolume \
-losgTerrain \
-losgText \
-losgShadow \
-losgSim \
-losgParticle \
-losgManipulator \
-losgGA \
-losgFX \
-losgDB \
-losgAnimation \
-losgUtil \
-losg \
-lOpenThreads \
-lgnustl_static

include $(BUILD_SHARED_LIBRARY)

application.mk

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
 
#ANDROID APPLICATION MAKEFILE
APP_BUILD_SCRIPT := $(call my-dir)/Android.mk
#APP_PROJECT_PATH := $(call my-dir)

APP_OPTIM := release

APP_PLATFORM    := android-8
APP_STL         := gnustl_static
APP_CPPFLAGS    := -fexceptions -frtti
APP_ABI         := armeabi armeabi-v7a
APP_MODULES     := osgNativeLib

运行结果

注:由于代码是基于OpenGL ES2,简单加载了一个四边形,并在片元着色器将四边形的颜色赋为浅蓝色,其实也可以通过

OSG将四边形的颜色或者纹理赋到四边形上,具体下篇将说明

https://blog.csdn.net/hai7song/article/details/40515465

参考:

https://blog.csdn.net/edgarliaohs/article/details/37877287

http://www.openscenegraph.com/index.php/documentation/platform-specifics/android/43-building-openscenegraph-for-android-3-0-2

osg for android学习之一:windows下编译(亲测通过)【转】的更多相关文章

  1. Android ijkplayer在windows下编译并导入Android Studio

     我是看着里面的步骤来做的,由于我自己对Linux环境和命令不熟悉,导致我对Cygwin的知识为零,在编译ijkplayer的时候走了一点弯路,需要的同学先去看一下上面的这篇文章,我这边是对上面文章做 ...

  2. Android学习笔记—Windows下NDK开发简单示例

    该示例假设Android开发环境已经搭建完成,NDK也配置成功: 1.在Eclipse上新建Android工程,名称为ndkdemo.修改res\layout\activity_main.xml &l ...

  3. 【Android学习】Windows下Android环境搭建

    一.  JDK下载配置 直接百度,很简单. 二.android JDK下载配置 1.进入下载官网(需要FQ):https://developer.android.com/studio/index.ht ...

  4. Android学习笔记02-Mac下编译java代码

    在Mac OS上配置JDK 1.7. 一 下载 Mac版本的JDK1.7 从以下下载地址,下载Mac版本的JDk1.7 安装文件 jdk-7u79-macosx-x64.dmg. http://www ...

  5. Windows下编译objective-C

    Windows下编译objective-C 2011-08-31 14:32 630人阅读 评论(0) 收藏 举报 windowscocoa工具objective clibraryxcode   目录 ...

  6. 在Windows下编译FFmpeg详细说明

    MinGW:一个可自由使用和自由发布的Windows特定头文件和使用GNC工具集导入库的集合,允许你生成本地的Windows程序而不需要第三方C运行时 MinGW,即 Minimalist GNU F ...

  7. OpenGL学习之windows下安装opengl的glut库

    OpenGL学习之windows下安装opengl的glut库 GLUT不是OpenGL所必须的,但它会给我们的学习带来一定的方便,推荐安装.  Windows环境下的GLUT下载地址:(大小约为15 ...

  8. 在Windows下编译OpenSSL(VS2005和VC6)

    需要说明的是请一定安装openssl-0.9.8a .  openssl-1.0.0我没有编译成功. 如何在Windows下编译OpenSSL (Vs2005使用Vc8的cl编译器)1.安装Activ ...

  9. 一步步实现windows版ijkplayer系列文章之四——windows下编译ijkplyer版ffmpeg

    一步步实现windows版ijkplayer系列文章之一--Windows10平台编译ffmpeg 4.0.2,生成ffplay 一步步实现windows版ijkplayer系列文章之二--Ijkpl ...

随机推荐

  1. 8.5 正睿暑期集训营 Day2

    目录 2018.8.5 正睿暑期集训营 Day2 总结 A.占领地区(前缀和) B.配对(组合) C 导数卷积(NTT) 考试代码 T1 T2 T3 2018.8.5 正睿暑期集训营 Day2 时间: ...

  2. 2018年牛客网NOIP赛前训练营游记

    2018年牛客网NOIP赛前训练营游记 提高组(第一场) 中位数 #include<cstdio> #include<cctype> #include<climits&g ...

  3. sqlserver -- 查看当前数据库的数据表(备忘)

    @_@||... 记性不好,备忘... 语句功能:查看当前数据库的所有表(根据所需,进行语句改写即可) SELECT * FROM sysobjects WHERE (xtype = 'U') 备注: ...

  4. UVALive 6911 Double Swords 树状数组

    Double Swords 题目连接: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8 ...

  5. (转载)Spring 注解@Component,@Service,@Controller,@Repository

    Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository.@Service 和 @Controller.在目前的 Spring ...

  6. .NET 4.0中使用内存映射文件实现进程通讯

    操作系统很早就开始使用内存映射文件(Memory Mapped File)来作为进程间的共享存储区,这是一种非常高效的进程通讯手段.Win32 API中也包含有创建内存映射文件的函数,然而,这些函数都 ...

  7. Bitbox : a small open, DIY 32 bit VGA console

    Bitbox : a small open, DIY 32 bit VGA console Hi all, I've been developing a simple DIY console and ...

  8. Revit API射线法读取空间中相交的元素

    Revit API提供根据射线来寻找经过的元素.方法是固定模式,没什么好说.关键代码:doc.FindReferencesWithContextByDirection(ptStart, (ptEnd  ...

  9. 使用Axure RP原型设计实践08,制作圆角文本框

    本篇体验做一个简单圆角文本框,做到3个效果: 1.初始状态,圆角文本框有淡淡的背景色,边框的颜色为浅灰色2.点击圆角文本框,让其获取焦点,边框变成蓝色,背景色变成白色3.圆角文本框失去焦点,边框变成红 ...

  10. Java集合框架顶层接口collectiion接口

    如何使用迭代器 通常情况下,你会希望遍历一个集合中的元素.例如,显示集合中的每个元素. 一般遍历数组都是采用for循环或者增强for,这两个方法也可以用在集合框架,但是还有一种方法是采用迭代器遍历集合 ...