Modding
Waypoint Map
Updated 21 November 2026
M opens a map of the world in the game's own style; click for waypoints (Shift+click: shared with everyone). Waypoints show on the compass.
Mod id example.waypointmap, side both.
A code mod: build it with dotnet build (see Making mods) and put the output folder in the game's Mods folder.
mod.json
{
"id": "example.waypointmap",
"name": "Waypoint Map",
"version": "1.2",
"author": "Seeds & Circuits",
"side": "both",
"description": "M opens a map of the world in the game's own style; click for waypoints (Shift+click: shared with everyone). Waypoints show on the compass."
}
WaypointMap.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SeedsAndCircuits.DebugConsole;
using SeedsAndCircuits.Inventory;
using SeedsAndCircuits.Inventory.UI;
using SeedsAndCircuits.Mods;
using SeedsAndCircuits.Player;
using SeedsAndCircuits.Terrain;
using SeedsAndCircuits.UI;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using Compass = SeedsAndCircuits.Player.UI.Compass; // UnityEngine has a Compass too (the device sensor)
namespace WaypointMap
{
/// <summary>
/// M opens a map of the whole world (drawn from the terrain's data, so all of it, loaded or not), centred on you. Click to set a waypoint, Shift+click
/// for a shared one everyone in the game sees, right-click to remove one. Waypoints show on the compass too.
/// <list type="bullet">
/// <item>Private waypoints are this player's own: saved on their machine, per world.</item>
/// <item>Shared waypoints live on the host: players ask the host to add or remove one, the host keeps them in the
/// world save (<c>WorldData</c>) and sends the list to everyone (and to each player who joins).</item>
/// <item>The key is rebindable (Settings ▸ Controls, "Waypoint Map: Open Map"); Settings ▸ Mods has its options.</item>
/// <item>The screen is the game's own UI (uGUI with its window look, font and colours), built in code. Input is read
/// in <c>OnUpdate</c>: a mod's own MonoBehaviours can't always be added as components.</item>
/// </list>
/// Side "both": everyone in a game needs it, because shared waypoints go through the host's copy.
/// </summary>
public sealed class WaypointMap : Mod
{
[Serializable]
sealed class Waypoint
{
public string name;
public Vector3 position;
public bool shared;
public string by;
}
[Serializable]
sealed class WaypointList
{
public string world;
public List<Waypoint> waypoints = new List<Waypoint>();
}
// The game's own colours (InventoryUIStyle): its blue, its green and its gold.
static readonly Color PrivateColor = new Color(0.55f, 0.78f, 1f, 1f);
static readonly Color SharedColor = new Color(0.62f, 0.9f, 0.55f, 1f);
static readonly Color PlayerColor = new Color(1f, 0.8f, 0.36f, 1f);
// The whole world, once per world; then the part in view, sharp, whenever the view settles.
const int OverviewPixels = 1024;
const int OverviewRowsPerFrame = 128;
const int DetailPixels = 1536;
const int DetailRowsPerFrame = 96;
/// <summary>The detail map covers this much more than the view, so a little panning needs no redraw.</summary>
const float DetailMargin = 1.5f;
const float DetailDelay = 0.12f;
/// <summary>Closest zoom: this many metres across the map.</summary>
const float MinSpan = 48f;
const float HoverRadius = 14f;
static WaypointMap s_Instance;
WaypointList _private = new WaypointList();
WaypointList _shared = new WaypointList(); // host: the real list; players: the host's last copy
string _worldKey;
InputAction _openKey;
ModToggle _onCompass;
ModSlider _mapSize;
// ------------------------------------------------------------------ lifecycle
public override void OnLoad()
{
s_Instance = this;
_openKey = AddKey("Open Map", "<Keyboard>/m");
_onCompass = AddToggle("compass", "Waypoints on the compass", true);
_mapSize = AddSlider("size", "Map size (% of the screen)", 50f, 95f, 85f, 5f);
// Host: players ask for changes to the shared list.
OnMessage("add", msg =>
{
if (!IsServer)
return;
Waypoint w = Json.FromJson<Waypoint>(msg.Text);
if (w == null || string.IsNullOrWhiteSpace(w.name))
return;
w.shared = true;
w.name = w.name.Trim();
_shared.waypoints.RemoveAll(x => x.name == w.name);
_shared.waypoints.Add(w);
SaveShared();
SendShared();
});
OnMessage("remove", msg =>
{
if (!IsServer || _shared.waypoints.RemoveAll(x => x.name == msg.Text) == 0)
return;
SaveShared();
SendShared();
});
// Everyone (the host too): the host's shared list, and which world it is.
OnMessage("shared", msg =>
{
WaypointList list = Json.FromJson<WaypointList>(msg.Text);
if (list == null)
return;
_shared = list;
if (_worldKey != list.world)
{
_worldKey = list.world;
LoadPrivate();
}
});
Compass.CollectMarkers += AddCompassMarkers;
}
public override void OnUnload()
{
Compass.CollectMarkers -= AddCompassMarkers;
Close();
ResetMap();
s_Instance = null;
}
public override void OnWorldLoaded()
{
if (!IsServer)
return; // players get the world and list from the host when they join
// The host's world: its name plus the host's player id, so two hosts' "World 1"s don't mix.
_worldKey = $"{WorldName}-{Short(InventoryStore.LocalPlayerId)}";
_shared = WorldData.Get<WaypointList>("shared") ?? new WaypointList();
_shared.world = _worldKey;
LoadPrivate();
SendShared();
}
public override void OnWorldUnloaded()
{
Close();
ResetMap();
_shared = new WaypointList();
_private = new WaypointList();
_worldKey = null;
}
public override void OnPlayerJoined(ulong clientId) =>
SendToClient(clientId, "shared", Json.ToJson(_shared));
// ------------------------------------------------------------------ files
static string Short(string id) => string.IsNullOrEmpty(id) ? "host" : id.Length > 8 ? id.Substring(0, 8) : id;
static string Safe(string name) => string.Concat((name ?? "world").Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c));
string PrivatePath => Path.Combine(DataFolder, "private", Safe(_worldKey) + ".json");
WaypointList Load(string path)
{
try
{
return File.Exists(path) ? Json.FromJson<WaypointList>(File.ReadAllText(path)) : null;
}
catch (Exception e)
{
LogWarning($"Could not read {path}: {e.Message}");
return null;
}
}
void Save(string path, WaypointList list)
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.WriteAllText(path, Json.ToJson(list, pretty: true));
}
void LoadPrivate() => _private = (_worldKey != null ? Load(PrivatePath) : null) ?? new WaypointList { world = _worldKey };
void SavePrivate()
{
if (_worldKey != null)
Save(PrivatePath, _private);
}
// In the world save: it moves, copies and gets deleted with the world.
void SaveShared() => WorldData.Set("shared", _shared);
void SendShared() => SendToClients("shared", Json.ToJson(_shared));
// ------------------------------------------------------------------ waypoints
IEnumerable<Waypoint> All => _private.waypoints.Concat(_shared.waypoints);
string NextName()
{
for (int i = 1; ; i++)
{
string name = $"Waypoint {i}";
if (All.All(w => w.name != name))
return name;
}
}
void Add(string name, Vector3 position, bool shared)
{
var w = new Waypoint { name = name, position = position, shared = shared, by = PlayerSpawn.Local != null ? PlayerSpawn.Local.DisplayName : null };
if (shared)
{
SendToServer("add", Json.ToJson(w)); // the host adds it and sends everyone the new list
return;
}
_private.waypoints.RemoveAll(x => x.name == name);
_private.waypoints.Add(w);
SavePrivate();
}
bool Remove(string name)
{
if (_private.waypoints.RemoveAll(x => x.name == name) > 0)
{
SavePrivate();
return true;
}
if (_shared.waypoints.Any(x => x.name == name))
{
SendToServer("remove", name);
return true;
}
return false;
}
void AddCompassMarkers(List<Compass.ExtraMarker> markers)
{
if (!_onCompass.Value)
return;
foreach (Waypoint w in All)
markers.Add(new Compass.ExtraMarker(w.position, w.shared ? SharedColor : PrivateColor));
}
// ------------------------------------------------------------------ opening and closing
bool _open;
int _closedFrame = -1;
public override void OnUpdate()
{
DrawOverviewSlice();
if (PlayerSpawn.Local == null || DebugConsole.IsOpen)
return;
// Mod keys only work during play; with the map open the game's controls are off, so the same key is read
// straight from the keyboard to close it. Escape, Tab, E and the gamepad's B close it too (the game's
// menu keys close every mod screen: OnCloseScreen).
if (!_open && Time.frameCount != _closedFrame && _openKey.WasPressedThisFrame())
Open();
else if (_open && PressedNow(_openKey))
Close();
if (_open)
UpdateScreen();
}
public override void OnCloseScreen() => Close();
static bool PressedNow(InputAction action)
{
foreach (InputBinding binding in action.bindings)
{
if (InputSystem.FindControl(binding.effectivePath) is UnityEngine.InputSystem.Controls.ButtonControl button && button.wasPressedThisFrame)
return true;
}
return false;
}
void Open()
{
TerrainWorld world = TerrainWorld.Instance;
if (world == null || !world.IsInitialized || _pixels == null)
return;
_open = true;
// Frees the cursor and turns the game's controls off (moving, tools, hotbar scroll...) until closed.
ScreenOpen = true;
BuildScreen();
_canvas.enabled = true;
// Centred on you, showing about your island (not the whole ocean around it).
Rect start = world.StartBounds;
float island = Mathf.Max(start.width, start.height);
_span = Mathf.Clamp(island > 0f ? island * 1.1f : _area.width * 0.5f, MinSpan, _area.width);
Vector3 me = PlayerSpawn.Local.Feet;
_center = new Vector2(me.x, me.z);
_dragging = false;
ViewChanged();
}
void Close()
{
if (!_open)
return;
_open = false;
_closedFrame = Time.frameCount;
_dragging = false;
if (_canvas != null)
_canvas.enabled = false;
ScreenOpen = false;
}
// ------------------------------------------------------------------ the map pictures
// Overview: the whole world (TerrainWorld.MapArea), drawn a few rows a frame after the world loads, from the
// terrain's data (TerrainWorld.RenderMap), so it's ready by the time the map opens and costs no frame much.
Rect _area;
Color32[] _pixels;
int _drawnRows;
Texture2D _overview;
// Detail: the part in view (with a margin), sharp at any zoom. Drawn into _detailPixels while the last one
// shows; it takes over once it's complete.
Color32[] _detailPixels;
Rect _drawingArea;
int _detailRows = -1; // -1: not drawing
Texture2D _detail;
Rect _detailArea;
bool _detailReady;
void DrawOverviewSlice()
{
TerrainWorld world = TerrainWorld.Instance;
if (world == null || !world.IsInitialized || PlayerSpawn.Local == null)
return;
if (_pixels == null)
{
_area = world.MapArea(PlayerSpawn.Local.Feet, 2048f);
_pixels = new Color32[OverviewPixels * OverviewPixels];
_drawnRows = 0;
}
if (_drawnRows >= OverviewPixels)
return;
if (!world.RenderMap(_area, OverviewPixels, _pixels, _drawnRows, OverviewRowsPerFrame))
return;
_drawnRows = Mathf.Min(OverviewPixels, _drawnRows + OverviewRowsPerFrame);
// Show progress while the map is open; upload once at the end otherwise.
if (_drawnRows < OverviewPixels && !_open)
return;
if (_overview == null)
_overview = new Texture2D(OverviewPixels, OverviewPixels, TextureFormat.RGBA32, true) { name = "Waypoint Map", wrapMode = TextureWrapMode.Clamp };
_overview.SetPixels32(_pixels);
_overview.Apply();
}
/// <summary>While open: (re)draws the detail map of the view once it has settled and the last one doesn't cover it.</summary>
void DrawDetailSlice()
{
TerrainWorld world = TerrainWorld.Instance;
if (world == null || _drawnRows < OverviewPixels)
return;
Rect view = View;
bool zoomedIn = _span < _area.width * 0.6f;
bool covered = _detailReady && Contains(_detailArea, view);
if (zoomedIn && !covered && Time.unscaledTime - _viewChangedAt >= DetailDelay &&
(_detailRows < 0 || !Contains(_drawingArea, view)))
{
float side = Mathf.Min(_span * DetailMargin, _area.width);
_drawingArea = ClampToArea(new Rect(_center.x - side * 0.5f, _center.y - side * 0.5f, side, side));
_detailPixels ??= new Color32[DetailPixels * DetailPixels];
_detailRows = 0;
}
if (_detailRows < 0)
return;
if (!world.RenderMap(_drawingArea, DetailPixels, _detailPixels, _detailRows, DetailRowsPerFrame))
return;
_detailRows += DetailRowsPerFrame;
if (_detailRows < DetailPixels)
return;
_detailRows = -1;
if (_detail == null)
_detail = new Texture2D(DetailPixels, DetailPixels, TextureFormat.RGBA32, true) { name = "Waypoint Map Detail", wrapMode = TextureWrapMode.Clamp };
_detail.SetPixels32(_detailPixels);
_detail.Apply();
_detailArea = _drawingArea;
_detailReady = true;
}
static bool Contains(Rect outer, Rect inner) =>
inner.xMin >= outer.xMin - 0.01f && inner.yMin >= outer.yMin - 0.01f &&
inner.xMax <= outer.xMax + 0.01f && inner.yMax <= outer.yMax + 0.01f;
Rect ClampToArea(Rect r)
{
r.x = Mathf.Clamp(r.x, _area.xMin, _area.xMax - r.width);
r.y = Mathf.Clamp(r.y, _area.yMin, _area.yMax - r.height);
return r;
}
void ResetMap()
{
_pixels = null;
_drawnRows = 0;
_detailPixels = null;
_detailRows = -1;
_detailReady = false;
if (_overview != null)
UnityEngine.Object.Destroy(_overview);
if (_detail != null)
UnityEngine.Object.Destroy(_detail);
_overview = _detail = null;
if (_canvas != null)
UnityEngine.Object.Destroy(_canvas.gameObject);
_canvas = null;
_markers.Clear();
}
// ------------------------------------------------------------------ the view
Vector2 _center; // world X/Z in the middle of the map
float _span; // metres across it
float _viewChangedAt;
bool _dragging, _dragged;
Vector2 _dragStart, _dragLast;
Rect View => new Rect(_center.x - _span * 0.5f, _center.y - _span * 0.5f, _span, _span);
void ViewChanged()
{
_span = Mathf.Clamp(_span, MinSpan, _area.width);
Rect clamped = ClampToArea(View);
_center = clamped.center;
_viewChangedAt = Time.unscaledTime;
}
/// <summary>World X/Z → a point in the map viewport (its centre is 0,0; north is up).</summary>
Vector2 ToLocal(Vector3 world) => new Vector2((world.x - _center.x) / _span * ViewSize, (world.z - _center.y) / _span * ViewSize);
Vector2 ToWorldXZ(Vector2 local) => _center + local / ViewSize * _span;
float ViewSize => _viewport != null ? _viewport.rect.width : 1f;
Vector3 ToWorld(Vector2 xz)
{
Vector3 me = PlayerSpawn.Local != null ? PlayerSpawn.Local.Feet : Vector3.zero;
// The ground under the click where it's loaded; elsewhere the player's height will do for a compass mark.
return Physics.Raycast(new Vector3(xz.x, me.y + 500f, xz.y), Vector3.down, out RaycastHit hit, 1500f, ~0, QueryTriggerInteraction.Ignore)
? hit.point
: new Vector3(xz.x, me.y, xz.y);
}
// ------------------------------------------------------------------ the screen (uGUI, the game's look)
Canvas _canvas;
RectTransform _window;
RectTransform _viewport;
RawImage _overviewImage, _detailImage;
RectTransform _markerLayer;
TMP_Text _status, _hint;
float _builtSize = -1f;
sealed class Marker
{
public RectTransform Root;
public ProceduralImage Dot;
public RectTransform Tag;
public TMP_Text Label;
}
readonly List<Marker> _markers = new List<Marker>();
Marker _me;
static InventoryUIStyle Style => InventoryUI.Current != null && InventoryUI.Current.style != null ? InventoryUI.Current.style : new InventoryUIStyle();
void BuildScreen()
{
if (_canvas != null && Mathf.Approximately(_builtSize, _mapSize.Value))
return;
if (_canvas != null)
{
UnityEngine.Object.Destroy(_canvas.gameObject);
_markers.Clear();
}
_builtSize = _mapSize.Value;
InventoryUIStyle s = Style;
var root = new GameObject("Waypoint Map");
UnityEngine.Object.DontDestroyOnLoad(root);
_canvas = root.AddComponent<Canvas>();
_canvas.renderMode = RenderMode.ScreenSpaceOverlay;
_canvas.sortingOrder = 60; // over the HUD and the inventory (50)
var scaler = root.AddComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920f, 1080f);
scaler.matchWidthOrHeight = 0.5f;
root.AddComponent<GraphicRaycaster>();
// Dims the game and keeps clicks off the HUD behind.
RectTransform backdrop = Rect("Backdrop", root.transform);
Stretch(backdrop);
backdrop.gameObject.AddComponent<Image>().color = new Color(0f, 0f, 0f, 0.45f);
const float pad = 22f, header = 40f, footer = 26f, gap = 14f;
float height = 1080f * _mapSize.Value / 100f;
float side = height - 2f * pad - header - footer - 2f * gap;
_window = Rect("Window", root.transform);
_window.sizeDelta = new Vector2(side + 2f * pad, height);
CraftingUIBuilder.WindowLook(_window.gameObject);
// Header: title, and the legend on the right.
TMP_Text title = Text(_window, "Map", 28f, s.text, FontStyles.Bold, TextAlignmentOptions.Left);
Place(title.rectTransform, new Vector2(0f, 1f), new Vector2(pad, -pad), new Vector2(300f, header));
RectTransform legend = Rect("Legend", _window);
Place(legend, new Vector2(1f, 1f), new Vector2(-pad, -pad), new Vector2(side - 200f, header));
var legendLayout = legend.gameObject.AddComponent<HorizontalLayoutGroup>();
legendLayout.childAlignment = TextAnchor.MiddleRight;
legendLayout.spacing = 6f;
legendLayout.childControlWidth = legendLayout.childControlHeight = true;
legendLayout.childForceExpandWidth = legendLayout.childForceExpandHeight = false;
LegendEntry(legend, Color.white, "You");
LegendEntry(legend, PlayerColor, "Players");
LegendEntry(legend, PrivateColor, "Waypoint");
LegendEntry(legend, SharedColor, "Shared");
// The map in an inset frame.
RectTransform frame = Rect("Frame", _window);
Place(frame, new Vector2(0.5f, 1f), new Vector2(0f, -pad - header - gap), new Vector2(side, side));
ProceduralImage frameLook = frame.gameObject.AddComponent<ProceduralImage>();
frameLook.color = new Color(0f, 0f, 0f, 0.35f);
frameLook.cornerRadius = 14f;
frameLook.outlineWidth = 1f;
frameLook.outlineColor = new Color(1f, 1f, 1f, 0.1f);
frameLook.raycastTarget = false;
_viewport = Rect("Viewport", frame);
Stretch(_viewport);
_viewport.offsetMin = new Vector2(5f, 5f);
_viewport.offsetMax = new Vector2(-5f, -5f);
_viewport.gameObject.AddComponent<RectMask2D>();
_overviewImage = Picture("Overview", _viewport);
_detailImage = Picture("Detail", _viewport);
_markerLayer = Rect("Markers", _viewport);
Stretch(_markerLayer);
_status = Text(_viewport, string.Empty, 20f, s.text, FontStyles.Bold, TextAlignmentOptions.Center);
Stretch(_status.rectTransform);
_hint = Text(_window, string.Empty, 16f, s.subtleText, FontStyles.Normal, TextAlignmentOptions.Center);
Place(_hint.rectTransform, new Vector2(0.5f, 0f), new Vector2(0f, pad), new Vector2(side, footer));
_hint.rectTransform.pivot = new Vector2(0.5f, 0f);
_me = NewMarker(isMe: true);
}
/// <summary>A dot in a marker colour and its name (the font has no "●").</summary>
void LegendEntry(RectTransform legend, Color color, string name)
{
RectTransform dot = Rect("Dot", legend);
var look = dot.gameObject.AddComponent<ProceduralImage>();
look.shape = ProceduralShape.Ellipse;
look.color = color;
look.raycastTarget = false;
var size = dot.gameObject.AddComponent<LayoutElement>();
size.preferredWidth = size.preferredHeight = 11f;
TMP_Text text = Text(legend, name, 17f, Style.subtleText, FontStyles.Normal, TextAlignmentOptions.Left);
text.margin = new Vector4(0f, 0f, 12f, 0f);
text.textWrappingMode = TextWrappingModes.NoWrap;
}
RawImage Picture(string name, RectTransform parent)
{
RectTransform r = Rect(name, parent);
Stretch(r);
var image = r.gameObject.AddComponent<RawImage>();
image.raycastTarget = false;
image.enabled = false;
return image;
}
Marker NewMarker(bool isMe = false)
{
InventoryUIStyle s = Style;
var m = new Marker { Root = Rect(isMe ? "You" : "Marker", _markerLayer) };
m.Root.sizeDelta = Vector2.zero;
RectTransform dot = Rect("Dot", m.Root);
dot.sizeDelta = isMe ? new Vector2(24f, 24f) : new Vector2(14f, 14f);
m.Dot = dot.gameObject.AddComponent<ProceduralImage>();
m.Dot.raycastTarget = false;
m.Dot.outlineWidth = 2f;
m.Dot.outlineColor = new Color(0.05f, 0.06f, 0.07f, 0.9f);
m.Dot.outlineAlignment = ProceduralOutlineAlignment.Outside;
m.Dot.shadowEnabled = true;
m.Dot.shadowColor = new Color(0f, 0f, 0f, 0.5f);
m.Dot.shadowBlur = 4f;
if (isMe)
{
// A heading arrow: a triangle, turned to where you look.
m.Dot.shape = ProceduralShape.Polygon;
m.Dot.sides = 3;
m.Dot.color = Color.white;
return m;
}
m.Dot.shape = ProceduralShape.Ellipse;
// A name tag: a dark pill sized to its text.
m.Tag = Rect("Tag", m.Root);
m.Tag.anchorMin = m.Tag.anchorMax = new Vector2(0.5f, 0.5f);
m.Tag.pivot = new Vector2(0f, 0.5f);
m.Tag.anchoredPosition = new Vector2(12f, 0f);
ProceduralImage pill = m.Tag.gameObject.AddComponent<ProceduralImage>();
pill.color = new Color(0.05f, 0.06f, 0.07f, 0.72f);
pill.cornerRadius = 9f;
pill.raycastTarget = false;
var layout = m.Tag.gameObject.AddComponent<HorizontalLayoutGroup>();
layout.padding = new RectOffset(8, 8, 2, 3);
layout.childControlWidth = layout.childControlHeight = true;
layout.childForceExpandWidth = layout.childForceExpandHeight = false;
var fit = m.Tag.gameObject.AddComponent<ContentSizeFitter>();
fit.horizontalFit = fit.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
m.Label = Text(m.Tag, string.Empty, 15f, s.text, FontStyles.Bold, TextAlignmentOptions.Left);
m.Label.textWrappingMode = TextWrappingModes.NoWrap;
_markers.Add(m);
return m;
}
TMP_Text Text(Transform parent, string text, float size, Color color, FontStyles style, TextAlignmentOptions align)
{
RectTransform r = Rect("Text", parent);
var t = r.gameObject.AddComponent<TextMeshProUGUI>();
t.font = Style.Font;
t.text = text;
t.fontSize = size;
t.color = color;
t.fontStyle = style;
t.alignment = align;
t.raycastTarget = false;
t.richText = true;
return t;
}
static RectTransform Rect(string name, Transform parent)
{
var go = new GameObject(name, typeof(RectTransform));
go.layer = 5; // UI
var r = (RectTransform)go.transform;
r.SetParent(parent, false);
return r;
}
static void Stretch(RectTransform r)
{
r.anchorMin = Vector2.zero;
r.anchorMax = Vector2.one;
r.offsetMin = r.offsetMax = Vector2.zero;
}
/// <summary>Anchored and pivoted at <paramref name="anchor"/> (a corner or edge of the parent).</summary>
static void Place(RectTransform r, Vector2 anchor, Vector2 position, Vector2 size)
{
r.anchorMin = r.anchorMax = r.pivot = anchor;
r.anchoredPosition = position;
r.sizeDelta = size;
}
// ------------------------------------------------------------------ every frame while open
void UpdateScreen()
{
if (_mapSize.Value != _builtSize)
BuildScreen();
HandleInput();
DrawDetailSlice();
// The pictures: the part of each that's in view.
Rect view = View;
_overviewImage.enabled = _overview != null;
if (_overview != null)
_overviewImage.texture = _overview;
_overviewImage.uvRect = UV(_area, view);
bool detail = _detailReady && _span < _area.width * 0.6f && Contains(_detailArea, view);
_detailImage.enabled = detail;
if (detail)
{
_detailImage.texture = _detail;
_detailImage.uvRect = UV(_detailArea, view);
}
_status.text = _drawnRows < OverviewPixels ? $"Drawing the map... {100 * _drawnRows / OverviewPixels}%" : string.Empty;
LayoutMarkers();
string close = _openKey.GetBindingDisplayString();
_hint.text = $"Click: waypoint · Shift+click: shared · Right-click: remove · Drag: move · Scroll: zoom · Space: find me · {close} / Esc: close";
}
/// <summary>Where <paramref name="view"/> lies in a picture of <paramref name="picture"/>, as a uvRect.</summary>
static Rect UV(Rect picture, Rect view) =>
new Rect((view.xMin - picture.xMin) / picture.width, (view.yMin - picture.yMin) / picture.height,
view.width / picture.width, view.height / picture.height);
Waypoint _hovered;
void HandleInput()
{
Mouse mouse = Mouse.current;
if (mouse == null || _viewport == null)
return;
RectTransformUtility.ScreenPointToLocalPointInRectangle(_viewport, mouse.position.ReadValue(), null, out Vector2 local);
local -= _viewport.rect.center;
float half = ViewSize * 0.5f;
bool over = Mathf.Abs(local.x) <= half && Mathf.Abs(local.y) <= half;
_hovered = null;
if (over)
{
float best = HoverRadius * HoverRadius;
foreach (Waypoint w in All)
{
float d = (ToLocal(w.position) - local).sqrMagnitude;
if (d <= best)
{
best = d;
_hovered = w;
}
}
}
// Zoom around the point under the mouse.
float scroll = mouse.scroll.ReadValue().y;
if (over && Mathf.Abs(scroll) > 0.01f)
{
Vector2 at = ToWorldXZ(local);
float span = Mathf.Clamp(_span * (scroll < 0f ? 1.25f : 0.8f), MinSpan, _area.width);
_center = at + (_center - at) * (span / _span);
_span = span;
ViewChanged();
}
if (mouse.leftButton.wasPressedThisFrame && over)
{
_dragging = true;
_dragged = false;
_dragStart = _dragLast = local;
}
if (_dragging && mouse.leftButton.isPressed)
{
if ((local - _dragStart).sqrMagnitude > 16f)
_dragged = true;
if (_dragged && local != _dragLast)
{
_center -= (local - _dragLast) / ViewSize * _span;
ViewChanged();
}
_dragLast = local;
}
if (_dragging && mouse.leftButton.wasReleasedThisFrame)
{
_dragging = false;
if (!_dragged && over)
{
Keyboard keyboard = Keyboard.current;
bool shift = keyboard != null && keyboard.shiftKey.isPressed;
Add(NextName(), ToWorld(ToWorldXZ(local)), shared: shift);
}
}
if (mouse.rightButton.wasPressedThisFrame && _hovered != null)
{
Remove(_hovered.name);
_hovered = null;
}
if (Keyboard.current != null && Keyboard.current.spaceKey.wasPressedThisFrame && PlayerSpawn.Local != null)
{
Vector3 me = PlayerSpawn.Local.Feet;
_center = new Vector2(me.x, me.z);
ViewChanged();
}
}
void LayoutMarkers()
{
float half = ViewSize * 0.5f;
int used = 0;
Vector3 mine = PlayerSpawn.Local != null ? PlayerSpawn.Local.Feet : Vector3.zero;
void Show(Vector3 position, Color color, string label)
{
Vector2 at = ToLocal(position);
if (Mathf.Abs(at.x) > half + 6f || Mathf.Abs(at.y) > half + 6f)
return;
Marker m = used < _markers.Count ? _markers[used] : NewMarker();
used++;
m.Root.gameObject.SetActive(true);
m.Root.anchoredPosition = at;
m.Dot.color = color;
if (m.Label.text != label)
m.Label.text = label;
}
foreach (PlayerSpawn p in PlayerSpawn.All)
{
if (p != null && p != PlayerSpawn.Local)
Show(p.Feet, PlayerColor, p.DisplayName);
}
foreach (Waypoint w in All)
{
string label = w.name;
if (w.shared && !string.IsNullOrEmpty(w.by))
label += $" <alpha=#88>({w.by})";
if (w == _hovered)
label += $" <alpha=#88>· {Vector3.Distance(mine, w.position):0} m";
Show(w.position, w.shared ? SharedColor : PrivateColor, label);
}
for (int i = used; i < _markers.Count; i++)
_markers[i].Root.gameObject.SetActive(false);
// You, on top: pointing the way you look (north up).
PlayerSpawn me = PlayerSpawn.Local;
_me.Root.gameObject.SetActive(me != null);
if (me == null)
return;
_me.Root.SetAsLastSibling();
_me.Root.anchoredPosition = ToLocal(me.Feet);
float yaw = Camera.main != null ? Camera.main.transform.eulerAngles.y : me.transform.eulerAngles.y;
_me.Root.localEulerAngles = new Vector3(0f, 0f, -yaw);
}
// ------------------------------------------------------------------ console
[ConsoleCommandAttribute("waypoint.add", "A waypoint at your feet (add 'shared' for everyone).", Usage = "<name> [shared]", Local = true)]
static string AddCommand(ConsoleArgs args)
{
WaypointMap mod = s_Instance;
PlayerSpawn local = PlayerSpawn.Local;
if (mod == null || local == null)
return "Not in a world.";
bool shared = args.Count > 1 && args[args.Count - 1] == "shared";
string name = args.Count == 0 ? mod.NextName() : string.Join(" ", Enumerable.Range(0, shared ? args.Count - 1 : args.Count).Select(i => args[i]));
mod.Add(name, local.Feet, shared);
return $"Waypoint \"{name}\"{(shared ? " shared" : string.Empty)}.";
}
[ConsoleCommandAttribute("waypoint.remove", "Removes a waypoint.", Usage = "<name>", Local = true)]
static string RemoveCommand(ConsoleArgs args)
{
WaypointMap mod = s_Instance;
string name = args.Rest(0) ?? throw new ConsoleArgumentException("Remove which?");
return mod != null && mod.Remove(name) ? $"Removed \"{name}\"." : $"No waypoint \"{name}\".";
}
[ConsoleCommandAttribute("waypoint.list", "Your waypoints and the shared ones.", Local = true)]
static string ListCommand()
{
WaypointMap mod = s_Instance;
if (mod == null || !mod.All.Any())
return "No waypoints.";
Vector3 me = PlayerSpawn.Local != null ? PlayerSpawn.Local.Feet : Vector3.zero;
return string.Join("\n", mod.All.Select(w =>
$"{(w.shared ? "[shared] " : string.Empty)}{w.name}: {Vector3.Distance(me, w.position):0} m{(w.shared && !string.IsNullOrEmpty(w.by) ? $" (by {w.by})" : string.Empty)}"));
}
}
}
WaypointMap.csproj
<Project Sdk="Microsoft.NET.Sdk">
<!-- Build settings and game references: ../Mod.props. Output: bin/Waypoint Map/ -->
<PropertyGroup>
<AssemblyName>WaypointMap</AssemblyName>
<ModFolder>Waypoint Map</ModFolder>
</PropertyGroup>
<Import Project="../Mod.props" />
</Project>