Java Code Examples for java.nio.FloatBuffer#hasRemaining()

The following examples show how to use java.nio.FloatBuffer#hasRemaining() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TrackingWorker.java    From procamtracker with GNU General Public License v2.0 6 votes vote down vote up
private IplImage getMonitorImage(IplImage floatImage, IplImage maskImage, int pyramidLevel) {
    final int inChannels = floatImage.nChannels();
    final int outChannels = 3;
    final int[] order = inChannels == 3 ? new int[] { 0, 1, 2 } : new int[] { 2, 1, 0 };

    if (monitorImages[pyramidLevel] == null) {
        monitorImages[pyramidLevel] = IplImage.create(floatImage.width(), floatImage.height(), IPL_DEPTH_8U, outChannels);
    }

    FloatBuffer in  = floatImage.getFloatBuffer();
    ByteBuffer mask = maskImage == null ? null : maskImage.getByteBuffer();
    ByteBuffer out  = monitorImages[pyramidLevel].getByteBuffer();
    float[] buffer = new float[4];
    while (in.hasRemaining() && out.hasRemaining() && (mask == null || mask.hasRemaining())) {
        byte m = mask == null ? (byte)0xFF : mask.get();
        for (int z = 0; z < inChannels; z++) {
            buffer[z] = Math.max(0, Math.min(1, Math.abs(in.get())));
        }
        for (int z = 0; z < outChannels; z++) {
            out.put((byte)(m == 0 ? 0 : Math.round(buffer[order[z]]*255)));
        }
    }
    return monitorImages[pyramidLevel];
}
 
Example 2
Source File: DOMOutputCapsule.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void write(FloatBuffer value, String name, FloatBuffer defVal) throws IOException {
    if (value == null) {
        return;
    }

    Element el = appendElement(name);
    el.setAttribute("size", String.valueOf(value.limit()));
    StringBuilder buf = new StringBuilder();
    int pos = value.position();
    value.rewind();
    int ctr = 0;
    while (value.hasRemaining()) {
        ctr++;
        buf.append(value.get());
        buf.append(" ");
    }
    if (ctr != value.limit())
        throw new IOException("'" + name
            + "' buffer contention resulted in write data consistency.  "
            + ctr + " values written when should have written "
            + value.limit());
    buf.setLength(Math.max(0, buf.length() - 1));
    value.position(pos);
    el.setAttribute(dataAttributeName, buf.toString());
    currentElement = (Element) el.getParentNode();
}
 
Example 3
Source File: BoundingBox.java    From react-native-3d-model-view with MIT License 5 votes vote down vote up
public static BoundingBox create(String id, FloatBuffer vertexBuffer, float[] modelMatrix) {
    float xMin = Float.MAX_VALUE, xMax = Float.MIN_VALUE, yMin = Float.MAX_VALUE, yMax = Float.MIN_VALUE, zMin = Float.MAX_VALUE, zMax = Float.MIN_VALUE;
    vertexBuffer = vertexBuffer.asReadOnlyBuffer();
    vertexBuffer.position(0);
    while (vertexBuffer.hasRemaining()) {
        float vertexx = vertexBuffer.get();
        float vertexy = vertexBuffer.get();
        float vertexz = vertexBuffer.get();
        if (vertexx < xMin) {
            xMin = vertexx;
        }
        if (vertexx > xMax) {
            xMax = vertexx;
        }
        if (vertexy < yMin) {
            yMin = vertexy;
        }
        if (vertexy > yMax) {
            yMax = vertexy;
        }
        if (vertexz < zMin) {
            zMin = vertexz;
        }
        if (vertexz > zMax) {
            zMax = vertexz;
        }
    }
    float[] min = new float[]{xMin, yMin, zMin, 1};
    float[] max = new float[]{xMax, yMax, zMax, 1};
    Matrix.multiplyMV(min,0,modelMatrix,0,min,0);
    Matrix.multiplyMV(max,0,modelMatrix,0,max,0);
    return new BoundingBox(id, min[0], max[0], min[1], max[1], min[2], max[2]);
}
 
Example 4
Source File: Utils.java    From sciview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static public List<Vector3f> getVertexList(Mesh m) {
    List<Vector3f> l = new ArrayList<>();

    FloatBuffer vb = m.getVertices();
    while( vb.hasRemaining() ) {
        float x = vb.get();
        float y = vb.get();
        float z = vb.get();
        l.add( new Vector3f(x, y, z) );
    }

    vb.flip();

    return l;
}
 
Example 5
Source File: BoundingBox.java    From geoar-app with Apache License 2.0 5 votes vote down vote up
@Deprecated
private void generateBoundingBox() {
	// get vertices of geometry
	FloatBuffer vertices = null; // geometry.getVerticesBuffer();
	vertices.rewind(); // set position to zero

	float[] min = { Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE };
	float[] max = { Float.MIN_VALUE, Float.MIN_VALUE, Float.MIN_VALUE };

	float[] vertex = new float[3];

	while (vertices.hasRemaining()) {
		vertex[0] = vertices.get(); // x
		vertex[1] = vertices.get(); // y
		vertex[2] = vertices.get(); // z

		min[0] = Math.min(min[0], vertex[0]);
		max[0] = Math.max(max[0], vertex[0]);
		min[1] = Math.min(min[1], vertex[1]);
		max[1] = Math.max(max[1], vertex[1]);
		min[2] = Math.min(min[2], vertex[2]);
		max[2] = Math.max(max[2], vertex[2]);
	}

	boundingPoints[0] = new float[] { min[0], min[1], min[2] }; // -x,-y,-z
	boundingPoints[1] = new float[] { min[0], min[1], max[2] }; // -x,-y,z
	boundingPoints[2] = new float[] { max[0], min[1], max[2] }; // x,-y,z
	boundingPoints[3] = new float[] { max[0], min[1], min[2] }; // x,-y,-z

	boundingPoints[4] = new float[] { min[0], max[1], min[2] }; // -x, y, -z
	boundingPoints[5] = new float[] { min[0], max[1], max[2] }; // -x, y, z
	boundingPoints[6] = new float[] { max[0], max[1], max[2] }; // ...
	boundingPoints[7] = new float[] { max[0], max[1], min[2] };
}
 
Example 6
Source File: DOMOutputCapsule.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void write(FloatBuffer value, String name, FloatBuffer defVal) throws IOException {
    if (value == null) {
        return;
    }

    Element el = appendElement(name);
    el.setAttribute("size", String.valueOf(value.limit()));
    StringBuilder buf = new StringBuilder();
    int pos = value.position();
    value.rewind();
    int ctr = 0;
    while (value.hasRemaining()) {
        ctr++;
        buf.append(value.get());
        buf.append(" ");
    }
    if (ctr != value.limit()) {
        throw new IOException("'" + name
            + "' buffer contention resulted in write data consistency.  "
            + ctr + " values written when should have written "
            + value.limit());
    }
    
    if (buf.length() > 0) {
        //remove last space
        buf.setLength(buf.length() - 1);
    }
    
    value.position(pos);
    el.setAttribute(dataAttributeName, buf.toString());
    currentElement = (Element) el.getParentNode();
}
 
Example 7
Source File: BoundingBox.java    From android-3D-model-viewer with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static BoundingBox create(String id, FloatBuffer vertexBuffer, float[] modelMatrix) {
    float xMin = Float.MAX_VALUE, xMax = -Float.MAX_VALUE, yMin = Float.MAX_VALUE, yMax = -Float.MAX_VALUE, zMin =
            Float.MAX_VALUE, zMax = -Float.MAX_VALUE;
    vertexBuffer = vertexBuffer.asReadOnlyBuffer();
    vertexBuffer.position(0);
    while (vertexBuffer.hasRemaining()) {
        float vertexx = vertexBuffer.get();
        float vertexy = vertexBuffer.get();
        float vertexz = vertexBuffer.get();
        if (vertexx < xMin) {
            xMin = vertexx;
        }
        if (vertexx > xMax) {
            xMax = vertexx;
        }
        if (vertexy < yMin) {
            yMin = vertexy;
        }
        if (vertexy > yMax) {
            yMax = vertexy;
        }
        if (vertexz < zMin) {
            zMin = vertexz;
        }
        if (vertexz > zMax) {
            zMax = vertexz;
        }
    }
    float[] min = new float[]{xMin, yMin, zMin, 1};
    float[] max = new float[]{xMax, yMax, zMax, 1};
    Matrix.multiplyMV(min,0,modelMatrix,0,min,0);
    Matrix.multiplyMV(max,0,modelMatrix,0,max,0);
    return new BoundingBox(id, min[0], max[0], min[1], max[1], min[2], max[2]);
}
 
Example 8
Source File: TestArrayPerf.java    From junion with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void mult(FloatBuffer a, FloatBuffer b, FloatBuffer store) {
	a.clear(); b.clear(); store.clear();
	while(a.hasRemaining()) {
		store.put(a.get()*b.get());
	}
}
 
Example 9
Source File: MeshConverter.java    From sciview with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static graphics.scenery.Mesh toScenery( final net.imagej.mesh.Mesh mesh, final boolean center ) {
        final int vCount = //
                ( int ) Math.min( Integer.MAX_VALUE, mesh.vertices().size() );
        final int tCount = //
                ( int ) Math.min( Integer.MAX_VALUE, mesh.triangles().size() );

        // Convert the mesh to an NIO-backed one.
        BufferMesh bufferMesh = new BufferMesh( vCount, tCount );

        Meshes.calculateNormals( mesh, bufferMesh );// Force recalculation of normals because not all meshes are safe

//        if( mesh instanceof BufferMesh ) {
//            // TODO: Check that BufferMesh capacities & positions are compatible.
//            // Need to double check what Scenery assumes about the given buffers.
//            bufferMesh = ( BufferMesh ) mesh;
//        } else {
//            // Copy the mesh into a BufferMesh.
//            bufferMesh = new BufferMesh( vCount, tCount );
//            Meshes.copy( mesh, bufferMesh );
//        }

        // Extract buffers from the BufferMesh.
        final FloatBuffer verts = bufferMesh.vertices().verts();
        final FloatBuffer vNormals = bufferMesh.vertices().normals();
        final FloatBuffer texCoords = bufferMesh.vertices().texCoords();
        final IntBuffer indices = bufferMesh.triangles().indices();

        // Prepare the buffers for Scenery to ingest them.
        // Sets capacity to equal position, then resets position to 0.
        verts.flip();
        if( center ) {// Do 2 passes, 1 to find center, and the other to shift
            double[] v = new double[] {0.0,0.0,0.0};// used for tally of coords and mean
            int coord = 0;// coordinate index
            int n = 0;// num verts
            while( verts.hasRemaining() ) {
                v[coord] += verts.get();
                if( coord == 0 ) n++;
                coord = ( coord + 1 ) % 3;
            }
            verts.flip();
            // Take average
            for( int k = 0; k < 3; k++ ) v[k] /= n;
            // Center shift
            coord = 0;
            float val;
            while( verts.hasRemaining() ) {
                val = verts.get();
                // Write
                verts.put(verts.position()-1,val-(float)v[coord]);
                coord = ( coord + 1 ) % 3;
            }
            verts.flip();
        }

        vNormals.flip();
        texCoords.flip();
        indices.flip();

        // Create and populate the Scenery mesh.
        graphics.scenery.Mesh scMesh = new graphics.scenery.Mesh();
        scMesh.setVertices( verts );
        scMesh.setNormals( vNormals );
        scMesh.setTexcoords( texCoords );
        scMesh.setIndices( indices );


        scMesh.setBoundingBox( scMesh.generateBoundingBox() );
        scMesh.setDirty( true );

        return scMesh;
    }
 
Example 10
Source File: ViewBuffers.java    From java-core-learning-example with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[]{0,0,0,0,0,0,0,'a'});
    bb.rewind();
    System.out.print("Byte Buffer ");
    while (bb.hasRemaining())
        System.out.print(bb.position() + " -> " + bb.get() + ", ");
    System.out.println();

    CharBuffer cb = ((ByteBuffer)bb.rewind()).asCharBuffer();
    System.out.print("Char Buffer ");
    while (cb.hasRemaining())
        System.out.print(cb.position() + " -> " + cb.get() + ", ");
    System.out.println();

    ShortBuffer sb = ((ByteBuffer)bb.rewind()).asShortBuffer();
    System.out.print("Short Buffer ");
    while (sb.hasRemaining())
        System.out.print(sb.position() + " -> " + sb.get() + ", ");
    System.out.println();

    IntBuffer ib = ((ByteBuffer)bb.rewind()).asIntBuffer();
    System.out.print("Int Buffer ");
    while (ib.hasRemaining())
        System.out.print(ib.position() + " -> " + ib.get());
    System.out.println();

    FloatBuffer fb = ((ByteBuffer)bb.rewind()).asFloatBuffer();
    System.out.print("Float Buffer ");
    while (fb.hasRemaining())
        System.out.print(fb.position() + " -> " + fb.get() + ", ");
    System.out.println();

    LongBuffer lb = ((ByteBuffer)bb.rewind()).asLongBuffer();
    System.out.print("Long Buffer ");
    while (lb.hasRemaining())
        System.out.print(lb.position() + " -> " + lb.get() + ", ");
    System.out.println();

    DoubleBuffer db = ((ByteBuffer)bb.rewind()).asDoubleBuffer();
    System.out.print("Double Buffer ");
    while (db.hasRemaining())
        System.out.print(db.position() + " -> " + db.get() + ", ");
    System.out.println();
}
 
Example 11
Source File: NADCON.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Loads latitude or longitude shifts data. This method should be invoked twice:
 *
 * <ol>
 *   <li>On an instance created for the latitude shifts file with a {@code latitude} argument set to null.</li>
 *   <li>On an instance created for the longitude shifts file with a {@code latitude} argument set to the
 *       instance created in the previous step.</li>
 * </ol>
 *
 * The result is stored in the {@link #grid} field.
 *
 * @param fb               a {@code FloatBuffer} view over the full {@link #buffer} range.
 * @param latitudeShifts   the previously loaded latitude shifts, or {@code null} if not yet loaded.
 * @param longitudeShifts  the file for the longitude grid.
 */
final void readGrid(final FloatBuffer fb, final Loader latitudeShifts, final Path longitudeShifts)
        throws IOException, FactoryException, NoninvertibleTransformException
{
    final int dim;
    final double scale;
    if (latitudeShifts == null) {
        dim   = 1;                                              // Dimension of latitudes.
        scale = DEGREES_TO_SECONDS * Δy;                        // NADCON shifts are positive north.
        grid  = new DatumShiftGridFile.Float<>(2, Units.DEGREE, Units.DEGREE,
                true, x0, y0, Δx, Δy, nx, ny, PARAMETERS, file, longitudeShifts);
        grid.accuracy = SECOND_PRECISION / DEGREES_TO_SECONDS;
    } else {
        if (x0 != latitudeShifts.x0 || Δx != latitudeShifts.Δx || nx != latitudeShifts.nx ||
            y0 != latitudeShifts.y0 || Δy != latitudeShifts.Δy || ny != latitudeShifts.ny || nz != latitudeShifts.nz)
        {
            throw new FactoryException(Errors.format(Errors.Keys.MismatchedGridGeometry_2,
                    latitudeShifts.file.getFileName(), file.getFileName()));
        }
        dim   = 0;                                              // Dimension of longitudes
        scale = -DEGREES_TO_SECONDS * Δx;                       // NADCON shifts are positive west.
        grid  = latitudeShifts.grid;                            // Continue writing in existing grid.
    }
    final float[] array = grid.offsets[dim];
    if (ascii != null) {
        for (int i=0; i<array.length; i++) {
            array[i] = (float) (Double.parseDouble(nextWord()) / scale);
        }
    } else {
        /*
         * Transfer all data from the FloatBuffer to the float[] array, except one float at the beginning
         * of every row which must be skipped. That skipped float value is not a translation value and is
         * expected to be always zero.
         */
        syncView(fb);
        int forCurrentRow = 0;
        for (int i=0; i<array.length;) {
            if (forCurrentRow == 0) {
                if (!fb.hasRemaining()) {
                    fillBuffer(fb);
                }
                if (fb.get() != 0) {
                    throw unexpectedFormat();
                }
                forCurrentRow = nx;
            }
            int remaining = fb.remaining();
            if (remaining == 0) {
                fillBuffer(fb);
                remaining = fb.remaining();
            }
            final int n = Math.min(forCurrentRow, remaining);
            fb.get(array, i, n);
            forCurrentRow -= n;
            i += n;
        }
        /*
         * Convert seconds to degrees for consistency with the unit declared at the beginning of this method,
         * then divide by cell size for consistency with the 'isCellRatio = true' configuration.
         */
        for (int i=0; i<array.length; i++) {
            array[i] /= scale;
        }
    }
}