Example usage for java.nio ByteOrder nativeOrder

List of usage examples for java.nio ByteOrder nativeOrder

Introduction

In this page you can find the example usage for java.nio ByteOrder nativeOrder.

Prototype

public static ByteOrder nativeOrder() 

Source Link

Document

Returns the current platform byte order.

Usage

From source file:ffx.xray.parsers.MTZFilter.java

/**
 * {@inheritDoc}/*from   w  w  w .jav  a2s .  c o  m*/
 */
@Override
public boolean readFile(File mtzFile, ReflectionList reflectionList, DiffractionRefinementData refinementData,
        CompositeConfiguration properties) {
    int nRead, nIgnore, nRes, nFriedel, nCut;
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;
    boolean transpose = false;

    StringBuilder sb = new StringBuilder();
    try {
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        byte headerOffset[] = new byte[4];
        byte bytes[] = new byte[80];
        int offset = 0;

        // Eat "MTZ" title.
        dataInputStream.read(bytes, offset, 4);
        String mtzstr = null;

        // Header offset.
        dataInputStream.read(headerOffset, offset, 4);

        // Machine stamp.
        dataInputStream.read(bytes, offset, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        int stamp = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampString = Integer.toHexString(stamp);
        switch (stampString.charAt(0)) {
        case '1':
        case '3':
            if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                byteOrder = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                byteOrder = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }

        byteBuffer = ByteBuffer.wrap(headerOffset);
        int headerOffsetI = byteBuffer.order(byteOrder).getInt();

        // skip to header and parse
        dataInputStream.skipBytes((headerOffsetI - 4) * 4);

        for (Boolean parsing = true; parsing; dataInputStream.read(bytes, offset, 80)) {
            mtzstr = new String(bytes);
            parsing = parseHeader(mtzstr);
        }

        // column identifiers
        foString = sigFoString = rFreeString = null;
        if (properties != null) {
            foString = properties.getString("fostring", null);
            sigFoString = properties.getString("sigfostring", null);
            rFreeString = properties.getString("rfreestring", null);
        }
        h = k = l = fo = sigFo = rFree = -1;
        fPlus = sigFPlus = fMinus = sigFMinus = rFreePlus = rFreeMinus = -1;
        boolean print = true;
        parseColumns(print);

        if (h < 0 || k < 0 || l < 0) {
            String message = "Fatal error in MTZ file - no H K L indexes?\n";
            logger.log(Level.SEVERE, message);
            return false;
        }

        // Reopen to start at beginning.
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        // Skip initial header.
        dataInputStream.skipBytes(80);

        // Check if HKLs need to be transposed or not.
        float data[] = new float[nColumns];
        HKL mate = new HKL();
        int nPosIgnore = 0;
        int nTransIgnore = 0;
        int nZero = 0;
        int none = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dataInputStream.read(bytes, offset, 4);
                byteBuffer = ByteBuffer.wrap(bytes);
                data[j] = byteBuffer.order(byteOrder).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionList.findSymHKL(ih, ik, il, mate, false);
            HKL hklpos = reflectionList.getHKL(mate);
            if (hklpos == null) {
                nPosIgnore++;
            }

            friedel = reflectionList.findSymHKL(ih, ik, il, mate, true);
            HKL hkltrans = reflectionList.getHKL(mate);
            if (hkltrans == null) {
                nTransIgnore++;
            }
            if (rFree > 0) {
                if (((int) data[rFree]) == 0) {
                    nZero++;
                } else if (((int) data[rFree]) == 1) {
                    none++;
                }
            }
            if (rFreePlus > 0) {
                if (((int) data[rFreePlus]) == 0) {
                    nZero++;
                } else if (((int) data[rFreePlus]) == 1) {
                    none++;
                }
            }
            if (rFreeMinus > 0) {
                if (((int) data[rFreeMinus]) == 0) {
                    nZero++;
                } else if (((int) data[rFreeMinus]) == 1) {
                    none++;
                }
            }
        }
        if (nPosIgnore > nTransIgnore) {
            transpose = true;
        }

        if (none > (nZero * 2) && refinementData.rfreeflag < 0) {
            refinementData.setFreeRFlag(0);
            sb.append(format(" Setting R free flag to %d based on MTZ file data.\n", refinementData.rfreeflag));
        } else if (nZero > (none * 2) && refinementData.rfreeflag < 0) {
            refinementData.setFreeRFlag(1);
            sb.append(format(" Setting R free flag to %d based on MTZ file data.\n", refinementData.rfreeflag));
        } else if (refinementData.rfreeflag < 0) {
            refinementData.setFreeRFlag(0);
            sb.append(format(" Setting R free flag to MTZ default: %d\n", refinementData.rfreeflag));
        }

        // reopen to start at beginning
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        // skip initial header
        dataInputStream.skipBytes(80);

        // read in data
        double anofSigF[][] = new double[refinementData.n][4];
        for (int i = 0; i < refinementData.n; i++) {
            anofSigF[i][0] = anofSigF[i][1] = anofSigF[i][2] = anofSigF[i][3] = Double.NaN;
        }
        nRead = nIgnore = nRes = nFriedel = nCut = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dataInputStream.read(bytes, offset, 4);
                byteBuffer = ByteBuffer.wrap(bytes);
                data[j] = byteBuffer.order(byteOrder).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionList.findSymHKL(ih, ik, il, mate, transpose);
            HKL hkl = reflectionList.getHKL(mate);
            if (hkl != null) {
                if (fo > 0 && sigFo > 0) {
                    if (refinementData.fsigfcutoff > 0.0) {
                        if ((data[fo] / data[sigFo]) < refinementData.fsigfcutoff) {
                            nCut++;
                            continue;
                        }
                    }
                    if (friedel) {
                        anofSigF[hkl.index()][2] = data[fo];
                        anofSigF[hkl.index()][3] = data[sigFo];
                        nFriedel++;
                    } else {
                        anofSigF[hkl.index()][0] = data[fo];
                        anofSigF[hkl.index()][1] = data[sigFo];
                    }
                } else {
                    if (fPlus > 0 && sigFPlus > 0) {
                        if (refinementData.fsigfcutoff > 0.0) {
                            if ((data[fPlus] / data[sigFPlus]) < refinementData.fsigfcutoff) {
                                nCut++;
                                continue;
                            }
                        }
                        anofSigF[hkl.index()][0] = data[fPlus];
                        anofSigF[hkl.index()][1] = data[sigFPlus];
                    }
                    if (fMinus > 0 && sigFMinus > 0) {
                        if (refinementData.fsigfcutoff > 0.0) {
                            if ((data[fMinus] / data[sigFMinus]) < refinementData.fsigfcutoff) {
                                nCut++;
                                continue;
                            }
                        }
                        anofSigF[hkl.index()][2] = data[fMinus];
                        anofSigF[hkl.index()][3] = data[sigFMinus];
                    }
                }
                if (rFree > 0) {
                    refinementData.setFreeR(hkl.index(), (int) data[rFree]);
                } else {
                    if (rFreePlus > 0 && rFreeMinus > 0) {
                        // not sure what the correct thing to do here is?
                        refinementData.setFreeR(hkl.index(), (int) data[rFreePlus]);
                    } else if (rFreePlus > 0) {
                        refinementData.setFreeR(hkl.index(), (int) data[rFreePlus]);
                    } else if (rFreeMinus > 0) {
                        refinementData.setFreeR(hkl.index(), (int) data[rFreeMinus]);
                    }
                }
                nRead++;
            } else {
                HKL tmp = new HKL(ih, ik, il);
                if (!reflectionList.resolution
                        .inInverseResSqRange(Crystal.invressq(reflectionList.crystal, tmp))) {
                    nRes++;
                } else {
                    nIgnore++;
                }
            }
        }

        // Set up fsigf from F+ and F-.
        refinementData.generate_fsigf_from_anofsigf(anofSigF);

        // Log results.
        if (logger.isLoggable(Level.INFO)) {
            sb.append(format(" MTZ file type (machine stamp): %s\n", stampString));
            sb.append(format(" HKL data is %s\n", transpose ? "transposed" : "not transposed"));
            sb.append(format(" HKL read in:                             %d\n", nRead));
            sb.append(format(" HKL read as friedel mates:               %d\n", nFriedel));
            sb.append(format(" HKL NOT read in (too high resolution):   %d\n", nRes));
            sb.append(format(" HKL NOT read in (not in internal list?): %d\n", nIgnore));
            sb.append(format(" HKL NOT read in (F/sigF cutoff):         %d\n", nCut));
            sb.append(format(" HKL in internal list:                    %d\n", reflectionList.hkllist.size()));
            logger.info(sb.toString());
        }
        if (rFree < 0 && rFreePlus < 0 && rFreeMinus < 0) {
            refinementData.generateRFree();
        }
    } catch (EOFException e) {
        String message = " MTZ end of file reached.";
        logger.log(Level.WARNING, message, e);
        return false;
    } catch (IOException e) {
        String message = " MTZ IO Exception.";
        logger.log(Level.WARNING, message, e);
        return false;
    }

    return true;
}

From source file:eu.sathra.SathraActivity.java

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    if (mParams.width == 0 && mParams.height == 0) {
        mParams.width = width;//  w w w  .j a va  2 s  . c om
        mParams.height = height;
    } else if (mParams.width == 0) {
        float screenRatio = width / (float) height;
        mParams.width = (int) (mParams.height * screenRatio);
    } else if (mParams.height == 0) {
        float screenRatio = height / (float) width;
        mParams.height = (int) (mParams.width * screenRatio);
    }

    gl.glViewport(0, 0, width, height);// mParams.width, mParams.height);

    Log.debug(String.format(SURFACE_CREATE_MSG_FORMAT, width, height, mParams.width, mParams.height));

    if (!mWasInitiated) {
        GLES20.glGenFramebuffers(1, buf, 0);
        GLES20.glGenTextures(1, tex, 0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tex[0]);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        IntBuffer tmp = ByteBuffer.allocateDirect(mParams.width * mParams.height * 4)
                .order(ByteOrder.nativeOrder()).asIntBuffer();
        GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, mParams.width, mParams.height, 0,
                GLES20.GL_RGBA, GLES20.GL_UNSIGNED_SHORT_4_4_4_4, tmp);

        shad = new Sprite(new Texture(tex[0], mParams.width, mParams.height));
        shad.setPivot(0.5f, 0.5f);

        onEngineInitiated();

        mWasInitiated = true;
    }
}

From source file:org.cocos2dx.lib.Cocos2dxBitmap.java

private static byte[] getPixels(Bitmap bitmap) {
    if (bitmap != null) {
        byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];
        ByteBuffer buf = ByteBuffer.wrap(pixels);
        buf.order(ByteOrder.nativeOrder());
        bitmap.copyPixelsToBuffer(buf);/*  w ww.j a  v a  2  s .co m*/
        return pixels;
    }

    return null;
}

From source file:org.ros.android.rviz_for_android.drawable.loader.ColladaLoader.java

private Map<String, ETC1Texture> getTextures(String prefix) {
    Map<String, ETC1Texture> retval = new HashMap<String, ETC1Texture>();

    String filesDirectory = serverConnection.getContext().getFilesDir().toString() + "/";

    // Find which types of acceptable textures are present (diffuse, bump, etc)
    for (textureType t : textureType.values()) {
        if (attributeExists("/COLLADA/library_effects/", t.toString(), "texture/@texture")) {
            String texPointer = super.existResult;

            String filename = null;
            // If the image library has an image with texPointer's ID, use that
            // otherwise, follow the pointer trail
            if (attributeExists("/COLLADA/library_images/image[@id='" + texPointer + "']/init_from")) {
                filename = super.existResult;
                Log.d("DAE", "Shortcut to texture name: " + filename);
            } else {
                // Locate the image ID from the texture pointer
                String imgID = getSingleAttribute(
                        "/COLLADA/library_effects//newparam[@sid='" + texPointer + "']/sampler2D/source");

                // Locate the image name
                String imgName = getSingleAttribute(
                        "/COLLADA/library_effects//newparam[@sid='" + imgID + "']/surface/init_from");

                // Locate the filename
                filename = getSingleAttribute("/COLLADA/library_images/image[@id='" + imgName + "']/init_from");
            }//from  w  w  w  .j a  v a2  s .  co  m

            Log.d("DAE", "Filename = " + filename);

            if (filename.length() == 0)
                Log.e("DAE", "Filename = 0 length!");

            // If a cached compressed copy exists, load that. Otherwise, download, compress, and save the image
            String compressedFilename = "COMPRESSED_" + serverConnection.getSanitizedPrefix(imgPrefix)
                    + filename;
            if (!serverConnection.fileExists(compressedFilename)) {
                Log.i("DAE", "No compressed cached copy exists.");

                // Load the uncompressed image         
                String downloadedFilename = serverConnection.getFile(imgPrefix + filename);
                Bitmap uncompressed = null;
                if (downloadedFilename == null) {
                    Log.e("DAE", "Unable to get file " + imgPrefix + filename + " from server!");
                    uncompressed = Bitmap.createBitmap(new int[] { 0, 0 }, 1, 1, Bitmap.Config.RGB_565);
                } else
                    uncompressed = openTextureFile(filesDirectory, downloadedFilename);

                // Flip the image
                Matrix flip = new Matrix();
                flip.postScale(1f, -1f);
                Bitmap uncompressed_two = Bitmap.createBitmap(uncompressed, 0, 0, uncompressed.getWidth(),
                        uncompressed.getHeight(), flip, true);
                uncompressed.recycle();

                // Compress the image
                ETC1Texture compressed = compressBitmap(uncompressed_two);

                // Save the compressed texture
                try {
                    BufferedOutputStream bout = new BufferedOutputStream(serverConnection.getContext()
                            .openFileOutput(compressedFilename, Context.MODE_WORLD_READABLE));
                    bout.write(compressed.getData().array());
                    bout.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // Add the compressed texture to the return map
                retval.put(t.toString(), compressed);
            } else {
                Log.i("DAE", "A compressed cached copy exists!");

                // Load the existing compressed texture
                try {
                    byte[] dataArray = IOUtils
                            .toByteArray(serverConnection.getContext().openFileInput(compressedFilename));
                    // Determine the dimensions of the image
                    int bytes = 2 * dataArray.length;
                    int width = 1024;
                    int height = 1024;

                    while ((width * height) > bytes && (width * height) >= 1) {
                        width /= 2;
                        height /= 2;
                    }

                    Log.i("DAE", "Compressed size determined to be " + width + " x " + height);

                    ByteBuffer dataBuffer = ByteBuffer.allocateDirect(dataArray.length)
                            .order(ByteOrder.nativeOrder());
                    dataBuffer.put(dataArray);
                    dataBuffer.position(0);
                    ETC1Texture compressed = new ETC1Texture(width, height, dataBuffer);
                    retval.put(t.toString(), compressed);
                } catch (FileNotFoundException e) {
                    Log.e("DAE", "Compressed texture not found!");
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.e("DAE", "IOException!");
                    e.printStackTrace();
                }
            }
        }
    }
    return retval;
}

From source file:org.apache.sysml.runtime.matrix.data.LibMatrixNative.java

private static FloatBuffer toFloatBuffer(double[] input, ThreadLocal<FloatBuffer> buff, boolean copy) {
    //maintain thread-local buffer (resized on demand)
    FloatBuffer ret = buff.get();
    if (ret == null || ret.capacity() < input.length) {
        ret = ByteBuffer.allocateDirect(4 * input.length).order(ByteOrder.nativeOrder()).asFloatBuffer();
        buff.set(ret);//from w  w  w . ja  v  a  2 s. c o  m
    }
    //copy to direct byte buffer
    final FloatBuffer ret2 = ret;
    if (copy) {
        IntStream.range(0, input.length).parallel().forEach(i -> ret2.put(i, (float) input[i]));
    }
    return ret2;
}

From source file:org.ros.android.rviz_for_android.drawable.loader.ColladaLoader.java

private ETC1Texture compressBitmap(Bitmap uncompressedBitmap) {
    // Rescale the bitmap to be half its current size
    Bitmap uncompressedBitmapResize = Bitmap.createScaledBitmap(uncompressedBitmap,
            uncompressedBitmap.getWidth() / 4, uncompressedBitmap.getHeight() / 4, true);
    uncompressedBitmap.recycle();//from   w w w .  j a  v  a 2  s.  c o  m

    // Copy the bitmap to a byte buffer
    ByteBuffer uncompressedBytes = ByteBuffer.allocateDirect(uncompressedBitmapResize.getByteCount())
            .order(ByteOrder.nativeOrder());
    uncompressedBitmapResize.copyPixelsToBuffer(uncompressedBytes);
    uncompressedBytes.position(0);

    int width = uncompressedBitmapResize.getWidth();
    int height = uncompressedBitmapResize.getHeight();

    // Compress the texture
    int encodedSize = ETC1.getEncodedDataSize(width, height);
    ByteBuffer compressed = ByteBuffer.allocateDirect(encodedSize).order(ByteOrder.nativeOrder());
    ETC1.encodeImage(uncompressedBytes, width, height, 2, 2 * width, compressed);

    ETC1Texture retval = new ETC1Texture(width, height, compressed);

    // We're done with the uncompressed bitmap, release it
    uncompressedBitmapResize.recycle();

    return retval;
}

From source file:edu.nyu.tandon.tool.PrunedPartition.java

public PrunedPartition(final String inputBasename, final String outputBasename,
        final DocumentalPartitioningStrategy strategy, final String strategyFilename,
        final int BloomFilterPrecision, final int bufferSize, final Map<Component, Coding> writerFlags,
        IndexType indexType, boolean skips, final int quantum, final int height,
        final int skipBufferOrCacheSize, final long logInterval, final boolean docPruning)
        throws ConfigurationException, IOException, ClassNotFoundException, SecurityException,
        InstantiationException, IllegalAccessException, URISyntaxException, InvocationTargetException,
        NoSuchMethodException {/* w ww .java 2 s  . com*/

    this.inputBasename = inputBasename;
    this.outputBasename = outputBasename;
    this.strategy = strategy;
    this.strategyFilename = strategyFilename;
    this.strategyProperties = strategy.properties();
    this.bufferSize = bufferSize;
    this.logInterval = logInterval;
    this.bloomFilterPrecision = BloomFilterPrecision;
    this.docPruning = docPruning;

    numIndices = strategy.numberOfLocalIndices();
    if (numIndices != 2)
        throw new ConfigurationException("Invalid number of indeces returnd from the strategy.");

    final Coding positionCoding = writerFlags.get(Component.POSITIONS);

    inputProperties = new Properties(inputBasename + DiskBasedIndex.PROPERTIES_EXTENSION);
    globalIndex = Index.getInstance(inputBasename, false,
            positionCoding == Coding.GOLOMB || positionCoding == Coding.INTERPOLATIVE, false);
    indexReader = globalIndex.getReader();

    localBasename = new String[numIndices];
    for (int i = 0; i < numIndices; i++)
        localBasename[i] = outputBasename + "-" + i;

    localTerms = new PrintWriter[numIndices];
    maxDocSize = new int[numIndices];
    maxDocPos = new int[numIndices];
    numTerms = new long[numIndices];
    occurrencies = new long[numIndices];
    numOccurrences = new long[numIndices];
    numPostings = new long[numIndices];
    indexWriter = new IndexWriter[numIndices];
    quasiSuccinctIndexWriter = new QuasiSuccinctIndexWriter[numIndices];

    this.numberOfDocuments = new long[2];
    numberOfDocuments[0] = strategy.numberOfDocuments(0);
    numberOfDocuments[1] = globalIndex.numberOfDocuments - numberOfDocuments[0];

    if ((havePayloads = writerFlags.containsKey(Component.PAYLOADS)) && !globalIndex.hasPayloads)
        throw new IllegalArgumentException(
                "You requested payloads, but the global index does not contain them.");
    if ((haveCounts = writerFlags.containsKey(Component.COUNTS)) && !globalIndex.hasCounts)
        throw new IllegalArgumentException("You requested counts, but the global index does not contain them.");
    if (!globalIndex.hasPositions && writerFlags.containsKey(Component.POSITIONS))
        writerFlags.remove(Component.POSITIONS);
    if ((havePositions = writerFlags.containsKey(Component.POSITIONS)) && !globalIndex.hasPositions)
        throw new IllegalArgumentException(
                "You requested positions, but the global index does not contain them.");
    if (indexType == IndexType.HIGH_PERFORMANCE && !havePositions)
        throw new IllegalArgumentException("You cannot disable positions for high-performance indices.");
    if (indexType != IndexType.INTERLEAVED && havePayloads)
        throw new IllegalArgumentException("Payloads are available in interleaved indices only.");
    skips |= indexType == IndexType.HIGH_PERFORMANCE;

    if (skips && (quantum <= 0 || height < 0))
        throw new IllegalArgumentException(
                "You must specify a positive quantum and a nonnegative height (variable quanta are not available when partitioning documentally).");

    // we only produce 1 index
    switch (indexType) {
    case INTERLEAVED:
        if (!skips)
            indexWriter[0] = new BitStreamIndexWriter(IOFactory.FILESYSTEM_FACTORY, localBasename[0],
                    numberOfDocuments[0], true, writerFlags);
        else
            indexWriter[0] = new SkipBitStreamIndexWriter(IOFactory.FILESYSTEM_FACTORY, localBasename[0],
                    numberOfDocuments[0], true, skipBufferOrCacheSize, writerFlags, quantum, height);
        break;
    case HIGH_PERFORMANCE:
        indexWriter[0] = new BitStreamHPIndexWriter(localBasename[0], numberOfDocuments[0], true,
                skipBufferOrCacheSize, writerFlags, quantum, height);
        break;
    case QUASI_SUCCINCT:
        quasiSuccinctIndexWriter[0] = (QuasiSuccinctIndexWriter) (indexWriter[0] = new QuasiSuccinctIndexWriter(
                IOFactory.FILESYSTEM_FACTORY, localBasename[0], numberOfDocuments[0],
                Fast.mostSignificantBit(quantum < 0 ? QuasiSuccinctIndex.DEFAULT_QUANTUM : quantum),
                skipBufferOrCacheSize, writerFlags, ByteOrder.nativeOrder()));
    }
    localTerms[0] = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(localBasename[0] + DiskBasedIndex.TERMS_EXTENSION), "UTF-8")));

    terms = new FastBufferedReader(new InputStreamReader(
            new FileInputStream(inputBasename + DiskBasedIndex.TERMS_EXTENSION), "UTF-8"));

}

From source file:it.unimi.di.big.mg4j.tool.PartitionDocumentally.java

public PartitionDocumentally(final String inputBasename, final String outputBasename,
        final DocumentalPartitioningStrategy strategy, final String strategyFilename,
        final int BloomFilterPrecision, final int bufferSize, final Map<Component, Coding> writerFlags,
        IndexType indexType, boolean skips, final int quantum, final int height,
        final int skipBufferOrCacheSize, final long logInterval) throws ConfigurationException, IOException,
        ClassNotFoundException, SecurityException, InstantiationException, IllegalAccessException,
        URISyntaxException, InvocationTargetException, NoSuchMethodException {

    this.inputBasename = inputBasename;
    this.outputBasename = outputBasename;
    this.strategy = strategy;
    this.strategyFilename = strategyFilename;
    this.strategyProperties = strategy.properties();
    this.bufferSize = bufferSize;
    this.logInterval = logInterval;
    this.bloomFilterPrecision = BloomFilterPrecision;

    numIndices = strategy.numberOfLocalIndices();

    final Coding positionCoding = writerFlags.get(Component.POSITIONS);

    inputProperties = new Properties(inputBasename + DiskBasedIndex.PROPERTIES_EXTENSION);
    globalIndex = Index.getInstance(inputBasename, false,
            positionCoding == Coding.GOLOMB || positionCoding == Coding.INTERPOLATIVE, false);
    indexReader = globalIndex.getReader();

    localBasename = new String[numIndices];
    for (int i = 0; i < numIndices; i++)
        localBasename[i] = outputBasename + "-" + i;

    localTerms = new PrintWriter[numIndices];
    maxDocSize = new int[numIndices];
    maxDocPos = new int[numIndices];
    numTerms = new long[numIndices];
    occurrencies = new long[numIndices];
    numOccurrences = new long[numIndices];
    numPostings = new long[numIndices];
    indexWriter = new IndexWriter[numIndices];
    quasiSuccinctIndexWriter = new QuasiSuccinctIndexWriter[numIndices];

    if ((havePayloads = writerFlags.containsKey(Component.PAYLOADS)) && !globalIndex.hasPayloads)
        throw new IllegalArgumentException(
                "You requested payloads, but the global index does not contain them.");
    if ((haveCounts = writerFlags.containsKey(Component.COUNTS)) && !globalIndex.hasCounts)
        throw new IllegalArgumentException("You requested counts, but the global index does not contain them.");
    if ((havePositions = writerFlags.containsKey(Component.POSITIONS)) && !globalIndex.hasPositions)
        throw new IllegalArgumentException(
                "You requested positions, but the global index does not contain them.");

    if (indexType == IndexType.HIGH_PERFORMANCE && !havePositions)
        throw new IllegalArgumentException("You cannot disable positions for high-performance indices.");
    if (indexType != IndexType.INTERLEAVED && havePayloads)
        throw new IllegalArgumentException("Payloads are available in interleaved indices only.");
    skips |= indexType == IndexType.HIGH_PERFORMANCE;
    if (skips && (quantum <= 0 || height < 0))
        throw new IllegalArgumentException(
                "You must specify a positive quantum and a nonnegative height (variable quanta are not available when partitioning documentally).");

    for (int i = 0; i < numIndices; i++) {
        switch (indexType) {
        case INTERLEAVED:
            if (!skips)
                indexWriter[i] = new BitStreamIndexWriter(IOFactory.FILESYSTEM_FACTORY, localBasename[i],
                        strategy.numberOfDocuments(i), true, writerFlags);
            else//from ww  w  .  jav  a2s.c  o m
                indexWriter[i] = new SkipBitStreamIndexWriter(IOFactory.FILESYSTEM_FACTORY, localBasename[i],
                        strategy.numberOfDocuments(i), true, skipBufferOrCacheSize, writerFlags, quantum,
                        height);
            break;
        case HIGH_PERFORMANCE:
            indexWriter[i] = new BitStreamHPIndexWriter(localBasename[i], strategy.numberOfDocuments(i), true,
                    skipBufferOrCacheSize, writerFlags, quantum, height);
            break;
        case QUASI_SUCCINCT:
            quasiSuccinctIndexWriter[i] = (QuasiSuccinctIndexWriter) (indexWriter[i] = new QuasiSuccinctIndexWriter(
                    IOFactory.FILESYSTEM_FACTORY, localBasename[i], strategy.numberOfDocuments(i),
                    Fast.mostSignificantBit(quantum < 0 ? QuasiSuccinctIndex.DEFAULT_QUANTUM : quantum),
                    skipBufferOrCacheSize, writerFlags, ByteOrder.nativeOrder()));
        }
        localTerms[i] = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(localBasename[i] + DiskBasedIndex.TERMS_EXTENSION), "UTF-8")));
    }

    terms = new FastBufferedReader(new InputStreamReader(
            new FileInputStream(inputBasename + DiskBasedIndex.TERMS_EXTENSION), "UTF-8"));
}

From source file:com.projecttango.experiments.javapointcloud.PointCloudActivity.java

private void setTangoListeners() {
    // Configure the Tango coordinate frame pair
    final ArrayList<TangoCoordinateFramePair> framePairs = new ArrayList<TangoCoordinateFramePair>();
    framePairs.add(new TangoCoordinateFramePair(TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
            TangoPoseData.COORDINATE_FRAME_DEVICE));
    // Listen for new Tango data
    mTango.connectListener(framePairs, new OnTangoUpdateListener() {

        @Override/*w w w. j  a v a 2s  .  c  o  m*/
        public void onPoseAvailable(final TangoPoseData pose) {

            mDeltaTime = (float) (pose.timestamp - mPosePreviousTimeStamp) * SECS_TO_MILLISECS;
            mPosePreviousTimeStamp = (float) pose.timestamp;
            if (mPreviousPoseStatus != pose.statusCode) {
                count = 0;
            }
            count++;
            mPreviousPoseStatus = pose.statusCode;
            mRenderer.getModelMatCalculator().updateModelMatrix(pose.getTranslationAsFloats(),
                    pose.getRotationAsFloats());
            mRenderer.updateViewMatrix();
            mGLView.requestRender();

            // Translation and Quaternion strings defined here. Can this be accessed later on xyzji availible?
            final DecimalFormat threeDec = new DecimalFormat("0.000");
            final String translationString = "[" + threeDec.format(pose.translation[0]) + ", "
                    + threeDec.format(pose.translation[1]) + ", " + threeDec.format(pose.translation[2]) + "] ";
            final String quaternionString = "[" + threeDec.format(pose.rotation[0]) + ", "
                    + threeDec.format(pose.rotation[1]) + ", " + threeDec.format(pose.rotation[2]) + ", "
                    + threeDec.format(pose.rotation[3]) + "] ";

            // Update the UI with TangoPose information
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    // Display pose data on screen in TextViews
                    mPoseTextView.setText(translationString);
                    mQuatTextView.setText(quaternionString);
                    mPoseCountTextView.setText(Integer.toString(count));
                    mDeltaTextView.setText(threeDec.format(mDeltaTime));
                    if (pose.statusCode == TangoPoseData.POSE_VALID) {
                        mPoseStatusTextView.setText(R.string.pose_valid);
                    } else if (pose.statusCode == TangoPoseData.POSE_INVALID) {
                        mPoseStatusTextView.setText(R.string.pose_invalid);
                    } else if (pose.statusCode == TangoPoseData.POSE_INITIALIZING) {
                        mPoseStatusTextView.setText(R.string.pose_initializing);
                    } else if (pose.statusCode == TangoPoseData.POSE_UNKNOWN) {
                        mPoseStatusTextView.setText(R.string.pose_unknown);
                    }

                }
            });

            // NEW - Printing data to an output Log
            Log.d(TAG,
                    "OUTPUT onPoseAvailable:" + " TStamp: " + mPosePreviousTimeStamp + " dTime: " + mDeltaTime
                            + " T: " + translationString + " R: " + quaternionString + " Status: "
                            + mPoseStatusTextView.getText().toString());

        }

        @Override
        public void onXyzIjAvailable(final TangoXyzIjData xyzIj) {
            Log.v(TAG, "SOME SHIT IS GOIN ON");
            mCurrentTimeStamp = (float) xyzIj.timestamp;
            final float frameDelta = (mCurrentTimeStamp - mXyIjPreviousTimeStamp) * SECS_TO_MILLISECS;
            mXyIjPreviousTimeStamp = mCurrentTimeStamp;
            byte[] buffer = new byte[xyzIj.xyzCount * 3 * 4];
            FileInputStream fileStream = new FileInputStream(xyzIj.xyzParcelFileDescriptor.getFileDescriptor());
            try {
                fileStream.read(buffer, xyzIj.xyzParcelFileDescriptorOffset, buffer.length);
                fileStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                TangoPoseData pointCloudPose = mTango.getPoseAtTime(mCurrentTimeStamp, framePairs.get(0));

                // NEW - Printing data to an output Log
                float[] translations = pointCloudPose.getTranslationAsFloats();
                float[] rotations = pointCloudPose.getRotationAsFloats();

                FloatBuffer mPointCloudFloatBuffer;
                mPointCloudFloatBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asFloatBuffer();
                PrintWriter p = new PrintWriter(new BufferedWriter(new FileWriter(outFile, true)));

                Log.d(TAG, "OUTPUT onxyzjiNEW:" + mPointCloudFloatBuffer.toString());
                p.println(mPointCloudFloatBuffer.get(xyzIj.xyzCount) + ", "
                        + mPointCloudFloatBuffer.get(xyzIj.xyzCount + 1) + ", "
                        + mPointCloudFloatBuffer.get(xyzIj.xyzCount + 2));
                p.close();

                mRenderer.getPointCloud().UpdatePoints(buffer, xyzIj.xyzCount);
                mRenderer.getModelMatCalculator().updatePointCloudModelMatrix(
                        pointCloudPose.getTranslationAsFloats(), pointCloudPose.getRotationAsFloats());
                mRenderer.getPointCloud()
                        .setModelMatrix(mRenderer.getModelMatCalculator().getPointCloudModelMatrixCopy());

            } catch (IOException e) {
                e.printStackTrace();
            } catch (TangoErrorException e) {
                Toast.makeText(getApplicationContext(), R.string.TangoError, Toast.LENGTH_SHORT).show();
            } catch (IndexOutOfBoundsException e) {
                Toast.makeText(getApplicationContext(), "SHIT IS FUCKED", Toast.LENGTH_SHORT).show();
            } catch (TangoInvalidException e) {
                Toast.makeText(getApplicationContext(), R.string.TangoError, Toast.LENGTH_SHORT).show();

            }

            // Must run UI changes on the UI thread. Running in the Tango
            // service thread
            // will result in an error.
            runOnUiThread(new Runnable() {
                DecimalFormat threeDec = new DecimalFormat("0.000");

                @Override
                public void run() {
                    // Display number of points in the point cloud
                    mPointCountTextView.setText(Integer.toString(xyzIj.xyzCount));
                    mFrequencyTextView.setText("" + threeDec.format(frameDelta));
                    mAverageZTextView.setText("" + threeDec.format(mRenderer.getPointCloud().getAverageZ()));
                }
            });
        }

        @Override
        public void onTangoEvent(final TangoEvent event) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mTangoEventTextView.setText(event.eventKey + ": " + event.eventValue);
                }
            });

            Log.v(TAG, "onTangoEvent" + event.eventKey + ": " + event.eventValue);
        }
    });
}

From source file:com.tumblr.cardboard.Tumblr3DActivity.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 ww .j a  va2 s . c  om
@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 bbVertices = ByteBuffer.allocateDirect(WorldLayoutData.RECT_COORDS.length * 4);
    bbVertices.order(ByteOrder.nativeOrder());
    mRectVertices = bbVertices.asFloatBuffer();
    mRectVertices.put(WorldLayoutData.RECT_COORDS);
    mRectVertices.position(0);

    ByteBuffer bbColors = ByteBuffer.allocateDirect(WorldLayoutData.RECT_COLORS.length * 4);
    bbColors.order(ByteOrder.nativeOrder());
    mRectColors = bbColors.asFloatBuffer();
    mRectColors.put(WorldLayoutData.RECT_COLORS);
    mRectColors.position(0);

    ByteBuffer bbFoundColors = ByteBuffer.allocateDirect(WorldLayoutData.RECT_FOUND_COLORS.length * 4);
    bbFoundColors.order(ByteOrder.nativeOrder());
    mRectFoundColors = bbFoundColors.asFloatBuffer();
    mRectFoundColors.put(WorldLayoutData.RECT_FOUND_COLORS);
    mRectFoundColors.position(0);

    ByteBuffer bbNormals = ByteBuffer.allocateDirect(WorldLayoutData.RECT_NORMALS.length * 4);
    bbNormals.order(ByteOrder.nativeOrder());
    mRectNormals = bbNormals.asFloatBuffer();
    mRectNormals.put(WorldLayoutData.RECT_NORMALS);
    mRectNormals.position(0);

    ByteBuffer bbTextureCoordinates = ByteBuffer.allocateDirect(WorldLayoutData.RECT_TEX_COORDS.length * 4);
    bbTextureCoordinates.order(ByteOrder.nativeOrder());
    mRectTexCoords = bbTextureCoordinates.asFloatBuffer();
    mRectTexCoords.put(WorldLayoutData.RECT_TEX_COORDS);
    mRectTexCoords.position(0);

    // make a floor
    ByteBuffer bbFloorVertices = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_COORDS.length * 4);
    bbFloorVertices.order(ByteOrder.nativeOrder());
    mFloorVertices = bbFloorVertices.asFloatBuffer();
    mFloorVertices.put(WorldLayoutData.FLOOR_COORDS);
    mFloorVertices.position(0);

    ByteBuffer bbFloorNormals = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_NORMALS.length * 4);
    bbFloorNormals.order(ByteOrder.nativeOrder());
    mFloorNormals = bbFloorNormals.asFloatBuffer();
    mFloorNormals.put(WorldLayoutData.FLOOR_NORMALS);
    mFloorNormals.position(0);

    ByteBuffer bbFloorColors = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_COLORS.length * 4);
    bbFloorColors.order(ByteOrder.nativeOrder());
    mFloorColors = bbFloorColors.asFloatBuffer();
    mFloorColors.put(WorldLayoutData.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.flat_fragment);

    mGlProgram = GLES20.glCreateProgram();
    GLES20.glAttachShader(mGlProgram, vertexShader);
    GLES20.glAttachShader(mGlProgram, gridShader);
    GLES20.glLinkProgram(mGlProgram);

    GLES20.glEnable(GLES20.GL_DEPTH_TEST);

    Matrix.setIdentityM(mModelFloor, 0);
    Matrix.translateM(mModelFloor, 0, 0, -FLOOR_DEPTH, 0); // Floor appears below user

    checkGLError("onSurfaceCreated");
}