Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable immediate mode rendering for custom layer in globe view #12143

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 162 additions & 0 deletions debug/custom-layer-globe.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html>
<head>
<title>Mapbox GL JS debug page</title>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel='stylesheet' href='../dist/mapbox-gl.css' />
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>

<body>
<div id='map'></div>

<script src='../dist/mapbox-gl-dev.js'></script>
<script src='../debug/access_token_generated.js'></script>
<script src="https://unpkg.com/three@0.126.0/build/three.min.js"></script>
<script>

const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [0, 0],
antialias: true, // create the gl context with MSAA antialiasing, so custom layers are antialiased
hash:true,
projection: 'globe'
});

const modelOrigin = [0, 35];
const modelAltitude = 100000;
const modelRotate = [Math.PI / 2, 0, 0];
const modelScale = 50000;

const DEG_TO_RAD = Math.PI / 180;
function degToRad(a) {
return a * DEG_TO_RAD;
}

const THREE = window.THREE;
let prevTime = Date.now();

const modelRadiusMeters = 20;

const customLayer = {
id: '3d-model',
type: 'custom',
renderingMode: '3d',
onAdd (map, gl) {
this.camera = new THREE.Camera();
this.scene = new THREE.Scene();

const geometry = new THREE.SphereGeometry(modelRadiusMeters, 32, 16);
const material = new THREE.MeshBasicMaterial({color: 0x8d9294, side: THREE.DoubleSide});
const cone = new THREE.Mesh(geometry, material);
this.scene.add(cone);

this.map = map;

this.renderer = new THREE.WebGLRenderer({
canvas: map.getCanvas(),
context: gl,
antialias: true
});

this.renderer.autoClear = false;
},
render (gl, projectionMatrix, globeMatrix) {
const now = Date.now();

const rotationX = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(1, 0, 0),
modelRotate[0]
);
const rotationY = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 1, 0),
modelRotate[1]
);
const rotationZ = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 0, 1),
modelRotate[2]
);

const projection = new THREE.Matrix4().fromArray(projectionMatrix);

let model;
const translate = new THREE.Matrix4().makeTranslation(0, modelRadiusMeters, 0);

if (globeMatrix !== null) {

const modelInEcef = mapboxgl.MercatorCoordinate.lngLatToEcef(modelOrigin, modelAltitude);
const scale = modelScale * mapboxgl.MercatorCoordinate.meterToEcefUnits();

const rotEcefX = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(1, 0, 0),
degToRad(modelOrigin[1])
);
const rotEcefY = new THREE.Matrix4().makeRotationAxis(
new THREE.Vector3(0, 1, 0),
degToRad(modelOrigin[0])
);

const world = new THREE.Matrix4().fromArray(globeMatrix);
model = new THREE.Matrix4()
.makeTranslation(
modelInEcef[0],
modelInEcef[1],
modelInEcef[2]
)
.multiply(rotEcefY)
.multiply(rotEcefX)
.scale(
new THREE.Vector3(scale, scale, scale)
)
.multiply(rotationX)
.multiply(rotationY)
.multiply(rotationZ)
.multiply(translate);

this.camera.projectionMatrix = projection.multiply(world).multiply(model);
} else {
const modelAsMercatorCoordinate = mapboxgl.MercatorCoordinate.fromLngLat(
modelOrigin,
modelAltitude
);

const scale = modelScale * modelAsMercatorCoordinate.meterInMercatorCoordinateUnits();
model = new THREE.Matrix4()
.makeTranslation(
modelAsMercatorCoordinate.x,
modelAsMercatorCoordinate.y,
modelAsMercatorCoordinate.z
)
.scale(
new THREE.Vector3(scale, scale, scale)
)
.multiply(rotationX)
.multiply(rotationY)
.multiply(rotationZ)
.multiply(translate);

this.camera.projectionMatrix = projection.multiply(model);
}

this.renderer.resetState();
this.renderer.render(this.scene, this.camera);
this.map.triggerRepaint();
const dt = (now - prevTime) / 1000;

modelOrigin[0] += dt * 20.0;
prevTime = now;
}
};

map.on('style.load', () => {
map.addLayer(customLayer, 'waterway-label');
});

</script>
</body>
</html>
3 changes: 1 addition & 2 deletions debug/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
zoom: 12.5,
center: [-122.4194, 37.7749],
style: 'mapbox://styles/mapbox/streets-v11',
hash: true,
projection: 'globe'
hash: true
});

</script>
Expand Down
42 changes: 41 additions & 1 deletion src/geo/mercator_coordinate.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,32 @@

import LngLat, {earthRadius} from '../geo/lng_lat.js';
import type {LngLatLike} from '../geo/lng_lat.js';
import EXTENT from '../data/extent.js';
import assert from 'assert';

export const GLOBE_RADIUS = EXTENT / Math.PI / 2.0;

const DEG_TO_RAD = Math.PI / 180;

export function degToRad(a: number): number {
return a * DEG_TO_RAD;
}

function csLatLngToECEF(cosLat: number, sinLat: number, lng: number, radius: number = GLOBE_RADIUS): Array<number> {
lng = degToRad(lng);

// Convert lat & lng to spherical representation. Use zoom=0 as a reference
const sx = cosLat * Math.sin(lng) * radius;
const sy = -sinLat * radius;
const sz = cosLat * Math.cos(lng) * radius;

return [sx, sy, sz];
}

export function latLngToECEF(lat: number, lng: number, radius?: number): Array<number> {
assert(lat <= 90 && lat >= -90, 'Lattitude must be between -90 and 90');
return csLatLngToECEF(Math.cos(degToRad(lat)), Math.sin(degToRad(lat)), lng, radius);
}

/*
* The average circumference of the world in meters.
Expand Down Expand Up @@ -42,6 +68,8 @@ export function altitudeFromMercatorZ(z: number, y: number): number {

export const MAX_MERCATOR_LATITUDE = 85.051129;

export const GLOBE_METERS_TO_ECEF = mercatorZfromAltitude(1, 0.0) * 2.0 * GLOBE_RADIUS * Math.PI;

/**
* Determine the Mercator scale factor for a given latitude, see
* https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor
Expand Down Expand Up @@ -108,6 +136,19 @@ class MercatorCoordinate {
mercatorZfromAltitude(altitude, lngLat.lat));
}

static meterToEcefUnits(): number {
return GLOBE_METERS_TO_ECEF;
}

static lngLatToEcef(lngLatLike: LngLatLike, altitude: number = 0): Array<number> {
const lngLat = LngLat.convert(lngLatLike);

const altInEcef = altitude * GLOBE_METERS_TO_ECEF;
const radius = GLOBE_RADIUS + altInEcef;

return latLngToECEF(lngLat.lat, lngLat.lng, radius);
}

/**
* Returns the `LngLat` for the coordinate.
*
Expand Down Expand Up @@ -152,7 +193,6 @@ class MercatorCoordinate {
// 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude
return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y));
}

}

export default MercatorCoordinate;
2 changes: 1 addition & 1 deletion src/geo/projection/globe.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export default class Globe extends Mercator {
this.supportsWorldCopies = false;
this.supportsFog = true;
this.zAxisUnit = "pixels";
this.unsupportedLayers = ['debug', 'custom'];
this.unsupportedLayers = ['debug'];
this.range = [3, 5];
}

Expand Down
12 changes: 12 additions & 0 deletions src/geo/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ class Transform {

// globe coordinate transformation matrix
globeMatrix: Float64Array;
customLayerGlobeMatrix: Float64Array;

globeCenterInViewSpace: [number, number, number];
globeRadius: number;
Expand Down Expand Up @@ -1535,6 +1536,17 @@ class Transform {
return this.mercatorMatrix.slice();
}

ecefToMercatorMatrix(): ?Array<number> {
if (this.projection.name === 'globe') {
const m = this.globeMatrix;

const s = mat4.create();
mat4.fromScaling(s, [1.0 / this.worldSize, 1.0 / this.worldSize, this.pixelsPerMeter / this.worldSize]);
return mat4.multiply([], s, m);
}
return null;
}

recenterOnTerrain() {

if (!this._elevation || this.projection.name === 'globe')
Expand Down
2 changes: 1 addition & 1 deletion src/render/draw_custom.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function drawCustom(painter: Painter, sourceCache: SourceCache, layer: CustomSty

context.setDepthMode(depthMode);

implementation.render(context.gl, painter.transform.customLayerMatrix());
implementation.render(context.gl, painter.transform.customLayerMatrix(), painter.transform.ecefToMercatorMatrix());

context.setDirty();
painter.setBaseState();
Expand Down
2 changes: 1 addition & 1 deletion src/style/style_layer/custom_style_layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type Map from '../../ui/map.js';
import assert from 'assert';
import type {ValidationErrors} from '../validate_style.js';

type CustomRenderMethod = (gl: WebGLRenderingContext, matrix: Array<number>) => void;
type CustomRenderMethod = (gl: WebGLRenderingContext, matrix: Array<number>, globeMatrix?: Array<number>, globeMercatorTransition?: number) => void;

/**
* Interface for custom style layers. This is a specification for
Expand Down