Add portrait settings support to school creation and update related API and UI components. Enhance error handling for invalid presets and ensure proper cloning of settings. Update tests to validate new functionality.
ci / server (push) Failing after 3m40s
ci / client (push) Failing after 14s

This commit is contained in:
Leonid Pershin
2026-08-20 08:17:58 +03:00
parent db95de0ddf
commit 9d96108516
20 changed files with 293 additions and 40 deletions
+17 -1
View File
@@ -48,6 +48,20 @@ internal static class SchoolEndpoints
GameCommandQueue commands,
CancellationToken cancellationToken) =>
{
SwarmUiConfigFile? portraitSettings = null;
if (request.PortraitSettings is not null)
{
try
{
request.PortraitSettings.Validate();
portraitSettings = SwarmUiConfigFile.Clone(request.PortraitSettings);
}
catch (InvalidOperationException ex)
{
return Problem(StatusCodes.Status400BadRequest, "invalid-portrait-settings", ex.Message);
}
}
var command = new GameCommand.CreateSchool(
request.Name ?? string.Empty,
DateTime.SpecifyKind(request.StartDate, DateTimeKind.Utc),
@@ -56,6 +70,7 @@ internal static class SchoolEndpoints
request.CountryId,
request.NativeLanguage,
request.Seed,
portraitSettings,
NewCompletion<SchoolCreationOutcome>());
commands.Enqueue(command);
@@ -802,7 +817,8 @@ internal sealed record CreateSchoolRequest(
MapLayout? Map,
string? CountryId,
string? NativeLanguage,
int? Seed);
int? Seed,
SwarmUiConfigFile? PortraitSettings);
internal sealed record SchoolResponse(
int Id,
@@ -8,6 +8,7 @@ internal static class SettingsEndpoints
{
var settings = endpoints.MapGroup("/api/settings");
// Default template copied into a new school. Living schools generate from their own copy.
settings.MapGet("/swarmui", (SwarmUiSettingsStore store) => Results.Ok(store.Current))
.WithName("GetSwarmUiSettings");
+1
View File
@@ -19,6 +19,7 @@ internal abstract record GameCommand
string? CountryId,
string? NativeLanguage,
int? Seed,
SwarmUiConfigFile? PortraitSettings,
TaskCompletionSource<SchoolCreationOutcome> Result) : GameCommand;
internal sealed record DeleteSchool(int SchoolId, TaskCompletionSource<bool> Result) : GameCommand;
+35 -3
View File
@@ -20,6 +20,7 @@ internal sealed class GameLoopService(
GameMetrics metrics,
SchoolStore store,
ModContent mods,
SwarmUiSettingsStore swarmSettings,
ILoggerFactory loggerFactory,
ILogger<GameLoopService> logger) : BackgroundService
{
@@ -61,6 +62,20 @@ internal sealed class GameLoopService(
}
}
/// <summary>Create-time SwarmUI copy for this living school, or null on older saves.</summary>
public SwarmUiConfigFile? PortraitSettingsOf(int schoolId)
{
foreach (var worker in Volatile.Read(ref _publishedWorkers))
{
if (worker.Id == schoolId)
{
return worker.PortraitSettings;
}
}
return null;
}
/// <summary>
/// Menu-style read of one school's published roster and frozen catalog. Does not post to the
/// mailbox — the list is HTTP over a snapshot, the same way the menu reads clocks.
@@ -414,7 +429,21 @@ internal sealed class GameLoopService(
var nativeLanguage = NativeLanguages.Pick(country.Names, seed, command.NativeLanguage, rollIfOmitted: true);
var climatePresetId = CountryClimate.Pick(country, seed, rollIfOmitted: true);
var worker = SpawnWorker(id, normalized, command.StartDate, running: true, ClockSpeed.DefaultIndex, isNew: true, packIds, command.Map, countryId, climatePresetId, nativeLanguage, seed);
var portrait = SwarmUiConfigFile.Clone(command.PortraitSettings ?? swarmSettings.Current);
var worker = SpawnWorker(
id,
normalized,
command.StartDate,
running: true,
ClockSpeed.DefaultIndex,
isNew: true,
packIds,
command.Map,
countryId,
climatePresetId,
nativeLanguage,
seed,
portraitSettings: portrait);
Track(worker);
worker.Start();
@@ -613,7 +642,8 @@ internal sealed class GameLoopService(
save.NativeLanguage,
createSeed: null,
save.Presence,
save.DressRules);
save.DressRules,
save.PortraitSettings);
worker.Start();
try
@@ -669,7 +699,8 @@ internal sealed class GameLoopService(
string? nativeLanguage,
int? createSeed = null,
IReadOnlyList<PresenceSnapshot>? presence = null,
SchoolDressRules? dressRules = null) =>
SchoolDressRules? dressRules = null,
SwarmUiConfigFile? portraitSettings = null) =>
new(
id,
name,
@@ -685,6 +716,7 @@ internal sealed class GameLoopService(
createSeed,
presence,
dressRules,
portraitSettings,
_options,
clients,
metrics,
+6 -2
View File
@@ -6,6 +6,7 @@ internal sealed class PortraitService(
SchoolStore store,
SwarmUiClient swarm,
SwarmUiSettingsStore settingsStore,
GameLoopService loop,
GameCommandQueue commands,
ILogger<PortraitService> logger)
{
@@ -74,7 +75,7 @@ internal sealed class PortraitService(
return PortraitPromptBuildResult.UnknownSchool;
}
var profile = settingsStore.Resolve(outcome.Card.Age, kind);
var profile = ConfigFor(schoolId).Resolve(outcome.Card.Age, kind);
var (positive, negative) = PortraitPromptBuilder.Build(outcome.Card, profile, kind, resolved);
return PortraitPromptBuildResult.Succeeded(
kind,
@@ -122,7 +123,7 @@ internal sealed class PortraitService(
return PortraitGenerationResult.UnknownSchool;
}
var profile = settingsStore.Resolve(outcome.Card.Age, kind);
var profile = ConfigFor(schoolId).Resolve(outcome.Card.Age, kind);
var (positive, negative) = PortraitPromptBuilder.Build(outcome.Card, profile, kind, promptExtra);
try
@@ -155,6 +156,9 @@ internal sealed class PortraitService(
}
}
private SwarmUiConfigFile ConfigFor(int schoolId) =>
loop.PortraitSettingsOf(schoolId) ?? settingsStore.Current;
private async Task<PersonCardResult> LookupPersonAsync(
int schoolId,
string personId,
+4
View File
@@ -35,6 +35,9 @@ internal sealed class SchoolSave
public IReadOnlyList<PresenceSnapshot>? Presence { get; init; }
public SchoolDressRules? DressRules { get; init; }
/// <summary>Portrait presets copied at create. Generation reads this, not the global template.</summary>
public SwarmUiConfigFile? PortraitSettings { get; init; }
}
/// <summary>Allocates school ids that survive a process restart.</summary>
@@ -172,6 +175,7 @@ internal sealed class SchoolStore
NativeLanguage = save.NativeLanguage,
Presence = save.Presence,
DressRules = save.DressRules,
PortraitSettings = save.PortraitSettings,
});
}
catch (Exception ex)
+22
View File
@@ -38,6 +38,7 @@ internal sealed class SchoolWorker
private readonly int? _createSeed;
private readonly IReadOnlyList<PresenceSnapshot>? _savedPresence;
private readonly SchoolDressRules? _savedDressRules;
private readonly SwarmUiConfigFile? _portraitSettings;
private readonly Action<int> _onFailed;
private readonly int _id;
@@ -74,6 +75,7 @@ internal sealed class SchoolWorker
int? createSeed,
IReadOnlyList<PresenceSnapshot>? savedPresence,
SchoolDressRules? savedDressRules,
SwarmUiConfigFile? portraitSettings,
SimulationOptions options,
ClientRegistry clients,
GameMetrics metrics,
@@ -96,6 +98,7 @@ internal sealed class SchoolWorker
_createSeed = createSeed;
_savedPresence = savedPresence;
_savedDressRules = savedDressRules;
_portraitSettings = portraitSettings;
_options = options;
_clients = clients;
_metrics = metrics;
@@ -113,6 +116,9 @@ internal sealed class SchoolWorker
/// <summary>Last clock the worker published. Menu requests read this; the live school stays here.</summary>
public SchoolState Snapshot => Volatile.Read(ref _snapshot);
/// <summary>Presets copied at create. Null on older saves — generation then uses the global template.</summary>
public SwarmUiConfigFile? PortraitSettings => _portraitSettings;
/// <summary>Last roster composition. Published like <see cref="Snapshot"/>; needs live on entities.</summary>
public Roster? RosterSnapshot => Volatile.Read(ref _rosterSnapshot);
@@ -1000,6 +1006,21 @@ internal sealed class SchoolWorker
return generated;
}
private static void RequireKnownApparel(DefCatalog catalog, Roster roster, ApplicantPool applicants)
{
foreach (var person in roster.People.Concat(applicants.Applicants.Select(row => row.Person)))
{
foreach (var item in person.Items)
{
if (!catalog.Things.TryGetValue(item.Def, out var def) || def.Abstract)
{
throw new SchoolContentUnavailableException(
$"School roster references unusable thing '{item.Def}'.");
}
}
}
}
private static string? ResolveCountryId(DefCatalog catalog, string? requested)
{
if (string.IsNullOrWhiteSpace(requested))
@@ -1055,6 +1076,7 @@ internal sealed class SchoolWorker
NativeLanguage = _nativeLanguage,
Presence = school.CapturePresence(),
DressRules = school.DressRules,
PortraitSettings = _portraitSettings,
});
}
catch (Exception ex)
@@ -233,6 +233,33 @@ internal sealed class SwarmUiConfigFile
Presets = [SwarmUiPresetDefinition.CreateDefault(), SwarmUiPresetDefinition.CreateChild()],
AgeRules = [new SwarmUiAgeRule { MinAge = 6, MaxAge = 11, PresetId = "child" }],
};
public static SwarmUiConfigFile Clone(SwarmUiConfigFile source)
{
var json = JsonSerializer.Serialize(source, CloneJson);
var copy = JsonSerializer.Deserialize<SwarmUiConfigFile>(json, CloneJson) ?? CreateDefault();
copy.Model = null;
copy.Steps = null;
copy.CfgScale = null;
copy.ClipSkip = null;
copy.Sampler = null;
copy.Scheduler = null;
copy.Seed = null;
copy.Positive = null;
copy.Negative = null;
copy.Avatar = null;
copy.Custom = null;
copy.FullBody = null;
copy.NormalizeAfterLoad();
return copy;
}
private static readonly JsonSerializerOptions CloneJson = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
}
internal sealed class SwarmUiPresetDefinition