Сообщество Империал: CK 2 Дневник разработчиков №18: Оптимизация и модинг - Crusader Kings II - Paradox Interactive - Библиотека Статей - Сообщество Империал
Добрый день. Я Magne Skjæran и сейчас я прохожу практику в роли программиста Crusader Kings 2. Также вы можете знать меня как администратора Wiki игр Paradox. Моя практика подходит к концу и было решено, что в её довершение я напишу дневник разработчиков про 2 мои любимые темы: оптимизацию и модинг.
Как все из вас знают, игра имеет свойство замедляться со временем, в основном из-за постепенного увеличения количества персонажей. Особенно это заметно для людей со слабым компьютером, но те, кто играют на 5 скорости, скорее всего тоже это отметили.
Также иногда игра зависает на несколько секунд. Чаще всего это во происходит во время автосохранения, но также есть пауза в конце каждого года и пауза поменьше в конце каждого месяца.
Мы приложили усилия не только для того, чтобы сильно уменьшить эти паузы, но и чтобы ускорить игру в целом. И мы достигли в этом серьёзного успеха.
С 2.6 в поздней игре автосохранения во время наших тестов были в два раза быстрее, чем раньше, при этом лаг в конце года лишь едва заметнее ежемесячного лага, который также сильно уменьшен.
В целом производительность также стала гораздо выше. Отдельные дни теперь быстрее обрабатываются.
Достигли мы этого благодаря множеству различных оптимизаций:
Несжатые сохранения теперь меньше чем обычно, что экономит время на сжатии и записи.
Сохранения записываются более эффективно.
Почти всё, что случалось в конце года, теперь распределено на весь год, так что пауза теперь не будет такой заметной.
Мы улучшили рендеринг карты и она значительно ускорилась.
Мы прошлись по случаям, когда режимы карты, имена и т.д. были помечены как «устаревшие» на карте и в интерфейсе и убедились, что они будут обновляться только когда это действительно нужно. Например, раньше статус оккупации был помечен как нуждающийся в обновлении, хотя статус на самом деле не изменялся, что давало лишнюю работу CPU.
Несколько однопоточных расчётов теперь многопоточные.
Различные улучшения в различных расчётах, сильно влияющих на производительность.
Теперь генерируется меньше случайных персонажей. Также игра будет более агрессивно уничтожать бесполезных персонажей.
Чтобы продемонстрировать последний пункт, я привожу число живых персонажей в год из одной из моих тестовых игр:
У меня нет такой же схемы для 2.5, но, для сравнения, после 400 лет со старого сохранения в 769 году у нас было примерно 30000 живых персонажей, почти в 2 раза больше, чем в моём тестовом сохранении выше.
В конце концов, вы не обязаны просто верить мне на слово: вот видео одновременного запуска 2.5.2 и 2.6:
Двигаемся дальше.
Мне приходилось модифицировать CKII, будучи одним из создателей прекрасного Historical Immersion Project, так что тема модинга близка мне.
По себе знаю, что часто модерам приходится писать различные костыли, потому что нужную им информацию не всегда легко достать. Поэтому я потратил время как и на работе, так и в свободное время, реализуя полезные триггеры и эффекты, даже когда PDS не нуждалось в них немедленно. Divine также занимался внедрением разнообразных возможностей для моддинга, которые предлагали пользователи, а остальная часть команды занималась возможностями, которые нужны для Reaper`s Due. Поправлено определённое количество багов в моддинге и добавлена новая полезная консольная команда.
В общей сложности в нашем чейджлоге модинга содержится около ста пунктов, каждый пункт содержит более одного триггера или эффекта.
Полный список изменений модинга в 2.6
Спойлер (раскрыть)
- Added possibility to have major province modifiers
- Causes of death can now be customized
- Execution method can be chosen via a priority system similar to government flavors
- added "health_penalty", "fertility_penalty", "martial_penalty", "intrigue_penalty", "diplomacy_penalty", "stewardship_penalty", "learning_penalty"
- a set of modifiers whose sum for a given stat can never be positive (allows your giving bonuses that only offset maluses instead of bonus that are positive no matter what)
- Added military_techpoints, economy_techpoints, culture_techpoints as generic modifiers (for province modifiers)
- Added "any_demesne_province" as an effect
- holdings/settlement modifiers can now be hidden
- Added "has_any_symptom" and "symptom=" triggers
- Added "num_of_symptoms" trigger
- Added "spawn_disease" effect which spawns a specific disease in a specific province
- Scope must be a province
- "spawn_disease=disease_name"
- Added "start_outbreak" which forces an outbreak, but follows the scenarios set up in the disease.txt file
- "start_outbreak=disease_name"
- Scope is not used
- Added "on_outbreak" OnAction which is called when a new outbreak starts
- scope is the province where the outbreak starts
- token_data is the disease name
- Added "scenarios" to diseases: they exclude certain regions and determine possible starting provinces
- Added various defines for modifiers to contagiousness of disease when determining the spread. They are only used with The Reaper's Due DLC
- Added yearly "on_province_major_modifier" on_action
- Added "regional_percentage" trigger:
regional_percentage = {
region = andalusia
percentage = 0.5
has_province_flag = aztec_explorers
}
- Added hospital_level trigger that tests the hospital level in a province. Province scope
- Added disease_defence trigger that tests the disease defense in a province. Province scope
- Added "has_game_rule" trigger to test the value of a game rule:
has_game_rule = {
name = gender
value = all
}
- Added triggers:
any_hospital
num_of_hospitals
num_of_hospitals_diff
has_hospital
hospital_has_any_building
is_hospital_decision_allowed
is_hospital_decision_potential
- Added Event scope:
hospital_owner
- Added supported_checksum = yes/no trigger. Added supported_checksums = { ABCD EFGH } field in .mod files. When supported_checksum trigger is used in game it tries to match the current checksum of the game with the entries in all active mods mod-files. The trigger returns true if it finds at least one match.
- Fixed an issue for mods trying to remove localisation from the base game's localisation.
- targeted_decisions, is_targeted_decision_allowed and is_targeted_decision_potential are now considered aliases for targetted_decisions, is_targetted_decision_allowed and is_targetted_decision_potential respectively and are evaluated in the same way.
- Fixed a CTD that could happen for mods that allowed you to play characters with only titular titles.
- scaled_wealth and transfer_scaled_wealth now supports an additional max field to cap the maximum amount of wealth gained/lost.
- Added enatic trait attribute equivalent of the agnatic attribute (which allowed certain traits, eg Sayyid, to always be inherited from the father).
- Added define MERCHANT_REPUBLIC_MAX_PATRICIANS which determines the amount of merchant republic families the game will allow to exist in a merchant republic.
- Added triggers monthly_prestige and monthly_piety.
- Added effects scaled_prestige and scaled_piety.
- It is now possible to script council voting for targeted_decisions.
- The council interface should now support voter minor titles with a grant limit higher than one (1).
- Added set_pentarch_title = <title/none> effect.
- The pentarchy entry in landed titles can now be assigned to a specific religion rather than all religions with autocephaly.
- Using title_prefix in a government definition should no longer default all non-prefix defined title names to the default versions.
- Ambitions are now valid for the ai aggression modifier "aggression".
- add_character_modifier and add_holding_modifier now supports the stacking = yes parameter.
- Added has_holding_modifier = x trigger that returns true of the holding has modifier x.
- Added has_instances_of_character_modifier, has_instances_of_province_modifier, has_instances_of_holding_modifier = { modifier = x amount = y } trigger where y is the amount of current applications of modifier x that the character needs to currently hold for the trigger to return true.
- Added remove_character_modifiers, remove_province_modifiers, remove_holding_modifiers = { modifier = x amount = y } effects that removes y amount of modifier x from the current scope.
- Added on_trade_post_construction_completed, on_fort_construction_completed on_action entries.
- Added on_trade_post_construction_start, on_fort_construction_start on action entries.
- Fixed some issues with on_settlement_construction_start on_action events.
- Added GetHusbandWifeCap, GetHusbandWifeCapOpp, GetMasterMistressCap, GetMasterMistressOpp, GetMasterMistressCapOpp character localisation functions.
- any_character trigger should no longer exclude the ROOT scope in it's evaluation.
- Fixed a possible issue with hidden effects inside scripted effects.
- Added trigger 'leader_traits' (number of)
- Reactivated the on_action 'on_focus_pulse'
- Disease effects are now customizable through script per disease
- Silk Road modifier icon can now be set in the text file
- Added define AUTOMATICALLY_ACCEPTS_COALITION_CALLS to determine if defensive pacts members automatically join at the start of wars
- Converted the Family Focus events to on_action events
- Fixed a bug where the 'end_war' effect would incorrectly invalidate wars
- The 'regent' event target is now properly invalidated if there is no regent
- Added trigger 'any_player'
- Added effect 'any_player'
- Added effect 'random_player'
- Added define WAR_CONTRIBUTION_THEOCRACY_GHW_MULT
- Fixed era bookmarks ignoring their defined text keys. WARNING: This means that your mod's era names are likely now unlocalised
- Fixed buttons F9 through F12 not working as shortcuts
- Fixed a number of triggers functioning identically when set to "= no" as when set to "= yes"
- has_terrain_specialization now takes "yes" and "no" as parameters as well, in addition to "any" and specific terrains
- Added missing localisation for a handful of triggers
- Era screen characters can now be restricted based on dlc by adding 'dlc = "dlc name"' to their entry
- Fixed the time control buttons being inactive in 867.1.1 in mods starting on or before that date
- Opinion modifiers can now be scripted to be stacking (default) or not
- Added a give_birth console command (requires existing pregnancy; use pollinate/cuckoo to impregnate)
- Added on_action 'on_holding_building_start'
- Added has_assigned_minor_title trigger. Usage: "has_assigned_minor_title = title_master_of_the_horse" or "has_assigned_minor_title = { title = title_commander count = 2 }"
- Added has_children and has_living_children triggers
- The "loot" trigger will no longer crash the game if applied to a land unit. It will always return false for land units, but it won't crash
- has_minor_title now also accepts "yes" and "no", to check whether the character holds any minor titles at all
- Can now add and destroying buildings in extra holdings (trade posts, forts & hospitals) with the following effects:
add_to_extra_holding = {
type = hospital
building = leper_colony_1
}
destroy_in_extra_holding = {
type = hospital
building = leper_colony_1
}
- The following effects have been added. They work the same as the equivalent for forts or trade posts:
create_hospital
destroy_hospital
any_hospital
- Scripted effects in event options will now show the traits and characters they affect
- Added a war_participation trigger. Example: any_war = { war_participation = { who = ROOT score = 0.5 } }
- Added an is_landed_title_allowed trigger, which checks whether a character fulfills the "allow" section of a specific title. Example: is_landed_title_allowed = e_hre or is_landed_title_allowed = ROOT, where ROOT is a title
- Added a "force_host" effect that forcibly changes the host a character. Scope should be the character being moved, target should be the character's new host.
Shouldn't be used lightly
force_host = ROOT
- Added join_faction, leave_faction and start_faction effects.
- Added faction_exists trigger.
- Added export_to_variable effect.
- Added while effect.
- Title prefix defined in landed_titles.txt should now support localisation variations dependent on the holder of the title.
- Added sound_effect effect.
- It should now be possible to make baronies independent through history editing.
- Added a "character_stats" console command that prints a variety of statistics to the console, such as the # of rulers of each tier, gender breakdown, and total wealth. This also gets written to stats.log
- Added a "dynasty_stats" console command that prints a variety of statistics to the console, such as the # of dynasties, number of single-person dynasties, and number of dynasties with only dead characters. This also gets written to stats.log
- Added a COURT_PRUNE_SIZE define, which defines when the game will try to find unneeded courtiers to kill off. Lowered to 10 from the original 20
- Added a "de_facto_liege_title" trigger, which checks that the defacto liege title of a character or title is the right-hand side. Example: ROOT = { de_facto_liege_title = e_hre }. Both sides can take a character or a title. If a character is provided, their primary title will be used. A defacto_liege_title scope already existed, but this should make some operations easier
- Added an "immortal" trigger, which checks if the character in the current scope is immortal
- Added an "is_incapable" trigger, which checks if the character in the current scope has an incapacitating trait
- Added an "is_pilgrim" trigger, which checks if the character in the current scope has a pilgrim trait
- Added a "same_regnal_name" trigger, which checks if the character in the current scope has the same regnal name as another character, meaning that they'll be considered the same name for the purpose of regnal numbering. Regnal names are currently defined as having the same first first name (E.G., "Gustav" and "Gustav Adolf" are the same regnal name), or the same cultural first first name (E.G., "Alfr_Alf" and "Alf_Alf" are the same regnal name)
- "monthly_income" and "yearly_income" can now be used in a holding scope. Before it could only take a character. Example: "b_constantinople = { yearly_income = 15 }"
- Added a "has_inheritance_blocker" trigger, which checks if the character in the current scope has a trait that blocks inheritance (cannot_inherit = yes)
- Added a "dynastic_prestige" trigger, which checks if the dynasty of the character in the current scope has a prestige of at least the given value. Example: "dynastic_prestige = 100"
- Added a "set_preferred_capital" effect, which sets the preferred capital of the title in the current scope (used for a variety of things, such as the AI to determine where to put their capital). Only works for dynamic titles, as static titles base their capital off of the landed_titles folder
- Added a "lacks_dlc" event pre-trigger. If the DLC is enabled, the event will not be evaluated
- Added a "has_dlc" event pre-trigger. If the DLC is disabled, the event will not be evaluated
- Added a "war" event pre-trigger, which takes "yes" or "no", and checks that the character is/isn't at war
- Added a "is_married" event pre-trigger, which takes "yes" or "no", and checks that the character is/isn't married
- Added a "friends" event pre-trigger, which takes "yes" or "no", and checks that the character does/doesn't have friends
- Added a "rivals" event pre-trigger, which takes "yes" or "no", and checks that the character does/doesn't have rivals
- Added a "has_global_flag" event pre-trigger, which checks that the given global flag has been set
- Added support for an after = { } - effect field in events. It works as a counterpart to immediate and executes after any option is executed.
- Replaced the COALITION_PROVINCE_THREAT_RATIO define with COALITION_SCARY_TROOP_STRENGTH_THREAT_RATIO. It is now actually used by the game
- Decisions now take the pre-triggers "only_rulers", "only_landed", and "only_independent". It is recommended that they be used when possible so as to reduce the time spent by the AI evaluating the decision. Note that the pre-trigger currently only applies to the AI, not to the player
- The "is_occupied" trigger now works in province scope, not just title scope
- The "is_occupied" trigger now works for county-level titles, not just baron-level titles
- "plot_decisions" are now only checked by characters that lead a plot or faction. Previously there was no functional difference between plot decisions and regular decisions
- Added "has_flag" as a quick trigger for province events. It works exactly like the "has_character_flag" quicktrigger, except the scope is the province for the event
- Added on_war_ended_invalid and on_crusade_invalid on_actions, that provide the same scopes as the other on_war_ended and on_crusade on_actions
- Added a CROWN_LAW_CHANGE_TIMER define. If set to 0, rulers will be restricted to MAX_CROWN_LAW_CHANGES. If set to 1, they'll have a CROWN_LAW_CHANGE_MONTHS cooldown
- Added a CROWN_LAW_CHANGE_MONTHS define
- Traits can now be hidden. Adding "hidden = yes" will make it invisible in all parts of the UI (except event options, where they can be hidden using hidden_tooltip)
- Added define "FAR_CRUSADES_WITHOUT_WEIGHT_MODIFIER" as a weight modifier to starting crusades on titles that are not adjacent to territory of our religion and don't have a crusade weight modifier. Default value is 75%
Одним из самых больших изменений, скорее всего является добавление игровых правил, как описано в одном из предыдущих дневников.
С правилами вы можете добавлять свои собственные настройки, с которыми пользователи смогут настраивать ваш мод. Больше нет нужды добавлять в первый день события или решения, чтобы настраивать мод таким неинтуитивным и неудобный способом, теперь игроки могут настраивать мод также, как и ванилу.
Число правил, как и число доступных вариантов, неограничено. Хотите добавить возможность выставить сценарий Shattered World, например? Добавьте это в правила и мир будет разбиваться так, как пользователь выставил в правилах, нет нужды выбирать это в событии в первый день.
На правила можно ссылаться где угодно в скрипте, их можно использовать практически для любой уместной цели.
Наконец, я написал, как модеры могут ускорить свои моды. Можете прочитать об этом в подразделе модинга. Я поместил это отдельно, чьлюы модеры могли задавать свои вопросы и получать свои ответы отдельно от этого дневника разработчиков: https://forum.parado...on-tips.962056/
На сегодня всё. The Reaper's Due и патч 2.6 выйдут 25 августа, так что совсем скоро вы сможете ощутить улучшения оптимизации и модинга на себе. Надеюсь, они вам понравятся, потому что мне понравилось их кодить!