Add overworld region-zone-chunk data model and admin live world editor

This commit is contained in:
dingo
2026-02-14 13:52:36 -05:00
parent 189e5fcff4
commit 18d6fe683b
9 changed files with 6017 additions and 22 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,248 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SystemRevivalServer.Migrations
{
/// <inheritdoc />
public partial class AddOverworldRegionZoneChunkEditor : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "world_regions",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
ZonesPerRegionX = table.Column<int>(type: "int", nullable: false),
ZonesPerRegionY = table.Column<int>(type: "int", nullable: false),
ChunksPerZoneX = table.Column<int>(type: "int", nullable: false),
ChunksPerZoneY = table.Column<int>(type: "int", nullable: false),
ChunkWidthTiles = table.Column<int>(type: "int", nullable: false),
ChunkHeightTiles = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_world_regions", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "world_zones",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
RegionId = table.Column<int>(type: "int", nullable: false),
ZoneX = table.Column<int>(type: "int", nullable: false),
ZoneY = table.Column<int>(type: "int", nullable: false),
Name = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_world_zones", x => x.Id);
table.ForeignKey(
name: "FK_world_zones_world_regions_RegionId",
column: x => x.RegionId,
principalTable: "world_regions",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "world_chunks",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
WorldZoneId = table.Column<long>(type: "bigint", nullable: false),
ChunkX = table.Column<int>(type: "int", nullable: false),
ChunkY = table.Column<int>(type: "int", nullable: false),
Version = table.Column<long>(type: "bigint", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_world_chunks", x => x.Id);
table.ForeignKey(
name: "FK_world_chunks_world_zones_WorldZoneId",
column: x => x.WorldZoneId,
principalTable: "world_zones",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "world_chunk_npc_spawns",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
WorldChunkId = table.Column<long>(type: "bigint", nullable: false),
NpcDefinitionId = table.Column<int>(type: "int", nullable: false),
TileX = table.Column<int>(type: "int", nullable: false),
TileY = table.Column<int>(type: "int", nullable: false),
Rotation = table.Column<int>(type: "int", nullable: false),
MetadataJson = table.Column<string>(type: "varchar(1024)", maxLength: 1024, nullable: true)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_world_chunk_npc_spawns", x => x.Id);
table.ForeignKey(
name: "FK_world_chunk_npc_spawns_dungeon_npc_definitions_NpcDefinition~",
column: x => x.NpcDefinitionId,
principalTable: "dungeon_npc_definitions",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_world_chunk_npc_spawns_world_chunks_WorldChunkId",
column: x => x.WorldChunkId,
principalTable: "world_chunks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "world_chunk_objects",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
WorldChunkId = table.Column<long>(type: "bigint", nullable: false),
ObjectDefinitionId = table.Column<int>(type: "int", nullable: false),
TileX = table.Column<int>(type: "int", nullable: false),
TileY = table.Column<int>(type: "int", nullable: false),
Rotation = table.Column<int>(type: "int", nullable: false),
MetadataJson = table.Column<string>(type: "varchar(1024)", maxLength: 1024, nullable: true)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_world_chunk_objects", x => x.Id);
table.ForeignKey(
name: "FK_world_chunk_objects_dungeon_objects_ObjectDefinitionId",
column: x => x.ObjectDefinitionId,
principalTable: "dungeon_objects",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_world_chunk_objects_world_chunks_WorldChunkId",
column: x => x.WorldChunkId,
principalTable: "world_chunks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "world_chunk_tiles",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
WorldChunkId = table.Column<long>(type: "bigint", nullable: false),
TileX = table.Column<int>(type: "int", nullable: false),
TileY = table.Column<int>(type: "int", nullable: false),
SheetId = table.Column<int>(type: "int", nullable: false),
FrameIndex = table.Column<int>(type: "int", nullable: false),
IsWalkable = table.Column<bool>(type: "tinyint(1)", nullable: false),
IsInvisiblePaywall = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_world_chunk_tiles", x => x.Id);
table.ForeignKey(
name: "FK_world_chunk_tiles_world_chunks_WorldChunkId",
column: x => x.WorldChunkId,
principalTable: "world_chunks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_world_chunk_npc_spawns_NpcDefinitionId",
table: "world_chunk_npc_spawns",
column: "NpcDefinitionId");
migrationBuilder.CreateIndex(
name: "IX_world_chunk_npc_spawns_WorldChunkId_TileX_TileY_NpcDefinitio~",
table: "world_chunk_npc_spawns",
columns: new[] { "WorldChunkId", "TileX", "TileY", "NpcDefinitionId" });
migrationBuilder.CreateIndex(
name: "IX_world_chunk_objects_ObjectDefinitionId",
table: "world_chunk_objects",
column: "ObjectDefinitionId");
migrationBuilder.CreateIndex(
name: "IX_world_chunk_objects_WorldChunkId_TileX_TileY_ObjectDefinitio~",
table: "world_chunk_objects",
columns: new[] { "WorldChunkId", "TileX", "TileY", "ObjectDefinitionId" });
migrationBuilder.CreateIndex(
name: "IX_world_chunk_tiles_WorldChunkId_TileX_TileY",
table: "world_chunk_tiles",
columns: new[] { "WorldChunkId", "TileX", "TileY" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_world_chunks_WorldZoneId_ChunkX_ChunkY",
table: "world_chunks",
columns: new[] { "WorldZoneId", "ChunkX", "ChunkY" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_world_regions_Name",
table: "world_regions",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_world_zones_RegionId_ZoneX_ZoneY",
table: "world_zones",
columns: new[] { "RegionId", "ZoneX", "ZoneY" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "world_chunk_npc_spawns");
migrationBuilder.DropTable(
name: "world_chunk_objects");
migrationBuilder.DropTable(
name: "world_chunk_tiles");
migrationBuilder.DropTable(
name: "world_chunks");
migrationBuilder.DropTable(
name: "world_zones");
migrationBuilder.DropTable(
name: "world_regions");
}
}
}
+322 -21
View File
@@ -1093,28 +1093,28 @@ namespace SystemRevivalServer.Migrations
b.Property<float>("DropChanceMultiplier")
.HasColumnType("float");
b.Property<float>("GoldDropChance")
.HasColumnType("float");
b.Property<bool>("GuaranteedDrop")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<float>("GoldDropChance")
.HasColumnType("float");
b.Property<int>("MaxGold")
b.Property<int>("MaxDrops")
.HasColumnType("int");
b.Property<int>("MaxDrops")
b.Property<int>("MaxGold")
.HasColumnType("int");
b.Property<int>("MaxTier")
.HasColumnType("int");
b.Property<int>("MinGold")
b.Property<int>("MinDrops")
.HasColumnType("int");
b.Property<int>("MinDrops")
b.Property<int>("MinGold")
.HasColumnType("int");
b.Property<int>("MinTier")
@@ -1367,14 +1367,14 @@ namespace SystemRevivalServer.Migrations
b.Property<int>("Defense")
.HasColumnType("int");
b.Property<int>("Dexterity")
.HasColumnType("int");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<int>("Dexterity")
.HasColumnType("int");
b.Property<int?>("DialogTreeId")
.HasColumnType("int");
@@ -1483,6 +1483,9 @@ namespace SystemRevivalServer.Migrations
.HasMaxLength(128)
.HasColumnType("varchar(128)");
b.Property<long>("RewardGold")
.HasColumnType("bigint");
b.Property<int?>("RewardItemDefinitionId")
.HasColumnType("int");
@@ -1493,9 +1496,6 @@ namespace SystemRevivalServer.Migrations
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<long>("RewardGold")
.HasColumnType("bigint");
b.Property<string>("RewardType")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
@@ -1526,6 +1526,9 @@ namespace SystemRevivalServer.Migrations
b.Property<int>("ConditionQuantity")
.HasColumnType("int");
b.Property<int>("ConditionType")
.HasColumnType("int");
b.Property<string>("ConditionValue")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
@@ -1533,9 +1536,6 @@ namespace SystemRevivalServer.Migrations
b.Property<bool>("ConsumeConditionItem")
.HasColumnType("tinyint(1)");
b.Property<int>("ConditionType")
.HasColumnType("int");
b.Property<int?>("NextNodeId")
.HasColumnType("int");
@@ -3098,6 +3098,236 @@ namespace SystemRevivalServer.Migrations
b.ToTable("tile_templates");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldChunk", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<long>("Id"));
b.Property<int>("ChunkX")
.HasColumnType("int");
b.Property<int>("ChunkY")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<long>("Version")
.HasColumnType("bigint");
b.Property<long>("WorldZoneId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("WorldZoneId", "ChunkX", "ChunkY")
.IsUnique();
b.ToTable("world_chunks");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldChunkNpcSpawn", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<long>("Id"));
b.Property<string>("MetadataJson")
.HasMaxLength(1024)
.HasColumnType("varchar(1024)");
b.Property<int>("NpcDefinitionId")
.HasColumnType("int");
b.Property<int>("Rotation")
.HasColumnType("int");
b.Property<int>("TileX")
.HasColumnType("int");
b.Property<int>("TileY")
.HasColumnType("int");
b.Property<long>("WorldChunkId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("NpcDefinitionId");
b.HasIndex("WorldChunkId", "TileX", "TileY", "NpcDefinitionId");
b.ToTable("world_chunk_npc_spawns");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldChunkObject", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<long>("Id"));
b.Property<string>("MetadataJson")
.HasMaxLength(1024)
.HasColumnType("varchar(1024)");
b.Property<int>("ObjectDefinitionId")
.HasColumnType("int");
b.Property<int>("Rotation")
.HasColumnType("int");
b.Property<int>("TileX")
.HasColumnType("int");
b.Property<int>("TileY")
.HasColumnType("int");
b.Property<long>("WorldChunkId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("ObjectDefinitionId");
b.HasIndex("WorldChunkId", "TileX", "TileY", "ObjectDefinitionId");
b.ToTable("world_chunk_objects");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldChunkTile", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<long>("Id"));
b.Property<int>("FrameIndex")
.HasColumnType("int");
b.Property<bool>("IsInvisiblePaywall")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsWalkable")
.HasColumnType("tinyint(1)");
b.Property<int>("SheetId")
.HasColumnType("int");
b.Property<int>("TileX")
.HasColumnType("int");
b.Property<int>("TileY")
.HasColumnType("int");
b.Property<long>("WorldChunkId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("WorldChunkId", "TileX", "TileY")
.IsUnique();
b.ToTable("world_chunk_tiles");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldRegion", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ChunkHeightTiles")
.HasColumnType("int");
b.Property<int>("ChunkWidthTiles")
.HasColumnType("int");
b.Property<int>("ChunksPerZoneX")
.HasColumnType("int");
b.Property<int>("ChunksPerZoneY")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("ZonesPerRegionX")
.HasColumnType("int");
b.Property<int>("ZonesPerRegionY")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("world_regions");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldZone", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<int>("RegionId")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("ZoneX")
.HasColumnType("int");
b.Property<int>("ZoneY")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RegionId", "ZoneX", "ZoneY")
.IsUnique();
b.ToTable("world_zones");
});
modelBuilder.Entity("DataServer.Data.Session", b =>
{
b.Property<ulong>("Id")
@@ -3694,6 +3924,77 @@ namespace SystemRevivalServer.Migrations
b.Navigation("PrimaryTileDefinition");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldChunk", b =>
{
b.HasOne("DataServer.Data.Entities.WorldZone", "Zone")
.WithMany()
.HasForeignKey("WorldZoneId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Zone");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldChunkNpcSpawn", b =>
{
b.HasOne("DataServer.Data.Entities.DungeonNpcDefinition", "NpcDefinition")
.WithMany()
.HasForeignKey("NpcDefinitionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DataServer.Data.Entities.WorldChunk", "Chunk")
.WithMany()
.HasForeignKey("WorldChunkId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Chunk");
b.Navigation("NpcDefinition");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldChunkObject", b =>
{
b.HasOne("DataServer.Data.Entities.DungeonObjectDefinition", "ObjectDefinition")
.WithMany()
.HasForeignKey("ObjectDefinitionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DataServer.Data.Entities.WorldChunk", "Chunk")
.WithMany()
.HasForeignKey("WorldChunkId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Chunk");
b.Navigation("ObjectDefinition");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldChunkTile", b =>
{
b.HasOne("DataServer.Data.Entities.WorldChunk", "Chunk")
.WithMany()
.HasForeignKey("WorldChunkId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Chunk");
});
modelBuilder.Entity("DataServer.Data.Entities.WorldZone", b =>
{
b.HasOne("DataServer.Data.Entities.WorldRegion", "Region")
.WithMany()
.HasForeignKey("RegionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Region");
});
modelBuilder.Entity("DataServer.Data.Session", b =>
{
b.HasOne("DataServer.Data.Account", "Account")
@@ -3740,6 +4041,11 @@ namespace SystemRevivalServer.Migrations
b.Navigation("Entries");
});
modelBuilder.Entity("DataServer.Data.Entities.DungeonMobDefinition", b =>
{
b.Navigation("AbilityAssignments");
});
modelBuilder.Entity("DataServer.Data.Entities.DungeonNpcDialogNode", b =>
{
b.Navigation("Options");
@@ -3755,11 +4061,6 @@ namespace SystemRevivalServer.Migrations
b.Navigation("Items");
});
modelBuilder.Entity("DataServer.Data.Entities.DungeonMobDefinition", b =>
{
b.Navigation("AbilityAssignments");
});
modelBuilder.Entity("DataServer.Data.Entities.MobSpriteSheet", b =>
{
b.Navigation("Animations");
@@ -160,6 +160,10 @@
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
<span>Dungeons</span>
</a>
<a href="/admin/worldeditor" class="sidebar-link @(ViewContext.RouteData.Values["page"]?.ToString()?.StartsWith("/WorldEditor") == true ? "active" : "")" data-tooltip="World Editor">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a2 2 0 01-2.828 0L6.343 16.657m11.314 0A8 8 0 005.03 7.343m12.627 9.314A8 8 0 1112 4a8 8 0 015.657 12.657z"/></svg>
<span>World Editor</span>
</a>
<a href="/admin/players" class="sidebar-link @(ViewContext.RouteData.Values["page"]?.ToString()?.StartsWith("/Players") == true ? "active" : "")" data-tooltip="Players">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"/></svg>
<span>Players</span>
@@ -0,0 +1,532 @@
@page "/admin/worldeditor"
@model GameServices.Admin.Pages.WorldEditor.IndexModel
@using System.Text.Json
@{
ViewData["Title"] = "World Editor";
var regionsJson = JsonSerializer.Serialize(Model.Regions.Select(r => new
{
id = r.Id,
name = r.Name,
zonesX = r.ZonesPerRegionX,
zonesY = r.ZonesPerRegionY,
chunksPerZoneX = r.ChunksPerZoneX,
chunksPerZoneY = r.ChunksPerZoneY,
chunkWidthTiles = r.ChunkWidthTiles,
chunkHeightTiles = r.ChunkHeightTiles
}));
var sheetsJson = JsonSerializer.Serialize(Model.TileSheets.Select(s => new
{
id = s.Id,
name = s.Name,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
cols = s.Columns,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight
}));
var objectsJson = JsonSerializer.Serialize(Model.ObjectDefinitions.Select(o => new { id = o.Id, name = o.Name }));
var npcsJson = JsonSerializer.Serialize(Model.NpcDefinitions.Select(n => new { id = n.Id, name = n.Name }));
}
<div class="space-y-6">
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold text-white">World Editor</h1>
<p class="text-gray-400 mt-1">Live chunk editing for tiles, objects, and NPC spawns</p>
</div>
</div>
<form id="af-form" method="post" class="hidden">
@Html.AntiForgeryToken()
</form>
<div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
<div class="xl:col-span-3 space-y-4">
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Selection</h2>
<div>
<label class="label">Region</label>
<select id="regionId" class="input"></select>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="label">Zone X</label>
<input id="zoneX" type="number" class="input" min="0" value="@Model.SelectedZoneX" />
</div>
<div>
<label class="label">Zone Y</label>
<input id="zoneY" type="number" class="input" min="0" value="@Model.SelectedZoneY" />
</div>
<div>
<label class="label">Chunk X</label>
<input id="chunkX" type="number" class="input" min="0" value="@Model.SelectedChunkX" />
</div>
<div>
<label class="label">Chunk Y</label>
<input id="chunkY" type="number" class="input" min="0" value="@Model.SelectedChunkY" />
</div>
</div>
<div class="flex gap-2">
<button type="button" class="btn btn-primary" onclick="loadChunk()">Load Chunk</button>
<button type="button" class="btn btn-secondary" onclick="loadZone()">Load Zone</button>
</div>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Paint Mode</h2>
<div>
<label class="label">Mode</label>
<select id="paintMode" class="input" onchange="renderChunk()">
<option value="tile">Tile</option>
<option value="object">Object</option>
<option value="npc">NPC</option>
<option value="erase">Erase</option>
</select>
</div>
<div id="eraseTargetWrap" class="hidden">
<label class="label">Erase Target</label>
<select id="eraseTarget" class="input">
<option value="tile">Tile</option>
<option value="object">Object</option>
<option value="npc">NPC</option>
</select>
</div>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Tile Tool</h2>
<div>
<label class="label">Sprite Sheet</label>
<select id="sheetId" class="input" onchange="onSheetChanged()"></select>
</div>
<div>
<label class="label">Frame Index</label>
<input id="frameIndex" type="number" class="input" min="0" value="0" />
</div>
<div class="grid grid-cols-1 gap-2">
<label class="flex items-center gap-2 text-gray-300 cursor-pointer">
<input id="isWalkable" type="checkbox" checked class="w-4 h-4 rounded border-gray-600 bg-gray-800 text-indigo-600" />
Walkable
</label>
<label class="flex items-center gap-2 text-gray-300 cursor-pointer">
<input id="isInvisiblePaywall" type="checkbox" class="w-4 h-4 rounded border-gray-600 bg-gray-800 text-indigo-600" />
Invisible Paywall
</label>
</div>
<a id="tileDefLink" href="/admin/tilemaps/tiles/edit" class="text-sm text-indigo-400 hover:underline">Edit Tile Definition</a>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Object Tool</h2>
<label class="label">Object</label>
<select id="objectDefinitionId" class="input"></select>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">NPC Tool</h2>
<label class="label">NPC</label>
<select id="npcDefinitionId" class="input"></select>
</div>
</div>
<div class="xl:col-span-9 space-y-4">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-2">Region Minimap</h2>
<canvas id="regionCanvas" width="360" height="240" class="w-full rounded border border-gray-700 bg-gray-900"></canvas>
</div>
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-2">Zone Chunk Map</h2>
<canvas id="zoneCanvas" width="360" height="240" class="w-full rounded border border-gray-700 bg-gray-900"></canvas>
</div>
</div>
<div class="card p-4">
<div class="flex items-center justify-between mb-2">
<h2 class="text-lg font-semibold text-white">Chunk Canvas</h2>
<div id="chunkMeta" class="text-sm text-gray-400">No chunk loaded</div>
</div>
<canvas id="chunkCanvas" width="768" height="768" class="w-full rounded border border-gray-700 bg-gray-900 cursor-crosshair"></canvas>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
const regions = @Html.Raw(regionsJson);
const sheets = @Html.Raw(sheetsJson);
const objectDefs = @Html.Raw(objectsJson);
const npcDefs = @Html.Raw(npcsJson);
let currentRegion = null;
let currentZoneChunks = [];
let currentChunk = null;
let currentTiles = new Map();
let currentObjects = [];
let currentNpcs = [];
let pollTimer = null;
const regionCanvas = document.getElementById('regionCanvas');
const regionCtx = regionCanvas.getContext('2d');
const zoneCanvas = document.getElementById('zoneCanvas');
const zoneCtx = zoneCanvas.getContext('2d');
const chunkCanvas = document.getElementById('chunkCanvas');
const chunkCtx = chunkCanvas.getContext('2d');
function token() {
return document.querySelector('#af-form input[name="__RequestVerificationToken"]').value;
}
function key(x, y) { return `${x},${y}`; }
function initSelectors() {
const regionSel = document.getElementById('regionId');
regionSel.innerHTML = regions.map(r => `<option value="${r.id}">${r.name}</option>`).join('');
regionSel.value = '@Model.SelectedRegionId';
regionSel.addEventListener('change', () => {
loadRegion();
});
const sheetSel = document.getElementById('sheetId');
sheetSel.innerHTML = sheets.map(s => `<option value="${s.id}">${s.name}</option>`).join('');
if (sheets.length) sheetSel.value = sheets[0].id;
onSheetChanged();
document.getElementById('objectDefinitionId').innerHTML = objectDefs.map(o => `<option value="${o.id}">${o.name}</option>`).join('');
document.getElementById('npcDefinitionId').innerHTML = npcDefs.map(n => `<option value="${n.id}">${n.name}</option>`).join('');
}
async function getJson(url) {
const res = await fetch(url);
return await res.json();
}
async function postJson(url, body) {
const params = new URLSearchParams();
for (const k of Object.keys(body)) {
const v = body[k];
if (v === undefined || v === null) continue;
params.set(k, String(v));
}
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'RequestVerificationToken': token()
},
body: params.toString()
});
return await res.json();
}
function selection() {
return {
regionId: parseInt(document.getElementById('regionId').value, 10) || 0,
zoneX: parseInt(document.getElementById('zoneX').value, 10) || 0,
zoneY: parseInt(document.getElementById('zoneY').value, 10) || 0,
chunkX: parseInt(document.getElementById('chunkX').value, 10) || 0,
chunkY: parseInt(document.getElementById('chunkY').value, 10) || 0
};
}
async function loadRegion() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Region&regionId=${s.regionId}`);
if (!data.success) return;
currentRegion = data.region;
renderRegionMap();
await loadZone();
}
async function loadZone() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Zone&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}`);
if (!data.success) return;
currentZoneChunks = data.chunks || [];
renderZoneMap();
}
async function loadChunk() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Chunk&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}&chunkX=${s.chunkX}&chunkY=${s.chunkY}`);
if (!data.success) return;
currentChunk = data.chunk;
currentTiles = new Map();
for (const t of data.tiles) currentTiles.set(key(t.x, t.y), t);
currentObjects = data.objects || [];
currentNpcs = data.npcs || [];
document.getElementById('chunkMeta').textContent = `Chunk ${s.zoneX}:${s.zoneY}:${s.chunkX}:${s.chunkY} v${currentChunk.version} (${currentChunk.width}x${currentChunk.height})`;
renderChunk();
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(checkChunkVersion, 2000);
}
async function checkChunkVersion() {
if (!currentChunk) return;
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Chunk&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}&chunkX=${s.chunkX}&chunkY=${s.chunkY}`);
if (!data.success) return;
if (data.chunk.version !== currentChunk.version) {
currentChunk = data.chunk;
currentTiles = new Map();
for (const t of data.tiles) currentTiles.set(key(t.x, t.y), t);
currentObjects = data.objects || [];
currentNpcs = data.npcs || [];
document.getElementById('chunkMeta').textContent = `Chunk ${s.zoneX}:${s.zoneY}:${s.chunkX}:${s.chunkY} v${currentChunk.version} (${currentChunk.width}x${currentChunk.height})`;
renderChunk();
loadZone();
}
}
function renderRegionMap() {
regionCtx.clearRect(0, 0, regionCanvas.width, regionCanvas.height);
if (!currentRegion) return;
const cellW = regionCanvas.width / currentRegion.zonesX;
const cellH = regionCanvas.height / currentRegion.zonesY;
const sx = parseInt(document.getElementById('zoneX').value, 10) || 0;
const sy = parseInt(document.getElementById('zoneY').value, 10) || 0;
for (let y = 0; y < currentRegion.zonesY; y++) {
for (let x = 0; x < currentRegion.zonesX; x++) {
const px = x * cellW;
const py = y * cellH;
regionCtx.fillStyle = (x === sx && y === sy) ? '#4338ca' : '#1f2937';
regionCtx.fillRect(px + 1, py + 1, cellW - 2, cellH - 2);
regionCtx.strokeStyle = '#374151';
regionCtx.strokeRect(px + 1, py + 1, cellW - 2, cellH - 2);
regionCtx.fillStyle = '#9ca3af';
regionCtx.font = '12px monospace';
regionCtx.fillText(`${x},${y}`, px + 6, py + 16);
}
}
}
function renderZoneMap() {
zoneCtx.clearRect(0, 0, zoneCanvas.width, zoneCanvas.height);
if (!currentRegion) return;
const w = currentRegion.chunksPerZoneX;
const h = currentRegion.chunksPerZoneY;
const cellW = zoneCanvas.width / w;
const cellH = zoneCanvas.height / h;
const sx = parseInt(document.getElementById('chunkX').value, 10) || 0;
const sy = parseInt(document.getElementById('chunkY').value, 10) || 0;
const versionByPos = new Map();
for (const c of currentZoneChunks) versionByPos.set(key(c.chunkX, c.chunkY), c.version);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const px = x * cellW;
const py = y * cellH;
const v = versionByPos.get(key(x, y));
zoneCtx.fillStyle = (x === sx && y === sy) ? '#4338ca' : (v ? '#14532d' : '#1f2937');
zoneCtx.fillRect(px + 1, py + 1, cellW - 2, cellH - 2);
zoneCtx.strokeStyle = '#374151';
zoneCtx.strokeRect(px + 1, py + 1, cellW - 2, cellH - 2);
}
}
}
function renderChunk() {
chunkCtx.clearRect(0, 0, chunkCanvas.width, chunkCanvas.height);
if (!currentChunk) return;
const tileSize = Math.max(6, Math.floor(Math.min(chunkCanvas.width / currentChunk.width, chunkCanvas.height / currentChunk.height)));
const drawW = currentChunk.width * tileSize;
const drawH = currentChunk.height * tileSize;
chunkCtx.fillStyle = '#111827';
chunkCtx.fillRect(0, 0, drawW, drawH);
for (const t of currentTiles.values()) {
const px = t.x * tileSize;
const py = t.y * tileSize;
if (t.isInvisiblePaywall) {
chunkCtx.fillStyle = '#7c2d12';
} else if (t.isWalkable) {
chunkCtx.fillStyle = '#1d4ed8';
} else {
chunkCtx.fillStyle = '#334155';
}
chunkCtx.fillRect(px, py, tileSize, tileSize);
}
chunkCtx.strokeStyle = 'rgba(148,163,184,0.16)';
chunkCtx.lineWidth = 1;
for (let x = 0; x <= currentChunk.width; x++) {
chunkCtx.beginPath();
chunkCtx.moveTo(x * tileSize + 0.5, 0);
chunkCtx.lineTo(x * tileSize + 0.5, drawH);
chunkCtx.stroke();
}
for (let y = 0; y <= currentChunk.height; y++) {
chunkCtx.beginPath();
chunkCtx.moveTo(0, y * tileSize + 0.5);
chunkCtx.lineTo(drawW, y * tileSize + 0.5);
chunkCtx.stroke();
}
for (const o of currentObjects) {
const px = o.x * tileSize + tileSize / 2;
const py = o.y * tileSize + tileSize / 2;
chunkCtx.fillStyle = '#f59e0b';
chunkCtx.beginPath();
chunkCtx.arc(px, py, Math.max(2, tileSize * 0.25), 0, Math.PI * 2);
chunkCtx.fill();
}
for (const n of currentNpcs) {
const px = n.x * tileSize + tileSize / 2;
const py = n.y * tileSize + tileSize / 2;
chunkCtx.fillStyle = '#22c55e';
chunkCtx.beginPath();
chunkCtx.rect(px - Math.max(2, tileSize * 0.2), py - Math.max(2, tileSize * 0.2), Math.max(4, tileSize * 0.4), Math.max(4, tileSize * 0.4));
chunkCtx.fill();
}
const mode = document.getElementById('paintMode').value;
document.getElementById('eraseTargetWrap').classList.toggle('hidden', mode !== 'erase');
}
function canvasTile(e) {
if (!currentChunk) return null;
const rect = chunkCanvas.getBoundingClientRect();
const scaleX = chunkCanvas.width / rect.width;
const scaleY = chunkCanvas.height / rect.height;
const cx = (e.clientX - rect.left) * scaleX;
const cy = (e.clientY - rect.top) * scaleY;
const tileSize = Math.max(6, Math.floor(Math.min(chunkCanvas.width / currentChunk.width, chunkCanvas.height / currentChunk.height)));
const x = Math.floor(cx / tileSize);
const y = Math.floor(cy / tileSize);
if (x < 0 || y < 0 || x >= currentChunk.width || y >= currentChunk.height) return null;
return { x, y };
}
async function handleChunkPaint(e) {
const pos = canvasTile(e);
if (!pos) return;
const s = selection();
const mode = document.getElementById('paintMode').value;
if (mode === 'tile') {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
const isWalkable = document.getElementById('isWalkable').checked;
const isInvisiblePaywall = document.getElementById('isInvisiblePaywall').checked;
const data = await postJson('/admin/worldeditor?handler=UpsertTile', {
...s,
x: pos.x,
y: pos.y,
sheetId,
frameIndex,
isWalkable,
isInvisiblePaywall
});
if (data.success) {
currentChunk.version = data.chunkVersion;
currentTiles.set(key(pos.x, pos.y), {
x: pos.x, y: pos.y, sheetId, frameIndex, isWalkable, isInvisiblePaywall
});
}
} else if (mode === 'object') {
const objectDefinitionId = parseInt(document.getElementById('objectDefinitionId').value, 10) || 0;
const data = await postJson('/admin/worldeditor?handler=UpsertObject', {
...s,
objectDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0
});
if (data.success) {
currentChunk.version = data.chunkVersion;
const idx = currentObjects.findIndex(o => o.id === data.op.id);
if (idx >= 0) currentObjects[idx] = { ...currentObjects[idx], ...data.op };
else currentObjects.push(data.op);
}
} else if (mode === 'npc') {
const npcDefinitionId = parseInt(document.getElementById('npcDefinitionId').value, 10) || 0;
const data = await postJson('/admin/worldeditor?handler=UpsertNpc', {
...s,
npcDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0
});
if (data.success) {
currentChunk.version = data.chunkVersion;
const idx = currentNpcs.findIndex(n => n.id === data.op.id);
if (idx >= 0) currentNpcs[idx] = { ...currentNpcs[idx], ...data.op };
else currentNpcs.push(data.op);
}
} else if (mode === 'erase') {
const eraseTarget = document.getElementById('eraseTarget').value;
if (eraseTarget === 'tile') {
const data = await postJson('/admin/worldeditor?handler=RemoveTile', { ...s, x: pos.x, y: pos.y });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentTiles.delete(key(pos.x, pos.y));
}
} else if (eraseTarget === 'object') {
const hit = currentObjects.find(o => o.x === pos.x && o.y === pos.y);
if (hit) {
const data = await postJson('/admin/worldeditor?handler=RemoveObject', { ...s, id: hit.id });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentObjects = currentObjects.filter(o => o.id !== hit.id);
}
}
} else if (eraseTarget === 'npc') {
const hit = currentNpcs.find(n => n.x === pos.x && n.y === pos.y);
if (hit) {
const data = await postJson('/admin/worldeditor?handler=RemoveNpc', { ...s, id: hit.id });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentNpcs = currentNpcs.filter(n => n.id !== hit.id);
}
}
}
}
renderChunk();
loadZone();
}
function onSheetChanged() {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
document.getElementById('tileDefLink').href = `/admin/tilemaps/tiles/edit?sheetId=${sheetId}&frameIndex=${frameIndex}`;
}
document.getElementById('frameIndex').addEventListener('input', onSheetChanged);
chunkCanvas.addEventListener('click', handleChunkPaint);
zoneCanvas.addEventListener('click', (e) => {
if (!currentRegion) return;
const rect = zoneCanvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / (rect.width / currentRegion.chunksPerZoneX));
const y = Math.floor((e.clientY - rect.top) / (rect.height / currentRegion.chunksPerZoneY));
document.getElementById('chunkX').value = x;
document.getElementById('chunkY').value = y;
renderZoneMap();
});
regionCanvas.addEventListener('click', (e) => {
if (!currentRegion) return;
const rect = regionCanvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / (rect.width / currentRegion.zonesX));
const y = Math.floor((e.clientY - rect.top) / (rect.height / currentRegion.zonesY));
document.getElementById('zoneX').value = x;
document.getElementById('zoneY').value = y;
renderRegionMap();
loadZone();
});
initSelectors();
loadRegion().then(loadChunk);
</script>
}
@@ -0,0 +1,624 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace GameServices.Admin.Pages.WorldEditor;
public class IndexModel : AdminPageModel
{
private readonly GameDbContext _db;
public IndexModel(GameDbContext db)
{
_db = db;
}
public List<WorldRegion> Regions { get; set; } = new();
public List<TileMapSheet> TileSheets { get; set; } = new();
public List<DungeonObjectDefinition> ObjectDefinitions { get; set; } = new();
public List<DungeonNpcDefinition> NpcDefinitions { get; set; } = new();
public int SelectedRegionId { get; set; }
public int SelectedZoneX { get; set; }
public int SelectedZoneY { get; set; }
public int SelectedChunkX { get; set; }
public int SelectedChunkY { get; set; }
public async Task OnGetAsync(int? regionId, int zoneX = 0, int zoneY = 0, int chunkX = 0, int chunkY = 0)
{
await EnsureDefaultRegionAsync();
Regions = await _db.WorldRegions
.Where(r => r.IsEnabled)
.OrderBy(r => r.Id)
.ToListAsync();
var selected = Regions.FirstOrDefault(r => r.Id == regionId) ?? Regions.First();
SelectedRegionId = selected.Id;
SelectedZoneX = Math.Clamp(zoneX, 0, Math.Max(0, selected.ZonesPerRegionX - 1));
SelectedZoneY = Math.Clamp(zoneY, 0, Math.Max(0, selected.ZonesPerRegionY - 1));
SelectedChunkX = Math.Clamp(chunkX, 0, Math.Max(0, selected.ChunksPerZoneX - 1));
SelectedChunkY = Math.Clamp(chunkY, 0, Math.Max(0, selected.ChunksPerZoneY - 1));
await EnsureZonesAsync(selected);
TileSheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.OrderBy(s => s.Name)
.ToListAsync();
ObjectDefinitions = await _db.DungeonObjects
.Where(o => o.IsEnabled)
.OrderBy(o => o.Name)
.ToListAsync();
NpcDefinitions = await _db.DungeonNpcDefinitions
.Where(n => n.IsEnabled)
.OrderBy(n => n.Name)
.ToListAsync();
}
public async Task<IActionResult> OnGetRegionAsync(int regionId)
{
var region = await _db.WorldRegions.FirstOrDefaultAsync(r => r.Id == regionId && r.IsEnabled);
if (region == null)
{
return new JsonResult(new { success = false, error = "region_not_found" }) { StatusCode = 404 };
}
await EnsureZonesAsync(region);
var zones = await _db.WorldZones
.Where(z => z.RegionId == region.Id && z.IsEnabled)
.OrderBy(z => z.ZoneY).ThenBy(z => z.ZoneX)
.ToListAsync();
var zoneIds = zones.Select(z => z.Id).ToList();
var chunkCounts = await _db.WorldChunks
.Where(c => zoneIds.Contains(c.WorldZoneId))
.GroupBy(c => c.WorldZoneId)
.Select(g => new { ZoneId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.ZoneId, x => x.Count);
return new JsonResult(new
{
success = true,
region = new
{
id = region.Id,
name = region.Name,
zonesX = region.ZonesPerRegionX,
zonesY = region.ZonesPerRegionY,
chunksPerZoneX = region.ChunksPerZoneX,
chunksPerZoneY = region.ChunksPerZoneY,
chunkWidthTiles = region.ChunkWidthTiles,
chunkHeightTiles = region.ChunkHeightTiles
},
zones = zones.Select(z => new
{
id = z.Id,
zoneX = z.ZoneX,
zoneY = z.ZoneY,
name = z.Name,
editedChunkCount = chunkCounts.GetValueOrDefault(z.Id)
})
});
}
public async Task<IActionResult> OnGetZoneAsync(int regionId, int zoneX, int zoneY)
{
var region = await _db.WorldRegions.FirstOrDefaultAsync(r => r.Id == regionId && r.IsEnabled);
if (region == null)
{
return new JsonResult(new { success = false, error = "region_not_found" }) { StatusCode = 404 };
}
if (!IsInside(region.ZonesPerRegionX, region.ZonesPerRegionY, zoneX, zoneY))
{
return new JsonResult(new { success = false, error = "zone_out_of_bounds" }) { StatusCode = 400 };
}
await EnsureZonesAsync(region);
var zone = await _db.WorldZones.FirstAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY);
var chunks = await _db.WorldChunks
.Where(c => c.WorldZoneId == zone.Id)
.Select(c => new { c.ChunkX, c.ChunkY, c.Version })
.ToListAsync();
return new JsonResult(new
{
success = true,
zone = new
{
id = zone.Id,
regionId,
zoneX,
zoneY,
chunksPerZoneX = region.ChunksPerZoneX,
chunksPerZoneY = region.ChunksPerZoneY
},
chunks
});
}
public async Task<IActionResult> OnGetChunkAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Zone == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var chunk = locate.Chunk;
var region = locate.Region;
var tiles = await _db.WorldChunkTiles
.Where(t => t.WorldChunkId == chunk.Id)
.OrderBy(t => t.TileY).ThenBy(t => t.TileX)
.Select(t => new
{
id = t.Id,
x = t.TileX,
y = t.TileY,
sheetId = t.SheetId,
frameIndex = t.FrameIndex,
isWalkable = t.IsWalkable,
isInvisiblePaywall = t.IsInvisiblePaywall
})
.ToListAsync();
var objects = await _db.WorldChunkObjects
.Include(o => o.ObjectDefinition)
.Where(o => o.WorldChunkId == chunk.Id)
.OrderBy(o => o.TileY).ThenBy(o => o.TileX)
.Select(o => new
{
id = o.Id,
x = o.TileX,
y = o.TileY,
objectDefinitionId = o.ObjectDefinitionId,
objectName = o.ObjectDefinition != null ? o.ObjectDefinition.Name : $"Object {o.ObjectDefinitionId}",
rotation = o.Rotation,
metadataJson = o.MetadataJson
})
.ToListAsync();
var npcs = await _db.WorldChunkNpcSpawns
.Include(n => n.NpcDefinition)
.Where(n => n.WorldChunkId == chunk.Id)
.OrderBy(n => n.TileY).ThenBy(n => n.TileX)
.Select(n => new
{
id = n.Id,
x = n.TileX,
y = n.TileY,
npcDefinitionId = n.NpcDefinitionId,
npcName = n.NpcDefinition != null ? n.NpcDefinition.Name : $"NPC {n.NpcDefinitionId}",
rotation = n.Rotation,
metadataJson = n.MetadataJson
})
.ToListAsync();
return new JsonResult(new
{
success = true,
chunk = new
{
id = chunk.Id,
regionId,
zoneX,
zoneY,
chunkX,
chunkY,
version = chunk.Version,
width = region.ChunkWidthTiles,
height = region.ChunkHeightTiles
},
tiles,
objects,
npcs
});
}
public async Task<IActionResult> OnPostUpsertTileAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY,
int x,
int y,
int sheetId,
int frameIndex,
bool isWalkable,
bool isInvisiblePaywall)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
if (!IsInside(locate.Region.ChunkWidthTiles, locate.Region.ChunkHeightTiles, x, y))
{
return new JsonResult(new { success = false, error = "tile_out_of_bounds" }) { StatusCode = 400 };
}
var sheetExists = await _db.TileMapSheets.AnyAsync(s => s.Id == sheetId && s.IsEnabled);
if (!sheetExists)
{
return new JsonResult(new { success = false, error = "sheet_not_found" }) { StatusCode = 404 };
}
var tile = await _db.WorldChunkTiles
.FirstOrDefaultAsync(t => t.WorldChunkId == locate.Chunk.Id && t.TileX == x && t.TileY == y);
if (tile == null)
{
tile = new WorldChunkTile
{
WorldChunkId = locate.Chunk.Id,
TileX = x,
TileY = y
};
_db.WorldChunkTiles.Add(tile);
}
tile.SheetId = sheetId;
tile.FrameIndex = frameIndex;
tile.IsWalkable = isWalkable;
tile.IsInvisiblePaywall = isInvisiblePaywall;
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new
{
type = "tile_upsert",
x,
y,
sheetId,
frameIndex,
isWalkable,
isInvisiblePaywall
}
});
}
public async Task<IActionResult> OnPostRemoveTileAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, int x, int y)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var tile = await _db.WorldChunkTiles
.FirstOrDefaultAsync(t => t.WorldChunkId == locate.Chunk.Id && t.TileX == x && t.TileY == y);
if (tile != null)
{
_db.WorldChunkTiles.Remove(tile);
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
}
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new { type = "tile_remove", x, y }
});
}
public async Task<IActionResult> OnPostUpsertObjectAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY,
long? id,
int objectDefinitionId,
int x,
int y,
int rotation = 0,
string? metadataJson = null)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
if (!IsInside(locate.Region.ChunkWidthTiles, locate.Region.ChunkHeightTiles, x, y))
{
return new JsonResult(new { success = false, error = "tile_out_of_bounds" }) { StatusCode = 400 };
}
var objectExists = await _db.DungeonObjects.AnyAsync(o => o.Id == objectDefinitionId && o.IsEnabled);
if (!objectExists)
{
return new JsonResult(new { success = false, error = "object_definition_not_found" }) { StatusCode = 404 };
}
WorldChunkObject obj;
if (id.HasValue)
{
obj = await _db.WorldChunkObjects.FirstOrDefaultAsync(o => o.Id == id.Value && o.WorldChunkId == locate.Chunk.Id)
?? new WorldChunkObject { WorldChunkId = locate.Chunk.Id };
if (obj.Id == 0)
{
_db.WorldChunkObjects.Add(obj);
}
}
else
{
obj = new WorldChunkObject { WorldChunkId = locate.Chunk.Id };
_db.WorldChunkObjects.Add(obj);
}
obj.ObjectDefinitionId = objectDefinitionId;
obj.TileX = x;
obj.TileY = y;
obj.Rotation = rotation;
obj.MetadataJson = string.IsNullOrWhiteSpace(metadataJson) ? null : metadataJson.Trim();
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new
{
type = "object_upsert",
id = obj.Id,
x = obj.TileX,
y = obj.TileY,
objectDefinitionId = obj.ObjectDefinitionId,
rotation = obj.Rotation,
metadataJson = obj.MetadataJson
}
});
}
public async Task<IActionResult> OnPostRemoveObjectAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long id)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var obj = await _db.WorldChunkObjects.FirstOrDefaultAsync(o => o.Id == id && o.WorldChunkId == locate.Chunk.Id);
if (obj != null)
{
_db.WorldChunkObjects.Remove(obj);
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
}
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new { type = "object_remove", id }
});
}
public async Task<IActionResult> OnPostUpsertNpcAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY,
long? id,
int npcDefinitionId,
int x,
int y,
int rotation = 0,
string? metadataJson = null)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
if (!IsInside(locate.Region.ChunkWidthTiles, locate.Region.ChunkHeightTiles, x, y))
{
return new JsonResult(new { success = false, error = "tile_out_of_bounds" }) { StatusCode = 400 };
}
var npcExists = await _db.DungeonNpcDefinitions.AnyAsync(n => n.Id == npcDefinitionId && n.IsEnabled);
if (!npcExists)
{
return new JsonResult(new { success = false, error = "npc_definition_not_found" }) { StatusCode = 404 };
}
WorldChunkNpcSpawn npc;
if (id.HasValue)
{
npc = await _db.WorldChunkNpcSpawns.FirstOrDefaultAsync(n => n.Id == id.Value && n.WorldChunkId == locate.Chunk.Id)
?? new WorldChunkNpcSpawn { WorldChunkId = locate.Chunk.Id };
if (npc.Id == 0)
{
_db.WorldChunkNpcSpawns.Add(npc);
}
}
else
{
npc = new WorldChunkNpcSpawn { WorldChunkId = locate.Chunk.Id };
_db.WorldChunkNpcSpawns.Add(npc);
}
npc.NpcDefinitionId = npcDefinitionId;
npc.TileX = x;
npc.TileY = y;
npc.Rotation = rotation;
npc.MetadataJson = string.IsNullOrWhiteSpace(metadataJson) ? null : metadataJson.Trim();
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new
{
type = "npc_upsert",
id = npc.Id,
x = npc.TileX,
y = npc.TileY,
npcDefinitionId = npc.NpcDefinitionId,
rotation = npc.Rotation,
metadataJson = npc.MetadataJson
}
});
}
public async Task<IActionResult> OnPostRemoveNpcAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long id)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var npc = await _db.WorldChunkNpcSpawns.FirstOrDefaultAsync(n => n.Id == id && n.WorldChunkId == locate.Chunk.Id);
if (npc != null)
{
_db.WorldChunkNpcSpawns.Remove(npc);
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
}
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new { type = "npc_remove", id }
});
}
private async Task EnsureDefaultRegionAsync()
{
if (await _db.WorldRegions.AnyAsync())
return;
_db.WorldRegions.Add(new WorldRegion
{
Name = "Default Region",
ZonesPerRegionX = 4,
ZonesPerRegionY = 4,
ChunksPerZoneX = 8,
ChunksPerZoneY = 8,
ChunkWidthTiles = 64,
ChunkHeightTiles = 64,
IsEnabled = true,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
});
await _db.SaveChangesAsync();
}
private async Task EnsureZonesAsync(WorldRegion region)
{
var existing = await _db.WorldZones
.Where(z => z.RegionId == region.Id)
.Select(z => new { z.ZoneX, z.ZoneY })
.ToListAsync();
var existingSet = existing.Select(z => $"{z.ZoneX}:{z.ZoneY}").ToHashSet();
var now = DateTime.UtcNow;
var added = false;
for (var y = 0; y < region.ZonesPerRegionY; y++)
{
for (var x = 0; x < region.ZonesPerRegionX; x++)
{
if (existingSet.Contains($"{x}:{y}"))
continue;
_db.WorldZones.Add(new WorldZone
{
RegionId = region.Id,
ZoneX = x,
ZoneY = y,
Name = $"Zone {x},{y}",
IsEnabled = true,
CreatedAt = now,
UpdatedAt = now
});
added = true;
}
}
if (added)
{
await _db.SaveChangesAsync();
}
}
private async Task<(bool Success, string? Error, WorldRegion? Region, WorldZone? Zone, WorldChunk? Chunk)> GetOrCreateChunkAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY)
{
var region = await _db.WorldRegions.FirstOrDefaultAsync(r => r.Id == regionId && r.IsEnabled);
if (region == null)
return (false, "region_not_found", null, null, null);
if (!IsInside(region.ZonesPerRegionX, region.ZonesPerRegionY, zoneX, zoneY))
return (false, "zone_out_of_bounds", region, null, null);
if (!IsInside(region.ChunksPerZoneX, region.ChunksPerZoneY, chunkX, chunkY))
return (false, "chunk_out_of_bounds", region, null, null);
await EnsureZonesAsync(region);
var zone = await _db.WorldZones
.FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled);
if (zone == null)
return (false, "zone_not_found", region, null, null);
var chunk = await _db.WorldChunks
.FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == chunkX && c.ChunkY == chunkY);
if (chunk == null)
{
chunk = new WorldChunk
{
WorldZoneId = zone.Id,
ChunkX = chunkX,
ChunkY = chunkY,
Version = 1,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
_db.WorldChunks.Add(chunk);
await _db.SaveChangesAsync();
}
return (true, null, region, zone, chunk);
}
private static bool IsInside(int width, int height, int x, int y)
{
return x >= 0 && y >= 0 && x < width && y < height;
}
}
+2 -1
View File
@@ -24,7 +24,8 @@ public sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<Gam
}
var opts = new DbContextOptionsBuilder<GameDbContext>()
.UseMySql(cs, ServerVersion.AutoDetect(cs))
// Keep design-time independent of live DB connectivity.
.UseMySql(cs, new MySqlServerVersion(new Version(8, 0, 36)))
.Options;
return new GameDbContext(opts);
+8
View File
@@ -79,6 +79,14 @@ public sealed class GameDbContext : DbContext
public DbSet<DungeonNpcDialogTree> DungeonNpcDialogTrees => Set<DungeonNpcDialogTree>();
public DbSet<DungeonNpcDialogNode> DungeonNpcDialogNodes => Set<DungeonNpcDialogNode>();
public DbSet<DungeonNpcDialogOption> DungeonNpcDialogOptions => Set<DungeonNpcDialogOption>();
// Overworld system
public DbSet<WorldRegion> WorldRegions => Set<WorldRegion>();
public DbSet<WorldZone> WorldZones => Set<WorldZone>();
public DbSet<WorldChunk> WorldChunks => Set<WorldChunk>();
public DbSet<WorldChunkTile> WorldChunkTiles => Set<WorldChunkTile>();
public DbSet<WorldChunkObject> WorldChunkObjects => Set<WorldChunkObject>();
public DbSet<WorldChunkNpcSpawn> WorldChunkNpcSpawns => Set<WorldChunkNpcSpawn>();
protected override void OnModelCreating(ModelBuilder b)
{
+198
View File
@@ -0,0 +1,198 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DataServer.Data.Entities;
[Table("world_regions")]
public class WorldRegion
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(64)]
public string Name { get; set; } = "";
public int ZonesPerRegionX { get; set; } = 4;
public int ZonesPerRegionY { get; set; } = 4;
public int ChunksPerZoneX { get; set; } = 8;
public int ChunksPerZoneY { get; set; } = 8;
public int ChunkWidthTiles { get; set; } = 64;
public int ChunkHeightTiles { get; set; } = 64;
public bool IsEnabled { get; set; } = true;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
[Table("world_zones")]
public class WorldZone
{
[Key]
public long Id { get; set; }
public int RegionId { get; set; }
[ForeignKey(nameof(RegionId))]
public WorldRegion? Region { get; set; }
public int ZoneX { get; set; }
public int ZoneY { get; set; }
[MaxLength(64)]
public string Name { get; set; } = "";
public bool IsEnabled { get; set; } = true;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
[Table("world_chunks")]
public class WorldChunk
{
[Key]
public long Id { get; set; }
public long WorldZoneId { get; set; }
[ForeignKey(nameof(WorldZoneId))]
public WorldZone? Zone { get; set; }
public int ChunkX { get; set; }
public int ChunkY { get; set; }
public long Version { get; set; } = 1;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
[Table("world_chunk_tiles")]
public class WorldChunkTile
{
[Key]
public long Id { get; set; }
public long WorldChunkId { get; set; }
[ForeignKey(nameof(WorldChunkId))]
public WorldChunk? Chunk { get; set; }
public int TileX { get; set; }
public int TileY { get; set; }
public int SheetId { get; set; }
public int FrameIndex { get; set; }
public bool IsWalkable { get; set; } = true;
public bool IsInvisiblePaywall { get; set; } = false;
}
[Table("world_chunk_objects")]
public class WorldChunkObject
{
[Key]
public long Id { get; set; }
public long WorldChunkId { get; set; }
[ForeignKey(nameof(WorldChunkId))]
public WorldChunk? Chunk { get; set; }
public int ObjectDefinitionId { get; set; }
[ForeignKey(nameof(ObjectDefinitionId))]
public DungeonObjectDefinition? ObjectDefinition { get; set; }
public int TileX { get; set; }
public int TileY { get; set; }
public int Rotation { get; set; }
[MaxLength(1024)]
public string? MetadataJson { get; set; }
}
[Table("world_chunk_npc_spawns")]
public class WorldChunkNpcSpawn
{
[Key]
public long Id { get; set; }
public long WorldChunkId { get; set; }
[ForeignKey(nameof(WorldChunkId))]
public WorldChunk? Chunk { get; set; }
public int NpcDefinitionId { get; set; }
[ForeignKey(nameof(NpcDefinitionId))]
public DungeonNpcDefinition? NpcDefinition { get; set; }
public int TileX { get; set; }
public int TileY { get; set; }
public int Rotation { get; set; }
[MaxLength(1024)]
public string? MetadataJson { get; set; }
}
public sealed class WorldRegionConfig : IEntityTypeConfiguration<WorldRegion>
{
public void Configure(EntityTypeBuilder<WorldRegion> e)
{
e.HasIndex(x => x.Name).IsUnique();
}
}
public sealed class WorldZoneConfig : IEntityTypeConfiguration<WorldZone>
{
public void Configure(EntityTypeBuilder<WorldZone> e)
{
e.HasIndex(x => new { x.RegionId, x.ZoneX, x.ZoneY }).IsUnique();
e.HasOne(x => x.Region)
.WithMany()
.HasForeignKey(x => x.RegionId)
.OnDelete(DeleteBehavior.Cascade);
}
}
public sealed class WorldChunkConfig : IEntityTypeConfiguration<WorldChunk>
{
public void Configure(EntityTypeBuilder<WorldChunk> e)
{
e.HasIndex(x => new { x.WorldZoneId, x.ChunkX, x.ChunkY }).IsUnique();
e.HasOne(x => x.Zone)
.WithMany()
.HasForeignKey(x => x.WorldZoneId)
.OnDelete(DeleteBehavior.Cascade);
}
}
public sealed class WorldChunkTileConfig : IEntityTypeConfiguration<WorldChunkTile>
{
public void Configure(EntityTypeBuilder<WorldChunkTile> e)
{
e.HasIndex(x => new { x.WorldChunkId, x.TileX, x.TileY }).IsUnique();
e.HasOne(x => x.Chunk)
.WithMany()
.HasForeignKey(x => x.WorldChunkId)
.OnDelete(DeleteBehavior.Cascade);
}
}
public sealed class WorldChunkObjectConfig : IEntityTypeConfiguration<WorldChunkObject>
{
public void Configure(EntityTypeBuilder<WorldChunkObject> e)
{
e.HasIndex(x => new { x.WorldChunkId, x.TileX, x.TileY, x.ObjectDefinitionId });
e.HasOne(x => x.Chunk)
.WithMany()
.HasForeignKey(x => x.WorldChunkId)
.OnDelete(DeleteBehavior.Cascade);
}
}
public sealed class WorldChunkNpcSpawnConfig : IEntityTypeConfiguration<WorldChunkNpcSpawn>
{
public void Configure(EntityTypeBuilder<WorldChunkNpcSpawn> e)
{
e.HasIndex(x => new { x.WorldChunkId, x.TileX, x.TileY, x.NpcDefinitionId });
e.HasOne(x => x.Chunk)
.WithMany()
.HasForeignKey(x => x.WorldChunkId)
.OnDelete(DeleteBehavior.Cascade);
}
}