Example usage for com.badlogic.gdx.utils Array get

List of usage examples for com.badlogic.gdx.utils Array get

Introduction

In this page you can find the example usage for com.badlogic.gdx.utils Array get.

Prototype

public T get(int index) 

Source Link

Usage

From source file:by.aleks.christmasboard.data.BitmapFontWriter.java

License:Apache License

/** 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.
 * /* w  w w .ja  v  a2 s .  c om*/
 * 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. Ultimately, LibGDX ignores the "info" line when reading back fonts.
 * 
 * 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.down)
            .append(",").append(info.padding.left).append(",").append(info.padding.right).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");

    //CHAR definitions
    for (int i = 0; i < glyphs.size; i++) {
        Glyph g = glyphs.get(i);
        buf.append(xmlTab).append(xmlOpen).append("char id=").append(quote(String.format("%-5s", g.id), true))
                .append("x=").append(quote(String.format("%-5s", g.srcX), true)).append("y=")
                .append(quote(String.format("%-5s", g.srcY), true)).append("width=")
                .append(quote(String.format("%-5s", g.width), true)).append("height=")
                .append(quote(String.format("%-5s", g.height), true)).append("xoffset=")
                .append(quote(String.format("%-5s", g.xoffset), true)).append("yoffset=")
                .append(quote(String.format("%-5s", fontData.flipped ? g.yoffset : -(g.height + g.yoffset)),
                        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);
}

From source file:by.aleks.christmasboard.data.BitmapFontWriter.java

License:Apache License

/** A convenience method to write pixmaps by page; typically returned from a PixmapPacker when used alongside
 * FreeTypeFontGenerator./*from   w ww .ja  v  a2s  .c om*/
 * 
 * @param pages the pages containing the Pixmaps
 * @param outputDir the output directory
 * @param fileName the file name
 * @return the file refs */
public static String[] writePixmaps(Array<Page> pages, FileHandle outputDir, String fileName) {
    Pixmap[] pix = new Pixmap[pages.size];
    for (int i = 0; i < pages.size; i++) {
        pix[i] = pages.get(i).getPixmap();
    }
    return writePixmaps(pix, outputDir, fileName);
}

From source file:CB_UI_Base.CB_Texturepacker.MaxRectsPacker.java

License:Apache License

public Array<Page> pack(Array<Rect_Base> inputRects) {
    for (int i = 0, nn = inputRects.size; i < nn; i++) {
        Rect_Base rect = inputRects.get(i);
        rect.width += settings.paddingX;
        rect.height += settings.paddingY;
    }/*from w  w  w.  ja va  2 s  .c om*/

    if (settings.fast) {
        if (settings.rotation) {
            // Sort by longest side if rotation is enabled.
            inputRects.sort(new Comparator<Rect_Base>() {
                public int compare(Rect_Base o1, Rect_Base o2) {
                    int n1 = o1.width > o1.height ? o1.width : o1.height;
                    int n2 = o2.width > o2.height ? o2.width : o2.height;
                    return n2 - n1;
                }
            });
        } else {
            // Sort only by width (largest to smallest) if rotation is disabled.
            inputRects.sort(new Comparator<Rect_Base>() {
                public int compare(Rect_Base o1, Rect_Base o2) {
                    return o2.width - o1.width;
                }
            });
        }
    }

    Array<Page> pages = new Array<Page>();
    while (inputRects.size > 0) {
        Page result = packPage(inputRects);
        pages.add(result);
        inputRects = result.remainingRects;
    }
    return pages;
}

From source file:CB_UI_Base.CB_Texturepacker.MaxRectsPacker.java

License:Apache License

private Page packPage(Array<Rect_Base> inputRects) {
    int edgePaddingX = 0, edgePaddingY = 0;
    if (!settings.duplicatePadding) { // if duplicatePadding, edges get only half padding.
        edgePaddingX = settings.paddingX;
        edgePaddingY = settings.paddingY;
    }/*w w  w  .j a  v a 2s. co  m*/

    // Find min size.
    int minWidth = Integer.MAX_VALUE;
    int minHeight = Integer.MAX_VALUE;
    for (int i = 0, nn = inputRects.size; i < nn; i++) {
        Rect_Base rect = inputRects.get(i);
        minWidth = Math.min(minWidth, rect.width);
        minHeight = Math.min(minHeight, rect.height);
        if (rect.width > settings.maxWidth && (!settings.rotation || rect.height > settings.maxWidth))
            throw new RuntimeException("Image does not fit with max page width " + settings.maxWidth
                    + " and paddingX " + settings.paddingX + ": " + rect);
        if (rect.height > settings.maxHeight && (!settings.rotation || rect.width > settings.maxHeight))
            throw new RuntimeException("Image does not fit in max page height " + settings.maxHeight
                    + " and paddingY " + settings.paddingY + ": " + rect);
    }
    minWidth = Math.max(minWidth, settings.minWidth);
    minHeight = Math.max(minHeight, settings.minHeight);

    System.out.print("Packing");

    // Find the minimal page size that fits all rects.
    BinarySearch widthSearch = new BinarySearch(minWidth, settings.maxWidth, settings.fast ? 25 : 15,
            settings.pot);
    BinarySearch heightSearch = new BinarySearch(minHeight, settings.maxHeight, settings.fast ? 25 : 15,
            settings.pot);
    int width = widthSearch.reset(), height = heightSearch.reset(), i = 0;
    Page bestResult = null;
    while (true) {
        Page bestWidthResult = null;
        while (width != -1) {
            Page result = packAtSize(true, width - edgePaddingX, height - edgePaddingY, inputRects);
            if (++i % 70 == 0)
                System.out.println();
            System.out.print(".");
            bestWidthResult = getBest(bestWidthResult, result);
            width = widthSearch.next(result == null);
        }
        bestResult = getBest(bestResult, bestWidthResult);
        height = heightSearch.next(bestWidthResult == null);
        if (height == -1)
            break;
        width = widthSearch.reset();
    }
    System.out.println();

    // Rects don't fit on one page. Fill a whole page and return.
    if (bestResult == null)
        bestResult = packAtSize(false, settings.maxWidth - edgePaddingX, settings.maxHeight - edgePaddingY,
                inputRects);

    return bestResult;
}

From source file:CB_UI_Base.CB_Texturepacker.MaxRectsPacker.java

License:Apache License

/**
 * @param fully/*from  w  ww. ja v a 2s . co  m*/
 *            If true, the only results that pack all rects will be considered. If false, all results are considered, not all rects may
 *            be packed.
 */
private Page packAtSize(boolean fully, int width, int height, Array<Rect_Base> inputRects) {
    Page bestResult = null;
    for (int i = 0, n = methods.length; i < n; i++) {
        maxRects.init(width, height);
        Page result;
        if (!settings.fast) {
            result = maxRects.pack(inputRects, methods[i]);
        } else {
            Array<Rect_Base> remaining = new Array<Rect_Base>();
            for (int ii = 0, nn = inputRects.size; ii < nn; ii++) {
                Rect_Base rect = inputRects.get(ii);
                if (maxRects.insert(rect, methods[i]) == null) {
                    while (ii < nn)
                        remaining.add(inputRects.get(ii++));
                }
            }
            result = maxRects.getResult();
            result.remainingRects = remaining;
        }
        if (fully && result.remainingRects.size > 0)
            continue;
        if (result.outputRects.size == 0)
            continue;
        bestResult = getBest(bestResult, result);
    }
    return bestResult;
}

From source file:cocos2d.touch_dispatcher.CCTouchDispatcher.java

License:Open Source License

protected void forceAddHandler(CCTouchHandler pHandler, Array<CCTouchHandler> pArray) {
    int u = 0;/*from   w  ww  . j a  v  a2s  .c o m*/
    for (int i = 0; i < pArray.size; i++) {
        CCTouchHandler h = pArray.get(i);

        if (h != null) {
            if (h.getPriority() < pHandler.getPriority()) {
                ++u;
            }

            if (h.getDelegate() == pHandler.getDelegate()) {
                return;
            }
        }
    }

    pArray.insert(u, pHandler);
}

From source file:com.agateau.pixelwheels.GameWorld.java

License:Open Source License

private void setupRacers(Array<GameInfo.Entrant> entrants) {
    VehicleCreator creator = new VehicleCreator(mGame.getAssets(), this);
    Assets assets = mGame.getAssets();//from ww w  . j  a v a 2s . c  om

    final float startAngle = 90;
    Array<Vector2> positions = mTrack.findStartTilePositions();
    positions.reverse();

    AudioManager audioManager = mGame.getAudioManager();
    for (int idx = 0; idx < entrants.size; ++idx) {
        Assert.check(idx < positions.size, "Too many entrants");
        GameInfo.Entrant entrant = entrants.get(idx);
        VehicleDef vehicleDef = assets.findVehicleDefById(entrant.getVehicleId());
        Vehicle vehicle = creator.create(vehicleDef, positions.get(idx), startAngle);
        Racer racer = new Racer(assets, audioManager, this, vehicle, entrant);
        if (entrant.isPlayer()) {
            GameInfo.Player player = (GameInfo.Player) entrant;
            PlayerPilot pilot = new PlayerPilot(assets, this, racer, mGame.getConfig(), player.getIndex());
            racer.setPilot(pilot);
            mPlayerRacers.add(racer);
        } else {
            racer.setPilot(new AIPilot(this, mTrack, racer));
        }
        addGameObject(racer);
        mRacers.add(racer);
    }
}

From source file:com.agateau.pixelwheels.map.LapPositionTableIO.java

License:Open Source License

public static LapPositionTable load(TiledMap map) {
    MapLayer layer = map.getLayers().get("Sections");
    Assert.check(layer != null, "No 'Sections' layer found");
    MapObjects objects = layer.getObjects();

    Array<Line> lines = new Array<Line>();
    lines.ensureCapacity(objects.getCount());
    Set<String> names = new HashSet<String>();
    for (MapObject obj : objects) {
        String name = obj.getName();
        Assert.check(!name.isEmpty(), "Section line is missing a name");
        Assert.check(!names.contains(name), "Duplicate section line " + name);
        names.add(name);/*  w w  w. j a v a 2s .co  m*/

        float order;
        try {
            order = Float.parseFloat(name);
        } catch (NumberFormatException e) {
            throw new RuntimeException("Invalid section name " + name);
        }
        Assert.check(obj instanceof PolylineMapObject,
                "'Sections' layer should only contain PolylineMapObjects");
        Polyline polyline = ((PolylineMapObject) obj).getPolyline();
        float[] vertices = polyline.getTransformedVertices();
        Assert.check(vertices.length == 4,
                "Polyline with name " + order + "should have 2 points, not " + (vertices.length / 2));
        Line line = new Line();
        line.x1 = vertices[0];
        line.y1 = vertices[1];
        line.x2 = vertices[2];
        line.y2 = vertices[3];
        line.order = order;
        lines.add(line);
    }
    lines.sort();

    LapPositionTable table = new LapPositionTable();
    for (int idx = 0; idx < lines.size; ++idx) {
        Line line1 = lines.get(idx);
        Line line2 = lines.get((idx + 1) % lines.size);
        float[] vertices = { line1.x1, line1.y1, line2.x1, line2.y1, line2.x2, line2.y2, line1.x2, line1.y2 };
        Polygon polygon = new Polygon(vertices);
        table.addSection(idx, polygon);
    }
    return table;
}

From source file:com.agateau.pixelwheels.map.Track.java

License:Open Source License

private TiledMapTile getTopTileAt(Array<TiledMapTileLayer> layers, float x, float y) {
    int tx = MathUtils.floor(x / mTileWidth);
    int ty = MathUtils.floor(y / mTileHeight);
    for (int idx = layers.size - 1; idx >= 0; idx--) {
        TiledMapTileLayer.Cell cell = layers.get(idx).getCell(tx, ty);
        if (cell != null) {
            return cell.getTile();
        }/*from  w ww  . j a v a2  s . com*/
    }
    return null;
}

From source file:com.agateau.pixelwheels.racer.Racer.java

License:Open Source License

public void selectBonus() {
    float normalizedRank = mGameWorld.getRacerNormalizedRank(this);

    Array<BonusPool> pools = mGameWorld.getBonusPools();
    float totalCount = 0;
    for (BonusPool pool : pools) {
        totalCount += pool.getCountForNormalizedRank(normalizedRank);
    }//from   ww w  . j  a v a2s .c o m

    // To avoid allocating an array of the counts for each normalized rank, we subtract counts
    // from pick, until it is less than 0, at this point we are on the selected pool
    float pick = MathUtils.random(0f, totalCount);
    BonusPool pool = null;
    for (int idx = 0; idx < pools.size; ++idx) {
        pool = pools.get(idx);
        pick -= pool.getCountForNormalizedRank(normalizedRank);
        if (pick < 0) {
            break;
        }
    }
    if (pool == null) {
        pool = pools.get(pools.size - 1);
    }

    mBonus = (Bonus) pool.obtain();
    mBonus.onPicked(this);
}