Java Code Examples for com.badlogic.gdx.utils.BufferUtils#copy()

The following examples show how to use com.badlogic.gdx.utils.BufferUtils#copy() . 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: ScreenshotService.java    From talos with Apache License 2.0 6 votes vote down vote up
private void takeScreenshot() {
    byte[] pixels = ScreenUtils.getFrameBufferPixels(0, 0, Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), true);

    float scaleX = (float)Gdx.graphics.getBackBufferWidth()/Gdx.graphics.getWidth();
    float scaleY = (float)Gdx.graphics.getBackBufferHeight()/Gdx.graphics.getHeight();

    // This loop makes sure the whole screenshot is opaque and looks exactly like what the user is seeing
    for (int i = 4; i < pixels.length; i += 4) {
        pixels[i - 1] = (byte) 255;
    }

    Pixmap pixmap = new Pixmap(Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), Pixmap.Format.RGBA8888);
    BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);

    color.set(pixmap.getPixel((int)(posX * scaleX), (int)(posY * scaleY)));

    pixmap.dispose();
}
 
Example 2
Source File: BasePicker.java    From Mundus with Apache License 2.0 6 votes vote down vote up
public Pixmap getFrameBufferPixmap(Viewport viewport) {
    int w = viewport.getScreenWidth();
    int h = viewport.getScreenHeight();
    int x = viewport.getScreenX();
    int y = viewport.getScreenY();
    final ByteBuffer pixelBuffer = BufferUtils.newByteBuffer(w * h * 4);

    Gdx.gl.glBindFramebuffer(GL20.GL_FRAMEBUFFER, fbo.getFramebufferHandle());
    Gdx.gl.glReadPixels(x, y, w, h, GL30.GL_RGBA, GL30.GL_UNSIGNED_BYTE, pixelBuffer);
    Gdx.gl.glBindFramebuffer(GL20.GL_FRAMEBUFFER, 0);

    final int numBytes = w * h * 4;
    byte[] imgLines = new byte[numBytes];
    final int numBytesPerLine = w * 4;
    for (int i = 0; i < h; i++) {
        pixelBuffer.position((h - i - 1) * numBytesPerLine);
        pixelBuffer.get(imgLines, i * numBytesPerLine, numBytesPerLine);
    }

    Pixmap pixmap = new Pixmap(w, h, Pixmap.Format.RGBA8888);
    BufferUtils.copy(imgLines, 0, pixmap.getPixels(), imgLines.length);

    return pixmap;
}
 
Example 3
Source File: MetalBasic3DRenderer.java    From robovm-samples with Apache License 2.0 6 votes vote down vote up
private void updateConstantBuffer() {
    baseModelViewMatrix.set(viewMatrix).translate(0.0f,  0.0f,  5f).rotate(1, 1, 1, rotation);
    ByteBuffer constant_buffer = dynamicConstantBuffer[constantDataBufferIndex].getContents();
    constant_buffer.order(ByteOrder.nativeOrder());
    for (int i = 0; i < kNumberOfBoxes; i++) {
        int multiplier = ((i % 2) == 0?1: -1);
        modelViewMatrix.set(baseModelViewMatrix).translate(0, 0, multiplier * 1.5f).rotate(1, 1, 1, rotation);

        normalMatrix.set(modelViewMatrix).tra().inv();
        constant_buffer.position((sizeOfConstantT *i) + normalMatrixOffset);
        BufferUtils.copy(normalMatrix.getValues(), 0, 16, constant_buffer);

        combinedMatrix.set(projectionMatrix).mul(modelViewMatrix);
        constant_buffer.position((sizeOfConstantT * i) + modelViewProjectionMatrixOffset);
        BufferUtils.copy(combinedMatrix.getValues(), 0, 16, constant_buffer);
    }
    rotation += 0.01;
}
 
Example 4
Source File: ShareChallenge.java    From Klooni1010 with GNU General Public License v3.0 4 votes vote down vote up
public boolean saveChallengeImage(final int score, final boolean timeMode) {
    final File saveAt = getShareImageFilePath();
    if (!saveAt.getParentFile().isDirectory())
        if (!saveAt.mkdirs())
            return false;

    final FileHandle output = new FileHandle(saveAt);

    final Texture shareBase = new Texture(Gdx.files.internal("share.png"));
    final int width = shareBase.getWidth();
    final int height = shareBase.getHeight();

    final FrameBuffer frameBuffer = new FrameBuffer(Pixmap.Format.RGB888, width, height, false);
    frameBuffer.begin();

    // Render the base share texture
    final SpriteBatch batch = new SpriteBatch();
    final Matrix4 matrix = new Matrix4();
    matrix.setToOrtho2D(0, 0, width, height);
    batch.setProjectionMatrix(matrix);

    Gdx.gl.glClearColor(Color.GOLD.r, Color.GOLD.g, Color.GOLD.b, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.begin();
    batch.draw(shareBase, 0, 0);

    // Render the achieved score
    final Label.LabelStyle style = new Label.LabelStyle();
    style.font = new BitmapFont(Gdx.files.internal("font/x1.0/geosans-light64.fnt"));
    Label label = new Label("just scored " + score + " on", style);
    label.setColor(Color.BLACK);
    label.setPosition(40, 500);
    label.draw(batch, 1);

    label.setText("try to beat me if you can");
    label.setPosition(40, 40);
    label.draw(batch, 1);

    if (timeMode) {
        Texture timeModeTexture = new Texture("ui/x1.5/stopwatch.png");
        batch.setColor(Color.BLACK);
        batch.draw(timeModeTexture, 200, 340);
    }

    batch.end();

    // Get the framebuffer pixels and write them to a local file
    final byte[] pixels = ScreenUtils.getFrameBufferPixels(0, 0, width, height, true);

    final Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);

    BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);
    PixmapIO.writePNG(output, pixmap);

    // Dispose everything
    pixmap.dispose();
    shareBase.dispose();
    batch.dispose();
    frameBuffer.end();

    return true;
}
 
Example 5
Source File: FreeTypeFontGenerator.java    From gdx-texture-packer-gui with Apache License 2.0 4 votes vote down vote up
/** Creates a new generator from the given font file. Uses {@link FileHandle#length()} to determine the file size. If the file
 * length could not be determined (it was 0), an extra copy of the font bytes is performed. Throws a
 * {@link GdxRuntimeException} if loading did not succeed. */
public FreeTypeFontGenerator (FileHandle fontFile, int faceIndex) {
	name = fontFile.pathWithoutExtension();
	int fileSize = (int)fontFile.length();

	library = FreeType.initFreeType();
	if (library == null) throw new GdxRuntimeException("Couldn't initialize FreeType");

	ByteBuffer buffer = null;

	try {
		buffer = fontFile.map();
	} catch (GdxRuntimeException e) {
		// Silently error, certain platforms do not support file mapping.
	}

	if (buffer == null) {
		InputStream input = fontFile.read();
		try {
			if (fileSize == 0) {
				// Copy to a byte[] to get the file size, then copy to the buffer.
				byte[] data = StreamUtils.copyStreamToByteArray(input, 1024 * 16);
				buffer = BufferUtils.newUnsafeByteBuffer(data.length);
				BufferUtils.copy(data, 0, buffer, data.length);
			} else {
				// Trust the specified file size.
				buffer = BufferUtils.newUnsafeByteBuffer(fileSize);
				StreamUtils.copyStream(input, buffer);
			}
		} catch (IOException ex) {
			throw new GdxRuntimeException(ex);
		} finally {
			StreamUtils.closeQuietly(input);
		}
	}

	face = library.newMemoryFace(buffer, faceIndex);
	if (face == null) throw new GdxRuntimeException("Couldn't create face for font: " + fontFile);

	if (checkForBitmapFont()) return;
	setPixelSizes(0, 15);
}
 
Example 6
Source File: FreeType.java    From gdx-texture-packer-gui with Apache License 2.0 4 votes vote down vote up
public Face newMemoryFace(byte[] data, int dataSize, int faceIndex) {
	ByteBuffer buffer = BufferUtils.newUnsafeByteBuffer(data.length);
	BufferUtils.copy(data, 0, buffer, data.length);
	return newMemoryFace(buffer, faceIndex);
}
 
Example 7
Source File: PaletteIndexedPixmap.java    From riiablo with Apache License 2.0 4 votes vote down vote up
public PaletteIndexedPixmap(int width, int height, byte[] data) {
  this(width, height);
  BufferUtils.copy(data, 0, getPixels(), data.length);
}
 
Example 8
Source File: IndexBufferObjectExt.java    From libgdx-snippets with MIT License 4 votes vote down vote up
public void setIndices(short[] indices, int offset, int count) {
	buffer.position(0);
	BufferUtils.copy(indices, offset, buffer, count);
	buffer.position(buffer.limit());
	buffer.limit(buffer.capacity());
}
 
Example 9
Source File: VertexBufferObjectExt.java    From libgdx-snippets with MIT License 4 votes vote down vote up
public void setVertices(float[] vertices, int offset, int count) {
	buffer.position(0);
	BufferUtils.copy(vertices, buffer, count, offset);
	buffer.position(buffer.limit());
	buffer.limit(buffer.capacity());
}
 
Example 10
Source File: MetalBasic3DRenderer.java    From robovm-samples with Apache License 2.0 4 votes vote down vote up
public void configure(MetalBasic3DView view) {
    // find a usable Device
    device = view.getDevice();
    
    // setup view with drawable formats
    view.setDepthPixelFormat(MTLPixelFormat.Depth32Float);
    view.setStencilPixelFormat(MTLPixelFormat.Invalid);
    view.setSampleCount(1);
    
    // create a new command queue
    commandQueue = device.newCommandQueue();
    
    defaultLibrary = device.newDefaultLibrary();
    if (defaultLibrary == null) {
        // If the shader libary isn't loading, nothing good will happen
        throw new Error(">> ERROR: Couldnt create a default shader library");
    }
    
    preparePipelineState(view);
    
    MTLDepthStencilDescriptor depthStateDesc = new MTLDepthStencilDescriptor();
    depthStateDesc.setDepthCompareFunction(MTLCompareFunction.Less);
    depthStateDesc.setDepthWriteEnabled(true);
    depthState = device.newDepthStencilState(depthStateDesc);
    
    // allocate a number of buffers in memory that matches the sempahore count so that
    // we always have one self contained memory buffer for each buffered frame.
    // In this case triple buffering is the optimal way to go so we cycle through 3 memory buffers
    for (int i = 0; i < kInFlightCommandBuffers; i++) {
        dynamicConstantBuffer[i] = device.newBuffer(maxBufferBytesPerFrame, MTLResourceOptions.CPUCacheModeDefaultCache);
        dynamicConstantBuffer[i].setLabel("ConstantBuffer" + i);
        
        // write initial color values for both cubes (at each offset).
        // Note, these will get animated during update
        ByteBuffer constant_buffer = dynamicConstantBuffer[i].getContents();
        constant_buffer.order(ByteOrder.nativeOrder());

        for (int j = 0; j < kNumberOfBoxes; j++) {
            if (j % 2 == 0) {
                constant_buffer.position((sizeOfConstantT * j) + ambientColorOffset);
                BufferUtils.copy(kBoxAmbientColors[0], 0, 4, constant_buffer);
                constant_buffer.position((sizeOfConstantT * j) + diffuseColorOffset);
                BufferUtils.copy(kBoxDiffuseColors[0], 0, 4, constant_buffer);
                constant_buffer.putInt((sizeOfConstantT * j) + multiplierOffset, 1);
            } else {
                constant_buffer.position((sizeOfConstantT * j) + ambientColorOffset);
                BufferUtils.copy(kBoxAmbientColors[1], 0, 4, constant_buffer);
                constant_buffer.position((sizeOfConstantT * j) + diffuseColorOffset);
                BufferUtils.copy(kBoxDiffuseColors[1], 0, 4, constant_buffer);
                constant_buffer.putInt((sizeOfConstantT * j) + multiplierOffset, -1);
            }
        }
    }
}