mapbox-unity-sdk icon indicating copy to clipboard operation
mapbox-unity-sdk copied to clipboard

GeoToWorldPosition applies heightmap offset in wrong space (with fix)

Open DennyLindberg opened this issue 8 years ago • 5 comments

Note: I have not included the bug report template because this is a transforms issue. Solution at the bottom.

I have been using AbstractMap.GeoToWorldPosition() to find the world position of latlon coordinates. After some testing I noticed that the height offset is applied on the Y+ axis in world space instead of along the normal of the map surface in local space. Not only is the height offset done in the wrong orientation, but it also disregards scaling from the Root transform.

How to reproduce: Place a map and use GeoToWorldPosition(latlon, true) to place an object on the map. It is correct until you rotate or scale the map transform.

Below are the two relevant functions unmodified. Note that Root.TransformPoint(worldPos) is done before QueryElevationAtInternal is applied as an offset onto worldPos.y. This gives us the incorrect result of localSpace -> worldSpace -> worldSpace + localSpace height.

private Vector3 GeoToWorldPositionXZ(Vector2d latitudeLongitude)
{
	// For quadtree implementation of the map, the map scale needs to be compensated for.
	var scaleFactor = Mathf.Pow(2, (InitialZoom - AbsoluteZoom));
	var worldPos = Conversions.GeoToWorldPosition(latitudeLongitude, CenterMercator, WorldRelativeScale * scaleFactor).ToVector3xz();
	return Root.TransformPoint(worldPos);
}

public virtual Vector3 GeoToWorldPosition(Vector2d latitudeLongitude, bool queryHeight = true)
{
	var worldPos = GeoToWorldPositionXZ(latitudeLongitude);

	if (queryHeight)
	{
		//Query Height.
		float tileScale = 1f;
		worldPos.y = QueryElevationAtInternal(latitudeLongitude, out tileScale);
	}

	return worldPos;
}

Below is a suggestion on how to correct it. (this is what I use until a future update is released)

public virtual Vector3 GeoToWorldPositionCorrected(Vector2d latitudeLongitude, bool queryHeight = true)
{
	if (queryHeight)
	{
		// GeoToWorldPositionXZ without applying Root.TransformPoint
		var scaleFactor = Mathf.Pow(2, (InitialZoom - AbsoluteZoom));
		var localPos = Conversions.GeoToWorldPosition(latitudeLongitude, CenterMercator, WorldRelativeScale * scaleFactor).ToVector3xz();
		
		// Query Height in local space
		float tileScale = 1f;
		localPos.y = QueryElevationAtInternal(latitudeLongitude, out tileScale);

		// Now apply Root.TransformPoint
		return Root.TransformPoint(localPos);
	}
	else
	{
		return GeoToWorldPositionXZ(latitudeLongitude);
	}
}

An additional note is that some places in the code that claims "world position" seems to mix up terminologies between Unity and Mapbox. Sometimes world means the world space (global space) of the scene and sometimes the world position of the map. This is evident with the Conversions.GeoToWorldPosition() function, which actually seems to be in local space of the map transform and not world space in Unity. (otherwise the code would not need to use Root.TransformPoint() on Conversions.GeoToWorldPosition())

DennyLindberg avatar Jun 15 '18 07:06 DennyLindberg

Hey @DennyLindberg,
I haven't tested it yet but even from the explanation and code, it makes perfect sense. Thanks for the detailed explanation and solution. I'll test it out asap. 🙏

brnkhy avatar Jun 23 '18 23:06 brnkhy

@brnkhy, @jordy-isaac Before you test it out, here's an update on my part.

It appears that the UnityTiles get additional scaling behaviors on them which cause some scenarios to break with the suggestion above. I made a revision which has been tested in v1.4.3 that looks like this. I now add the height inside the local space of the unity tile. This code is identical to the original GeoToWorldPosition (shipped with the SDK), except that I have modified the queryHeight part.

public Vector3 GeoToWorldPosition_ConsiderTile(Vector2d latitudeLongitude, bool queryHeight = true)
{
	Vector3 worldPos = GeoToWorldPositionXZ(latitudeLongitude);

	if (queryHeight)
	{
		//Query Height.
		float tileScale = 1f;
		float height = QueryElevationAtInternal(latitudeLongitude, out tileScale);

		// Apply height inside the unity tile space
		UnityTile tile;
		if (MapVisualizer.ActiveTiles.TryGetValue(Conversions.LatitudeLongitudeToTileId(latitudeLongitude.x, latitudeLongitude.y, (int)Zoom), out tile))
		{
			if (tile.gameObject != null)
			{
				// Calculate height in the local space of the tile gameObject.
				// Height is aligned with the y axis in local space.
				// This also helps us avoid scale values when setting the height. 
				var localPos = tile.gameObject.transform.InverseTransformPoint(worldPos);
				localPos.y = height;
				worldPos = tile.gameObject.transform.TransformPoint(localPos);
			}
		}
	}

	return worldPos;
}

Here's an image showing without and with correction. I have tested different scenarios where I have modified the Abstract Map options such as Exaggeration Factor, Use Relative Height and Tile Size. I have also tested this while using the QuadTreeCameraMovement script to translate and zoom. On top of this I have also scaled the map using Unity transform widgets. worldpositionissue

I have also tested the modified function with all examples that are shipped with the SDK and they still look the same. Nothing seems to have been broken in the process.

This code was used for testing. (add it to any MonoBehaviour / script component in the scene) It simply gets the user click -> raytrace map -> convert hitpoint to latlon -> convert latlon back to world position (with/without terrain height). Make sure the terrain generates a collider before using it and that you added the Map layer in Unity.

public AbstractMap _map;
public bool useNewMethod = false;
public bool queryHeight = true;
public GameObject debugObject;
public Camera GetActiveCamera()
{
	Camera cam = Camera.main;
	foreach (Camera c in Camera.allCameras)
	{
		if (c.enabled)
		{
			cam = c;
			break;
		}
	}

	return cam;
}

public bool ScreenToWorldRaycast(Vector3 screenPosition, out RaycastHit hit, string traceLayer = "")
{
	// Select all layers by default if no name is supplied
	int layerMask = string.IsNullOrEmpty(traceLayer) ? ~0 : LayerMask.GetMask(traceLayer);

	Camera cam = GetActiveCamera();
	Ray ray = cam.ScreenPointToRay(screenPosition);

	return Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity, layerMask);
}

void Update () 
{
	if (Input.GetMouseButtonDown(0))
	{
		RaycastHit hit;
		if (ScreenToWorldRaycast(Input.mousePosition, out hit, "Map"))
		{
			Vector2d latLon =  _map.WorldToGeoPosition(hit.point);

			if (debugObject)
			{
				Debug.Log("Clicked at latlon: " + latLon);

				if (useNewMethod)
				{
					debugObject.transform.position = _map.GeoToWorldPosition_ConsiderTile(latLon, queryHeight);
				}
				else
				{
					debugObject.transform.position = _map.GeoToWorldPosition(latLon, queryHeight);
				}
				debugObject.transform.rotation = _map.transform.rotation;
			}
		}
	}
}

DennyLindberg avatar Jun 28 '18 11:06 DennyLindberg

Hey @DennyLindberg! Sorry it took quite some time but I applied this (as the default height query method) and pushed it on this branch; https://github.com/mapbox/mapbox-unity-sdk/pull/979 We'll test and check it as team and merge it for next release if everyone approves.

brnkhy avatar Aug 23 '18 16:08 brnkhy

Merged with #979

abhishektrip avatar Sep 13 '18 04:09 abhishektrip

t all layers by default if no name

You are a champion for figuring that out bro, nice work!

StarKing777 avatar Oct 14 '19 11:10 StarKing777