Compare commits

..
47 Commits
Author SHA1 Message Date
anth64 cbbd87a862 chore: bump version to 0.7.0 2026-11-05 21:10:03 +01:00
anth64 1c1ad9bfdd feat: merge overlapping buffer volumes in the visualizer 2026-11-05 21:05:06 +01:00
anth64 6f30fc626c chore: remove claimlinkvisualizer reference. 2026-08-26 22:03:32 +02:00
anth64 05ff998287 chore: bump version to 0.6.0 2026-08-26 21:29:44 +02:00
anth64 cac8e590d3 fix: use custommessage- sentinel for client-side buffer-zone deny message 2026-08-26 21:25:30 +02:00
anth64 62c94bc775 feat: push-based buffer/permission sync for the client-side TestBlockAccess pre-check
The server now pushes buffer and permission state to clients continuously: a full sync when a player joins, and an incremental delta on every registry mutation, mirroring vanilla's own land claim sync model. ClaimLinkBufferIndex is now instantiable, so the client and server each get their own region-indexed lookup built from the same algorithm.
2026-08-26 00:01:58 +02:00
anth64 b14eb5c538 feat: convert to Universal mod, merge ClaimLinkVisualizer in, keep CommandHook as a true soft dependency via runtime proxy 2026-08-25 23:14:58 +02:00
anth64 8f0e4bd687 chore: bump version to 0.5.1 2026-08-24 19:26:59 +02:00
anth64 725f450da7 fix: resolve offline members' names in info output instead of showing raw uid 2026-08-24 19:26:53 +02:00
anth64 8cedbc841b docs: write full README with command reference and buffer explanation 2026-08-24 17:49:23 +02:00
anth64 b93abfe899 style: apply formatter to buffer/registry/command/network files 2026-08-24 17:49:18 +02:00
anth64 a03219c114 feat: add buffer-zone permission grants via allow/allowgroup/deny/denygroup, bump to 0.5.0 2026-08-09 20:05:22 +02:00
anth64 095b826178 feat: deny non-members from modifying claim link buffer zones, bump to 0.4.0 2026-08-09 20:05:15 +02:00
anth64 636a7dee98 feat: filter buffer data sent to visualizer clients by view distance 2026-07-31 07:38:56 +02:00
anth64 1e4400555c chore: bump version to 0.2.0 2026-07-31 07:18:56 +02:00
anth64 0dfcc5396a feat: add client-visualizer network endpoint for buffer geometry 2026-07-30 23:14:06 +02:00
anth64 c110ee2604 fix: normalize claim geometry before growing buffer (raw start/end marks aren't min/max ordered) 2026-07-27 07:40:12 +02:00
anth64 baf3ccbd93 feat: enforce buffer-zone non-overlap on /claimlink link 2026-07-26 15:30:35 +02:00
anth64 3cf6db1d2a fix: clear PendingLoads on /land claim new to match vanilla's unconditional reset 2026-07-26 14:36:37 +02:00
anth64 12219e6ef5 feat: add ClaimLinkConfig with configurable buffer size 2026-07-26 12:07:46 +02:00
anth64 0e0e4e0f74 chore: bump version to 0.1.0 2026-07-26 11:28:08 +02:00
anth64 154e7b7848 chore: bump version to 0.0.7 2026-07-26 11:25:27 +02:00
anth64 9e37ec11cf feat: implement admin delete/unlink/kick, fix admin unlink claim arg type 2026-07-26 11:23:21 +02:00
anth64 4d98a115ed feat: infer claim link group from chat context when omitted; drop redundant admin info 2026-07-26 11:21:13 +02:00
anth64 99238c4744 feat: hook group leave/kick to proactively cancel pending actions with a reason 2026-07-26 10:33:46 +02:00
anth64 1c079b7e44 fix: cancel pending actions on group disband even if not yet a claim link 2026-07-26 09:08:08 +02:00
anth64 b7ca9fa53b fix: track groupId per pending action for precise cleanup on delete/disband; split group hook into its own listener; self-heal orphaned registry entries in list 2026-07-26 08:51:54 +02:00
anth64 c55787ce40 feat: react to /group confirmdisband and recheck live membership on link confirm 2026-07-23 07:57:39 +02:00
anth64 b10d3a0f55 fix: cancel old owner's pending action on ownership transfer 2026-07-21 20:29:32 +02:00
anth64 b5ceba442a fix: cancel kicked player's pending action to stop stale link re-add 2026-07-21 20:25:21 +02:00
anth64 d248b772dc fix: split adminfree (by player name) from adminfreehere (by position) 2026-07-21 19:36:48 +02:00
anth64 c8fc86069b feat: gate claim link info detail by membership/admin, count members with no claims 2026-07-20 23:36:03 +02:00
anth64 2e4cc25b20 fix: guard claim-link entries against stale indices and dead groups 2026-07-20 23:28:37 +02:00
anth64 fc7e601f5b refactor: expose TryResolveOwnedClaim for future external mod consumption 2026-07-19 20:43:05 +02:00
anth64 a2e4a68f9e refactor: rebuild claim link registry around live index tracking, drop ClaimLink type 2026-07-19 20:31:10 +02:00
anth64 741d283f38 refactor: clear pending actions in claim link command instead of land claim listener 2026-07-19 10:49:11 +02:00
anth64 9fcf6f1da5 fix: resolve claim on load 2026-07-19 10:48:41 +02:00
anth64 f699cd6d54 chore: log adminfree phase and claims found at caller position 2026-07-18 11:55:24 +02:00
anth64 94b6723456 feat: sanity-check claim save/free against tracked ordering state 2026-07-18 11:47:52 +02:00
anth64 de2026d239 refactor: merge land command Before/After into shared phase-aware dispatch 2026-07-18 11:46:32 +02:00
anth64 fffc046126 refactor: normalize claim link membership into flat entry storage 2026-07-15 18:46:52 +02:00
anth64 eaa79f8f52 fix: transferownership correctly sets owner level and demotes old owner to op, works for offline players, notifies members 2026-07-14 22:52:32 +02:00
anth64 1c0a5f88a1 refactor: remove "claims" text from list of claims in FormatInfo. 2026-07-14 22:21:07 +02:00
anth64 d4ef3eba06 fix: show player name in require player 2026-07-14 22:17:00 +02:00
anth64 32dbd4ad91 feat: implement claimlink admin transferownership 2026-07-13 07:56:37 +02:00
anth64 41a2f1a09d feat: implement claimlink transferownership with debug logging 2026-07-13 07:50:50 +02:00
anth64 bee6b6434a fix: RequireOpOrOwner allows OwnerUID holder regardless of membership level 2026-07-13 07:40:24 +02:00
20 changed files with 2839 additions and 368 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.7.0] - 2026-11-05
### Changed
- Buffer zone visualization now merges overlapping buffer volumes of a claim link into disjoint boxes, so overlapping buffers no longer draw on top of each other.
+25 -5
View File
@@ -1,24 +1,44 @@
using System.Collections.Generic;
using ProtoBuf;
using Vintagestory.API.Common;
namespace ClaimLink;
[ProtoContract]
public class ClaimLinkMember
public class ClaimLinkSaveData
{
[ProtoMember(1)]
public string OwnerPlayerUid = "";
public List<int> Links = new();
[ProtoMember(2)]
public List<int> LocalClaimIndices = new();
public List<ClaimLinkEntrySaveData> Entries = new();
[ProtoMember(3)]
public List<ClaimLinkPermissionSaveData> Permissions = new();
}
[ProtoContract]
public class ClaimLink
public class ClaimLinkPermissionSaveData
{
[ProtoMember(1)]
public int GroupId;
[ProtoMember(2)]
public List<ClaimLinkMember> Members = new();
public Dictionary<string, EnumBlockAccessFlags> PermittedPlayerUids = new();
[ProtoMember(3)]
public Dictionary<int, EnumBlockAccessFlags> PermittedPlayerGroupIds = new();
}
[ProtoContract]
public class ClaimLinkEntrySaveData
{
[ProtoMember(1)]
public string OwnerPlayerUid = "";
[ProtoMember(2)]
public int GroupId;
[ProtoMember(3)]
public List<int> ClaimIndicies = new();
}
+6
View File
@@ -34,4 +34,10 @@
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="assets\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
+139
View File
@@ -0,0 +1,139 @@
using System.Collections.Generic;
using Vintagestory.API.Common;
using Vintagestory.API.MathTools;
namespace ClaimLink;
internal static class ClaimLinkBuffer
{
internal static List<Cuboidi> GetBuffer(int groupId)
{
List<Cuboidi> cuboids = new();
foreach (string uid in ClaimLinkModSystem.Registry.MemberUidsForGroup(groupId))
{
foreach (
int claimIndex in ClaimLinkModSystem.Registry.ClaimsForPlayerInGroup(uid, groupId)
)
{
if (
!ClaimLinkModSystem.TryResolveOwnedClaim(uid, claimIndex, out LandClaim? claim)
|| claim == null
)
continue;
foreach (Cuboidi area in claim.Areas)
cuboids.Add(GrowOne(area));
}
}
return cuboids;
}
internal static bool TryFindOverlappingClaimLink(
List<Cuboidi> areas,
ISet<int>? excludeGroupIds,
out int violatingGroupId
)
{
foreach (int groupId in ClaimLinkModSystem.Registry.All)
{
if (excludeGroupIds != null && excludeGroupIds.Contains(groupId))
continue;
foreach (Cuboidi bufferCuboid in GetBuffer(groupId))
foreach (Cuboidi area in areas)
if (area.Intersects(bufferCuboid))
{
violatingGroupId = groupId;
return true;
}
}
violatingGroupId = -1;
return false;
}
internal static bool TryFindOverlappingClaim(
List<Cuboidi> areas,
string excludeOwnerUid,
ISet<int>? excludeGroupIds,
out LandClaim? violatingClaim
)
{
HashSet<LandClaim> excludedClaims = new();
if (excludeGroupIds != null)
foreach (int groupId in excludeGroupIds)
foreach (string uid in ClaimLinkModSystem.Registry.MemberUidsForGroup(groupId))
foreach (
int claimIndex in ClaimLinkModSystem.Registry.ClaimsForPlayerInGroup(uid, groupId)
)
if (
ClaimLinkModSystem.TryResolveOwnedClaim(
uid,
claimIndex,
out LandClaim? excludedClaim
)
&& excludedClaim != null
)
excludedClaims.Add(excludedClaim);
foreach (LandClaim claim in ClaimLinkModSystem.LandClaimAPI.All)
{
if (claim.OwnedByPlayerUid == excludeOwnerUid)
continue;
if (excludedClaims.Contains(claim))
continue;
foreach (Cuboidi claimArea in claim.Areas)
foreach (Cuboidi area in areas)
if (area.Intersects(claimArea))
{
violatingClaim = claim;
return true;
}
}
violatingClaim = null;
return false;
}
internal static ISet<int> MemberClaimLinkIds(string uid)
{
HashSet<int> groupIds = new();
var memberships = ClaimLinkModSystem
.PlayerData.GetPlayerDataByUid(uid)
?.PlayerGroupMemberships;
if (memberships == null)
return groupIds;
foreach (int groupId in memberships.Keys)
if (ClaimLinkModSystem.Registry.Exists(groupId))
groupIds.Add(groupId);
return groupIds;
}
internal static List<Cuboidi> GrowAreas(List<Cuboidi> areas)
{
List<Cuboidi> grown = new();
foreach (Cuboidi area in areas)
grown.Add(GrowOne(area));
return grown;
}
private static Cuboidi GrowOne(Cuboidi area)
{
Cuboidi normalized = new Cuboidi(
area.MinX,
area.MinY,
area.MinZ,
area.MaxX,
area.MaxY,
area.MaxZ
);
int bufferSize = ClaimLinkModSystem.Config.BufferSize;
return normalized.GrowBy(bufferSize, bufferSize, bufferSize);
}
}
+70
View File
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using Vintagestory.API.MathTools;
namespace ClaimLink;
internal class ClaimLinkBufferIndex
{
private readonly Func<int, int, long> regionIndex;
private readonly Dictionary<long, HashSet<int>> groupIdsByRegion = new();
private readonly Dictionary<int, List<Cuboidi>> buffersByGroupId = new();
private int regionSize;
internal ClaimLinkBufferIndex(Func<int, int, long> regionIndex)
{
this.regionIndex = regionIndex;
}
internal void Rebuild(IEnumerable<(int groupId, List<Cuboidi> buffers)> source, int regionSize)
{
this.regionSize = regionSize;
groupIdsByRegion.Clear();
buffersByGroupId.Clear();
if (regionSize <= 0)
return;
foreach ((int groupId, List<Cuboidi> buffers) in source)
{
buffersByGroupId[groupId] = buffers;
HashSet<long> regionKeys = new();
foreach (Cuboidi buffer in buffers)
{
int minRegionX = buffer.MinX / regionSize;
int maxRegionX = buffer.MaxX / regionSize;
int minRegionZ = buffer.MinZ / regionSize;
int maxRegionZ = buffer.MaxZ / regionSize;
for (int rx = minRegionX; rx <= maxRegionX; rx++)
for (int rz = minRegionZ; rz <= maxRegionZ; rz++)
regionKeys.Add(regionIndex(rx, rz));
}
foreach (long regionKey in regionKeys)
{
if (!groupIdsByRegion.TryGetValue(regionKey, out HashSet<int>? groupIds))
groupIdsByRegion[regionKey] = groupIds = new();
groupIds.Add(groupId);
}
}
}
internal IEnumerable<int> CandidateGroupIds(BlockPos pos)
{
if (regionSize <= 0)
return Array.Empty<int>();
long regionKey = regionIndex(pos.X / regionSize, pos.Z / regionSize);
return groupIdsByRegion.TryGetValue(regionKey, out HashSet<int>? groupIds)
? groupIds
: Array.Empty<int>();
}
internal List<Cuboidi> CachedBuffer(int groupId) =>
buffersByGroupId.TryGetValue(groupId, out List<Cuboidi>? buffers)
? buffers
: new List<Cuboidi>();
}
+81
View File
@@ -0,0 +1,81 @@
using Vintagestory.API.Common;
using Vintagestory.API.MathTools;
using Vintagestory.API.Server;
namespace ClaimLink;
internal static class ClaimLinkBufferProtection
{
internal static void Register(ICoreServerAPI api)
{
api.Event.CanPlaceOrBreakBlock += OnCanPlaceOrBreakBlock;
api.Event.CanUseBlock += OnCanUseBlock;
}
private static bool OnCanUseBlock(IServerPlayer byPlayer, BlockSelection blockSel) =>
IsAllowed(byPlayer, blockSel.Position, EnumBlockAccessFlags.Use);
private static bool OnCanPlaceOrBreakBlock(
IServerPlayer byPlayer,
BlockSelection blockSel,
out string claimant
)
{
bool allowed = IsAllowed(byPlayer, blockSel.Position, EnumBlockAccessFlags.BuildOrBreak);
claimant = allowed ? null! : "custommessage-claimlink-buffer-zone";
return allowed;
}
private static bool IsAllowed(
IServerPlayer byPlayer,
BlockPos pos,
EnumBlockAccessFlags accessFlag
)
{
bool allowed = true;
foreach (int groupId in ClaimLinkModSystem.BufferIndex.CandidateGroupIds(pos))
{
if (IsMember(byPlayer, groupId))
continue;
foreach (Cuboidi buffer in ClaimLinkModSystem.BufferIndex.CachedBuffer(groupId))
if (
buffer.Contains(pos)
&& !ClaimLinkModSystem.Registry.HasPermission(groupId, byPlayer, accessFlag)
)
allowed = false;
}
return allowed || HasClaimAccess(byPlayer, pos, accessFlag);
}
private static bool IsMember(IServerPlayer player, int groupId)
{
foreach (PlayerGroupMembership membership in player.Groups)
if (membership.GroupUid == groupId)
return true;
return false;
}
private static bool HasClaimAccess(
IServerPlayer player,
BlockPos pos,
EnumBlockAccessFlags accessFlag
)
{
LandClaim[]? claims = ClaimLinkModSystem.LandClaimAPI.Get(pos);
if (claims == null)
return false;
foreach (LandClaim claim in claims)
{
if (claim.TestPlayerAccess(player, accessFlag) != EnumPlayerAccessResult.Denied)
return true;
if (accessFlag == EnumBlockAccessFlags.Use && claim.AllowUseEveryone)
return true;
}
return false;
}
}
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
namespace ClaimLink;
internal class ClaimLinkConfig
{
public int BufferSize = 16;
}
+122 -26
View File
@@ -1,5 +1,5 @@
using System.Collections.Generic;
using CommandHook;
using Vintagestory.API.Client;
using Vintagestory.API.Common;
using Vintagestory.API.Server;
@@ -12,53 +12,149 @@ public class ClaimLinkModSystem : ModSystem
internal static ClaimLinkRegistry Registry = null!;
internal static IGroupManager Groups = null!;
internal static IWorldAccessor World = null!;
internal ClaimLinkCommandListener? cmdListener;
public override bool ShouldLoad(EnumAppSide forSide) => forSide == EnumAppSide.Server;
internal static IWorldManagerAPI WorldManager = null!;
internal static IPlayerDataManager PlayerData = null!;
internal static ClaimLinkConfig Config = null!;
internal static ClaimLinkBufferIndex BufferIndex = null!;
private object? cmdListenerProxy;
private object? groupCmdListenerProxy;
public override void StartServerSide(ICoreServerAPI api)
{
LandClaimAPI = api.World.Claims;
Logger = api.Logger;
Registry = new ClaimLinkRegistry(api.WorldManager.SaveGame);
Groups = api.Groups;
World = api.World;
WorldManager = api.WorldManager;
Groups = api.Groups;
Logger = api.Logger;
PlayerData = api.PlayerData;
Config = api.LoadModConfig<ClaimLinkConfig>("claimlink.json") ?? new ClaimLinkConfig();
api.StoreModConfig(Config, "claimlink.json");
Registry = new ClaimLinkRegistry(api.WorldManager.SaveGame);
BufferIndex = new ClaimLinkBufferIndex(WorldManager.MapRegionIndex2D);
RebuildBufferIndex();
api.Event.SaveGameLoaded += RebuildBufferIndex;
cmdListener = new ClaimLinkCommandListener();
CommandHookModSystem.Register(cmdListener);
ClaimLinkChatCommand.Register(api);
api.Event.PlayerDisconnect += ClaimLinkCommandListener.OnPlayerDisconnect;
if (api.ModLoader.IsModEnabled("commandhook"))
{
api.Event.SaveGameLoaded += () => RegisterCommandHooks(api);
}
else
{
api.Logger.Fatal(
"ClaimLink requires the CommandHook mod on the server for /land and /group integration. That integration is disabled; /claimlink commands and buffer protection still work."
);
}
ClaimLinkChatCommand.Register(api);
ClaimLinkVisualizerNetwork.Start(api);
ClaimLinkBufferProtection.Register(api);
api.Event.PlayerDisconnect += ClaimLinkChatCommand.OnPlayerDisconnect;
}
private void RegisterCommandHooks(ICoreServerAPI api)
{
CommandListener cmdListener = new();
CommandHook.ICommandHookListener cmdProxy = CommandHookListenerProxy.Create(
cmdListener.ModId,
cmdListener.Commands,
cmdListener.Before,
cmdListener.After
);
CommandHook.CommandHookModSystem.Register(cmdProxy);
cmdListenerProxy = cmdProxy;
GroupCommandListener groupListener = new();
CommandHook.ICommandHookListener groupProxy = CommandHookListenerProxy.Create(
groupListener.ModId,
groupListener.Commands,
groupListener.Before,
groupListener.After
);
CommandHook.CommandHookModSystem.Register(groupProxy);
groupCmdListenerProxy = groupProxy;
api.Event.PlayerDisconnect += CommandListener.OnPlayerDisconnect;
api.Event.PlayerDisconnect += GroupCommandListener.OnPlayerDisconnect;
}
internal static void RebuildBufferIndex()
{
List<(int groupId, List<Vintagestory.API.MathTools.Cuboidi> buffers)> source = new();
foreach (int groupId in Registry.All)
source.Add((groupId, ClaimLinkBuffer.GetBuffer(groupId)));
BufferIndex.Rebuild(source, WorldManager.RegionSize);
}
public override void StartClientSide(ICoreClientAPI api) => ClaimLinkVisualizerClient.Start(api);
public override void Dispose()
{
if (cmdListener != null)
CommandHookModSystem.Unregister(cmdListener);
if (cmdListenerProxy != null || groupCmdListenerProxy != null)
UnregisterCommandHooks();
}
internal static bool TryResolveOwnedClaim(string ownerPlayerUid, int localIndex, out int globalIndex, out LandClaim? claim)
private void UnregisterCommandHooks()
{
globalIndex = -1;
claim = null;
if (cmdListenerProxy != null)
CommandHook.CommandHookModSystem.Unregister(
(CommandHook.ICommandHookListener)cmdListenerProxy
);
if (groupCmdListenerProxy != null)
CommandHook.CommandHookModSystem.Unregister(
(CommandHook.ICommandHookListener)groupCmdListenerProxy
);
}
List<LandClaim> claims = LandClaimAPI.All;
int count = 0;
for (int i = 0; i < claims.Count; ++i)
private static IEnumerable<(int claimIndex, LandClaim claim)> EnumerateOwnedClaims(
string ownerPlayerUid
)
{
if (claims[i].OwnedByPlayerUid != ownerPlayerUid)
int index = 0;
foreach (LandClaim c in LandClaimAPI.All)
{
if (c.OwnedByPlayerUid != ownerPlayerUid)
continue;
if (count == localIndex)
yield return (index, c);
index++;
}
}
public static bool TryResolveOwnedClaim(
string ownerPlayerUid,
int claimIndex,
out LandClaim? claim
)
{
globalIndex = i;
claim = claims[i];
foreach ((int index, LandClaim c) in EnumerateOwnedClaims(ownerPlayerUid))
{
if (index == claimIndex)
{
claim = c;
return true;
}
count++;
}
claim = null;
return false;
}
internal static bool TryResolveClaimIndex(
string ownerPlayerUid,
LandClaim target,
out int claimIndex
)
{
foreach ((int index, LandClaim c) in EnumerateOwnedClaims(ownerPlayerUid))
{
if (ReferenceEquals(c, target))
{
claimIndex = index;
return true;
}
}
claimIndex = -1;
return false;
}
}
+311 -31
View File
@@ -1,65 +1,345 @@
using System.Collections.Generic;
using ProtoBuf;
using Vintagestory.API.Common;
using Vintagestory.API.Server;
namespace ClaimLink;
[ProtoContract]
public class ClaimLinkData
{
[ProtoMember(1)]
public List<ClaimLink> Links = new();
}
public class ClaimLinkRegistry
{
private const string SaveKey = "claimlink:links";
private const string SaveKey = "claimlink:claimlinkdata";
private static readonly Dictionary<string, EnumBlockAccessFlags> EmptyPlayerFlags = new();
private static readonly Dictionary<int, EnumBlockAccessFlags> EmptyGroupFlags = new();
private readonly ISaveGame saveGame;
private readonly Dictionary<int, ClaimLink> byGroupId = new();
private readonly List<int> claimLinks = new();
private readonly Dictionary<string, Dictionary<int, List<int>>> entries = new();
private readonly Dictionary<int, Dictionary<string, EnumBlockAccessFlags>> permittedPlayerUids =
new();
private readonly Dictionary<
int,
Dictionary<int, EnumBlockAccessFlags>
> permittedPlayerGroupIds = new();
public ClaimLinkRegistry(ISaveGame saveGame)
{
this.saveGame = saveGame;
ClaimLinkData? data = saveGame.GetData<ClaimLinkData?>(SaveKey, null);
ClaimLinkSaveData? data = saveGame.GetData<ClaimLinkSaveData?>(SaveKey, null);
if (data == null)
return;
foreach (ClaimLink link in data.Links)
byGroupId[link.GroupId] = link;
claimLinks.AddRange(data.Links);
foreach (var entry in data.Entries)
{
if (!entries.ContainsKey(entry.OwnerPlayerUid))
entries[entry.OwnerPlayerUid] = new Dictionary<int, List<int>>();
entries[entry.OwnerPlayerUid][entry.GroupId] = new(entry.ClaimIndicies);
}
public ClaimLink? Get(int groupId) => byGroupId.TryGetValue(groupId, out ClaimLink? link) ? link : null;
public IReadOnlyCollection<ClaimLink> All => byGroupId.Values;
public void Add(ClaimLink link)
foreach (var permission in data.Permissions)
{
byGroupId[link.GroupId] = link;
Save();
if (permission.PermittedPlayerUids.Count > 0)
permittedPlayerUids[permission.GroupId] = new(permission.PermittedPlayerUids);
if (permission.PermittedPlayerGroupIds.Count > 0)
permittedPlayerGroupIds[permission.GroupId] = new(
permission.PermittedPlayerGroupIds
);
}
}
public IReadOnlyList<int> All => claimLinks;
public bool Exists(int groupId) => claimLinks.Contains(groupId);
public void Add(int groupId)
{
claimLinks.Add(groupId);
Save(new[] { groupId });
}
public void Remove(int groupId)
{
byGroupId.Remove(groupId);
Save();
claimLinks.Remove(groupId);
foreach (var groups in entries.Values)
groups.Remove(groupId);
permittedPlayerUids.Remove(groupId);
permittedPlayerGroupIds.Remove(groupId);
Prune();
Save(new[] { groupId });
}
public bool IsClaimLinked(string ownerPlayerUid, int localIndex) => FindLinkContaining(ownerPlayerUid, localIndex) != null;
public ClaimLink? FindLinkContaining(string ownerPlayerUid, int localIndex)
public void GrantPlayer(int groupId, string uid, EnumBlockAccessFlags flags)
{
foreach (ClaimLink link in byGroupId.Values)
foreach (ClaimLinkMember member in link.Members)
if (member.OwnerPlayerUid == ownerPlayerUid && member.LocalClaimIndices.Contains(localIndex))
return link;
if (!permittedPlayerUids.TryGetValue(groupId, out var uids))
permittedPlayerUids[groupId] = uids = new();
uids[uid] = flags;
Save(new[] { groupId });
}
public bool RevokePlayer(int groupId, string uid)
{
bool removed = permittedPlayerUids.TryGetValue(groupId, out var uids) && uids.Remove(uid);
if (!removed)
return false;
if (uids!.Count == 0)
permittedPlayerUids.Remove(groupId);
Save(new[] { groupId });
return true;
}
public void GrantGroup(int groupId, int targetGroupId, EnumBlockAccessFlags flags)
{
if (!permittedPlayerGroupIds.TryGetValue(groupId, out var groups))
permittedPlayerGroupIds[groupId] = groups = new();
groups[targetGroupId] = flags;
Save(new[] { groupId });
}
public bool RevokeGroup(int groupId, int targetGroupId)
{
bool removed =
permittedPlayerGroupIds.TryGetValue(groupId, out var groups)
&& groups.Remove(targetGroupId);
if (!removed)
return false;
if (groups!.Count == 0)
permittedPlayerGroupIds.Remove(groupId);
Save(new[] { groupId });
return true;
}
public bool HasPermission(int groupId, IPlayer player, EnumBlockAccessFlags accessFlag)
{
if (
permittedPlayerUids.TryGetValue(groupId, out var uids)
&& uids.TryGetValue(player.PlayerUID, out EnumBlockAccessFlags flags)
&& (flags & accessFlag) != 0
)
return true;
if (permittedPlayerGroupIds.TryGetValue(groupId, out var groups))
foreach (PlayerGroupMembership membership in player.Groups)
if (groups.TryGetValue(membership.GroupUid, out flags) && (flags & accessFlag) != 0)
return true;
return false;
}
public IReadOnlyDictionary<string, EnumBlockAccessFlags> PermittedPlayersForGroup(
int groupId
) => permittedPlayerUids.TryGetValue(groupId, out var uids) ? uids : EmptyPlayerFlags;
public IReadOnlyDictionary<int, EnumBlockAccessFlags> PermittedGroupsForGroup(int groupId) =>
permittedPlayerGroupIds.TryGetValue(groupId, out var groups) ? groups : EmptyGroupFlags;
public void RemoveGroupFromAllPermissions(int targetGroupId)
{
List<int>? changedGroupIds = null;
foreach (var (groupId, groups) in permittedPlayerGroupIds)
if (groups.Remove(targetGroupId))
(changedGroupIds ??= new()).Add(groupId);
if (changedGroupIds == null)
return;
List<int>? emptyGroupIds = null;
foreach (var (groupId, groups) in permittedPlayerGroupIds)
if (groups.Count == 0)
(emptyGroupIds ??= new()).Add(groupId);
if (emptyGroupIds != null)
foreach (int groupId in emptyGroupIds)
permittedPlayerGroupIds.Remove(groupId);
Save(changedGroupIds);
}
public bool IsClaimLinked(string uid, int claimIndex) =>
FindGroupContaining(uid, claimIndex) != null;
public int? FindGroupContaining(string uid, int claimIndex)
{
if (!entries.TryGetValue(uid, out var groups))
return null;
foreach (var (groupId, claims) in groups)
if (claims.Contains(claimIndex))
return groupId;
return null;
}
public void Save()
public bool AddEntry(string uid, int groupId, int claimIndex)
{
saveGame.StoreData(SaveKey, new ClaimLinkData { Links = new List<ClaimLink>(byGroupId.Values) });
if (CommandListener.PendingLoads.ContainsKey(uid))
return false;
if (!Exists(groupId))
return false;
if (!entries.TryGetValue(uid, out var groups))
entries[uid] = groups = new();
if (!groups.TryGetValue(groupId, out var claims))
groups[groupId] = claims = new();
claims.Add(claimIndex);
Save(new[] { groupId });
return true;
}
public void RemoveEntry(string uid, int groupId, int claimIndex)
{
if (entries.TryGetValue(uid, out var groups) && groups.TryGetValue(groupId, out var claims))
claims.Remove(claimIndex);
Prune();
Save(new[] { groupId });
}
public void ClaimRemoved(string uid, int removedIndex)
{
if (!entries.TryGetValue(uid, out var groups))
return;
int[] affectedGroupIds = new List<int>(groups.Keys).ToArray();
foreach (var claims in groups.Values)
{
claims.Remove(removedIndex);
for (int i = 0; i < claims.Count; i++)
if (claims[i] > removedIndex)
claims[i]--;
}
Prune();
Save(affectedGroupIds);
}
public void ClaimSaved(string uid, int claimIndex)
{
if (!entries.TryGetValue(uid, out var groups))
return;
int[] affectedGroupIds = new List<int>(groups.Keys).ToArray();
int count = 0;
foreach (Vintagestory.API.Common.LandClaim c in ClaimLinkModSystem.LandClaimAPI.All)
if (c.OwnedByPlayerUid == uid)
count++;
int newIndex = count - 1;
foreach (var claims in groups.Values)
{
int i = claims.IndexOf(claimIndex);
for (int j = 0; j < claims.Count; j++)
if (j != i && claims[j] > claimIndex)
claims[j]--;
if (i >= 0)
claims[i] = newIndex;
}
Save(affectedGroupIds);
}
public bool HasAnyEntry(string uid, int groupId) =>
entries.TryGetValue(uid, out var groups)
&& groups.TryGetValue(groupId, out var claims)
&& claims.Count > 0;
public void RemoveAllForPlayerInGroup(string uid, int groupId)
{
if (entries.TryGetValue(uid, out var groups))
groups.Remove(groupId);
Prune();
Save(new[] { groupId });
}
public void ClearAllForPlayer(string uid)
{
int[] affectedGroupIds = entries.TryGetValue(uid, out var groups)
? new List<int>(groups.Keys).ToArray()
: System.Array.Empty<int>();
entries.Remove(uid);
Save(affectedGroupIds);
}
public IEnumerable<string> MemberUidsForGroup(int groupId)
{
foreach (var (uid, groups) in entries)
if (groups.ContainsKey(groupId))
yield return uid;
}
public int MemberCountForGroup(int groupId)
{
int count = 0;
foreach (var uid in MemberUidsForGroup(groupId))
count++;
return count;
}
public IReadOnlyList<int> ClaimsForPlayerInGroup(string uid, int groupId) =>
entries.TryGetValue(uid, out var groups) && groups.TryGetValue(groupId, out var claims)
? claims
: System.Array.Empty<int>();
private void Prune()
{
List<string>? empty = null;
foreach (var (uid, groups) in entries)
if (groups.Count == 0)
(empty ??= new()).Add(uid);
if (empty != null)
foreach (var uid in empty)
entries.Remove(uid);
}
private void Save(IReadOnlyCollection<int> affectedGroupIds)
{
var entryList = new List<ClaimLinkEntrySaveData>();
foreach (var (uid, groups) in entries)
foreach (var (groupId, claims) in groups)
entryList.Add(
new ClaimLinkEntrySaveData
{
OwnerPlayerUid = uid,
GroupId = groupId,
ClaimIndicies = new(claims),
}
);
var permissionGroupIds = new HashSet<int>();
foreach (int groupId in permittedPlayerUids.Keys)
permissionGroupIds.Add(groupId);
foreach (int groupId in permittedPlayerGroupIds.Keys)
permissionGroupIds.Add(groupId);
var permissionList = new List<ClaimLinkPermissionSaveData>();
foreach (int groupId in permissionGroupIds)
{
permittedPlayerUids.TryGetValue(groupId, out var uids);
permittedPlayerGroupIds.TryGetValue(groupId, out var groups);
permissionList.Add(
new ClaimLinkPermissionSaveData
{
GroupId = groupId,
PermittedPlayerUids = uids != null ? new(uids) : new(),
PermittedPlayerGroupIds = groups != null ? new(groups) : new(),
}
);
}
saveGame.StoreData(
SaveKey,
new ClaimLinkSaveData
{
Links = claimLinks,
Entries = entryList,
Permissions = permissionList,
}
);
ClaimLinkModSystem.RebuildBufferIndex();
ClaimLinkVisualizerNetwork.BroadcastDelta(affectedGroupIds);
}
}
+207
View File
@@ -0,0 +1,207 @@
using System.Collections.Generic;
using Vintagestory.API.Client;
using Vintagestory.API.Common;
using Vintagestory.API.MathTools;
namespace ClaimLink;
internal static class ClaimLinkVisualizerClient
{
private const int HighlightSlotId = 8341;
private const int ClientRegionSize = 512;
private static ICoreClientAPI capi = null!;
private static bool visible;
private static ClaimLinkVisualizerConfig config = null!;
private static IClientNetworkChannel channel = null!;
private static readonly Dictionary<int, ClaimLinkBufferEntryDto> knownEntries = new();
private static readonly ClaimLinkBufferIndex bufferIndex = new(ClientRegionKey);
internal static void Start(ICoreClientAPI api)
{
capi = api;
config = api.LoadModConfig<ClaimLinkVisualizerConfig>("claimlinkvisualizer.json") ?? new ClaimLinkVisualizerConfig();
api.StoreModConfig(config, "claimlinkvisualizer.json");
channel = api.Network.RegisterChannel(ClaimLinkVisualizerNetwork.ChannelName)
.RegisterMessageType<ClaimLinkBufferResponse>()
.SetMessageHandler<ClaimLinkBufferResponse>(OnBuffersPushed);
api.Input.RegisterHotKey(
"claimlinkvisualizertoggle",
"Toggle ClaimLink buffer visualization",
GlKeys.R,
HotkeyType.CharacterControls,
ctrlPressed: true
);
api.Input.SetHotKeyHandler("claimlinkvisualizertoggle", OnToggle);
api.Event.TestBlockAccess += OnTestBlockAccess;
}
private static long ClientRegionKey(int regionX, int regionZ) => ((long)regionX << 32) | (uint)regionZ;
private static bool OnToggle(KeyCombination comb)
{
visible = !visible;
if (visible)
RenderHighlights();
else
Clear();
return true;
}
private static void OnBuffersPushed(ClaimLinkBufferResponse response)
{
if (response.IsFullSync)
knownEntries.Clear();
foreach (ClaimLinkBufferEntryDto entry in response.Entries)
{
if (entry.Cuboids.Count == 0)
knownEntries.Remove(entry.GroupId);
else
knownEntries[entry.GroupId] = entry;
}
RebuildIndex();
if (visible)
RenderHighlights();
}
private static void RebuildIndex()
{
List<(int groupId, List<Cuboidi> buffers)> source = new();
foreach ((int groupId, ClaimLinkBufferEntryDto entry) in knownEntries)
{
List<Cuboidi> cuboids = new();
foreach (ClaimLinkBufferCuboidDto c in entry.Cuboids)
cuboids.Add(new Cuboidi(c.MinX, c.MinY, c.MinZ, c.MaxX, c.MaxY, c.MaxZ));
source.Add((groupId, cuboids));
}
bufferIndex.Rebuild(source, ClientRegionSize);
}
private static EnumWorldAccessResponse OnTestBlockAccess(
IPlayer player,
BlockSelection blockSel,
EnumBlockAccessFlags accessType,
ref string claimant,
EnumWorldAccessResponse response
)
{
if (response != EnumWorldAccessResponse.Granted)
return response;
BlockPos pos = blockSel.Position;
foreach (int groupId in bufferIndex.CandidateGroupIds(pos))
{
if (IsMember(groupId))
continue;
bool inBuffer = false;
foreach (Cuboidi buffer in bufferIndex.CachedBuffer(groupId))
if (buffer.Contains(pos))
{
inBuffer = true;
break;
}
if (!inBuffer)
continue;
EnumBlockAccessFlags granted = knownEntries.TryGetValue(groupId, out var entry)
? (EnumBlockAccessFlags)entry.GrantedAccess
: EnumBlockAccessFlags.None;
if ((granted & accessType) != 0)
continue;
if (HasClaimAccess(pos, accessType))
continue;
claimant = "custommessage-claimlink-buffer-zone";
return EnumWorldAccessResponse.DeniedByMod;
}
return response;
}
private static bool IsMember(int groupId)
{
foreach (PlayerGroupMembership membership in capi.World.Player.Groups)
if (membership.GroupUid == groupId)
return true;
return false;
}
private static bool HasClaimAccess(BlockPos pos, EnumBlockAccessFlags accessFlag)
{
LandClaim[]? claims = capi.World.Claims.Get(pos);
if (claims == null)
return false;
foreach (LandClaim claim in claims)
{
if (claim.TestPlayerAccess(capi.World.Player, accessFlag) != EnumPlayerAccessResult.Denied)
return true;
if (accessFlag == EnumBlockAccessFlags.Use && claim.AllowUseEveryone)
return true;
}
return false;
}
private static void RenderHighlights()
{
List<BlockPos> positions = new();
List<int> colors = new();
foreach ((int groupId, ClaimLinkBufferEntryDto entry) in knownEntries)
{
int color = HashToColor(groupId);
List<Cuboidi> raw = new();
foreach (ClaimLinkBufferCuboidDto c in entry.Cuboids)
raw.Add(new Cuboidi(c.MinX, c.MinY, c.MinZ, c.MaxX, c.MaxY, c.MaxZ));
foreach (Cuboidi cuboid in CuboidUnion.Merge(raw))
{
positions.Add(new BlockPos(cuboid.MinX, cuboid.MinY, cuboid.MinZ));
positions.Add(new BlockPos(cuboid.MaxX, cuboid.MaxY, cuboid.MaxZ));
colors.Add(color);
}
}
capi.World.HighlightBlocks(
capi.World.Player,
HighlightSlotId,
positions,
colors,
EnumHighlightBlocksMode.Absolute,
EnumHighlightShape.Cubes
);
}
private static void Clear() =>
capi.World.HighlightBlocks(
capi.World.Player,
HighlightSlotId,
new List<BlockPos>(),
new List<int>()
);
private static int HashToColor(int groupId)
{
unchecked
{
uint h = (uint)groupId * config.ColorHashSeed;
int r = (byte)(h >> 16);
int g = (byte)(h >> 8);
int b = (byte)h;
return ColorUtil.ColorFromRgba(r, g, b, 255);
}
}
}
+6
View File
@@ -0,0 +1,6 @@
namespace ClaimLink;
internal class ClaimLinkVisualizerConfig
{
public uint ColorHashSeed = 2654435761u;
}
+125
View File
@@ -0,0 +1,125 @@
using System.Collections.Generic;
using ProtoBuf;
using Vintagestory.API.Common;
using Vintagestory.API.MathTools;
using Vintagestory.API.Server;
namespace ClaimLink;
[ProtoContract]
public class ClaimLinkBufferCuboidDto
{
[ProtoMember(1)]
public int MinX;
[ProtoMember(2)]
public int MinY;
[ProtoMember(3)]
public int MinZ;
[ProtoMember(4)]
public int MaxX;
[ProtoMember(5)]
public int MaxY;
[ProtoMember(6)]
public int MaxZ;
}
[ProtoContract]
public class ClaimLinkBufferEntryDto
{
[ProtoMember(1)]
public int GroupId;
[ProtoMember(2)]
public List<ClaimLinkBufferCuboidDto> Cuboids = new();
[ProtoMember(3)]
public int GrantedAccess;
}
[ProtoContract]
public class ClaimLinkBufferResponse
{
[ProtoMember(1)]
public List<ClaimLinkBufferEntryDto> Entries = new();
[ProtoMember(2)]
public bool IsFullSync;
}
internal static class ClaimLinkVisualizerNetwork
{
internal const string ChannelName = "claimlinkvisualizer";
private static IServerNetworkChannel channel = null!;
internal static void Start(ICoreServerAPI api)
{
channel = api.Network.RegisterChannel(ChannelName).RegisterMessageType<ClaimLinkBufferResponse>();
api.Event.PlayerNowPlaying += SendFullSync;
}
private static void SendFullSync(IServerPlayer toPlayer)
{
ClaimLinkBufferResponse response = new() { IsFullSync = true };
foreach (int groupId in ClaimLinkModSystem.Registry.All)
{
ClaimLinkBufferEntryDto entry = BuildEntry(groupId, toPlayer);
if (entry.Cuboids.Count > 0)
response.Entries.Add(entry);
}
channel.SendPacket(response, toPlayer);
}
internal static void BroadcastDelta(IReadOnlyCollection<int> affectedGroupIds)
{
if (affectedGroupIds.Count == 0 || channel == null)
return;
foreach (IPlayer onlinePlayer in ClaimLinkModSystem.World.AllOnlinePlayers)
{
if (onlinePlayer is not IServerPlayer serverPlayer)
continue;
ClaimLinkBufferResponse response = new() { IsFullSync = false };
foreach (int groupId in affectedGroupIds)
response.Entries.Add(BuildEntry(groupId, serverPlayer));
channel.SendPacket(response, serverPlayer);
}
}
private static ClaimLinkBufferEntryDto BuildEntry(int groupId, IServerPlayer forPlayer)
{
EnumBlockAccessFlags granted = EnumBlockAccessFlags.None;
if (ClaimLinkModSystem.Registry.HasPermission(groupId, forPlayer, EnumBlockAccessFlags.BuildOrBreak))
granted |= EnumBlockAccessFlags.BuildOrBreak;
if (ClaimLinkModSystem.Registry.HasPermission(groupId, forPlayer, EnumBlockAccessFlags.Use))
granted |= EnumBlockAccessFlags.Use;
ClaimLinkBufferEntryDto entry = new() { GroupId = groupId, GrantedAccess = (int)granted };
foreach (Cuboidi cuboid in ClaimLinkBuffer.GetBuffer(groupId))
{
entry.Cuboids.Add(
new ClaimLinkBufferCuboidDto
{
MinX = cuboid.MinX,
MinY = cuboid.MinY,
MinZ = cuboid.MinZ,
MaxX = cuboid.MaxX,
MaxY = cuboid.MaxY,
MaxZ = cuboid.MaxZ,
}
);
}
return entry;
}
}
+45
View File
@@ -0,0 +1,45 @@
using System.Collections.Generic;
using System.Reflection;
using Vintagestory.API.Common;
namespace ClaimLink;
internal delegate TextCommandResult? HookBeforeDelegate(TextCommandCallingArgs args);
internal delegate void HookAfterDelegate(TextCommandCallingArgs args, TextCommandResult result);
internal class CommandHookListenerProxy : DispatchProxy
{
private string modId = null!;
private IReadOnlyList<string> commands = null!;
private HookBeforeDelegate? before;
private HookAfterDelegate? after;
internal static CommandHook.ICommandHookListener Create(
string modId,
IReadOnlyList<string> commands,
HookBeforeDelegate? before,
HookAfterDelegate? after
)
{
object proxy = Create<CommandHook.ICommandHookListener, CommandHookListenerProxy>()!;
CommandHookListenerProxy p = (CommandHookListenerProxy)proxy;
p.modId = modId;
p.commands = commands;
p.before = before;
p.after = after;
return (CommandHook.ICommandHookListener)proxy;
}
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) =>
targetMethod!.Name switch
{
"get_ModId" => modId,
"get_Commands" => commands,
"get_Registration" => new CommandHook.CommandRegistration(
before == null ? null : new CommandHook.CommandBeforeDelegate(before),
after == null ? null : new CommandHook.CommandAfterDelegate(after)
),
_ => null,
};
}
+416
View File
@@ -0,0 +1,416 @@
using System.Collections.Generic;
using Vintagestory.API.Common;
using Vintagestory.API.Config;
using Vintagestory.API.MathTools;
using Vintagestory.API.Server;
namespace ClaimLink;
public class CommandListener
{
public string ModId => "claimlink";
public IReadOnlyList<string> Commands => new[] { "land" };
internal static Dictionary<string, int> PendingLoads = new Dictionary<string, int>();
internal static Dictionary<string, List<Cuboidi>?> PendingSaveChecks =
new Dictionary<string, List<Cuboidi>?>();
private delegate void SubHandler(Caller caller, CmdArgs args);
private static readonly Dictionary<string, SubHandler> topLevel = new()
{
["claim"] = Claim,
["free"] = Free,
["adminfree"] = AdminFree,
["adminfreehere"] = AdminFreeHere,
};
private static readonly Dictionary<string, SubHandler> claimSub = new()
{
["load"] = ClaimLoad,
["new"] = ClaimNew,
["save"] = ClaimSave,
["cancel"] = ClaimCancel,
};
private static void Dispatch(TextCommandCallingArgs args)
{
CmdArgs rawArgs = args.RawArgs.Clone();
while (rawArgs.Length > 0)
{
string word = rawArgs.PeekWord();
if (topLevel.TryGetValue(word, out SubHandler? handler))
{
rawArgs.PopWord();
handler(args.Caller, rawArgs);
}
else
{
rawArgs.PopWord();
}
}
}
internal TextCommandResult? Before(TextCommandCallingArgs args)
{
Dispatch(args);
return null;
}
internal void After(TextCommandCallingArgs args, TextCommandResult result)
{
if (args.Caller.Player == null)
return;
string uid = args.Caller.Player.PlayerUID;
if (!PendingSaveChecks.Remove(uid, out List<Cuboidi>? snapshot))
return;
if (result.Status != EnumCommandStatus.Success)
return;
List<LandClaim> allClaims = ClaimLinkModSystem.LandClaimAPI.All;
if (allClaims.Count == 0)
return;
LandClaim savedClaim = allClaims[allClaims.Count - 1];
if (savedClaim.OwnedByPlayerUid != uid)
return;
int? linkedGroupId = null;
if (ClaimLinkModSystem.TryResolveClaimIndex(uid, savedClaim, out int savedIndex))
linkedGroupId = ClaimLinkModSystem.Registry.FindGroupContaining(uid, savedIndex);
bool isLinked = linkedGroupId != null;
List<Cuboidi> checkAreas = isLinked
? ClaimLinkBuffer.GrowAreas(savedClaim.Areas)
: savedClaim.Areas;
ISet<int> excludeGroupIds = isLinked
? new HashSet<int> { linkedGroupId!.Value }
: ClaimLinkBuffer.MemberClaimLinkIds(uid);
LandClaim? violatingClaim = null;
bool violatesClaimLink = ClaimLinkBuffer.TryFindOverlappingClaimLink(
checkAreas,
excludeGroupIds,
out int violatingGroupId
);
bool violatesClaim =
isLinked
&& !violatesClaimLink
&& ClaimLinkBuffer.TryFindOverlappingClaim(
checkAreas,
uid,
excludeGroupIds,
out violatingClaim
);
if (!violatesClaimLink && !violatesClaim)
{
ClaimLinkModSystem.RebuildBufferIndex();
return;
}
ClaimLinkModSystem.LandClaimAPI.Remove(savedClaim);
string reason = violatesClaimLink
? (
ClaimLinkModSystem.Groups.PlayerGroupsById.TryGetValue(
violatingGroupId,
out PlayerGroup? violatingGroup
)
? $"it overlaps the protected buffer of '{violatingGroup!.Name}'"
: "it overlaps the protected buffer of another claim link"
)
: $"its buffer would overlap the claim owned by {violatingClaim!.LastKnownOwnerName}";
if (snapshot != null)
{
savedClaim.Areas.Clear();
savedClaim.Areas.AddRange(snapshot);
ClaimLinkModSystem.LandClaimAPI.Add(savedClaim);
NotifyPlayer(args.Caller.Player, $"Your claim growth was reverted: {reason}.");
}
else
{
NotifyPlayer(args.Caller.Player, $"Your claim was rejected: {reason}.");
}
}
private static void NotifyPlayer(IPlayer player, string message)
{
if (player is IServerPlayer sp)
sp.SendMessage(GlobalConstants.GeneralChatGroup, message, EnumChatType.Notification);
}
private static void Claim(Caller caller, CmdArgs args)
{
string? word = args.PeekWord();
if (word == null)
return;
if (claimSub.TryGetValue(word, out SubHandler? handler))
{
args.PopWord();
handler(caller, args);
}
}
private static void ClaimSave(Caller caller, CmdArgs args)
{
if (caller.Player == null)
return;
string uid = caller.Player.PlayerUID;
PendingSaveChecks[uid] = null;
if (!PendingLoads.TryGetValue(uid, out int pendingIndex))
return;
if (
ClaimLinkModSystem.TryResolveOwnedClaim(uid, pendingIndex, out LandClaim? existingClaim)
&& existingClaim != null
)
{
List<Cuboidi> snapshot = new();
foreach (Cuboidi area in existingClaim.Areas)
snapshot.Add(area.Clone());
PendingSaveChecks[uid] = snapshot;
}
ClaimLinkModSystem.Registry.ClaimSaved(uid, pendingIndex);
PendingLoads.Remove(uid);
ClaimLinkChatCommand.PendingActions.Remove(uid);
}
private static void ClaimLoad(Caller caller, CmdArgs args)
{
int? claimIndex = args.PopInt();
if (caller.Player == null || claimIndex == null)
return;
if (
ClaimLinkModSystem.TryResolveOwnedClaim(caller.Player.PlayerUID, (int)claimIndex, out _)
)
PendingLoads[caller.Player.PlayerUID] = (int)claimIndex;
}
private static void ClaimNew(Caller caller, CmdArgs args)
{
if (caller.Player == null)
return;
PendingLoads.Remove(caller.Player.PlayerUID);
}
private static void ClaimCancel(Caller caller, CmdArgs args)
{
if (caller.Player == null)
return;
PendingLoads.Remove(caller.Player.PlayerUID);
}
private static void Free(Caller caller, CmdArgs args)
{
if (caller.Player == null)
return;
string uid = caller.Player.PlayerUID;
int? claimIndex = args.PopInt();
if (claimIndex == null)
return;
if (args.PopWord() != "confirm")
return;
ClaimLinkModSystem.Registry.ClaimRemoved(uid, (int)claimIndex);
ClaimLinkChatCommand.PendingActions.Remove(uid);
}
private static void AdminFree(Caller caller, CmdArgs args)
{
if (caller.Player == null)
return;
string? name = args.PopWord();
if (name == null)
return;
string? uid = ClaimLinkModSystem.PlayerData.GetPlayerDataByLastKnownName(name)?.PlayerUID;
if (uid == null)
return;
ClaimLinkModSystem.Registry.ClearAllForPlayer(uid);
ClaimLinkChatCommand.PendingActions.Remove(uid);
}
private static void AdminFreeHere(Caller caller, CmdArgs args)
{
if (caller.Player == null)
return;
LandClaim[] claims = ClaimLinkModSystem.LandClaimAPI.Get(
caller.Player.Entity.Pos.AsBlockPos
);
foreach (LandClaim c in claims)
if (ClaimLinkModSystem.TryResolveClaimIndex(c.OwnedByPlayerUid, c, out int claimIndex))
{
ClaimLinkModSystem.Registry.ClaimRemoved(c.OwnedByPlayerUid, claimIndex);
ClaimLinkChatCommand.PendingActions.Remove(c.OwnedByPlayerUid);
}
}
internal static void OnPlayerDisconnect(IServerPlayer player)
{
PendingLoads.Remove(player.PlayerUID);
PendingSaveChecks.Remove(player.PlayerUID);
}
}
public class GroupCommandListener
{
public string ModId => "claimlink.group";
public IReadOnlyList<string> Commands => new[] { "group" };
internal static Dictionary<string, int> PendingDisbands = new Dictionary<string, int>();
internal static Dictionary<string, (string AffectedUid, int GroupId)> PendingMembershipChecks =
new Dictionary<string, (string, int)>();
internal TextCommandResult? Before(TextCommandCallingArgs args)
{
if (args.Caller.Player == null)
return null;
string callerUid = args.Caller.Player.PlayerUID;
CmdArgs rawArgs = args.RawArgs.Clone();
string? word = rawArgs.PopWord();
switch (word)
{
case "confirmdisband":
ConfirmDisband(args, callerUid, rawArgs);
break;
case "leave":
Leave(args, callerUid, rawArgs);
break;
case "kick":
Kick(args, callerUid, rawArgs);
break;
}
return null;
}
private static void ConfirmDisband(
TextCommandCallingArgs args,
string callerUid,
CmdArgs rawArgs
)
{
string? name = rawArgs.PopWord();
int? groupId =
name != null
? ClaimLinkModSystem.Groups.GetPlayerGroupByName(name)?.Uid
: args.Caller.FromChatGroupId;
if (groupId != null)
PendingDisbands[callerUid] = (int)groupId;
}
private static void Leave(TextCommandCallingArgs args, string callerUid, CmdArgs rawArgs)
{
string? name = rawArgs.PopWord();
int? groupId =
name != null
? ClaimLinkModSystem.Groups.GetPlayerGroupByName(name)?.Uid
: args.Caller.FromChatGroupId;
if (groupId != null)
PendingMembershipChecks[callerUid] = (callerUid, (int)groupId);
}
private static void Kick(TextCommandCallingArgs args, string callerUid, CmdArgs rawArgs)
{
string? word1 = rawArgs.PopWord();
string? word2 = rawArgs.PopWord();
string? targetName;
int? groupId;
if (word2 != null)
{
groupId =
word1 != null ? ClaimLinkModSystem.Groups.GetPlayerGroupByName(word1)?.Uid : null;
targetName = word2;
}
else
{
targetName = word1;
groupId = args.Caller.FromChatGroupId;
}
if (targetName == null || groupId == null)
return;
string? targetUid = ClaimLinkModSystem
.PlayerData.GetPlayerDataByLastKnownName(targetName)
?.PlayerUID;
if (targetUid != null)
PendingMembershipChecks[callerUid] = (targetUid, (int)groupId);
}
internal void After(TextCommandCallingArgs args, TextCommandResult result)
{
if (args.Caller.Player == null)
return;
string callerUid = args.Caller.Player.PlayerUID;
if (PendingDisbands.TryGetValue(callerUid, out int disbandedGroupId))
{
PendingDisbands.Remove(callerUid);
if (!ClaimLinkModSystem.Groups.PlayerGroupsById.ContainsKey(disbandedGroupId))
{
ClaimLinkChatCommand.RemovePendingActionsForGroup(
disbandedGroupId,
"group no longer exists"
);
if (ClaimLinkModSystem.Registry.Exists(disbandedGroupId))
ClaimLinkModSystem.Registry.Remove(disbandedGroupId);
ClaimLinkModSystem.Registry.RemoveGroupFromAllPermissions(disbandedGroupId);
}
}
if (PendingMembershipChecks.TryGetValue(callerUid, out var check))
{
PendingMembershipChecks.Remove(callerUid);
bool stillMember =
ClaimLinkModSystem
.PlayerData.GetPlayerDataByUid(check.AffectedUid)
?.PlayerGroupMemberships.ContainsKey(check.GroupId) == true;
if (!stillMember)
ClaimLinkChatCommand.CancelPendingAction(
check.AffectedUid,
check.GroupId,
"you are no longer a member of the group"
);
}
}
internal static void OnPlayerDisconnect(IServerPlayer player)
{
PendingDisbands.Remove(player.PlayerUID);
PendingMembershipChecks.Remove(player.PlayerUID);
}
}
+137
View File
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using Vintagestory.API.MathTools;
namespace ClaimLink;
/// <summary>
/// Turns a set of possibly overlapping half-open cuboids into a set of disjoint cuboids covering
/// the same volume, so overlapping boxes render as one continuous shape.
/// </summary>
internal static class CuboidUnion
{
internal static List<Cuboidi> Merge(IEnumerable<Cuboidi> cuboids)
{
List<Cuboidi> result = new();
foreach (Cuboidi cuboid in cuboids)
{
List<Cuboidi> pieces = new() { Normalize(cuboid) };
foreach (Cuboidi existing in result)
{
List<Cuboidi> next = new();
foreach (Cuboidi piece in pieces)
Subtract(piece, existing, next);
pieces = next;
if (pieces.Count == 0)
break;
}
result.AddRange(pieces);
}
Coalesce(result);
return result;
}
private static Cuboidi Normalize(Cuboidi c) =>
new(c.MinX, c.MinY, c.MinZ, c.MaxX, c.MaxY, c.MaxZ);
// Appends the parts of `piece` not covered by `cut` (at most 6 boxes).
private static void Subtract(Cuboidi piece, Cuboidi cut, List<Cuboidi> output)
{
if (
piece.MaxX <= cut.MinX
|| piece.MinX >= cut.MaxX
|| piece.MaxY <= cut.MinY
|| piece.MinY >= cut.MaxY
|| piece.MaxZ <= cut.MinZ
|| piece.MinZ >= cut.MaxZ
)
{
output.Add(piece);
return;
}
int x0 = Math.Max(piece.MinX, cut.MinX);
int x1 = Math.Min(piece.MaxX, cut.MaxX);
int y0 = Math.Max(piece.MinY, cut.MinY);
int y1 = Math.Min(piece.MaxY, cut.MaxY);
int z0 = Math.Max(piece.MinZ, cut.MinZ);
int z1 = Math.Min(piece.MaxZ, cut.MaxZ);
if (piece.MinX < x0)
output.Add(new Cuboidi(piece.MinX, piece.MinY, piece.MinZ, x0, piece.MaxY, piece.MaxZ));
if (piece.MaxX > x1)
output.Add(new Cuboidi(x1, piece.MinY, piece.MinZ, piece.MaxX, piece.MaxY, piece.MaxZ));
if (piece.MinY < y0)
output.Add(new Cuboidi(x0, piece.MinY, piece.MinZ, x1, y0, piece.MaxZ));
if (piece.MaxY > y1)
output.Add(new Cuboidi(x0, y1, piece.MinZ, x1, piece.MaxY, piece.MaxZ));
if (piece.MinZ < z0)
output.Add(new Cuboidi(x0, y0, piece.MinZ, x1, y1, z0));
if (piece.MaxZ > z1)
output.Add(new Cuboidi(x0, y0, z1, x1, y1, piece.MaxZ));
}
// Joins face-adjacent boxes that share the same cross-section, to drop subtraction slivers.
private static void Coalesce(List<Cuboidi> boxes)
{
bool merged;
do
{
merged = false;
for (int i = 0; i < boxes.Count && !merged; i++)
for (int j = i + 1; j < boxes.Count && !merged; j++)
if (TryJoin(boxes[i], boxes[j], out Cuboidi joined))
{
boxes[i] = joined;
boxes.RemoveAt(j);
merged = true;
}
} while (merged);
}
private static bool TryJoin(Cuboidi a, Cuboidi b, out Cuboidi joined)
{
bool sameX = a.MinX == b.MinX && a.MaxX == b.MaxX;
bool sameY = a.MinY == b.MinY && a.MaxY == b.MaxY;
bool sameZ = a.MinZ == b.MinZ && a.MaxZ == b.MaxZ;
if (sameY && sameZ && (a.MaxX == b.MinX || b.MaxX == a.MinX))
joined = new Cuboidi(
Math.Min(a.MinX, b.MinX),
a.MinY,
a.MinZ,
Math.Max(a.MaxX, b.MaxX),
a.MaxY,
a.MaxZ
);
else if (sameX && sameZ && (a.MaxY == b.MinY || b.MaxY == a.MinY))
joined = new Cuboidi(
a.MinX,
Math.Min(a.MinY, b.MinY),
a.MinZ,
a.MaxX,
Math.Max(a.MaxY, b.MaxY),
a.MaxZ
);
else if (sameX && sameY && (a.MaxZ == b.MinZ || b.MaxZ == a.MinZ))
joined = new Cuboidi(
a.MinX,
a.MinY,
Math.Min(a.MinZ, b.MinZ),
a.MaxX,
a.MaxY,
Math.Max(a.MaxZ, b.MaxZ)
);
else
{
joined = null!;
return false;
}
return true;
}
}
-136
View File
@@ -1,136 +0,0 @@
using Vintagestory.API.Common;
using System.Collections.Generic;
using CommandHook;
using Vintagestory.API.Server;
namespace ClaimLink;
public class ClaimLinkCommandListener : ICommandHookListener
{
public string ModId => "claimlink";
public IReadOnlyList<string> Commands => new[] { "land" };
public CommandRegistration Registration => new(Before, After);
private static Dictionary<string, int> pendingLoads = new Dictionary<string, int>();
private delegate void SubHandler(Caller caller, CmdArgs args);
private static readonly Dictionary<string, SubHandler> topLevel = new()
{
["claim"] = Claim,
["free"] = Free,
["info"] = Info,
["list"] = List,
["adminfree"] = AdminFree,
};
private static readonly Dictionary<string, SubHandler> claimSub = new()
{
["load"] = ClaimLoad,
["new"] = ClaimNew,
["grant"] = ClaimGrant,
["revoke"] = ClaimRevoke,
["grantgroup"] = ClaimGrantGroup,
["revokegroup"] = ClaimRevokeGroup,
["start"] = ClaimStart,
["end"] = ClaimEnd,
["grow"] = ClaimGrow,
["shrink"] = ClaimShrink,
["add"] = ClaimAdd,
["allowuseeveryone"] = ClaimAllowUseEveryone,
["plevel"] = ClaimPLevel,
["fullheight"] = ClaimFullHeight,
["save"] = ClaimSave,
["cancel"] = ClaimCancel,
["download"] = ClaimDownload,
};
private TextCommandResult? Before(TextCommandCallingArgs args)
{
CmdArgs rawArgs = args.RawArgs.Clone();
while (rawArgs.Length > 0)
{
string word = rawArgs.PeekWord();
if (topLevel.TryGetValue(word, out SubHandler? handler))
{
rawArgs.PopWord();
handler(args.Caller, rawArgs);
}
else
{
rawArgs.PopWord();
}
}
return null;
}
private void After(TextCommandCallingArgs args, TextCommandResult result)
{
}
private static void Claim(Caller caller, CmdArgs args)
{
string word = args.PeekWord();
if (claimSub.TryGetValue(word, out SubHandler? handler))
{
args.PopWord();
handler(caller, args);
}
}
private static void ClaimLoad(Caller caller, CmdArgs args)
{
if (caller.Player == null)
return;
int? claimIndex = args.PopInt();
if (claimIndex == null || claimIndex < 0 || claimIndex > 999)
return;
if (!ClaimLinkModSystem.TryResolveOwnedClaim(caller.Player.PlayerUID, (int)claimIndex, out int globalIndex, out _))
return;
pendingLoads[caller.Player.PlayerUID] = globalIndex;
}
private static void ClaimCancel(Caller caller, CmdArgs args)
{
if (caller.Player == null)
return;
pendingLoads.Remove(caller.Player.PlayerUID);
}
private static void Free(Caller caller, CmdArgs args) { }
private static void Info(Caller caller, CmdArgs args) { }
private static void List(Caller caller, CmdArgs args) { }
private static void AdminFree(Caller caller, CmdArgs args) { }
private static void ClaimNew(Caller caller, CmdArgs args) { }
private static void ClaimGrant(Caller caller, CmdArgs args) { }
private static void ClaimRevoke(Caller caller, CmdArgs args) { }
private static void ClaimGrantGroup(Caller caller, CmdArgs args) { }
private static void ClaimRevokeGroup(Caller caller, CmdArgs args) { }
private static void ClaimStart(Caller caller, CmdArgs args) { }
private static void ClaimEnd(Caller caller, CmdArgs args) { }
private static void ClaimGrow(Caller caller, CmdArgs args) { }
private static void ClaimShrink(Caller caller, CmdArgs args) { }
private static void ClaimAdd(Caller caller, CmdArgs args) { }
private static void ClaimAllowUseEveryone(Caller caller, CmdArgs args) { }
private static void ClaimPLevel(Caller caller, CmdArgs args) { }
private static void ClaimFullHeight(Caller caller, CmdArgs args) { }
private static void ClaimSave(Caller caller, CmdArgs args) { }
private static void ClaimDownload(Caller caller, CmdArgs args) { }
internal static void OnPlayerDisconnect(IServerPlayer player)
{
pendingLoads.Remove(player.PlayerUID);
ClaimLinkChatCommand.RemovePending(player.PlayerUID);
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"custommessage-claimlink-buffer-zone": "This area is a claim link buffer zone.",
"ingameerror-noprivilege-buildbreak-claimlink-buffer-zone": "This area is a claim link buffer zone."
}
+3 -4
View File
@@ -3,14 +3,13 @@
"type": "Code",
"modid": "claimlink",
"name": "ClaimLink",
"side": "Server",
"side": "Universal",
"authors": [
"anth64"
],
"description": "Link claims together with groups.",
"version": "0.0.6",
"version": "0.7.0",
"dependencies": {
"game": "1.22.3",
"commandhook": "2.1.0"
"game": "1.22.5"
}
}
+52 -1
View File
@@ -1,3 +1,54 @@
# ClaimLink
A modification for claims in Vintage Story
Links vanilla Vintage Story land claims to an existing player group and adds a protected buffer zone around the linked area. Requires [CommandHook](https://mods.vintagestory.at/show/mod/56633) 2.1.0+.
Root command: `/claimlink` (aliases: `/clink`, `/claiml`, `/cl`). Requires the `chat` privilege.
Most actions that change state (`new`, `link`, `unlink`, `kick`, `delete`, `transferownership`) stage the change and ask you to confirm it with `/claimlink confirm` or back out with `/claimlink cancel`. Buffer permission commands (`allow`, `allowgroup`, `deny`, `denygroup`) and read-only commands (`info`, `list`) apply immediately.
A `groupname` argument can usually be left off if you're sending the command from that group's chat channel, it'll infer the group from context, same as vanilla's own `/group` commands.
## Player commands
| Command | Args | Description |
|---|---|---|
| `new` (`n`) | `[groupname]` | Promote a group you own into a claim link. Owner only. |
| `link` (`l`) | `<claim> [groupname]` | Link a claim you own into a claim link. Must be a member. Rejected if the claim's buffer would overlap another claim link's buffer or another player's raw claim. |
| `unlink` (`ul`) | `<claim>` | Remove one of your claims from its claim link. |
| `confirm` (`c`) | | Confirm your pending staged action. |
| `cancel` | | Cancel your pending staged action. |
| `kick` | `<groupname> [playername]` | Force-unlink all of a player's claims from the claim link. Owner or op only. |
| `allow` | `<playername> <use\|build\|all> [groupname]` | Grant a player buffer access without adding them to the group. Owner or op only. |
| `allowgroup` | `<targetgroup> <use\|build\|all> [groupname]` | Grant a whole other player group buffer access. Owner or op only. |
| `deny` | `<groupname> [playername]` | Revoke a player's buffer access. Owner or op only. |
| `denygroup` | `<groupname> [targetgroup]` | Revoke a group's buffer access. Owner or op only. |
| `delete` | `[groupname]` | Delete a claim link (the underlying vanilla group is untouched, it just stops being a claim link). Owner only. |
| `transferownership` (`transfer`, `to`) | `<groupname> [playername]` | Transfer ownership of the claim link to another member. Owner only. |
| `info` (`i`) | `[groupname]` | Show a claim link's members and linked claims. Full detail (claims, granted access) only shown to members or ops with `controlserver`; others just see the member list. |
| `list` (`ls`) | | List every claim link on the server and its member count. |
`claim` arguments are the claim's index in `/land claim list` (your own claim numbering, same as vanilla).
`allow`/`allowgroup`/`deny`/`denygroup` access levels: `use` (interact), `build` (place/break), `all` (both).
## Admin commands
`/claimlink admin` (alias `/claimlink a`), requires `controlserver`. Same shape as the player commands but works on any claim link regardless of ownership or membership, and skips the confirm/cancel staging (instant).
| Command | Args | Description |
|---|---|---|
| `admin delete` (`del`) | `[groupname]` | Delete any claim link. |
| `admin unlink` | `<playername> <claim>` | Unlink a specific claim from any claim link. |
| `admin kick` | `<groupname> [playername]` | Force-unlink all of a player's claims from any claim link. |
| `admin transferownership` (`transfer`, `to`) | `<playername> [groupname]` | Force-transfer ownership of any claim link. |
| `admin allow` | `<playername> <use\|build\|all> [groupname]` | Grant buffer access on any claim link. |
| `admin allowgroup` | `<targetgroup> <use\|build\|all> [groupname]` | Grant a group buffer access on any claim link. |
| `admin deny` | `<groupname> [playername]` | Revoke a player's buffer access on any claim link. |
| `admin denygroup` | `<groupname> [targetgroup]` | Revoke a group's buffer access on any claim link. |
## How the buffer works
A vanilla claim can be made of multiple cuboid areas (grown one face-adjacent cuboid at a time), and the buffer follows the same shape: each area gets its own grown box, outward by a configurable margin (`BufferSize`, default 16 blocks, in `ModConfig/claimlink.json`) on every axis. Areas close enough for their grown boxes to touch or overlap, whether from the same claim or different claims linked to the same claim link, read as one continuous protected area. Linking a claim, or growing an existing linked claim via `/land claim save`, checks the resulting buffer against every other claim link's buffer and every other player's raw claim, and rejects the change if it would overlap either. Your own claim link is exempt from that check, so its own areas are free to overlap or touch each other, which is exactly how they end up reading as one continuous protected area. Only overlap with a different claim link, or with someone else's claim, is blocked.
Buffer permissions only cover the empty space around the linked claims, not the claims themselves. In that space, only members of the claim link's group, or anyone explicitly granted access via `allow`/`allowgroup`, can place, break, or use blocks; grant level (`use`/`build`/`all`) controls which. On the ground of a claim that's actually part of the claim link, normal vanilla permissions (owner, claim's group, explicit permission, `AllowUseEveryone`) decide access instead, same as any other claim.