Skip to content

custom_layer

Stable

A custom WebGL layer drawn with your own GLSL shaders, whose uniforms follow the LiveView's assigns.

The example's template and LiveView, read from the files that run in the preview.

lib/maplibrex_demo_web/examples/custom_layer_example.html.heex
<div id="custom-layer-example">
  <%!-- The shaders are strings, and every other attribute is an assign the
        layer follows after mount. The component can come before its map:
        the layer is added once the map can take it. --%>
  <.custom_layer
    id="example-custom-layer"
    map_id="example-custom-layer-map"
    vertex_shader={vertex_shader()}
    fragment_shader={fragment_shader()}
    uniforms={@uniforms}
    before_id={@before_id}
    min_zoom={@min_zoom}
    max_zoom={@max_zoom}
  />

  <.example_frame error={@map_error} error_id="example-custom-layer-map-error">
    <%!-- Dark in both themes: the light points would vanish on a light
          basemap. --%>
    <.map
      id="example-custom-layer-map"
      center={[0, 20]}
      zoom={1.6}
      style={style_url(@basemap)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <div class="space-y-4 border-t border-line px-4 py-4">
    <div class="grid gap-x-8 gap-y-4 lg:grid-cols-[auto_1fr]">
      <.example_group id="example-custom-layer-colors" label="u_color" code>
        <.example_button
          :for={{name, color} <- colors()}
          id={"example-custom-layer-color-#{name}"}
          code
          pressed={@color == color}
          phx-click="color"
          phx-value-color={name}
        >
          <.example_swatch color={css_color(color)} />{inspect(color)}
        </.example_button>
      </.example_group>

      <.example_group id="example-custom-layer-basemaps" label="basemap" code>
        <.example_button
          :for={basemap <- basemaps()}
          id={"example-custom-layer-basemap-#{basemap}"}
          code
          pressed={@basemap == basemap}
          phx-click="basemap"
          phx-value-basemap={basemap}
        >
          {basemap}
        </.example_button>
      </.example_group>

      <.example_group id="example-custom-layer-before-id" label="before_id" code>
        <.example_button
          :for={before_id <- before_ids()}
          id={"example-custom-layer-before-id-#{before_id || "nil"}"}
          code
          pressed={@before_id == before_id}
          phx-click="before_id"
          phx-value-before_id={before_id || ""}
        >
          {inspect(before_id)}
        </.example_button>
      </.example_group>

      <div class="flex flex-wrap gap-x-8 gap-y-4">
        <.example_group id="example-custom-layer-min-zoom" label="min_zoom" code>
          <.example_button
            :for={zoom <- min_zooms()}
            id={"example-custom-layer-min-zoom-#{zoom || "nil"}"}
            code
            pressed={@min_zoom == zoom}
            phx-click="min_zoom"
            phx-value-zoom={zoom || ""}
          >
            {inspect(zoom)}
          </.example_button>
        </.example_group>

        <.example_group id="example-custom-layer-max-zoom" label="max_zoom" code>
          <.example_button
            :for={zoom <- max_zooms()}
            id={"example-custom-layer-max-zoom-#{zoom || "nil"}"}
            code
            pressed={@max_zoom == zoom}
            phx-click="max_zoom"
            phx-value-zoom={zoom || ""}
          >
            {inspect(zoom)}
          </.example_button>
        </.example_group>
      </div>
    </div>

    <.form
      for={@options}
      id="example-custom-layer-options"
      phx-change="options"
      class="grid gap-4 sm:grid-cols-3"
    >
      <.example_range field={@options[:speed]} label="speed" min="0" max="5" step="0.1" />
      <.example_range
        field={@options[:point_size]}
        label="point_size"
        min="1"
        max="10"
        step="0.5"
      />
      <%!-- Pushed to the layer with update_uniforms_<id>: see the module. --%>
      <.example_range field={@options[:opacity]} label="opacity" min="0" max="1" step="0.05" />
    </.form>
  </div>

  <.example_readout values={[
    color: inspect(@color),
    speed: @speed,
    point_size: @point_size,
    opacity: @opacity,
    basemap: @basemap,
    before_id: inspect(@before_id),
    min_zoom: inspect(@min_zoom),
    max_zoom: inspect(@max_zoom)
  ]} />
</div>
lib/maplibrex_demo_web/examples/custom_layer_example.ex
defmodule MaplibrexDemoWeb.Examples.CustomLayerExample do
  @moduledoc """
  The example of `<.custom_layer>`: 1,000 points drawn by the GLSL shaders
  below, which drift east, moved by uniforms set from the server.

  MaplibreX places the points at random over the world and, because the
  uniforms include `u_time`, advances that uniform in the browser on every
  frame. Everything else the shaders read (colour, speed, size, opacity) is
  an assign: a button or a slider changes the assigns, the layer's
  `uniforms` attribute follows them, and the layer draws the new uniforms
  from its next frame.

  The opacity slider shows the other way in: it pushes `u_opacity` alone to
  `"update_uniforms_<id>"`, without re-rendering the layer, and MaplibreX
  merges it over the uniforms the layer has. The assign keeps the new
  opacity too, so the next change of the `uniforms` attribute carries it.

  The layer's place follows its assigns as well: `before_id` draws it under
  the basemap's water, which hides the points at sea, and `min_zoom` and
  `max_zoom` limit the zooms it is drawn at. A new basemap is a new `style`
  for the map; the layer goes back to its place on it.

  Points that follow a real vector field, such as wind or ocean currents,
  are what `<.flow_layer>` draws: see the wind and ocean currents scenario.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  # Demo plumbing, not needed in an application: applies the page's locale
  # and copies each map event to the page's Events tab.
  on_mount MaplibrexDemoWeb.Examples.Plumbing

  @vertex_shader """
  attribute vec2 a_position;
  uniform mat4 u_matrix;
  uniform float u_point_size;
  uniform float u_time;
  uniform float u_speed;

  void main() {
    // Positions are MapLibre's Mercator coordinates, from 0 to 1. Each
    // point drifts east, on a wave of its own phase.
    vec2 pos = a_position + vec2(u_time * u_speed * 0.003, 0.0);
    pos.y += sin(pos.x * 40.0 + u_time * 3.0) * 0.0015;

    // A point that leaves the world comes back on the other side.
    pos = fract(pos);

    gl_Position = u_matrix * vec4(pos, 0.0, 1.0);
    gl_PointSize = u_point_size;
  }
  """

  @fragment_shader """
  precision mediump float;

  uniform vec3 u_color;
  uniform float u_opacity;

  void main() {
    // A round point with a soft edge.
    float dist = length(gl_PointCoord - vec2(0.5));
    float alpha = 1.0 - smoothstep(0.3, 0.5, dist);

    gl_FragColor = vec4(u_color, alpha * u_opacity);
  }
  """

  @colors [
    {"blue", [0.2, 0.6, 0.9]},
    {"white", [0.9, 0.9, 0.9]},
    {"orange", [1.0, 0.3, 0.1]},
    {"green", [0.3, 0.85, 0.45]}
  ]

  # Two dark basemaps: the light points would vanish on a light one.
  @basemaps ~w(dark fiord)

  # Where the layer is drawn: on top of the basemap (no before_id), or under
  # its water layer, which then covers the points at sea.
  @before_ids [nil, "water"]

  # The map opens at zoom 1.6: with min_zoom 2 the points appear once it is
  # zoomed in to 2, with max_zoom 3 they go once it is zoomed in to 3.
  @min_zooms [nil, 2]
  @max_zooms [nil, 3]

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(color: [0.2, 0.6, 0.9], speed: 1.0, point_size: 3.0, opacity: 0.8)
      |> assign(basemap: "dark", before_id: nil, min_zoom: nil, max_zoom: nil, map_error: nil)
      |> assign_uniforms()

    {:ok, socket}
  end

  # Driven from the server: every control changes assigns, and the layer's
  # attributes follow them.

  @impl true
  def handle_event("color", %{"color" => name}, socket) do
    case List.keyfind(@colors, name, 0) do
      {^name, color} -> {:noreply, socket |> assign(:color, color) |> assign_uniforms()}
      nil -> {:noreply, socket}
    end
  end

  # The opacity slider alone: pushed to the layer, whose attributes stay as
  # they are. LiveView names the input that changed in "_target".
  def handle_event("options", %{"_target" => ["opacity"], "opacity" => opacity}, socket) do
    opacity = float(opacity, socket.assigns.opacity)

    {:noreply,
     socket
     |> assign(:opacity, opacity)
     |> assign_options()
     |> push_event("update_uniforms_example-custom-layer", %{uniforms: %{"u_opacity" => opacity}})}
  end

  def handle_event("options", params, socket) do
    %{speed: speed, point_size: point_size, opacity: opacity} = socket.assigns

    {:noreply,
     socket
     |> assign(
       speed: float(params["speed"], speed),
       point_size: float(params["point_size"], point_size),
       opacity: float(params["opacity"], opacity)
     )
     |> assign_uniforms()}
  end

  def handle_event("basemap", %{"basemap" => basemap}, socket) do
    choose(socket, :basemap, basemap, @basemaps)
  end

  def handle_event("before_id", %{"before_id" => value}, socket) do
    choose(socket, :before_id, if(value == "", do: nil, else: value), @before_ids)
  end

  def handle_event("min_zoom", %{"zoom" => value}, socket) do
    choose(socket, :min_zoom, zoom(value), @min_zooms)
  end

  def handle_event("max_zoom", %{"zoom" => value}, socket) do
    choose(socket, :max_zoom, zoom(value), @max_zooms)
  end

  def handle_event("map:error", %{"error" => message}, socket) do
    {:noreply, assign(socket, :map_error, message)}
  end

  # A choice of a set, from a button; any other value is ignored.
  defp choose(socket, key, value, choices) do
    if value in choices, do: {:noreply, assign(socket, key, value)}, else: {:noreply, socket}
  end

  # The layer's uniforms, and the form, from the current assigns.
  defp assign_uniforms(socket) do
    socket
    |> assign(:uniforms, uniforms(socket.assigns))
    |> assign_options()
  end

  defp uniforms(assigns) do
    %{
      # Only needs to be present: the browser advances it on every frame.
      "u_time" => 0.0,
      "u_color" => assigns.color,
      "u_speed" => assigns.speed,
      "u_point_size" => assigns.point_size,
      "u_opacity" => assigns.opacity
    }
  end

  defp vertex_shader, do: @vertex_shader
  defp fragment_shader, do: @fragment_shader
  defp colors, do: @colors
  defp basemaps, do: @basemaps
  defp before_ids, do: @before_ids
  defp min_zooms, do: @min_zooms
  defp max_zooms, do: @max_zooms

  defp style_url(basemap), do: "https://tiles.openfreemap.org/styles/#{basemap}"

  defp css_color([r, g, b]), do: "rgb(#{round(r * 255)}, #{round(g * 255)}, #{round(b * 255)})"

  defp assign_options(socket) do
    form =
      socket.assigns
      |> Map.take([:speed, :point_size, :opacity])
      |> Map.new(fn {key, value} -> {Atom.to_string(key), value} end)
      |> to_form()

    assign(socket, :options, form)
  end

  # Slider values arrive as strings: "2.5"; anything else keeps the value.
  defp float(value, current) do
    case Float.parse(value || "") do
      {float, _rest} -> float
      :error -> current
    end
  end

  # A zoom button's value: "" for none, or a whole zoom level.
  defp zoom(""), do: nil

  defp zoom(value) do
    case Integer.parse(value) do
      {zoom, ""} -> zoom
      _ -> :invalid
    end
  end
end