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

The following examples show how to use java.nio.FloatBuffer#wrap() . 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: TestPointerToBuffer.java    From jcuda with MIT License 6 votes vote down vote up
@Test
public void testWithSliceAtOffset2()
{
    float array[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
    FloatBuffer arrayBuffer = FloatBuffer.wrap(array);
    FloatBuffer directBuffer = 
        ByteBuffer.allocateDirect(array.length * Sizeof.FLOAT).
            order(ByteOrder.nativeOrder()).asFloatBuffer();
    directBuffer.put(array);
    directBuffer.rewind();
    
    arrayBuffer.position(2);
    directBuffer.position(2);

    FloatBuffer arraySlice = arrayBuffer.slice();
    FloatBuffer directSlice = directBuffer.slice();
    
    assertTrue(copyWithTo      (arraySlice,  4, new float[] {0, 1, 2, 3}));
    assertTrue(copyWithToBuffer(arraySlice,  4, new float[] {2, 3, 4, 5}));
    assertTrue(copyWithTo      (directSlice, 4, new float[] {2, 3, 4, 5}));
    assertTrue(copyWithToBuffer(directSlice, 4, new float[] {2, 3, 4, 5}));
}
 
Example 2
Source File: TestPointerToBuffer.java    From jcuda with MIT License 6 votes vote down vote up
@Test
public void testWithPosition2()
{
    float array[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
    FloatBuffer arrayBuffer = FloatBuffer.wrap(array);
    FloatBuffer directBuffer = 
        ByteBuffer.allocateDirect(array.length * Sizeof.FLOAT).
            order(ByteOrder.nativeOrder()).asFloatBuffer();
    directBuffer.put(array);
    directBuffer.rewind();
    
    arrayBuffer.position(2);
    directBuffer.position(2);
    
    assertTrue(copyWithTo      (arrayBuffer,  4, new float[] {0, 1, 2, 3}));
    assertTrue(copyWithToBuffer(arrayBuffer,  4, new float[] {2, 3, 4, 5}));
    assertTrue(copyWithTo      (directBuffer, 4, new float[] {0, 1, 2, 3}));
    assertTrue(copyWithToBuffer(directBuffer, 4, new float[] {2, 3, 4, 5}));
}
 
Example 3
Source File: SmoothFilter.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int size) {
	float[] data = buffer.array();
	float[] retval = new float[data.length];

	for (int y = this.radius; y < size - this.radius; y++) {
		for (int x = this.radius; x < size - this.radius; x++) {
			int idx = y * size + x;
			float n = 0;
			for (int i = -this.radius; i < this.radius + 1; i++) {
				for (int j = -this.radius; j < this.radius + 1; j++) {
					n += data[(y + i) * size + x + j];
				}
			}
			retval[idx] = this.effect * n / (4 * this.radius * (this.radius + 1) + 1) + (1 - this.effect) * data[idx];
		}
	}

	return FloatBuffer.wrap(retval);
}
 
Example 4
Source File: SmoothFilter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int size) {
	float[] data = buffer.array();
	float[] retval = new float[data.length];

	for (int y = this.radius; y < size - this.radius; y++) {
		for (int x = this.radius; x < size - this.radius; x++) {
			int idx = y * size + x;
			float n = 0;
			for (int i = -this.radius; i < this.radius + 1; i++) {
				for (int j = -this.radius; j < this.radius + 1; j++) {
					n += data[(y + i) * size + x + j];
				}
			}
			retval[idx] = this.effect * n / (4 * this.radius * (this.radius + 1) + 1) + (1 - this.effect) * data[idx];
		}
	}

	return FloatBuffer.wrap(retval);
}
 
Example 5
Source File: NDArrayCreationOpTest.java    From djl with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateCSRMatrix() {
    try (NDManager manager = NDManager.newBaseManager()) {
        float[] expected = {7, 8, 9};
        FloatBuffer buf = FloatBuffer.wrap(expected);
        long[] indptr = {0, 2, 2, 3};
        long[] indices = {0, 2, 1};
        NDArray nd = manager.createCSR(buf, indptr, indices, new Shape(3, 4));
        float[] array = nd.toFloatArray();
        Assert.assertEquals(array[0], expected[0]);
        Assert.assertEquals(array[2], expected[1]);
        Assert.assertEquals(array[9], expected[2]);
        Assert.assertTrue(nd.isSparse());
    }
}
 
Example 6
Source File: DataBuffers.java    From java with Apache License 2.0 5 votes vote down vote up
/**
 * Create a buffer from an array of floats into a data buffer.
 *
 * @param array array of floats
 * @param readOnly true if the buffer created must be read-only
 * @param makeCopy true if the array must be copied, false will wrap the provided array
 * @return a new buffer
 */
public static FloatDataBuffer of(float[] array, boolean readOnly, boolean makeCopy) {
  float[] bufferArray = makeCopy ? Arrays.copyOf(array, array.length) : array;
  if (RawDataBufferFactory.canBeUsed()) {
    return RawDataBufferFactory.create(bufferArray, readOnly);
  }
  FloatBuffer buf = FloatBuffer.wrap(bufferArray);
  return NioDataBufferFactory.create(readOnly ? buf.asReadOnlyBuffer() : buf);
}
 
Example 7
Source File: ObjectDetector.java    From tensorflow-example-java with Do What The F*ck You Want To Public License 5 votes vote down vote up
/**
 * Executes graph on the given preprocessed image
 * @param image preprocessed image
 * @return output tensor returned by tensorFlow
 */
private float[] executeYOLOGraph(final Tensor<Float> image) {
    try (Graph graph = new Graph()) {
        graph.importGraphDef(GRAPH_DEF);
        try (Session s = new Session(graph);
            Tensor<Float> result = s.runner().feed("input", image).fetch("output").run().get(0).expect(Float.class)) {
            float[] outputTensor = new float[YOLOClassifier.getInstance().getOutputSizeByShape(result)];
            FloatBuffer floatBuffer = FloatBuffer.wrap(outputTensor);
            result.writeTo(floatBuffer);
            return outputTensor;
        }
    }
}
 
Example 8
Source File: CameraListener.java    From ShaderEditor with MIT License 5 votes vote down vote up
private void setOrientationAndFlip(int orientation) {
	switch (orientation) {
		default:
		case 0:
			orientationMatrix = FloatBuffer.wrap(new float[]{
					1f, 0f,
					0f, -1f,
			});
			addent[0] = 0f;
			addent[1] = 1f;
			break;
		case 90:
			orientationMatrix = FloatBuffer.wrap(new float[]{
					0f, -1f,
					-1f, 0f,
			});
			addent[0] = 1f;
			addent[1] = 1f;
			break;
		case 180:
			orientationMatrix = FloatBuffer.wrap(new float[]{
					-1f, 0f,
					0f, 1f,
			});
			addent[0] = 1f;
			addent[1] = 0f;
			break;
		case 270:
			orientationMatrix = FloatBuffer.wrap(new float[]{
					0f, 1f,
					1f, 0f,
			});
			addent[0] = 0f;
			addent[1] = 0f;
			break;
	}
}
 
Example 9
Source File: CefRenderer.java    From pandomium with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
protected void render(GL2 gl2) {
    if (use_draw_pixels_ || view_width_ == 0 || view_height_ == 0) {
        return;
    }

    assert (initialized_context_ != null);

    final float[] vertex_data = {
            //tu,   tv,     x,     y,    z
            0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f };
    FloatBuffer vertices = FloatBuffer.wrap(vertex_data);

    gl2.glClear(gl2.GL_COLOR_BUFFER_BIT | gl2.GL_DEPTH_BUFFER_BIT);

    gl2.glMatrixMode(gl2.GL_MODELVIEW);
    gl2.glLoadIdentity();

    // Match GL units to screen coordinates.
    gl2.glViewport(0, 0, view_width_, view_height_);
    gl2.glMatrixMode(gl2.GL_PROJECTION);
    gl2.glLoadIdentity();

    // Draw the background gradient.
    gl2.glPushAttrib(gl2.GL_ALL_ATTRIB_BITS);
    gl2.glBegin(gl2.GL_QUADS);
    gl2.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);  // red
    gl2.glVertex2f(-1.0f, -1.0f);
    gl2.glVertex2f(1.0f, -1.0f);
    gl2.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);  // blue
    gl2.glVertex2f(1.0f, 1.0f);
    gl2.glVertex2f(-1.0f, 1.0f);
    gl2.glEnd();
    gl2.glPopAttrib();

    // Rotate the view based on the mouse spin.
    if (spin_x_ != 0) {
        gl2.glRotatef(-spin_x_, 1.0f, 0.0f, 0.0f);
    }
    if (spin_y_ != 0) {
        gl2.glRotatef(-spin_y_, 0.0f, 1.0f, 0.0f);
    }

    if (transparent_) {
        // Alpha blending style. Texture values have premultiplied alpha.
        gl2.glBlendFunc(gl2.GL_ONE, gl2.GL_ONE_MINUS_SRC_ALPHA);

        // Enable alpha blending.
        gl2.glEnable(gl2.GL_BLEND);
    }

    // Enable 2D textures.
    gl2.glEnable(gl2.GL_TEXTURE_2D);

    // Draw the facets with the texture.
    assert (texture_id_[0] != 0);
    gl2.glBindTexture(gl2.GL_TEXTURE_2D, texture_id_[0]);
    gl2.glInterleavedArrays(gl2.GL_T2F_V3F, 0, vertices);
    gl2.glDrawArrays(gl2.GL_QUADS, 0, 4);

    // Disable 2D textures.
    gl2.glDisable(gl2.GL_TEXTURE_2D);

    if (transparent_) {
        // Disable alpha blending.
        gl2.glDisable(gl2.GL_BLEND);
    }
}
 
Example 10
Source File: PerturbFilter.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer data, int workSize) {
	float[] arr = data.array();
	int origSize = (int) Math.ceil(workSize / (2 * this.magnitude + 1));
	int offset = (workSize - origSize) / 2;
	Logger.getLogger(PerturbFilter.class.getCanonicalName()).info(
			"Found origSize : " + origSize + " and offset: " + offset + " for workSize : " + workSize + " and magnitude : "
					+ this.magnitude);
	float[] retval = new float[workSize * workSize];
	float[] perturbx = new FractalSum().setOctaves(8).setScale(5f).getBuffer(sx, sy, base, workSize).array();
	float[] perturby = new FractalSum().setOctaves(8).setScale(5f).getBuffer(sx, sy, base + 1, workSize).array();
	for (int y = 0; y < workSize; y++) {
		for (int x = 0; x < workSize; x++) {
			// Perturb our coordinates
			float noisex = perturbx[y * workSize + x];
			float noisey = perturby[y * workSize + x];

			int px = (int) (origSize * noisex * this.magnitude);
			int py = (int) (origSize * noisey * this.magnitude);

			float c00 = arr[this.wrap(y - py, workSize) * workSize + this.wrap(x - px, workSize)];
			float c01 = arr[this.wrap(y - py, workSize) * workSize + this.wrap(x + px, workSize)];
			float c10 = arr[this.wrap(y + py, workSize) * workSize + this.wrap(x - px, workSize)];
			float c11 = arr[this.wrap(y + py, workSize) * workSize + this.wrap(x + px, workSize)];

			float c0 = ShaderUtils.mix(c00, c01, noisex);
			float c1 = ShaderUtils.mix(c10, c11, noisex);
			retval[y * workSize + x] = ShaderUtils.mix(c0, c1, noisey);
		}
	}
	return FloatBuffer.wrap(retval);
}
 
Example 11
Source File: YOLO.java    From cineast with MIT License 5 votes vote down vote up
/**
 * Executes graph on the given preprocessed image
 *
 * @param image preprocessed image
 * @return output tensor returned by tensorFlow
 */
private float[] executeYOLOGraph(final Tensor<Float> image) {

  Tensor<Float> result = yoloSession.runner().feed("input", image).fetch("output").run().get(0)
      .expect(Float.class);

  float[] outputTensor = new float[getOutputSizeByShape(result)];
  FloatBuffer floatBuffer = FloatBuffer.wrap(outputTensor);
  result.writeTo(floatBuffer);
  result.close();
  return outputTensor;

}
 
Example 12
Source File: PathOverlay.java    From clearvolume with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void init(	GL pGL,
					DisplayRequestInterface pDisplayRequestInterface)
{
	// box display: construct the program and related objects
	try
	{
		mBoxGLProgram = GLProgram.buildProgram(	pGL,
												PathOverlay.class,
												new String[]
												{	"shaders/path_vert.glsl",
													"shaders/path_geom.glsl",
													"shaders/path_frag.glsl" });

		mPath = new ClearGeometryObject(mBoxGLProgram,
										3,
										GL.GL_LINE_STRIP);
		mPath.setDynamic(true);

		mPath.setVerticesAndCreateBuffer(mPathPoints.getFloatBuffer());
		mStartColor = FloatBuffer.wrap(new float[]
		{ 1.0f, 0.0f, 0.0f, 1.0f });

	}
	catch (final Throwable e)
	{
		e.printStackTrace();
	}
}
 
Example 13
Source File: DLHelpers.java    From orbit-image-analysis with GNU General Public License v3.0 4 votes vote down vote up
public static RawDetections executeInceptionGraph(final Session s, final Tensor<Float> input, final int inputWidth, final int inputHeight, final int maxDetections, final int maskWidth, final int maskHeight) {
    // image metas
    //  meta = np.array(
    //        [image_id] +                  # size=1
    //        list(original_image_shape) +  # size=3
    //        list(image_shape) +           # size=3
    //        list(window) +                # size=4 (y1, x1, y2, x2) in image cooredinates
    //        [scale[0]] +                     # size=1 NO LONGER, I dont have time to correct this properly so take only the first element
    //        list(active_class_ids)        # size=num_classes
    //    )
    final FloatBuffer metas = FloatBuffer.wrap(new float[]{
            0,
            inputWidth,inputHeight,3,
            inputWidth,inputHeight,3,
            0,0,inputWidth,inputHeight,
            1,
            0,0
    });
    final Tensor<Float> meta_data = Tensor.create(new long[]{1,14},metas);

    List<Tensor<?>> res = s
            .runner()
            .feed("input_image", input)
            .feed("input_image_meta", meta_data)
            .feed("input_anchors", getAnchors(inputWidth))  // dtype float and shape [?,?,4]
            .fetch("mrcnn_detection/Reshape_1")   // mrcnn_mask/Reshape_1   mrcnn_detection/Reshape_1    mrcnn_bbox/Reshape     mrcnn_class/Reshape_1
            .fetch("mrcnn_mask/Reshape_1")
            .run();

    float[][][] res_detection = new float[1][maxDetections][6];   // mrcnn_detection/Reshape_1   -> y1,x1,y2,x2,class_id,probability (ordered desc)
    float[][][][][] res_mask = new float[1][maxDetections][maskHeight][maskWidth][2];   // mrcnn_mask/Reshape_1
    Tensor<Float> mrcnn_detection = res.get(0).expect(Float.class);
    Tensor<Float> mrcnn_mask = res.get(1).expect(Float.class);
    mrcnn_detection.copyTo(res_detection);
    mrcnn_mask.copyTo(res_mask);

    RawDetections rawDetections = new RawDetections();
    rawDetections.objectBB = res_detection;
    rawDetections.masks = res_mask;
    return rawDetections;
}
 
Example 14
Source File: PathOverlay.java    From clearvolume with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setStartEndColor(float[] startColor, float[] endColor)
{
	mStartColor = FloatBuffer.wrap(startColor);
	mEndColor = FloatBuffer.wrap(endColor);
}
 
Example 15
Source File: TestObjAlignmentV2.java    From JglTF with MIT License 4 votes vote down vote up
/**
 * Test whether the padding bytes are inserted that are necessary to
 * align the accessors to the size of their component type.
 */
@Test
public void testObjAlignment() 
{
    // Create an OBJ consisting of a single triangle
    IntBuffer indices = IntBuffer.wrap(new int[] { 0,1,2 });
    FloatBuffer vertices = FloatBuffer.wrap(new float[] 
    {
        0.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
    });
    Obj obj = Objs.createFromIndexedTriangleData(
        indices, vertices, null, null);
    
    // Create the GltfData, using GL_UNSIGNED_SHORT indices, causing
    // an offset of 6 bytes. (This means that 2 padding bytes will
    // have to be inserted for the subsequent vertex positions data)
    ObjGltfAssetCreatorV2 objGltfAssetCreator = new ObjGltfAssetCreatorV2();
    objGltfAssetCreator.setIndicesComponentType(
        GltfConstants.GL_UNSIGNED_SHORT);
    GltfAssetV2 gltfAsset = 
        objGltfAssetCreator.convert(obj, null, "test", null);
    
    // Obtain the glTF and the accessor and buffer view of the vertices
    GlTF gltf = gltfAsset.getGltf();

    List<Accessor> accessors = gltf.getAccessors();
    Accessor accessor = accessors.get(1); 
    
    List<BufferView> bufferViews = gltf.getBufferViews();
    BufferView bufferView = bufferViews.get(0);
    
    // Compute the byte offset of the accessor referring to the
    // buffer view, and the total byte offset referring to the buffer
    int accessorByteOffset = accessor.getByteOffset();
    int totalByteOffset = 
        accessor.getByteOffset() + bufferView.getByteOffset();
    
    // Check whether the data is properly aligned
    final int sizeOfFloat = 4;
    assertEquals("Byte offset must be divisble by 4",
        0, accessorByteOffset % sizeOfFloat);
    assertEquals("Total byte offset must be divisible by 4",
        0, totalByteOffset % sizeOfFloat);
    
}
 
Example 16
Source File: TestObjAlignmentV1.java    From JglTF with MIT License 4 votes vote down vote up
/**
 * Test whether the padding bytes are inserted that are necessary to
 * align the accessors to the size of their component type.
 */
@Test
public void testObjAlignment() 
{
    // Create an OBJ consisting of a single triangle
    IntBuffer indices = IntBuffer.wrap(new int[] { 0,1,2 });
    FloatBuffer vertices = FloatBuffer.wrap(new float[] 
    {
        0.0f, 0.0f, 0.0f,
        1.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
    });
    Obj obj = Objs.createFromIndexedTriangleData(
        indices, vertices, null, null);
    
    // Create the GltfData, using GL_UNSIGNED_SHORT indices, causing
    // an offset of 6 bytes. (This means that 2 padding bytes will
    // have to be inserted for the subsequent vertex positions data)
    ObjGltfAssetCreatorV1 objGltfAssetCreator = new ObjGltfAssetCreatorV1();
    objGltfAssetCreator.setIndicesComponentType(
        GltfConstants.GL_UNSIGNED_SHORT);
    GltfAssetV1 gltfAsset = 
        objGltfAssetCreator.convert(obj, null, "test", null);
    
    // Obtain the glTF and the accessor and buffer view of the vertices
    GlTF gltf = gltfAsset.getGltf();

    Map<String, Accessor> accessors = gltf.getAccessors();
    Accessor accessor = accessors.get("obj_positions"); 
    
    Map<String, BufferView> bufferViews = gltf.getBufferViews();
    BufferView bufferView = bufferViews.get("obj_attributes_bufferView");
    
    // Compute the byte offset of the accessor referring to the
    // buffer view, and the total byte offset referring to the buffer
    int accessorByteOffset = accessor.getByteOffset();
    int totalByteOffset = 
        accessor.getByteOffset() + bufferView.getByteOffset();
    
    // Check whether the data is properly aligned
    final int sizeOfFloat = 4;
    assertEquals("Byte offset must be divisble by 4",
        0, accessorByteOffset % sizeOfFloat);
    assertEquals("Total byte offset must be divisible by 4",
        0, totalByteOffset % sizeOfFloat);
    
}
 
Example 17
Source File: InstSegMaskRCNN.java    From orbit-image-analysis with GNU General Public License v3.0 4 votes vote down vote up
public RawDetections executeInceptionGraph(Session s, Tensor<Float> input) {
        // image metas
        //  meta = np.array(
        //        [image_id] +                  # size=1
        //        list(original_image_shape) +  # size=3
        //        list(image_shape) +           # size=3
        //        list(window) +                # size=4 (y1, x1, y2, x2) in image cooredinates
        //        [scale[0]] +                     # size=1 NO LONGER, I dont have time to correct this properly so take only the first element
        //        list(active_class_ids)        # size=num_classes
        //    )
        final FloatBuffer metas = FloatBuffer.wrap(new float[]{
                0,
                512,512,3,
                512,512,3,
                0,0,512,512,
                1,
                0,0
        });
        final Tensor<Float> meta_data = Tensor.create(new long[]{1,14},metas);

            List<Tensor<?>> res = s
            .runner()
            .feed("input_image", input)
            .feed("input_image_meta", meta_data)
            .feed("input_anchors", getAnchors())  // dtype float and shape [?,?,4]
            .fetch("mrcnn_detection/Reshape_1")   // mrcnn_mask/Reshape_1   mrcnn_detection/Reshape_1    mrcnn_bbox/Reshape     mrcnn_class/Reshape_1
            .fetch("mrcnn_mask/Reshape_1")
            .run();

            float[][][] res_detection = new float[1][512][6];   // mrcnn_detection/Reshape_1   -> y1,x1,y2,x2,class_id,probability (ordered desc)
            float[][][][][] res_mask = new float[1][512][28][28][2];   // mrcnn_mask/Reshape_1
            Tensor<Float> mrcnn_detection = res.get(0).expect(Float.class);
            Tensor<Float> mrcnn_mask = res.get(1).expect(Float.class);
            mrcnn_detection.copyTo(res_detection);
            mrcnn_mask.copyTo(res_mask);

            RawDetections rawDetections = new RawDetections();
            rawDetections.objectBB = res_detection;
            rawDetections.masks = res_mask;
            return rawDetections;
}
 
Example 18
Source File: OptimizedErode.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public FloatBuffer filter(float sx, float sy, float base, FloatBuffer buffer, int size) {
	float[] tmp = buffer.array();
	float[] retval = new float[tmp.length];

	for (int y = this.radius + 1; y < size - this.radius; y++) {
		for (int x = this.radius + 1; x < size - this.radius; x++) {
			int idx = y * size + x;
			float h = tmp[idx];

			float horizAvg = 0;
			int horizCount = 0;
			float vertAvg = 0;
			int vertCount = 0;

			boolean horizT = false;
			boolean vertT = false;

			for (int i = 0; i >= -this.radius; i--) {
				int idxV = (y + i) * size + x;
				int idxVL = (y + i - 1) * size + x;
				int idxH = y * size + x + i;
				int idxHL = y * size + x + i - 1;
				float hV = tmp[idxV];
				float hH = tmp[idxH];

				if (Math.abs(h - hV) > this.talus && Math.abs(h - tmp[idxVL]) > this.talus || vertT) {
					vertT = true;
				} else {
					if (Math.abs(h - hV) <= this.talus) {
						vertAvg += hV;
						vertCount++;
					}
				}

				if (Math.abs(h - hH) > this.talus && Math.abs(h - tmp[idxHL]) > this.talus || horizT) {
					horizT = true;
				} else {
					if (Math.abs(h - hH) <= this.talus) {
						horizAvg += hH;
						horizCount++;
					}
				}
			}

			retval[idx] = 0.5f * (vertAvg / (vertCount > 0 ? vertCount : 1) + horizAvg / (horizCount > 0 ? horizCount : 1));
		}
	}
	return FloatBuffer.wrap(retval);
}
 
Example 19
Source File: TriangleBatch.java    From constellation with Apache License 2.0 4 votes vote down vote up
/**
 * We've finished providing data; compact the data, map the buffers, and set
 * up the vertex array.
 * <p>
 * You should really save the results of the indexing for future use if the
 * model data is static (doesn't change).
 *
 * @param gl the current OpenGL context.
 */
public void end(final GL3 gl) {
    // Create the master vertex array object.
    gl.glGenVertexArrays(1, vertexArrayBufferObject, 0);
    gl.glBindVertexArray(vertexArrayBufferObject[0]);

    // Create the buffer objects.
    gl.glGenBuffers(4, bufferObjects, 0);

    // Copy data to video memory.
    FloatBuffer buf;

    // Vertex data.
    buf = FloatBuffer.wrap(GLTools.toFloatArray(allVerts));
    gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, bufferObjects[VERTEX_DATA]);
    gl.glEnableVertexAttribArray(ShaderManager.ATTRIBUTE_VERTEX);
    gl.glBufferData(GL3.GL_ARRAY_BUFFER, GLBuffers.SIZEOF_FLOAT * 3 * nNumVerts, buf, GL3.GL_STATIC_DRAW);
    gl.glVertexAttribPointer(ShaderManager.ATTRIBUTE_VERTEX, 3, GL3.GL_FLOAT, false, 0, 0);

    // Normal data.
    buf = FloatBuffer.wrap(GLTools.toFloatArray(allNorms));
    gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, bufferObjects[NORMAL_DATA]);
    gl.glEnableVertexAttribArray(ShaderManager.ATTRIBUTE_NORMAL);
    gl.glBufferData(GL3.GL_ARRAY_BUFFER, GLBuffers.SIZEOF_FLOAT * 3 * nNumVerts, buf, GL3.GL_STATIC_DRAW);
    gl.glVertexAttribPointer(ShaderManager.ATTRIBUTE_NORMAL, 3, GL3.GL_FLOAT, false, 0, 0);

    // Texture coordinates.
    buf = FloatBuffer.wrap(GLTools.toFloatArray(allTexCoords));
    gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, bufferObjects[TEXTURE_DATA]);
    gl.glEnableVertexAttribArray(ShaderManager.ATTRIBUTE_TEXTURE0);
    gl.glBufferData(GL3.GL_ARRAY_BUFFER, GLBuffers.SIZEOF_FLOAT * nNumVerts * 2, buf, GL3.GL_STATIC_DRAW);
    gl.glVertexAttribPointer(ShaderManager.ATTRIBUTE_TEXTURE0, 2, GL3.GL_FLOAT, false, 0, 0);

    // Indexes.
    ShortBuffer shortBuf = ShortBuffer.wrap(allIndexes);
    gl.glBindBuffer(GL3.GL_ELEMENT_ARRAY_BUFFER, bufferObjects[INDEX_DATA]);
    gl.glBufferData(GL3.GL_ELEMENT_ARRAY_BUFFER, GLBuffers.SIZEOF_SHORT * nNumIndexes, shortBuf, GL3.GL_STATIC_DRAW);

    // Done
    gl.glBindVertexArray(0);

    // Free older, larger arrays.
    // Reassign pointers so they are marked as unused.
    allIndexes = null;
    allVerts = null;
    allNorms = null;
    allTexCoords = null;
}
 
Example 20
Source File: Resampler.java    From cythara with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Process a batch of samples. Alternative interface if you prefer to work with arrays.
 *
 * @param factor         resampling rate for this batch
 * @param inBuffer       array containing input samples in the range -1.0 to 1.0
 * @param inBufferOffset offset into inBuffer at which to start processing
 * @param inBufferLen    number of valid elements in the inputBuffer
 * @param lastBatch      pass true if this is the last batch of samples
 * @param outBuffer      array to hold the resampled data
 * @param outBufferOffset Offset in the output buffer.
 * @param outBufferLen    Output buffer length.
 * @return the number of samples consumed and generated
 */
public Result process(double factor, float[] inBuffer, int inBufferOffset, int inBufferLen, boolean lastBatch, float[] outBuffer, int outBufferOffset, int outBufferLen) {
    FloatBuffer inputBuffer = FloatBuffer.wrap(inBuffer, inBufferOffset, inBufferLen);
    FloatBuffer outputBuffer = FloatBuffer.wrap(outBuffer, outBufferOffset, outBufferLen);

    process(factor, inputBuffer, lastBatch, outputBuffer);

    return new Result(inputBuffer.position() - inBufferOffset, outputBuffer.position() - outBufferOffset);
}