com.badlogic.gdx.maps.MapLayer Java Examples

The following examples show how to use com.badlogic.gdx.maps.MapLayer. 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: UAtlasTmxMapLoader.java    From uracer-kotd with Apache License 2.0 6 votes vote down vote up
protected void loadObjectGroup (TiledMap map, Element element) {
	if (element.getName().equals("objectgroup")) {
		String name = element.getAttribute("name", null);
		MapLayer layer = new MapLayer();
		layer.setName(name);
		Element properties = element.getChildByName("properties");
		if (properties != null) {
			loadProperties(layer.getProperties(), properties);
		}

		for (Element objectElement : element.getChildrenByName("object")) {
			loadObject(layer, objectElement);
		}

		map.getLayers().add(layer);
	}
}
 
Example #2
Source File: Box2DMapObjectParser.java    From Entitas-Java with MIT License 6 votes vote down vote up
/**
 * @param map the {@link Map} which hierarchy to print
 * @return a human readable {@link String} containing the hierarchy of the {@link com.badlogic.gdx.maps.MapObjects} of the given {@link Map}
 */
public String getHierarchy(Map map) {
    String hierarchy = map.getClass().getName() + "\n", key, layerHierarchy;

    Iterator<String> keys = map.getProperties().getKeys();
    while (keys.hasNext())
        hierarchy += (key = keys.next()) + ": " + map.getProperties().get(key) + "\n";

    for (MapLayer layer : map.getLayers()) {
        hierarchy += "\t" + layer.getName() + " (" + layer.getClass().getName() + "):\n";
        layerHierarchy = getHierarchy(layer).replace("\n", "\n\t\t");
        layerHierarchy = layerHierarchy.endsWith("\n\t\t") ? layerHierarchy.substring(0, layerHierarchy.lastIndexOf("\n\t\t")) : layerHierarchy;
        hierarchy += !layerHierarchy.equals("") ? "\t\t" + layerHierarchy : layerHierarchy;
    }

    return hierarchy;
}
 
Example #3
Source File: GameWorld.java    From uracer-kotd with Apache License 2.0 5 votes vote down vote up
private void createMeshes () {
	staticMeshes.clear();
	TotalMeshes = 0;

	// static meshes layer
	if (mapUtils.hasObjectGroup(ObjectGroup.StaticMeshes)) {
		MapLayer group = mapUtils.getObjectGroup(ObjectGroup.StaticMeshes);
		for (int i = 0; i < group.getObjects().getCount(); i++) {
			MapObject o = group.getObjects().get(i);

			float scale = 1f;
			if (o.getProperties().get(ObjectProperties.MeshScale.mnemonic) != null) {
				scale = Float.parseFloat(o.getProperties().get(ObjectProperties.MeshScale.mnemonic, String.class));
			}

			// @off
			OrthographicAlignedStillModel mesh = ModelFactory.create(
				o.getProperties().get("type", String.class),
				o.getProperties().get("x", Integer.class),
				o.getProperties().get("y", Integer.class),
				scale * pixelsPerMeterFactor
			);
			// @on

			if (mesh != null) {
				staticMeshes.add(mesh);
			}
		}
	}

	// walls by polylines
	List<OrthographicAlignedStillModel> walls = createWalls();
	trackWalls = new TrackWalls(walls);

	// trees
	List<TreeStillModel> trees = createTrees();
	trackTrees = new TrackTrees(trees);

	TotalMeshes = staticMeshes.size() + trackWalls.count() + trackTrees.count();
}
 
Example #4
Source File: MapUtils.java    From uracer-kotd with Apache License 2.0 5 votes vote down vote up
public MapLayer getObjectGroup (ObjectGroup group) {
	MapLayer cached = cachedGroups.get(group.mnemonic);
	if (cached == null) {
		cached = map.getLayers().get(group.mnemonic);
		cachedGroups.put(group.mnemonic, cached);
	}

	return cached;
}
 
Example #5
Source File: CollectibleRenderer.java    From ninja-rabbit with GNU General Public License v2.0 5 votes vote down vote up
public void load(final World world, final BodyEditorLoader loader, final AssetManager assets, final MapLayer layer,
		final Object userData) {
	if (layer == null) {
		return;
	}

	for (MapObject mo : layer.getObjects()) {
		BodyDef bodyDefinition = new BodyDef();
		bodyDefinition.type = BodyType.KinematicBody;
		float x = ((Float) mo.getProperties().get("x")).floatValue() * unitScale;
		float y = ((Float) mo.getProperties().get("y")).floatValue() * unitScale;
		bodyDefinition.position.set(x, y);

		BodyFactory bodyFactory = null;
		Entity entity = null;

		if (CARROT_TYPE.equals(mo.getProperties().get(TYPE_PROPERTY, CARROT_TYPE, String.class))) {
			bodyFactory = new CarrotBodyFactory(loader);
			entity = EntityFactory.createCollectible(world, assets);
		} else {
			throw new IllegalArgumentException("Unknown collectible type {" + mo.getProperties().get(TYPE_PROPERTY, String.class) + "}");
		}

		Body body = bodyFactory.create(world, bodyDefinition);

		entity.setBody(body);
		body.setUserData(entity);
		collectibles.add(entity);
	}
}
 
Example #6
Source File: WorldRenderer.java    From killingspree with MIT License 5 votes vote down vote up
public void loadLevel(String level, boolean isServer, String name) {
    this.isServer = isServer;
    map = new TmxMapLoader().load(level);
    TiledMapTileLayer layer = (TiledMapTileLayer) map.
                                getLayers().get("terrain");
    VIEWPORT_WIDTH = (int) (layer.getTileWidth() * layer.getWidth());
    VIEWPORT_HEIGHT = (int) (layer.getTileHeight() * layer.getHeight());
    viewport = new FitViewport(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, camera);
    renderer = new OrthogonalTiledMapRenderer(map);
    name = name.trim();
    if (name.length() == 0)
        name = "noname";
    if (name.length() >= 10){
        name = name.substring(0, 10);
    }
    ClientDetailsMessage clientDetails = new ClientDetailsMessage();
    clientDetails.name = name;
    clientDetails.protocolVersion = Constants.PROTOCOL_VERSION;
    if (isServer) {
        MapLayer collision =  map.
                getLayers().get("collision");
        for(MapObject object: collision.getObjects()) {
            worldManager.createWorldObject(object);
        }
        worldManager.addIncomingEvent(MessageObjectPool.instance.
                eventPool.obtain().set(State.RECEIVED, clientDetails));
    } else {
        client.sendTCP(clientDetails);
    }
    controls = new onScreenControls();
    
}
 
Example #7
Source File: Box2DMapObjectParser.java    From Entitas-Java with MIT License 5 votes vote down vote up
/**
 * @param layer the {@link MapLayer} which hierarchy to print
 * @return a human readable {@link String} containing the hierarchy of the {@link com.badlogic.gdx.maps.MapObjects} of the given {@link MapLayer}
 */
public String getHierarchy(MapLayer layer) {
    String hierarchy = "", key;

    for (MapObject object : layer.getObjects()) {
        hierarchy += object.getName() + " (" + object.getClass().getName() + "):\n";
        Iterator<String> keys = object.getProperties().getKeys();
        while (keys.hasNext())
            hierarchy += "\t" + (key = keys.next()) + ": " + object.getProperties().get(key) + "\n";
    }

    return hierarchy;
}
 
Example #8
Source File: Box2DMapObjectParser.java    From Entitas-Java with MIT License 5 votes vote down vote up
/**
 * creates the given {@link Map Map's} {@link com.badlogic.gdx.maps.MapObjects} in the given {@link World}
 *
 * @param world the {@link World} to create the {@link com.badlogic.gdx.maps.MapObjects} of the given {@link Map} in
 * @param map   the {@link Map} which {@link com.badlogic.gdx.maps.MapObjects} to create in the given {@link World}
 * @return the given {@link World} with the parsed {@link com.badlogic.gdx.maps.MapObjects} of the given {@link Map} created in it
 */
public World load(World world, Map map) {
    if (!ignoreMapUnitScale)
        unitScale = getProperty(map.getProperties(), aliases.unitScale, unitScale);
    box2dObjectFactory.setUnitScale(unitScale);
    tileWidth = getProperty(map.getProperties(), "tilewidth", (int) tileWidth);
    tileHeight = getProperty(map.getProperties(), "tileheight", (int) tileHeight);

    for (MapLayer mapLayer : map.getLayers())
        load(world, mapLayer);

    return world;
}
 
Example #9
Source File: Map.java    From RuinsOfRevenge with MIT License 4 votes vote down vote up
public Map(FileLocation loc, String mapfile, Physics physics) {
	TmxObjectsLoader objs = null;
	try {
		objs = new TmxObjectsLoader(new XmlReader().parse(loc.getFile(mapfile)));
	} catch (IOException e) {
		e.printStackTrace();
	}
	this.map = new TmxMapLoader(loc.getResolver()).load(mapfile);
	this.renderer = new OrthogonalTiledMapRenderer(map, 1f / objs.getTileWidth());

	fringeLayerIndex = computeEntityLayer();
	if (fringeLayerIndex == 999) {
		belowEntities = new int[map.getLayers().getCount()];
		aboveEntities = new int[0];
		fillCounting(0, belowEntities);
		fringeLayer = null;
	} else {
		belowEntities = new int[fringeLayerIndex];
		aboveEntities = new int[map.getLayers().getCount()-fringeLayerIndex-1];
		fillCounting(0, belowEntities);
		fillCounting(fringeLayerIndex+1, aboveEntities);
		MapLayer mapLayer = map.getLayers().get(fringeLayerIndex);
		if (mapLayer instanceof TiledMapTileLayer) {
			fringeLayer = new FringeLayer(map, (TiledMapTileLayer) mapLayer);
		} else {
			fringeLayer = null;
		}
	}

	if (physics != null) {
		for (TmxObjectsLoader.TmxObjectGroup group : objs.getObjectGroups()) {
			for (TmxObjectsLoader.TmxObject obj : group.objects) {
				if (!obj.name.equalsIgnoreCase("spawnpoint")) {
					objs.loadToPhysics(obj, physics);
				} else {
					spawnpoint.set(obj.x / objs.getTileWidth(), obj.y / objs.getTileHeight());
				}
			}
		}
	}
}
 
Example #10
Source File: CollectibleRenderer.java    From ninja-rabbit with GNU General Public License v2.0 4 votes vote down vote up
public void load(final World world, final BodyEditorLoader loader, final AssetManager assets, final MapLayer layer) {
	load(world, loader, assets, layer, null);
}
 
Example #11
Source File: LevelFactory.java    From ninja-rabbit with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Loads a tiled map described by the given level number. Creates {@link CollectibleRenderer}
 * for collectible layers (every layer which name starts with "collectible").
 *
 * @param world
 *            The Box2D {@link World} used to create bodies and fixtures from objects layers in
 *            the map.
 * @param loader
 * @param batch
 *            A {@link Batch} to use while rendering tiles.
 * @param assets
 *            {@link AssetManager} from where to get audio and graphics resources for the
 *            collectibles.
 * @param level
 *            Number of the level the returned render should draw.
 * @param unitScale
 *            Pixels per unit.
 *
 * @return A new {@link LevelRenderer}, ready to render the map, its bodies and collectibles.
 */
public static LevelRenderer create(final World world, final BodyEditorLoader loader, final Batch batch,
		final AssetManager assets, final byte level,
		final float unitScale) {
	TiledMap tiledMap = new TmxMapLoader().load(String.format(LEVEL_MAP_FILE, level));
	LevelRenderer renderer = new LevelRenderer(tiledMap, assets, batch, unitScale);

	for (MapLayer ml : tiledMap.getLayers()) {
		if (ml.getName().toLowerCase().startsWith(COLLECTIBLES_LAYER)) {
			CollectibleRenderer carrots = new CollectibleRenderer(unitScale);
			carrots.load(world, loader, assets, ml);
			renderer.addCollectibleRenderer(carrots);
		}
	}
	return renderer;
}
 
Example #12
Source File: Map.java    From Norii with Apache License 2.0 4 votes vote down vote up
public MapLayer getCollisionLayer() {
	return collisionLayer;
}
 
Example #13
Source File: MapManager.java    From Norii with Apache License 2.0 4 votes vote down vote up
public MapLayer getCollisionLayer(){
    return currentMap.getCollisionLayer();
}
 
Example #14
Source File: GameWorld.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
private List<TreeStillModel> createTrees () {
	List<TreeStillModel> models = null;

	if (mapUtils.hasObjectGroup(ObjectGroup.Trees)) {

		// We want to differentiate tree meshes as much as we can
		// rotation will helps immensely, but non-orthogonal rotations
		// will cause the bounding box to get recomputed only approximately
		// thus loosing precision: orthogonal rotations instead provides
		// high
		// quality AABB recomputation.
		//
		// We still have 4 variations for any given tree!
		treeRotations[0] = 0;
		treeRotations[1] = 90;
		treeRotations[2] = 180;
		treeRotations[3] = 270;

		MathUtils.random.setSeed(Long.MAX_VALUE);
		MapLayer group = mapUtils.getObjectGroup(ObjectGroup.Trees);

		if (group.getObjects().getCount() > 0) {

			models = new ArrayList<TreeStillModel>(group.getObjects().getCount());

			for (int i = 0; i < group.getObjects().getCount(); i++) {
				RectangleMapObject o = (RectangleMapObject)group.getObjects().get(i);

				float scale = 1f;
				if (o.getProperties().get(ObjectProperties.MeshScale.mnemonic) != null) {
					scale = Float.parseFloat(o.getProperties().get(ObjectProperties.MeshScale.mnemonic, String.class));
				}

				TreeStillModel model = null;
				if (o.getProperties().get("type") != null) {
					//@off
					model = ModelFactory.createTree(
						o.getProperties().get("type", String.class),
						o.getRectangle().x,
						worldSizePx.y - o.getRectangle().y,
						scale);
					//@on
				} else {
					Gdx.app.log("TrackTrees", "Load error, no type was given for the tree #" + (i + 1));
				}

				if (model != null) {
					// model.setRotation( MathUtils.random( -180f, 180f ),
					// 0, 0, 1f );
					model.setRotation(treeRotations[MathUtils.random(0, 3)], 0, 0, 1f);
					models.add(nextIndexForTrees(models, model), model);
				}
			}
		}
	}

	return models;
}
 
Example #15
Source File: GameWorld.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
private List<OrthographicAlignedStillModel> createWalls () {
	List<OrthographicAlignedStillModel> models = null;

	if (mapUtils.hasObjectGroup(ObjectGroup.Walls)) {
		Vector2 fromMt = new Vector2();
		Vector2 toMt = new Vector2();
		Vector2 offsetMt = new Vector2();

		// create material
		TextureAttribute ta = new TextureAttribute(Art.meshTrackWall, 0, "u_texture");
		ta.uWrap = TextureWrap.Repeat.getGLEnum();
		ta.vWrap = TextureWrap.Repeat.getGLEnum();
		Material mat = new Material("trackWall", ta);

		MapLayer group = mapUtils.getObjectGroup(ObjectGroup.Walls);
		if (group.getObjects().getCount() > 0) {
			models = new ArrayList<OrthographicAlignedStillModel>(group.getObjects().getCount());

			for (int i = 0; i < group.getObjects().getCount(); i++) {
				PolylineMapObject o = (PolylineMapObject)group.getObjects().get(i);

				//@off
				List<Vector2> points = MapUtils.extractPolyData(
					o.getPolyline().getVertices());
				//@on
				if (points.size() >= 2) {
					float wallTicknessMt = 0.75f;
					float[] mags = new float[points.size() - 1];

					offsetMt.set(o.getPolyline().getX(), o.getPolyline().getY());
					offsetMt.set(Convert.px2mt(offsetMt));

					fromMt.set(Convert.px2mt(points.get(0))).add(offsetMt);
					fromMt.y = worldSizeMt.y - fromMt.y;

					for (int j = 1; j <= points.size() - 1; j++) {
						toMt.set(Convert.px2mt(points.get(j))).add(offsetMt);
						toMt.y = worldSizeMt.y - toMt.y;

						// create box2d wall
						Box2DFactory.createWall(box2dWorld, fromMt, toMt, wallTicknessMt, 0f);

						// compute magnitude
						mags[j - 1] = (float)Math.sqrt((toMt.x - fromMt.x) * (toMt.x - fromMt.x) + (toMt.y - fromMt.y)
							* (toMt.y - fromMt.y));

						fromMt.set(toMt);
					}

					Mesh mesh = buildWallMesh(points, mags);

					StillSubMesh[] subMeshes = new StillSubMesh[1];
					subMeshes[0] = new StillSubMesh("wall", mesh, GL20.GL_TRIANGLES);

					OrthographicAlignedStillModel model = new OrthographicAlignedStillModel(new StillModel(subMeshes), mat);

					model.setPosition(o.getPolyline().getX(), worldSizePx.y - o.getPolyline().getY());
					model.setScale(1);

					models.add(model);
				}
			}
		}
	}

	return models;
}
 
Example #16
Source File: GameWorld.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
private List<Polygon> createTrackPolygons () {
	List<Polygon> s = null;

	if (mapUtils.hasObjectGroup(ObjectGroup.Sectors)) {
		Vector2 pt = new Vector2();
		Vector2 offsetMt = new Vector2();

		MapLayer group = mapUtils.getObjectGroup(ObjectGroup.Sectors);
		if (group.getObjects().getCount() > 0) {
			s = new ArrayList<Polygon>(group.getObjects().getCount());

			for (int i = 0; i < group.getObjects().getCount(); i++) {
				PolygonMapObject o = (PolygonMapObject)group.getObjects().get(i);

				//@off
				List<Vector2> points = MapUtils.extractPolyData(
					o.getPolygon().getVertices()
				);
				//@on

				if (points.size() != 4) {
					throw new GdxRuntimeException("A quadrilateral is required!");
				}

				offsetMt.set(o.getPolygon().getX(), o.getPolygon().getY());
				offsetMt.set(Convert.px2mt(offsetMt));

				float[] vertices = new float[8];
				for (int j = 0; j < points.size(); j++) {
					// convert to uracer convention
					pt.set(Convert.px2mt(points.get(j))).add(offsetMt);
					pt.y = worldSizeMt.y - pt.y;

					vertices[j * 2] = pt.x;
					vertices[j * 2 + 1] = pt.y;
				}

				Polygon p = new Polygon(vertices);
				Rectangle r = p.getBoundingRectangle();
				float oX = r.x + r.width / 2;
				float oY = r.y + r.height / 2;
				p.setOrigin(oX, oY);

				s.add(p);
			}

		} else {
			throw new GdxRuntimeException("There are no defined sectors for this track");
		}

	}

	return s;

}
 
Example #17
Source File: GameWorld.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
private List<Vector2> createRoute () {
	List<Vector2> r = null;

	if (mapUtils.hasObjectGroup(ObjectGroup.Route)) {
		Vector2 fromMt = new Vector2();
		Vector2 toMt = new Vector2();
		Vector2 offsetMt = new Vector2();

		MapLayer group = mapUtils.getObjectGroup(ObjectGroup.Route);
		if (group.getObjects().getCount() == 1) {
			PolylineMapObject o = (PolylineMapObject)group.getObjects().get(0);

			//@off
			List<Vector2> points = MapUtils.extractPolyData(
				o.getPolyline().getVertices());
			//@on

			r = new ArrayList<Vector2>(points.size());

			offsetMt.set(o.getPolyline().getX(), o.getPolyline().getY());
			offsetMt.set(Convert.px2mt(offsetMt));

			fromMt.set(Convert.px2mt(points.get(0))).add(offsetMt);
			fromMt.y = worldSizeMt.y - fromMt.y;

			r.add(new Vector2(fromMt));

			for (int j = 1; j <= points.size() - 1; j++) {
				toMt.set(Convert.px2mt(points.get(j))).add(offsetMt);
				toMt.y = worldSizeMt.y - toMt.y;
				r.add(new Vector2(toMt));
			}
		} else {
			if (group.getObjects().getCount() > 1) {
				throw new GdxRuntimeException("Too many routes");
			} else if (group.getObjects().getCount() == 0) {
				throw new GdxRuntimeException("No route defined for this track");
			}
		}

	}

	return r;
}
 
Example #18
Source File: GameWorld.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
private void createLights () {
		if (!mapUtils.hasObjectGroup(ObjectGroup.Lights)) {
			this.nightMode = false;
			return;
		}

		float rttScale = 0.5f;
		int maxRays = 360;

		if (!URacer.Game.isDesktop()) {
			rttScale = 0.2f;
			maxRays = 360;
		}

		RayHandler.setColorPrecisionHighp();

		rayHandler = new RayHandler(box2dWorld, maxRays, (int)(ScaleUtils.PlayWidth * rttScale),
			(int)(ScaleUtils.PlayHeight * rttScale), true);
		rayHandler.setShadows(true);
		rayHandler.setCulling(true);
		rayHandler.setBlur(true);
		rayHandler.setBlurNum(2);
		rayHandler.setAmbientLight(0.1f, 0.05f, 0.1f, 0.4f);

		final Color c = new Color();

		// setup player headlights data
		c.set(0.1f, 0.2f, 0.9f, 0.85f);

		int headlightsMask = CollisionFilters.CategoryTrackWalls;
		// int headlightsMask = CollisionFilters.CategoryTrackWalls | CollisionFilters.CategoryReplay;
		// int headlightsMask = CollisionFilters.CategoryReplay;
		// int headlightsMask = 0;

		playerHeadlightsA = new ConeLight(rayHandler, maxRays, c, 25, 0, 0, 0, 9);
		playerHeadlightsA.setSoft(true);
		playerHeadlightsA.setMaskBits(headlightsMask);

		playerHeadlightsB = new ConeLight(rayHandler, maxRays, c, 25, 0, 0, 0, 9);
		playerHeadlightsB.setSoft(true);
		playerHeadlightsB.setMaskBits(headlightsMask);

		// setup level lights data, if any
		Vector2 pos = new Vector2();
		MapLayer group = mapUtils.getObjectGroup(ObjectGroup.Lights);

		int lights_count = group.getObjects().getCount();
		lights = new PointLight[lights_count];

		for (int i = 0; i < lights_count; i++) {
			//@off
			c.set(
//			 MathUtils.random(0,1),
//			 MathUtils.random(0,1),
//			 MathUtils.random(0,1),
							1f, .85f, 0.6f, 0.8f
//				MathUtils.random(0.85f,1),
//				MathUtils.random(0.8f,0.85f),
//				MathUtils.random(0.6f,0.8f),
//				0.55f
			);
			//@on

			RectangleMapObject o = (RectangleMapObject)group.getObjects().get(i);
			pos.set(o.getRectangle().x, o.getRectangle().y);// .scl(scalingStrategy.invTileMapZoomFactor);
			pos.y = worldSizePx.y - pos.y;
			pos.set(Convert.px2mt(pos));// .scl(scalingStrategy.tileMapZoomFactor);

			PointLight l = new PointLight(rayHandler, maxRays, c, MathUtils.random(15, 20), pos.x, pos.y);
			l.setSoft(true);
			l.setStaticLight(false);
			l.setMaskBits(CollisionFilters.CategoryPlayer | CollisionFilters.CategoryTrackWalls);

			lights[i] = l;
		}

		// playerImpulse = new PointLight(rayHandler, maxRays);
		// playerImpulse.setMaskBits(CollisionFilters.CategoryPlayer | CollisionFilters.CategoryReplay);
		// playerImpulse.setSoft(true);
		// playerImpulse.setStaticLight(false);
		// playerImpulse.setActive(true);
		// playerImpulse.setColor(1, 1, 1, 1f);
		// playerImpulse.setDistance(5);
	}