Search in sources :

Example 31 with Array

use of com.badlogic.gdx.utils.Array in project commons-gdx by gemserk.

the class LibgdxResourceBuilder method animation.

public void animation(final String id, final String textureAtlasId, final String prefix, final int sf, final int ef, final boolean loop, final boolean removeAlias, final float time, final float... times) {
    resourceManager.addVolatile(id, new DataLoader<Animation>() {

        class DuplicatedSpritesRemover {

            float[] times;

            Sprite[] frames;

            public void removeDuplicates(Sprite[] frames, float[] times) {
                ArrayList<Sprite> newSprites = new ArrayList<Sprite>();
                ArrayList<FloatValue> newTimes = new ArrayList<FloatValue>();
                Sprite lastSprite = null;
                int i = 0;
                FloatValue frameTime = null;
                do {
                    Sprite sprite = frames[i];
                    if (SpriteUtils.isAliasSprite(lastSprite, sprite)) {
                        frameTime.value += times[i];
                    } else {
                        newSprites.add(sprite);
                        lastSprite = sprite;
                        frameTime = new FloatValue(times[i]);
                        newTimes.add(frameTime);
                    }
                    i++;
                } while (i < frames.length);
                this.frames = new Sprite[newSprites.size()];
                this.times = new float[newTimes.size()];
                newSprites.toArray(this.frames);
                for (i = 0; i < newTimes.size(); i++) this.times[i] = newTimes.get(i).value;
            }
        }

        FrameAnimationImpl cachedFrameAnimation = null;

        Animation cachedAnimation = null;

        @Override
        public Animation load() {
            if (cachedAnimation == null) {
                TextureAtlas textureAtlas = resourceManager.getResourceValue(textureAtlasId);
                Array<Sprite> sprites = null;
                try {
                    sprites = textureAtlas.createSprites(prefix);
                } catch (GdxRuntimeException e) {
                    throw new RuntimeException("Failed to create animation " + id + " from texture atlas " + textureAtlasId, e);
                }
                if (sprites.size == 0)
                    throw new IllegalArgumentException("Failed to create animation " + id + ", no regions found for prefix " + prefix);
                int endFrame = ef;
                int startFrame = sf;
                if (endFrame == -1)
                    endFrame = sprites.size - 1;
                if (startFrame == -1)
                    startFrame = 0;
                Sprite[] frames = new Sprite[endFrame - startFrame + 1];
                int frameNumber = startFrame;
                if (endFrame >= sprites.size) {
                    throw new IllegalArgumentException("Failed to create animation " + id + ", end frame " + endFrame + " couldn't be greater than sprites quantity " + sprites.size);
                }
                int framesCount = frames.length;
                float[] newTimes = new float[framesCount];
                // newTimes[0] = 0.001f * (float) time;
                newTimes[0] = time;
                float lastTime = newTimes[0];
                for (int i = 1; i < framesCount; i++) {
                    if (i < times.length) {
                        // newTimes[i] = ((float) times[i]) * 0.001f;
                        newTimes[i] = times[i];
                        lastTime = newTimes[i];
                    } else
                        newTimes[i] = lastTime;
                }
                for (int i = 0; i < frames.length; i++) {
                    Sprite sprite = sprites.get(frameNumber);
                    if (sprite instanceof AtlasSprite)
                        frames[i] = new AtlasSprite(((AtlasSprite) sprite).getAtlasRegion());
                    else
                        frames[i] = new Sprite(sprite);
                    frameNumber++;
                }
                if (removeAlias) {
                    int framesBeforeRemoval = frames.length;
                    DuplicatedSpritesRemover duplicatedSpritesRemover = new DuplicatedSpritesRemover();
                    duplicatedSpritesRemover.removeDuplicates(frames, newTimes);
                    frames = duplicatedSpritesRemover.frames;
                    newTimes = duplicatedSpritesRemover.times;
                    Gdx.app.log("commons-gdx", "[" + id + "] frames removed: " + (framesBeforeRemoval - frames.length));
                }
                cachedFrameAnimation = new FrameAnimationImpl(newTimes);
                cachedFrameAnimation.setLoop(loop);
                cachedAnimation = new Animation(frames, cachedFrameAnimation);
            }
            Sprite[] frames = new Sprite[cachedAnimation.getFramesCount()];
            for (int i = 0; i < frames.length; i++) {
                Sprite sprite = cachedAnimation.getFrame(i);
                if (sprite instanceof AtlasSprite)
                    frames[i] = new AtlasSprite(((AtlasSprite) sprite).getAtlasRegion());
                else
                    frames[i] = new Sprite(sprite);
            }
            return new Animation(frames, new FrameAnimationImpl(cachedFrameAnimation));
        }
    });
}
Also used : AtlasSprite(com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasSprite) Sprite(com.badlogic.gdx.graphics.g2d.Sprite) ArrayList(java.util.ArrayList) AtlasSprite(com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasSprite) Array(com.badlogic.gdx.utils.Array) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) FrameAnimationImpl(com.gemserk.animation4j.FrameAnimationImpl) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) TextureAtlas(com.badlogic.gdx.graphics.g2d.TextureAtlas) Animation(com.gemserk.animation4j.gdx.Animation) FloatValue(com.gemserk.commons.values.FloatValue)

Example 32 with Array

use of com.badlogic.gdx.utils.Array in project commons-gdx by gemserk.

the class LibgdxResourceBuilder method splitLoadingTextureAtlas.

public void splitLoadingTextureAtlas(final String id, final String file) {
    FileHandle packFile = Gdx.files.internal(file);
    final TextureAtlasData textureAtlasData = new TextureAtlasData(packFile, packFile.parent(), false);
    Array<Page> pages = textureAtlasData.getPages();
    final String pageTextureSuffix = "_generated_page_";
    for (int i = 0; i < pages.size; i++) {
        Page page = pages.get(i);
        FileHandle textureFile = page.textureFile;
        resource(id + pageTextureSuffix + i, texture2(textureFile).format(page.format).useMipMaps(page.useMipMaps).magFilter(page.magFilter).minFilter(page.minFilter));
    }
    resourceManager.add(id, new DataLoader<TextureAtlas>() {

        @Override
        public TextureAtlas load() {
            Array<Page> pages = textureAtlasData.getPages();
            for (int i = 0; i < pages.size; i++) {
                Page page = pages.get(i);
                try {
                    String textureResourceId = id + pageTextureSuffix + i;
                    page.texture = resourceManager.getResourceValue(textureResourceId);
                    if (page.texture == null)
                        throw new RuntimeException("The resource " + textureResourceId + " was not found");
                } catch (Exception e) {
                    throw new RuntimeException("Error while loading page for textureAtlas " + id + " - page: " + page.textureFile.path(), e);
                }
            }
            return new TextureAtlas(textureAtlasData);
        }

        @Override
        public void unload(TextureAtlas atlas) {
            atlas.dispose();
        }
    });
}
Also used : Array(com.badlogic.gdx.utils.Array) TextureAtlasData(com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) FileHandle(com.badlogic.gdx.files.FileHandle) TextureAtlas(com.badlogic.gdx.graphics.g2d.TextureAtlas) Page(com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData.Page) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException)

Example 33 with Array

use of com.badlogic.gdx.utils.Array in project libgdx by libgdx.

the class BitmapFontWriter method writeFont.

/** Writes the given BitmapFontData to a file, using the specified <tt>pageRefs</tt> strings as the image paths for each
	 * texture page. The glyphs in BitmapFontData have a "page" id, which references the index of the pageRef you specify here.
	 * 
	 * The FontInfo parameter is useful for cleaner output; such as including a size and font face name hint. However, it can be
	 * null to use default values. LibGDX ignores most of the "info" line when reading back fonts, only padding is used. Padding
	 * also affects the size, location, and offset of the glyphs that are output.
	 * 
	 * Likewise, the scaleW and scaleH are only for cleaner output. They are currently ignored by LibGDX's reader. For maximum
	 * compatibility with other BMFont tools, you should use the width and height of your texture pages (each page should be the
	 * same size).
	 * 
	 * @param fontData the bitmap font
	 * @param pageRefs the references to each texture page image file, generally in the same folder as outFntFile
	 * @param outFntFile the font file to save to (typically ends with '.fnt')
	 * @param info the optional info for the file header; can be null
	 * @param scaleW the width of your texture pages
	 * @param scaleH the height of your texture pages */
public static void writeFont(BitmapFontData fontData, String[] pageRefs, FileHandle outFntFile, FontInfo info, int scaleW, int scaleH) {
    if (info == null) {
        info = new FontInfo();
        info.face = outFntFile.nameWithoutExtension();
    }
    int lineHeight = (int) fontData.lineHeight;
    int pages = pageRefs.length;
    int packed = 0;
    int base = (int) ((fontData.capHeight) + (fontData.flipped ? -fontData.ascent : fontData.ascent));
    OutputFormat fmt = BitmapFontWriter.getOutputFormat();
    boolean xml = fmt == OutputFormat.XML;
    StringBuilder buf = new StringBuilder();
    if (xml) {
        buf.append("<font>\n");
    }
    String xmlOpen = xml ? "\t<" : "";
    String xmlCloseSelf = xml ? "/>" : "";
    String xmlTab = xml ? "\t" : "";
    String xmlClose = xml ? ">" : "";
    String xmlQuote = xml ? "\"" : "";
    String alphaChnlParams = xml ? " alphaChnl=\"0\" redChnl=\"0\" greenChnl=\"0\" blueChnl=\"0\"" : " alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0";
    // INFO LINE
    buf.append(xmlOpen).append("info face=\"").append(info.face == null ? "" : info.face.replaceAll("\"", "'")).append("\" size=").append(quote(info.size)).append(" bold=").append(quote(info.bold ? 1 : 0)).append(" italic=").append(quote(info.italic ? 1 : 0)).append(" charset=\"").append(info.charset == null ? "" : info.charset).append("\" unicode=").append(quote(info.unicode ? 1 : 0)).append(" stretchH=").append(quote(info.stretchH)).append(" smooth=").append(quote(info.smooth ? 1 : 0)).append(" aa=").append(quote(info.aa)).append(" padding=").append(xmlQuote).append(info.padding.up).append(",").append(info.padding.right).append(",").append(info.padding.down).append(",").append(info.padding.left).append(xmlQuote).append(" spacing=").append(xmlQuote).append(info.spacing.horizontal).append(",").append(info.spacing.vertical).append(xmlQuote).append(xmlCloseSelf).append("\n");
    // COMMON line
    buf.append(xmlOpen).append("common lineHeight=").append(quote(lineHeight)).append(" base=").append(quote(base)).append(" scaleW=").append(quote(scaleW)).append(" scaleH=").append(quote(scaleH)).append(" pages=").append(quote(pages)).append(" packed=").append(quote(packed)).append(alphaChnlParams).append(xmlCloseSelf).append("\n");
    if (xml)
        buf.append("\t<pages>\n");
    // PAGES
    for (int i = 0; i < pageRefs.length; i++) {
        buf.append(xmlTab).append(xmlOpen).append("page id=").append(quote(i)).append(" file=\"").append(pageRefs[i]).append("\"").append(xmlCloseSelf).append("\n");
    }
    if (xml)
        buf.append("\t</pages>\n");
    // CHARS
    Array<Glyph> glyphs = new Array<Glyph>(256);
    for (int i = 0; i < fontData.glyphs.length; i++) {
        if (fontData.glyphs[i] == null)
            continue;
        for (int j = 0; j < fontData.glyphs[i].length; j++) {
            if (fontData.glyphs[i][j] != null) {
                glyphs.add(fontData.glyphs[i][j]);
            }
        }
    }
    buf.append(xmlOpen).append("chars count=").append(quote(glyphs.size)).append(xmlClose).append("\n");
    int padLeft = 0, padRight = 0, padTop = 0, padX = 0, padY = 0;
    if (info != null) {
        padTop = info.padding.up;
        padLeft = info.padding.left;
        padRight = info.padding.right;
        padX = padLeft + padRight;
        padY = info.padding.up + info.padding.down;
    }
    // CHAR definitions
    for (int i = 0; i < glyphs.size; i++) {
        Glyph g = glyphs.get(i);
        boolean empty = g.width == 0 || g.height == 0;
        buf.append(xmlTab).append(xmlOpen).append("char id=").append(quote(String.format("%-6s", g.id), true)).append("x=").append(quote(String.format("%-5s", empty ? 0 : g.srcX - padLeft), true)).append("y=").append(quote(String.format("%-5s", empty ? 0 : g.srcY - padRight), true)).append("width=").append(quote(String.format("%-5s", empty ? 0 : g.width + padX), true)).append("height=").append(quote(String.format("%-5s", empty ? 0 : g.height + padY), true)).append("xoffset=").append(quote(String.format("%-5s", g.xoffset - padLeft), true)).append("yoffset=").append(quote(String.format("%-5s", fontData.flipped ? g.yoffset + padTop : -(g.height + (g.yoffset + padTop))), true)).append("xadvance=").append(quote(String.format("%-5s", g.xadvance), true)).append("page=").append(quote(String.format("%-5s", g.page), true)).append("chnl=").append(quote(0, true)).append(xmlCloseSelf).append("\n");
    }
    if (xml)
        buf.append("\t</chars>\n");
    // KERNINGS
    int kernCount = 0;
    StringBuilder kernBuf = new StringBuilder();
    for (int i = 0; i < glyphs.size; i++) {
        for (int j = 0; j < glyphs.size; j++) {
            Glyph first = glyphs.get(i);
            Glyph second = glyphs.get(j);
            int kern = first.getKerning((char) second.id);
            if (kern != 0) {
                kernCount++;
                kernBuf.append(xmlTab).append(xmlOpen).append("kerning first=").append(quote(first.id)).append(" second=").append(quote(second.id)).append(" amount=").append(quote(kern, true)).append(xmlCloseSelf).append("\n");
            }
        }
    }
    // KERN info
    buf.append(xmlOpen).append("kernings count=").append(quote(kernCount)).append(xmlClose).append("\n");
    buf.append(kernBuf);
    if (xml) {
        buf.append("\t</kernings>\n");
        buf.append("</font>");
    }
    String charset = info.charset;
    if (charset != null && charset.length() == 0)
        charset = null;
    outFntFile.writeString(buf.toString(), false, charset);
}
Also used : Array(com.badlogic.gdx.utils.Array) Glyph(com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph)

Example 34 with Array

use of com.badlogic.gdx.utils.Array in project libgdx by libgdx.

the class FreeTypeFontGenerator method generateFont.

/** Generates a new {@link BitmapFont}. The size is expressed in pixels. Throws a GdxRuntimeException if the font could not be
	 * generated. Using big sizes might cause such an exception.
	 * @param parameter configures how the font is generated */
public BitmapFont generateFont(FreeTypeFontParameter parameter, FreeTypeBitmapFontData data) {
    generateData(parameter, data);
    if (data.regions == null && parameter.packer != null) {
        data.regions = new Array();
        parameter.packer.updateTextureRegions(data.regions, parameter.minFilter, parameter.magFilter, parameter.genMipMaps);
    }
    BitmapFont font = new BitmapFont(data, data.regions, true);
    font.setOwnsTexture(parameter.packer == null);
    return font;
}
Also used : Array(com.badlogic.gdx.utils.Array) BitmapFont(com.badlogic.gdx.graphics.g2d.BitmapFont)

Example 35 with Array

use of com.badlogic.gdx.utils.Array in project libgdx by libgdx.

the class TexturePackerTest method render.

public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Settings settings = new Settings();
    settings.fast = false;
    settings.pot = false;
    settings.maxWidth = 1024;
    settings.maxHeight = 1024;
    settings.rotation = false;
    settings.paddingX = 0;
    if (pages == null) {
        Random random = new Random(1243);
        Array<Rect> inputRects = new Array();
        for (int i = 0; i < 240; i++) {
            Rect rect = new Rect();
            rect.name = "rect" + i;
            rect.height = 16 + random.nextInt(120);
            rect.width = 16 + random.nextInt(240);
            inputRects.add(rect);
        }
        for (int i = 0; i < 10; i++) {
            Rect rect = new Rect();
            rect.name = "rect" + (40 + i);
            rect.height = 400 + random.nextInt(340);
            rect.width = 1 + random.nextInt(10);
            inputRects.add(rect);
        }
        long s = System.nanoTime();
        pages = new MaxRectsPacker(settings).pack(inputRects);
        long e = System.nanoTime();
        System.out.println("fast: " + settings.fast);
        System.out.println((e - s) / 1e6f + " ms");
        System.out.println();
    }
    int x = 20, y = 20;
    for (Page page : pages) {
        renderer.setColor(Color.GRAY);
        renderer.begin(ShapeType.Filled);
        for (int i = 0; i < page.outputRects.size; i++) {
            Rect rect = page.outputRects.get(i);
            renderer.rect(x + rect.x + settings.paddingX, y + rect.y + settings.paddingY, rect.width - settings.paddingX, rect.height - settings.paddingY);
        }
        renderer.end();
        renderer.setColor(Color.RED);
        renderer.begin(ShapeType.Line);
        for (int i = 0; i < page.outputRects.size; i++) {
            Rect rect = page.outputRects.get(i);
            renderer.rect(x + rect.x + settings.paddingX, y + rect.y + settings.paddingY, rect.width - settings.paddingX, rect.height - settings.paddingY);
        }
        renderer.setColor(Color.GREEN);
        renderer.rect(x, y, page.width + settings.paddingX * 2, page.height + settings.paddingY * 2);
        renderer.end();
        x += page.width + 20;
    }
}
Also used : Array(com.badlogic.gdx.utils.Array) Rect(com.badlogic.gdx.tools.texturepacker.TexturePacker.Rect) Random(java.util.Random) Page(com.badlogic.gdx.tools.texturepacker.TexturePacker.Page) Settings(com.badlogic.gdx.tools.texturepacker.TexturePacker.Settings)

Aggregations

Array (com.badlogic.gdx.utils.Array)67 FileHandle (com.badlogic.gdx.files.FileHandle)18 GdxRuntimeException (com.badlogic.gdx.utils.GdxRuntimeException)16 AssetDescriptor (com.badlogic.gdx.assets.AssetDescriptor)9 Texture (com.badlogic.gdx.graphics.Texture)8 TextureAtlas (com.badlogic.gdx.graphics.g2d.TextureAtlas)7 IntArray (com.badlogic.gdx.utils.IntArray)7 Element (com.badlogic.gdx.utils.XmlReader.Element)7 IOException (java.io.IOException)7 BitmapFont (com.badlogic.gdx.graphics.g2d.BitmapFont)5 TextureRegion (com.badlogic.gdx.graphics.g2d.TextureRegion)5 JsonValue (com.badlogic.gdx.utils.JsonValue)5 ObjectMap (com.badlogic.gdx.utils.ObjectMap)5 Color (com.badlogic.gdx.graphics.Color)4 ModelMaterial (com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial)4 Page (com.badlogic.gdx.tools.texturepacker.TexturePacker.Page)4 Rect (com.badlogic.gdx.tools.texturepacker.TexturePacker.Rect)4 Json (com.badlogic.gdx.utils.Json)4 TextureParameter (com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter)3 GwtFileHandle (com.badlogic.gdx.backends.gwt.GwtFileHandle)3