Skip to content
This repository was archived by the owner on Aug 22, 2025. It is now read-only.

Conversation

@kurokoTurbo
Copy link
Contributor

@kurokoTurbo kurokoTurbo commented Jun 15, 2024

Описание PR

Генетика

Чек-лист (неактуален, обновлять его особо не буду):

  • Rechecked all my code

система в общем

  • подвязать нормально прототипы к MutationEffect (точнее протестить это с помощью дебаг-мутации)
  • написать дебаг-мутацию для тестов (х-рей) (надо в клиентском eyecomponent DrawFov = false поставить)
  • раундстартом случайно инициализировать генетические последовательности для мутаций, 32 бит каждая. последовательности должны быть уникальны. еще присвоить уникальный двузначный номер каждой мутации
  • на компините инициализировать геном сущности с геномкомпонентом: берешь последовательность для мутации, случайно меняешь в этой последовательности несколько (неогранченное число, но с убывающей вероятностью) оснований, сохраняешь от какой мутации инитнул последовательность в геномлейаут или в геномкомпоненте. к каждой последовательности генеришь комплиментарную последовательность. то есть чтобы каждое основание первой последовательности было комплиментарно основанию комплиментарной последовательности с таким же индексом (А - Т, C - G)
  • ивент, который будет бродкаститься если что-то изменило геном человека
  • если сущность может получать радиацию, надо сделать ей шанс случайно попереворачивать биты в геноме от радиации и шанс зароллить добавление еще одной последовательности в лейаут с уже активированной случайно мутацией

дна консоль

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

мутаторы

  • добавляет в лейаут последовательность в дополнение к обычным последовательностям
  • применяет мутацию
  • добавляет инстабилити

активатор

  • если у сущности есть последовательность, инитная от мутации активатора, активирует эту мутацию и делает последовательность в геноме равной последовательности мутации. инстабилити не добавляет

мутадон (реагент)

  • деактивирует мутации
  • удаляет последовательности, если мутации добавлены мутатором
  • случайно переворачивает биты в активированных активатором последовательностях

typo:

  • Feature
  • Fix
  • Tweak
  • Balance

Изменения

Changelog

🆑 MJ Sailor, CaypenNow

  • add: Генетика!

Summary by CodeRabbit

  • New Features

    • Added DNAConsoleBoundUserInterface class to manage DNA console window UI.
    • Introduced user interface layout for DNA console window in DNAConsoleWindow.xaml.
    • Added DNAConsoleWindow class to populate UI elements based on DNA console state.
    • Implemented DNAModifierComponent class to manage DNA modification functionality.
    • Introduced DNAScannerBoundUserInterface for managing DNA scanner UI.
    • Added DNAScannerComponent for scanning genetic material with configurable settings.
    • Implemented DNAScannerSystem to handle interactions with the DNA scanner.
    • Added GenomeSystem for managing genetic components and mutations.
    • Introduced GeneticInjectorComponent for managing genetic injection mechanics.
  • Bug Fixes

    • Updated ActiveModifierComponent for improved tracking in the cloning process.
  • Documentation

    • Added GlowingMutation class for mutation effects related to entity lighting.
  • Refactor

    • Improved genetic mutation handling in GenomeSystem.Mutations.cs.
    • Added GeneticInjectorSystem to manage genetic injections efficiently.

@rhailrake
Copy link
Contributor

@coderabbitai summary

@coderabbitai
Copy link

coderabbitai bot commented Jun 17, 2024

Actions performed

Summary regeneration triggered.

@coderabbitai
Copy link

coderabbitai bot commented Jun 17, 2024

Walkthrough

The recent updates introduce a comprehensive suite of new classes and components that enhance genetic manipulation features within the client and server modules. Key improvements include user interface advancements for DNA consoles and scanners, alongside robust systems for managing genetic traits and mutations, significantly enriching gameplay interactions in the genetics domain.

Changes

File Change Summary
DNA Console UI Introduces DNAConsoleBoundUserInterface for managing the DNA console UI; implements DNAConsoleWindow with a structured layout for displaying information and updates.
DNAModifier and Components Adds DNAModifierComponent, ActiveModifierComponent, and DNAConsoleComponent to manage DNA modifiers and their interactions within the genetics framework.
Genetic Injector System Introduces GeneticInjectorComponent and GeneticInjectorSystem for handling genetic injections and mutations, including events for user interactions.
DNA Scanner UI and Functions Adds DNAScannerBoundUserInterface and DNAScannerWindow, enhancing user experience with scanning operations. Introduces DNAScannerComponent and DNAScannerSystem for scanning functionality.
Genome Management Implements GenomeComponent and GenomeSystem for managing genetic traits, mutations, and their application mechanics within the game.
Messaging and Events Introduces DNAScannerScannedGenomeMessage for UI communication related to genetic data, along with DNAScannerDoAfterEvent for managing delayed actions.
Utilities and Controls Defines DNAScannerUiKey enum for managing UI states related to DNA scanning, ensuring modularity and clarity in the system.
Prototypes and Assets Introduces YAML configurations for DNA-related components and devices, including properties for genetic modifications and operational states.

Poem

🐇 In code we weave a tapestry,
With DNA's dance, a mystery.
Scanners whir, and windows bloom,
Genetic wonders chase the gloom.
A rabbit's joy, in bytes we 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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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: 21

Outside diff range and nitpick comments (4)
Content.Server/_White/Genetics/Components/GenomeComponent.cs (2)

6-9: Clarify the component's functionality in the summary.

The summary comment could be more specific about how other systems interact with this component to utilize the genome data.


10-10: Translate the TODO comment.

The TODO comment is in a non-English language, which might not be accessible to all developers. Consider translating it to English to maintain consistency and accessibility in the codebase.

Content.Client/_White/DNAConsole/DNAConsoleBoundInterface.cs (1)

12-12: Constructor documentation needed.

The constructor for DNAConsoleBoundUserInterface is not documented. Adding XML documentation comments would improve code readability and maintainability, especially for new developers.

Content.Shared/_White/Genetics/Genome.cs (1)

190-197: Method documentation needed.

The Extend method is marked with a TODO comment but lacks a clear description of its purpose and usage. Proper documentation would improve maintainability.

"Please add a summary documentation comment explaining the purpose and use cases for the Extend method."

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b6d9ee4 and 39c9d1d.

Files ignored due to path filters (10)
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/closed.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/closed_unpowered.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/idle_unlit.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/maint_unlit.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/occupied.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/occupied_unlit.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/off_unlit.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/open.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/open_unpowered.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/red_unlit.png is excluded by !**/*.png
Files selected for processing (24)
  • Content.Client/_White/DNAConsole/DNAConsoleBoundInterface.cs (1 hunks)
  • Content.Client/_White/DNAConsole/DNAConsoleWindow.xaml (1 hunks)
  • Content.Client/_White/DNAConsole/DNAConsoleWindow.xaml.cs (1 hunks)
  • Content.Client/_White/DNAModifier/DNAModifierComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/ActiveModifierComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/DNAConsoleComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/DNAModifierComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/GenomeComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/DNAConsoleSystem.cs (1 hunks)
  • Content.Server/_White/Genetics/DNAModifierSystem.cs (1 hunks)
  • Content.Server/_White/Genetics/GenomeSystem.cs (1 hunks)
  • Content.Server/_White/Genetics/MutationSystem.cs (1 hunks)
  • Content.Shared/_White/DNAConsole/SharedDNAConsole.cs (1 hunks)
  • Content.Shared/_White/DNAModifier/SharedDNAModifierComponent.cs (1 hunks)
  • Content.Shared/_White/Genetics/GenesPrototype.cs (1 hunks)
  • Content.Shared/_White/Genetics/Genome.cs (1 hunks)
  • Content.Shared/_White/Genetics/GenomeLayout.cs (1 hunks)
  • Content.Shared/_White/Genetics/GenomePrototype.cs (1 hunks)
  • Content.Shared/_White/Genetics/MutationCollectionPrototype.cs (1 hunks)
  • Content.Shared/_White/Genetics/MutationEffect.cs (1 hunks)
  • Content.Shared/_White/Genetics/MutationPrototype.cs (1 hunks)
  • Content.Shared/_White/Genetics/Mutations/XrayMutation.cs (1 hunks)
  • Resources/Prototypes/White/genetic_prototypes.yml (1 hunks)
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/meta.json (1 hunks)
Files not reviewed due to errors (4)
  • Content.Client/_White/DNAConsole/DNAConsoleWindow.xaml (no review received)
  • Content.Shared/_White/DNAConsole/SharedDNAConsole.cs (no review received)
  • Content.Server/_White/Genetics/GenomeSystem.cs (no review received)
  • Content.Server/_White/Genetics/DNAModifierSystem.cs (no review received)
Additional comments not posted (20)
Content.Client/_White/DNAModifier/DNAModifierComponent.cs (1)

5-8: Approved the class definition and registration.

The DNAModifierComponent class is correctly defined and registered as a component. The inheritance from SharedDNAModifierComponent ensures it's part of the shared logic across client and server, which is a good practice for maintainability and consistency.

Content.Server/_White/Genetics/Components/ActiveModifierComponent.cs (1)

3-9: Approved the component definition for cloning pods.

The ActiveModifierComponent is appropriately commented and registered. The description clearly indicates its purpose as a tracking component for cloning pods, which aligns well with the genetics system's architecture.

Content.Shared/_White/Genetics/MutationEffect.cs (1)

5-13: Approved the abstract class and record struct for mutation effects.

The MutationEffect abstract class is well-defined with appropriate attributes (ImplicitDataDefinitionForInheritors and MeansImplicitUse), which enhance its usability in inherited classes. The MutationEffectArgs record struct is succinctly defined, encapsulating necessary entities for mutation effects.

Content.Shared/_White/DNAModifier/SharedDNAModifierComponent.cs (1)

5-21: Approved the enums for DNA modifier states.

The enums DNAModifierVisual and DNAModifierStatus are well-defined with appropriate serialization attributes (Serializable, NetSerializable). These attributes are crucial for ensuring that these enums can be correctly serialized and deserialized across the network, which is essential for a multiplayer game environment.

Content.Shared/_White/Genetics/GenesPrototype.cs (1)

17-18: Well-defined boolean gene set.

The Bools field is correctly defined and uses a HashSet<string> which is appropriate for ensuring unique entries without specified order.

Content.Shared/_White/Genetics/MutationPrototype.cs (1)

22-23: Sensible default for mutation instability.

The optional nature and default value of 0 for the Instability field is appropriate, ensuring that mutations are stable unless explicitly defined otherwise.

Content.Shared/_White/Genetics/GenomePrototype.cs (1)

23-24: Well-defined genome structure mapping.

The ValueBits dictionary is appropriately marked as required and provides a clear mapping of genome data, ensuring robust data integrity and usability.

Resources/Textures/White/Objects/Devices/dna_modifier.rsi/meta.json (1)

1-67: Well-defined animation states and clear licensing.

The animation states for the DNA modifier are properly defined with appropriate delays, and the licensing is clearly stated, ensuring legal clarity and operational functionality.

Content.Server/_White/Genetics/Components/GenomeComponent.cs (2)

41-41: Review default Genome initialization.

Similar to Layout, ensure that initializing Genome with new() does not lead to issues where the instance is expected to have specific initial state or configuration.

Verification successful

Review default Genome initialization.

The Genome object in the GenomeComponent class is initialized with new(), which means it is instantiated with its default constructor. This initialization is straightforward and does not indicate any specific configuration or state requirements.

  • The Genome object is declared and initialized as follows:
    [DataField]
    public Genome Genome = new();

There are no additional initializations or configurations applied to the Genome object within the GenomeComponent class. Therefore, it is reasonable to conclude that the default initialization does not lead to issues where the instance is expected to have a specific initial state or configuration.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Check if Genome is properly initialized before use.
ast-grep --lang csharp --pattern $'class GenomeComponent {
  Genome Genome = $$$;
  $$$
}'

Length of output: 91



Script:

#!/bin/bash
# Locate the GenomeComponent class definition and inspect the initialization of the Genome object.
ast-grep --lang csharp --pattern 'class GenomeComponent { $$$ }'

Length of output: 66



Script:

#!/bin/bash
# Locate the file containing the GenomeComponent class.
fd 'GenomeComponent.cs'

# Once we have the file, inspect the initialization of the Genome object within it.
file_path=$(fd 'GenomeComponent.cs')
if [ -n "$file_path" ]; then
  echo "Inspecting file: $file_path"
  ast-grep --lang csharp --pattern 'class GenomeComponent { $$$ }' "$file_path"
else
  echo "GenomeComponent.cs file not found."
fi

Length of output: 549



Script:

#!/bin/bash
# Specifically target the initialization of the Genome object within the GenomeComponent class.
ast-grep --lang csharp --pattern 'class GenomeComponent {
  public Genome Genome = new();
  $$$
}' Content.Server/_White/Genetics/Components/GenomeComponent.cs

Length of output: 161



Script:

#!/bin/bash
# Print the entire content of the GenomeComponent.cs file to inspect the initialization of the Genome object.
cat Content.Server/_White/Genetics/Components/GenomeComponent.cs

Length of output: 1426


25-25: Initialization of Layout.

The direct initialization of Layout with new() might not be ideal if it depends on specific setup steps. Ensure that this does not lead to uninitialized state issues where the Layout is expected to be fully configured upon creation.

Verification successful

Initialization of Layout verified.

The GenomeLayout class is defined with a default constructor and does not have any complex initialization requirements. The GenomeComponent class initializes Layout with new(), and based on the extracted context, it appears to be properly set up for use.

  • GenomeLayout contains a dictionary Values and an integer TotalBits, which are initialized directly.
  • There are no specific setup steps or dependencies required for GenomeLayout upon creation.
  • The GenomeComponent class uses Layout in a straightforward manner, ensuring it is ready for use.

No issues found with the initialization of Layout.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that GenomeLayout is properly initialized before use.
ast-grep --lang csharp --pattern $'class GenomeComponent {
  GenomeLayout Layout = $$$;
  $$$
}'

Length of output: 97



Script:

#!/bin/bash
# Find the definition and constructors of GenomeLayout class
ast-grep --lang csharp --pattern 'class GenomeLayout {
  $$$
}'

# Find the definition and constructors of GenomeComponent class
ast-grep --lang csharp --pattern 'class GenomeComponent {
  $$$
}'

Length of output: 134



Script:

#!/bin/bash
# Find the definition and constructors of GenomeLayout class using rg
rg 'class GenomeLayout'

# Find the definition and constructors of GenomeComponent class using rg
rg 'class GenomeComponent'

Length of output: 251



Script:

#!/bin/bash
# Extract the constructors of GenomeLayout class
ast-grep --lang csharp --pattern 'class GenomeLayout {
  $$$
  public GenomeLayout($_) {
    $$$
  }
  $$$
}' Content.Shared/_White/Genetics/GenomeLayout.cs

# Inspect the GenomeComponent class for how Layout is used and initialized
ast-grep --lang csharp --pattern 'class GenomeComponent {
  $$$
}' Content.Server/_White/Genetics/Components/GenomeComponent.cs

Length of output: 633



Script:

#!/bin/bash
# Extract the constructors of GenomeLayout class using rg
rg 'public GenomeLayout' Content.Shared/_White/Genetics/GenomeLayout.cs

# Inspect the GenomeComponent class for how Layout is used and initialized using rg
rg 'GenomeLayout' Content.Server/_White/Genetics/Components/GenomeComponent.cs

Length of output: 192



Script:

#!/bin/bash
# Extract the class definition and methods of GenomeLayout
rg -A 20 'class GenomeLayout' Content.Shared/_White/Genetics/GenomeLayout.cs

# Inspect the GenomeComponent class for usage of Layout
rg -A 10 'Layout' Content.Server/_White/Genetics/Components/GenomeComponent.cs

Length of output: 1283

Content.Client/_White/DNAConsole/DNAConsoleBoundInterface.cs (1)

9-10: Ensure proper handling of nullable window instance.

The _window field is nullable and used throughout the class. Ensure that all accesses to _window are properly guarded against null values to prevent runtime exceptions.

Verification successful

Ensure proper handling of nullable window instance.

The _window field in DNAConsoleBoundInterface.cs is nullable and used throughout the class. The usages in this file are properly guarded against null values, preventing potential runtime exceptions.

  • Content.Client/_White/DNAConsole/DNAConsoleBoundInterface.cs:
    • Line 16: _window?.Populate((DNAConsoleBoundUserInterfaceState) state);
    • Line 18: if (_window != null)
    • Line 21: _window?.Dispose();
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Check all usages of _window to ensure it's always checked for null before usage.
rg --type csharp $'_window\?.'

Length of output: 112516

Content.Server/_White/Genetics/MutationSystem.cs (1)

20-32: Consider using a more scalable data structure for race damage mapping.

Currently, the method GetDamage uses a hardcoded dictionary for race damage values, which limits flexibility and maintainability. Consider fetching these values from a configuration file or database to allow easy updates without code changes.
[REFACTOR_SUGGESTion]

Content.Shared/_White/Genetics/Genome.cs (3)

18-18: Class declaration and structure review.

The Genome class is well-structured for handling genetic data. The use of partial class suggests that it might be extended or modified in other parts of the codebase.


20-20: Dependency injection usage.

The IRobustRandom dependency is correctly injected. This is essential for the functionality that involves randomness in genetic mutations.


33-36: Constructor design.

The constructor allows initializing the Bits array with a specified count, defaulting to zero. This flexibility is good for different initialization needs.

Content.Server/_White/Genetics/DNAConsoleSystem.cs (5)

22-22: Class declaration and structure review.

The CloningConsoleSystem class is appropriately named and clearly dedicated to managing the cloning console's functionality.


24-30: Dependency injection completeness.

All necessary systems and managers like DeviceLinkSystem, IAdminLogManager, and PowerReceiverSystem are correctly injected, ensuring that the console system has access to all required functionalities.


51-53: Power check before action.

The method OnButtonPressed correctly checks if the console is powered before proceeding with any operations, which is a crucial check for preventing actions during power outages.


76-83: Linking logic in OnNewLink.

The method properly handles new device links by setting the connected console and modifier. However, the magic string ScannerPort should be replaced with a constant if used multiple times for consistency and maintainability.

- args.SourcePort == DNAConsoleComponent.ScannerPort
+ args.SourcePort == DNAConsoleComponent.SCANNER_PORT  // Assuming SCANNER_PORT is a constant defined in DNAConsoleComponent.

Likely invalid or redundant comment.


155-197: User interface state management.

The method GetUserInterfaceState effectively gathers all necessary information to update the UI state. The use of localization for UI text is a good practice. Ensure that all localization keys used (generic-unknown) are defined in the localization files.

Verification successful

Localization keys are defined correctly.

The localization key generic-unknown is defined in multiple files, ensuring proper localization for the UI text.

  • Resources/Locale/en-US/generic.ftl
  • Resources/Locale/ru-RU/generic.ftl
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Check if localization keys are defined
rg 'generic-unknown' -t yaml

Length of output: 28



Script:

#!/bin/bash
# Check if localization keys are defined in all files
rg 'generic-unknown'

Length of output: 1242

@kurokoTurbo
Copy link
Contributor Author

хуя нейроколлега насрал

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: 12

Outside diff range, codebase verification and nitpick comments (13)
Content.Shared/_White/Genetics/DNAScannerUiKey.cs (1)

5-12: Clarify or expand enum members.

The DNAScannerUiKey enum currently contains a single member Key. Consider clarifying its purpose or expanding it with more members if needed.

Content.Server/_White/Genetics/Systems/GenomeSystem.Instability.cs (1)

14-17: Translate comments and implement TODOs.

Translate the comments to English for consistency and accessibility. Additionally, consider implementing the TODO functionality or documenting it as a future task.

// If effects are about to be applied, but the entity is still injecting mutations, cancel the preparation, recalculate, and apply new effects.

// TODO: Implement a probability density function p(instability, x), where x is the "severity" of the effect.
// Alternatively, find another way to define a distribution for an arbitrary number of effects with arbitrary severity indicators for any 200 > Instability > 100.
Content.Server/_White/Genetics/MutationPrototype.cs (1)

6-8: Improve class summary documentation.

Enhance the class summary to provide more context about the purpose and usage of the MutationPrototype.

/// <summary>
/// Represents a prototype for a genetic mutation, defining properties such as name, instability, and genetic sequence length.
/// </summary>
Content.Server/_White/Genetics/Components/DNAScannerComponent.cs (1)

8-9: Add XML documentation for the class.

Consider adding a summary description for the DNAScannerComponent class to provide context about its purpose and usage.

/// <summary>
/// Component for scanning DNA from entities.
/// </summary>
public sealed partial class DNAScannerComponent : Component
Content.Server/_White/Genetics/GenomePrototype.cs (1)

13-15: Add XML documentation for the class.

Consider adding a summary description for the GenomePrototype class to provide context about its purpose and usage.

/// <summary>
/// Prototype for defining genome structures.
/// </summary>
public sealed partial class GenomePrototype : IPrototype
Content.Shared/_White/Genetics/Components/GeneticInjectorComponent.cs (1)

6-7: Add XML documentation for the class.

Consider adding a summary description for the GeneticInjectorComponent class to provide context about its purpose and usage.

/// <summary>
/// Component for injecting genetic mutations into entities.
/// </summary>
public sealed partial class GeneticInjectorComponent : Component
Content.Shared/_White/Genetics/DNAScannerScannedGenomeMessage.cs (1)

9-10: Add XML documentation for the class.

Consider adding a summary description for the DNAScannerScannedGenomeMessage class to provide context about its purpose and usage.

/// <summary>
/// Message containing the results of a DNA scan.
/// </summary>
public sealed class DNAScannerScannedGenomeMessage : BoundUserInterfaceMessage
Content.Client/_White/DNAConsole/DNAConsoleWindow.xaml (1)

21-21: Clarify the purpose of DNATest label.

The label DNATest with the text "all is ok." seems to be a placeholder. Ensure this label serves a meaningful purpose or remove it if it's unnecessary.

-    <Label HorizontalAlignment="Center" Text="all is ok." Name="DNATest" />
+    <!-- TODO: Clarify the purpose of this label or remove it if unnecessary. -->
Content.Server/_White/Genetics/Components/GenomeComponent.cs (1)

40-40: Clarify the purpose of the field.

The comment "TODO: wtf is this" is uninformative. Replace it with a meaningful description or remove it if unnecessary.

- /// TODO: wtf is this
+ /// Indicates whether the entity has human genes.
Content.Server/_White/Genetics/Systems/DNAScannerSystem.cs (1)

18-18: Expand the class summary.

The class summary "This handles..." is incomplete. Provide a detailed description of the class responsibilities.

- /// This handles...
+ /// Handles DNA scanning interactions, including initiating scans and updating the user interface.
Content.Server/_White/Genetics/Systems/GenomeSystem.Mutations.cs (1)

14-47: Clarify the purpose of the OnGenomeChanged method.

The method includes a TODO comment and handles genome changes. Ensure the logic is correct and consider adding comments to clarify the method's purpose and functionality.

Content.Shared/_White/Genetics/Genome.cs (1)

182-192: Clarify mutation probability logic.

The Mutate method includes a commented-out line regarding probability. Clarify the logic or remove the comment if it's unnecessary.

Content.Server/_White/Genetics/DNAModifierSystem.cs (1)

63-68: Remove redundant base.Initialize() call.

The call to base.Initialize() in OnComponentInit is unnecessary since this method is not overriding a base method.

-    base.Initialize();
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b6d9ee4 and 6d60683.

Files ignored due to path filters (10)
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/closed.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/closed_unpowered.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/idle_unlit.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/maint_unlit.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/occupied.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/occupied_unlit.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/off_unlit.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/open.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/open_unpowered.png is excluded by !**/*.png
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/red_unlit.png is excluded by !**/*.png
Files selected for processing (38)
  • Content.Client/_White/DNAConsole/DNAConsoleBoundInterface.cs (1 hunks)
  • Content.Client/_White/DNAConsole/DNAConsoleWindow.xaml (1 hunks)
  • Content.Client/_White/DNAConsole/DNAConsoleWindow.xaml.cs (1 hunks)
  • Content.Client/_White/DNAModifier/DNAModifierComponent.cs (1 hunks)
  • Content.Client/_White/Genetics/DNAScannerBoundUserInterface.cs (1 hunks)
  • Content.Client/_White/Genetics/DNAScannerWindow.xaml (1 hunks)
  • Content.Client/_White/Genetics/DNAScannerWindow.xaml.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/ActiveModifierComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/DNAConsoleComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/DNAModifierComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/DNAScannerComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/Components/GenomeComponent.cs (1 hunks)
  • Content.Server/_White/Genetics/DNAConsoleSystem.cs (1 hunks)
  • Content.Server/_White/Genetics/DNAModifierSystem.cs (1 hunks)
  • Content.Server/_White/Genetics/GenomeChangedEvent.cs (1 hunks)
  • Content.Server/_White/Genetics/GenomePrototype.cs (1 hunks)
  • Content.Server/_White/Genetics/MutationCollectionPrototype.cs (1 hunks)
  • Content.Server/_White/Genetics/MutationEffect.cs (1 hunks)
  • Content.Server/_White/Genetics/MutationPrototype.cs (1 hunks)
  • Content.Server/_White/Genetics/Mutations/GlowingMutation.cs (1 hunks)
  • Content.Server/_White/Genetics/RemoveMutationsReagentEffect.cs (1 hunks)
  • Content.Server/_White/Genetics/Systems/DNAScannerSystem.cs (1 hunks)
  • Content.Server/_White/Genetics/Systems/GeneticInjectorSystem.cs (1 hunks)
  • Content.Server/_White/Genetics/Systems/GenomeSystem.Instability.cs (1 hunks)
  • Content.Server/_White/Genetics/Systems/GenomeSystem.Mutations.cs (1 hunks)
  • Content.Server/_White/Genetics/Systems/GenomeSystem.cs (1 hunks)
  • Content.Shared/_White/DNAConsole/SharedDNAConsole.cs (1 hunks)
  • Content.Shared/_White/DNAModifier/SharedDNAModifierComponent.cs (1 hunks)
  • Content.Shared/_White/Genetics/Components/GeneticInjectorComponent.cs (1 hunks)
  • Content.Shared/_White/Genetics/DNAScannerDoAfterEvent.cs (1 hunks)
  • Content.Shared/_White/Genetics/DNAScannerScannedGenomeMessage.cs (1 hunks)
  • Content.Shared/_White/Genetics/DNAScannerUiKey.cs (1 hunks)
  • Content.Shared/_White/Genetics/GenesPrototype.cs (1 hunks)
  • Content.Shared/_White/Genetics/Genome.cs (1 hunks)
  • Content.Shared/_White/Genetics/GenomeLayout.cs (1 hunks)
  • Content.Shared/_White/Genetics/SharedGeneticInjectorSystem.cs (1 hunks)
  • Resources/Prototypes/White/genetic_prototypes.yml (1 hunks)
  • Resources/Textures/White/Objects/Devices/dna_modifier.rsi/meta.json (1 hunks)
Files skipped from review due to trivial changes (2)
  • Content.Client/_White/Genetics/DNAScannerWindow.xaml
  • Content.Server/_White/Genetics/Components/ActiveModifierComponent.cs
Additional comments not posted (60)
Content.Client/_White/DNAModifier/DNAModifierComponent.cs (1)

5-8: Placeholder component.

The DNAModifierComponent class is currently empty and acts as a placeholder. Ensure to add relevant logic or properties in the future as needed.

Content.Shared/_White/Genetics/DNAScannerDoAfterEvent.cs (1)

6-9: Correct serialization setup.

The DNAScannerDoAfterEvent class is correctly set up for serialization and network communication.

Content.Client/_White/Genetics/DNAScannerWindow.xaml.cs (1)

7-13: Correct XAML loading setup.

The DNAScannerWindow class is correctly set up to load its XAML using RobustXamlLoader.

Content.Server/_White/Genetics/MutationEffect.cs (1)

5-11: Correct design for inheritance and ECS integration.

The MutationEffect class is well-designed for inheritance, with abstract methods Apply and Cancel to be implemented in derived classes. It integrates well with the entity-component system using EntityUid and IEntityManager.

Content.Shared/_White/DNAModifier/SharedDNAModifierComponent.cs (1)

5-21: Enums for network communication look good.

The enums DNAModifierVisual and DNAModifierStatus are well-defined and appropriately marked with [Serializable, NetSerializable] for network serialization. This setup is clear and concise.

Content.Server/_White/Genetics/Components/DNAConsoleComponent.cs (4)

6-6: Clarify the purpose of ScannerPort.

The constant ScannerPort is defined but its purpose or usage is not immediately clear from the code or comments. Consider adding a comment explaining its role, especially how it interacts with other components.


9-9: Consider initializing Modifier in the constructor.

Currently, Modifier is nullable and not initialized. If there's a default state or a typical initial value, consider initializing it in the constructor to improve robustness and clarity.


13-13: Validate MaxDistance for reasonable values.

The MaxDistance property is exposed but lacks validation. Ensure that it cannot be set to negative values or unreasonably high values, which could lead to unexpected behavior.


15-15: Document the behavior of ModifierInRange.

The ModifierInRange property is a boolean but lacks documentation on when and how it should be used or modified. Adding documentation can improve maintainability and understandability of the code.

Content.Server/_White/Genetics/Components/DNAModifierComponent.cs (3)

9-9: Clarify the purpose of ScannerPort.

Similar to the DNAConsoleComponent, the purpose of ScannerPort is not immediately clear. Consider adding a comment explaining its role, particularly in how it interacts with other components.


10-10: Ensure proper initialization of BodyContainer.

BodyContainer is initialized to default!, which implies non-null but does not actually initialize it. Ensure that this container is properly initialized to prevent runtime errors.


13-13: Consider implications of CloningFailChanceMultiplier.

While CloningFailChanceMultiplier is adjustable, consider adding validation or constraints to prevent setting it to negative values, which might not make sense contextually.

Content.Server/_White/Genetics/GenomeChangedEvent.cs (1)

6-17: Ensure proper initialization of GenomeChangedEvent properties.

The GenomeChangedEvent class is well-structured, with properties initialized in the constructor. Ensure that Comp and RegionsChanged are correctly instantiated before use to avoid null reference issues.

Content.Server/_White/Genetics/MutationCollectionPrototype.cs (1)

5-19: Prototype structure for mutation collections looks good.

The MutationCollectionPrototype class is well-defined, with properties for ID and mutations. The use of [IdDataField] and [DataField] attributes is appropriate for defining prototype data.

Content.Shared/_White/Genetics/GenesPrototype.cs (1)

24-25: Clarify handling of unused bits.

The Ints dictionary is well-defined. However, the comment about unused bits being dropped silently could lead to confusion. Consider adding more detailed documentation or explicit handling in the system to manage unused bits.

Content.Server/_White/Genetics/Components/DNAScannerComponent.cs (1)

10-38: LGTM!

The properties are well-documented and appropriately configured.

Content.Server/_White/Genetics/GenomePrototype.cs (1)

16-24: LGTM!

The properties are well-documented and appropriately configured.

Content.Shared/_White/Genetics/Components/GeneticInjectorComponent.cs (2)

8-34: LGTM!

The properties are well-documented and appropriately configured.


36-39: LGTM!

The GeneticInjectorDoAfterEvent is correctly implemented.

Resources/Textures/White/Objects/Devices/dna_modifier.rsi/meta.json (1)

1-66: LGTM!

The metadata file is well-structured and complete.

Content.Shared/_White/Genetics/DNAScannerScannedGenomeMessage.cs (1)

11-34: LGTM!

The properties and constructor are well-documented and appropriately implemented.

Content.Shared/_White/Genetics/SharedGeneticInjectorSystem.cs (1)

13-17: Dependency Injection Setup.

The dependencies are injected correctly using the [Dependency] attribute. Ensure these systems are necessary for the functionality of this class.

Content.Client/_White/DNAConsole/DNAConsoleBoundInterface.cs (2)

24-24: Re-enable or remove commented-out code.

The commented-out line for handling the ModifierButton press event is left in the code. If this functionality is needed, it should be uncommented; otherwise, it should be removed to clean up the codebase.


44-44: Consistent cleanup in Dispose method.

The cleanup code in the Dispose method is partially commented out. Ensure that all event handlers added are removed during disposal to prevent memory leaks.

Content.Client/_White/DNAConsole/DNAConsoleWindow.xaml (1)

1-4: Verify window size settings.

The window size is set to a fixed size of 400x400. Consider whether this size is appropriate for all screen resolutions and if dynamic resizing is needed.

Content.Shared/_White/DNAConsole/SharedDNAConsole.cs (4)

5-19: Well-defined UI state class.

The DNAConsoleBoundUserInterfaceState class is well-defined, encapsulating the necessary state information for the DNA console UI.


21-29: Enum ModifierStatus is well-defined.

The ModifierStatus enum provides clear status options for the DNA console's modifier, aiding in state management.


37-42: Enum UiButton is well-defined.

The UiButton enum clearly defines the UI buttons available for interaction, facilitating consistent button handling.


44-53: Class UiButtonPressedMessage is well-structured.

The UiButtonPressedMessage class is well-structured for handling button press events, ensuring clear communication between the UI and backend.

Content.Server/_White/Genetics/Components/GenomeComponent.cs (1)

18-18: Ensure appropriate default value for required fields.

The GenomeId is marked as required but initialized to an empty string. This could lead to runtime issues if not properly handled. Consider enforcing a valid default value or handling this scenario gracefully.

Resources/Prototypes/White/genetic_prototypes.yml (2)

24-24: Provide meaningful descriptions.

The description "soon" is not informative. Ensure all entities have meaningful descriptions before going live.


41-41: Verify power load configuration.

The powerLoad is set to a high value (3400). Ensure this is intended and tested under load conditions to prevent potential issues.

Content.Client/_White/DNAConsole/DNAConsoleWindow.xaml.cs (1)

21-83: Refactor and optimize the Populate method.

The method contains multiple visibility toggles and string localizations which can be streamlined. Consider using helper methods to manage visibility states and set text based on the ModifierStatus. This will improve readability and maintainability.

Content.Shared/_White/Genetics/GenomeLayout.cs (2)

31-31: Add error handling for missing keys.

The method GetBool lacks error handling for missing keys in the Values dictionary. Consider adding checks to prevent runtime exceptions.


65-65: Add error handling for missing keys.

The method SetInt lacks error handling for missing keys in the Values dictionary. Consider adding checks to prevent runtime exceptions.

Content.Server/_White/Genetics/Systems/DNAScannerSystem.cs (1)

39-40: Check for nullability and reachability.

Ensure that args.Target is not null and is reachable before proceeding. The current check is correct but ensure it's consistently applied throughout the codebase.

Content.Server/_White/Genetics/Systems/GeneticInjectorSystem.cs (2)

19-24: Ensure event subscriptions are necessary and complete.

The Initialize method subscribes to two events. Verify that these events are sufficient for the intended functionality and consider whether additional events might be needed.


81-112: Review mutation application logic.

The OnInjectDoAfterComplete method applies mutations to a target. Ensure that the logic for applying mutations is correct and consider edge cases, such as when mutations cannot be applied.

Content.Server/_White/Genetics/Systems/GenomeSystem.Mutations.cs (2)

49-62: Verify mutation application logic.

The ApplyMutatorMutation method applies mutations and effects. Ensure that all necessary checks are in place and that the method behaves as expected under various conditions.


85-115: Ensure correct handling of activator mutations.

The ApplyActivatorMutation method applies activator mutations. Verify that the logic correctly handles various scenarios, such as when mutations are already active.

Content.Server/_White/Genetics/Systems/GenomeSystem.cs (2)

37-47: Ensure complete initialization logic.

The Initialize method subscribes to several events. Verify that all necessary events are subscribed and that the initialization logic is complete.


56-108: Review genome component initialization.

The OnGenomeCompInit method initializes genome components. Ensure that the logic correctly initializes components and handles edge cases.

Content.Server/_White/Genetics/DNAConsoleSystem.cs (2)

120-133: Ensure UI state consistency.

The UpdateUserInterface method updates the UI state. Verify that the UI state remains consistent under different conditions, such as power loss.


142-154: Review connection rechecking logic.

The RecheckConnections method verifies connections. Ensure that the logic accurately reflects the current state of connections and handles disconnections properly.

Content.Server/_White/Genetics/DNAModifierSystem.cs (16)

35-48: Initialization looks good!

The method correctly subscribes to necessary events for the DNAModifierComponent.


50-54: Drag-and-drop handling is appropriate.

The method correctly determines if an entity can be dropped onto the DNA modifier.


55-61: Insertion check logic is correct.

The method appropriately checks if the target entity has a BodyComponent.


70-76: Relay movement handling is appropriate.

The method correctly checks interaction permissions before ejecting the body.


77-96: Verb addition logic is sound.

The method correctly adds an interaction verb for inserting entities, ensuring all necessary conditions are met.


98-114: Alternative verb handling is appropriate.

The method correctly adds an eject verb when the modifier is occupied, ensuring accessibility and interaction capability.


116-119: Destruction handling is correct.

The method appropriately handles the destruction event by ejecting any contained entity.


121-124: Drag-and-drop insertion is straightforward.

The method correctly handles the drag-and-drop event by calling InsertBody.


126-129: Port disconnection handling is correct.

The method appropriately nullifies the connected console upon port disconnection.


131-142: Anchor state change handling is appropriate.

The method correctly manages console connections based on the entity's anchor state.


143-159: Status determination logic is correct.

The method accurately determines the status of the DNA modifier based on power and body state.


164-175: Damage state status logic is sound.

The method correctly returns status values based on the entity's damage state.


177-182: Appearance update logic is appropriate.

The method correctly updates the appearance based on the DNA modifier's status.


184-199: Periodic update logic is efficient.

The method efficiently updates the appearance of DNA modifiers based on a time interval.


200-220: Body insertion logic is comprehensive.

The method thoroughly checks conditions before inserting a body and updates the necessary components and appearance.


221-232: Body ejection logic is correct.

The method appropriately handles the ejection of a body, ensuring all relevant components and states are updated.

Comment on lines +13 to +22
protected override void Open()
{
base.Open();
_window = new DNAScannerWindow
{
Title = EntMan.GetComponent<MetaDataComponent>(Owner).EntityName,
};
_window.OnClose += Close;
_window.OpenCentered();
}
Copy link

Choose a reason for hiding this comment

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

Enhance error handling and resource management.

  1. Consider handling potential exceptions when retrieving the MetaDataComponent. This can prevent runtime errors if the component is missing.
  2. Ensure that the _window resource is properly disposed of when it's no longer needed to prevent memory leaks.
protected override void Open()
{
    base.Open();
    try
    {
        var metaData = EntMan.GetComponent<MetaDataComponent>(Owner);
        _window = new DNAScannerWindow
        {
            Title = metaData.EntityName,
        };
    }
    catch (Exception ex)
    {
        Logger.Error($"Failed to open DNA scanner window: {ex.Message}");
        return;
    }
    _window.OnClose += Close;
    _window.OpenCentered();
}

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        _window?.Dispose();
    }
    base.Dispose(disposing);
}

Comment on lines +11 to +15
// Issues will arise if mutation is added to already glowing entity.
public override void Apply(EntityUid uid, IEntityManager entityManager)
{
var light = new PointLightComponent();
entityManager.AddComponent(uid, light);
Copy link

Choose a reason for hiding this comment

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

Check for existing components before adding.

Before adding a PointLightComponent, check if it already exists to prevent potential issues with duplicate components.

public override void Apply(EntityUid uid, IEntityManager entityManager)
{
    if (!entityManager.HasComponent<PointLightComponent>(uid))
    {
        var light = new PointLightComponent();
        entityManager.AddComponent(uid, light);
    }
    else
    {
        Logger.Warning($"Entity {uid} already has a PointLightComponent.");
    }
}

Comment on lines +31 to +32
[DataField("effects")]
public MutationEffect[] Effect = default!;
Copy link

Choose a reason for hiding this comment

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

Initialize the Effect array to prevent null references.

Ensure the Effect array is initialized to avoid potential null reference exceptions.

[DataField("effects")]
public MutationEffect[] Effect { get; private set; } = Array.Empty<MutationEffect>();

Comment on lines +25 to +30
private void OnInjectorStartup(Entity<GeneticInjectorComponent> entity, ref ComponentStartup args)
{
// ???? why ?????
// TODO: wtf is this
Dirty(entity);
}
Copy link

Choose a reason for hiding this comment

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

Clarify the purpose of OnInjectorStartup.

The method contains unclear comments and a TODO. Clarify the purpose of this method and remove or replace the placeholder comments with meaningful descriptions.

-    // ???? why ?????
-    // TODO: wtf is this
+    // This method marks the entity as dirty to ensure its state is updated.
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private void OnInjectorStartup(Entity<GeneticInjectorComponent> entity, ref ComponentStartup args)
{
// ???? why ?????
// TODO: wtf is this
Dirty(entity);
}
private void OnInjectorStartup(Entity<GeneticInjectorComponent> entity, ref ComponentStartup args)
{
// This method marks the entity as dirty to ensure its state is updated.
Dirty(entity);
}

Comment on lines +32 to +40
private void OnInjectorUse(Entity<GeneticInjectorComponent> entity, ref UseInHandEvent args)
{
if (args.Handled)
return;

// inject yourself here

args.Handled = true;
}
Copy link

Choose a reason for hiding this comment

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

Implement OnInjectorUse functionality.

The OnInjectorUse method currently lacks implementation. Define the intended behavior when the injector is used, and ensure the args.Handled flag is set appropriately after the action is performed.

-    // inject yourself here
+    // TODO: Implement the injection logic here.

Committable suggestion was skipped due to low confidence.

Comment on lines +27 to +79
// TODO: log
public void OnAfterInteract(Entity<GeneticInjectorComponent> entity, ref AfterInteractEvent args)
{
if (args.Handled || !args.CanReach || args.Target == null)
return;

if (!TryComp<GenomeComponent>(args.Target.Value, out var targetGenome))
{
if (!entity.Comp.Forced)
{
return;
}

targetGenome = new GenomeComponent();
AddComp(args.Target.Value, targetGenome);
}

if (!entity.Comp.Used)
return;

if (entity.Comp.MutationProtos.Count + entity.Comp.ActivatorMutations.Count == 0)
return;

var delay = entity.Comp.UseDelay;

if (args.User != args.Target.Value)
{
// Create a pop-up for the target
var userName = Identity.Entity(args.User, EntityManager);
_popup.PopupEntity(Loc.GetString("injector-component-injecting-target",
("user", userName)), args.User, args.Target.Value);

// Check if the target is incapacitated or in combat mode and modify time accordingly.
if (_mobState.IsIncapacitated(args.Target.Value))
{
delay /= 2.5f;
}
}
else
{
delay /= 2.5f;
}

// TODO: admin log here
_doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, delay, new GeneticInjectorDoAfterEvent(),
entity.Owner, target: args.Target.Value, used: entity.Owner)
{
BreakOnUserMove = true,
BreakOnDamage = true,
BreakOnTargetMove = true,
MovementThreshold = 0.1f,
});
}
Copy link

Choose a reason for hiding this comment

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

Consider adding logging for interaction events.

The OnAfterInteract method includes TODO comments for logging. Implement logging to track interactions and potential issues during gameplay.

// Example logging implementation
_logger.Info($"Genetic injection interaction started by {args.User} on {args.Target}");

Comment on lines +64 to +77
public void CancelMutatorMutation(EntityUid uid, GenomeComponent comp, string mutationName)
{
if (!comp.MutatedMutations.Contains(mutationName) || _mutations.TryGetValue(mutationName, out var mutation))
return;

comp.MutatedMutations.Remove(mutationName);
comp.Instability -= mutation.Instability;
foreach (var effect in mutation.Effects)
{
effect.Cancel(uid, EntityManager);
}

CheckInstability(uid, comp, -mutation.Instability);
}
Copy link

Choose a reason for hiding this comment

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

Correct the condition in CancelMutatorMutation.

The condition in the CancelMutatorMutation method seems incorrect. It should check if the mutation exists before proceeding.

- if (!comp.MutatedMutations.Contains(mutationName) || _mutations.TryGetValue(mutationName, out var mutation))
+ if (!comp.MutatedMutations.Contains(mutationName) || !_mutations.TryGetValue(mutationName, out var mutation))
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void CancelMutatorMutation(EntityUid uid, GenomeComponent comp, string mutationName)
{
if (!comp.MutatedMutations.Contains(mutationName) || _mutations.TryGetValue(mutationName, out var mutation))
return;
comp.MutatedMutations.Remove(mutationName);
comp.Instability -= mutation.Instability;
foreach (var effect in mutation.Effects)
{
effect.Cancel(uid, EntityManager);
}
CheckInstability(uid, comp, -mutation.Instability);
}
public void CancelMutatorMutation(EntityUid uid, GenomeComponent comp, string mutationName)
{
if (!comp.MutatedMutations.Contains(mutationName) || !_mutations.TryGetValue(mutationName, out var mutation))
return;
comp.MutatedMutations.Remove(mutationName);
comp.Instability -= mutation.Instability;
foreach (var effect in mutation.Effects)
{
effect.Cancel(uid, EntityManager);
}
CheckInstability(uid, comp, -mutation.Instability);
}

Comment on lines +22 to +26
/// <summary>
/// Bits that represent the genes bools and ints.
/// </summary>
[ViewVariables]
public BitArray Bits = new BitArray(0);
Copy link

Choose a reason for hiding this comment

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

Consider thread safety for Bits.

The Bits field is publicly accessible. Consider encapsulating it to ensure thread safety and prevent unintended modifications.

// Example encapsulation
private BitArray _bits = new BitArray(0);
public BitArray Bits => new BitArray(_bits);

Comment on lines +82 to +93
public string GetBases(int index, int bases)
{
var builder = new StringBuilder(bases);
for (int i = 0; i < bases; i++)
{
// 2 bits makes a base
var c = Bases[GetInt(index + i * 2, 2)];
builder.Append(c);
}

return builder.ToString();
}
Copy link

Choose a reason for hiding this comment

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

Optimize GetBases method.

Consider optimizing the GetBases method by pre-allocating the StringBuilder with a capacity equal to bases.

var builder = new StringBuilder(bases);

Comment on lines +133 to +150
private void InitializeMutations()
{
_proto.TryIndex<MutationCollectionPrototype>(_mutationsPool, out var pool);
if (pool == null)
{
//TODO: throw an error here
return;
}

foreach (var mutation in pool.Mutations)
{
_proto.TryIndex<MutationPrototype>(mutation, out var mutationProto);
if (mutationProto != null)
_mutations.Add(mutationProto.Name, (GenerateSomeRandomGeneticSequenceAndCheckIfItIsIn_mutationsFunction(mutationProto.Length), mutationProto.Effect, mutationProto.Instability));
}

_mutationsInitialized = true;
}
Copy link

Choose a reason for hiding this comment

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

Handle mutation initialization errors.

The InitializeMutations method includes a TODO comment about error handling. Implement error handling to ensure robustness.

if (pool == null)
{
    _sawmill.Error("Mutation pool not found");
    throw new InvalidOperationException("Mutation pool initialization failed");
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants