Mod API Reference:Client MapLayers: Difference between revisions

From War.app Wiki
Jump to navigation Jump to search
Created page with " Put the function in a file named <code>Client_MapLayers.lua</code>: <pre> function Client_MapLayers(game, layers) local layer = layers.Create('Territory IDs', true); for terrID, _ in pairs(game.Map.Territories) do layer.AddLabel(terrID, tostring(terrID)); end end </pre> Client_Visual draws a visual for one order. This hook instead draws '''map layers''': labels and shapes that stay on the map for as long as the g..."
 
No edit summary
 
Line 1: Line 1:
Put the function in a file named <code>Client_MapLayers.lua</code>:
Put the function in a file named <code>Client_MapLayers.lua</code>:


<pre>
<pre>
function Client_MapLayers(game, layers)
function Client_MapLayers(game, layers)
     local layer = layers.Create('Territory IDs', true);
     layers.Create('Territory IDs', function(game, layer)
    for terrID, _ in pairs(game.Map.Territories) do
        for terrID, _ in pairs(game.Map.Territories) do
        layer.AddLabel(terrID, tostring(terrID));
            layer.AddLabel(terrID, tostring(terrID));
     end
        end
     end);
end
end
</pre>
</pre>
Line 14: Line 14:


Players turn each layer on or off with checkboxes in a "Map layers" dialog, which opens from a button in the game's menu. That button only appears in games where a mod created at least one layer. The device remembers each player's choice for each mod and layer name.
Players turn each layer on or off with checkboxes in a "Map layers" dialog, which opens from a button in the game's menu. That button only appears in games where a mod created at least one layer. The device remembers each player's choice for each mod and layer name.
The client calls the hook when the game loads and every time it refreshes, and redraws the layers each time. Turning a layer on or off doesn't run the hook again.


Layers are drawn above territories and bonus links, and below army numbers.
Layers are drawn above territories and bonus links, and below army numbers.


Like Client_Visual, layers are shown in the app and on the website in 3D mode, but not on the website in 2D mode. In 2D mode, the "Map layers" dialog says that layers aren't supported.
Like Client_Visual, layers are shown in the app and on the website in 3D mode, but not on the website in 2D mode. In 2D mode, the "Map layers" dialog says that layers aren't supported.
== How it works ==
Client_MapLayers runs once, when the game loads. Its only job is to create the mod's layers with <code>layers.Create</code>. You don't add labels or shapes here. Each layer has a '''build function''' that does that.
* A layer's build function runs the first time the layer is shown. If the layer starts out shown, that's when the game loads. If the player never shows a layer, its build function never runs.
* After that, the layer is drawn once and kept. Refreshing the game doesn't rebuild it, and neither does the player turning it off and on again.
* To change a layer later, keep the layer that <code>layers.Create</code> returned, such as in a global variable. You can then call its functions from any client hook, such as [[Mod API Reference:Client GameRefresh|Client_GameRefresh]]. You can add or remove individual items, clear the layer, or run its build function again with <code>Rebuild</code>.


{| class="wikitable"
{| class="wikitable"
Line 29: Line 35:
|}
|}


=== layers.Create ===
== layers.Create ==
<code>layers.Create(name, defaultVisible)</code>
<code>layers.Create(name, buildFunction, defaultVisible)</code>


Creates a layer and returns it.
Creates a layer and returns it.
* '''name''': the name shown next to the layer's checkbox, under your mod's name. Names are cut to 50 characters. Creating a layer with a name you've already used in this call returns that same layer, so you can add to it from several places.
* '''name''': the name shown next to the layer's checkbox, under your mod's name. Names are cut to 50 characters. Each of a mod's layers must have a different name. Using the same name twice is an error.
* '''buildFunction''': a function <code>function(game, layer)</code> that adds the layer's labels and shapes. <code>game</code> is a [[Mod API Reference:ClientGame|ClientGame]] and <code>layer</code> is the same layer that <code>layers.Create</code> returns.
* '''defaultVisible''': whether the layer is shown before the player has changed its checkbox. Optional; defaults to true.
* '''defaultVisible''': whether the layer is shown before the player has changed its checkbox. Optional; defaults to true.


A mod can create up to 10 layers.
A mod can create up to 10 layers.
== Layer functions ==
These functions work the same way inside the build function and later, from other hooks. All of them except <code>AddShape</code> and <code>IsVisible</code> return the layer, so calls can be chained.


=== layer.AddLabel ===
=== layer.AddLabel ===
<code>layer.AddLabel(territoryID, text, options)</code>
<code>layer.AddLabel(territoryID, text, options)</code>


Adds a text label at a territory's middle point. It returns the layer, so calls can be chained.
Adds a text label at a territory's middle point.
* '''territoryID''': the territory to put the label on.
* '''territoryID''': the territory to put the label on.
* '''text''': the text to show. Text is cut to 100 characters.
* '''text''': the text to show. Text is cut to 100 characters.
Line 47: Line 57:
{| class="wikitable"
{| class="wikitable"
! Field !! Default !! Description
! Field !! Default !! Description
|-
| <code>Id</code> || none || A string or integer that identifies the label, so you can replace or remove it later. See [[#Ids|Ids]].
|-
|-
| <code>FontSize</code> || 10 || The size of the text, from 4 to 40.
| <code>FontSize</code> || 10 || The size of the text, from 4 to 40.
Line 60: Line 72:


=== layer.AddShape ===
=== layer.AddShape ===
<code>layer.AddShape()</code>
<code>layer.AddShape(options)</code>


Adds a shape and returns an object with the same functions as the <code>visual</code> object in [[Mod API Reference:Client Visual|Client_Visual]]:
Adds a shape and returns an object with the same functions as the <code>visual</code> object in [[Mod API Reference:Client Visual|Client_Visual]]:
Line 66: Line 78:
* SetFrames, SetRestTime and SetDepthTest
* SetFrames, SetRestTime and SetDepthTest
* SetAnchorTerritory and SetAnchorPoint
* SetAnchorTerritory and SetAnchorPoint
'''options''' is optional. It's a table whose only field is <code>Id</code>, which works the same as a label's Id.


Shapes don't animate. A shape is drawn at its rest pose: the pose at the time given to SetRestTime, which defaults to 1 (the last frame). For a shape that doesn't change, SetVertices is simplest.
Shapes don't animate. A shape is drawn at its rest pose: the pose at the time given to SetRestTime, which defaults to 1 (the last frame). For a shape that doesn't change, SetVertices is simplest.
Line 71: Line 85:
A layer can have up to 200 shapes. Problems with a shape are written to the mod log, the same as for Client_Visual. A shape that can't be drawn, such as one with a triangle index past the last vertex, is skipped.
A layer can have up to 200 shapes. Problems with a shape are written to the mod log, the same as for Client_Visual. A shape that can't be drawn, such as one with a triangle index past the last vertex, is skipped.


=== layer.Remove ===
<code>layer.Remove(id)</code> or <code>layer.Remove({id1, id2, ...})</code>
Removes the labels and shapes that have the given Id, or any of the Ids in the list. An Id that isn't in the layer is ignored.
=== layer.Clear ===
<code>layer.Clear()</code>
Removes everything from the layer.
=== layer.Rebuild ===
<code>layer.Rebuild()</code>
Clears the layer and runs its build function again. This is the simplest way to update a layer when much of it has changed. Changes your code made to the layer earlier in the same run are dropped, because the rebuild replaces them. Changes made after the call to Rebuild are applied on top of the rebuilt layer.
Calling Rebuild from inside the layer's own build function is an error.
=== layer.IsVisible ===
<code>layer.IsVisible()</code>
Returns true if the layer is currently shown on the map. It returns false if the player has turned the layer off, or if the client can't show layers (the website in 2D mode). Use it to skip the work of updating a layer nobody can see.
== Ids ==
Give a label or shape an Id if you'll want to change or remove it later. An Id is a string or an integer of up to 100 characters. Labels and shapes in a layer share the same Ids, so a label and a shape with the same Id are both removed by <code>Remove</code> with that Id.
Adding a label or shape with an Id that's already in the layer replaces the old one. That makes it easy to update a single item, such as a label whose text changes:
<pre>
CountLayer.AddLabel(terrID, 'Visited ' .. count .. ' times', { Id = terrID });
</pre>
== Updating a layer ==
* '''Changes are applied together.''' The changes your code makes to a layer are applied together when it finishes running. Only the labels and shapes that were added or removed are redrawn; the rest of the layer stays as it is. The 1000-label and 200-shape limits apply to what the layer will contain after the changes.
* '''Hidden layers ignore changes.''' A change to a hidden layer is ignored, because there's nothing on the map to change. When the player shows the layer again, it's built from scratch by its build function, so the build function should always describe the layer's current state. Use <code>IsVisible</code> to skip work for hidden layers.
* '''Not from Client_MapLayers.''' Calling <code>AddLabel</code>, <code>AddShape</code>, <code>Remove</code> or <code>Clear</code> from Client_MapLayers itself is an error. Add content in the build function, or later.
== Example ==
This example shows a green square on each of the player's territories. The layer is hidden until the player turns it on. Instead of rebuilding the whole layer, Client_GameRefresh adds squares for territories the player has gained and removes squares for territories they've lost. Each square's Id is its territory ID.
<code>Client_MapLayers.lua</code>:
<pre>
<pre>
-- a green square on each of the player's territories, hidden until the player turns it on
-- The territories the player owns, as a set
if (game.Us ~= nil) then
function MyTerritories(game)
     local mine = layers.Create('My territories', false);
     local ret = {};
     for terrID, standing in pairs(game.LatestStanding.Territories) do
     for terrID, standing in pairs(game.LatestStanding.Territories) do
         if (standing.OwnerPlayerID == game.Us.ID) then
         if (standing.OwnerPlayerID == game.Us.ID) then
             mine.AddShape()
             ret[terrID] = true;
                .SetAnchorTerritory(terrID)
        end
                .SetVertices({ {-8, -8}, {8, -8}, {8, 8}, {-8, 8} })
    end
                .SetTriangles({ 1, 2, 3, 1, 3, 4 })
    return ret;
                .SetColors('#8000FF00');
end
 
function AddMySquare(layer, terrID)
    layer.AddShape({ Id = terrID })
        .SetAnchorTerritory(terrID)
        .SetVertices({ {-8, -8}, {8, -8}, {8, 8}, {-8, 8} })
        .SetTriangles({ 1, 2, 3, 1, 3, 4 })
        .SetColors('#8000FF00');
end
 
function Client_MapLayers(game, layers)
    if (game.Us ~= nil) then
        MyTerritoriesLayer = layers.Create('My territories', function(game, layer)
            MyTerritoriesShown = MyTerritories(game);
            for terrID, _ in pairs(MyTerritoriesShown) do
                AddMySquare(layer, terrID);
            end
        end, false);
    end
end
</pre>
 
<code>Client_GameRefresh.lua</code>:
<pre>
function Client_GameRefresh(game)
    if (MyTerritoriesLayer ~= nil and MyTerritoriesLayer.IsVisible() and MyTerritoriesShown ~= nil) then
        local now = MyTerritories(game);
        for terrID, _ in pairs(MyTerritoriesShown) do
            if (now[terrID] == nil) then
                MyTerritoriesLayer.Remove(terrID);
            end
         end
         end
        for terrID, _ in pairs(now) do
            if (MyTerritoriesShown[terrID] == nil) then
                AddMySquare(MyTerritoriesLayer, terrID);
            end
        end
        MyTerritoriesShown = now;
     end
     end
end
</pre>
A simpler version of Client_GameRefresh rebuilds the whole layer instead:
<pre>
if (MyTerritoriesLayer ~= nil) then
    MyTerritoriesLayer.Rebuild();
end
end
</pre>
</pre>

Latest revision as of 01:38, 17 November 2026

Put the function in a file named Client_MapLayers.lua:

function Client_MapLayers(game, layers)
    layers.Create('Territory IDs', function(game, layer)
        for terrID, _ in pairs(game.Map.Territories) do
            layer.AddLabel(terrID, tostring(terrID));
        end
    end);
end

Client_Visual draws a visual for one order. This hook instead draws map layers: labels and shapes that stay on the map for as long as the game is open. Examples are territory IDs, zones of control, or a mod's own borders.

Players turn each layer on or off with checkboxes in a "Map layers" dialog, which opens from a button in the game's menu. That button only appears in games where a mod created at least one layer. The device remembers each player's choice for each mod and layer name.

Layers are drawn above territories and bonus links, and below army numbers.

Like Client_Visual, layers are shown in the app and on the website in 3D mode, but not on the website in 2D mode. In 2D mode, the "Map layers" dialog says that layers aren't supported.

How it works

Client_MapLayers runs once, when the game loads. Its only job is to create the mod's layers with layers.Create. You don't add labels or shapes here. Each layer has a build function that does that.

  • A layer's build function runs the first time the layer is shown. If the layer starts out shown, that's when the game loads. If the player never shows a layer, its build function never runs.
  • After that, the layer is drawn once and kept. Refreshing the game doesn't rebuild it, and neither does the player turning it off and on again.
  • To change a layer later, keep the layer that layers.Create returned, such as in a global variable. You can then call its functions from any client hook, such as Client_GameRefresh. You can add or remove individual items, clear the layer, or run its build function again with Rebuild.
Argument Type Description
game ClientGame Information about the game.
layers table The object you create layers with. See below.

layers.Create

layers.Create(name, buildFunction, defaultVisible)

Creates a layer and returns it.

  • name: the name shown next to the layer's checkbox, under your mod's name. Names are cut to 50 characters. Each of a mod's layers must have a different name. Using the same name twice is an error.
  • buildFunction: a function function(game, layer) that adds the layer's labels and shapes. game is a ClientGame and layer is the same layer that layers.Create returns.
  • defaultVisible: whether the layer is shown before the player has changed its checkbox. Optional; defaults to true.

A mod can create up to 10 layers.

Layer functions

These functions work the same way inside the build function and later, from other hooks. All of them except AddShape and IsVisible return the layer, so calls can be chained.

layer.AddLabel

layer.AddLabel(territoryID, text, options)

Adds a text label at a territory's middle point.

  • territoryID: the territory to put the label on.
  • text: the text to show. Text is cut to 100 characters.
  • options: optional. A table with any of these fields:
Field Default Description
Id none A string or integer that identifies the label, so you can replace or remove it later. See Ids.
FontSize 10 The size of the text, from 4 to 40.
FillColor 0 (black) The color of the text, as a number in the form 0xRRGGBB, such as 0xFF0000 for red.
OffsetX 0 How far right of the territory's middle to put the label, in map units.
OffsetY -18 How far below the territory's middle to put the label, in map units. The default puts it just above the army number.

A layer can have up to 1000 labels.

layer.AddShape

layer.AddShape(options)

Adds a shape and returns an object with the same functions as the visual object in Client_Visual:

  • SetVertices, SetTriangles and SetColors
  • SetFrames, SetRestTime and SetDepthTest
  • SetAnchorTerritory and SetAnchorPoint

options is optional. It's a table whose only field is Id, which works the same as a label's Id.

Shapes don't animate. A shape is drawn at its rest pose: the pose at the time given to SetRestTime, which defaults to 1 (the last frame). For a shape that doesn't change, SetVertices is simplest.

A layer can have up to 200 shapes. Problems with a shape are written to the mod log, the same as for Client_Visual. A shape that can't be drawn, such as one with a triangle index past the last vertex, is skipped.

layer.Remove

layer.Remove(id) or layer.Remove({id1, id2, ...})

Removes the labels and shapes that have the given Id, or any of the Ids in the list. An Id that isn't in the layer is ignored.

layer.Clear

layer.Clear()

Removes everything from the layer.

layer.Rebuild

layer.Rebuild()

Clears the layer and runs its build function again. This is the simplest way to update a layer when much of it has changed. Changes your code made to the layer earlier in the same run are dropped, because the rebuild replaces them. Changes made after the call to Rebuild are applied on top of the rebuilt layer.

Calling Rebuild from inside the layer's own build function is an error.

layer.IsVisible

layer.IsVisible()

Returns true if the layer is currently shown on the map. It returns false if the player has turned the layer off, or if the client can't show layers (the website in 2D mode). Use it to skip the work of updating a layer nobody can see.

Ids

Give a label or shape an Id if you'll want to change or remove it later. An Id is a string or an integer of up to 100 characters. Labels and shapes in a layer share the same Ids, so a label and a shape with the same Id are both removed by Remove with that Id.

Adding a label or shape with an Id that's already in the layer replaces the old one. That makes it easy to update a single item, such as a label whose text changes:

CountLayer.AddLabel(terrID, 'Visited ' .. count .. ' times', { Id = terrID });

Updating a layer

  • Changes are applied together. The changes your code makes to a layer are applied together when it finishes running. Only the labels and shapes that were added or removed are redrawn; the rest of the layer stays as it is. The 1000-label and 200-shape limits apply to what the layer will contain after the changes.
  • Hidden layers ignore changes. A change to a hidden layer is ignored, because there's nothing on the map to change. When the player shows the layer again, it's built from scratch by its build function, so the build function should always describe the layer's current state. Use IsVisible to skip work for hidden layers.
  • Not from Client_MapLayers. Calling AddLabel, AddShape, Remove or Clear from Client_MapLayers itself is an error. Add content in the build function, or later.

Example

This example shows a green square on each of the player's territories. The layer is hidden until the player turns it on. Instead of rebuilding the whole layer, Client_GameRefresh adds squares for territories the player has gained and removes squares for territories they've lost. Each square's Id is its territory ID.

Client_MapLayers.lua:

-- The territories the player owns, as a set
function MyTerritories(game)
    local ret = {};
    for terrID, standing in pairs(game.LatestStanding.Territories) do
        if (standing.OwnerPlayerID == game.Us.ID) then
            ret[terrID] = true;
        end
    end
    return ret;
end

function AddMySquare(layer, terrID)
    layer.AddShape({ Id = terrID })
        .SetAnchorTerritory(terrID)
        .SetVertices({ {-8, -8}, {8, -8}, {8, 8}, {-8, 8} })
        .SetTriangles({ 1, 2, 3, 1, 3, 4 })
        .SetColors('#8000FF00');
end

function Client_MapLayers(game, layers)
    if (game.Us ~= nil) then
        MyTerritoriesLayer = layers.Create('My territories', function(game, layer)
            MyTerritoriesShown = MyTerritories(game);
            for terrID, _ in pairs(MyTerritoriesShown) do
                AddMySquare(layer, terrID);
            end
        end, false);
    end
end

Client_GameRefresh.lua:

function Client_GameRefresh(game)
    if (MyTerritoriesLayer ~= nil and MyTerritoriesLayer.IsVisible() and MyTerritoriesShown ~= nil) then
        local now = MyTerritories(game);
        for terrID, _ in pairs(MyTerritoriesShown) do
            if (now[terrID] == nil) then
                MyTerritoriesLayer.Remove(terrID);
            end
        end
        for terrID, _ in pairs(now) do
            if (MyTerritoriesShown[terrID] == nil) then
                AddMySquare(MyTerritoriesLayer, terrID);
            end
        end
        MyTerritoriesShown = now;
    end
end

A simpler version of Client_GameRefresh rebuilds the whole layer instead:

if (MyTerritoriesLayer ~= nil) then
    MyTerritoriesLayer.Rebuild();
end