Example usage for java.nio ByteBuffer asShortBuffer

List of usage examples for java.nio ByteBuffer asShortBuffer

Introduction

In this page you can find the example usage for java.nio ByteBuffer asShortBuffer.

Prototype

public abstract ShortBuffer asShortBuffer();

Source Link

Document

Returns a short buffer which is based on the remaining content of this byte buffer.

Usage

From source file:org.mrgeo.data.raster.RasterWritable.java

private static byte[] rasterToBytes(final Raster raster) {
    final int datatype = raster.getTransferType();

    byte[] pixels;

    final Object elements = raster.getDataElements(raster.getMinX(), raster.getMinY(), raster.getWidth(),
            raster.getHeight(), null);/*  ww w  .  jav  a  2  s .  com*/

    switch (datatype) {
    case DataBuffer.TYPE_BYTE: {
        pixels = (byte[]) elements;
        break;
    }
    case DataBuffer.TYPE_FLOAT: {
        final float[] floatElements = (float[]) elements;

        pixels = new byte[floatElements.length * RasterUtils.FLOAT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final FloatBuffer floatbuff = bytebuff.asFloatBuffer();
        floatbuff.put(floatElements);

        break;
    }
    case DataBuffer.TYPE_DOUBLE: {
        final double[] doubleElements = (double[]) elements;

        pixels = new byte[doubleElements.length * RasterUtils.DOUBLE_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final DoubleBuffer doubleBuff = bytebuff.asDoubleBuffer();
        doubleBuff.put(doubleElements);

        break;
    }
    case DataBuffer.TYPE_INT: {
        final int[] intElements = (int[]) elements;

        pixels = new byte[intElements.length * RasterUtils.INT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final IntBuffer intBuff = bytebuff.asIntBuffer();
        intBuff.put(intElements);

        break;
    }
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_USHORT: {
        final short[] shortElements = (short[]) elements;

        pixels = new byte[shortElements.length * RasterUtils.SHORT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final ShortBuffer shortbuff = bytebuff.asShortBuffer();
        shortbuff.put(shortElements);

        break;
    }
    default:
        throw new RasterWritableException("Error trying to append raster.  Bad raster data type");
    }

    return pixels;
}

From source file:rb.app.GLObject.java

public void allocateBuffer() {
    int SHORT_MAX = 250000;
    int FLOAT_MAX = 1000000;

    Log.d("GLRenderer", "Allocate (short):" + SHORT_MAX * 2 + " bytes");
    ByteBuffer vbb = ByteBuffer.allocateDirect(SHORT_MAX * 2);
    vbb.order(ByteOrder.nativeOrder());
    _shortBuffer = vbb.asShortBuffer();
    _shortBuffer.position(0);/*from   w  w w.  j a  v  a2  s.  c o m*/

    Log.d("GLRenderer", "Allocate (float):" + FLOAT_MAX * 4 + " bytes");
    ByteBuffer fbb = ByteBuffer.allocateDirect(FLOAT_MAX * 4);
    fbb.order(ByteOrder.nativeOrder());
    _floatBuffer = fbb.asFloatBuffer();
    _floatBuffer.position(0);
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java

private ByteBuffer getPixelBuffer(TaggedImage img) throws IOException {
    if (rgb_) {//from w  ww. j a  v a  2s  .  c om
        if (byteDepth_ == 1) {
            byte[] originalPix = (byte[]) img.pix;
            byte[] pix = new byte[originalPix.length * 3 / 4];
            int count = 0;
            for (int i = 0; i < originalPix.length; i++) {
                if ((i + 1) % 4 != 0) {
                    pix[count] = originalPix[i];
                    count++;
                }
            }
            return ByteBuffer.wrap(pix);
        } else {
            short[] originalPix = (short[]) img.pix;
            short[] pix = new short[originalPix.length * 3 / 4];
            int count = 0;
            for (int i = 0; i < originalPix.length; i++) {
                if ((i + 1) % 4 != 0) {
                    pix[count] = originalPix[i];
                    count++;
                }
            }
            ByteBuffer buffer = ByteBuffer.allocate(pix.length * 2).order(BYTE_ORDER);
            buffer.asShortBuffer().put(pix);
            return buffer;
        }
    } else {
        if (byteDepth_ == 1) {
            return ByteBuffer.wrap((byte[]) img.pix);
        } else {
            short[] pix = (short[]) img.pix;
            ByteBuffer buffer = ByteBuffer.allocate(pix.length * 2).order(BYTE_ORDER);
            buffer.asShortBuffer().put(pix);
            return buffer;
        }
    }
}

From source file:com.sveder.cardboardpassthrough.MainActivity.java

/**
 * Creates the buffers we use to store information about the 3D world. OpenGL doesn't use Java
 * arrays, but rather needs data in a format it can understand. Hence we use ByteBuffers.
 * @param config The EGL configuration used when creating the surface.
 *//*from  w w w  . j a v  a2 s.co  m*/
@Override
public void onSurfaceCreated(EGLConfig config) {
    Log.i(TAG, "onSurfaceCreated");
    GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.5f); // Dark background so text shows up well

    ByteBuffer bb = ByteBuffer.allocateDirect(squareVertices.length * 4);
    bb.order(ByteOrder.nativeOrder());
    vertexBuffer = bb.asFloatBuffer();
    vertexBuffer.put(squareVertices);
    vertexBuffer.position(0);

    ByteBuffer dlb = ByteBuffer.allocateDirect(drawOrder.length * 2);
    dlb.order(ByteOrder.nativeOrder());
    drawListBuffer = dlb.asShortBuffer();
    drawListBuffer.put(drawOrder);
    drawListBuffer.position(0);

    ByteBuffer bb2 = ByteBuffer.allocateDirect(textureVertices.length * 4);
    bb2.order(ByteOrder.nativeOrder());
    textureVerticesBuffer = bb2.asFloatBuffer();
    textureVerticesBuffer.put(textureVertices);
    textureVerticesBuffer.position(0);

    int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
    int fragmentShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

    mProgram = GLES20.glCreateProgram(); // create empty OpenGL ES Program
    GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program
    GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
    GLES20.glLinkProgram(mProgram);

    texture = createTexture();
    startCamera(texture);

    //        ByteBuffer bbVertices = ByteBuffer.allocateDirect(DATA.CUBE_COORDS.length * 4);
    //        bbVertices.order(ByteOrder.nativeOrder());
    //        mCubeVertices = bbVertices.asFloatBuffer();
    //        mCubeVertices.put(DATA.CUBE_COORDS);
    //        mCubeVertices.position(0);
    //
    //        ByteBuffer bbColors = ByteBuffer.allocateDirect(DATA.CUBE_COLORS.length * 4);
    //        bbColors.order(ByteOrder.nativeOrder());
    //        mCubeColors = bbColors.asFloatBuffer();
    //        mCubeColors.put(DATA.CUBE_COLORS);
    //        mCubeColors.position(0);
    //
    //        ByteBuffer bbFoundColors = ByteBuffer.allocateDirect(DATA.CUBE_FOUND_COLORS.length * 4);
    //        bbFoundColors.order(ByteOrder.nativeOrder());
    //        mCubeFoundColors = bbFoundColors.asFloatBuffer();
    //        mCubeFoundColors.put(DATA.CUBE_FOUND_COLORS);
    //        mCubeFoundColors.position(0);
    //
    //        ByteBuffer bbNormals = ByteBuffer.allocateDirect(DATA.CUBE_NORMALS.length * 4);
    //        bbNormals.order(ByteOrder.nativeOrder());
    //        mCubeNormals = bbNormals.asFloatBuffer();
    //        mCubeNormals.put(DATA.CUBE_NORMALS);
    //        mCubeNormals.position(0);
    //
    //        // make a floor
    //        ByteBuffer bbFloorVertices = ByteBuffer.allocateDirect(DATA.FLOOR_COORDS.length * 4);
    //        bbFloorVertices.order(ByteOrder.nativeOrder());
    //        mFloorVertices = bbFloorVertices.asFloatBuffer();
    //        mFloorVertices.put(DATA.FLOOR_COORDS);
    //        mFloorVertices.position(0);
    //
    //        ByteBuffer bbFloorNormals = ByteBuffer.allocateDirect(DATA.FLOOR_NORMALS.length * 4);
    //        bbFloorNormals.order(ByteOrder.nativeOrder());
    //        mFloorNormals = bbFloorNormals.asFloatBuffer();
    //        mFloorNormals.put(DATA.FLOOR_NORMALS);
    //        mFloorNormals.position(0);
    //
    //        ByteBuffer bbFloorColors = ByteBuffer.allocateDirect(DATA.FLOOR_COLORS.length * 4);
    //        bbFloorColors.order(ByteOrder.nativeOrder());
    //        mFloorColors = bbFloorColors.asFloatBuffer();
    //        mFloorColors.put(DATA.FLOOR_COLORS);
    //        mFloorColors.position(0);
    //
    //        int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, R.raw.light_vertex);
    //        int gridShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, R.raw.grid_fragment);
    //
    //        mGlProgram = GLES20.glCreateProgram();
    //        GLES20.glAttachShader(mGlProgram, vertexShader);
    //        GLES20.glAttachShader(mGlProgram, gridShader);
    //        GLES20.glLinkProgram(mGlProgram);
    //
    //        GLES20.glEnable(GLES20.GL_DEPTH_TEST);
    //
    //        // Object first appears directly in front of user
    //        Matrix.setIdentityM(mModelCube, 0);
    //        Matrix.translateM(mModelCube, 0, 0, 0, -mObjectDistance);
    //
    //        Matrix.setIdentityM(mModelFloor, 0);
    //        Matrix.translateM(mModelFloor, 0, 0, -mFloorDepth, 0); // Floor appears below user
    //
    //        checkGLError("onSurfaceCreated");
}

From source file:com.aimfire.gallery.cardboard.PhotoActivity.java

@Override
public void onSurfaceCreated(EGLConfig config) {
    if (BuildConfig.DEBUG)
        Log.i(TAG, "onSurfaceCreated");

    /*/*  ww w  .ja v  a  2s. co  m*/
     *  Dark background so text shows up well.
     */
    GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.5f);

    ByteBuffer bbElements = ByteBuffer.allocateDirect(drawOrder.length * 2);
    bbElements.order(ByteOrder.nativeOrder());
    mPicElements = bbElements.asShortBuffer();
    mPicElements.put(drawOrder);
    mPicElements.position(0);

    int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
    int fragmentShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

    mPicProgram = GLES20.glCreateProgram();
    GLES20.glAttachShader(mPicProgram, vertexShader);
    GLES20.glAttachShader(mPicProgram, fragmentShader);
    GLES20.glLinkProgram(mPicProgram);
    GLES20.glUseProgram(mPicProgram);

    checkGLError("Pic program");

    mDimRatioParam = GLES20.glGetUniformLocation(mPicProgram, "u_dimRatio");
    mZoomParam = GLES20.glGetUniformLocation(mPicProgram, "u_zoom");
    mParallaxParam = GLES20.glGetUniformLocation(mPicProgram, "u_parallax");

    mPicPositionParam = GLES20.glGetAttribLocation(mPicProgram, "a_position");

    GLES20.glEnableVertexAttribArray(mPicPositionParam);
    checkGLError("Pic program params");

    GLES20.glEnable(GLES20.GL_DEPTH_TEST);
    checkGLError("onSurfaceCreated");

    /*
     * initializes a few textures (current, previous and next). we have to do this
     * here (as opposed to onCreate) as gl context is only available here
     */
    initTextures();

    /*
     * so onDrawEye will know to draw
     */
    mAssetChangedLeft = mAssetChangedRight = true;
}

From source file:nitf.imageio.NITFReader.java

/**
 * Optimization to read the entire image in one fell swoop... This is most
 * likely the common use case for this codec, so we hope this optimization
 * will be helpful./*from w  w w  .  j  a  v a  2  s  .c o m*/
 * 
 * @param imageIndex
 * @param sourceXSubsampling
 * @param sourceYSubsampling
 * @param bandOffsets
 * @param pixelSize
 * @param imRas
 * @throws IOException
 */
protected void readFullImage(int imageIndex, Rectangle destRegion, int sourceXSubsampling,
        int sourceYSubsampling, int[] bandOffsets, int pixelSize, WritableRaster imRas) throws IOException {
    try {
        ImageSubheader subheader = record.getImages()[imageIndex].getSubheader();
        int numCols = destRegion.width;
        int numRows = destRegion.height;

        int nBands = subheader.getBandCount();

        /*
         * NOTE: This is a "fix" that will be removed once the underlying
         * NITRO library gets patched. Currently, if you make a request of a
         * single band, it doesn't matter which band you request - the data
         * from the first band will be returned regardless. This is
         * obviously wrong. To thwart this, we will read all bands, then
         * scale down what we return to the user based on their actual
         * request.
         */

        int[] requestBands = bandOffsets;
        /*
         * if (nBands != bandOffsets.length && bandOffsets.length == 1
         * && bandOffsets[0] != 0)
         * {
         * requestBands = new int[nBands];
         * for (int i = 0; i < nBands; ++i)
         * requestBands[i] = i;
         * }
         */

        int bufSize = numCols * numRows * pixelSize;
        byte[][] imageBuf = new byte[requestBands.length][bufSize];

        // make a SubWindow from the params
        // TODO may want to read by blocks or rows to make faster and more
        // memory efficient
        SubWindow window;
        window = new SubWindow();
        window.setNumBands(requestBands.length);
        window.setBandList(requestBands);
        window.setNumCols(numCols);
        window.setNumRows(numRows);
        window.setStartCol(0);
        window.setStartRow(0);

        // the NITRO library can do the subsampling for us
        if (sourceYSubsampling != 1 || sourceXSubsampling != 1) {
            DownSampler downSampler = new PixelSkipDownSampler(sourceYSubsampling, sourceXSubsampling);
            window.setDownSampler(downSampler);
        }

        // String pixelJustification = subheader.getPixelJustification()
        // .getStringData().trim();
        // boolean shouldSwap = pixelJustification.equals("R");

        // since this is Java, we need the data in big-endian format
        // boolean shouldSwap = ByteOrder.nativeOrder() !=
        // ByteOrder.BIG_ENDIAN;

        nitf.ImageReader imageReader = getImageReader(imageIndex);
        imageReader.read(window, imageBuf);

        List<ByteBuffer> bandBufs = new ArrayList<ByteBuffer>();

        for (int i = 0; i < bandOffsets.length; ++i) {
            ByteBuffer bandBuf = null;

            // the special "fix" we added needs to do this
            if (bandOffsets.length != requestBands.length) {
                bandBuf = ByteBuffer.wrap(imageBuf[bandOffsets[i]]);
            } else {
                bandBuf = ByteBuffer.wrap(imageBuf[i]);
            }
            // ban dBuf.order(ByteOrder.nativeOrder());
            // shouldSwap ? ByteOrder.LITTLE_ENDIAN
            // : ByteOrder.BIG_ENDIAN);

            bandBufs.add(bandBuf);
        }

        // optimization for 1 band case... just dump the whole thing
        if (bandOffsets.length == 1) {
            ByteBuffer bandBuf = bandBufs.get(0);

            switch (pixelSize) {
            case 1:
                ByteBuffer rasterByteBuf = ByteBuffer.wrap(((DataBufferByte) imRas.getDataBuffer()).getData());
                rasterByteBuf.put(bandBuf);
                break;
            case 2:
                ShortBuffer rasterShortBuf = ShortBuffer
                        .wrap(((DataBufferUShort) imRas.getDataBuffer()).getData());
                rasterShortBuf.put(bandBuf.asShortBuffer());
                break;
            case 4:
                FloatBuffer rasterFloatBuf = FloatBuffer
                        .wrap(((DataBufferFloat) imRas.getDataBuffer()).getData());
                rasterFloatBuf.put(bandBuf.asFloatBuffer());
                break;
            case 8:
                DoubleBuffer rasterDoubleBuf = DoubleBuffer
                        .wrap(((DataBufferDouble) imRas.getDataBuffer()).getData());
                rasterDoubleBuf.put(bandBuf.asDoubleBuffer());
                break;
            }
        } else {
            // for multi-band case, we need to iterate over each pixel...
            // TODO -- optimize this!... somehow

            for (int srcY = 0, srcX = 0; srcY < numRows; srcY++) {
                // Copy each (subsampled) source pixel into imRas
                for (int dstX = 0; dstX < numCols; srcX += pixelSize, dstX++) {
                    for (int i = 0; i < bandOffsets.length; ++i) {
                        ByteBuffer bandBuf = bandBufs.get(i);

                        switch (pixelSize) {
                        case 1:
                            imRas.setSample(dstX, srcY, i, bandBuf.get(srcX));
                            break;
                        case 2:
                            imRas.setSample(dstX, srcY, i, bandBuf.getShort(srcX));
                            break;
                        case 4:
                            imRas.setSample(dstX, srcY, i, bandBuf.getFloat(srcX));
                            break;
                        case 8:
                            imRas.setSample(dstX, srcY, i, bandBuf.getDouble(srcX));
                            break;
                        }
                    }
                }
            }
        }
    } catch (NITFException e1) {
        throw new IOException(ExceptionUtils.getStackTrace(e1));
    }
}

From source file:org.mrgeo.data.raster.RasterWritable.java

private static Raster read(final byte[] rasterBytes, Writable payload) throws IOException {
    WritableRaster raster;//from   w ww  .j  a va 2  s.  c o  m

    final ByteBuffer rasterBuffer = ByteBuffer.wrap(rasterBytes);

    @SuppressWarnings("unused")
    final int headersize = rasterBuffer.getInt(); // this isn't really used anymore...
    final int height = rasterBuffer.getInt();
    final int width = rasterBuffer.getInt();
    final int bands = rasterBuffer.getInt();
    final int datatype = rasterBuffer.getInt();
    final SampleModelType sampleModelType = SampleModelType.values()[rasterBuffer.getInt()];

    SampleModel model;
    switch (sampleModelType) {
    case BANDED:
        model = new BandedSampleModel(datatype, width, height, bands);
        break;
    case MULTIPIXELPACKED:
        throw new NotImplementedException("MultiPixelPackedSampleModel not implemented yet");
        // model = new MultiPixelPackedSampleModel(dataType, w, h, numberOfBits)
    case PIXELINTERLEAVED: {
        final int pixelStride = rasterBuffer.getInt();
        final int scanlineStride = rasterBuffer.getInt();
        final int bandcnt = rasterBuffer.getInt();
        final int[] bandOffsets = new int[bandcnt];
        for (int i = 0; i < bandcnt; i++) {
            bandOffsets[i] = rasterBuffer.getInt();
        }
        model = new PixelInterleavedSampleModel(datatype, width, height, pixelStride, scanlineStride,
                bandOffsets);
        break;
    }
    case SINGLEPIXELPACKED:
        throw new NotImplementedException("SinglePixelPackedSampleModel not implemented yet");
        // model = new SinglePixelPackedSampleModel(dataType, w, h, bitMasks);
    case COMPONENT: {
        final int pixelStride = rasterBuffer.getInt();
        final int scanlineStride = rasterBuffer.getInt();
        final int bandcnt = rasterBuffer.getInt();
        final int[] bandOffsets = new int[bandcnt];
        for (int i = 0; i < bandcnt; i++) {
            bandOffsets[i] = rasterBuffer.getInt();
        }
        model = new ComponentSampleModel(datatype, width, height, pixelStride, scanlineStride, bandOffsets);
        break;
    }
    default:
        throw new RasterWritableException("Unknown RasterSampleModel type");
    }

    // include the header size param in the count
    int startdata = rasterBuffer.position();

    // calculate the data size
    int[] samplesize = model.getSampleSize();
    int samplebytes = 0;
    for (int ss : samplesize) {
        // bits to bytes
        samplebytes += (ss / 8);
    }
    int databytes = model.getHeight() * model.getWidth() * samplebytes;

    // final ByteBuffer rasterBuffer = ByteBuffer.wrap(rasterBytes, headerbytes, databytes);
    // the corner of the raster is always 0,0
    raster = Raster.createWritableRaster(model, null);

    switch (datatype) {
    case DataBuffer.TYPE_BYTE: {
        // we can't use the byte buffer explicitly because the header info is
        // still in it...
        final byte[] bytedata = new byte[databytes];
        rasterBuffer.get(bytedata);

        raster.setDataElements(0, 0, width, height, bytedata);
        break;
    }
    case DataBuffer.TYPE_FLOAT: {
        final FloatBuffer floatbuff = rasterBuffer.asFloatBuffer();
        final float[] floatdata = new float[databytes / RasterUtils.FLOAT_BYTES];

        floatbuff.get(floatdata);

        raster.setDataElements(0, 0, width, height, floatdata);
        break;
    }
    case DataBuffer.TYPE_DOUBLE: {
        final DoubleBuffer doublebuff = rasterBuffer.asDoubleBuffer();
        final double[] doubledata = new double[databytes / RasterUtils.DOUBLE_BYTES];

        doublebuff.get(doubledata);

        raster.setDataElements(0, 0, width, height, doubledata);

        break;
    }
    case DataBuffer.TYPE_INT: {
        final IntBuffer intbuff = rasterBuffer.asIntBuffer();
        final int[] intdata = new int[databytes / RasterUtils.INT_BYTES];

        intbuff.get(intdata);

        raster.setDataElements(0, 0, width, height, intdata);

        break;
    }
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_USHORT: {
        final ShortBuffer shortbuff = rasterBuffer.asShortBuffer();
        final short[] shortdata = new short[databytes / RasterUtils.SHORT_BYTES];
        shortbuff.get(shortdata);
        raster.setDataElements(0, 0, width, height, shortdata);
        break;
    }
    default:
        throw new RasterWritableException("Error trying to read raster.  Bad raster data type");
    }

    // should we even try to extract the payload?
    if (payload != null) {
        // test to see if this is a raster with a possible payload
        final int payloadStart = startdata + databytes;
        if (rasterBytes.length > payloadStart) {
            // extract the payload
            final ByteArrayInputStream bais = new ByteArrayInputStream(rasterBytes, payloadStart,
                    rasterBytes.length - payloadStart);
            final DataInputStream dis = new DataInputStream(bais);
            payload.readFields(dis);
        }
    }
    return raster;
}