-
-
Notifications
You must be signed in to change notification settings - Fork 318
/
render_raster_layer.cpp
524 lines (453 loc) · 21.5 KB
/
render_raster_layer.cpp
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#include <mbgl/renderer/layers/render_raster_layer.hpp>
#include <mbgl/renderer/buckets/raster_bucket.hpp>
#include <mbgl/renderer/render_tile.hpp>
#include <mbgl/renderer/paint_parameters.hpp>
#include <mbgl/renderer/render_static_data.hpp>
#include <mbgl/renderer/sources/render_image_source.hpp>
#include <mbgl/programs/programs.hpp>
#include <mbgl/programs/raster_program.hpp>
#include <mbgl/tile/tile.hpp>
#include <mbgl/gfx/context.hpp>
#include <mbgl/gfx/cull_face_mode.hpp>
#include <mbgl/math/angles.hpp>
#include <mbgl/style/layers/raster_layer_impl.hpp>
#include <mbgl/util/logging.hpp>
#if MLN_DRAWABLE_RENDERER
#include <mbgl/renderer/layers/raster_layer_tweaker.hpp>
#include <mbgl/gfx/image_drawable_data.hpp>
#include <mbgl/gfx/drawable_impl.hpp>
#include <mbgl/gfx/drawable_builder.hpp>
#include <mbgl/renderer/layer_group.hpp>
#include <mbgl/renderer/update_parameters.hpp>
#include <mbgl/shaders/shader_program_base.hpp>
#endif
namespace mbgl {
using namespace style;
using namespace shaders;
namespace {
inline const RasterLayer::Impl& impl_cast(const Immutable<style::Layer::Impl>& impl) {
assert(impl->getTypeInfo() == RasterLayer::Impl::staticTypeInfo());
return static_cast<const RasterLayer::Impl&>(*impl);
}
} // namespace
RenderRasterLayer::RenderRasterLayer(Immutable<style::RasterLayer::Impl> _impl)
: RenderLayer(makeMutable<RasterLayerProperties>(std::move(_impl))),
unevaluated(impl_cast(baseImpl).paint.untransitioned()) {
styleDependencies = unevaluated.getDependencies();
}
RenderRasterLayer::~RenderRasterLayer() = default;
void RenderRasterLayer::transition(const TransitionParameters& parameters) {
unevaluated = impl_cast(baseImpl).paint.transitioned(parameters, std::move(unevaluated));
}
void RenderRasterLayer::evaluate(const PropertyEvaluationParameters& parameters) {
const auto previousProperties = staticImmutableCast<RasterLayerProperties>(evaluatedProperties);
auto properties = makeMutable<RasterLayerProperties>(
staticImmutableCast<RasterLayer::Impl>(baseImpl),
unevaluated.evaluate(parameters, previousProperties->evaluated));
passes = properties->evaluated.get<style::RasterOpacity>() > 0 ? RenderPass::Translucent : RenderPass::None;
properties->renderPasses = mbgl::underlying_type(passes);
evaluatedProperties = std::move(properties);
#if MLN_DRAWABLE_RENDERER
if (layerTweaker) {
layerTweaker->updateProperties(evaluatedProperties);
}
#endif
}
bool RenderRasterLayer::hasTransition() const {
return unevaluated.hasTransition();
}
bool RenderRasterLayer::hasCrossfade() const {
return false;
}
#if MLN_LEGACY_RENDERER
static float saturationFactor(float saturation) {
if (saturation > 0) {
return 1.f - 1.f / (1.001f - saturation);
} else {
return -saturation;
}
}
static float contrastFactor(float contrast) {
if (contrast > 0) {
return 1 / (1 - contrast);
} else {
return 1 + contrast;
}
}
static std::array<float, 3> spinWeights(float spin) {
spin = util::deg2radf(spin);
float s = std::sin(spin);
float c = std::cos(spin);
std::array<float, 3> spin_weights = {
{(2 * c + 1) / 3, (-std::sqrt(3.0f) * s - c + 1) / 3, (std::sqrt(3.0f) * s - c + 1) / 3}};
return spin_weights;
}
#endif
void RenderRasterLayer::prepare(const LayerPrepareParameters& params) {
renderTiles = params.source->getRenderTiles();
imageData = params.source->getImageRenderData();
// It is possible image data is not available until the source loads it.
assert(renderTiles || imageData || !params.source->isEnabled());
#if MLN_DRAWABLE_RENDERER
updateRenderTileIDs();
#endif // MLN_DRAWABLE_RENDERER
}
#if MLN_LEGACY_RENDERER
void RenderRasterLayer::render(PaintParameters& parameters) {
if (parameters.pass != RenderPass::Translucent || (!renderTiles && !imageData)) {
return;
}
if (!parameters.shaders.getLegacyGroup().populate(rasterProgram)) return;
const auto& evaluated = static_cast<const RasterLayerProperties&>(*evaluatedProperties).evaluated;
RasterProgram::Binders paintAttributeData{evaluated, 0};
auto draw = [&](const mat4& matrix,
const auto& vertexBuffer,
const auto& indexBuffer,
const auto& segments,
const auto& textureBindings,
const std::string& drawScopeID) {
const auto allUniformValues = RasterProgram::computeAllUniformValues(
RasterProgram::LayoutUniformValues{
uniforms::matrix::Value(matrix),
uniforms::opacity::Value(evaluated.get<RasterOpacity>()),
uniforms::fade_t::Value(1),
uniforms::brightness_low::Value(evaluated.get<RasterBrightnessMin>()),
uniforms::brightness_high::Value(evaluated.get<RasterBrightnessMax>()),
uniforms::saturation_factor::Value(saturationFactor(evaluated.get<RasterSaturation>())),
uniforms::contrast_factor::Value(contrastFactor(evaluated.get<RasterContrast>())),
uniforms::spin_weights::Value(spinWeights(evaluated.get<RasterHueRotate>())),
uniforms::buffer_scale::Value(1.0f),
uniforms::scale_parent::Value(1.0f),
uniforms::tl_parent::Value(std::array<float, 2>{{0.0f, 0.0f}}),
},
paintAttributeData,
evaluated,
static_cast<float>(parameters.state.getZoom()));
const auto allAttributeBindings = RasterProgram::computeAllAttributeBindings(
vertexBuffer, paintAttributeData, evaluated);
checkRenderability(parameters, RasterProgram::activeBindingCount(allAttributeBindings));
rasterProgram->draw(parameters.context,
*parameters.renderPass,
gfx::Triangles(),
parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly),
gfx::StencilMode::disabled(),
parameters.colorModeForRenderPass(),
gfx::CullFaceMode::disabled(),
indexBuffer,
segments,
allUniformValues,
allAttributeBindings,
textureBindings,
getID() + "/" + drawScopeID);
};
const gfx::TextureFilterType filter = evaluated.get<RasterResampling>() == RasterResamplingType::Nearest
? gfx::TextureFilterType::Nearest
: gfx::TextureFilterType::Linear;
if (imageData && !imageData->bucket->needsUpload()) {
RasterBucket& bucket = *imageData->bucket;
assert(bucket.texture);
size_t i = 0;
for (const auto& matrix_ : imageData->matrices) {
draw(matrix_,
*bucket.vertexBuffer,
*bucket.indexBuffer,
bucket.segments,
RasterProgram::TextureBindings{
textures::image0::Value{bucket.texture->getResource(), filter},
textures::image1::Value{bucket.texture->getResource(), filter},
},
std::to_string(i++));
}
} else if (renderTiles) {
for (const RenderTile& tile : *renderTiles) {
auto* bucket_ = tile.getBucket(*baseImpl);
if (!bucket_) {
continue;
}
auto& bucket = static_cast<RasterBucket&>(*bucket_);
if (!bucket.hasData()) continue;
assert(bucket.texture);
if (bucket.vertexBuffer && bucket.indexBuffer) {
// Draw only the parts of the tile that aren't drawn by another tile in the layer.
draw(parameters.matrixForTile(tile.id, !parameters.state.isChanging()),
*bucket.vertexBuffer,
*bucket.indexBuffer,
bucket.segments,
RasterProgram::TextureBindings{
textures::image0::Value{bucket.texture->getResource(), filter},
textures::image1::Value{bucket.texture->getResource(), filter},
},
"image");
} else {
// Draw the full tile.
if (bucket.segments.empty()) {
// Copy over the segments so that we can create our own DrawScopes.
bucket.segments = RenderStaticData::rasterSegments();
}
draw(parameters.matrixForTile(tile.id, !parameters.state.isChanging()),
*parameters.staticData.rasterVertexBuffer,
*parameters.staticData.quadTriangleIndexBuffer,
bucket.segments,
RasterProgram::TextureBindings{
textures::image0::Value{bucket.texture->getResource(), filter},
textures::image1::Value{bucket.texture->getResource(), filter},
},
"image");
}
}
}
}
#endif // MLN_LEGACY_RENDERER
#if MLN_DRAWABLE_RENDERER
void RenderRasterLayer::markLayerRenderable(bool willRender, UniqueChangeRequestVec& changes) {
RenderLayer::markLayerRenderable(willRender, changes);
if (imageLayerGroup) {
activateLayerGroup(imageLayerGroup, willRender, changes);
}
}
void RenderRasterLayer::layerRemoved(UniqueChangeRequestVec& changes) {
RenderLayer::layerRemoved(changes);
if (imageLayerGroup) {
activateLayerGroup(imageLayerGroup, false, changes);
}
}
void RenderRasterLayer::layerIndexChanged(int32_t newLayerIndex, UniqueChangeRequestVec& changes) {
RenderLayer::layerIndexChanged(newLayerIndex, changes);
changeLayerIndex(imageLayerGroup, newLayerIndex, changes);
}
void RenderRasterLayer::update(gfx::ShaderRegistry& shaders,
gfx::Context& context,
const TransformState& /*state*/,
const std::shared_ptr<UpdateParameters>&,
[[maybe_unused]] const RenderTree& renderTree,
[[maybe_unused]] UniqueChangeRequestVec& changes) {
if ((!renderTiles || renderTiles->empty()) && !imageData) {
if (layerGroup) {
stats.drawablesRemoved += layerGroup->clearDrawables();
}
if (imageLayerGroup) {
stats.drawablesRemoved += imageLayerGroup->clearDrawables();
}
return;
}
constexpr auto renderPass = RenderPass::Translucent;
if (!rasterShader) {
rasterShader = context.getGenericShader(shaders, "RasterShader");
if (!rasterShader) {
return;
}
}
if (!layerTweaker) {
layerTweaker = std::make_shared<RasterLayerTweaker>(getID(), evaluatedProperties);
if (layerGroup) {
layerGroup->addLayerTweaker(layerTweaker);
}
if (imageLayerGroup) {
imageLayerGroup->addLayerTweaker(layerTweaker);
}
}
if (!staticDataVertices) {
staticDataVertices = std::make_shared<RasterVertexVector>(RenderStaticData::rasterVertices());
}
if (!staticDataIndices) {
staticDataIndices = std::make_shared<TriangleIndexVector>(RenderStaticData::quadTriangleIndices());
}
if (!staticDataSegments) {
staticDataSegments = std::make_shared<RasterSegmentVector>(RenderStaticData::rasterSegments());
}
const auto createBuilder = [&] {
auto builder = context.createDrawableBuilder("raster");
builder->setShader(rasterShader);
builder->setRenderPass(renderPass);
builder->setSubLayerIndex(0);
builder->setDepthType(gfx::DepthMaskType::ReadOnly);
builder->setColorMode(gfx::ColorMode::alphaBlended());
builder->setCullFaceMode(gfx::CullFaceMode::disabled());
return builder;
};
const auto setTextures = [&](gfx::UniqueDrawableBuilder& builder, RasterBucket& bucket) {
if (bucket.image) {
if (!bucket.texture2d) {
if (auto tex = context.createTexture2D()) {
tex->setImage(bucket.image);
bucket.texture2d = std::move(tex);
}
}
if (bucket.texture2d) {
const auto& evaluated = static_cast<const RasterLayerProperties&>(*evaluatedProperties).evaluated;
const bool nearest = evaluated.get<RasterResampling>() == RasterResamplingType::Nearest;
const auto filter = nearest ? gfx::TextureFilterType::Nearest : gfx::TextureFilterType::Linear;
bucket.texture2d->setSamplerConfiguration(
{filter, gfx::TextureWrapType::Clamp, gfx::TextureWrapType::Clamp});
builder->setTexture(bucket.texture2d, idRasterImage0Texture);
builder->setTexture(bucket.texture2d, idRasterImage1Texture);
}
}
};
gfx::VertexAttributeArrayPtr staticAttrs;
// Build vertex attributes and apply them to a drawable or a builder.
// Populates a drawable xor a drawable builder for creates and updates, respectively.
// Returns false if the drawable must be re-created.
const auto buildVertexData =
[&](const gfx::UniqueDrawableBuilder& builder, gfx::Drawable* drawable, const RasterBucket& bucket) {
// The bucket may later add, remove, or change masking. In that case, the tile's
// shared data and segments are not updated, and it needs to be re-created.
if (drawable &&
(bucket.sharedVertices->isModifiedAfter(drawable->createTime) || bucket.sharedTriangles->getDirty())) {
return false;
}
// The bucket only fills in geometry for masked tiles,
// otherwise the standard tile extent geometry should be used.
const bool shared = (!bucket.sharedVertices->empty() && !bucket.sharedTriangles->empty() &&
!bucket.segments.empty());
const auto& vertices = shared ? bucket.sharedVertices : staticDataVertices;
const auto& indices = shared ? bucket.sharedTriangles : staticDataIndices;
const auto* segments = shared ? &bucket.segments : staticDataSegments.get();
gfx::VertexAttributeArrayPtr bucketAttrs;
auto& vertexAttrs = shared ? bucketAttrs : staticAttrs;
if (!vertexAttrs) {
vertexAttrs = context.createVertexAttributeArray();
if (auto& attr = vertexAttrs->set(idRasterPosVertexAttribute)) {
attr->setSharedRawData(vertices,
offsetof(RasterLayoutVertex, a1),
/*vertexOffset=*/0,
sizeof(RasterLayoutVertex),
gfx::AttributeDataType::Short2);
}
if (auto& attr = vertexAttrs->set(idRasterTexturePosVertexAttribute)) {
attr->setSharedRawData(vertices,
offsetof(RasterLayoutVertex, a2),
/*vertexOffset=*/0,
sizeof(RasterLayoutVertex),
gfx::AttributeDataType::Short2);
}
}
assert(!!drawable ^ !!builder);
if (drawable) {
drawable->updateVertexAttributes(
vertexAttrs, vertices->elements(), gfx::Triangles(), indices, segments->data(), segments->size());
} else if (builder) {
builder->setVertexAttributes(vertexAttrs);
builder->setRawVertices({}, vertices->elements(), gfx::AttributeDataType::Short2);
builder->setSegments(gfx::Triangles(), indices, segments->data(), segments->size());
}
return true;
};
gfx::UniqueDrawableBuilder builder;
if (imageData) {
// TODO: Can we avoid rebuilding drawables each time in this case as well?
if (imageLayerGroup) {
stats.drawablesRemoved += imageLayerGroup->clearDrawables();
}
RasterBucket& bucket = *imageData->bucket;
if (!bucket.vertices.empty()) {
if (!imageLayerGroup) {
// Set up a layer group
imageLayerGroup = context.createLayerGroup(layerIndex, /*initialCapacity=*/64, getID());
imageLayerGroup->addLayerTweaker(layerTweaker);
activateLayerGroup(imageLayerGroup, isRenderable, changes);
}
// Create a drawable for each transformation
// TODO: Share textures
builder = createBuilder();
for (const auto& matrix_ : imageData->matrices) {
buildVertexData(builder, /*drawable=*/nullptr, bucket);
setTextures(builder, bucket);
// finish
builder->flush(context);
for (auto& drawable : builder->clearDrawables()) {
drawable->setData(std::make_unique<gfx::ImageDrawableData>(matrix_));
drawable->setLayerTweaker(layerTweaker);
imageLayerGroup->addDrawable(std::move(drawable));
++stats.drawablesAdded;
}
}
}
} else if (renderTiles) {
// Remove existing drawables that are no longer in the cover set
if (layerGroup) {
stats.drawablesRemoved += removeLayerGroupDrawablesIf(*layerGroup, [&](gfx::Drawable& drawable) {
return drawable.getTileID() && !hasRenderTile(*drawable.getTileID());
});
} else {
// Set up a tile layer group
if (auto layerGroup_ = context.createTileLayerGroup(layerIndex, /*initialCapacity=*/64, getID())) {
layerGroup_->addLayerTweaker(layerTweaker);
setLayerGroup(std::move(layerGroup_), changes);
}
}
auto* tileLayerGroup = static_cast<TileLayerGroup*>(layerGroup.get());
for (const RenderTile& tile : *renderTiles) {
const auto& tileID = tile.getOverscaledTileID();
auto* bucket_ = tile.getBucket(*baseImpl);
if (!bucket_ || !bucket_->hasData()) {
removeTile(renderPass, tileID);
continue;
}
bool cleared = false;
auto& bucket = static_cast<RasterBucket&>(*bucket_);
if (setRenderTileBucketID(tileID, bucket.getID())) {
// Bucket ID changed, we need to rebuild the drawables
removeTile(renderPass, tileID);
cleared = true;
}
// If the bucket data has changed, rebuild the drawables.
else if (!bucket.vertices.empty() && !bucket.indices.empty() && !bucket.segments.empty()) {
// Find the earliest time on existing drawables
std::optional<std::chrono::duration<double>> tileUpdateTime;
tileLayerGroup->visitDrawables(renderPass, tileID, [&](const auto& drawable) {
if (!tileUpdateTime || drawable.createTime < *tileUpdateTime) {
tileUpdateTime = drawable.createTime;
}
});
if (tileUpdateTime && (bucket.vertices.isModifiedAfter(*tileUpdateTime) || bucket.indices.getDirty())) {
removeTile(renderPass, tileID);
cleared = true;
}
}
if (!cleared) {
// Update existing drawables
bool geometryChanged = false;
auto updateExisting = [&](gfx::Drawable& drawable) {
// Only current drawables are updated, ones produced for
// a previous style retain the attribute values for that style.
if (drawable.getLayerTweaker() != layerTweaker) {
return false;
}
gfx::UniqueDrawableBuilder none;
if (!geometryChanged && !buildVertexData(none, &drawable, bucket)) {
// Masking changed, need to rebuild this tile
geometryChanged = true;
}
return true;
};
// If we update existing drawables, don't build new ones.
// But if the geometry has changed, we need to drop and re-build them anyway.
if (updateTile(renderPass, tileID, std::move(updateExisting)) && !geometryChanged) {
continue;
} else if (geometryChanged) {
removeTile(renderPass, tileID);
}
}
// Otherwise, create new ones.
if (!builder) {
builder = createBuilder();
}
if (bucket.image && !builder->getTexture(idRasterImage0Texture) &&
!builder->getTexture(idRasterImage1Texture)) {
setTextures(builder, bucket);
};
buildVertexData(builder, /*drawable=*/nullptr, bucket);
// finish
builder->flush(context);
for (auto& drawable : builder->clearDrawables()) {
drawable->setTileID(tileID);
drawable->setLayerTweaker(layerTweaker);
tileLayerGroup->addDrawable(renderPass, tileID, std::move(drawable));
++stats.drawablesAdded;
}
}
}
}
#endif // MLN_DRAWABLE_RENDERER
} // namespace mbgl