Skip to content

Fix invalid liege entries in title history #2166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ImperatorToCK3/CK3/Characters/CharacterCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ public void PurgeUnneededCharacters(Title.LandedTitles titles, DynastyCollection
dynasties.FlattenDynastiesWithNoFounders(this, houses, ck3BookmarkDate);

// Clean up title history.
titles.RemoveInvalidHoldersFromHistory(this);
titles.CleanUpHistory(this, ck3BookmarkDate);
}

public void RemoveEmployerIdFromLandedCharacters(Title.LandedTitles titles, Date conversionDate) {
Expand Down
27 changes: 26 additions & 1 deletion ImperatorToCK3/CK3/Titles/LandedTitles.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@
return this.SelectMany(t => t.GetAllHolderIds()).ToImmutableHashSet();
}

public void RemoveInvalidHoldersFromHistory(CharacterCollection characters) {
public void CleanUpHistory(CharacterCollection characters, Date ck3BookmarkDate) {
Logger.Debug("Removing invalid holders from history...");

var validIds = characters.Select(c => c.Id).ToImmutableHashSet();
Expand All @@ -270,6 +270,31 @@
value => value.ToString() is string valStr && valStr != "0" && !validIds.Contains(valStr)
);
}

// Remove liege entries that are not valid (liege title is not held at the entry date).
foreach (var title in this) {
if (!title.History.Fields.TryGetValue("liege", out var liegeField)) {
continue;
}

foreach (var (date, entriesList) in liegeField.DateToEntriesDict.ToArray()) {
if (entriesList.Count == 0) {
continue;
}

var lastEntry = entriesList.Last();
var liegeTitleId = lastEntry.Value.ToString();
if (liegeTitleId is null || liegeTitleId == "0") {
continue;
}

if (!TryGetValue(liegeTitleId, out var liegeTitle)) {
liegeField.DateToEntriesDict.Remove(date);
} else if (liegeTitle.GetHolderId(date) == "0") {
liegeField.DateToEntriesDict.Remove(date);
}
}
}
}

public void ImportImperatorCountries(
Expand Down Expand Up @@ -532,168 +557,168 @@
}
}

public void ImportImperatorHoldings(ProvinceCollection ck3Provinces, Imperator.Characters.CharacterCollection irCharacters, Date conversionDate) {
Logger.Info("Importing Imperator holdings...");
var counter = 0;

var highLevelTitlesThatHaveHolders = this
.Where(t => t.Rank >= TitleRank.duchy && t.GetHolderId(conversionDate) != "0")
.ToImmutableList();
var highLevelTitleCapitalBaronyIds = highLevelTitlesThatHaveHolders
.Select(t=>t.CapitalCounty?.CapitalBaronyId ?? t.CapitalBaronyId)
.ToImmutableHashSet();

// Dukes and above should be excluded from having their holdings converted.
// Otherwise, governors with holdings would own parts of other governorships.
var dukeAndAboveIds = highLevelTitlesThatHaveHolders
.Where(t => t.Rank >= TitleRank.duchy)
.Select(t => t.GetHolderId(conversionDate))
.ToImmutableHashSet();

// We exclude baronies that are capitals of duchies and above.
var eligibleBaronies = this
.Where(t => t.Rank == TitleRank.barony)
.Where(b => !highLevelTitleCapitalBaronyIds.Contains(b.Id))
.ToArray();

var countyCapitalBaronies = eligibleBaronies
.Where(b => b.DeJureLiege?.CapitalBaronyId == b.Id)
.OrderBy(b => b.Id)
.ToArray();

var nonCapitalBaronies = eligibleBaronies.Except(countyCapitalBaronies).OrderBy(b => b.Id).ToArray();


// In CK3, a county holder shouldn't own baronies in counties that are not their own.
// This dictionary tracks what counties are held by what characters.
Dictionary<string, HashSet<string>> countiesPerCharacter = []; // characterId -> countyIds

// Evaluate all capital baronies first (we want to distribute counties first, then baronies).
foreach (var barony in countyCapitalBaronies) {
var ck3Province = GetBaronyProvince(barony);
if (ck3Province is null) {
continue;
}

// Skip none holdings and temple holdings.
if (ck3Province.GetHoldingType(conversionDate) is "church_holding" or "none") {
continue;
}

var irProvince = ck3Province.PrimaryImperatorProvince; // TODO: when the holding owner of the primary I:R province is not able to hold the CK3 equivalent, also check the holding owners from secondary source provinces
var ck3Owner = GetEligibleCK3OwnerForImperatorProvince(irProvince);
if (ck3Owner is null) {
continue;
}

var realm = ck3Owner.ImperatorCharacter?.HomeCountry?.CK3Title;
var deFactoLiege = realm;
if (realm is not null) {
var deJureDuchy = barony.DeJureLiege?.DeJureLiege;
if (deJureDuchy is not null && deJureDuchy.GetHolderId(conversionDate) != "0" && deJureDuchy.GetTopRealm(conversionDate) == realm) {
deFactoLiege = deJureDuchy;
} else {
var deJureKingdom = deJureDuchy?.DeJureLiege;
if (deJureKingdom is not null && deJureKingdom.GetHolderId(conversionDate) != "0" && deJureKingdom.GetTopRealm(conversionDate) == realm) {
deFactoLiege = deJureKingdom;
}
}
}

// Barony is a county capital, so set the county holder to the holding owner.
var county = barony.DeJureLiege;
if (county is null) {
Logger.Warn($"County capital barony {barony.Id} has no de jure county!");
continue;
}
county.SetHolder(ck3Owner, conversionDate);
county.SetDeFactoLiege(deFactoLiege, conversionDate);

if (!countiesPerCharacter.TryGetValue(ck3Owner.Id, out var countyIds)) {
countyIds = [];
countiesPerCharacter[ck3Owner.Id] = countyIds;
}
countyIds.Add(county.Id);

++counter;
}

// In CK3, a baron that doesn't own counties can only hold a single barony.
// This dictionary IDs of such barons that already hold a barony.
HashSet<string> baronyHolderIds = [];

// After all possible county capital baronies are distributed, distribute the rest of the eligible baronies.
foreach (var barony in nonCapitalBaronies) {
var ck3Province = GetBaronyProvince(barony);
if (ck3Province is null) {
continue;
}

// Skip none holdings and temple holdings.
if (ck3Province.GetHoldingType(conversionDate) is "church_holding" or "none") {
continue;
}

var irProvince = ck3Province.PrimaryImperatorProvince; // TODO: when the holding owner of the primary I:R province is not able to hold the CK3 equivalent, also check the holding owners from secondary source provinces
var ck3Owner = GetEligibleCK3OwnerForImperatorProvince(irProvince);
if (ck3Owner is null) {
continue;
}
if (baronyHolderIds.Contains(ck3Owner.Id)) {
continue;
}

var county = barony.DeJureLiege;
if (county is null) {
Logger.Warn($"Barony {barony.Id} has no de jure county!");
continue;
}
// A non-capital barony cannot be held by a character that owns a county but not the county the barony is in.
if (countiesPerCharacter.TryGetValue(ck3Owner.Id, out var countyIds) && !countyIds.Contains(county.Id)) {
continue;
}

barony.SetHolder(ck3Owner, conversionDate);
// No need to set de facto liege for baronies, they are tied to counties.

baronyHolderIds.Add(ck3Owner.Id);

++counter;
}
Logger.Info($"Imported {counter} holdings from I:R.");
Logger.IncrementProgress();
return;

Province? GetBaronyProvince(Title barony) {
var ck3ProvinceId = barony.ProvinceId;
if (ck3ProvinceId is null) {
return null;
}
if (!ck3Provinces.TryGetValue(ck3ProvinceId.Value, out var ck3Province)) {
return null;
}
return ck3Province;
}

Character? GetEligibleCK3OwnerForImperatorProvince(Imperator.Provinces.Province? irProvince) {
var holdingOwnerId = irProvince?.HoldingOwnerId;
if (holdingOwnerId is null) {
return null;
}

var irOwner = irCharacters[holdingOwnerId.Value];
var ck3Owner = irOwner.CK3Character;
if (ck3Owner is null) {
return null;
}
if (dukeAndAboveIds.Contains(ck3Owner.Id)) {
return null;
}

return ck3Owner;
}
}

Check notice on line 721 in ImperatorToCK3/CK3/Titles/LandedTitles.cs

View check run for this annotation

codefactor.io / CodeFactor

ImperatorToCK3/CK3/Titles/LandedTitles.cs#L560-L721

Complex Method
public void RemoveInvalidLandlessTitles(Date ck3BookmarkDate) {
Logger.Info("Removing invalid landless titles...");
var removedGeneratedTitles = new HashSet<string>();
Expand Down
Loading