updated the Android version

This commit is contained in:
Zeno Rogue 2018-06-07 18:28:32 +02:00
parent d40680358c
commit c7109fe521
9 changed files with 304 additions and 218 deletions

View File

@ -3,7 +3,7 @@
# your build.
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11 -O3")
# Specifies a library name, specifies whether the library is STATIC or
# SHARED, and provides relative paths to the source code. You can
@ -20,13 +20,14 @@ add_library( # Specifies the name of the library.
# Provides a relative path to your source file(s).
src/main/jni/hyper.cpp )
# GLESv2
find_path(GLES2_INCLUDE_DIR GLES2/gl2.h
HINTS ${ANDROID_NDK})
find_library(GLES2_LIBRARY libGLESv1_CM.so
HINTS ${GLES2_INCLUDE_DIR}/../lib)
target_include_directories(hyper PUBLIC ${GLES2_INCLUDE_DIR})
find_path(GLES1_INCLUDE_DIR GLES/gl.h HINTS ${ANDROID_NDK})
find_library(GLES1_LIBRARY libGLESv1_CM.so HINTS ${GLES1_INCLUDE_DIR}/../lib)
target_include_directories(hyper PUBLIC ${GLES1_INCLUDE_DIR})
# GLESv3
find_path(GLES3_INCLUDE_DIR GLES3/gl3.h HINTS ${ANDROID_NDK})
find_library(GLES3_LIBRARY libGLESv3.so HINTS ${GLES3_INCLUDE_DIR}/../lib)
target_include_directories(hyper PUBLIC ${GLES3_INCLUDE_DIR})
find_library( # Sets the name of the path variable.
log-lib
@ -45,6 +46,6 @@ target_link_libraries( # Specifies the target library.
# Links the target library to the log library
# included in the NDK.
${log-lib}
# ${GLES2_LIBRARY}
GLESv1_CM
GLESv3
# ${GLES1_LIBRARY}
)

View File

@ -28,7 +28,7 @@ android {
ndk {
moduleName "hyper"
ldLibs "GLESv1_CM -llog"
ldLibs "GLESv3 -llog"
stl "stlport_static"
// abiFilters 'armeabi', 'x86_64'
abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'mips', 'mips64'

View File

@ -18,7 +18,7 @@
package com.android.texample;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLES20;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
@ -36,7 +36,7 @@ public class GLText {
allchars = new StringBuffer();
for(char c=32; c<=126; c++)
allchars.append(c);
allchars.append("°´ÁÄÇÈÉÍÎÖÚÜßàáâãäçèéêìíîïòóôõöøùúüýąćČčĎďĘęĚěğİıŁłńňŘřŚśŞşŠšťůŹźŻżŽžδϕЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёᵈ");
allchars.append("°²´½ÁÄÇÈÉÍÎÖÚÜßàáâãäçèéêìíîïòóôõöøùúüýąćČčĎďĘęĚěğİıŁłńňŘřŚśŞşŠšŤťůŹźŻżŽžδϕЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёᵈ");
}
int numChars() {
@ -60,7 +60,7 @@ public class GLText {
public final static int CHAR_BATCH_SIZE = 100; // Number of Characters to Render Per Batch
//--Members--//
GL10 gl; // GL10 Instance
public Shader shader; // GL10 Instance
AssetManager assets; // Asset Manager
SpriteBatch batch; // Batch Renderer
@ -88,12 +88,12 @@ public class GLText {
//--Constructor--//
// D: save GL instance + asset manager, create arrays, and initialize the members
// A: gl - OpenGL ES 10 Instance
public GLText(GL10 gl) {
this.gl = gl; // Save the GL10 Instance
public GLText(Shader sh) {
this.shader = sh; // Save the GL10 Instance
buildAllchars();
batch = new SpriteBatch( gl, CHAR_BATCH_SIZE ); // Create Sprite Batch (with Defined Size)
batch = new SpriteBatch( sh, CHAR_BATCH_SIZE ); // Create Sprite Batch (with Defined Size)
charWidths = new float[numChars()]; // Create the Array of Character Widths
charRgn = new TextureRegion[numChars()]; // Create the Array of Character Regions
@ -195,7 +195,7 @@ public class GLText {
textureSize = 2048; // Set 2048 Texture Size
// create an empty bitmap (alpha only)
Bitmap bitmap = Bitmap.createBitmap( textureSize, textureSize, Bitmap.Config.ALPHA_8 ); // Create Bitmap
Bitmap bitmap = Bitmap.createBitmap( textureSize, textureSize, Bitmap.Config.ARGB_8888 ); // Create Bitmap
Canvas canvas = new Canvas( bitmap ); // Create Canvas for Rendering to Bitmap
bitmap.eraseColor( 0x00000000 ); // Set Transparent Background (ARGB)
@ -221,19 +221,19 @@ public class GLText {
// generate a new texture
int[] textureIds = new int[1]; // Array to Get Texture Id
gl.glGenTextures( 1, textureIds, 0 ); // Generate New Texture
GLES20.glGenTextures( 1, textureIds, 0 ); // Generate New Texture
textureId = textureIds[0]; // Save Texture Id
// setup filters for texture
gl.glBindTexture( GL10.GL_TEXTURE_2D, textureId ); // Bind Texture
gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST ); // Set Minification Filter
gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR ); // Set Magnification Filter
gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE ); // Set U Wrapping
gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE ); // Set V Wrapping
GLES20.glBindTexture( GLES20.GL_TEXTURE_2D, textureId ); // Bind Texture
GLES20.glTexParameterf( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST ); // Set Minification Filter
GLES20.glTexParameterf( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR ); // Set Magnification Filter
GLES20.glTexParameterf( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE ); // Set U Wrapping
GLES20.glTexParameterf( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE ); // Set V Wrapping
// load the generated bitmap onto the texture
GLUtils.texImage2D( GL10.GL_TEXTURE_2D, 0, bitmap, 0 ); // Load Bitmap to Texture
gl.glBindTexture( GL10.GL_TEXTURE_2D, 0 ); // Unbind Texture
GLUtils.texImage2D( GLES20.GL_TEXTURE_2D, 0, bitmap, 0 ); // Load Bitmap to Texture
GLES20.glBindTexture( GLES20.GL_TEXTURE_2D, 0 ); // Unbind Texture
// release the bitmap
bitmap.recycle(); // Release the Bitmap
@ -270,13 +270,12 @@ public class GLText {
begin( 1.0f, 1.0f, 1.0f, alpha ); // Begin with White (Explicit Alpha)
}
public void begin(float red, float green, float blue, float alpha) {
gl.glColor4f( red, green, blue, alpha ); // Set Color+Alpha
gl.glBindTexture( GL10.GL_TEXTURE_2D, textureId ); // Bind the Texture
shader.setColor( red, green, blue, alpha ); // Set Color+Alpha
GLES20.glBindTexture( GLES20.GL_TEXTURE_2D, textureId ); // Bind the Texture
batch.beginBatch(); // Begin Batch
}
public void end() {
batch.endBatch(); // End Batch
gl.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); // Restore Default Color/Alpha
}
//--Draw Text--//

View File

@ -5,17 +5,17 @@ package com.android.texample;
// import android.util.FloatMath;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLES20;
public class SpriteBatch {
//--Constants--//
final static int VERTEX_SIZE = 4; // Vertex Size (in Components) ie. (X,Y,U,V)
final static int VERTEX_SIZE = 6; // Vertex Size (in Components) ie. (X,Y,U,V)
final static int VERTICES_PER_SPRITE = 4; // Vertices Per Sprite
final static int INDICES_PER_SPRITE = 6; // Indices Per Sprite
//--Members--//
GL10 gl; // GL Instance
Shader shader; // GL Instance
Vertices vertices; // Vertices Instance Used for Rendering
float[] vertexBuffer; // Vertex Buffer
int bufferIndex; // Vertex Buffer Start Index
@ -26,10 +26,10 @@ public class SpriteBatch {
// D: prepare the sprite batcher for specified maximum number of sprites
// A: gl - the gl instance to use for rendering
// maxSprites - the maximum allowed sprites per batch
public SpriteBatch(GL10 gl, int maxSprites) {
this.gl = gl; // Save GL Instance
public SpriteBatch(Shader sh, int maxSprites) {
this.shader = sh; // Save GL Instance
this.vertexBuffer = new float[maxSprites * VERTICES_PER_SPRITE * VERTEX_SIZE]; // Create Vertex Buffer
this.vertices = new Vertices( gl, maxSprites * VERTICES_PER_SPRITE, maxSprites * INDICES_PER_SPRITE, false, true, false ); // Create Rendering Vertices
this.vertices = new Vertices( sh, maxSprites * VERTICES_PER_SPRITE, maxSprites * INDICES_PER_SPRITE); // Create Rendering Vertices
this.bufferIndex = 0; // Reset Buffer Index
this.maxSprites = maxSprites; // Save Maximum Sprites
this.numSprites = 0; // Clear Sprite Counter
@ -54,7 +54,7 @@ public class SpriteBatch {
// A: textureId - the ID of the texture to use for the batch
// R: [none]
public void beginBatch(int textureId) {
gl.glBindTexture( GL10.GL_TEXTURE_2D, textureId ); // Bind the Texture
GLES20.glBindTexture( GLES20.GL_TEXTURE_2D, textureId ); // Bind the Texture
numSprites = 0; // Empty Sprite Counter
bufferIndex = 0; // Reset Buffer Index (Empty)
}
@ -70,9 +70,8 @@ public class SpriteBatch {
public void endBatch() {
if ( numSprites > 0 ) { // IF Any Sprites to Render
vertices.setVertices( vertexBuffer, 0, bufferIndex ); // Set Vertices from Buffer
vertices.bind(); // Bind Vertices
vertices.draw( GL10.GL_TRIANGLES, 0, numSprites * INDICES_PER_SPRITE ); // Render Batched Sprites
vertices.unbind(); // Unbind Vertices
vertices.prepare(); // Bind Vertices
vertices.draw( GLES20.GL_TRIANGLES, 0, numSprites * INDICES_PER_SPRITE ); // Render Batched Sprites
}
}
@ -102,21 +101,29 @@ public class SpriteBatch {
vertexBuffer[bufferIndex++] = x1; // Add X for Vertex 0
vertexBuffer[bufferIndex++] = y1; // Add Y for Vertex 0
vertexBuffer[bufferIndex++] = 0; // Add X for Vertex 0
vertexBuffer[bufferIndex++] = 1; // Add Y for Vertex 0
vertexBuffer[bufferIndex++] = region.u1; // Add U for Vertex 0
vertexBuffer[bufferIndex++] = region.v2; // Add V for Vertex 0
vertexBuffer[bufferIndex++] = x2; // Add X for Vertex 1
vertexBuffer[bufferIndex++] = y1; // Add Y for Vertex 1
vertexBuffer[bufferIndex++] = 0; // Add X for Vertex 0
vertexBuffer[bufferIndex++] = 1; // Add Y for Vertex 0
vertexBuffer[bufferIndex++] = region.u2; // Add U for Vertex 1
vertexBuffer[bufferIndex++] = region.v2; // Add V for Vertex 1
vertexBuffer[bufferIndex++] = x2; // Add X for Vertex 2
vertexBuffer[bufferIndex++] = y2; // Add Y for Vertex 2
vertexBuffer[bufferIndex++] = 0; // Add X for Vertex 0
vertexBuffer[bufferIndex++] = 1; // Add Y for Vertex 0
vertexBuffer[bufferIndex++] = region.u2; // Add U for Vertex 2
vertexBuffer[bufferIndex++] = region.v1; // Add V for Vertex 2
vertexBuffer[bufferIndex++] = x1; // Add X for Vertex 3
vertexBuffer[bufferIndex++] = y2; // Add Y for Vertex 3
vertexBuffer[bufferIndex++] = 0; // Add X for Vertex 0
vertexBuffer[bufferIndex++] = 1; // Add Y for Vertex 0
vertexBuffer[bufferIndex++] = region.u1; // Add U for Vertex 3
vertexBuffer[bufferIndex++] = region.v1; // Add V for Vertex 3

View File

@ -8,25 +8,17 @@ import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLES20;
public class Vertices {
//--Constants--//
final static int POSITION_CNT_2D = 2; // Number of Components in Vertex Position for 2D
final static int POSITION_CNT_3D = 3; // Number of Components in Vertex Position for 3D
final static int COLOR_CNT = 4; // Number of Components in Vertex Color
final static int TEXCOORD_CNT = 2; // Number of Components in Vertex Texture Coords
final static int NORMAL_CNT = 3; // Number of Components in Vertex Normal
final static int INDEX_SIZE = Short.SIZE / 8; // Index Byte Size (Short.SIZE = bits)
//--Members--//
// NOTE: all members are constant, and initialized in constructor!
final GL10 gl; // GL Instance
final boolean hasColor; // Use Color in Vertices
final boolean hasTexCoords; // Use Texture Coords in Vertices
final boolean hasNormals; // Use Normals in Vertices
final Shader sh; // GL Instance
public final int positionCnt; // Number of Position Components (2=2D, 3=3D)
public final int vertexStride; // Vertex Stride (Element Size of a Single Vertex)
public final int vertexSize; // Bytesize of a Single Vertex
@ -46,16 +38,10 @@ public class Vertices {
// hasNormals - use normals in vertices
// use3D - (false, default) use 2d positions (ie. x/y only)
// (true) use 3d positions (ie. x/y/z)
public Vertices(GL10 gl, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords, boolean hasNormals) {
this( gl, maxVertices, maxIndices, hasColor, hasTexCoords, hasNormals, false ); // Call Overloaded Constructor
}
public Vertices(GL10 gl, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords, boolean hasNormals, boolean use3D) {
this.gl = gl; // Save GL Instance
this.hasColor = hasColor; // Save Color Flag
this.hasTexCoords = hasTexCoords; // Save Texture Coords Flag
this.hasNormals = hasNormals; // Save Normals Flag
this.positionCnt = use3D ? POSITION_CNT_3D : POSITION_CNT_2D; // Set Position Component Count
this.vertexStride = this.positionCnt + ( hasColor ? COLOR_CNT : 0 ) + ( hasTexCoords ? TEXCOORD_CNT : 0 ) + ( hasNormals ? NORMAL_CNT : 0 ); // Calculate Vertex Stride
public Vertices(Shader sh, int maxVertices, int maxIndices) {
this.sh = sh; // Save GL Instance
this.positionCnt = 4; // Set Position Component Count
this.vertexStride = 6; // Calculate Vertex Stride
this.vertexSize = this.vertexStride * 4; // Calculate Vertex Byte Size
ByteBuffer buffer = ByteBuffer.allocateDirect( maxVertices * vertexSize ); // Allocate Buffer for Vertices (Max)
@ -113,30 +99,16 @@ public class Vertices {
// USAGE: call once before calling draw() multiple times for this buffer.
// A: [none]
// R: [none]
public void bind() {
gl.glEnableClientState( GL10.GL_VERTEX_ARRAY ); // Enable Position in Vertices
public void prepare() {
vertices.position( 0 ); // Set Vertex Buffer to Position
gl.glVertexPointer( positionCnt, GL10.GL_FLOAT, vertexSize, vertices ); // Set Vertex Pointer
// GLES20.glVertexPointer( positionCnt, GLES20.GL_FLOAT, vertexSize, vertices ); // Set Vertex Pointer
GLES20.glVertexAttribPointer(sh.aPosition, 4, GLES20.GL_FLOAT, false, vertexSize, vertices);
if ( hasColor ) { // IF Vertices Have Color
gl.glEnableClientState( GL10.GL_COLOR_ARRAY ); // Enable Color in Vertices
vertices.position( positionCnt ); // Set Vertex Buffer to Color
gl.glColorPointer( COLOR_CNT, GL10.GL_FLOAT, vertexSize, vertices ); // Set Color Pointer
vertices.position( positionCnt ); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified)
// GLES20.glTexCoordPointer( TEXCOORD_CNT, GLES20.GL_FLOAT, vertexSize, vertices ); // Set Texture Coords Pointer
GLES20.glVertexAttribPointer(sh.aTexture, 2, GLES20.GL_FLOAT, false, vertexSize, vertices);
}
if ( hasTexCoords ) { // IF Vertices Have Texture Coords
gl.glEnableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); // Enable Texture Coords in Vertices
vertices.position( positionCnt + ( hasColor ? COLOR_CNT : 0 ) ); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified)
gl.glTexCoordPointer( TEXCOORD_CNT, GL10.GL_FLOAT, vertexSize, vertices ); // Set Texture Coords Pointer
}
if ( hasNormals ) {
gl.glEnableClientState( GL10.GL_NORMAL_ARRAY ); // Enable Normals in Vertices
vertices.position( positionCnt + ( hasColor ? COLOR_CNT : 0 ) + ( hasTexCoords ? TEXCOORD_CNT : 0 ) ); // Set Vertex Buffer to Normals (NOTE: position based on whether color/texcoords is also specified)
gl.glNormalPointer( GL10.GL_FLOAT, vertexSize, vertices ); // Set Normals Pointer
}
}
//--Draw--//
// D: draw the currently bound vertices in the vertex/index buffers
// USAGE: can only be called after calling bind() for this buffer.
@ -147,118 +119,11 @@ public class Vertices {
public void draw(int primitiveType, int offset, int numVertices) {
if ( indices != null ) { // IF Indices Exist
indices.position( offset ); // Set Index Buffer to Specified Offset
gl.glDrawElements( primitiveType, numVertices, GL10.GL_UNSIGNED_SHORT, indices ); // Draw Indexed
GLES20.glDrawElements( primitiveType, numVertices, GLES20.GL_UNSIGNED_SHORT, indices ); // Draw Indexed
}
else { // ELSE No Indices Exist
gl.glDrawArrays( primitiveType, offset, numVertices ); // Draw Direct (Array)
GLES20.glDrawArrays( primitiveType, offset, numVertices ); // Draw Direct (Array)
}
}
//--Unbind--//
// D: clear binding states when done rendering batches.
// USAGE: call once before calling draw() multiple times for this buffer.
// A: [none]
// R: [none]
public void unbind() {
gl.glDisableClientState( GL10.GL_VERTEX_ARRAY ); // Clear Vertex Array State
if ( hasColor ) // IF Vertices Have Color
gl.glDisableClientState( GL10.GL_COLOR_ARRAY ); // Clear Color State
if ( hasTexCoords ) // IF Vertices Have Texture Coords
gl.glDisableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); // Clear Texture Coords State
if ( hasNormals ) // IF Vertices Have Normals
gl.glDisableClientState( GL10.GL_NORMAL_ARRAY ); // Clear Normals State
}
//--Draw Full--//
// D: draw the vertices in the vertex/index buffers
// NOTE: unoptimized version! use bind()/draw()/unbind() for batches
// A: primitiveType - the type of primitive to draw
// offset - the offset in the vertex/index buffer to start at
// numVertices - the number of vertices (indices) to draw
// R: [none]
public void drawFull(int primitiveType, int offset, int numVertices) {
gl.glEnableClientState( GL10.GL_VERTEX_ARRAY ); // Enable Position in Vertices
vertices.position( 0 ); // Set Vertex Buffer to Position
gl.glVertexPointer( positionCnt, GL10.GL_FLOAT, vertexSize, vertices ); // Set Vertex Pointer
if ( hasColor ) { // IF Vertices Have Color
gl.glEnableClientState( GL10.GL_COLOR_ARRAY ); // Enable Color in Vertices
vertices.position( positionCnt ); // Set Vertex Buffer to Color
gl.glColorPointer( COLOR_CNT, GL10.GL_FLOAT, vertexSize, vertices ); // Set Color Pointer
}
if ( hasTexCoords ) { // IF Vertices Have Texture Coords
gl.glEnableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); // Enable Texture Coords in Vertices
vertices.position( positionCnt + ( hasColor ? COLOR_CNT : 0 ) ); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified)
gl.glTexCoordPointer( TEXCOORD_CNT, GL10.GL_FLOAT, vertexSize, vertices ); // Set Texture Coords Pointer
}
if ( indices != null ) { // IF Indices Exist
indices.position( offset ); // Set Index Buffer to Specified Offset
gl.glDrawElements( primitiveType, numVertices, GL10.GL_UNSIGNED_SHORT, indices ); // Draw Indexed
}
else { // ELSE No Indices Exist
gl.glDrawArrays( primitiveType, offset, numVertices ); // Draw Direct (Array)
}
if ( hasTexCoords ) // IF Vertices Have Texture Coords
gl.glDisableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); // Clear Texture Coords State
if ( hasColor ) // IF Vertices Have Color
gl.glDisableClientState( GL10.GL_COLOR_ARRAY ); // Clear Color State
gl.glDisableClientState( GL10.GL_VERTEX_ARRAY ); // Clear Vertex Array State
}
//--Set Vertex Elements--//
// D: use these methods to alter the values (position, color, textcoords, normals) for vertices
// WARNING: these do NOT validate any values, ensure that the index AND specified
// elements EXIST before using!!
// A: x, y, z - the x,y,z position to set in buffer
// r, g, b, a - the r,g,b,a color to set in buffer
// u, v - the u,v texture coords to set in buffer
// nx, ny, nz - the x,y,z normal to set in buffer
// R: [none]
void setVtxPosition(int vtxIdx, float x, float y) {
int index = vtxIdx * vertexStride; // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( x ) ); // Set X
vertices.put( index + 1, Float.floatToRawIntBits( y ) ); // Set Y
}
void setVtxPosition(int vtxIdx, float x, float y, float z) {
int index = vtxIdx * vertexStride; // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( x ) ); // Set X
vertices.put( index + 1, Float.floatToRawIntBits( y ) ); // Set Y
vertices.put( index + 2, Float.floatToRawIntBits( z ) ); // Set Z
}
void setVtxColor(int vtxIdx, float r, float g, float b, float a) {
int index = ( vtxIdx * vertexStride ) + positionCnt; // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( r ) ); // Set Red
vertices.put( index + 1, Float.floatToRawIntBits( g ) ); // Set Green
vertices.put( index + 2, Float.floatToRawIntBits( b ) ); // Set Blue
vertices.put( index + 3, Float.floatToRawIntBits( a ) ); // Set Alpha
}
void setVtxColor(int vtxIdx, float r, float g, float b) {
int index = ( vtxIdx * vertexStride ) + positionCnt; // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( r ) ); // Set Red
vertices.put( index + 1, Float.floatToRawIntBits( g ) ); // Set Green
vertices.put( index + 2, Float.floatToRawIntBits( b ) ); // Set Blue
}
void setVtxColor(int vtxIdx, float a) {
int index = ( vtxIdx * vertexStride ) + positionCnt; // Calculate Actual Index
vertices.put( index + 3, Float.floatToRawIntBits( a ) ); // Set Alpha
}
void setVtxTexCoords(int vtxIdx, float u, float v) {
int index = ( vtxIdx * vertexStride ) + positionCnt + ( hasColor ? COLOR_CNT : 0 ); // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( u ) ); // Set U
vertices.put( index + 1, Float.floatToRawIntBits( v ) ); // Set V
}
void setVtxNormal(int vtxIdx, float x, float y, float z) {
int index = ( vtxIdx * vertexStride ) + positionCnt + ( hasColor ? COLOR_CNT : 0 ) + ( hasTexCoords ? TEXCOORD_CNT : 0 ); // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( x ) ); // Set X
vertices.put( index + 1, Float.floatToRawIntBits( y ) ); // Set Y
vertices.put( index + 2, Float.floatToRawIntBits( z ) ); // Set Z
}
}

View File

@ -12,7 +12,9 @@ import android.os.Build;
import android.os.PowerManager;
// bimport android.widget.Toast;
import android.opengl.GLES20;
import com.android.texample.GLText;
import com.android.texample.Shader;
public class HyperRenderer implements GLSurfaceView.Renderer {
@ -25,8 +27,9 @@ public class HyperRenderer implements GLSurfaceView.Renderer {
int [] graphdata;
int gdpos;
int gdpop() { return graphdata[gdpos++]; }
boolean initialized;
public void onDrawFrame(GL10 gl) {
public void onDrawFrame(GL10 unused) {
if(game.forceCanvas) return;
PowerManager pm = (PowerManager) game.getSystemService(Context.POWER_SERVICE);
@ -34,11 +37,15 @@ public class HyperRenderer implements GLSurfaceView.Renderer {
if(!isScreenOn) return;
if(!game.activityVisible) return;
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
GLES20.glClear(GL10.GL_COLOR_BUFFER_BIT);
synchronized(game) {
game.hv.updateGame();
game.draw();
graphdata = game.loadMap();
if(!initialized) { game.glhrinit(); initialized = true; }
game.hv.updateGame();
game.draw();
graphdata = game.loadMap();
glText.shader.aPosition = game.getaPosition();
glText.shader.aTexture = game.getaTexture();
glText.shader.uColor = game.getuColor();
}
if(graphdata == null) return;
@ -80,7 +87,7 @@ public class HyperRenderer implements GLSurfaceView.Renderer {
}
String s = ss.toString();
y = height - y;
glText.setScale(size / 48.0f);
@ -104,25 +111,23 @@ public class HyperRenderer implements GLSurfaceView.Renderer {
break;
}}
// disable texture + alpha
gl.glDisable( GL10.GL_BLEND ); // Disable Alpha Blend
gl.glDisable( GL10.GL_TEXTURE_2D ); // Disable Texture Mapping
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
public void onSurfaceChanged(GL10 unused, int width, int height) {
GLES20.glViewport(0, 0, width, height);
// Save width and height
this.width = width; // Save Current Width
this.height = height; // Save Current Height
this.width = width; // Save Current Width
this.height = height; // Save Current Height
initialized = false;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
glText = new GLText( gl );
glText = new GLText( new Shader() );
glText.load(Typeface.DEFAULT_BOLD, 48, 2, 2 ); // Create Font (Height: 48 Pixels / X+Y Padding 2 Pixels)
initialized = false;
}

View File

@ -24,6 +24,10 @@ import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.SensorEvent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.opengl.GLSurfaceView;
@ -44,7 +48,7 @@ import android.widget.FrameLayout.LayoutParams;
import android.widget.Toast;
import android.util.Log;
public class HyperRogue extends Activity {
public class HyperRogue extends Activity implements SensorEventListener {
private static final int RESULT_SETTINGS = 1;
private static final boolean isGold = false;
@ -179,6 +183,8 @@ public class HyperRogue extends Activity {
applyUserSettings();
UiChangeListener();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
public native int initGame();
@ -199,6 +205,10 @@ public class HyperRogue extends Activity {
public native boolean getGoogleConnection();
public native void setGoogleSignin(boolean issigned, boolean isconnecting);
public native void handleKey(int keyCode);
public native void glhrinit();
public native int getaPosition();
public native int getaTexture();
public native int getuColor();
static {
System.loadLibrary("hyper");
@ -323,6 +333,8 @@ public class HyperRogue extends Activity {
if(usegl && glview == null) {
glview = new GLSurfaceView(this);
glview.setEGLContextClientVersion(2);
HyperRenderer hr =new HyperRenderer();
hr.game = this;
glview.setEGLConfigChooser(new HRConfigChooser());
@ -365,6 +377,10 @@ public class HyperRogue extends Activity {
}
if (backgroundmusic != null) backgroundmusic.stop();
if(listening) {
mSensorManager.unregisterListener(this);
listening = false;
}
}
// remove for the lite version START
@ -395,8 +411,8 @@ public class HyperRogue extends Activity {
}
protected void onResume() {
activityVisible = true;
super.onResume();
activityVisible = true;
if(backgroundmusic != null) {
try {backgroundmusic.prepare(); } catch(Exception e) {}
backgroundmusic.start();
@ -553,6 +569,18 @@ public class HyperRogue extends Activity {
if(curland == 64) id = R.raw.mirror; // Bull Dash
if(curland == 65) id = R.raw.mirror; // Crossroads V
if(curland == 66) id = R.raw.laboratory; // CA land
if(curland >= 67 && curland <= 71) id = R.raw.mirror; // Reflection and old Mirror Land
if(curland == 72) id = R.raw.hell; // Volcanic Wasteland
if(curland == 73) id = R.raw.icyland; // Blizzard
if(curland == 74) id = R.raw.graveyard; // Hunting Ground
if(curland == 75 || curland == 76) id = R.raw.graveyard; // Terracotta (+Mercury River)
if(curland == 77) id = R.raw.desert; // Crystal World
if(curland == 78) id = R.raw.desert; // Snake Nest
if(curland == 79) id = R.raw.caves; // Docks
if(curland == 80) id = R.raw.graveyard; // Ruined City
if(curland == 81) id = R.raw.caves; // Magnetosphere
if(curland == 82) id = R.raw.laboratory; // Jelly Kingdom
if(id > 0) backgroundmusic = MediaPlayer.create(this, id);
if(backgroundmusic != null) {
@ -589,6 +617,67 @@ public class HyperRogue extends Activity {
return bounds.width();
}
private SensorManager mSensorManager;
private Sensor mSensor;
// private final float[] mAccelerometerReading = new float[3];
// private final float[] mMagnetometerReading = new float[3];
private final float[] mRotationMatrix = {1,0,0, 0,1,0, 0,0,1};
boolean listening;
Sensor mRotation; // mAccelerometer, mMagneticField;
final int[] msgn = {1, 1, -1};
final int[] msgnl = {1, -1, 1};
final int[] lsc = {1, 0, 2};
double getOrientation(int i, int j) {
if(!listening) {
final HyperRogue act = this;
runOnUiThread(new Runnable() { public void run() {
listening = true;
/*act.mAccelerometer = act.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
act.mMagneticField = act.mSensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR);
act.mSensorManager.registerListener(act, act.mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL, SensorManager.SENSOR_DELAY_UI);
act.mSensorManager.registerListener(act, act.mMagneticField,
SensorManager.SENSOR_DELAY_NORMAL, SensorManager.SENSOR_DELAY_UI);*/
act.mRotation = act.mSensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR);
act.mSensorManager.registerListener(act, act.mRotation,
SensorManager.SENSOR_DELAY_NORMAL, SensorManager.SENSOR_DELAY_UI);
}});
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
if((rotation & 1) == 1)
return mRotationMatrix[lsc[j]+3*lsc[i]]*msgnl[i]*msgnl[j];
return mRotationMatrix[j+3*i]*msgn[i]*msgn[j];
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
// You must implement this callback in your code.
}
public void onSensorChanged(SensorEvent event) {
/*if (event.sensor == mAccelerometer) {
System.arraycopy(event.values, 0, mAccelerometerReading,
0, mAccelerometerReading.length);
mSensorManager.getRotationMatrix(mRotationMatrix, null,
mAccelerometerReading, mMagnetometerReading);
} else if (event.sensor == mMagneticField) {
System.arraycopy(event.values, 0, mMagnetometerReading,
0, mMagnetometerReading.length);
mSensorManager.getRotationMatrix(mRotationMatrix, null,
mAccelerometerReading, mMagnetometerReading);
}*/
if(event.sensor.getType() == Sensor.TYPE_GAME_ROTATION_VECTOR)
mSensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
}
}
class HRConfigChooser implements EGLConfigChooser {

View File

@ -168,10 +168,13 @@ public class HyperView extends View {
}}
}
long clockzero = 0;
public void updateGame() {
lasttick = curtick;
curtick = (int)SystemClock.elapsedRealtime();
if(clockzero == 0) clockzero = SystemClock.elapsedRealtime();
curtick = (int) (SystemClock.elapsedRealtime() - clockzero);
if(clickcnt > 0) clickcnt--;
game.update(width, height, curtick, mousex, mousey, clicked | ((clickcnt & 1) > 0));
@ -182,15 +185,18 @@ public class HyperView extends View {
@Override
public void onDraw(final Canvas canvas) {
super.onDraw(canvas);
PowerManager pm = (PowerManager) game.getSystemService(Context.POWER_SERVICE);
PowerManager pm = (PowerManager) game.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH ? pm.isInteractive() : pm.isScreenOn();
if(!isScreenOn) return;
if(!game.activityVisible) return;
dc = canvas;
dc = canvas;
width = getWidth();
height = getHeight();

View File

@ -1,5 +1,5 @@
// HyperRogue for Android
// Copyright (C) 2012-2017 Zeno Rogue
// Hyperbolic Rogue for Android
// Copyright (C) 2012-2018 Zeno Rogue
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
@ -17,10 +17,37 @@
#define ISANDROID 1
#define GL_ES
#define CAP_ACHIEVE 1
#define CAP_SHADER 1
#define CAP_VERTEXBUFFER 0
#define HNEW 1
#define MOBPAR_FORMAL JNIEnv *env, jobject thiz
#define MOBPAR_ACTUAL env, thiz
#include <android/log.h>
#include <stdio.h>
char android_log_buf[1000000];
int android_log_bufpos = 0;
#define XPRINTF
#pragma clang diagnostic ignored "-Wformat-security"
template<class...T>
// __attribute__((__format__ (__printf__, 1, 2)))
void Xprintf(const char *fmt, T... t) {
snprintf(android_log_buf+android_log_bufpos, 1000000-android_log_bufpos, fmt, t...);
int last_cr = 0;
int i;
for(i=0; android_log_buf[i]; i++) if(android_log_buf[i] == 10) {
android_log_buf[i] = 0;
__android_log_print(ANDROID_LOG_VERBOSE, "RUG", "%s", android_log_buf+last_cr);
last_cr = i+1;
}
android_log_bufpos = 0;
while(i > last_cr) android_log_buf[android_log_bufpos++] = android_log_buf[last_cr++];
}
void gdpush(int t);
#include <jni.h>
@ -32,16 +59,15 @@ std::string levelfile, picfile;
bool settingsChanged = false;
#include "../../../../../init.cpp"
struct transmatrix getOrientation();
#include "/home/eryx/proj/rogue/hyper/init.cpp"
// #define delref env->DeleteLocalRef(_thiz)
int semaphore = 0;
bool crash = false;
#include <android/log.h>
#define LOCK(s, x) \
semaphore++; const char *xs = x; if(semaphore > 1) { crash = true; \
__android_log_print(ANDROID_LOG_WARN, "HyperRogue", "concurrency crash in %s\n", x); semaphore--; fflush(stdout); return s; }
@ -77,11 +103,15 @@ Java_com_roguetemple_hyperroid_HyperRogue_captureBack
}
void uploadAll(MOBPAR_FORMAL);
void applyScoreCache(char whattodo);
bool wantgoogle;
extern "C" bool
Java_com_roguetemple_hyperroid_HyperRogue_keepinmemory
( MOBPAR_FORMAL) {
saveStats(true);
if(wantgoogle) applyScoreCache('s');
else applyScoreCache('d');
uploadAll(MOBPAR_ACTUAL);
if(!canmove) return false;
if(items[itOrbSafety]) return false;
@ -128,6 +158,34 @@ Java_com_roguetemple_hyperroid_HyperRogue_getGL(MOBPAR_FORMAL)
return vid.usingGL;
}
extern "C" void
Java_com_roguetemple_hyperroid_HyperRogue_glhrinit(MOBPAR_FORMAL)
{
__android_log_print(ANDROID_LOG_WARN, "HyperRogue", "glhr::init %d\n", 0);
#if HNEW
glhr::init();
#endif
__android_log_print(ANDROID_LOG_WARN, "HyperRogue", "glhr::init done %d\n", 0);
}
extern "C" int
Java_com_roguetemple_hyperroid_HyperRogue_getaPosition(MOBPAR_FORMAL)
{
return glhr::aPosition;
}
extern "C" int
Java_com_roguetemple_hyperroid_HyperRogue_getaTexture(MOBPAR_FORMAL)
{
return glhr::aTexture;
}
extern "C" int
Java_com_roguetemple_hyperroid_HyperRogue_getuColor(MOBPAR_FORMAL)
{
return glhr::current->uColor;
}
string sscorefile, sconffile, scachefile;
#include <sys/stat.h>
@ -162,12 +220,14 @@ Java_com_roguetemple_hyperroid_HyperRogue_initGame(MOBPAR_FORMAL) {
__android_log_print(ANDROID_LOG_VERBOSE, "HyperRogue", "Initializing game, gamerunning = %d\n", gamerunning);
printf("test\n");
fflush(stdout);
if(gamerunning) return 1;
gamerunning = true;
gamerunning = true;
initAll();
if(showstartmenu) pushScreen(showStartMenu);
uploadAll(MOBPAR_ACTUAL);
__android_log_print(ANDROID_LOG_VERBOSE, "HyperRogue", "Game initialized, gamerunning = %d\n", gamerunning);
return 0;
}
@ -183,17 +243,29 @@ int textwidth(int siz, const string &str) {
return res;
}
void achievement_init() {}
bool achievementsConnected = false;
string doViewLeaderboard;
bool doViewAchievements;
bool doOpenURL;
bool currentlyConnecting() { return false; }
bool currentlyConnected() { return false; }
void viewLeaderboard(string what) { doViewLeaderboard = what; }
void viewAchievements() { doViewAchievements = true; }
vector<pair<int, int> > scoresToUpload;
vector<const char *> achievementsToUpload;
vector<pair<string, int> > soundsToPlay;
void openURL() {
doOpenURL = true;
}
int last_upload[NUMLEADER];
void shareScore(MOBPAR_FORMAL) {
string s = buildScoreDescription();
jclass cls = env->GetObjectClass(thiz);
@ -216,8 +288,34 @@ extern "C" void Java_com_roguetemple_hyperroid_HyperRogue_draw(MOBPAR_FORMAL) {
infoticks = getticks();
} */
tw_thiz = thiz; tw_env = env;
#if HNEW
glhr::be_textured();
glhr::be_nontextured();
#if CAP_SHADER
glEnableVertexAttribArray(glhr::aPosition);
#else
glEnableClientState(GL_VERTEX_ARRAY);
#endif
#endif
mobile_draw(MOBPAR_ACTUAL);
uploadAll(MOBPAR_ACTUAL);
#if HNEW
// text is drawn with 'textured'
glhr::be_textured();
glhr::set_depthtest(false);
stereo::set_viewport(0);
stereo::set_mask(0);
glhr::new_projection();
glhr::projection_multiply(glhr::translate(-1,-1,0));
glhr::projection_multiply(glhr::ortho(vid.xres/2, vid.yres/2, 1));
glhr::set_modelview(glhr::id);
glhr::color2(0xC08040F0);
#endif
UNLOCK
}
@ -261,10 +359,26 @@ void playSound(cell *c, const string& fname, int vol) {
soundsToPlay.push_back(make_pair(fname, vol));
}
transmatrix orientation;
bool orientation_requested;
transmatrix getOrientation() {
orientation_requested = true;
return orientation;
}
void uploadAll(JNIEnv *env, jobject thiz) {
jclass cls = env->GetObjectClass(thiz);
if(orientation_requested) {
jmethodID mid = env->GetMethodID(cls, "getOrientation", "(II)D");
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
orientation[i][j] = env->CallDoubleMethod(thiz, mid, i, j);
orientation_requested = false;
}
for(int i=0; i<size(soundsToPlay); i++) {
jmethodID mid = env->GetMethodID(cls, "playSound", "(Ljava/lang/String;I)V");
jobject str = env->NewStringUTF(soundsToPlay[i].first.c_str());