初次提交

This commit is contained in:
2022-09-19 18:05:01 +08:00
commit 57051fc44b
5401 changed files with 325410 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Sample16_6</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bn.Sample16_6"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MyActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>

View File

@@ -0,0 +1,13 @@
precision mediump float;
varying vec4 ambient;
varying vec4 diffuse;
varying vec4 specular;
varying vec4 aaColor; //接收从顶点着色器过来的参数
void main()
{
//给此片元从纹理中采样出颜色值
vec4 finalColor = vec4(0.0,1.0,0.0,0.0);
//给此片元颜色值
gl_FragColor = finalColor*ambient+finalColor*specular+finalColor*diffuse;
}

View File

@@ -0,0 +1,47 @@
uniform mat4 uMVPMatrix; //总变换矩阵
uniform mat4 uMMatrix; //变换矩阵
uniform vec3 uCamera; //摄像机位置
uniform vec3 uLightLocationRed; //红色光源位置
attribute vec3 aPosition; //顶点位置
attribute vec4 aColor; //顶点颜色
varying vec4 aaColor;//颜色,传给片段着色器
attribute vec3 aNormal; //法向量
varying vec4 ambient;
varying vec4 diffuse;
varying vec4 specular;
//定位光光照计算的方法
void pointLight( //定位光光照计算的方法
in vec3 normal, //法向量
inout vec4 ambient, //环境光最终强度
inout vec4 diffuse, //散射光最终强度
inout vec4 specular, //镜面光最终强度
in vec3 lightLocation, //光源位置
in vec4 lightAmbient, //环境光强度
in vec4 lightDiffuse, //散射光强度
in vec4 lightSpecular //镜面光强度
){
ambient=lightAmbient; //直接得出环境光的最终强度
vec3 normalTarget=aPosition+normal; //计算变换后的法向量
vec3 newNormal=(uMMatrix*vec4(normalTarget,1)).xyz-(uMMatrix*vec4(aPosition,1)).xyz;
newNormal=normalize(newNormal); //对法向量规格化
//计算从表面点到摄像机的向量
vec3 eye= normalize(uCamera-(uMMatrix*vec4(aPosition,1)).xyz);
//计算从表面点到光源位置的向量vp
vec3 vp= normalize(lightLocation-(uMMatrix*vec4(aPosition,1)).xyz);
vp=normalize(vp);//格式化vp
vec3 halfVector=normalize(vp+eye); //求视线与光线的半向量
float shininess=50.0; //粗糙度,越小越光滑
float nDotViewPosition=max(0.0,dot(newNormal,vp)); //求法向量与vp的点积与0的最大值
diffuse=lightDiffuse*nDotViewPosition; //计算散射光的最终强度
float nDotViewHalfVector=dot(newNormal,halfVector); //法线与半向量的点积
float powerFactor=max(0.0,pow(nDotViewHalfVector,shininess)); //镜面反射光强度因子
specular=lightSpecular*powerFactor; //计算镜面光的最终强度
}
void main()
{
gl_Position = uMVPMatrix * vec4(aPosition,1); //根据总变换矩阵计算此次绘制此顶点位置
pointLight(normalize(aNormal),ambient,diffuse,specular,uLightLocationRed,
vec4(0.1,0.1,0.1,1.0),vec4(0.5,0.5,0.5,1.0),vec4(0.6,0.6,0.6,1.0));
}

View File

@@ -0,0 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-8

View File

@@ -0,0 +1,23 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bn.Sample16_6;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, MainActivity!</string>
<string name="app_name">Sample16_6</string>
</resources>

View File

@@ -0,0 +1,12 @@
package com.bn.Sample16_6;
public class Constant {
public static final float springConstant=500; //弹性系数
public static final float springLength=0.2f; //弹簧的长度
public static final float frictionConstant=0.2f; //弹簧的摩擦系数
public static final float springR=0.03f; //半径
public static final float groundHeight=-1.3f; //地面的高度
public static boolean flag=true;
public static float deadTime = 10; //线程的截止时间
}

View File

@@ -0,0 +1,42 @@
package com.bn.Sample16_6;
/*
* 质点类
*
* 根据质点受到力的情况,计算质点当前的位置与速度
*
*/
public class Mass {
float m; //质点的质量
Vector3 pos; //质点的位置
Vector3 vel; //质点的速度
Vector3 force; //质点的受力
public Mass(float m){//构造器
this.m=m; //指定质量
pos = new Vector3();//初始化位置
vel = new Vector3();//初始化速度
}
public Mass(float m,Vector3 pos,Vector3 vel){//构造器
this.m=m; //指定质量
this.pos=pos; //指定位置
this.vel=vel; //指定速度
}
//调用该方法,对质点施加力(包括重力、空气阻力等)
public void applyForce(Vector3 force){ //施加力的方法
this.force=this.force.add(force);
}
//该方法初始化质点受到的力初始时受到的力为0
public void initForce(){
force = new Vector3(0,0,0);
}
//计算质点当前位置与速度的方法
public void calculateCurrPosAndVel(float dt){
Vector3 a = force.multiConstant(1/m); // 计算加速度 a = F/m
Vector3 deltaV = a.multiConstant(dt); //计算速度增量 deltaV = at
vel = vel.add(deltaV); // 计算速度v = v + at
pos = pos.add(vel.multiConstant(dt)); // 计算位置 pos = pos + vt
}
}

View File

@@ -0,0 +1,182 @@
package com.bn.Sample16_6;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import android.opengl.Matrix;
//存储系统矩阵状态的类
public class MatrixState
{
private static float[] mProjMatrix = new float[16];//4x4矩阵 投影用
private static float[] mVMatrix = new float[16];//摄像机位置朝向9参数矩阵
private static float[] currMatrix;//当前变换矩阵
public static float[] lightLocation=new float[]{0,0,0};//定位光光源位置
public static FloatBuffer cameraFB;
public static FloatBuffer lightPositionFB;
//保护变换矩阵的栈
static float[][] mStack=new float[10][16];
static int stackTop=-1;
public static void setInitStack()//获取不变换初始矩阵
{
currMatrix=new float[16];
Matrix.setRotateM(currMatrix, 0, 0, 1, 0, 0);
}
public static void pushMatrix()//保护变换矩阵
{
stackTop++;
for(int i=0;i<16;i++)
{
mStack[stackTop][i]=currMatrix[i];
}
}
public static void popMatrix()//恢复变换矩阵
{
for(int i=0;i<16;i++)
{
currMatrix[i]=mStack[stackTop][i];
}
stackTop--;
}
public static void translate(float x,float y,float z)//设置沿xyz轴移动
{
Matrix.translateM(currMatrix, 0, x, y, z);
}
public static void rotate(float angle,float x,float y,float z)//设置绕xyz轴移动
{
Matrix.rotateM(currMatrix,0,angle,x,y,z);
}
public static void scale(float x,float y,float z)
{
Matrix.scaleM(currMatrix,0, x, y, z);
}
//插入自带矩阵
public static void matrix(float[] self)
{
float[] result=new float[16];
Matrix.multiplyMM(result,0,currMatrix,0,self,0);
currMatrix=result;
}
//设置摄像机
static ByteBuffer llbb= ByteBuffer.allocateDirect(3*4);
static float[] cameraLocation=new float[3];//摄像机位置
public static void setCamera
(
float cx, //摄像机位置x
float cy, //摄像机位置y
float cz, //摄像机位置z
float tx, //摄像机目标点x
float ty, //摄像机目标点y
float tz, //摄像机目标点z
float upx, //摄像机UP向量X分量
float upy, //摄像机UP向量Y分量
float upz //摄像机UP向量Z分量
)
{
Matrix.setLookAtM
(
mVMatrix,
0,
cx,
cy,
cz,
tx,
ty,
tz,
upx,
upy,
upz
);
cameraLocation[0]=cx;
cameraLocation[1]=cy;
cameraLocation[2]=cz;
llbb.clear();
llbb.order(ByteOrder.nativeOrder());//设置字节顺序
cameraFB=llbb.asFloatBuffer();
cameraFB.put(cameraLocation);
cameraFB.position(0);
}
//设置透视投影参数
public static void setProjectFrustum
(
float left, //near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near, //near面距离
float far //far面距离
)
{
Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//设置正交投影参数
public static void setProjectOrtho
(
float left, //near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near, //near面距离
float far //far面距离
)
{
Matrix.orthoM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//获取具体物体的总变换矩阵
static float[] mMVPMatrix=new float[16];
public static float[] getFinalMatrix()
{
Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, currMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
return mMVPMatrix;
}
//获取具体物体的变换矩阵
public static float[] getMMatrix()
{
return currMatrix;
}
//获取投影矩阵
public static float[] getProjMatrix()
{
return mProjMatrix;
}
//获取摄像机朝向的矩阵
public static float[] getCaMatrix()
{
return mVMatrix;
}
//设置灯光位置的方法
static ByteBuffer llbbL = ByteBuffer.allocateDirect(3*4);
public static void setLightLocation(float x,float y,float z)
{
llbbL.clear();
lightLocation[0]=x;
lightLocation[1]=y;
lightLocation[2]=z;
llbbL.order(ByteOrder.nativeOrder());//设置字节顺序
lightPositionFB=llbbL.asFloatBuffer();
lightPositionFB.put(lightLocation);
lightPositionFB.position(0);
}
}

View File

@@ -0,0 +1,52 @@
package com.bn.Sample16_6;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
public class MyActivity extends Activity {
MySurfaceView surfaceView;
@Override
public void onCreate(Bundle savedInstanceState) {
//设置为全屏
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//设置为横屏模式
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
super.onCreate(savedInstanceState);
surfaceView = new MySurfaceView(this);
setContentView(surfaceView);
}
@Override
protected void onResume() {
super.onResume();
surfaceView.onResume();
Constant.flag=true;
}
@Override
protected void onPause() {
super.onPause();
surfaceView.onPause();
Constant.flag=false;
}
@Override
public boolean onKeyDown(int keyCode,KeyEvent e)
{
switch(keyCode)
{
case 4:
System.exit(0);
break;
}
return true;
}
}

View File

@@ -0,0 +1,100 @@
package com.bn.Sample16_6;
import android.opengl.GLSurfaceView;
import android.opengl.GLES20;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import static com.bn.Sample16_6.Constant.*;
class MySurfaceView extends GLSurfaceView
{
private SceneRenderer mRenderer;//场景渲染器
public MySurfaceView(Context context) {
super(context);
this.setEGLContextClientVersion(2); //设置使用OPENGL ES2.0
mRenderer = new SceneRenderer(); //创建场景渲染器
setRenderer(mRenderer); //设置渲染器
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);//设置渲染模式为主动渲染
}
private class SceneRenderer implements GLSurfaceView.Renderer
{
Rope rope;
Stick stick;
public void onDrawFrame(GL10 gl)
{
//清除深度缓冲与颜色缓冲
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
MatrixState.pushMatrix();
for(int i=0;i<rope.massCount-1;i++){
Mass mass1 = rope.massList.get(i);
Mass mass2 = rope.massList.get(i+1);
Vector3 stickVector = mass1.pos.add(mass2.pos.multiConstant(-1));
MatrixState.pushMatrix();
MatrixState.translate(mass2.pos.x, mass2.pos.y, mass2.pos.z);
Vector3.moveXToSomeVector(new double[]{stickVector.x,stickVector.y,stickVector.z});
stick.drawSelf(springLength/2,0);
MatrixState.popMatrix();
}
MatrixState.popMatrix();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
//设置视窗大小及位置
GLES20.glViewport(0, 0, width, height);
//计算GLSurfaceView的宽高比
float ratio=0;
ratio= (float) width / height;
//调用此方法计算产生透视投影矩阵
MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 1.5f, 10);
//调用此方法产生摄像机9参数位置矩阵
MatrixState.setCamera(0,0,2.2f,0f,0f,0f,0f,1.0f,0.0f);
//打开背面剪裁
GLES20.glEnable(GLES20.GL_CULL_FACE);
//设置灯光的初始位置
MatrixState.setLightLocation(0,2,2);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//设置屏幕背景色RGBA
GLES20.glClearColor(1f,1f,1f, 1.0f);
//打开深度检测
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
MatrixState.setInitStack();
rope = new Rope(
40, //massCount
0.1f, //m
new Vector3(0,-9.8f,0),//G
10.0f, //groundRepulsion地面弹性
0.2f, //friction 地面摩擦性
20f, //地面的缓冲系数
groundHeight, //地面的高度
0.2f,//空气阻力
new Vector3(-1,0,0),//绳头的速度
new Vector3(0,groundHeight,-1)//绳头的初始位置
);
stick = new Stick(MySurfaceView.this,springLength,springR,10);//创建棍
new Thread(){
float time=0;
float dt = 0.01f;
public void run(){
while(flag && time<deadTime){
time+=0.01f;
rope.operate(dt);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
}

View File

@@ -0,0 +1,115 @@
package com.bn.Sample16_6;
import static com.bn.Sample16_6.Constant.springLength;
import java.util.ArrayList;
import java.util.List;
/*
* 绳子类
*/
public class Rope extends RopeSimulation {
List<Spring> springList;//弹簧列表
Vector3 gravity;//重力
Vector3 connectionPos;//绳头结点的位置
Vector3 connectionVel;//绳头结点的速度
float groundRepulsionConstant;//地面的反弹系数
float groundFrictionConstant;//地面的摩擦系数
float groundAbsorptionConstant;//地面的缓冲系数
float groundHeight;//地面的高度
float airFrictionConstant;//空气的摩擦系数
public Rope(
int massCount, //质点的数量
float m, //质点的质量
Vector3 gravity, //重力
float groundRepulsionConstant, //地面反弹系数
float groundFrictionConstant, //地面摩擦系数
float groundAbsorptionConstant, //地面缓冲系数
float groundHeight, //地面高度
float airFrictionConstant, //空气阻力
Vector3 connectionVel, //绳头速度
Vector3 connectionPos) { //绳头位置
super(massCount, m); //调用父类的构造器创建massCount个质量为m的质点Mass的对象
this.gravity = gravity; //指定重力
this.groundRepulsionConstant = groundRepulsionConstant;//指定地面反弹系数
this.groundFrictionConstant = groundFrictionConstant;//指定地面摩擦系数
this.groundAbsorptionConstant = groundAbsorptionConstant;//指定地面缓冲系数
this.groundHeight = groundHeight; //指定地面高度
this.airFrictionConstant = airFrictionConstant;//指定空气阻力
this.connectionVel=connectionVel;//绳头速度
this.connectionPos=connectionPos;//绳头位置
for(int i=0;i<massCount;i++){ //初始化所有质点的位置
massList.get(i).pos.x = i*springLength; //指定x坐标
massList.get(i).pos.y = groundHeight; //指定y坐标
massList.get(i).pos.z = 0; //指定z坐标
}
springList = new ArrayList<Spring>(); //创建存放弹簧对象的列表
for(int i=0;i<massCount-1;i++){ //初始化质点之间的弹簧(弹簧的数量比质点的数量少一个)
Spring temp = new Spring(massList.get(i),massList.get(i+1));
springList.add(temp); //加入到弹簧对象的列表
}
}
//计算绳子当前运动轨迹的方法
public void solve() {
for(int i=0;i<massCount-1;i++){
springList.get(i).calculateSpringForce(); //该弹簧对其两端质点施加的力
}
for(int i=0;i<massCount;i++){ //物体受到的其他力
Mass mass = massList.get(i);
//施加万有引力
mass.applyForce(gravity.multiConstant(mass.m));
//施加空气阻力
mass.applyForce(mass.vel.multiConstant(-1).multiConstant(airFrictionConstant));
if(mass.pos.y<=groundHeight){
Vector3 v = mass.vel.copy();
v.y=0;
//摩擦力
mass.applyForce(v.multiConstant(-1).multiConstant(groundFrictionConstant));
v = mass.vel.copy();
v.x=0;
v.z=0;
if(v.y<0){
mass.applyForce(v.multiConstant(-1).multiConstant(groundAbsorptionConstant));
}
//计算地面的反作用力
Vector3 force = new Vector3(0,groundRepulsionConstant,0).multiConstant(groundHeight-mass.pos.y);
mass.applyForce(force);
}
}
}
@Override
public void simulateRope(float dt){ //模拟绳子运动的方法
super.simulateRope(dt); //调用父类的模拟方法
Mass head = massList.get(0); //获取绳头的质点
Vector3[] result = calCentripetalForceAndVel();//计算向心力和速度
head.applyForce(result[0]); //施加向心力
connectionVel = result[1]; //计算速度
connectionPos = connectionPos.add( //计算绳头质点的位置
connectionVel.multiConstant(dt));
if(connectionPos.y<groundHeight){ //保证绳头在地面的高度之上
connectionPos.y=groundHeight;
connectionVel.y=0;
}
head.pos=connectionPos; //设置绳头的位置
head.vel=connectionVel;//设置绳头的速度
}
public Vector3[] calCentripetalForceAndVel(){
Mass head = massList.get(0); //获取绳头质点
Vector3 center = new Vector3(0,head.pos.y,-2);//绕y轴旋转
Vector3 forceDir = center.add(head.pos.multiConstant(-1)).normal();
Vector3 force = forceDir.multiConstant(head.m); //向心力 F=m*v*v/r 此处令v=1,r=1;
Vector3 velDir = Vector3.yRotate(
Math.toRadians(90), new double[]{forceDir.x,forceDir.y,forceDir.z,1});
Vector3 vel = velDir.multiConstant(10);//速度大小为10
if(head.pos.y<1.5f){
vel.y=1;//垂直速度为1
}
return new Vector3[]{force,vel};//返回向心力和速度
}
}

View File

@@ -0,0 +1,53 @@
package com.bn.Sample16_6;
import java.util.ArrayList;
import java.util.List;
/*
* 由所有质点组成的一个模拟绳子运动的抽象绳子类
*/
public abstract class RopeSimulation {
List<Mass> massList; //存放所有质点对象的列表
int massCount; //质点数量
public RopeSimulation(int massCount,float m){ //参数为质点的数量与每个质点的质量
this.massCount=massCount; //质点数量赋值
massList = new ArrayList<Mass>(); //创建存放所有质点对象的列表
for(int i=0;i<massCount;i++){
Mass mass = new Mass(m); //创建massCount个相同的质量为m的质点
massList.add(mass); //加入到质点的列表中
}
}
//获取质点对象列表中某个质点的对象
public Mass getMass(int index){
if(index<0||index>=massCount){
return null;
}
return massList.get(index);
}
//初始化质点列表中每一个质点对象受到的力的情况初始化时每个质点受力为0
public void init(){
for(int i=0;i<massList.size();i++){
massList.get(i).initForce(); //初始化质点的受力情况
}
}
//计算绳子当前运动轨迹的抽象方法
public abstract void solve();
//更新质点列表中,每一个质点当前位置与当前速度的方法,使得所有的质点均模拟绳子运动
public void simulateRope(float dt){
for(int i=0;i<massList.size();i++){
massList.get(i).calculateCurrPosAndVel(dt); //更新该质点的速度和质量
}
}
//不断更新组成绳子的每个质点位置与速度,从而使得绳子运动起来
public void operate(float dt){
init();
solve();
simulateRope(dt);
}
}

View File

@@ -0,0 +1,121 @@
package com.bn.Sample16_6;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import android.content.res.Resources;
import android.opengl.GLES20;
import android.util.Log;
//加载顶点Shader与片元Shader的工具类
public class ShaderUtil
{
//加载制定shader的方法
public static int loadShader
(
int shaderType, //shader的类型 GLES20.GL_VERTEX_SHADER GLES20.GL_FRAGMENT_SHADER
String source //shader的脚本字符串
)
{
//创建一个新shader
int shader = GLES20.glCreateShader(shaderType);
//若创建成功则加载shader
if (shader != 0)
{
//加载shader的源代码
GLES20.glShaderSource(shader, source);
//编译shader
GLES20.glCompileShader(shader);
//存放编译成功shader数量的数组
int[] compiled = new int[1];
//获取Shader的编译情况
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0)
{//若编译失败则显示错误日志并删除此shader
Log.e("ES20_ERROR", "Could not compile shader " + shaderType + ":");
Log.e("ES20_ERROR", GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
//创建shader程序的方法
public static int createProgram(String vertexSource, String fragmentSource)
{
//加载顶点着色器
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0)
{
return 0;
}
//加载片元着色器
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0)
{
return 0;
}
//创建程序
int program = GLES20.glCreateProgram();
//若程序创建成功则向程序中加入顶点着色器与片元着色器
if (program != 0)
{
//向程序中加入顶点着色器
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
//向程序中加入片元着色器
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
//链接程序
GLES20.glLinkProgram(program);
//存放链接成功program数量的数组
int[] linkStatus = new int[1];
//获取program的链接情况
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
//若链接失败则报错并删除程序
if (linkStatus[0] != GLES20.GL_TRUE)
{
Log.e("ES20_ERROR", "Could not link program: ");
Log.e("ES20_ERROR", GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
}
return program;
}
//检查每一步操作是否有错误的方法
public static void checkGlError(String op)
{
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR)
{
Log.e("ES20_ERROR", op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
//从sh脚本中加载shader内容的方法
public static String loadFromAssetsFile(String fname,Resources r)
{
String result=null;
try
{
InputStream in=r.getAssets().open(fname);
int ch=0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((ch=in.read())!=-1)
{
baos.write(ch);
}
byte[] buff=baos.toByteArray();
baos.close();
in.close();
result=new String(buff,"UTF-8");
result=result.replaceAll("\\r\\n","\n");
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
}

View File

@@ -0,0 +1,38 @@
package com.bn.Sample16_6;
/*
* 弹簧类
*/
public class Spring {
Mass mass1;//质点1
Mass mass2;//质点2
float springConstant;//弹性系数
float springLength;//弹簧长度
float frictionConstant;//摩擦系数
public Spring(Mass mass1, Mass mass2) {//构造器
this.mass1 = mass1; //指定第一个质点
this.mass2 = mass2; //指定第二个质点
this.springConstant = Constant.springConstant;//指定弹性系数
this.springLength = Constant.springLength;//指定弹簧长度
this.frictionConstant = Constant.frictionConstant;//指定弹簧摩擦系数
}
public void calculateSpringForce(){ //计算各个物体受力的方法
Vector3 springVector = mass1.pos.add(mass2.pos.multiConstant(-1));//弹簧的伸长方向
float distance = springVector.length();//两个质点间的距离
Vector3 force;//作用力
if(distance!=0){
float deltaX = distance-this.springLength;//弹簧偏离平衡位置的距离
Vector3 normalV =springVector.multiConstant(1/distance).multiConstant(-1);//将弹簧的方向向量规格化;
force = normalV.multiConstant(deltaX).multiConstant(springConstant);//弹簧的拉力 = k*deltaX*dir
force = force.add(mass1.vel.add(mass2.vel.multiConstant(-1)).multiConstant(-frictionConstant));//计算合力
mass1.applyForce(force);//对第一个质点施加力
mass2.applyForce(force.multiConstant(-1));//对第二个质点施加力
}
}
}

View File

@@ -0,0 +1,243 @@
package com.bn.Sample16_6;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import android.opengl.GLES20;
/*
* 木棒类
*/
public class Stick {
int mProgram;//自定义渲染管线着色器程序id
int muMVPMatrixHandle;//总变换矩阵引用id
int muMMatrixHandle;//位置、旋转变换矩阵
int maCameraHandle; //摄像机位置属性引用id
int maPositionHandle; //顶点位置属性引用id
int maNormalHandle; //顶点法向量属性引用id
int maColorHandle; //颜色属性引用id
int maRedLightLocationHandle;//光源位置属性引用id
int maGreenBlueLightLocationHandle;//光源位置属性引用id
String mVertexShader;//顶点着色器代码脚本
String mFragmentShader;//片元着色器代码脚本
static float[] mMMatrix = new float[16];//具体物体的移动旋转矩阵
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mNormalBuffer;//顶点纹理坐标数据缓冲
int vCount=0;
float yAngle=0;//绕y轴旋转的角度
float xAngle=0;//绕x轴旋转的角度
float zAngle=0;//绕z轴旋转的角度
float length=10f;//圆柱长度
float circle_radius=2f;//圆截环半径
float degreespan=18f; //圆截环每一份的度数大小
public Stick(MySurfaceView mv,float length,float circle_radius,float degreespan)
{
//初始化顶点坐标数据的initVertexData方法
initVertexData( length, circle_radius, degreespan);
//调用初始化着色器的initShader方法
initShader(mv);
}
//初始化顶点坐标数据的initVertexData方法
public void initVertexData(float length,float circle_radius,float degreespan)
{
//顶点坐标数据的初始化================begin============================
ArrayList<Float> val=new ArrayList<Float>();//顶点存放列表
ArrayList<Float> ial=new ArrayList<Float>();//法向量存放列表
this.length = length;
this.circle_radius = circle_radius;
this.degreespan = degreespan;
for(float circle_degree=360.0f;circle_degree>0.0f;circle_degree-=degreespan)//循环行
{
float x1 =(float)(-length/2);
float y1=(float) (circle_radius*Math.sin(Math.toRadians(circle_degree)));
float z1=(float) (circle_radius*Math.cos(Math.toRadians(circle_degree)));
float a1=0;
float b1=y1;
float c1=z1;
float l1=getVectorLength(a1, b1, c1);//模长
a1=a1/l1;//法向量规格化
b1=b1/l1;
c1=c1/l1;
float x2 =(float)(-length/2);
float y2=(float) (circle_radius*Math.sin(Math.toRadians(circle_degree-degreespan)));
float z2=(float) (circle_radius*Math.cos(Math.toRadians(circle_degree-degreespan)));
float a2=0;
float b2=y2;
float c2=z2;
float l2=getVectorLength(a2, b2, c2);//模长
a2=a2/l2;//法向量规格化
b2=b2/l2;
c2=c2/l2;
float x3 =(float)(length/2);
float y3=(float) (circle_radius*Math.sin(Math.toRadians(circle_degree-degreespan)));
float z3=(float) (circle_radius*Math.cos(Math.toRadians(circle_degree-degreespan)));
float a3=0;
float b3=y3;
float c3=z3;
float l3=getVectorLength(a3, b3, c3);//模长
a3=a3/l3;//法向量规格化
b3=b3/l3;
c3=c3/l3;
float x4 =(float)(length/2);
float y4=(float) (circle_radius*Math.sin(Math.toRadians(circle_degree)));
float z4=(float) (circle_radius*Math.cos(Math.toRadians(circle_degree)));
float a4=0;
float b4=y4;
float c4=z4;
float l4=getVectorLength(a4, b4, c4);//模长
a4=a4/l4;//法向量规格化
b4=b4/l4;
c4=c4/l4;
val.add(x1);val.add(y1);val.add(z1);//两个三角形共6个顶点的坐标
val.add(x2);val.add(y2);val.add(z2);
val.add(x4);val.add(y4);val.add(z4);
val.add(x2);val.add(y2);val.add(z2);
val.add(x3);val.add(y3);val.add(z3);
val.add(x4);val.add(y4);val.add(z4);
ial.add(a1);ial.add(b1);ial.add(c1);//顶点对应的法向量
ial.add(a2);ial.add(b2);ial.add(c2);
ial.add(a4);ial.add(b4);ial.add(c4);
ial.add(a2);ial.add(b2);ial.add(c2);
ial.add(a3);ial.add(b3);ial.add(c3);
ial.add(a4);ial.add(b4);ial.add(c4);
}
vCount=val.size()/3;//顶点的数量为坐标值数量的1/3因为一个顶点有3个坐标
//将alVertix中的坐标值转存到一个float数组中
float vertices[]=new float[vCount*3];
for(int i=0;i<val.size();i++)
{
System.out.println("val.get(i)="+val.get(i));
vertices[i]=val.get(i);
}
//创建顶点坐标数据缓冲
//vertices.length*4是因为一个整数四个字节
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为int型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
//将alVertix中的坐标值转存到一个float数组中
float normals[]=new float[ial.size()];
for(int i=0;i<ial.size();i++)
{
normals[i]=ial.get(i);
}
//创建顶点坐标数据缓冲
//vertices.length*4是因为一个整数四个字节
ByteBuffer nbb = ByteBuffer.allocateDirect(normals.length*4);
nbb.order(ByteOrder.nativeOrder());//设置字节顺序
mNormalBuffer = nbb.asFloatBuffer();//转换为int型缓冲
mNormalBuffer.put(normals);//向缓冲区中放入顶点坐标数据
mNormalBuffer.position(0);//设置缓冲区起始位置
}
//初始化着色器
public void initShader(MySurfaceView mv)
{
//加载顶点着色器的脚本内容
mVertexShader=ShaderUtil.loadFromAssetsFile("vertex_stick.sh", mv.getResources());
ShaderUtil.checkGlError("==ss==");
//加载片元着色器的脚本内容
mFragmentShader=ShaderUtil.loadFromAssetsFile("frag_stick.sh", mv.getResources());
//基于顶点着色器与片元着色器创建程序
ShaderUtil.checkGlError("==ss==");
mProgram = ShaderUtil.createProgram(mVertexShader, mFragmentShader);
//获取程序中顶点位置属性引用id
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点经纬度属性引用id
maColorHandle=GLES20.glGetAttribLocation(mProgram, "aColor");
//获取程序中顶点法向量属性引用id
maNormalHandle= GLES20.glGetAttribLocation(mProgram, "aNormal");
//获取程序中总变换矩阵引用id
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
//获取程序中摄像机位置引用id
maCameraHandle=GLES20.glGetUniformLocation(mProgram, "uCamera");
//获取程序中光源位置引用id
maRedLightLocationHandle=GLES20.glGetUniformLocation(mProgram, "uLightLocationRed");
//获取位置、旋转变换矩阵引用id
muMMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMMatrix");
}
public void drawSelf(float xOffset,float yOffset)
{
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//设置沿Z轴正向位移1
MatrixState.translate(xOffset,yOffset,0f);
//设置绕y轴旋转
MatrixState.rotate(yAngle,0,1,0);
//设置绕x轴旋转
MatrixState.rotate(xAngle,1,0,0);
//设置绕z轴旋转
MatrixState.rotate(zAngle,0,0,1);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//将位置、旋转变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMMatrixHandle, 1, false, MatrixState.getMMatrix(), 0);
//将摄像机位置传入shader程序
GLES20.glUniform3fv(maCameraHandle, 1, MatrixState.cameraFB);
//将光源位置传入shader程序
GLES20.glUniform3fv(maRedLightLocationHandle, 1, MatrixState.lightPositionFB);
//为画笔指定顶点位置数据
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//为画笔指定顶点法向量数据
GLES20.glVertexAttribPointer
(
maNormalHandle,
4,
GLES20.GL_FLOAT,
false,
3*4,
mNormalBuffer
);
//允许顶点位置数据数组
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maNormalHandle);
//绘制三角形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount);
}
//法向量规格化,求模长度
public float getVectorLength(float x,float y,float z)
{
float pingfang=x*x+y*y+z*z;
float length=(float) Math.sqrt(pingfang);
return length;
}
}

View File

@@ -0,0 +1,144 @@
package com.bn.Sample16_6;
public class Vector3 {
float x;
float y;
float z;
public Vector3(){};
public Vector3(float x, float y, float z) {
super();
this.x = x;
this.y = y;
this.z = z;
}
//向量的相加
public Vector3 add(Vector3 temp) {
Vector3 result = new Vector3();
result.x=this.x+temp.x;
result.y=this.y+temp.y;
result.z=this.z+temp.z;
return result;
}
//向量相乘
public Vector3 multiConstant(float constant) {
Vector3 result = new Vector3();
result.x = this.x*constant;
result.y = this.y*constant;
result.z = this.z*constant;
return result;
}
public void init(){
this.x=0;
this.y=0;
this.z=0;
}
public float length() {
return (float) Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);
}
@Override
public String toString(){
return "Vector:("+this.x+","+this.y+","+this.z+")";
}
public Vector3 copy(){
return new Vector3(this.x,this.y,this.z);
}
//计算叉积--v1叉乘v2
public static double[] getCJ(double[] v1,double[] v2){
double[] result = new double[3];
result[0]=v1[1]*v2[2]-v1[2]*v2[1];
result[1]=v1[2]*v2[0]-v1[0]*v2[2];
result[2]=v1[0]*v2[1]-v1[1]*v2[0];
return result;
}
public static int compare(double x,double y){
if(Math.abs(x-y)<0.000001){
return 0;
}else if(x-y>0.000001){
return 1;
}else{
return -1;
}
}
//计算两个向量的夹角--结果为度
public static double getAngleBetweenTwoVector(double[] vector1,double[] vector2){
double angle=0;
double DJ = vector1[0]*vector2[0]+vector1[1]*vector2[1]+vector1[2]*vector2[2];//计算点积
double mode = getMode(vector1)*getMode(vector2);//求向量模的积
double cosa = DJ/mode;
if(compare(cosa,1)==0){
return 0;
}
angle = Math.toDegrees(Math.acos(cosa));
return angle;
}
//求向量的模
public static double getMode(double[] vector){
return Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]+vector[2]*vector[2]);
}
//变换坐标系--是x轴变换到指定向量的位置
public static void moveXToSomeVector(double[] vector){
double x[]={1,0,0};
double angle = getAngleBetweenTwoVector(x,vector);//vector与x轴的夹角
//通过x与vector的叉积计算出旋转轴的向量
double pivot[] = getCJ(x,vector);
MatrixState.rotate((float)angle, (float)pivot[0], (float)pivot[1],(float)pivot[2]);
}
public static Vector3 yRotate(double angle,double[] gVector)
{
double[][] matrix=//绕y轴旋转变换矩阵
{
{Math.cos(angle),0,-Math.sin(angle),0},
{0,1,0,0},
{Math.sin(angle),0,Math.cos(angle),0},
{0,0,0,1}
};
double[] tempDot={gVector[0],gVector[1],gVector[2],gVector[3]};
for(int j=0;j<4;j++)
{
gVector[j]=(tempDot[0]*matrix[0][j]+tempDot[1]*matrix[1][j]+
tempDot[2]*matrix[2][j]+tempDot[3]*matrix[3][j]);
}
return new Vector3((float)gVector[0],(float)gVector[1],(float)gVector[2]);
}
//angle为弧度 gVector 为重力向量[x,y,z,1]
//返回值为旋转后的向量
public static Vector3 zRotate(double angle,double[] gVector)
{
double[][] matrix=//绕z轴旋转变换矩阵
{
{Math.cos(angle),Math.sin(angle),0,0},
{-Math.sin(angle),Math.cos(angle),0,0},
{0,0,1,0},
{0,0,0,1}
};
double[] tempDot={gVector[0],gVector[1],gVector[2],gVector[3]};
for(int j=0;j<4;j++)
{
gVector[j]=(tempDot[0]*matrix[0][j]+tempDot[1]*matrix[1][j]+
tempDot[2]*matrix[2][j]+tempDot[3]*matrix[3][j]);
}
return new Vector3((float)gVector[0],(float)gVector[1],(float)gVector[2]);
}
public Vector3 normal(){
float module = (float) Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);
return new Vector3(this.x/module,this.y/module,this.z/module);
}
}