-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
custom_style_layer.js
246 lines (221 loc) · 9.24 KB
/
custom_style_layer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// @flow
import StyleLayer from '../style_layer.js';
import MercatorCoordinate from '../../geo/mercator_coordinate.js';
import type {Map} from '../../ui/map.js';
import assert from 'assert';
import type {ValidationErrors} from '../validate_style.js';
import type {ProjectionSpecification} from '../../style-spec/types.js';
import type SourceCache from '../../source/source_cache.js';
type CustomRenderMethod = (gl: WebGL2RenderingContext, matrix: Array<number>, projection: ?ProjectionSpecification, projectionToMercatorMatrix: ?Array<number>, projectionToMercatorTransition: ?number, centerInMercator: ?Array<number>, pixelsPerMeterRatio: ?number) => void;
/**
* Interface for custom style layers. This is a specification for
* implementers to model: it is not an exported method or class.
*
* Custom layers allow a user to render directly into the map's GL context using the map's camera.
* These layers can be added between any regular layers using {@link Map#addLayer}.
*
* Custom layers must have a unique `id` and must have the `type` of `"custom"`.
* They must implement `render` and may implement `prerender`, `onAdd` and `onRemove`.
* They can trigger rendering using {@link Map#triggerRepaint}
* and they should appropriately handle {@link Map.event:webglcontextlost} and
* {@link Map.event:webglcontextrestored}.
*
* The `renderingMode` property controls whether the layer is treated as a `"2d"` or `"3d"` map layer. Use:
* - `"renderingMode": "3d"` to use the depth buffer and share it with other layers
* - `"renderingMode": "2d"` to add a layer with no depth. If you need to use the depth buffer for a `"2d"` layer you must use an offscreen
* framebuffer and {@link CustomLayerInterface#prerender}.
*
* @interface CustomLayerInterface
* @property {string} id A unique layer id.
* @property {string} type The layer's type. Must be `"custom"`.
* @property {string} renderingMode Either `"2d"` or `"3d"`. Defaults to `"2d"`.
* @example
* // Custom layer implemented as ES6 class
* class NullIslandLayer {
* constructor() {
* this.id = 'null-island';
* this.type = 'custom';
* this.renderingMode = '2d';
* }
*
* onAdd(map, gl) {
* const vertexSource = `
* uniform mat4 u_matrix;
* void main() {
* gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);
* gl_PointSize = 20.0;
* }`;
*
* const fragmentSource = `
* void main() {
* gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
* }`;
*
* const vertexShader = gl.createShader(gl.VERTEX_SHADER);
* gl.shaderSource(vertexShader, vertexSource);
* gl.compileShader(vertexShader);
* const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
* gl.shaderSource(fragmentShader, fragmentSource);
* gl.compileShader(fragmentShader);
*
* this.program = gl.createProgram();
* gl.attachShader(this.program, vertexShader);
* gl.attachShader(this.program, fragmentShader);
* gl.linkProgram(this.program);
* }
*
* render(gl, matrix) {
* gl.useProgram(this.program);
* gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, matrix);
* gl.drawArrays(gl.POINTS, 0, 1);
* }
* }
*
* map.on('load', () => {
* map.addLayer(new NullIslandLayer());
* });
* @see [Example: Add a custom style layer](https://docs.mapbox.com/mapbox-gl-js/example/custom-style-layer/)
* @see [Example: Add a 3D model](https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/)
*/
/**
* Optional method called when the layer has been added to the Map with {@link Map#addLayer}. This
* gives the layer a chance to initialize gl resources and register event listeners.
*
* @function
* @memberof CustomLayerInterface
* @instance
* @name onAdd
* @param {Map} map The Map this custom layer was just added to.
* @param {WebGL2RenderingContext} gl The gl context for the map.
*/
/**
* Optional method called when the layer has been removed from the Map with {@link Map#removeLayer}. This
* gives the layer a chance to clean up gl resources and event listeners.
*
* @function
* @memberof CustomLayerInterface
* @instance
* @name onRemove
* @param {Map} map The Map this custom layer was just added to.
* @param {WebGL2RenderingContext} gl The gl context for the map.
*/
/**
* Optional method called during a render frame to allow a layer to prepare resources or render into a texture.
*
* The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering.
*
* @function
* @memberof CustomLayerInterface
* @instance
* @name prerender
* @param {WebGL2RenderingContext} gl The map's gl context.
* @param {Array<number>} matrix The map's camera matrix. It projects spherical mercator
* coordinates to gl coordinates. The mercator coordinate `[0, 0]` represents the
* top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When
* the `renderingMode` is `"3d"`, the z coordinate is conformal. A box with identical x, y, and z
* lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat
* can be used to project a `LngLat` to a mercator coordinate.
*/
/**
* Called during a render frame allowing the layer to draw into the GL context.
*
* The layer can assume blending and depth state is set to allow the layer to properly
* blend and clip other layers. The layer cannot make any other assumptions about the
* current GL state.
*
* If the layer needs to render to a texture, it should implement the `prerender` method
* to do this and only use the `render` method for drawing directly into the main framebuffer.
*
* The blend function is set to `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. This expects
* colors to be provided in premultiplied alpha form where the `r`, `g` and `b` values are already
* multiplied by the `a` value. If you are unable to provide colors in premultiplied form you
* may want to change the blend function to
* `gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`.
*
* @function
* @memberof CustomLayerInterface
* @instance
* @name render
* @param {WebGL2RenderingContext} gl The map's gl context.
* @param {Array<number>} matrix The map's camera matrix. It projects spherical mercator
* coordinates to gl coordinates. The spherical mercator coordinate `[0, 0]` represents the
* top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When
* the `renderingMode` is `"3d"`, the z coordinate is conformal. A box with identical x, y, and z
* lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat
* can be used to project a `LngLat` to a mercator coordinate.
*/
export type CustomLayerInterface = {
id: string,
type: 'custom',
slot?: string | void,
renderingMode?: '2d' | '3d',
render: CustomRenderMethod,
prerender?: CustomRenderMethod | void,
renderToTile?: (gl: WebGL2RenderingContext, tileId: MercatorCoordinate) => void,
shouldRerenderTiles?: () => boolean,
onAdd?: (map: Map, gl: WebGL2RenderingContext) => void,
onRemove?: (map: Map, gl: WebGL2RenderingContext) => void
}
export function validateCustomStyleLayer(layerObject: CustomLayerInterface): ValidationErrors {
const errors = [];
const id = layerObject.id;
if (id === undefined) {
errors.push({
message: `layers.${id}: missing required property "id"`
});
}
if (layerObject.render === undefined) {
errors.push({
message: `layers.${id}: missing required method "render"`
});
}
if (layerObject.renderingMode &&
layerObject.renderingMode !== '2d' &&
layerObject.renderingMode !== '3d') {
errors.push({
message: `layers.${id}: property "renderingMode" must be either "2d" or "3d"`
});
}
return errors;
}
class CustomStyleLayer extends StyleLayer {
implementation: CustomLayerInterface;
constructor(implementation: CustomLayerInterface, scope: string) {
super(implementation, {}, scope);
this.implementation = implementation;
if (implementation.slot) this.slot = implementation.slot;
}
is3D(): boolean {
return this.implementation.renderingMode === '3d';
}
hasOffscreenPass(): boolean {
return this.implementation.prerender !== undefined;
}
isDraped(_: ?SourceCache): boolean {
return this.implementation.renderToTile !== undefined;
}
shouldRedrape(): boolean {
return !!this.implementation.shouldRerenderTiles && this.implementation.shouldRerenderTiles();
}
recalculate() {}
updateTransitions() {}
hasTransition(): boolean {
return false;
}
serialize(): any {
assert(false, "Custom layers cannot be serialized");
}
// $FlowFixMe[method-unbinding]
onAdd(map: Map) {
if (this.implementation.onAdd) {
this.implementation.onAdd(map, map.painter.context.gl);
}
}
// $FlowFixMe[method-unbinding]
onRemove(map: Map) {
if (this.implementation.onRemove) {
this.implementation.onRemove(map, map.painter.context.gl);
}
}
}
export default CustomStyleLayer;