Skip to content
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

[PORT] Turret AI #731

Merged
merged 4 commits into from
Jan 2, 2025
Merged

[PORT] Turret AI #731

merged 4 commits into from
Jan 2, 2025

Conversation

CrimeMoot
Copy link
Collaborator

@CrimeMoot CrimeMoot commented Jan 2, 2025

Теперь ЦИИ может с помощью ПКМ настроить турели на атаку по определённым целям.
Есть 3 режима целей:

  • Никто
  • Враждебные
  • Все

Но он может настраивать только турели с определённым компонентом, которых пока что нет на картах.

space-syndicate/space-station-14-next@d6b89e7
space-syndicate/space-station-14-next@9dc9373
space-syndicate/space-station-14-next@5418be6

Summary by CodeRabbit

  • Новые функции

    • Добавлена система управления турелями с тремя режимами: "Никто", "Враждебные" и "Все".
    • Турели теперь могут иметь различные настройки фракционной принадлежности.
  • Локализация

    • Добавлены русскоязычные строки для управления турелями.
  • Компоненты

    • Введены новые компоненты для контроля и взаимодействия с турелями: TurretControllableComponent, TurretControllerComponent и TurretControlSystem.
  • Фракции

    • Добавлены новые фракции для турелей: TurretPassive, TurretPeace и TurretHostile.

Copy link

coderabbitai bot commented Jan 2, 2025

Warning

Rate limit exceeded

@CrimeMoot has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 49 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f3a35ff and 138c8fb.

📒 Files selected for processing (1)
  • Resources/Prototypes/_SpaceCats/ai_factions.yml (1 hunks)

Walkthrough

Представлен новый механизм управления турелями, который позволяет изменять режимы их работы. Система включает новые компоненты TurretControllableComponent и TurretControllerComponent, а также систему TurretControlSystem. Добавлены три режима контроля турелей: "Никто", "Враждебные" и "Все". Функциональность реализована для администраторов-призраков и станционного ИИ с возможностью переключения режимов работы турелей.

Changes

Файл Изменения
Content.Shared/Verbs/VerbCategory.cs Добавлен новый статический экземпляр TurretControlMode
Content.Shared/_Cats/TurretControl/Components/ Добавлены компоненты TurretControllableComponent и TurretControllerComponent
Content.Shared/_Cats/TurretControl/TurretControlSystem.cs Создана новая система управления турелями
Resources/Prototypes/Entities/Mobs/Player/ Добавлен компонент TurretController для администраторов-призраков и станционного ИИ
Resources/Prototypes/_SpaceCats/ Введены новые фракции турелей и прототип турели с управлением

Sequence Diagram

sequenceDiagram
    participant User
    participant Turret
    participant TurretControlSystem
    
    User->>TurretControlSystem: Выбор режима управления
    TurretControlSystem->>Turret: Установка режима фракции
    TurretControlSystem->>Turret: Обновление поведения
Loading

Poem

🤖 Турель, турель, послушный страж,
Режимы смены - просто шаж!
Никто, враждебный или все -
Контроль у нас теперь в красе!
Да здравствует турельный драйв! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
Content.Shared/_Cats/TurretControl/Components/TurretControllableComponent.cs (1)

3-4: Новый компонент без логики.
Рекомендуется добавить XML-комментарии (докстринг) для уточнения назначения и использования компонента в будущем.

Content.Shared/_Cats/TurretControl/Components/TurretControllerComponent.cs (1)

5-10: Добавление TurretControllerComponent выглядит разумно.
Подумайте о том, чтобы сделать поле RequiredComponents неизменяемым (например, объявить как readonly или использовать неизменяемую коллекцию), если в рантайме вам не нужно динамически изменять этот список. Это повысит надежность и упростит чтение кода.

Content.Shared/_Cats/TurretControl/TurretControlSystem.cs (1)

56-63: SetFaction удаляет все предыдущие фракции и добавляет только одну.
Убедитесь, что подобное поведение соответствует игровому замыслу и не нужно ли сохранять некоторые фракции при переключении режима турели.

Resources/Prototypes/_SpaceCats/Entities/Objects/Weapons/Guns/turrets.yml (1)

9-9: Добавьте пустую строку в конец файла

Для соответствия стандартам YAML необходимо добавить пустую строку в конец файла.

🧰 Tools
🪛 yamllint (1.35.1)

[error] 9-9: no new line character at the end of file

(new-line-at-end-of-file)

Resources/Prototypes/_SpaceCats/ai_factions.yml (1)

37-37: Добавьте пустую строку в конец файла

Для соответствия стандартам YAML необходимо добавить пустую строку в конец файла.

🧰 Tools
🪛 yamllint (1.35.1)

[error] 37-37: no new line character at the end of file

(new-line-at-end-of-file)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec207b6 and 97a343e.

📒 Files selected for processing (9)
  • Content.Shared/Verbs/VerbCategory.cs (1 hunks)
  • Content.Shared/_Cats/TurretControl/Components/TurretControllableComponent.cs (1 hunks)
  • Content.Shared/_Cats/TurretControl/Components/TurretControllerComponent.cs (1 hunks)
  • Content.Shared/_Cats/TurretControl/TurretControlSystem.cs (1 hunks)
  • Resources/Locale/ru-RU/_Cats/turret-control.ftl (1 hunks)
  • Resources/Prototypes/Entities/Mobs/Player/admin_ghost.yml (1 hunks)
  • Resources/Prototypes/Entities/Mobs/Player/silicon.yml (1 hunks)
  • Resources/Prototypes/_SpaceCats/Entities/Objects/Weapons/Guns/turrets.yml (1 hunks)
  • Resources/Prototypes/_SpaceCats/ai_factions.yml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Resources/Locale/ru-RU/_Cats/turret-control.ftl
🧰 Additional context used
🪛 yamllint (1.35.1)
Resources/Prototypes/_SpaceCats/Entities/Objects/Weapons/Guns/turrets.yml

[error] 9-9: no new line character at the end of file

(new-line-at-end-of-file)

Resources/Prototypes/_SpaceCats/ai_factions.yml

[error] 37-37: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (14)
Content.Shared/_Cats/TurretControl/Components/TurretControllableComponent.cs (1)

1-1: Использование пространства имен выглядит корректно.

Content.Shared/_Cats/TurretControl/Components/TurretControllerComponent.cs (2)

1-1: Импорт Robust.Shared.Prototypes используется по назначению.


3-3: Выбор пространства имен соответствует структуре проекта.

Content.Shared/_Cats/TurretControl/TurretControlSystem.cs (7)

1-5: Необходимые пространства имен импортированы корректно.


7-8: Пространство имен выглядит логичным и следует общей структуре проекта.


9-12: Класс TurretControlSystem корректно наследуется от EntitySystem.
Убедитесь, что внедрение зависимостей (Dependency) инициализировано при старте.


13-21: Статические константы для идентификаторов фракций.
Убедитесь, что данные прототипы "TurretPassive", "TurretPeace", "TurretHostile" существуют и правильно настроены.


22-25: Инициализация системы и подписка на событие GetVerbsEvent произведены верно.


27-42: Метод OnGetVerbs проверяет необходимые компоненты корректно.
Убедитесь, что условие if (!HasComp(e.User, component.Value.Component.GetType())) ... действительно отражает логику, при которой контроллер даёт право переключать режимы. Если возможна ситуация, когда часть компонентов не требуется, стоит продумать более гибкие проверки.


44-54: CreateVerb аккуратно инкапсулирует логику создания нового верба.
Добавлена понятная локализация через Loc.GetString, что упрощает перевод.

Content.Shared/Verbs/VerbCategory.cs (1)

89-89: Добавлена новая категория вербов TurretControlMode.
Категория успешно интегрируется с системой вербов, что расширяет функционал управления турелями.

Resources/Prototypes/_SpaceCats/Entities/Objects/Weapons/Guns/turrets.yml (1)

1-9: Структура сущности выглядит правильной

Компоненты NpcFactionMember и TurretControllable корректно настроены для реализации управления турелью.

🧰 Tools
🪛 yamllint (1.35.1)

[error] 9-9: no new line character at the end of file

(new-line-at-end-of-file)

Resources/Prototypes/Entities/Mobs/Player/admin_ghost.yml (1)

100-100: Компонент TurretController добавлен корректно

Интеграция компонента TurretController в сущность AdminObserver выполнена правильно и не нарушает существующую функциональность.

Resources/Prototypes/Entities/Mobs/Player/silicon.yml (1)

439-441: Корректная реализация компонента управления турелями!

Добавление компонента TurretController с зависимостью от StationAiHeld логично интегрируется в сущность StationAiBrain и соответствует целям PR по реализации управления турелями через ИИ.

Давайте проверим корректность реализации компонента:

✅ Verification successful

Подтверждаю корректность реализации управления турелями!

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

  • TurretControllerComponent требует наличие StationAiHeld, что обеспечивает контроль только со стороны ИИ станции
  • TurretControllableComponent корректно маркирует турели, которыми можно управлять
  • TurretControlSystem реализует логику управления с тремя режимами работы турели:
    • Пассивный (не атакует никого)
    • Мирный (атакует только враждебные цели)
    • Враждебный (атакует всех)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Проверяем наличие всех необходимых компонентов
# и их взаимодействие в системе

# Поиск определений компонентов
echo "Поиск определений компонентов:"
ast-grep --pattern 'class TurretController'
ast-grep --pattern 'class TurretControllableComponent'

# Поиск использования компонентов в системах
echo "Поиск использования в системах:"
ast-grep --pattern 'class TurretControlSystem'

Length of output: 66025


Script:

#!/bin/bash
# Поиск определений и использования компонентов TurretController
echo "=== Поиск файлов с TurretControl ==="
fd -e cs -e yml "TurretControl"

echo -e "\n=== Содержимое файлов с TurretControl ==="
fd -e cs -e yml "TurretControl" -x cat {}

echo -e "\n=== Поиск использования в системах ==="
rg -l "TurretController" --type cs

Length of output: 3403

hostile:
- Dragon
- SimpleHostile
- Xeno
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Удалите дублирующуюся запись фракции Xeno

В списке hostile фракции TurretPeace фракция Xeno указана дважды.

  hostile:
  - Dragon
  - SimpleHostile
  - Xeno
  - Blob
  - Flesh
- - Xeno
  - Zombie

Also applies to: 12-12

Comment on lines 1 to 37
- type: npcFaction
id: TurretPassive

- type: npcFaction
id: TurretPeace
hostile:
- Dragon
- SimpleHostile
- Xeno
- Blob
- Flesh
- Xeno
- Zombie

- type: npcFaction
id: TurretHostile
hostile:
- Dragon
- NanoTrasen
- Mouse
- Passive
- PetsNT
- SimpleHostile
- SimpleNeutral
- Syndicate
- Xeno
- Zombie
- Revolutionary
- Blob
- SuperZloy
- Spanish
- Britan
- SpecialForce
- CombineForce
- CentralCommand
- FleshHuman
- Flesh
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Обнаружены несоответствия в списках враждебных фракций

В файле Resources/Prototypes/_SpaceCats/ai_factions.yml найдены следующие проблемы:

  • В списке TurretPeace дублируется фракция Xeno
  • В списке TurretHostile отсутствуют фракции Changeling, Diona, GlimmerMonster, PsionicInterloper, ShadowkinDarkHostile, ShadowkinDarkFriendly, MalfunctioningRobot, AiEnemy, AiTurret, которые определены в кодовой базе
  • В списке TurretHostile присутствует фракция FleshHuman, которая не определена в кодовой базе

Рекомендации:

  • Удалить дублирующуюся запись Xeno из списка TurretPeace
  • Рассмотреть необходимость добавления отсутствующих фракций в список TurretHostile
  • Удалить или определить фракцию FleshHuman
🔗 Analysis chain

Проверьте полноту списков враждебных фракций

Убедитесь, что списки враждебных фракций полные и актуальные. Рекомендуется проверить:

  1. Все ли необходимые фракции включены
  2. Нет ли устаревших или неиспользуемых фракций
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Описание: Поиск всех определений фракций в кодовой базе
rg -g '*.yml' 'type:\s*npcFaction' -A 3

Length of output: 8188

🧰 Tools
🪛 yamllint (1.35.1)

[error] 37-37: no new line character at the end of file

(new-line-at-end-of-file)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
Resources/Prototypes/_SpaceCats/ai_factions.yml (1)

6-13: ⚠️ Potential issue

Обнаружено дублирование фракции Xeno

В списке hostile фракции TurretPeace фракция Xeno указана дважды (строки 9 и 12).

  hostile:
  - Dragon
  - SimpleHostile
  - Xeno
  - Blob
  - Flesh
- - Xeno
  - Zombie
🧹 Nitpick comments (1)
Resources/Prototypes/_SpaceCats/ai_factions.yml (1)

36-36: Добавьте пустую строку в конец файла

Согласно стандартам YAML, файл должен заканчиваться пустой строкой.

  - Flesh
+ 
🧰 Tools
🪛 yamllint (1.35.1)

[error] 36-36: no new line character at the end of file

(new-line-at-end-of-file)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 97a343e and f3a35ff.

📒 Files selected for processing (1)
  • Resources/Prototypes/_SpaceCats/ai_factions.yml (1 hunks)
🧰 Additional context used
🪛 yamllint (1.35.1)
Resources/Prototypes/_SpaceCats/ai_factions.yml

[error] 36-36: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (2)
Resources/Prototypes/_SpaceCats/ai_factions.yml (2)

1-3: Корректное определение пассивной фракции турели

Определение фракции TurretPassive соответствует режиму "Никто" и реализовано правильно.


17-36: Требуется проверка определений фракций

Необходимо проверить корректность списка враждебных фракций:

  1. Отсутствуют следующие определенные в кодовой базе фракции:

    • Changeling
    • Diona
    • GlimmerMonster
    • PsionicInterloper
    • ShadowkinDarkHostile
    • ShadowkinDarkFriendly
    • MalfunctioningRobot
    • AiEnemy
    • AiTurret
  2. Рекомендуется проверить актуальность существующих фракций.

✅ Verification successful

Let me verify the existence and location of these factions with another search to ensure we have complete information.


Определения фракций в файле корректны

После анализа всех определений фракций в кодовой базе можно сделать следующие выводы:

  1. Все перечисленные в комментарии "отсутствующие" фракции на самом деле определены в других файлах и не должны быть добавлены в список враждебных фракций для TurretHostile, так как:

    • Changeling имеет свой собственный список враждебных фракций
    • GlimmerMonster и PsionicInterloper враждебны только друг другу
    • ShadowkinDarkHostile и ShadowkinDarkFriendly враждебны только друг другу
    • AiEnemy и AiTurret враждебны только друг другу
    • MalfunctioningRobot имеет свой специфический список враждебных фракций
    • Diona определена отдельно со своим списком враждебных фракций
  2. Текущий список враждебных фракций для TurretHostile полностью соответствует логике игры и не требует дополнений.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Описание: Поиск определений фракций в кодовой базе
rg -g '*.yml' 'id:\s*(Changeling|Diona|GlimmerMonster|PsionicInterloper|ShadowkinDarkHostile|ShadowkinDarkFriendly|MalfunctioningRobot|AiEnemy|AiTurret)'

Length of output: 5827


Script:

#!/bin/bash
# Поиск всех определений фракций в файлах ai_factions.yml
fd -g '*ai_factions.yml' --exec cat {}

Length of output: 6182

🧰 Tools
🪛 yamllint (1.35.1)

[error] 36-36: no new line character at the end of file

(new-line-at-end-of-file)

@CrimeMoot CrimeMoot merged commit 0cfaf5c into master Jan 2, 2025
12 checks passed
@CrimeMoot CrimeMoot deleted the turret_ai branch January 2, 2025 08:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant