Modding Tutorials/PatchOperations

From RimWorld Wiki
Jump to navigation Jump to search

Modding Tutorials

RimWorld Alpha 17 added a new modding feature: XML PatchOperations. Using these allows mods to edit specific elements of XML defs, rather than simply overwriting the old def with a new one, which was the required approach until A17. This greatly reduces mod conflicts, because mods that make separate changes to the same def won't necessarily overwrite one another's changes. Mods using PatchOperations can avoid requiring special compatibility mods, and can even add special features conditional on other mods being loaded.

Here's a simple example of replacing the texture path for deep water:

<?xml version="1.0" encoding="utf-8" ?>
<Patch>
  <Operation Class="PatchOperationReplace">
    <xpath>/Defs/TerrainDef[defName="WaterDeep"]/texturePath</xpath>
    <value>
      <texturePath>Your/Texture/Path/Here</texturePath>
    </value>
  </Operation>
</Patch>

This xml file simply goes inside YourMod/Patches/ and you're done.

Overview of available PatchOperations

These are the available PatchOperation types:

XPath syntax

Each PatchOperation must specify an XML node to modify. It uses XPaths to specify them. An XPath is a "path" for the patch to follow when trying to find XML nodes matching the description. It will follow each part of the path from left to right. Note that these "paths" have zero relation to the file path or folder structure: They follow the structure of the XML nodes.

XPaths start at the root node. Since the root node of all Defs is enforced to be <Defs>, so /Defs/ is the start of our xpath. */ is also valid, as it uses the * wildcard: * matches any element, so it'll match the root (the top level) of the XML tree. // is technically also valid, but because that construct selects all the elements in the XML tree, it's an expensive operation that makes game loading exponentially slower.

Once the root is selected, the XPath lets the system walk down specific branches of the tree. If we use the example from the lead, we get a specific path:

/Defs/TerrainDef[defName="WaterDeep"]/texturePath

  1. The root node is selected
  2. All child nodes of the root node called "TerrainDef" are selected
  3. We narrow down from "all TerrainDefs" to only those with the child "defName" node whose value is "WaterDeep", which should give us exactly one node because defNames must be unique
  4. We select the child node "texturePath" from this node
    1. Note that we cannot put .../texturePath/ to specify the content of the texturePath node. If we want to replace texturePath, we have to replace it with <texturePath>/new/path/to/texture</texturePath>

For more info, see this Thread. XPath is a well-documented industry standard (good resource, too); there are plenty of resources available on the subject ranging from exhaustive tutorials to simple StackOverflow questions.

"Success" option

The <success>...</success> term specifies whether the entire operation is considered a success or not. If the overall patch operation is not considered a success, an error is thrown. This is particularly used in Sequences and Tests, where you'd not want to throw an error on a simple test.

Options available are:

  • Always - this patch operation is considered a success - sometimes used for Sequences so that if an early test in the sequence fails, an error is not reported (because the sequence is still a successful patch)
  • Normal - this patch operation is considered a success if it succeeded (content patched, test passed, etc)
  • Invert - If the patch failed (e.g., a test), then it's considered a success (useful for a negative test in a sequence)
  • Never - this patch operation "failed." Even if it patched whatever it was supposed to correctly. If you ever use this, leave a note here for the curious.

Overview of individual PatchOperations

PatchOperationAdd

PatchOperationAdd adds a child node to the selected node.

Def before patch Patch operation Def after patch
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>
<Operation Class="PatchOperationAdd">
    <xpath>/Defs/ExampleDef[defName="Example"]/exampleList</xpath>
    <value>
        <li>Foo</li>
        <li>Bar</li>
    </value>
</Operation>
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList>
            <li>Foo</li>
            <li>Bar</li>
        </exampleList>
    </ExampleDef>
</Defs>

PatchOperationInsert

PatchOperationInsert adds a sibling to the selected node.

Def before patch Patch operation Def after patch
<Defs>
  <ExampleDef>
    <defName>Example</defName>
    <exampleNode>Some text</exampleNode>
    <exampleList />
  </ExampleDef>
</Defs>
<Operation Class="PatchOperationInsert">
  <xpath>/Defs/ExampleDef[defName="Example"]/exampleNode</xpath>
  <value>
    <anotherExample>A new sibling</anotherExample>
  </value>
</Operation>
<Defs>
  <ExampleDef>
    <defName>Example</defName>
    <exampleNode>Some text</exampleNode>
    <anotherExample>A new sibling</anotherExample>
    <exampleList />
  </ExampleDef>
</Defs>

PatchOperationRemove

PatchOperationRemove removes the selected node.

Def before patch Patch operation Def after patch
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>
<Operation Class="PatchOperationRemove">
    <xpath>/Defs/ExampleDef[defName="Example"]/exampleNode</xpath>
</Operation>
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleList />
    </ExampleDef>
</Defs>

PatchOperationReplace

PatchOperationReplace replaces the selected node.

Def before patch Patch operation Def after patch
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>
<Operation Class="PatchOperationReplace">
    <xpath>/Defs/ExampleDef[defName="Example"]/exampleNode</xpath>
    <value>
        <anotherExample>An alternate node</anotherExample>
    </value>
</Operation>
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <anotherExample>An alternate node</anotherExample>
        <exampleList />
    </ExampleDef>
</Defs>

PatchOperationAttributeAdd

PatchOperationAttributeAdd will add an attribute and set its value, but only if that attribute is not yet present.

Def before patch Patch operation Def after patch
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>
<Operation Class="PatchOperationAttributeAdd">
    <xpath>/Defs/ExampleDef[defName="Example"]/exampleNode</xpath>
    <attribute>ExampleAttribute</attribute>
    <value>ExampleValue</value>
</Operation>
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode ExampleAttribute"ExampleValue">Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>

PatchOperationAttributeSet

PatchOperationAttributeSet will add an attribute and set its value. Unlike PatchAttributeAdd, PatchOperationAttributeSet will overwrite any existing value.

Def before patch Patch operation Def after patch
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode ExampleAttribute="ExampleValue">Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>
<Operation Class="PatchOperationAttributeSet">
    <xpath>/Defs/ExampleDef[defName="Example"]/exampleNode</xpath>
    <attribute>ExampleAttribute</attribute>
    <value>DifferentExampleValue</value>
</Operation>
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode ExampleAttribute="DifferentExampleValue">Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>

PatchOperationAttributeRemove

PatchOperationAttributeRemove removes the specified attribute.

Def before patch Patch operation Def after patch
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode ExampleAttribute"ExampleValue">Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>
<Operation Class="PatchOperationAttributeRemove">
    <xpath>/Defs/ExampleDef[defName="Example"]/exampleNode</xpath>
    <attribute>ExampleAttribute</attribute>
</Operation>
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>

PatchOperationAddModExtension

PatchOperationAddModExtension adds a Mod Extension.

Def before patch Patch operation Def after patch
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>

<Operation Class="PatchOperationAddModExtension">
    <xpath>/Defs/ExampleDef[defName="Example"]</xpath>
    <value>
        <li Class="ExampleNameSpace.ExampleModExtension">
            <exampleValue>true</exampleValue>
        </li>
    </value>
</Operation>
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList />
        <modExtensions>
            <li Class="ExampleNameSpace.ExampleModExtension">
                <exampleValue>true</exampleValue>
            </li>
        </modExtensions>
    </ExampleDef>
</Defs>

PatchOperationSetName

PatchOperationSetName changes the name of a node.

Def before patch Patch operation Def after patch
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <exampleNode>Some text</exampleNode>
        <exampleList />
    </ExampleDef>
</Defs>
<Operation Class="PatchOperationSetName">
    <xpath>/Defs/ExampleDef[defName="Example"]/exampleNode</xpath>
    <name>newExampleName</name>
</Operation>
<Defs>
    <ExampleDef>
        <defName>Example</defName>
        <newExampleName>Some text</newExampleName>
        <exampleList />
    </ExampleDef>
</Defs>

PatchOperationSequence

PatchOperationSequence will complete all operations in the order of their listing, and stop when any of them fails.

Modders will often specify <success>Always</success>, which will mean that even if one part of the sequence fails (e.g., a test), the whole is still considered a success and no unneeded errors show up.

Patch Operation

<Operation Class="PatchOperationSequence">
  <!-- put <success>Always</success> if using tests?  Leave out for simple sequences -->
  <operations>
    <li Class="PatchOperationInsert"><!-- Always happens! -->
      <xpath>/Defs/ExampleDef[defName="Example"]/exampleNode</xpath>
      <value>
        <anotherExample>A new sibling</anotherExample>
      </value>
    </li>
    <li Class="PatchOperationAdd"><!-- Always happens! -->
      <xpath>/Defs/ExampleDef[defName="Example"]</xpath>
      <value><label>I'm a node</label></value>
    <li>
    <!-- etc -->
  <operations>
</Operation>

Effect

Def before patch Def after patch
<Defs>
  <ExampleDef>

    <defName>Example</defName>
    <exampleNode>Some text</exampleNode>

    <exampleList />
  </ExampleDef>
</Defs>
<Defs>
  <ExampleDef>
    <label>I'm a node</label>
    <defName>Example</defName>
    <exampleNode>Some text</exampleNode>
    <anotherExample>A new sibling</anotherExample>
    <exampleList />
  </ExampleDef>
</Defs>

Another Example: Maybe you don't like the "Example" ExampleDef...

<Operation Class="PatchOperationSequence">
  <success>Always</success><!-- No errors thrown -->
  <operations>
    <li Class="PatchOperationRemove"><!-- :o  ...this returns true -->
      <xpath>/Defs/ExampleDef[defName="Example"]<xpath>
    </li>
    <li Class="PatchOperationAdd"><!-- so this runs -->
      <xpath>/Defs</xpath>
      <value>
        <ExampleDef><defName>MyBetterExample</defName></ExampleDef>
      </value>
  </operations>
</Operation>

If ExampleDef were already gone, MyBetterExample would not get added.

PatchOperationTest

PatchOperationTest tests for the existence/validity of an xpath. Useful to stop a PatchOperationSequence. Often used as a simpler, less powerful version of PatchOperationConditional. The following example patch is from Apparello, by Shinzy.

<Operation Class="PatchOperationSequence">
    <!-- check for worn graphics and if none found, add one -->
    <success>Always</success>
    <operations>
        <li Class="PatchOperationTest">
            <xpath>/Defs/ThingDef[defName = "Apparel_Pants"]/apparel/wornGraphicPath</xpath>
            <success>Invert</success>
        </li>
        <li Class="PatchOperationAdd">
            <xpath>/Defs/ThingDef[defName = "Apparel_Pants"]/apparel</xpath>
            <value>
                <wornGraphicPath>Accessorello/Pants/Pants</wornGraphicPath>
            </value>
        </li>
    </operations>
</Operation>

PatchOperationConditional

PatchOperationConditional can branch logic based on a match/nomatch. The following example patch adds a <comps> node if it does not yet exist, and adds itself

Important Note: If the xpath does not match and <nomatch> has not been specified, this will return 'false' - which may throw an error to the user. Likewise, if the xpath does match and there is no <match>, a failure. You may specify <success>Always</success> to avoid any errors.

This patch is courtesy Mehni. See original.

<!-- Add /comps/li/compClass if there are no comps yet. -->
<!-- Add /li/compClass to /comps if exists (i.e. other mod already added the comps field first) -->
<Operation Class="PatchOperationConditional">
    <xpath>/Defs/WorldObjectDef[defName="Caravan"]/comps</xpath>
    <nomatch Class="PatchOperationAdd">
        <xpath>/Defs/WorldObjectDef[defName="Caravan"]</xpath>
        <value>
            <comps>
                <li>
                    <compClass>MoreFactionInteraction.WorldObjectComp_CaravanComp</compClass>
                </li>
            </comps>
        </value>
    </nomatch>
    <match Class="PatchOperationAdd">
        <xpath>/Defs/WorldObjectDef[defName="Caravan"]/comps</xpath>
        <value>
            <li>
                <compClass>MoreFactionInteraction.WorldObjectComp_CaravanComp</compClass>
            </li>
        </value>
    </match>
</Operation>

PatchOperationFindMod

PatchOperationFindMod searches the list of active mods for the mods listed in <li></li> tags.

For a successful match, <li>ModName</li> has to match the <name>ModName</name> in the About.xml of the mod you base your patch behaviour on. It only needs to find one of the mods in the list for a successful match. This (shortened) patch is courtesy Mehni. See original.

The following Patch adds the RimQuest mod extension to the listed Defs when RimQuest is found.

<Operation Class="PatchOperationFindMod">
    <mods>
        <li>RimQuest</li>
    </mods>
    <match Class="PatchOperationAddModExtension">
        <xpath>/Defs/IncidentDef[defName="MFI_DiplomaticMarriage" or defName="MFI_HuntersLodge" or defName="MFI_Quest_PeaceTalks"]</xpath>
        <value>
            <li Class = "RimQuest.RimQuest_ModExtension">
                <canBeARimQuest>false</canBeARimQuest>
            </li>
        </value>
    </match>
</Operation>

The following Patch replace the tabWindowClass of the xpath when Relations Tab is not found.

<Operation Class="PatchOperationFindMod">
    <mods>
        <li>Relations Tab</li>
    </mods>
    <nomatch Class="PatchOperationReplace">
        <xpath>/Defs/MainButtonDef[defName="Factions"]/tabWindowClass</xpath>
        <value>
            <tabWindowClass>MyNameSpace.MyTabWindowClass</tabWindowClass>
        </value>
    </nomatch>
</Operation>

Common issues

Spelling matters, and XPath is case sensitive. It's very case sensitive. If you've written something that doesn't work but you're convinced it should, put it through some XPath validator. Case sensitivity includes but is not limited to the <Operation Class="PatchOperationWhatever">, the XPath, the value, every tag -- spell it right.

Another common issue is swapping Insert and Add, which leads to a different position in the node. A common misconception is trying to account for file paths. The file path is completely irrelevant to the expression you're writing. XPath is used to search XML content, not files themselves.

Still beating your head against a wall? The main RimWorld discord has helpful people and a bot where you can test XPath, and the forums have a help section as well.

Some advanced examples

This (shortened) patch is courtesy XeoNovaDan. See original. Viewer discretion is advised. Parents please take precautions if young children are present.

<Operation Class="PatchOperationFindMod">
    <mods>
        <li>Expanded Woodworking for Vegetable Garden Project</li>
    </mods>
    <match Class="PatchOperationSequence">
        <success>Always</success>
        <operations>
            <!-- Nested PatchOpFindMod. Used because Expanded Woodworking adds more Wood when VGP Xtra is installed. -->
            <li Class="PatchOperationFindMod">
                <mods>
                    <li>VGP Xtra Trees and Flowers</li>
                </mods>
                <match Class="PatchOperationSequence">
                    <success>Always</success>
                    <operations>
                        <!-- Processed camellia lumber. Mostly useful for building long-lasting, simple structures and furniture.-->
                        <li Class="PatchOperationAddModExtension">
                            <xpath>/Defs/ThingDef[defName="LumberCamellia"]</xpath>
                            <value>
                                <li Class="SurvivalTools.StuffPropsTool">
                                    <toolStatFactors>
                                        <ConstructionSpeed>0.55</ConstructionSpeed>
                                    </toolStatFactors>
                                </li>
                            </value>
                        </li>
                    </operations>
                </match>
            </li>
        </operations>
    </match>
</Operation>

Random stuff

  • @ select by attribute. Useful for patching (Abstract) bases.
    /Defs/ThingDef[@Name="BuildingBase"]
  • or is inclusive.
    /Defs/ThingDef[defName="Cassowary" or defName = "Emu" or defName = "Ostrich" or defName = "Turkey"]
    selects all of those in a single (faster) operation.
  • PatchOperationAdd and PatchOperationInsert have an order tag which allows you to either Prepend or Append your add. Default behaviour of Add is to Append, insert Prepends.
  • There is a success tag whose values can be Normal, Invert, Always and Never. This is used for the sake of error reporting: by default an error is logged when a patch fails to apply. For PatchOperationSequences and PatchOperationTests, you can set success to Always to avoid error logging.
  • More useful things:
    • Select nodes by text
      ExampleTag/li[text()="Submit"]
    • Select nodes by text with a type of wildcard
      ExampleTag[contains(text(), "MFI_")]
    • Exclude nodes with not()
      [not(xxxxx)]
    • Can't think of an example but I'm sure someone will find a use for
      [count(li)]
    • Go back to parentnode with
      ..

Write your own

Outside the scope of this wiki, but it's possible to write your own PatchOperation.
- Example PatchOperationMakeGunCECompatible
- Example PatchOperationAddOrReplace

Resources

The best tutorial on PatchOperations created by Zhentar: Introduction to PatchOperation

You can also learn about XPaths here: XPath tutorial

There is also an Overview of PatchOperations on the RimWorldModGuide.