wow-addons/ShipRoutes/ShipRoutes.lua
rope 40add57ba9 Ship Routes: routes rest faded, hover brings one to full opacity
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:38:46 +00:00

626 lines
20 KiB
Lua

-- Ship Routes: draws boat, zeppelin and airship routes on the world map, with a marker
-- at each dock that says where the ship goes. Route data is in Data.lua (generated).
local addonName, ns = ...
local PREFIX = "|cff66bbffShip Routes|r: "
local TEMPLATE = "ShipRoutesPinTemplate"
local ICONS = "Interface\\AddOns\\ShipRoutes\\Icons\\"
local GLYPH = { boat = ICONS .. "anchor", air = ICONS .. "zeppelin", exit = ICONS .. "arrow" }
local COLORS = {
Alliance = { 0.35, 0.62, 1.00 },
Horde = { 1.00, 0.32, 0.24 },
Neutral = { 1.00, 0.82, 0.25 },
}
-- line width in screen pixels, and resting opacity: routes sit faded until hovered
local STYLE = {
boat = { width = 3, alpha = 0.4 },
air = { width = 2.5, alpha = 0.35 },
}
local LIT = 1 -- opacity of a route while its marker is hovered; the rest stay at their resting opacity
local WORLD_MAP = 947 -- Azeroth: the shared space that legs between continents are drawn in
local WORLD = -1 -- instance marker in Data.lua for a point given on the world map
-- the zone or continent map each instance is placed on the world map by
local HOME_MAP = { [0] = 1415, [1] = 1414, [2991] = 2521 }
local NEARBY = 800 -- yards: other departures this close show in a dock's tooltip
local EXIT_INSET = 0.025 -- share of the map an edge marker sits inside the border
local EXIT_MERGE = 0.06 -- edge markers closer than this share of the map width merge
local db
local function Color(route)
return COLORS[route.faction or "Neutral"]
end
local function Visible(route)
if not db or not db.mine then
return true
end
local f = route.faction
return f == nil or f == "Neutral" or f == UnitFactionGroup("player")
end
ns.Visible = Visible
---------------------------------------------------------------------------
-- Projection: (instance, world x, world y) or a world map point -> position on a uiMap
---------------------------------------------------------------------------
local function IsWorldMap(uiMapID)
local info = C_Map.GetMapInfo(uiMapID)
return info and info.mapType and info.mapType <= Enum.UIMapType.World
end
-- world position on a zone or continent map
local direct = {}
local function Direct(uiMapID)
local cached = direct[uiMapID]
if cached ~= nil then
return cached or nil
end
local fn = false
if not IsWorldMap(uiMapID) then
local inst, topLeft = C_Map.GetWorldPosFromMapPos(uiMapID, CreateVector2D(0, 0))
local _, mid = C_Map.GetWorldPosFromMapPos(uiMapID, CreateVector2D(0.5, 0.5))
if inst and topLeft and mid then
local top, left = topLeft:GetXY()
local midTop, midLeft = mid:GetXY()
local height, width = (top - midTop) * 2, (left - midLeft) * 2
if height ~= 0 and width ~= 0 then
fn = function(m, x, y)
if m ~= inst then
return nil
end
return (left - y) / width, (top - x) / height
end
end
end
end
direct[uiMapID] = fn
return fn or nil
end
-- where a map sits on the world map: { minU, maxU, minV, maxV }
local rects = {}
local function Rect(uiMapID)
local cached = rects[uiMapID]
if cached ~= nil then
return cached or nil
end
local r = false
if uiMapID == WORLD_MAP then
r = { 0, 1, 0, 1 }
else
local minX, maxX, minY, maxY = C_Map.GetMapRectOnMap(uiMapID, WORLD_MAP)
if minX and maxX ~= minX and maxY ~= minY then
r = { minX, maxX, minY, maxY }
end
end
rects[uiMapID] = r
return r or nil
end
local function ToWorldMap(m, a, b)
if m == WORLD then
return a, b
end
local home = HOME_MAP[m]
local d, r = home and Direct(home), home and Rect(home)
if not d or not r then
return nil
end
local u, v = d(m, a, b)
if not u then
return nil
end
return r[1] + u * (r[2] - r[1]), r[3] + v * (r[4] - r[3])
end
local function Project(uiMapID, m, a, b)
if m ~= WORLD then
local d = Direct(uiMapID)
local u, v
if d then
u, v = d(m, a, b)
end
if u then
return u, v
end
end
local r = Rect(uiMapID)
if not r then
return nil
end
local wu, wv = ToWorldMap(m, a, b)
if not wu then
return nil
end
return (wu - r[1]) / (r[2] - r[1]), (wv - r[3]) / (r[4] - r[3])
end
ns.Project = Project
local function Inside(u, v)
return u and u >= 0 and u <= 1 and v >= 0 and v <= 1
end
-- Catmull-Rom through flat canvas points, a step every ~12 units
local function Smooth(pts)
local n = #pts / 2
if n < 3 then
return pts
end
local out = {}
local function P(i)
i = math.max(1, math.min(n, i))
return pts[2 * i - 1], pts[2 * i]
end
for i = 1, n - 1 do
local x0, y0 = P(i - 1)
local x1, y1 = P(i)
local x2, y2 = P(i + 1)
local x3, y3 = P(i + 2)
local len = math.sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2)
local steps = math.max(2, math.min(24, math.floor(len / 12)))
for s = 0, steps - 1 do
local t = s / steps
local t2, t3 = t * t, t * t * t
out[#out + 1] = 0.5 * (2 * x1 + (-x0 + x2) * t + (2 * x0 - 5 * x1 + 4 * x2 - x3) * t2 + (-x0 + 3 * x1 - 3 * x2 + x3) * t3)
out[#out + 1] = 0.5 * (2 * y1 + (-y0 + y2) * t + (2 * y0 - 5 * y1 + 4 * y2 - y3) * t2 + (-y0 + 3 * y1 - 3 * y2 + y3) * t3)
end
end
out[#out + 1], out[#out + 2] = pts[#pts - 1], pts[#pts]
return out
end
-- walking from the start of a canvas polyline, where it first leaves the W x H box
local function ExitPoint(pts, W, H)
for i = 1, #pts - 3, 2 do
local ax, ay, bx, by = pts[i], pts[i + 1], pts[i + 2], pts[i + 3]
if bx < 0 or bx > W or by < 0 or by > H then
local t, edge = 1, nil
local function try(tt, e)
if tt >= 0 and tt < t then
t, edge = tt, e
end
end
if bx < 0 then try(ax / (ax - bx), "left") end
if bx > W then try((W - ax) / (bx - ax), "right") end
if by < 0 then try(ay / (ay - by), "top") end
if by > H then try((H - ay) / (by - ay), "bottom") end
return ax + (bx - ax) * t, ay + (by - ay) * t, math.atan2(-(by - ay), bx - ax), edge or "right"
end
end
return nil
end
---------------------------------------------------------------------------
-- Text
---------------------------------------------------------------------------
-- the stops a ship leaving stop i calls at, in order
local function Destinations(route, i)
local out, n = {}, #route.stops
for k = 1, n - 1 do
out[k] = route.stops[(i - 1 + k) % n + 1]
end
return out
end
ns.Destinations = Destinations
local function RouteText(route, i)
local d = Destinations(route, i)
local text = route.noun .. " to " .. d[1][1]
for k = 2, #d do
text = text .. ", then " .. d[k][1]
end
return text
end
ns.RouteText = RouteText
local function Departures(stop, except)
local out = {}
for _, route in ipairs(ns.routes) do
if route ~= except and Visible(route) then
for i, s in ipairs(route.stops) do
if s[2] == stop[2] then
local dx, dy = s[3] - stop[3], s[4] - stop[4]
if dx * dx + dy * dy <= NEARBY * NEARBY then
out[#out + 1] = { route = route, index = i }
end
end
end
end
end
return out
end
-- an edge marker's line for one leg: where it leads, and how to say it
local function ExitText(e)
local route = e.route
local name = route.stops[e.far][1]
if #route.stops > 2 and e.far == e.leg.from then
return route.noun .. " from " .. name
end
return route.noun .. " to " .. name
end
local function FillTooltip(tip, pin)
if pin.kind == "dock" then
local route = pin.route
local c = Color(route)
local stop = route.stops[pin.index]
tip:SetText(stop[1], 1, 1, 1)
tip:AddLine(RouteText(route, pin.index), c[1], c[2], c[3])
if route.faction then
tip:AddLine(route.faction, 0.6, 0.6, 0.6)
end
local others = Departures(stop, route)
if #others > 0 then
tip:AddLine(" ")
tip:AddLine("Also from here:", 0.8, 0.8, 0.8)
for _, o in ipairs(others) do
local oc = Color(o.route)
tip:AddLine(RouteText(o.route, o.index), oc[1], oc[2], oc[3])
end
end
tip:AddLine("Click: show " .. Destinations(route, pin.index)[1][1], 0.5, 0.5, 0.5)
else
local first = pin.exits[1]
local c = Color(first.route)
tip:SetText(ExitText(first), c[1], c[2], c[3])
for k = 2, #pin.exits do
local e = pin.exits[k]
local ec = Color(e.route)
tip:AddLine(ExitText(e), ec[1], ec[2], ec[3])
end
tip:AddLine("Click: show " .. first.route.stops[first.far][1], 0.5, 0.5, 0.5)
end
end
ns.FillTooltip = FillTooltip
-- opens the zone map holding a stop, or its continent
local function ShowStop(map, stop)
local home = HOME_MAP[stop[2]]
if not home then
return
end
local target = home
local u, v = Project(home, stop[2], stop[3], stop[4])
if u then
local info = C_Map.GetMapInfoAtPosition(home, u, v)
if info and info.mapID then
target = info.mapID
end
end
map:SetMapID(target)
end
---------------------------------------------------------------------------
-- Data provider: lines on an overlay, pins for docks and map edges
---------------------------------------------------------------------------
local provider = CreateFromMixins(MapCanvasDataProviderMixin)
ns.provider = provider
function provider:OnAdded(map)
MapCanvasDataProviderMixin.OnAdded(self, map)
self.overlay = CreateFrame("Frame", nil, map:GetCanvas())
self.overlay:SetAllPoints(map:GetCanvas())
self.lines = { BORDER = {}, ARTWORK = {} }
self.used = { BORDER = 0, ARTWORK = 0 }
self.drawn = {}
end
function provider:Line(layer)
local n = self.used[layer] + 1
self.used[layer] = n
local line = self.lines[layer][n]
if not line then
line = self.overlay:CreateLine(nil, layer)
self.lines[layer][n] = line
end
line:Show()
return line
end
function provider:ClearLines()
for layer, list in pairs(self.lines) do
for i = 1, #list do
list[i]:Hide()
end
self.used[layer] = 0
end
end
function provider:Segment(x1, y1, x2, y2, c, alpha, px)
local scale = self:GetMap():GetCanvasScale()
for _, spec in ipairs({ { "BORDER", px + 2, 0, 0, 0, alpha * 0.55 }, { "ARTWORK", px, c[1], c[2], c[3], alpha } }) do
local line = self:Line(spec[1])
line.px = spec[2]
line:SetThickness(spec[2] / scale)
line:SetColorTexture(spec[3], spec[4], spec[5], spec[6])
line:SetStartPoint("TOPLEFT", self.overlay, x1, -y1)
line:SetEndPoint("TOPLEFT", self.overlay, x2, -y2)
end
end
function provider:DrawLines()
self:ClearLines()
local canvas = self:GetMap():GetCanvas()
local W, H = canvas:GetWidth(), canvas:GetHeight()
local hl = self.highlight
for _, item in ipairs(self.drawn) do
local route = item.route
local style = STYLE[route.kind]
local c = Color(route)
local alpha = (hl and hl[route]) and LIT or style.alpha
local px = style.width + ((hl and hl[route]) and 1.5 or 0)
local pts = item.pts
for i = 1, #pts - 3, 2 do
local ax, ay, bx, by = pts[i], pts[i + 1], pts[i + 2], pts[i + 3]
local offscreen = (ax < 0 and bx < 0) or (ax > W and bx > W) or (ay < 0 and by < 0) or (ay > H and by > H)
if not offscreen then
self:Segment(ax, ay, bx, by, c, alpha, px)
end
end
end
end
-- routes: a set of routes to light up, or nil
function provider:SetHighlight(routes)
self.highlight = routes
self:DrawLines()
end
function provider:RemoveAllData()
self:GetMap():RemoveAllPinsByTemplate(TEMPLATE)
self:ClearLines()
self.drawn = {}
self.highlight = nil
end
function provider:RefreshAllData()
self:RemoveAllData()
if not db or db.hidden then
return
end
local map = self:GetMap()
local mapID = map:GetMapID()
if not mapID then
return
end
self.overlay:SetFrameLevel(map:GetPinFrameLevelsManager():GetValidFrameLevel("PIN_FRAME_LEVEL_MAP_HIGHLIGHT"))
local canvas = map:GetCanvas()
local W, H = canvas:GetWidth(), canvas:GetHeight()
if not W or W == 0 then
return
end
local exits = {}
for _, route in ipairs(ns.routes) do
if Visible(route) then
for i, stop in ipairs(route.stops) do
local u, v = Project(mapID, stop[2], stop[3], stop[4])
if Inside(u, v) then
map:AcquirePin(TEMPLATE, "dock", route, i):SetPosition(u, v)
end
end
for _, leg in ipairs(route.legs) do
local pts, ok = {}, true
for j = 1, #leg, 3 do
local u, v = Project(mapID, leg[j], leg[j + 1], leg[j + 2])
if not u then
ok = false
break
end
pts[#pts + 1], pts[#pts + 2] = u * W, v * H
end
if ok and #pts >= 4 then
if leg.smooth then
pts = Smooth(pts)
end
self.drawn[#self.drawn + 1] = { route = route, pts = pts }
-- a leg with one end on this map gets a marker where it leaves
local n = #pts
local startIn = Inside(pts[1] / W, pts[2] / H)
local endIn = Inside(pts[n - 1] / W, pts[n] / H)
if startIn ~= endIn then
local walk, far = pts, leg.to
if endIn then
walk, far = {}, leg.from
for j = n - 1, 1, -2 do
walk[#walk + 1], walk[#walk + 2] = pts[j], pts[j + 1]
end
end
local x, y, angle, edge = ExitPoint(walk, W, H)
if x then
exits[#exits + 1] = { route = route, leg = leg, far = far, x = x, y = y, angle = angle, edge = edge }
end
end
end
end
end
end
-- merge markers that leave at about the same place, then place them inside the border
local groups = {}
for _, e in ipairs(exits) do
local into
for _, g in ipairs(groups) do
local dx, dy = e.x - g[1].x, e.y - g[1].y
if dx * dx + dy * dy <= (EXIT_MERGE * W) ^ 2 then
into = g
break
end
end
if into then
into[#into + 1] = e
else
groups[#groups + 1] = { e }
end
end
local inset = EXIT_INSET
for _, g in ipairs(groups) do
local u = math.max(inset, math.min(1 - inset, g[1].x / W))
local v = math.max(inset, math.min(1 - inset, g[1].y / H))
map:AcquirePin(TEMPLATE, "exit", g):SetPosition(u, v)
end
self:DrawLines()
end
function provider:OnCanvasScaleChanged()
local scale = self:GetMap():GetCanvasScale()
for layer, list in pairs(self.lines) do
for i = 1, self.used[layer] do
list[i]:SetThickness(list[i].px / scale)
end
end
end
function provider:OnCanvasSizeChanged()
self:RefreshAllData()
end
---------------------------------------------------------------------------
-- Pins
---------------------------------------------------------------------------
ShipRoutesPinMixin = CreateFromMixins(MapCanvasPinMixin)
function ShipRoutesPinMixin:OnLoad()
self:UseFrameLevelType("PIN_FRAME_LEVEL_AREA_POI")
self:SetScalingLimits(1, 1.0, 1.25)
local font, size = self.Label:GetFont()
if font then
self.Label:SetFont(font, size, "OUTLINE")
end
end
local LABEL_ANCHOR = {
left = { "LEFT", "RIGHT", 3, 0, "LEFT" },
right = { "RIGHT", "LEFT", -3, 0, "RIGHT" },
top = { "TOP", "BOTTOM", 0, -2, "CENTER" },
bottom = { "BOTTOM", "TOP", 0, 2, "CENTER" },
}
function ShipRoutesPinMixin:OnAcquired(kind, a, b)
self.kind = kind
self.Label:ClearAllPoints()
if kind == "dock" then
self.route, self.index, self.exits = a, b, nil
local c = Color(a)
self:SetSize(20, 20)
self.Ring:SetVertexColor(c[1], c[2], c[3], 1)
self.Glyph:SetTexture(GLYPH[a.kind])
self.Glyph:SetRotation(0)
self.Glyph:SetVertexColor(1, 1, 1, 1)
self.Label:Hide()
else
local first = a[1]
self.route, self.index, self.exits = first.route, first.far, a
local c = Color(first.route)
self:SetSize(16, 16)
self.Ring:SetVertexColor(c[1], c[2], c[3], 1)
self.Glyph:SetTexture(GLYPH.exit)
self.Glyph:SetRotation(first.angle)
self.Glyph:SetVertexColor(c[1], c[2], c[3], 1)
-- one line per destination, in its route's colour
local text, seen = {}, {}
for _, e in ipairs(a) do
local name = e.route.stops[e.far][1]
local ec = Color(e.route)
local key = name .. ec[1]
if not seen[key] then
seen[key] = true
text[#text + 1] = string.format("|cff%02x%02x%02x%s|r", ec[1] * 255, ec[2] * 255, ec[3] * 255, name)
end
end
local anchor = LABEL_ANCHOR[first.edge]
self.Label:SetPoint(anchor[1], self, anchor[2], anchor[3], anchor[4])
self.Label:SetJustifyH(anchor[5])
self.Label:SetText(table.concat(text, "\n"))
self.Label:Show()
end
self.Disc:SetVertexColor(0.06, 0.06, 0.08, 0.9)
self:CheckMouseButtonPassthrough("RightButton")
end
function ShipRoutesPinMixin:OnMouseEnter()
local set = { [self.route] = true }
for _, e in ipairs(self.exits or {}) do
set[e.route] = true
end
provider:SetHighlight(set)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
FillTooltip(GameTooltip, self)
GameTooltip:Show()
end
function ShipRoutesPinMixin:OnMouseLeave()
provider:SetHighlight(nil)
GameTooltip:Hide()
end
function ShipRoutesPinMixin:OnMouseClickAction(button)
if button ~= "LeftButton" then
return
end
local stop
if self.kind == "dock" then
stop = Destinations(self.route, self.index)[1]
else
stop = self.route.stops[self.index]
end
ShowStop(self:GetMap(), stop)
end
---------------------------------------------------------------------------
-- Setup and slash command
---------------------------------------------------------------------------
local function Refresh()
if provider:GetMap() then
provider:RefreshAllData()
end
end
local attached = false
local function Attach()
if not attached and WorldMapFrame and WorldMapFrame.AddDataProvider then
attached = true
WorldMapFrame:AddDataProvider(provider)
end
end
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(_, _, name)
if name == addonName then
ShipRoutesDB = ShipRoutesDB or {}
db = ShipRoutesDB
Attach()
elseif name == "Blizzard_WorldMap" then
Attach()
end
end)
SLASH_SHIPROUTES1 = "/routes"
SlashCmdList.SHIPROUTES = function(msg)
msg = (msg or ""):lower():match("^%s*(.-)%s*$")
if msg == "mine" then
db.mine = true
db.hidden = false
print(PREFIX .. "showing routes your faction can take.")
elseif msg == "all" then
db.mine = false
db.hidden = false
print(PREFIX .. "showing all routes.")
elseif msg == "" then
db.hidden = not db.hidden
print(PREFIX .. (db.hidden and "hidden." or "shown."))
else
print(PREFIX .. "/routes toggles the map lines, /routes mine shows only your faction's, /routes all shows every route.")
end
Refresh()
end