Android Tutorial - File : Buffer
Fast Float Buffer
//package com.ryanm.droid.rugl.util; import java.lang.ref.SoftReference; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * Convenient work-around for poor {@link FloatBuffer#put(float[])} performance. * This should become unnecessary in gingerbread, @see <a href * ="http://code.google.com/p/android/issues/detail?id=11078">Issue 11078</a> * * @author ryanm */ public class FastFloatBuffer { /** * Underlying data - give this to OpenGL */ public ByteBuffer bytes; private FloatBuffer floats; private IntBuffer ints; /** * Use a {@link SoftReference} so that the array can be collected if * necessary */ private static SoftReference<int[]> intArray = new SoftReference<int[]>( new int[0]); /** * Constructs a new direct native-ordered buffer * * @param capacity * the number of floats */ public FastFloatBuffer(int capacity) { bytes = ByteBuffer.allocateDirect((capacity * 4)).order( ByteOrder.nativeOrder()); floats = bytes.asFloatBuffer(); ints = bytes.asIntBuffer(); } /** * See {@link FloatBuffer#flip()} */ public void flip() { bytes.flip(); floats.flip(); ints.flip(); } /** * See {@link FloatBuffer#put(float)} * * @param f */ public void put(float f) { bytes.position(bytes.position() + 4); floats.put(f); ints.position(ints.position() + 1); } /** * It's like {@link FloatBuffer#put(float[])}, but about 10 times faster * * @param data */ public void put(float[] data) { int[] ia = intArray.get(); if (ia == null || ia.length < data.length) { ia = new int[data.length]; intArray = new SoftReference<int[]>(ia); } for (int i = 0; i < data.length; i++) { ia[i] = Float.floatToRawIntBits(data[i]); } bytes.position(bytes.position() + 4 * data.length); floats.position(floats.position() + data.length); ints.put(ia, 0, data.length); } /** * For use with pre-converted data. This is 50x faster than * {@link #put(float[])}, and 500x faster than * {@link FloatBuffer#put(float[])}, so if you've got float[] data that * won't change, {@link #convert(float...)} it to an int[] once and use this * method to put it in the buffer * * @param data * floats that have been converted with * {@link Float#floatToIntBits(float)} */ public void put(int[] data) { bytes.position(bytes.position() + 4 * data.length); floats.position(floats.position() + data.length); ints.put(data, 0, data.length); } /** * Converts float data to a format that can be quickly added to the buffer * with {@link #put(int[])} * * @param data * @return the int-formatted data */ public static int[] convert(float... data) { int[] id = new int[data.length]; for (int i = 0; i < data.length; i++) { id[i] = Float.floatToRawIntBits(data[i]); } return id; } /** * See {@link FloatBuffer#put(FloatBuffer)} * * @param b */ public void put(FastFloatBuffer b) { bytes.put(b.bytes); floats.position(bytes.position() >> 2); ints.position(bytes.position() >> 2); } /** * @return See {@link FloatBuffer#capacity()} */ public int capacity() { return floats.capacity(); } /** * @return See {@link FloatBuffer#position()} */ public int position() { return floats.position(); } /** * See {@link FloatBuffer#position(int)} * * @param p */ public void position(int p) { bytes.position(4 * p); floats.position(p); ints.position(p); } /** * @return See {@link FloatBuffer#slice()} */ public FloatBuffer slice() { return floats.slice(); } /** * @return See {@link FloatBuffer#remaining()} */ public int remaining() { return floats.remaining(); } /** * @return See {@link FloatBuffer#limit()} */ public int limit() { return floats.limit(); } /** * See {@link FloatBuffer#clear()} */ public void clear() { bytes.clear(); floats.clear(); ints.clear(); } }
Demonstrate the Frame Buffer Object OpenGL ES extension.
package app.test; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11ExtensionPack; import android.app.Activity; import android.opengl.GLSurfaceView; import android.opengl.GLU; import android.os.Bundle; import android.os.SystemClock; /** * Demonstrate the Frame Buffer Object OpenGL ES extension. * <p> * This sample renders a scene into an offscreen frame buffer, and then uses the * resulting image as a texture to render an onscreen scene. */ public class FrameBufferObjectActivity extends Activity { private GLSurfaceView mGLSurfaceView; private class Renderer implements GLSurfaceView.Renderer { private boolean mContextSupportsFrameBufferObject; private int mTargetTexture; private int mFramebuffer; private int mFramebufferWidth = 256; private int mFramebufferHeight = 256; private int mSurfaceWidth; private int mSurfaceHeight; private Triangle mTriangle; private Cube mCube; private float mAngle; /** * Setting this to true will change the behavior of this sample. It will * suppress the normally onscreen rendering, and it will cause the * rendering that would normally be done to the offscreen FBO be * rendered onscreen instead. This can be helpful in debugging the * rendering algorithm. */ private static final boolean DEBUG_RENDER_OFFSCREEN_ONSCREEN = false; public void onDrawFrame(GL10 gl) { checkGLError(gl); if (mContextSupportsFrameBufferObject) { GL11ExtensionPack gl11ep = (GL11ExtensionPack) gl; if (DEBUG_RENDER_OFFSCREEN_ONSCREEN) { drawOffscreenImage(gl, mSurfaceWidth, mSurfaceHeight); } else { gl11ep.glBindFramebufferOES( GL11ExtensionPack.GL_FRAMEBUFFER_OES, mFramebuffer); drawOffscreenImage(gl, mFramebufferWidth, mFramebufferHeight); gl11ep.glBindFramebufferOES( GL11ExtensionPack.GL_FRAMEBUFFER_OES, 0); drawOnscreen(gl, mSurfaceWidth, mSurfaceHeight); } } else { // Current context doesn't support frame buffer objects. // Indicate this by drawing a red background. gl.glClearColor(1, 0, 0, 0); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } } public void onSurfaceChanged(GL10 gl, int width, int height) { checkGLError(gl); mSurfaceWidth = width; mSurfaceHeight = height; gl.glViewport(0, 0, width, height); } public void onSurfaceCreated(GL10 gl, EGLConfig config) { mContextSupportsFrameBufferObject = checkIfContextSupportsFrameBufferObject(gl); if (mContextSupportsFrameBufferObject) { mTargetTexture = createTargetTexture(gl, mFramebufferWidth, mFramebufferHeight); mFramebuffer = createFrameBuffer(gl, mFramebufferWidth, mFramebufferHeight, mTargetTexture); mCube = new Cube(); mTriangle = new Triangle(); } } private void drawOnscreen(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); float ratio = (float) width / height; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); gl.glClearColor(0, 0, 1, 0); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTargetTexture); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); mTriangle.draw(gl); // Restore default state so the other renderer is not affected. gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } private void drawOffscreenImage(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); float ratio = (float) width / height; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); gl.glEnable(GL10.GL_CULL_FACE); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glClearColor(0, 0.5f, 1, 0); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(0, 0, -3.0f); gl.glRotatef(mAngle, 0, 1, 0); gl.glRotatef(mAngle * 0.25f, 1, 0, 0); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); mCube.draw(gl); gl.glRotatef(mAngle * 2.0f, 0, 1, 1); gl.glTranslatef(0.5f, 0.5f, 0.5f); mCube.draw(gl); mAngle += 1.2f; // Restore default state so the other renderer is not affected. gl.glDisable(GL10.GL_CULL_FACE); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } private int createTargetTexture(GL10 gl, int width, int height) { int texture; int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); texture = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, texture); gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, width, height, 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, null); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); ; return texture; } private int createFrameBuffer(GL10 gl, int width, int height, int targetTextureId) { GL11ExtensionPack gl11ep = (GL11ExtensionPack) gl; int framebuffer; int[] framebuffers = new int[1]; gl11ep.glGenFramebuffersOES(1, framebuffers, 0); framebuffer = framebuffers[0]; gl11ep.glBindFramebufferOES(GL11ExtensionPack.GL_FRAMEBUFFER_OES, framebuffer); int depthbuffer; int[] renderbuffers = new int[1]; gl11ep.glGenRenderbuffersOES(1, renderbuffers, 0); depthbuffer = renderbuffers[0]; gl11ep.glBindRenderbufferOES(GL11ExtensionPack.GL_RENDERBUFFER_OES, depthbuffer); gl11ep.glRenderbufferStorageOES( GL11ExtensionPack.GL_RENDERBUFFER_OES, GL11ExtensionPack.GL_DEPTH_COMPONENT16, width, height); gl11ep.glFramebufferRenderbufferOES( GL11ExtensionPack.GL_FRAMEBUFFER_OES, GL11ExtensionPack.GL_DEPTH_ATTACHMENT_OES, GL11ExtensionPack.GL_RENDERBUFFER_OES, depthbuffer); gl11ep.glFramebufferTexture2DOES( GL11ExtensionPack.GL_FRAMEBUFFER_OES, GL11ExtensionPack.GL_COLOR_ATTACHMENT0_OES, GL10.GL_TEXTURE_2D, targetTextureId, 0); int status = gl11ep .glCheckFramebufferStatusOES(GL11ExtensionPack.GL_FRAMEBUFFER_OES); if (status != GL11ExtensionPack.GL_FRAMEBUFFER_COMPLETE_OES) { throw new RuntimeException("Framebuffer is not complete: " + Integer.toHexString(status)); } gl11ep.glBindFramebufferOES(GL11ExtensionPack.GL_FRAMEBUFFER_OES, 0); return framebuffer; } private boolean checkIfContextSupportsFrameBufferObject(GL10 gl) { return checkIfContextSupportsExtension(gl, "GL_OES_framebuffer_object"); } /** * This is not the fastest way to check for an extension, but fine if we * are only checking for a few extensions each time a context is * created. * * @param gl * @param extension * @return true if the extension is present in the current context. */ private boolean checkIfContextSupportsExtension(GL10 gl, String extension) { String extensions = " " + gl.glGetString(GL10.GL_EXTENSIONS) + " "; // The extensions string is padded with spaces between extensions, // but not // necessarily at the beginning or end. For simplicity, add spaces // at the // beginning and end of the extensions string and the extension // string. // This means we can avoid special-case checks for the first or last // extension, as well as avoid special-case checks when an extension // name // is the same as the first part of another extension name. return extensions.indexOf(" " + extension + " ") >= 0; } } static void checkGLError(GL gl) { int error = ((GL10) gl).glGetError(); if (error != GL10.GL_NO_ERROR) { throw new RuntimeException("GLError 0x" + Integer.toHexString(error)); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create our surface view and set it as the content of our // Activity mGLSurfaceView = new GLSurfaceView(this); mGLSurfaceView.setRenderer(new Renderer()); setContentView(mGLSurfaceView); } @Override protected void onResume() { // Ideally a game should implement onResume() and onPause() // to take appropriate action when the activity looses focus super.onResume(); mGLSurfaceView.onResume(); } @Override protected void onPause() { // Ideally a game should implement onResume() and onPause() // to take appropriate action when the activity looses focus super.onPause(); mGLSurfaceView.onPause(); } } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); // A unit-sided equalateral triangle centered on the origin. float[] coords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; for (int i = 0; i < VERTS; i++) { for (int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i * 3 + j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { for (int j = 0; j < 2; j++) { mTexBuffer.put(coords[i * 3 + j] * 2.0f + 0.5f); } } for (int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; } /** * A vertex shaded cube. */ class Cube { public Cube() { int one = 0x10000; int vertices[] = { -one, -one, -one, one, -one, -one, one, one, -one, -one, one, -one, -one, -one, one, one, -one, one, one, one, one, -one, one, one, }; int colors[] = { 0, 0, 0, one, one, 0, 0, one, one, one, 0, one, 0, one, 0, one, 0, 0, one, one, one, 0, one, one, one, one, one, one, 0, one, one, one, }; byte indices[] = { 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5, 3, 0, 1, 3, 1, 2 }; // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4); vbb.order(ByteOrder.nativeOrder()); mVertexBuffer = vbb.asIntBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4); cbb.order(ByteOrder.nativeOrder()); mColorBuffer = cbb.asIntBuffer(); mColorBuffer.put(colors); mColorBuffer.position(0); mIndexBuffer = ByteBuffer.allocateDirect(indices.length); mIndexBuffer.put(indices); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CW); gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer); gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer); gl.glDrawElements(GL10.GL_TRIANGLES, 36, GL10.GL_UNSIGNED_BYTE, mIndexBuffer); } private IntBuffer mVertexBuffer; private IntBuffer mColorBuffer; private ByteBuffer mIndexBuffer; }
Loads a file to a ByteBuffer.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; class Main { static final String defaultCharset = "UTF-8"; // used if not found in header // or meta charset private static final int bufferSize = 0x20000; // ~130K. /** * Loads a file to a Document. * * @param in * file to load * @param charsetName * character set of input * @param baseUri * base URI of document, to resolve relative links against * @return Document * @throws IOException * on IO error */ static ByteBuffer readToByteBuffer(InputStream inStream) throws IOException { byte[] buffer = new byte[bufferSize]; ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize); int read; while (true) { read = inStream.read(buffer); if (read == -1) break; outStream.write(buffer, 0, read); } ByteBuffer byteData = ByteBuffer.wrap(outStream.toByteArray()); return byteData; } }
Make a direct NIO FloatBuffer from an array of floats
//package edu.dhbw.andar.util; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.Iterator; import java.util.List; import android.hardware.Camera.Size; public class GraphicsUtil { //private final static double epsilon = 0.001; //this epsilon being so large is intended, as often there will not be an adequate resolution with //the correct aspect ratio available //so we trade the correct aspect ratio for faster rendering private final static double epsilon = 0.17; /** * Make a direct NIO FloatBuffer from an array of floats * @param arr The array * @return The newly created FloatBuffer */ public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** * Make a direct NIO ByteBuffer from an array of floats * @param arr The array * @return The newly created FloatBuffer */ public static ByteBuffer makeByteBuffer(byte[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length); bb.order(ByteOrder.nativeOrder()); bb.put(arr); bb.position(0); return bb; } public static ByteBuffer makeByteBuffer(int size) { ByteBuffer bb = ByteBuffer.allocateDirect(size); bb.position(0); return bb; } /** * Get the optimal preview size for the given screen size. * @param sizes * @param screenWidth * @param screenHeight * @return */ public static Size getOptimalPreviewSize(List<Size> sizes, int screenWidth, int screenHeight) { double aspectRatio = ((double)screenWidth)/screenHeight; Size optimalSize = null; for (Iterator<Size> iterator = sizes.iterator(); iterator.hasNext();) { Size currSize = iterator.next(); double curAspectRatio = ((double)currSize.width)/currSize.height; //do the aspect ratios equal? if ( Math.abs( aspectRatio - curAspectRatio ) < epsilon ) { //they do if(optimalSize!=null) { //is the current size smaller than the one before if(optimalSize.height>currSize.height && optimalSize.width>currSize.width) { optimalSize = currSize; } } else { optimalSize = currSize; } } } if(optimalSize == null) { //did not find a size with the correct aspect ratio.. let's choose the smallest instead for (Iterator<Size> iterator = sizes.iterator(); iterator.hasNext();) { Size currSize = iterator.next(); if(optimalSize!=null) { //is the current size smaller than the one before if(optimalSize.height>currSize.height && optimalSize.width>currSize.width) { optimalSize = currSize; } else { optimalSize = currSize; } }else { optimalSize = currSize; } } } return optimalSize; } public static boolean containsSize(List<Size> sizes, Size size) { for (Iterator<Size> iterator = sizes.iterator(); iterator.hasNext();) { Size currSize = iterator.next(); if(currSize.width == size.width && currSize.height == size.height) { return true; } } return false; } public static Size getSmallestSize(List<Size> sizes) { Size optimalSize = null; for (Iterator<Size> iterator = sizes.iterator(); iterator.hasNext();) { Size currSize = iterator.next(); if(optimalSize == null) { optimalSize = currSize; } else if(optimalSize.height>currSize.height && optimalSize.width>currSize.width) { optimalSize = currSize; } } return optimalSize; } }
Make Float Buffer From Array
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import android.content.res.Resources; class MemUtil { public static FloatBuffer makeFloatBufferFromArray(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } }
Creates a floatbuffer of the given size.
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import android.content.res.Resources; class MemUtil { /** * creates a floatbuffer of the given size. * @param size * @return */ public static FloatBuffer makeFloatBuffer(int size) { ByteBuffer bb = ByteBuffer.allocateDirect(size*4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.position(0); return fb; } }
Make Float Buffer with ByteBuffer.allocateDirect
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import android.content.res.Resources; class MemUtil { public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } }
allocate Float Buffer
import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; class OpenGLUtils { public static FloatBuffer allocateFloatBuffer(int capacity) { ByteBuffer vbb = ByteBuffer.allocateDirect(capacity); vbb.order(ByteOrder.nativeOrder()); return vbb.asFloatBuffer(); } }
to Short Buffer
import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; class OpenGLUtils { public static ShortBuffer toShortBuffer(short[] values) { ByteBuffer vbb = ByteBuffer.allocateDirect(values.length * 2); vbb.order(ByteOrder.nativeOrder()); ShortBuffer buffer = vbb.asShortBuffer(); buffer.put(values); buffer.position(0); return buffer; } }
to Float Buffer Position Zero
import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; class OpenGLUtils { public static FloatBuffer toFloatBufferPositionZero(float[] values) { ByteBuffer vbb = ByteBuffer.allocateDirect(values.length * 4); vbb.order(ByteOrder.nativeOrder()); FloatBuffer buffer = vbb.asFloatBuffer(); buffer.put(values); buffer.position(0); return buffer; } }
allocate Short Buffer
import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; class OpenGLUtils { public static ShortBuffer allocateShortBuffer(int capacity) { ByteBuffer vbb = ByteBuffer.allocateDirect(capacity); vbb.order(ByteOrder.nativeOrder()); return vbb.asShortBuffer(); } }
allocate Int Buffer
import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; class OpenGLUtils { public static IntBuffer allocateInttBuffer(int capacity) { ByteBuffer vbb = ByteBuffer.allocateDirect(capacity); vbb.order(ByteOrder.nativeOrder()); return vbb.asIntBuffer(); } }
Read InputStream with BufferedReader
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author Eddie * */ class Utils { public static String convertStreamToString(InputStream is) throws IOException { /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder * and returned as String. */ if (is != null) { StringBuilder sb = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } } finally { is.close(); } return sb.toString(); } else { return ""; } } }
To convert the InputStream to String we use the BufferedReader.readLine() method.
//package com.sdhillon.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
class Util {
public static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
make Float Buffer
//package min3d; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class Utils { public static final float DEG = (float)(Math.PI / 180f); private static final int BYTES_PER_FLOAT = 4; /** * Convenience method to create a Bitmap given a Context's drawable resource ID. */ public static Bitmap makeBitmapFromResourceId(Context $context, int $id) { InputStream is = $context.getResources().openRawResource($id); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } return bitmap; } public static FloatBuffer makeFloatBuffer3(float $a, float $b, float $c) { ByteBuffer b = ByteBuffer.allocateDirect(3 * BYTES_PER_FLOAT); b.order(ByteOrder.nativeOrder()); FloatBuffer buffer = b.asFloatBuffer(); buffer.put($a); buffer.put($b); buffer.put($c); buffer.position(0); return buffer; } public static FloatBuffer makeFloatBuffer4(float $a, float $b, float $c, float $d) { ByteBuffer b = ByteBuffer.allocateDirect(4 * BYTES_PER_FLOAT); b.order(ByteOrder.nativeOrder()); FloatBuffer buffer = b.asFloatBuffer(); buffer.put($a); buffer.put($b); buffer.put($c); buffer.put($d); buffer.position(0); return buffer; } }
get Buffer From Array
//package com.mamlambo.easy3d.helpers; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; class OpenGLUtilities { public static final float PI = 3.14159265358979323846f; static ByteBuffer getByteBufferFromByteArray(byte array[]) { ByteBuffer buffer = ByteBuffer.allocateDirect(array.length); buffer.put(array); buffer.position(0); return buffer; } static FloatBuffer getFloatBufferFromFloatArray(float array[]) { ByteBuffer tempBuffer = ByteBuffer.allocateDirect(array.length * 4); tempBuffer.order(ByteOrder.nativeOrder()); FloatBuffer buffer = tempBuffer.asFloatBuffer(); buffer.put(array); buffer.position(0); return buffer; } static IntBuffer getIntBufferFromIntArray(int array[]) { ByteBuffer tempBuffer = ByteBuffer.allocateDirect(array.length * 4); tempBuffer.order(ByteOrder.nativeOrder()); IntBuffer buffer = tempBuffer.asIntBuffer(); buffer.put(array); buffer.position(0); return buffer; } }
Your own float buffer
import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; class MyFloatBuffer { private final static ByteOrder BYTE_ORDER = ByteOrder.nativeOrder(); private final FloatBuffer floats; public MyFloatBuffer(int capacity) { floats = ByteBuffer.allocateDirect(capacity * 4).order(BYTE_ORDER) .asFloatBuffer(); } public final void put(float[] src) { floats.put(src); } public final void flip() { floats.flip(); } public final Buffer asBuffer() { return floats; } }
Direct Buffer
//package org.glscene.util; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import javax.microedition.khronos.opengles.GL10; interface DirectBufferable { public void putInto(ByteBuffer buffer); } abstract class DirectBuffer implements Serializable { public static final long serialVersionUID = 1L; protected transient ByteBuffer fBuffer; protected int fGLSize; protected void allocate(int size) { if (size == 0) { fBuffer = null; } else { fBuffer = ByteBuffer.allocateDirect(size); fBuffer.order(ByteOrder.nativeOrder()); } } protected void put(DirectBufferable aBufferable) { aBufferable.putInto(fBuffer); fBuffer.position(0); } abstract public int GLType(); public boolean empty() { return (fBuffer != null); } public int size() { if (fBuffer == null) { return 0; } else { return (fBuffer.capacity() >> 2); } } public void glVertexPointer(GL10 gl) { gl.glVertexPointer(fGLSize, GLType(), 0, fBuffer); } public void glVertexPointer(GL10 gl, int size, int stride) { gl.glVertexPointer(size, GLType(), stride, fBuffer); } public void glNormalPointer(GL10 gl) { gl.glNormalPointer(GLType(), 0, fBuffer); } public void glNormalPointer(GL10 gl, int stride) { gl.glNormalPointer(GLType(), stride, fBuffer); } public void glColorPointer(GL10 gl) { gl.glColorPointer(fGLSize, GLType(), 0, fBuffer); } public void glColorPointer(GL10 gl, int size, int stride) { gl.glColorPointer(size, GLType(), stride, fBuffer); } public void glTexCoordPointer(GL10 gl) { gl.glTexCoordPointer(fGLSize, GLType(), 0, fBuffer); } public void glTexCoordPointer(GL10 gl, int size, int stride) { gl.glTexCoordPointer(size, GLType(), stride, fBuffer); } }
create Buffer
import java.nio.ByteBuffer; import java.nio.ByteOrder; class IOUtils { public static ByteBuffer createBuffer() { ByteBuffer buffer = ByteBuffer.allocate(64); // 64 bytes max package // size buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short) 0); // Allocate a short for size return buffer; } }
Write String to File with BufferWriter
import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; class Utils { public static void writeToFile(String fileName, String text) throws IOException { BufferedWriter out = null; try { // XXX is it UTF8 or UTF-8 ??? out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(fileName), "UTF8")); out.write(text); out.close(); } finally { if (out != null) { out.close(); } } } }
Byte Buffer Stack
/** * Copyright (C) 2009 Michael A. MacDonald */ package com.antlersoft.util; /** * @author Michael A. MacDonald * */ public class ByteBufferStack { private byte[] m_buffer; private int[] m_offsets; private int m_depth; private int m_max_depth; private int m_max_size; public static final int MAX_DEPTH = 20; public static final int MAX_SIZE = 1048; public ByteBufferStack(int maxDepth, int maxSize) { m_depth = 0; m_max_depth = maxDepth; m_max_size = maxSize; m_offsets= new int[maxDepth]; m_buffer = new byte[maxSize]; } public ByteBufferStack() { this(MAX_DEPTH, MAX_SIZE); } /** * * @return Start of the buffer; this value is valid at least until the next call of reserve() */ public byte[] getBuffer() { return m_buffer; } /** * * @return Offset in getBuffer() of last reserved region */ public int getOffset() { return m_offsets[m_depth]; } public int reserve(int count) { if (count < 0 || (count + m_max_size < 0)) throw new IllegalArgumentException("Count must by greater than 0"); if (m_depth == m_max_depth) { m_max_depth *= 2; int[] new_offsets = new int[m_max_depth]; System.arraycopy(m_offsets, 0, new_offsets, 0, m_depth); m_offsets = new_offsets; } int result = m_offsets[m_depth]; int new_size = result + count; m_offsets[m_depth++] = new_size; if (new_size > m_max_size) { m_max_size = Math.max(2 * m_max_size, new_size); byte[] new_buffer = new byte[m_max_size]; System.arraycopy(m_buffer, 0, new_buffer, 0, result); m_buffer = new_buffer; } return result; } public void release() { if (m_depth<1) { throw new IllegalStateException("release() without reserve()"); } m_depth--; } }
Compute the SHA-1 hash of the bytes in the given buffer
import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; //package atorrentapi; class Main { public static byte[] hash(ByteBuffer hashThis) { try { // byte[] hash = new byte[20]; MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(hashThis); return md.digest(); } catch (NoSuchAlgorithmException nsae) { } return null; } }
An utility class for java.nio.Buffers
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; public abstract class BufferUtils { public static ByteBuffer createByteBuffer(int size) { ByteBuffer bb = ByteBuffer.allocateDirect(size); bb.order(ByteOrder.nativeOrder()); return bb; } public static CharBuffer createCharBuffer(int size) { ByteBuffer bb = ByteBuffer.allocateDirect(2*size); bb.order(ByteOrder.nativeOrder()); return bb.asCharBuffer(); } /** * @param size number of floats the buffer should hold * @return the newly allocated float buffer */ public static FloatBuffer createFloatBuffer(int size) { ByteBuffer bb = ByteBuffer.allocateDirect(4*size); bb.order(ByteOrder.nativeOrder()); return bb.asFloatBuffer(); } /** * @param size number of integers the buffer should hold * @return the newly allocated integer buffer */ private static IntBuffer createIntBuffer(int size) { ByteBuffer bb = ByteBuffer.allocateDirect(4*size); bb.order(ByteOrder.nativeOrder()); return bb.asIntBuffer(); } public static IntBuffer toFixedBuffer(FloatBuffer floatBuffer) { int len = floatBuffer.capacity(); IntBuffer fixedBuffer = createIntBuffer(len); floatBuffer.clear(); fixedBuffer.clear(); for(int i = 0; i < len; i++) { fixedBuffer.put((int)(floatBuffer.get(i)*65536)); } fixedBuffer.clear(); return null; } }