Ru/Response System: Difference between revisions

From Valve Developer Community
< Ru
Jump to navigation Jump to search
No edit summary
No edit summary
Line 3: Line 3:


'''Система Реакций (Response System)''' используется для того, чтобы решить, какую реплику (и/или анимацию) следует использовать NPC (или игроку), когда они хотят что-то сказать, и стоит ли вообще что-то говорить.
'''Система Реакций (Response System)''' используется для того, чтобы решить, какую реплику (и/или анимацию) следует использовать NPC (или игроку), когда они хотят что-то сказать, и стоит ли вообще что-то говорить.
{{note|Большая часть этой статьи основана на ветке Source 2013. В {{l4d|4}} появилась переписанная система ответов, которая выполняет большинство тех же функций, но имеет различные оптимизации, пути и утилиты, которые еще не полностью задокументированы в этой статье. Эта улучшенная система также доступна во всех играх, выпущенных после ''Left 4 Dead'', включая {{l4d2|4}}. Код этой системы находится в открытом доступе по адресу {{astools|4|nt=1}}. {{also|{{mapbase}}}}}}
{{toc-right}}
'''Система Реакций/Реагирования (Response System)''' используется для того, чтобы решить, какую реплику (и/или анимацию) следует использовать NPC (или игроку), когда они хотят что-то сказать, и стоит ли вообще что-то говорить.


{{note|Большая часть этой статьи основана на ветке Source 2013. В {{l4d|4}} появилась переписанная система ответов, которая выполняет большинство тех же функций, но имеет различные оптимизации, пути и утилиты, которые еще не полностью задокументированы в этой статье. Эта улучшенная система также доступна во всех играх, выпущенных после ''Left 4 Dead'', включая {{l4d2|4}}. Код этой системы находится в открытом доступе по адресу {{astools|4|nt=1}}. {{also|{{mapbase}}}}}}
{{note|Большая часть этой статьи основана на ветке Source 2013. В {{l4d|4}} появилась переписанная система ответов, которая выполняет большинство тех же функций, но имеет различные оптимизации, пути и утилиты, которые еще не полностью задокументированы в этой статье. Эта улучшенная система также доступна во всех играх, выпущенных после ''Left 4 Dead'', включая {{l4d2|4}}. Код этой системы находится в открытом доступе по адресу {{astools|4|nt=1}}. {{also|{{mapbase}}}}}}
Line 10: Line 16:
Большинство пользователей системы Response System должны говорить в ответ на события, происходящие в игре. Речь может быть вызвана кодом или вводом данных с карты. Триггерная речь включает в себя реакцию ''концепт'', которая соответствует реакциям в системе. Концепты - это категории речи, используемые в связи с определенным событием, например, с тем, что была замечена опасность (<code>TLK_DANGER</code>) или был увиден враг (<code>TLK_STARTCOMBAT</code>). Хотя концепт можно использовать отдельно для базового и простого диалога, речь также может быть вызвана различными '''Критериями''' которые описывают вещи, связанные с концепцией и/или текущим состоянием говорящего и окружающего его мира. Это позволяет создавать сложные диалоговые деревья, включающие разные реплики для разных ситуаций.
Большинство пользователей системы Response System должны говорить в ответ на события, происходящие в игре. Речь может быть вызвана кодом или вводом данных с карты. Триггерная речь включает в себя реакцию ''концепт'', которая соответствует реакциям в системе. Концепты - это категории речи, используемые в связи с определенным событием, например, с тем, что была замечена опасность (<code>TLK_DANGER</code>) или был увиден враг (<code>TLK_STARTCOMBAT</code>). Хотя концепт можно использовать отдельно для базового и простого диалога, речь также может быть вызвана различными '''Критериями''' которые описывают вещи, связанные с концепцией и/или текущим состоянием говорящего и окружающего его мира. Это позволяет создавать сложные диалоговые деревья, включающие разные реплики для разных ситуаций.


Например, {{ent|npc_alyx}} в ''Half-Life 2'''s episodic series speaks the <code>TLK_PLAYER_KILLED_NPC</code> concept when the player kills an enemy NPC. This concept has additional criteria for conditions related to the NPC or the way it was killed. If the player killed the NPC through a headshot, the response system will pick a response that requires that criteria, which usually results in Alyx complimenting the player's shot or remarking that it was a headshot.
Например, {{ent|npc_alyx}} в эпизодах серии ''Half-Life 2'' использует концепт <code>TLK_PLAYER_KILLED_NPC</code> - когда игрок убивает враждебного NPC. Этот концепт является дополнительным критерием для условий, относящийся к NPC или способом, как был убит NPC. Если игрок убил NPC выстрелом в голову, система реагирования подберет ответ, включающий такой критерий, и в таком случае Аликс будет хвались игрока за точность или отметит убийство врага выстрелов голову.


The Response System normally uses scripts in the <code>scripts/talker</code> directory. When it receives a concept and its criteria, it searches through the response scripts for a '''rule''' that matches its concept and criteria. When it finds one, it uses that rule's '''response''' or selection of responses. A response can be a {{L|Soundscripts|soundscript}}, a {{L|Sentences|sentence}}, or even an instanced {{L|Choreography Implementation|choreographed scene}}.
По стандарту система реагирований использует скрипты, находящиеся по пути <code>scripts/talker</code> относительно ''GameInfo.txt''. Получив концепцию и её критерии, он ищет в сценариях ответов '''правило''', соответствующее концепции и критериям. Когда правило найдено, он использует его ''ответ'' или выбор ответов. Такой ответ может быть как {{L|Soundscripts|звуковым скриптом}}, как заготовленной {{L|Sentences|sentence}} фразой, так и {{L|Choreography Implementation|хореографической сценой}}.


Despite the advantages, most NPCs do not use this system by default. For example, {{ent|npc_pigeon}} only uses soundscripts by default and does not use the Response System.
Несмотря на преимущества, большинство NPC не используют эту систему по умолчанию. Например, {{ent|npc_pigeon|голубь}} по умолчанию использует только звуковые скрипты и не использует систему ответов.


Here's a quick list of places where the Response System is used:
Краткий перечень, где используется система реагирования:
* In {{hl2|4}}, most player companion NPCs ({{L|npc_citizen|citizens}}, {{L|npc_alyx|Alyx}}, etc.) use the Response System for NPC speech.
* В {{hl2|4}} большинство NPC-компаньонов ({{L|npc_citizen|ситизены}}, {{L|npc_alyx|Аликс}}, и т.д.) используют систему правил реагирования для NPC.
* In {{tf2|4}}, all classes use the Response System for voice commands and taunt responses.
* В {{tf2|4}} все классы используют систему реагирования для голосовых команд и ответных колкостей.
* In the {{l4ds|4}}, all of the survivors use the Response System to respond to the players' actions and events in the world.
* В {{l4ds|4}} все выжившие используют систему реагирования, чтобы отвечать на действия игроков и события в мире.
* In {{portal2|4}}, Atlas and P-body (the robots in co-op mode) both use the Response System for taunt gestures.
* В {{portal2|4}} Атлас и P-body (роботы в совместном режиме) используют систему реагирования для дразнящих жестов.
* In {{csgo|4}}, all player characters use the Response System and keep track of which responses have already been used.
* В {{csgo|4}} все персонажи игроков используют систему ответов и следят за тем, какие ответы уже были использованы.
* In {{hla|4}}, see {{L|HLALYX:Response_rules.txt}}.
* В {{hla|4}} гляньте {{L|HLALYX:Response_rules.txt}}.


{{ModernCodenote|The Response System is normally used on classes derived from <code>CBaseFlex</code> with the <code>CAI_ExpresserHost<></code> template class, which is automatically implemented on <code>CAI_BaseActor</code>. All NPCs and players already derive from <code>CBaseFlex</code>, so you'd usually just want to use <code>CAI_ExpresserHost<></code>, but the Response System can be used in a more limited way on any entity using the <code>DispatchResponse()</code> function, which is how {{ent|env_speaker}} works. <code>GetResponseSystem()</code> can be used to make concepts search a specific response system tree and must be overridden if you are planning on using <code>DispatchResponse()</code> without <code>CAI_ExpresserHost<></code>.}}
{{ModernCodenote|The Response System is normally used on classes derived from <code>CBaseFlex</code> with the <code>CAI_ExpresserHost<></code> template class, which is automatically implemented on <code>CAI_BaseActor</code>. All NPCs and players already derive from <code>CBaseFlex</code>, so you'd usually just want to use <code>CAI_ExpresserHost<></code>, but the Response System can be used in a more limited way on any entity using the <code>DispatchResponse()</code> function, which is how {{ent|env_speaker}} works. <code>GetResponseSystem()</code> can be used to make concepts search a specific response system tree and must be overridden if you are planning on using <code>DispatchResponse()</code> without <code>CAI_ExpresserHost<></code>.}}
Line 38: Line 44:
::*"Не так близко!"
::*"Не так близко!"
::*"Спасибо что подошел!"
::*"Спасибо что подошел!"
:*''Был ли врагом {{ent|npc_headcrab}}?''
:*''Был ли врагом {{ent|npc_headcrab|хедкраб}}?''
::*"Ты не получишь мою бошку!"
::*"Ты не получишь мою бошку!"
::*"Ненавижу хедкрабов!"
::*"Ненавижу хедкрабов!"


Вы также можете использовать комбинации различных критериев.
Вы также можете использовать комбинации различных критериев.
:*''Использовал ли я дробовик против {{ent|npc_headcrab}}, который был достаточно близко ко мне?''
:*''Использовал ли я дробовик против {{ent|npc_headcrab|хедкраба}}, который был достаточно близко ко мне?''
::*"Отойди от моей пушки, хедкраб!"
::*"Отойди от моей пушки, хедкраб!"


Вы также можете управлять отдельными строками, чтобы они не повторялись в течение определенного времени или вообще не повторялись.
Вы также можете управлять отдельными строками, чтобы они не повторялись в течение определенного времени или вообще не повторялись.


==Structure==
==Структура==
{{note|'Criterion' is the singular form of 'Criteria'.}}
{{note|'Criterion' - это форма единственного числа от 'Criteria'.}}


The Response System is made up of four core pieces: '''Concepts''', '''Criteria''', '''Rules''', and '''Response Groups'''. The way these are used is as follows:
В Response System'е имеются четыре составные части: '''Концепты (Concepts)''', '''Критерии (Criteria)''', '''Правила (Rules)''', и '''Группа ответов (Response Groups)'''. И вот каким образом они используются:
#An NPC requests a line of speech for a speech '''concept'''.
#NPC запрашивает реплику для '''концепции''' речи.
#*''For example, let's say our NPC requests a line of speech for the <code>TLK_SHOT</code> concept. An NPC speaks this concept whenever they're shot by an enemy.''
#*''Например, допустим, наш NPC запрашивает строку речи для концепции <code>TLK_SHOT</code>. NPC произносит эту концепцию всякий раз, когда в них стреляет враг.''
#The NPC gathers a bunch of '''criteria''' reflecting the NPC's current state and other relevant data about the state of the world. Many concepts also have '''modifiers''', which are criteria unique to specific concepts that usually reflect the event itself.
#NPC собирает кучу '''критериев''', отражающих текущее состояние NPC и другие важные данные о состоянии мира. Многие концепции также имеют '''модификаторы''' - критерии, уникальные для конкретных концепций, которые обычно отражают само событие.
#*''When the NPC requests a line for the <code>TLK_SHOT</code> concept, the game assembles the NPC's current health, etc. as part of the default criteria set. Then, it appends the concept's modifiers, which may include the type of enemy that shot them, the amount of damage they took, etc.''
#*''Когда NPC запрашивает концепт <code>TLK_SHOT</code>, игра собирает текущее здоровье NPC (например) как часть набора критериев по умолчанию. Затем он добавляет модификаторы концепции, которые могут включать тип врага, который в них стрелял, количество полученного урона и т.д.''
#The '''concept''' and '''criteria''' are passed into the NPC's response system, which is normally a single global instance shared by all NPCs.
#'''Концепт''' и '''Критерии''' передаются в систему ответа NPC, которая обычно представляет собой один глобальный экземпляр, общий для всех NPC.
#The Response System searches through its big list of '''rules'''.
#Теперь система реагирования просматривает большой список '''правил'''..
#*Each '''rule''' contains a list of criteria which is tested against the '''criteria''' assembled by the NPC. Note that the '''concept''' is treated as a high-priority criterion in this phase.
#*Каждое такое '''правило''' содержит в себе список критериев, которые который проверяется на соответствие '''критериям''', собранным NPC. Обратите внимание, что на этом этапе '''концепция''' рассматривается как высокоприоритетный критерий.
#*Each '''rule''' gets a score based on how many of the criteria are true. If at least one criterion is marked as ''required'' and isn't satisfied, the rule will never be chosen. Most criteria are set to be required, but criteria that aren't required simply boost the rule's score.
#*Каждое '''правило''' получает оценку, основанную на том, сколько критериев верны. Если хотя бы один критерий отмечен как 'обязательный' и не выполнен, правило никогда не будет выбрано. Большинство критериев являются обязательными, но критерии, которые не являются обязательными, просто повышают оценку правила.
#**''In our <code>TLK_SHOT</code> example, there might be multiple <code>TLK_SHOT</code> rules which contain different lines. One rule might contain criteria that test to see if the NPC is very close to the enemy who shot him. Another rule might test to see if it was a specific type of enemy that shot him (such as a Combine Soldier). Another rule might test to see if the NPC has <25% of its health left after the shot.''
#**''Для нашего <code>TLK_SHOT</code> может содержаться несколько <code>TLK_SHOT</code> правил, которые имеют различные реплики. Одно правило может содержать критерий, проверяющий насколько близок к NPC враг, который стрелял в него. Другое может проверять, выстелил ли в NPC враг особо класса сущности (как пример, Солдат Альянса). Ещё одно - уровень здоровья NPC (например, осталось ли у NPC хотя бы <25% уровня его здоровья после выстрела.)''
#The Response System scores all of the '''rules''' in its list and chooses the one that scores highest. The '''rule''' that scores the highest specifies a '''response group'''.
#Система реагирования оценивает все '''правила''' в своем списке и выбирает то, которое набрало наибольшее количество баллов. Правило, набравшее наибольшее количество баллов, определяет '''группу реагирования'''.
#A '''response group''' is simply a list of possible '''responses''', each of which might be a line of speech and/or animation. One response is selected based on the settings of the response group and the individual responses. When a valid response is chosen, the NPC plays the response.
#'''Группа ответов''' - это лишь список заготовленных заранее '''ответов''', каждый из которых (ответов) может бы, например, репликой и/или анимацией (как в случае использования хореографической сцены). Один ответ выбирается на основе настроек группы ответов и отдельных ответов. Когда выбран правильный ответ, NPC воспроизводит его.
#*''In our <code>TLK_SHOT</code> example, let's say the <25% health rule was chosen. This rule would have a response group which might contain a list of lines like "One more shot like that, and I'm done for!", "Oh man, I'm in trouble!", or "I need medical attention over here!"''
#*''Давайте для нашего примера концепта <code>TLK_SHOT</code> сделаем правило, смотрящее за уровнем здоровья NPC (если у NPC меньше 25% его здоровья). У этого правила есть группа ответа, которая может содержать список реплик вроде «Ещё один такой выстрел, и мне конец!», «О, Боже, я в беде!» или «Мне нужна медицинская помощь!»''.
#*''Another rule for <code>TLK_SHOT</code> could check if the enemy shooting them is a Combine soldier and point to a response group with lines like "That Combine soldier's got me pinned down!" or "Help me with this soldier!". Another rule could check if the enemy is a Combine gunship and point to a group with "That gunship is kicking my butt!" and "Someone help me take down that gunship before it kills me!"
#*''Другое правило для <code>TLK_SHOT</code> может проверить, является ли стреляющий в них враг Солдатом Альянса, и указать на группу ответа с репликами вроде «Этот солдат Альянса прижал меня к земле!» или «Помогите мне с этим солдатом!». Другое правило может проверять, не является ли враг Штурмовиком Альянса, и указывать на группу с репликами «Этот корабль надирает мне задницу!» и «Кто-нибудь, помогите мне уничтожить этот корабль, пока он меня не убил!».
#If no rule matches the given criteria (or the chosen response group doesn't repeat itself and has been exhausted), the NPC doesn't say anything.
#Если ни одно правило не соответствует заданным критериям (или выбранная группа ответов не повторяется и исчерпана), NPC вообще никак уникально не отреагирует.


===Концепты===
===Концепты===
Line 148: Line 154:
: An optional parameter that states that this criterion is required for rules containing it to be used at all. If a required criterion does not match successfully, rules containing it score 0 and are immediately skipped. Most criteria use this parameter.
: An optional parameter that states that this criterion is required for rules containing it to be used at all. If a required criterion does not match successfully, rules containing it score 0 and are immediately skipped. Most criteria use this parameter.


Some examples from ''Half-Life 2'':
И вот некоторые примеры из ''Half-Life 2'':
*This defines a criterion named '''PlayerNear''', which checks to make sure the player is within 500 units of the speaking NPC.
*Определение критерия, названное '''PlayerNear''' обозначает, что расстояние от игрока до говорящего NPC должно составлять хотя бы 500 юнитов.
:<pre>criterion "PlayerNear" "distancetoplayer" "<500" required</pre>
:<pre>criterion "PlayerNear" "distancetoplayer" "<500" required</pre>
*This defines a criterion named '''IsCitizen''', which checks to make sure the speaking NPC is a {{ent|npc_citizen}}.
*Определение критерия, названное '''IsCitizen''' обозначает, что класс говорящего NPC должен быть {{ent|npc_citizen}}.
:<pre>criterion "IsCitizen" "classname" "npc_citizen" "required"</pre>
:<pre>criterion "IsCitizen" "classname" "npc_citizen" "required"</pre>
*This defines a criterion named '''IsMap_d3_c17_12''', which checks to make sure the game is currently on '''d3_c17_12.bsp'''. Useful for making all the citizens in one map say different lines than other maps.
*Определение критерия, названное '''IsMap_d3_c17_12''' обозначает, что текущая игра проходит на карте в названием '''d3_c17_12.bsp'''. Пригодится для того, чтобы заставить всех сущностей одной карты произносить реплики, отличные от других карт.
:<pre>criterion "IsMap_d3_c17_12" "map" "d3_c17_12" "required"</pre>
:<pre>criterion "IsMap_d3_c17_12" "map" "d3_c17_12" "required"</pre>
*This defines a criterion named '''IsBob''', which checks to make sure the speaking NPC has a targetname of "bob". This is a unique citizen in the game, and this criteria makes it easy to have him say unique lines.
*Здесь определяется критерий '''IsBob''', назван ли NPC как "bob" ''("targetname" "bob")''. Это уникальный гражданин в игре, и этот критерий позволяет легко заставить его произносить уникальные реплики.
:<pre>criterion "IsBob" "targetname" "bob" required</pre>
:<pre>criterion "IsBob" "targetname" "bob" required</pre>



Revision as of 14:48, 19 October 2024

Under construction.png
This page is actively undergoing a major edit.
As a courtesy, please do not edit this while this message is displayed.
If this page has not been edited for at least several hours to a few days, please remove this template. This message is intended to help reduce edit conflicts; please remove it between editing sessions to allow others to edit the page.

The person who added this notice will be listed in its edit history should you wish to contact them.

Info content.png
This page needs to be translated.
This page either contains information that is only partially or incorrectly translated, or there isn't a translation yet.
If this page cannot be translated for some reason, or is left untranslated for an extended period of time after this notice is posted, the page should be requested to be deleted.
Also, please make sure the article complies with the alternate languages guide.(en)

Система Реакций (Response System) используется для того, чтобы решить, какую реплику (и/или анимацию) следует использовать NPC (или игроку), когда они хотят что-то сказать, и стоит ли вообще что-то говорить.

Note.pngПримечание:Большая часть этой статьи основана на ветке Source 2013. В Left 4 Dead Left 4 Dead появилась переписанная система ответов, которая выполняет большинство тех же функций, но имеет различные оптимизации, пути и утилиты, которые еще не полностью задокументированы в этой статье. Эта улучшенная система также доступна во всех играх, выпущенных после Left 4 Dead, включая Left 4 Dead 2 Left 4 Dead 2. Код этой системы находится в открытом доступе по адресу Alien Swarm - SDK Alien Swarm Authoring Tools. (также в Mapbase)

Система Реакций/Реагирования (Response System) используется для того, чтобы решить, какую реплику (и/или анимацию) следует использовать NPC (или игроку), когда они хотят что-то сказать, и стоит ли вообще что-то говорить.

Note.pngПримечание:Большая часть этой статьи основана на ветке Source 2013. В Left 4 Dead Left 4 Dead появилась переписанная система ответов, которая выполняет большинство тех же функций, но имеет различные оптимизации, пути и утилиты, которые еще не полностью задокументированы в этой статье. Эта улучшенная система также доступна во всех играх, выпущенных после Left 4 Dead, включая Left 4 Dead 2 Left 4 Dead 2. Код этой системы находится в открытом доступе по адресу Alien Swarm - SDK Alien Swarm Authoring Tools. (также в Mapbase)

Большинство пользователей системы Response System должны говорить в ответ на события, происходящие в игре. Речь может быть вызвана кодом или вводом данных с карты. Триггерная речь включает в себя реакцию концепт, которая соответствует реакциям в системе. Концепты - это категории речи, используемые в связи с определенным событием, например, с тем, что была замечена опасность (TLK_DANGER) или был увиден враг (TLK_STARTCOMBAT). Хотя концепт можно использовать отдельно для базового и простого диалога, речь также может быть вызвана различными Критериями которые описывают вещи, связанные с концепцией и/или текущим состоянием говорящего и окружающего его мира. Это позволяет создавать сложные диалоговые деревья, включающие разные реплики для разных ситуаций.

Например, npc_alyx в эпизодах серии Half-Life 2 использует концепт TLK_PLAYER_KILLED_NPC - когда игрок убивает враждебного NPC. Этот концепт является дополнительным критерием для условий, относящийся к NPC или способом, как был убит NPC. Если игрок убил NPC выстрелом в голову, система реагирования подберет ответ, включающий такой критерий, и в таком случае Аликс будет хвались игрока за точность или отметит убийство врага выстрелов голову.

По стандарту система реагирований использует скрипты, находящиеся по пути scripts/talker относительно GameInfo.txt. Получив концепцию и её критерии, он ищет в сценариях ответов правило, соответствующее концепции и критериям. Когда правило найдено, он использует его ответ или выбор ответов. Такой ответ может быть как звуковым скриптом(en), как заготовленной sentence(en) фразой, так и хореографической сценой(en).

Несмотря на преимущества, большинство NPC не используют эту систему по умолчанию. Например, npc_pigeon голубь по умолчанию использует только звуковые скрипты и не использует систему ответов.

Краткий перечень, где используется система реагирования:

  • В Half-Life 2 Half-Life 2 большинство NPC-компаньонов (ситизены(en), Аликс(en), и т.д.) используют систему правил реагирования для NPC.
  • В Team Fortress 2 Team Fortress 2 все классы используют систему реагирования для голосовых команд и ответных колкостей.
  • В Серия игр Left 4 DeadСерия игр Left 4 Dead Серия игр Left 4 Dead все выжившие используют систему реагирования, чтобы отвечать на действия игроков и события в мире.
  • В Portal 2 Portal 2 Атлас и P-body (роботы в совместном режиме) используют систему реагирования для дразнящих жестов.
  • В Counter-Strike: Global Offensive Counter-Strike: Global Offensive все персонажи игроков используют систему ответов и следят за тем, какие ответы уже были использованы.
  • В Half-Life: Alyx Half-Life: Alyx гляньте HLALYX:Response_rules.txt(en).
Cpp.pngКод:The Response System is normally used on classes derived from CBaseFlex with the CAI_ExpresserHost<> template class, which is automatically implemented on CAI_BaseActor. All NPCs and players already derive from CBaseFlex, so you'd usually just want to use CAI_ExpresserHost<>, but the Response System can be used in a more limited way on any entity using the DispatchResponse() function, which is how env_speaker works. GetResponseSystem() can be used to make concepts search a specific response system tree and must be overridden if you are planning on using DispatchResponse() without CAI_ExpresserHost<>.

Задача

Система Response System была создана для того, чтобы NPC, игроки и т.д. использовали единую и надежную систему управления речью. Она не только позволяет разработчикам и сценаристам создавать сложные диалоговые деревья, но и позволяет моддерам легко изменять или добавлять новую речь в игру без необходимости писать код или изменять BSP-файл, сохраняя при этом полный контроль над тем, как и когда будет использоваться речь.

Эту систему лучше всего использовать для речи, исходящей от системы ИИ, поскольку эти реплики будут произноситься много раз на протяжении всей игры. (например, граждане говорят что-то, когда перезаряжают оружие).

Вот пример сложного диалога с NPC, использующего систему ответов:

  • Я только что убил врага.
  • Использовал дробовик?
  • "Съешь свинца!"
  • Был ли враг достаточно близко?
  • "Не так близко!"
  • "Спасибо что подошел!"
  • "Ты не получишь мою бошку!"
  • "Ненавижу хедкрабов!"

Вы также можете использовать комбинации различных критериев.

  • Использовал ли я дробовик против npc_headcrab хедкраба, который был достаточно близко ко мне?
  • "Отойди от моей пушки, хедкраб!"

Вы также можете управлять отдельными строками, чтобы они не повторялись в течение определенного времени или вообще не повторялись.

Структура

Note.pngПримечание:'Criterion' - это форма единственного числа от 'Criteria'.

В Response System'е имеются четыре составные части: Концепты (Concepts), Критерии (Criteria), Правила (Rules), и Группа ответов (Response Groups). И вот каким образом они используются:

  1. NPC запрашивает реплику для концепции речи.
    • Например, допустим, наш NPC запрашивает строку речи для концепции TLK_SHOT. NPC произносит эту концепцию всякий раз, когда в них стреляет враг.
  2. NPC собирает кучу критериев, отражающих текущее состояние NPC и другие важные данные о состоянии мира. Многие концепции также имеют модификаторы - критерии, уникальные для конкретных концепций, которые обычно отражают само событие.
    • Когда NPC запрашивает концепт TLK_SHOT, игра собирает текущее здоровье NPC (например) как часть набора критериев по умолчанию. Затем он добавляет модификаторы концепции, которые могут включать тип врага, который в них стрелял, количество полученного урона и т.д.
  3. Концепт и Критерии передаются в систему ответа NPC, которая обычно представляет собой один глобальный экземпляр, общий для всех NPC.
  4. Теперь система реагирования просматривает большой список правил..
    • Каждое такое правило содержит в себе список критериев, которые который проверяется на соответствие критериям, собранным NPC. Обратите внимание, что на этом этапе концепция рассматривается как высокоприоритетный критерий.
    • Каждое правило получает оценку, основанную на том, сколько критериев верны. Если хотя бы один критерий отмечен как 'обязательный' и не выполнен, правило никогда не будет выбрано. Большинство критериев являются обязательными, но критерии, которые не являются обязательными, просто повышают оценку правила.
      • Для нашего TLK_SHOT может содержаться несколько TLK_SHOT правил, которые имеют различные реплики. Одно правило может содержать критерий, проверяющий насколько близок к NPC враг, который стрелял в него. Другое может проверять, выстелил ли в NPC враг особо класса сущности (как пример, Солдат Альянса). Ещё одно - уровень здоровья NPC (например, осталось ли у NPC хотя бы <25% уровня его здоровья после выстрела.)
  5. Система реагирования оценивает все правила в своем списке и выбирает то, которое набрало наибольшее количество баллов. Правило, набравшее наибольшее количество баллов, определяет группу реагирования.
  6. Группа ответов - это лишь список заготовленных заранее ответов, каждый из которых (ответов) может бы, например, репликой и/или анимацией (как в случае использования хореографической сцены). Один ответ выбирается на основе настроек группы ответов и отдельных ответов. Когда выбран правильный ответ, NPC воспроизводит его.
    • Давайте для нашего примера концепта TLK_SHOT сделаем правило, смотрящее за уровнем здоровья NPC (если у NPC меньше 25% его здоровья). У этого правила есть группа ответа, которая может содержать список реплик вроде «Ещё один такой выстрел, и мне конец!», «О, Боже, я в беде!» или «Мне нужна медицинская помощь!».
    • Другое правило для TLK_SHOT может проверить, является ли стреляющий в них враг Солдатом Альянса, и указать на группу ответа с репликами вроде «Этот солдат Альянса прижал меня к земле!» или «Помогите мне с этим солдатом!». Другое правило может проверять, не является ли враг Штурмовиком Альянса, и указывать на группу с репликами «Этот корабль надирает мне задницу!» и «Кто-нибудь, помогите мне уничтожить этот корабль, пока он меня не убил!».
  7. Если ни одно правило не соответствует заданным критериям (или выбранная группа ответов не повторяется и исчерпана), NPC вообще никак уникально не отреагирует.

Концепты

Концепты (Concepts) - это обозначение формата string(en) который представляет собой высокоуровневую причину попытки речи персонажа. В коде определен набор концептов, которые будут вызываться автоматически, но технически концепт - это просто специальный высокоуровневый критерий, который персонажи отслеживают. Они ни к чему не привязаны, и вы можете свободно создавать свои собственные в файле ответа. Вы можете вызывать концепции в коде или с помощью Input команды DispatchResponse или SpeakResponseConcept(en) НПС.

Вот список некоторых предопределенных концепций NPC, используемых в Half-Life 2:

TLK_HELLO		Когда я впервые увидел игрока.
TLK_IDLE		Когда я долго бездействую.
TLK_USE		        Когда игрок применил +USE ко мне.
TLK_PLPUSH		Когда игрок толкнул меня.
TLK_STARE		Когда игрок долгое время смотрит (буквально, пялиться) на меня.
TLK_DANGER		Когда я понимаю, что рядом со мной опасная обстановка (например, граната).
TLK_WOUND		Когда я получил урон.
TLK_HIDEANDRELOAD	Когда я решу спрятаться и перезарядить пистолет.
TLK_PLYR_PHYSATK	Когда в меня попадает предмет, брошенный игроком.

Не все NPC говорят на всех концептах, и не все NPC говорят на концептах при одинаковых обстоятельствах. Полный список см. в список концепций реагирования(en).

Набор Критериев

Критерии - это набор условий, которые содержат данные, связанные с текущим состоянием говорящего и обстоятельствами концепции, когда предпринимается попытка речи. Его можно интерпретировать как набор KeyValues(en). Вот пример набора критериев, созданного npc_alyx, которая пытается говорить, потому что только что убила своего текущего врага:

concept                = TLK_ENEMY_DEAD          Концепт, которое пытается озвучить NPC.
map                    = d3_c17_07               Название текущей карты.
classname              = npc_alyx                Класс сущности (classname(en)) говорящего NPC.
name                   = alyx                    Имя (targetname(en)) говорящего NPC.
health                 = 75                      Текущий уровень здоровья говорящего NPC.
healthfrac             = 0.9375                  Здоровье говорящего NPC, как доля от максимального здоровья NPC (по умолчанию максимальное здоровье npc_alyx равно 80).
skill.cfg              = 1                       Текущий уровень скила.
timesinceseenplayer    = 0.090000                Количество времени, прошедшее с тех пор, как говорящий NPC видел игрока.
distancetoenemy        = 312.639679              Расстояние от говорящего NPC до его текущего врага.
activity               = ACT_RUN                 Анимация, которую выполняет говорящий NPC.
npcstate               = [NPCState::Combat]      Состояние ИИ говорящего NPC.
enemy                  = npc_combine_s           Класс сущности classname(en), выступающей врагом говорящего NPC.
speed                  = 79.235                  Момент скорости говорящего NPC.
weapon                 = weapon_alyxgun          Текущее оружие, которое держит в руках говорящий NPC.
distancetoplayer       = 211.240692              Расстояние от говорящего NPC до игрока.
seeplayer              = 1                       Видит ли говорящий NPC игрока или нет.
seenbyplayer           = 0                       Находится ли говорящий NPC в поле зрения игрока.
readiness              = agitated                Уровень readiness(en) говорящего NPC.
playerhealth           = 100                     Текущий уровень здоровья игрока.
playerhealthfrac       = 1.000                   Текущее здоровье игрока, как доля от его максимального уровня.
playerweapon           = weapon_shotgun          Текущее оружие, которое держит игрок.
playeractivity         = ACT_WALK                Анимация, которую выполняет игрок.
playerspeed            = 0.000                   Текущий момент скорости игрока.

This concept does not have any modifiers by default. All criteria in the above list are general and gathered for each concept.

Criteria such as the ones in the list above can be checked by a rule's list of criteria, and used to make decisions about which response group to use for the desired concept. For instance:

  • The enemy criterion could be used to pick the right response to the TLK_ENEMY_DEAD concept. Instead of making a general statement, Alyx could say "I took care of that soldier!" or "I took care of that headcrab!".
  • The healthfrac field could be used to choose a "Phew, that was close!" line if her health was <20% when she finished off her enemy.
  • The distancetoenemy field could be used to choose different lines for when she killed her enemy at long or short range. i.e. "Those guys are scary when they get that close!" or "It's not easy hitting 'em at that range."

Even though the criteria listed above are general and not concept-specific, the criteria will always vary under different circumstances and might not always be available (i.e. NPCs that aren't in combat won't have enemy or distancetoenemy criteria). Additionally, mapmakers can append extra criteria to specific NPCs, or to all NPCs in the game. See Response contexts(en) for more info.

Rule Criteria

Rules have a list of criteria that are tested against the character's criteria set. When a rule is scored, each criterion is checked against the given data, and the rule receives points for criteria that successfully match. The amount of points a criterion earns for the rule is determined by the criterion's weight.

Criteria are defined inside the script files (see below). The following format is used:

criterion <criterion name> <key to check> <desired value> <optional: weight X> <optional: required>

The parameters are as follows:

criterion name
The name of the criterion. Must not match an existing criterion.
key to check
The key within the character's criteria set that this criterion will check.
desired value
The desired value of the key within the criteria set. This can take multiple forms:
  • Numeric values: "0", "1", or "100".
  • Inverse Numeric values: "!=0" would match if the value is not equal to 0.
  • String value: "npc_alyx", "weapon_alyxgun", or "npc_combine_s".
  • Enumerated(en) value: "[NPCState::Combat]".
  • Ranges:
    • ">0" : Match if the value is greater than 0.
    • "<=0.5" : Match if the value is less than, or equal to, 0.5.
    • ">10,<=50" : Match if the value is greater than 10 and less than, or equal to, 50.
    • ">0,<[NPCState::Alert] : Match if the value is greater than 0 and less then the value of enumeration for NPCState::Alert.
Note.pngПримечание:Does not support wildcards by default.
weight X
An optional parameter, where X is the amount of points this criterion is worth if it matches. If unspecified, criterion are worth 1 point by default.
required
An optional parameter that states that this criterion is required for rules containing it to be used at all. If a required criterion does not match successfully, rules containing it score 0 and are immediately skipped. Most criteria use this parameter.

И вот некоторые примеры из Half-Life 2:

  • Определение критерия, названное PlayerNear обозначает, что расстояние от игрока до говорящего NPC должно составлять хотя бы 500 юнитов.
criterion "PlayerNear" "distancetoplayer" "<500" required
  • Определение критерия, названное IsCitizen обозначает, что класс говорящего NPC должен быть npc_citizen.
criterion "IsCitizen" "classname" "npc_citizen" "required"
  • Определение критерия, названное IsMap_d3_c17_12 обозначает, что текущая игра проходит на карте в названием d3_c17_12.bsp. Пригодится для того, чтобы заставить всех сущностей одной карты произносить реплики, отличные от других карт.
criterion "IsMap_d3_c17_12" "map" "d3_c17_12" "required"
  • Здесь определяется критерий IsBob, назван ли NPC как "bob" ("targetname" "bob"). Это уникальный гражданин в игре, и этот критерий позволяет легко заставить его произносить уникальные реплики.
criterion "IsBob" "targetname" "bob" required
Tip.pngСовет:A concept is a criterion which almost always has a weight of 5.

Rules

A rule contains a list of criteria and at least one response group. The rule receives points for each of the criteria that successfully matches the speaker's criteria set. The highest scoring rule will direct to one of its response groups, which is used to determine the exact speech the NPC will use. Rules are defined inside the script files (see below). The following format is used:

rule <rule name>
{
   criteria <criterion name 1> [optional: <criterion name 2> <criterion name 3> etc.]
   response <response group name> [optional: <response group name 2> etc.]
   [optional: matchonce]
   [optional: applyContext <data>]
}

The parameters are as follows:

  • rule name : The name of the rule. Must not match an existing rule.
  • criteria : The list of criteria the rule should score with.
  • response : The list of response groups that should be chosen if this rule scores the highest.
  • matchonce : An optional parameter which, if specified, causes this rule to be deactivated once it has been chosen once.
  • applyContext : An optional parameter which applies a response context(en).

For example, the following text defines a rule called CitizenTalkStare. ConceptTalkStare is a criterion that checks to make sure the concept the speaking NPC wants to speak is "TLK_STARE". IsCitizen is a criterion that checks to make sure the speaking NPC is a citizen(en). NPCIdle is a criterion that checks to make sure the NPC's state is "NPCState::Idle". If this rule scores highest, the response group that will be used is CitizenTalkStare.

rule CitizenTalkStare
{
   criteria     ConceptTalkStare IsCitizen NPCIdle
   response     CitizenTalkStare
}

Note that the rule name and the response group name can be identical because rule names need only be unique amongst rules, and response groups names only unique amongst groups.

Response Groups

A response group contains a set of possible responses, along with some optional data that defines how the responses should be used. When a response group is chosen by a rule, a response is chosen from the list and given back to the speaker to use. Response groups are defined inside the script files (see below). The following format is used:

response <response group name>
{
   [optional: permitrepeats]
   [optional: sequential]	  
   [optional: norepeat]		  

   <response type> <response> <optional: ...>
   <response type> <response> <optional: ...>
   <response type> <response> <optional: ...>
}

The response group parameters are as follows:

  • permitrepeats : If specified, responses in this group are allowed to repeat. If unspecified, the default behavior is to use all responses in the list before repeating any,
  • sequential : If specified, responses will be used in the order they're listed in the group. If unspecified, the default behavior is to randomly choose responses from the list.
  • norepeat : If specified, once all responses in the list have been played, the response group will be disabled. Any rules that choose this response group will return no response to the speaker.

Responses

The response is the actual response which is selected by the system and then used by the speaker. A response group can list as many responses as desired, with each response being one of the following types:

  • speak : The response is a soundscript(en) or raw audio file.
  • sentence : The response is a sentence name from sentences.txt.
  • scene : The response is a .vcd file. See Choreography Implementation(en) for more information.
  • response : The response is a reference to another response group which should be selected instead.
  • print : The response is some text that should be printed at the speaker's position in developer 1 (used for placeholder responses).
    Note.pngПримечание:Mapbase Mapbase replaces this with game_text-like screen messages by default.
  • entityio (Во всех играх начиная с Alien Swarm)[подтвердить](также в Mapbase) : The response is an I/O event(en) which fires on a specific entity with the speaker as the activator. The format is entityio "<name> <input> <param>". This is different from followup responses, which are covered in more detail farther below.
  • vscript (только в Mapbase) : The response is a line of VScript(en) code that runs from the scope of the speaker.
  • vscript_file (только в Mapbase) : The response is a path to a VScript file that runs from the scope of the speaker.

Post-response delay parameters

Each response supports a variety of optional parameters.

    • nodelay : After the response has finished, the speaker is allowed to speak again immediately.
    • defaultdelay : After the response has finished, the speaker won't be allowed to speak for a random amount, between 2.8 & 3.2 seconds.
    • delay X : After the response has finished, the speaker won't be allowed to speak for X seconds. X can also be a range, e.g. "5.5,7.5"
  • weapondelay X : When the response starts, the speaker will not fire their weapon for X seconds. Only available on HL2 NPC allies by default.
  • speakonce : Prevents the response from being used more than once.
  • odds X : If specified, then when this response is chosen, there is a chance the speaker will say nothing instead of saying the response. The odds is a (0-100)% chance of canceling the response, meaning an odds of 25 gives a 25% chance of saying nothing.
  • respeakdelay : If specified, this response may not be used unless the concept hasn't been spoken in at least X seconds. X can also be a range, e.g. "5.5,7.5"
  • soundlevel : If specified, this soundlevel should be used for the response instead of the default SNDLVL_TALKING.
  • displayfirst : If specified, this response should be used first (ignores the weight parameter).
  • displaylast : If specified, this response should be used last (ignores the weight parameter).
  • weight : If specified, used to weight the selection of the responses in the list. By default, all responses have a weight of 1. Please note that responses won't be repeated until all of the other responses have been chosen, meaning once all of the high-weight responses are chosen, the system will only count the responses of less weight. This can be counteracted with permitrepeats.
  • noscene : Stops the Response System from creating an auto-generated scene for a speak response.
  • stop_on_nonidle : When the response is spoken, stop the scene when the NPC enters a non-idle state. In Source 2013, only works in HL2 episodic mods on scene responses.
  • predelay : When the response is chosen, it won't actually be spoken until X seconds have passed. Only works on scene responses. X can also be a range, e.g. "5.5,7.5"

For example, the following response group is used by citizens(en) to respond to the TLK_STARE concept. Citizens will use the responses in the list in the order they're listed (due to the sequential parameter). Each response, when chosen, stops the NPC from talking for a random amount of time between 10 & 20 seconds.

response "CitizenTalkStare"
{
   sequential
   scene "scenes/npc/$gender01/doingsomething.vcd" delay "10,20"
   scene "scenes/npc/$gender01/getgoingsoon.vcd"  delay "10,20"
   scene "scenes/npc/$gender01/waitingsomebody.vcd"  delay "10,20"
}

Script files

The /scripts/talker/response_rules.txt is the base script file that contains all the criteria, rules, and response groups used by the Response Rules System. The file can also include other files using the #include keyword, which allows you to cleanly divide the rules up according to NPC, map, and so on. Note that some entities, like the env_speaker(en), specify their script files that contain a subset of the criteria, rules, and response groups for the entity to use. See scripts/talker/terminal_pa.txt for an example used by the terminal announcement at the train station.

Followup responses

Left 4 Dead Left 4 Dead introduced "followups", events which occur following the response. They are triggered as response parameters similar to odds, predelay, etc.

Cpp.pngКод:The code for the followup system is available in the Alien Swarm SDK(en), along with the rest of the rewritten response system. (также в Mapbase)
  • fire : Fires an input through the I/O system with the speaker as the activator and caller. Format is fire <target> <input> <delay>. Does not support parameters.
  • then : Causes another response to be dispatched on an entity. Format is then <target> <concept> <response contexts> <delay>. Used for making characters dynamically respond to each other.
Note.pngПримечание:A negative delay causes the followup to be dispatched X amount of time after the speaker starts speaking, as opposed to when they're finished speaking.

A few unique targetnames can be used:

  • self : The entity speaking the response.
  • subject : Uses the entity name found in the speaker's "Subject" context, if it exists. The game sets this for info_remarkable responses.
  • from : Uses the entity name found in the speaker's "From" context, if it exists. The game sets this to the name of the previous followup respondent, allowing followups to bounce back and forth.
  • any : Dispatched to any valid respondent within the range stored in rr_followup_maxdist (1800 by default).
  • all : Dispatched to all valid respondents within the range stored in rr_followup_maxdist (1800 by default).
Note.pngПримечание:The "Subject" and "From" contexts only store entity names, so be careful when there are multiple potential targets with the same name!

Example from Left 4 Dead 2 in coach.txt:

Response _c1m4startelevator4bCoach
{
	scene "scenes/Coach/WorldC1M4B01.vcd"  then mechanic _c1m4startelevator5a foo:0 -2.313 //Son, you got a DEAL.
	scene "scenes/Coach/WorldC1M4B02.vcd"  then mechanic _c1m4startelevator5a foo:0 -5.790 //Ha HA! All the way to New Orleans! Baby, that sounds like a PLAN.
	scene "scenes/Coach/WorldC1M4B05.vcd"  then mechanic _c1m4startelevator5b foo:0 -6.334 //Normally I wouldn't do this. But in these circumstances, I think Mr. Gibbs, Jr. ain't gonna mind.
	scene "scenes/Coach/WorldC1M4B10.vcd"  then mechanic _c1m4startelevator5b foo:0 -2.685 //Forgive us Jimmy, but we need your car.
}

Advanced response rules usage

The Response System can be used in many advanced and specialized ways. Here's a few tips and tricks for advanced usage of the system:

Firing custom responses with DispatchResponse
Absolutely anything can be passed to an NPC as a response concept, so long as it is to be found somewhere in the script files. You aren't limited to the AI's predefined TLK_* concepts at all.
For example, you might want NPCs from a onlooking group to speak congratulatory response concepts when a player successfully solves part of a puzzle.
Player allies in HL2 also have a SpeakResponseConcept input with more advanced handling and conditions.

See the response scripts for Alyx in EP1/EP2 or the response scripts for the L4D survivors for more examples of advanced response system usage.

Debugging

Нужно сделать: rr_debugresponses(en)

Notes

  • To be able to use the Response Rules system, an NPC must be derived from the CAI_BaseActor(en) class.
  • See the scripts/talker/npc_*.txt files for examples of specific NPC response rules.
  • The scripts/talker/response_rules.txt is the manifest for the response rules system. If you add new response rule script files for your new NPC, make sure you #include it at the end of the scripts/talker/response_rules.txt file.

See also

External links