com.w67clement.openw67render.utils.OpenUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.w67clement.openw67render.utils.OpenUtils.java

Source

/*
 * Copyright  2016 Clment "w67clement" Wagner
 *
 * This file is part of OpenW67Render.
 *
 * OpenW67Render is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * OpenW67Render is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with OpenW67Render.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.w67clement.openw67render.utils;

import com.w67clement.openw67render.OpenContext;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Configuration;

/**
 * Created by w67clement on 13/05/2016.
 * <p>
 * Class of project: openw67render
 */
public class OpenUtils {

    public static boolean pointIsInRectangle(int x1, int y1, int x2, int y2, double pX, double pY) {
        Rectangle rectangle = new Rectangle(x1, y1, x2, y2);
        return rectangle.contains(pX, pY);
    }

    /**
     * Do a percentage from a value and a maximum
     *
     * @param value   The value
     * @param maximum The maximum value
     *
     * @return The made percentage
     */
    public static int percentage(int value, int maximum) {
        return crossMult(value, maximum, 100);
    }

    /**
     * Do a cross multiplication
     *
     * @param value       The value
     * @param maximum     The maximum value
     * @param coefficient The coefficient
     *
     * @return The result
     */
    public static int crossMult(int value, int maximum, int coefficient) {
        return (int) ((double) value / (double) maximum * (double) coefficient);
    }

    /**
     * Determines if the OpenGL context supports version 3.2.
     *
     * @return True, if OpenGL context supports version 3.2, else false.
     */
    public static boolean isDefaultGLContext() {
        return GL.getCapabilities().OpenGL32;
    }

    /**
     * Gets only the alone value in a list.
     *
     * @param list List with the value.
     * @param <U>  Value type.
     *
     * @return The value if there is a value else null. It can throw a IllegalStateException if there is more values in the list.
     */
    public static <U> U getAloneValue(List<U> list) {
        if (list.size() > 1)
            throw new IllegalStateException();
        else if (list.size() < 1)
            return null;
        else
            return list.get(0);
    }

    private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
        ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
        buffer.flip();
        newBuffer.put(buffer);
        return newBuffer;
    }

    /**
     * Reads the specified resource and returns the raw data as a ByteBuffer.
     *
     * @param resource   the resource to read
     * @param bufferSize the initial buffer size
     *
     * @return the resource data
     *
     * @throws IOException if an IO error occurs
     */
    public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
        ByteBuffer buffer;

        Path path = Paths.get(resource);
        if (Files.isReadable(path)) {
            try (SeekableByteChannel fc = Files.newByteChannel(path)) {
                buffer = BufferUtils.createByteBuffer((int) fc.size() + 1);
                int bytes = 0;
                while (bytes != -1) {
                    bytes = fc.read(buffer);
                }
            }
        } else {
            try (InputStream source = OpenUtils.class.getResourceAsStream(resource);
                    ReadableByteChannel rbc = Channels.newChannel(source)) {
                buffer = BufferUtils.createByteBuffer(bufferSize);

                while (true) {
                    int bytes = rbc.read(buffer);
                    if (bytes == -1)
                        break;
                    if (buffer.remaining() == 0)
                        buffer = resizeBuffer(buffer, buffer.capacity() * 2);
                }
            }
        }

        buffer.flip();
        return buffer;
    }

    private static GraphicsConfiguration getGraphicsConfiguration() {
        GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        return environment.getDefaultScreenDevice().getDefaultConfiguration();
    }

    public static BufferedImage createTranslucentCompatibleImage(int width, int height) {
        return getGraphicsConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
    }

    /**
     * This method loads the natives libraries required by LWJGL. The specified
     * libraries will get extracted into the folder native.
     *
     * @throws IOException if an error occurs during extracting the libraries
     */
    public static void unpackNatives() throws IOException {
        Path libraryPath = Paths.get("natives");

        /* Only unpack if native folder doesn't exist */
        if (!Files.exists(libraryPath)) {
            /* Get OS name and architecture */
            String os = System.getProperty("os.name").toLowerCase();
            String arch = System.getProperty("os.arch").toLowerCase();

            /* Check if JVM is 64 bit */
            boolean is64bit = arch.equals("amd64") || arch.equals("x86_64");

            /* Extract libraries */
            if (!Files.isDirectory(libraryPath)) {
                Files.createDirectory(libraryPath);
            } else if (Files.exists(libraryPath)) {
                return;
            }
            String[] libraries;
            if (os.contains("win")) {
                /* Windows */
                if (is64bit) {
                    libraries = new String[] { "windows/lwjgl.dll", "windows/glfw.dll", "windows/OpenAL.dll",
                            "windows/jemalloc.dll" };
                } else {
                    libraries = new String[] { "windows/lwjgl32.dll", "windows/glfw32.dll", "windows/OpenAL32.dll",
                            "windows/jemalloc32.dll" };
                }
            } else if (os.contains("mac")) {
                /* Mac OS X */
                libraries = new String[] { "osx/liblwjgl.dylib", "osx/libglfw.dylib", "osx/libopenal.dylib",
                        "osx/libjemalloc.dylib" };

                /* Mac OS X needs headless mode for AWT */
                System.setProperty("java.awt.headless", "true");
            } else if (os.contains("nix") || os.contains("nux") || os.indexOf("aix") > 0) {
                libraries = new String[] { "linux/liblwjgl.so", "linux/libglfw.so", "linux/libopenal.so",
                        "linux/libjemalloc.so" };
            } else {
                /* Not supported */
                throw new RuntimeException(
                        "Operating System " + System.getProperty("os.name") + " is not supported");
            }
            for (String library : libraries) {
                libraryPath.resolve(library).getParent().toFile().mkdirs();
                Files.createFile(libraryPath.resolve(library));
                Files.copy(OpenContext.class.getResourceAsStream("/natives/" + library),
                        libraryPath.resolve(library), StandardCopyOption.REPLACE_EXISTING);
            }
        }

        /* Set LWJGL library path */
        Configuration.LIBRARY_PATH.set(libraryPath.toString());
    }
}