Skip to content

自定义渲染 ​

本篇介绍通过 SFMCustomDrawOverlay 的 Metal 自绘能力实现的高级效果,包含 OD 线运动光点和 3D 热力图两个示例。CustomDrawOverlay 的基础用法见图层叠加 - CustomDrawOverlay。

OD 线运动光点 ​

功能说明 ​

OD(Origin-Destination)线从起点向多条终点绘制直线,并附带沿线条运动的彗星拖尾光点动画。基于 SFMCustomDrawOverlay 的 Metal 自绘实现,包含线段绘制(triangle strip 屏幕空间定宽线)和光点绘制(point primitive 圆形辉光)两个 pass。

关键代码 ​

objc
// ── 创建 OD 线覆盖物 ──
SFMCustomDrawOverlay *overlay = [SFMCustomDrawOverlay
    overlayWithDrawLevel:SFMCustomDrawOverlayLevelAboveLabels];

// 1) prepare: 编译 shader + depthStencilState
overlay.prepareBlock = ^(SFMDrawResource *resource) {
    id<MTLDevice> device = resource.device;
    id<MTLLibrary> library = [device newLibraryWithSource:shaderSource options:nil error:&error];
    // 保存 device/library/resource,pipeline 首帧懒加载
    MTLDepthStencilDescriptor *dsDesc = [[MTLDepthStencilDescriptor alloc] init];
    dsDesc.depthCompareFunction = MTLCompareFunctionAlways;
    dsDesc.depthWriteEnabled = NO;
    depthStencilState = [device newDepthStencilStateWithDescriptor:dsDesc];
};

// 2) draw: 每帧投影经纬度 → 画线 + 画光点 → 自驱下一帧
overlay.drawBlock = ^(SFMDrawContext context, id<MTLRenderCommandEncoder> encoder) {
    double scale = pow(2.0, context.zoomLevel);
    SFMMatrix4 m = context.projectionMatrix;

    // 画线(每条 OD 线 4 顶点 triangle strip)
    [encoder setRenderPipelineState:linePipelineState];
    [encoder setVertexBuffer:lineBuffer offset:0 atIndex:0];
    [encoder setVertexBytes:&lineUniforms length:sizeof(LineUniforms) atIndex:1];
    [encoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:lineVertCount];

    // 画光点(每条线 N 个拖尾点,alpha 递减)
    [encoder setRenderPipelineState:pointPipelineState];
    [encoder setVertexBuffer:pointBuffer offset:0 atIndex:0];
    [encoder setVertexBytes:&pointUniforms length:sizeof(PointUniforms) atIndex:1];
    [encoder drawPrimitives:MTLPrimitiveTypePoint vertexStart:0 vertexCount:pointVertCount];

    // 自驱下一帧(地图静止时光点也持续运动)
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mapView triggerRepaint];
    });
};

// 3) teardown: 释放资源
overlay.teardownBlock = ^{
    linePipelineState = nil;
    pointPipelineState = nil;
    // ...
};

[self.mapView addCustomDrawOverlay:overlay];

// ── 移除 ──
[self.mapView removeCustomDrawOverlay:overlay];

要点 ​

  • 经纬度投影使用 Web Mercator 公式:经度 → (180 + lng) / 360 * worldSize * scale,纬度 → 球面投影 Y * scale,其中 worldSize = 512、scale = 2^zoom。
  • 线段使用 triangle strip 在屏幕空间定宽渲染:顶点携带起止点坐标 + 参数 t + side(±1 法向偏移),vertex shader 中算出屏幕法向偏移实现定宽。
  • 光点使用 point primitive 绘制:每个拖尾点的 alpha 从 1.0 递减到 0,fragment shader 中用 pointCoord 做圆形辉光(smoothstep(0.5, 0.0, distance))。
  • 每条线的运动速度和初始偏移按公式计算:speed = 0.12 + (i % 5) * 0.03、offset = (i * 0.137) % 1.0,使各线光点错峰运动。
  • 持续动画需在 drawBlock 末尾 dispatch_async(main, ^{ [mapView triggerRepaint]; }) 自驱下一帧,否则地图静止时不会重绘。
  • pipeline state 必须在 drawBlock 首帧用当前帧的 live renderPassDescriptor 创建,depthAttachmentPixelFormat / stencilAttachmentPixelFormat 需与 MapLibre framebuffer 匹配。
  • 顶点数据超过 4096 字节时 setVertexBytes 不可用,需改用 MTLBuffer。

3D 热力图 ​

功能说明 ​

3D 热力图将密度数据渲染为带高度拉伸的曲面,通过双 pass Metal 自绘实现:密度 pass 离屏渲染每个数据点的高斯衰减权重到密度纹理,着色 pass 将密度纹理采样到网格曲面上并按高度拉伸 Z 轴,最终按色带着色。支持高度系数和半径系数的动态调整。

关键代码 ​

objc
// ── 创建 3D 热力图覆盖物 ──
SFMCustomDrawOverlay *overlay = [SFMCustomDrawOverlay
    overlayWithDrawLevel:SFMCustomDrawOverlayLevelAboveLabels];

// 设置数据点(经度, 纬度, 权重)
float *points = malloc(kPointCount * 3 * sizeof(float));
// 填充 points[i*3]=lng, points[i*3+1]=lat, points[i*3+2]=weight(0~1)

// 设置初始视角(倾斜以便观察高度拉伸)
[mapView setPitch:55 animated:NO];
mapView.pitchEnabled = YES;

// 1) prepare: 编译 shader + 建 pipeline + 色带纹理 + 网格 buffer
overlay.prepareBlock = ^(SFMDrawResource *resource) {
    // 编译密度 pass shader(sfm_density_vertex/fragment)+ 着色 pass shader(sfm_surface_vertex/fragment)
    // 创建密度 pipeline(RGBA8 离屏 + 加色混合 + 无 depth)
    // 创建着色 pipeline(主 framebuffer 格式 + depth + alpha 混合)
    // 创建色带纹理(256×1,7 个色标)
    // 创建网格索引 buffer(384×384 网格,uint32 索引)
};

// 2) draw: 密度 pass(离屏)+ 着色 pass(主 encoder)
overlay.drawBlock = ^(SFMDrawContext context, id<MTLRenderCommandEncoder> encoder) {
    double scale = pow(2.0, context.zoomLevel);

    // 投影数据点 → world 坐标,计算 bbox
    // ...

    // 1. 密度 pass:独立 commandBuffer 离屏编码
    id<MTLCommandBuffer> densityCmd = [commandQueue commandBuffer];
    MTLRenderPassDescriptor *densityPass = [MTLRenderPassDescriptor renderPassDescriptor];
    densityPass.colorAttachments[0].texture = densityTexture;
    densityPass.colorAttachments[0].loadAction = MTLLoadActionClear;
    id<MTLRenderCommandEncoder> densityEnc = [densityCmd renderCommandEncoderWithDescriptor:densityPass];
    [densityEnc setRenderPipelineState:densityPipeline];
    [densityEnc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:vertCount];
    [densityEnc endEncoding];
    [densityCmd commit];
    [densityCmd waitUntilCompleted];  // 确保密度纹理就绪后再采样

    // 2. 着色 pass:主 encoder,网格曲面拉伸
    SurfaceUniforms sUniforms;
    sUniforms.mvp = /* context.projectionMatrix 转换为 matrix_float4x4 */;
    sUniforms.height = heightScale * scale * MIN(bw, bh);  // 高度系数 × scale × bbox 短边
    [encoder setRenderPipelineState:surfacePipeline];
    [encoder setDepthStencilState:depthStencilLess];  // 深度测试
    [encoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
                         indexCount:gridIndexCount
                          indexType:MTLIndexTypeUInt32
                        indexBuffer:gridIndexBuffer
                  indexBufferOffset:0];
};

[self.mapView addCustomDrawOverlay:overlay];

// ── 动态调整参数 ──
heightScale *= 1.3;   // 高度增大
heightScale /= 1.3;   // 高度减小
radiusFraction *= 1.2;  // 半径增大
radiusFraction /= 1.2;  // 半径减小
// 参数在下一次 drawBlock 调用时自动生效

要点 ​

  • 密度 pass 使用独立 commandBuffer 离屏编码,避免与主 encoder 编码顺序冲突,必须 waitUntilCompleted 确保密度纹理就绪后再在着色 pass 中采样。
  • 密度 pass 采用加色混合(sourceRGBBlendFactor = SourceAlpha, destinationRGBBlendFactor = One),使重叠区域密度累加。
  • 着色 pass 使用深度测试(depthCompareFunction = Less, depthWriteEnabled = YES),使曲面有正确的遮挡关系。
  • 网格分辨率 384(顶点数 385×385),索引用 uint32 避免超过 65535 顶点上限。
  • heightScale 控制高度拉伸幅度,radiusFraction 控制高斯衰减半径(占 bbox 短边的比例),均可在运行时动态调整。
  • 倾斜地图(setPitch:55)才能观察到 3D 高度拉伸效果,俯视时只能看到色带着色。
  • 色带纹理 256×1 像素,7 个色标从透明(alpha=0)到黄白色,通过密度值采样。
  • teardownBlock 必须释放所有 Metal 资源(pipeline、buffer、texture、sampler、depthStencilState 等)。

V3.2-202604301400