java.nio.Buffer Java Examples

The following examples show how to use java.nio.Buffer. 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: NativeCursors.java    From Monocle with GNU General Public License v2.0 6 votes vote down vote up
/** Creates a shifted version of the source cursor. Buffers must be
 * ShortBuffers for a bit depth of 16 or IntBuffers for a bit depth of 32.
 *
 * @param sourceBuffer The original cursor to be shifted
 * @param destBuffer A buffer to receive the shifted cursor
 * @param offsetX the number of pixels the cursor is to be shifted right
 * @param offsetY the number of pixels the cursor is to be shifted down
 * @param width the pixel width of the cursor
 * @param height the pixel height of the cursor
 * @param depth the pixel depth of the cursor (16 or 32)
 * @param transparentPixel the color key used for transparent pixels
 */
static void offsetCursor(Buffer sourceBuffer,
                                Buffer destBuffer,
                                int offsetX, int offsetY,
                                int width, int height,
                                int depth, int transparentPixel) {
    switch (depth) {
        case 32:
            offsetCursor32((IntBuffer) sourceBuffer,
                           (IntBuffer) destBuffer,
                           offsetX, offsetY,
                           width, height,
                           transparentPixel);
            break;
        case 16:
            offsetCursor16((ShortBuffer) sourceBuffer,
                           (ShortBuffer) destBuffer,
                           offsetX, offsetY,
                           width, height,
                           transparentPixel);
            break;
        default:
            throw new UnsupportedOperationException();
    }
}
 
Example #2
Source File: VTTCueBox.java    From mp4parser with Apache License 2.0 6 votes vote down vote up
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
    ByteBuffer header = ByteBuffer.allocate(8);
    IsoTypeWriter.writeUInt32(header, getSize());
    header.put(IsoFile.fourCCtoBytes(getType()));
    writableByteChannel.write((ByteBuffer) ((Buffer)header).rewind());
    if (cueSourceIDBox != null) {
        cueSourceIDBox.getBox(writableByteChannel);
    }
    if (cueIDBox != null) {
        cueIDBox.getBox(writableByteChannel);
    }
    if (cueTimeBox != null) {
        cueTimeBox.getBox(writableByteChannel);
    }
    if (cueSettingsBox != null) {
        cueSettingsBox.getBox(writableByteChannel);
    }
    if (cuePayloadBox != null) {
        cuePayloadBox.getBox(writableByteChannel);
    }
}
 
Example #3
Source File: OrtUtils.java    From djl with Apache License 2.0 6 votes vote down vote up
public static OnnxTensor toTensor(
        OrtEnvironment env, Buffer data, Shape shape, DataType dataType) throws OrtException {
    long[] sh = shape.getShape();
    switch (dataType) {
        case FLOAT32:
            return OnnxTensor.createTensor(env, (FloatBuffer) data, sh);
        case FLOAT64:
            return OnnxTensor.createTensor(env, (DoubleBuffer) data, sh);
        case INT32:
            return OnnxTensor.createTensor(env, (IntBuffer) data, sh);
        case INT64:
            return OnnxTensor.createTensor(env, (LongBuffer) data, sh);
        case INT8:
        case UINT8:
            return OnnxTensor.createTensor(env, (ByteBuffer) data, sh, OnnxJavaType.INT8);
        case BOOLEAN:
            return OnnxTensor.createTensor(env, (ByteBuffer) data, sh, OnnxJavaType.BOOL);
        case FLOAT16:
        default:
            throw new EngineException("Data type not supported: " + dataType);
    }
}
 
Example #4
Source File: ChannelDataOutput.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Writes {@code length} characters from the array to the stream.
 *
 * @param  dataSize  the size of the Java primitive type which is the element of the array.
 * @param  offset    the starting position within {@code src} to write.
 * @param  length    the number of characters to write.
 * @throws IOException if an error occurred while writing the stream.
 */
final void writeFully(final int dataSize, int offset, int length) throws IOException {
    clearBitOffset(); // Actually needed only if length == 0.
    ensureBufferAccepts(Math.min(length * dataSize, buffer.capacity()));
    final Buffer view = createView(); // Must be after ensureBufferAccept
    int n = Math.min(view.remaining(), length);
    transfer(offset, n);
    skipInBuffer(n * dataSize);
    while ((length -= n) != 0) {
        offset += n;
        ensureBufferAccepts(Math.min(length, view.capacity()) * dataSize);
        view.rewind().limit(buffer.remaining() / dataSize);
        transfer(offset, n = view.remaining());
        skipInBuffer(n * dataSize);
    }
}
 
Example #5
Source File: MjpegTest.java    From mp4parser with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    IsoFile isofile = new IsoFile("C:\\content\\bbb-small\\output_320x180-mjpeg.mp4");
    ESDescriptorBox esDescriptorBox = Path.getPath(isofile, "/moov[0]/trak[0]/mdia[0]/minf[0]/stbl[0]/stsd[0]/mp4v[0]/esds[0]");
    byte[] d = new byte[((Buffer)esDescriptorBox.getData()).rewind().remaining()];
    esDescriptorBox.getData().get(d);
    System.err.println(Hex.encodeHex(d));

    Movie mRef = MovieCreator.build("C:\\content\\bbb-small\\output_320x180_150.mp4");
    Track refTrack = mRef.getTracks().get(0);

    File baseDir = new File("C:\\content\\bbb-small");
    File[] iFrameJpegs = baseDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".jpg");
        }
    });
    Arrays.sort(iFrameJpegs);

    Movie mRes = new Movie();
    mRes.addTrack(new OneJpegPerIframe("iframes", iFrameJpegs, refTrack));

    new DefaultMp4Builder().build(mRes).writeContainer(new FileOutputStream("output-mjpeg.mp4").getChannel());
}
 
Example #6
Source File: BaseLoader.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * Load an ndarray from a blob
 *
 * @param blob the blob to load from
 * @return the loaded ndarray
 */
@Override
public INDArray load(Blob blob) throws SQLException {
    if (blob == null)
        return null;
    try(InputStream is = blob.getBinaryStream()) {
        ByteBuffer direct = ByteBuffer.allocateDirect((int) blob.length());
        ReadableByteChannel readableByteChannel = Channels.newChannel(is);
        readableByteChannel.read(direct);
        Buffer byteBuffer = (Buffer) direct;
        byteBuffer.rewind();
        return BinarySerde.toArray(direct);
    } catch (Exception e) {
       throw new RuntimeException(e);
    }


}
 
Example #7
Source File: FFmpegRecorderActivity.java    From FFmpegRecorder with GNU General Public License v3.0 6 votes vote down vote up
/**
 * shortBuffer��������Ƶ�����ݺ���ʼλ��
 * @param shortBuffer
 */
private void record(ShortBuffer shortBuffer)
{
	try
	{
		synchronized (mAudioRecordLock)
		{
			if (videoRecorder != null)
			{
				this.mCount += shortBuffer.limit();
				videoRecorder.record(0,new Buffer[] {shortBuffer});
			}
			return;
		}
	}
	catch (FrameRecorder.Exception localException){}
}
 
Example #8
Source File: ImageRenderer.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the data as vectors. The number of vectors must be equal to the {@linkplain #getNumBands() expected number of bands}.
 * All vectors must be backed by arrays (indirectly, through {@linkplain Vector#buffer() buffers} backed by arrays) and have
 * the same {@linkplain Vector#size() size}.
 * This method wraps the underlying arrays of a primitive type into a Java2D buffer; data are not copied.
 *
 * <p><b>Implementation note:</b> the NIO buffers are set by a call to {@link #setData(int, Buffer...)},
 * which can be overridden by subclasses if desired.</p>
 *
 * @param  data  the vectors wrapping arrays of primitive type.
 * @throws NullArgumentException if {@code data} is null or one of {@code data} element is null.
 * @throws MismatchedCoverageRangeException if the number of specified vectors is not equal to the number of bands.
 * @throws UnsupportedOperationException if a vector is not backed by an accessible array or is read-only.
 * @throws RasterFormatException if vectors do not have the same size.
 * @throws ArithmeticException if a buffer position overflows the 32 bits integer capacity.
 */
public void setData(final Vector... data) {
    ArgumentChecks.ensureNonNull("data", data);
    ensureExpectedBandCount(data.length, true);
    final Buffer[] buffers = new Buffer[data.length];
    int dataType = DataBuffer.TYPE_UNDEFINED;
    for (int i=0; i<data.length; i++) {
        final Vector v = data[i];
        ArgumentChecks.ensureNonNullElement("data", i, v);
        final int t = RasterFactory.getType(v.getElementType(), v.isUnsigned());
        if (dataType != t) {
            if (i != 0) {
                throw new RasterFormatException(Resources.format(Resources.Keys.MismatchedDataType));
            }
            dataType = t;
        }
        buffers[i] = v.buffer().orElseThrow(UnsupportedOperationException::new);
    }
    setData(dataType, buffers);
}
 
Example #9
Source File: BaseLoader.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * Load an ndarray from a blob
 *
 * @param blob the blob to load from
 * @return the loaded ndarray
 */
@Override
public INDArray load(Blob blob) throws SQLException {
    if (blob == null)
        return null;
    try(InputStream is = blob.getBinaryStream()) {
        ByteBuffer direct = ByteBuffer.allocateDirect((int) blob.length());
        ReadableByteChannel readableByteChannel = Channels.newChannel(is);
        readableByteChannel.read(direct);
        Buffer byteBuffer = (Buffer) direct;
        byteBuffer.rewind();
        return BinarySerde.toArray(direct);
    } catch (Exception e) {
       throw new RuntimeException(e);
    }


}
 
Example #10
Source File: VertexBuffer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Called to initialize the data in the <code>VertexBuffer</code>. Must only
 * be called once.
 * 
 * @param usage The usage for the data, or how often will the data
 * be updated per frame. See the {@link Usage} enum.
 * @param components The number of components per element.
 * @param format The {@link Format format}, or data-type of a single
 * component.
 * @param data A native buffer, the format of which matches the {@link Format}
 * argument.
 */
public void setupData(Usage usage, int components, Format format, Buffer data){
    if (id != -1)
        throw new UnsupportedOperationException("Data has already been sent. Cannot setupData again.");

    if (usage == null || format == null || data == null)
        throw new IllegalArgumentException("None of the arguments can be null");
        
    if (components < 1 || components > 4)
        throw new IllegalArgumentException("components must be between 1 and 4");

    this.data = data;
    this.components = components;
    this.usage = usage;
    this.format = format;
    this.componentsLength = components * format.getComponentSize();
    this.lastLimit = data.limit();
    setUpdateNeeded();
}
 
Example #11
Source File: ImageWritable.java    From DataVec with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object obj) {
    if (obj instanceof ImageWritable) {
        Frame f2 = ((ImageWritable) obj).getFrame();

        Buffer[] b1 = this.frame.image;
        Buffer[] b2 = f2.image;

        if (b1.length != b2.length)
            return false;

        for (int i = 0; i < b1.length; i++) {
            if (!b1[i].equals(b2[i]))
                return false;
        }

        return true;
    } else {
        return false;
    }
}
 
Example #12
Source File: RawDataFileImpl.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public synchronized DataPoint[] readDataPoints(int ID) throws IOException {

    final Long currentOffset = dataPointsOffsets.get(ID);
    final Integer numOfDataPoints = dataPointsLengths.get(ID);

    if ((currentOffset == null) || (numOfDataPoints == null)) {
      throw new IllegalArgumentException("Unknown storage ID " + ID);
    }

    final int numOfBytes = numOfDataPoints * 2 * 4;

    if (buffer.capacity() < numOfBytes) {
      buffer = ByteBuffer.allocate(numOfBytes * 2);
    } else {
      // JDK 9 breaks compatibility with JRE8: need to cast
      // https://stackoverflow.com/questions/48693695/java-nio-buffer-not-loading-clear-method-on-runtime
      ((Buffer) buffer).clear();
    }

    dataPointsFile.seek(currentOffset);
    dataPointsFile.read(buffer.array(), 0, numOfBytes);

    FloatBuffer floatBuffer = buffer.asFloatBuffer();

    DataPoint dataPoints[] = new DataPoint[numOfDataPoints];

    for (int i = 0; i < numOfDataPoints; i++) {
      float mz = floatBuffer.get();
      float intensity = floatBuffer.get();
      dataPoints[i] = new SimpleDataPoint(mz, intensity);
    }

    return dataPoints;

  }
 
Example #13
Source File: GpuStream.java    From OSPREY3 with GNU General Public License v2.0 5 votes vote down vote up
public <T extends Buffer> CUBuffer<T> makeOrExpandBuffer(CUBuffer<T> dest, T src) {
	if (dest == null) {
		return makeBuffer(src);
	}
	dest.expand(src);
	return dest;
}
 
Example #14
Source File: SkinningControl.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void resetToBind() {
    for (Geometry geometry : targets) {
        Mesh mesh = geometry.getMesh();
        if (mesh != null && mesh.isAnimated()) {
            Buffer bwBuff = mesh.getBuffer(Type.BoneWeight).getData();
            Buffer biBuff = mesh.getBuffer(Type.BoneIndex).getData();
            if (!biBuff.hasArray() || !bwBuff.hasArray()) {
                mesh.prepareForAnim(true); // prepare for software animation
            }
            VertexBuffer bindPos = mesh.getBuffer(Type.BindPosePosition);
            VertexBuffer bindNorm = mesh.getBuffer(Type.BindPoseNormal);
            VertexBuffer pos = mesh.getBuffer(Type.Position);
            VertexBuffer norm = mesh.getBuffer(Type.Normal);
            FloatBuffer pb = (FloatBuffer) pos.getData();
            FloatBuffer nb = (FloatBuffer) norm.getData();
            FloatBuffer bpb = (FloatBuffer) bindPos.getData();
            FloatBuffer bnb = (FloatBuffer) bindNorm.getData();
            pb.clear();
            nb.clear();
            bpb.clear();
            bnb.clear();

            //reseting bind tangents if there is a bind tangent buffer
            VertexBuffer bindTangents = mesh.getBuffer(Type.BindPoseTangent);
            if (bindTangents != null) {
                VertexBuffer tangents = mesh.getBuffer(Type.Tangent);
                FloatBuffer tb = (FloatBuffer) tangents.getData();
                FloatBuffer btb = (FloatBuffer) bindTangents.getData();
                tb.clear();
                btb.clear();
                tb.put(btb).clear();
            }


            pb.put(bpb).clear();
            nb.put(bnb).clear();
        }
    }
}
 
Example #15
Source File: FTP.java    From BetterBackdoor with MIT License 5 votes vote down vote up
/**
 * Receives file with path {@code filePath} using {@code socketChannel} and
 * {@code fileChannel}.
 *
 * @param filePath      path of file to receive
 * @param socketChannel {@link java.nio.channels.SocketChannel} to use for
 *                      receiving
 * @throws IOException
 */
private static void rec(String filePath, SocketChannel socketChannel) throws IOException {
	RandomAccessFile file = new RandomAccessFile(filePath, "rw");
	FileChannel fileChannel = file.getChannel();
	ByteBuffer buffer = ByteBuffer.allocate(1024);
	while (socketChannel.read(buffer) > 0) {
		((Buffer) buffer).flip();
		fileChannel.write(buffer);
		((Buffer) buffer).clear();
	}
	file.close();
	fileChannel.close();
}
 
Example #16
Source File: SkeletonControl.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
void resetToBind() {
    for (Mesh mesh : targets) {
        if (mesh.isAnimated()) {
            Buffer bwBuff = mesh.getBuffer(Type.BoneWeight).getData();
            Buffer biBuff = mesh.getBuffer(Type.BoneIndex).getData();
            if (!biBuff.hasArray() || !bwBuff.hasArray()) {
                mesh.prepareForAnim(true); // prepare for software animation
            }
            VertexBuffer bindPos = mesh.getBuffer(Type.BindPosePosition);
            VertexBuffer bindNorm = mesh.getBuffer(Type.BindPoseNormal);
            VertexBuffer pos = mesh.getBuffer(Type.Position);
            VertexBuffer norm = mesh.getBuffer(Type.Normal);
            FloatBuffer pb = (FloatBuffer) pos.getData();
            FloatBuffer nb = (FloatBuffer) norm.getData();
            FloatBuffer bpb = (FloatBuffer) bindPos.getData();
            FloatBuffer bnb = (FloatBuffer) bindNorm.getData();
            pb.clear();
            nb.clear();
            bpb.clear();
            bnb.clear();

            //reseting bind tangents if there is a bind tangent buffer
            VertexBuffer bindTangents = mesh.getBuffer(Type.BindPoseTangent);
            if (bindTangents != null) {
                VertexBuffer tangents = mesh.getBuffer(Type.Tangent);
                FloatBuffer tb = (FloatBuffer) tangents.getData();
                FloatBuffer btb = (FloatBuffer) bindTangents.getData();
                tb.clear();
                btb.clear();
                tb.put(btb).clear();
            }


            pb.put(bpb).clear();
            nb.put(bnb).clear();
        }
    }
}
 
Example #17
Source File: LwjglGLExt.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void checkLimit(Buffer buffer) {
    if (buffer == null) {
        return;
    }
    if (buffer.limit() == 0) {
        throw new RendererException("Attempting to upload empty buffer (limit = 0), that's an error");
    }
    if (buffer.remaining() == 0) {
        throw new RendererException("Attempting to upload empty buffer (remaining = 0), that's an error");
    }
}
 
Example #18
Source File: EDITokenizer.java    From edireader with GNU General Public License v3.0 5 votes vote down vote up
/**
     * Look ahead into the source of input chars and return the next n chars to
     * be seen, without disturbing the normal operation of getChar().
     *
     * @param n number of chars to return
     * @return char[] containing upcoming input chars
     * @throws IOException for problem reading EDI data
     */
    public char[] lookahead(int n) throws IOException {
        logger.debug("EDITokenizer.lookahead({})", n);
        char[] rval = new char[n];

        // The 1st char is grabbed using the tokenizer's built-in
        // getChar() / ungetChar() mechanism. This allows things to work
        // properly whether or not the next char has already been gotten.
        getChar();
        rval[0] = cChar;
        ungetChar();

        // The minus 1 is because we have already filled the first char of the return value, so we only need n-1 more
        if (charBuffer.remaining() < n - 1) {
            logger.debug("Buffering more data to satisfy lookahead({}})", n);
            readUntilBufferProvidesAtLeast(n - 1);
        }

        // Move chars from the buffer into the return value
        int j = 1;
        for (int i = charBuffer.position(); i < ((Buffer) charBuffer).limit() && j < n; i++)
            rval[j++] = charBuffer.get(i);

        // If more lookahead chars were requested than were satisfied for any reason,
        // then fill the return value with '?' to the requested length.
        for (; j < n; ) {
            rval[j++] = '?';
//            throw new RuntimeException("problem with lookahead " + n);
        }

        return rval;
    }
 
Example #19
Source File: ResultJsonParserV2.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Continue parsing with the given data
 *
 * @param in readOnly byteBuffer backed by an array (the data to be reed is from position to limit)
 */
public void continueParsing(ByteBuffer in) throws SnowflakeSQLException
{
  if (state == State.UNINITIALIZED)
  {
    throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR,
                                    ErrorCode.INTERNAL_ERROR.getMessageCode(),
                                    "Json parser hasn't been initialized!");
  }

  // If stopped during a \\u, continue here
  if (((Buffer) partialEscapedUnicode).position() > 0)
  {
    int lenToCopy = Math.min(12 - ((Buffer) partialEscapedUnicode).position(), in.remaining());
    if (lenToCopy > partialEscapedUnicode.remaining())
    {
      resizePartialEscapedUnicode(lenToCopy);
    }
    partialEscapedUnicode.put(in.array(), in.arrayOffset() + ((Buffer) in).position(), lenToCopy);
    ((Buffer) in).position(((Buffer) in).position() + lenToCopy);

    if (((Buffer) partialEscapedUnicode).position() < 12)
    {
      // Not enough data to parse escaped unicode
      return;
    }
    ByteBuffer toBeParsed = partialEscapedUnicode.duplicate();
    ((Buffer) toBeParsed).flip();
    continueParsingInternal(toBeParsed, false);
    ((Buffer) partialEscapedUnicode).clear();
  }
  continueParsingInternal(in, false);
}
 
Example #20
Source File: SampleImpl.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
public ByteBuffer asByteBuffer() {
    byte[] bCopy = new byte[l2i(size)];
    ByteBuffer copy = ByteBuffer.wrap(bCopy);
    for (ByteBuffer b : data) {
        copy.put(b.duplicate());
    }
    ((Buffer)copy).rewind();
    return copy;
}
 
Example #21
Source File: TemporalLevelEntry.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer get() {
    ByteBuffer content = ByteBuffer.allocate(1);
    content.put((byte) (levelIndependentlyDecodable ? 0x80 : 0x00));
    ((Buffer)content).rewind();
    return content;
}
 
Example #22
Source File: OrtUtils.java    From djl with Apache License 2.0 5 votes vote down vote up
public static NDArray toNDArray(NDManager manager, OnnxTensor tensor) {
    if (manager instanceof OrtNDManager) {
        return ((OrtNDManager) manager).create(tensor);
    }
    ByteBuffer bb = tensor.getByteBuffer();
    bb.order(ByteOrder.nativeOrder());
    DataType dataType = OrtUtils.toDataType(tensor.getInfo().type);
    Shape shape = new Shape(tensor.getInfo().getShape());
    Buffer buf = dataType.asDataType(bb);
    tensor.close();
    return manager.create(buf, shape, dataType);
}
 
Example #23
Source File: BufferUtils.java    From Ultraino with MIT License 5 votes vote down vote up
@Override
public void run() {
    try {
        while (true) {
            Reference<? extends Buffer> toclean = BufferUtils.removeCollected.remove();
            BufferUtils.trackedBuffers.remove(toclean);
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example #24
Source File: EDITokenizer.java    From edireader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a String representation of the current state of the tokenizer
 * for testing and debugging purposes.
 *
 * @return String representation
 */
@Override
public String toString() {
    String result = "tokenizer state:";
    result += " segmentCount=" + segmentCount;
    result += " charCount=" + charCount;
    result += " segTokenCount=" + segTokenCount;
    result += " segCharCount=" + segCharCount;
    result += " currentToken=" + currentToken;
    result += " buffer.limit=" + ((Buffer) charBuffer).limit();
    result += " buffer.position=" + charBuffer.position();
    return result;
}
 
Example #25
Source File: SampleDescriptionBox.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
    ByteBuffer versionFlagNumOfChildBoxes = ByteBuffer.allocate(8);
    dataSource.read(versionFlagNumOfChildBoxes);
    ((Buffer)versionFlagNumOfChildBoxes).rewind();
    version = IsoTypeReader.readUInt8(versionFlagNumOfChildBoxes);
    flags = IsoTypeReader.readUInt24(versionFlagNumOfChildBoxes);
    // number of child boxes is not required
    initContainer(dataSource, contentSize - 8, boxParser);
}
 
Example #26
Source File: JoglRenderer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void updateBufferData(VertexBuffer vb) {
    int bufId = vb.getId();
    if (bufId == -1) {
        // create buffer
        gl.glGenBuffers(1, ib1);
        bufId = ib1.get(0);
        vb.setId(bufId);
        objManager.registerForCleanup(vb);
    }

    int target;
    if (vb.getBufferType() == VertexBuffer.Type.Index) {
        target = gl.GL_ELEMENT_ARRAY_BUFFER;
        if (context.boundElementArrayVBO != bufId) {
            gl.glBindBuffer(target, bufId);
            context.boundElementArrayVBO = bufId;
        }
    } else {
        target = gl.GL_ARRAY_BUFFER;
        if (context.boundArrayVBO != bufId) {
            gl.glBindBuffer(target, bufId);
            context.boundArrayVBO = bufId;
        }
    }

    int usage = convertUsage(vb.getUsage());
    Buffer data = vb.getData();
    data.rewind();

    gl.glBufferData(target,
            data.capacity() * vb.getFormat().getComponentSize(),
            data,
            usage);

    vb.clearUpdateNeeded();
}
 
Example #27
Source File: LodGenerator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void gatherIndexData(Mesh mesh, List<Vertex> vertexLookup) {
    VertexBuffer indexBuffer = mesh.getBuffer(VertexBuffer.Type.Index);
    indexCount = indexBuffer.getNumElements() * 3;
    Buffer b = indexBuffer.getDataReadOnly();
    b.rewind();
    
    while (b.remaining() != 0) {
        Triangle tri = new Triangle();
        tri.isRemoved = false;
        triangleList.add(tri);            
        for (int i = 0; i < 3; i++) {
            if (b instanceof IntBuffer) {
                tri.vertexId[i] = ((IntBuffer) b).get();
            } else {
                //bit shift to avoid negative values due to conversion form short to int.
                //we need an unsigned int here.
                tri.vertexId[i] = ((ShortBuffer) b).get()& 0xffff;
            }
           // assert (tri.vertexId[i] < vertexLookup.size());
            tri.vertex[i] = vertexLookup.get(tri.vertexId[i]);
            //debug only;
            tri.vertex[i].index = tri.vertexId[i];
        }
        if (tri.isMalformed()) {
            if (!tri.isRemoved) {
                logger.log(Level.FINE, "malformed triangle found with ID:{0}\n{1} It will be excluded from Lod level calculations.", new Object[]{triangleList.indexOf(tri), tri.toString()});
                tri.isRemoved = true;
                indexCount -= 3;
            }
            
        } else {
            tri.computeNormal();
            addTriangleToEdges(tri);
        }
    }
    b.rewind();
}
 
Example #28
Source File: GeoTiff.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
     * Test read data
     *
     * @param offset Offset
     * @param size Size
     * @throws IOException
     */
    private ByteBuffer testReadData(int offset, int size) throws IOException {
        this.channel.position(offset);
        ByteBuffer buffer = ByteBuffer.allocate(size);
        buffer.order(this.byteOrder);

        this.channel.read(buffer);
        ((Buffer)buffer).flip();

//        for (int i = 0; i < size / 4; i++) {
//            System.out.println(i + ": " + buffer.getFloat());
//        }
        return buffer;
    }
 
Example #29
Source File: GLES20Canvas.java    From Trebuchet with GNU General Public License v3.0 5 votes vote down vote up
private int uploadBuffer(Buffer buffer, int elementSize) {
    mGLId.glGenBuffers(1, mTempIntArray, 0);
    checkError();
    int bufferId = mTempIntArray[0];
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferId);
    checkError();
    GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, buffer.capacity() * elementSize, buffer,
            GLES20.GL_STATIC_DRAW);
    checkError();
    return bufferId;
}
 
Example #30
Source File: DecoderSpecificInfo.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
public ByteBuffer serialize() {
    ByteBuffer out = ByteBuffer.allocate(getSize());
    IsoTypeWriter.writeUInt8(out, tag);
    writeSize(out, getContentSize());
    out.put(bytes);
    return (ByteBuffer) ((Buffer)out).rewind();
}