blueprint¶
Contains the Blueprint class for easily creating and exporting blueprints.
- class Blueprint(
- label='',
- label_color=None,
- description='',
- icons=NOTHING,
- version=NOTHING,
- index: ~typing.Annotated[int,
- <draftsman.validators._AndValidator object at 0x7e1ce9d4e8c0>] | None = None,
- item: str = 'blueprint',
- snapping_grid_size=None,
- snapping_grid_position=NOTHING,
- absolute_snapping: bool = False,
- position_relative_to_grid=NOTHING,
- *,
- extra_keys: dict[str,
- ~typing.Any] | None = None,
- entities: ~draftsman.classes.entity_list.EntityList = NOTHING,
- tiles: ~draftsman.classes.tile_list.TileList = NOTHING,
- groups: ~draftsman.classes.collection.CollectionList = NOTHING,
- schedules: ~draftsman.classes.schedule_list.ScheduleList = NOTHING,
- wires=NOTHING,
- parameters: list[~draftsman.signatures.IDParameter | ~draftsman.signatures.NumberParameter] = NOTHING,
- stock_connections: list[~draftsman.signatures.StockConnection] = NOTHING,
Bases:
Transformable,Collection,BlueprintableFactorio Blueprint class.
- absolute_snapping : bool¶
Serialized
This attribute is imported/exported from blueprint strings.
Whether or not the blueprint uses absolute positioning or relative positioning for the snapping grid. On import, a value of
Noneis interpreted as a defaultTrue.
- description : str¶
Serialized
This attribute is imported/exported from blueprint strings.
The description of the blueprintable. Visible when hovering over it when inside someone’s inventory. Has a maximum size of 500 bytes.
- property double_grid_aligned : bool¶
Whether or not the blueprint is aligned with the double grid, which is the grid that rail entities use, like rails and train-stops. If the blueprint has any entities that are double-grid-aligned, the Blueprint is considered double-grid-aligned. Read only.
- entities : EntityList¶
Serialized
This attribute is imported/exported from blueprint strings.
The list containing this collection’s entities.
Supports inserting/appending new entities via a string name, as well as any keyword arguments to pass to that entity’s constructor:
blueprint.entities.append("wooden-chest", bar=10) assert type(blueprint.entities[-1]) is Container assert blueprint.entities[-1].name == "wooden-chest" assert blueprint.entities[-1].bar == 10In addition to indexing by integer location,
EntityListalso supports indexing via string, corresponding to theidof the entity:blueprint.entities.insert(0, "wooden-chest", id="example") assert blueprint.entities["example"] is blueprint.entities[0]
- extra_keys : dict[str, Any] | None¶
Serialized
This attribute is imported/exported from blueprint strings.
Any additional keys that are not recognized by Draftsman when loading from a raw JSON dictionary end up as keys in this attribute. Under normal circumstances, this field should always remain
None, indicating that all fields provided were properly translated into the internal Python format.If there are any values in
extra_keysafter being imported from a raw JSON dictionary, then (left alone) these values will also be exported back into an output JSON dictionary in order to keep import-export cycles stable. A side effect of this is that users can use this attribute to add additional fields that will end up in the output string, primarily for custom metadata that can be read by other tools:>>> input_dict = { ... "name": "wooden-chest", ... "position": {"x": 0.5, "y": 0.5}, ... "unknown_key": "blah" ... } >>> container = Container.from_dict(input_dict) >>> container.extra_keys {"unknown_key": "blah"} >>> container.extra_keys["custom"] = "data" >>> container.to_dict() { "name": "wooden-chest", "position": {"x": 0.5, "y": 0.5}, "unknown_key": "blah", "custom": "data" }The structure of input keys are preserved, meaning you may have to recurse through keys to find the unknown data:
>>> input_dict = { ... "name": "wooden-chest", ... "position": {"x": 0.5, "y": 0.5}, ... "nested": { ... "dictionary": "value" ... } ... } >>> container = Container.from_dict(input_dict) >>> container.extra_keys {"nested": {"dictionary": "value"}}Note
While Draftsman makes an effort to preserve keys that it doesn’t recognize, Factorio itself makes no such effort - so if you create a blueprint string with custom metadata and then import it into the game, that additional data will be stripped and cannot be retrieved when exporting a new string from the game.
- property flippable : bool¶
Whether or not this collection can be flipped or not. This is determined by whether or not any of the entities contained can be flipped or not. Read only.
- groups : CollectionList¶
A list of child
Groupobjects that this collection contains.Like
EntityList, Groups added to this list with populated IDs can be accessed via those IDs:>>> from draftsman.blueprintable import Blueprint, Group >>> blueprint = Blueprint() >>> new_group = Group(id="something") >>> blueprint.groups.append(new_group) Group(...) >>> assert blueprint.groups["something"] == new_groupThis attribute is not exported. Instead, all entities/tiles that are contained within it are “flattened” to the root-most entity/tile lists, with their positions and associations preserved.
Added in version 3.0.0.
- icons : list[Icon]¶
Serialized
This attribute is imported/exported from blueprint strings.
The visible icons of the blueprintable, as shown in the icon in Factorio’s GUI. A max of 4
Icons are permitted.Icons can also be specified more succinctly as a simple list of signal names:
>>> from draftsman.blueprintable import Blueprint >>> blueprint = Blueprint() >>> blueprint.icons = ["transport-belt"] >>> blueprint.icons [Icon(index=0, signal=SignalID(name='transport-belt', type='item', quality='normal'))]
- index : uint16 | None¶
Serialized
This attribute is imported/exported from blueprint strings.
The location of the blueprintable in a parent
BlueprintBook. This member is automatically generated if omitted, but can be manually set with this attribute. This attribute has no meaning when the blueprintable is not located inside another blueprint book.
- item : str¶
Serialized
This attribute is imported/exported from blueprint strings.
Always the name of the corresponding Factorio item to this blueprintable instance. Read only.
- label : str¶
Serialized
This attribute is imported/exported from blueprint strings.
The user given name (title) of the blueprintable.
- label_color : Color | None¶
Serialized
This attribute is imported/exported from blueprint strings.
The
Colorof the Blueprint’s label.
- parameters : list[IDParameter | NumberParameter]¶
Serialized
This attribute is imported/exported from blueprint strings.
A list of all
Parameters that this blueprint implements.Parameters are evaluated sequentially from the beginning of the list to the end.
Added in version 3.1.0: (Factorio 2.0)
- position_relative_to_grid : Vector¶
Serialized
This attribute is imported/exported from blueprint strings.
The absolute position of the snapping grid in the world. Only used if
absolute_snappingis set toTrue.
- property root_item : 'blueprint'¶
Serialized
This attribute is imported/exported from blueprint strings.
The “root” key of this Blueprintable’s dictionary form. For example, blueprints have the
root_itemkey “blueprint”:{ "blueprint": { # <- this is the "root_item" ... } }All keys (except for
index) are contained within this sub- dictionary.
- property rotatable : bool¶
Whether or not this collection can be rotated or not. Included for posterity; always returns True, even when containing entities that have no direction component. Read only.
- schedules : ScheduleList¶
Serialized
This attribute is imported/exported from blueprint strings.
A list of the Collections’s
Schedules.
- snapping_grid_position : Vector¶
Sets the position of the snapping grid. Offsets all of the positions of the entities by this amount, effectively acting as a translation in relation to the snapping grid.
Note
This attribute does not offset each entities position until export!
- snapping_grid_size : Vector | None¶
Serialized
This attribute is imported/exported from blueprint strings.
Sets the size of the snapping grid to use. The presence of this entry determines whether or not the Blueprint will have a snapping grid or not.
- stock_connections : list[StockConnection]¶
Serialized
This attribute is imported/exported from blueprint strings.
A list of connections between train cars, documenting exactly which ones are connected to what. Prior to Factorio 2.0, train car connections were inferred and automatically generated on blueprint import; this field allows for manual control over this behavior.
Added in version 3.0.0: (Factorio 2.0)
- tiles : TileList¶
Serialized
This attribute is imported/exported from blueprint strings.
The list containing this collection’s tiles.
Supports inserting/appending new tiles via a string name, as well as any keyword arguments to pass to that entity’s constructor:
blueprint.tiles.append("landfill") assert type(blueprint.tiles[-1]) is Tile assert blueprint.tiles[-1].name == "landfill"
- version : uint64¶
Serialized
This attribute is imported/exported from blueprint strings.
The version of Factorio the Blueprint was created in.
The Blueprint
versionis a 64-bit integer, which is a bitwise-OR of four 16-bit numbers. You can interpret this number more clearly by decoding it withdraftsman.utils.decode_version(), or you can use the functionsversion_tuple()orversion_string()which will give you a more readable output. This version number defaults to the version of Factorio of Draftsman’s environment.The version can be set either a 64-bit int in the format above, or as a sequence of ints (usually a list or tuple) which is then encoded into the combined representation. The sequence is defined as:
[major_version, minor_version, patch, development_release]withpatchanddevelopment_releasedefaulting to 0.- Example:
>>> from draftsman.blueprintable import Blueprint >>> blueprint = Blueprint() >>> blueprint.version = (1, 0) # version 1.0.0.0 >>> assert blueprint.version == 281474976710656 >>> assert blueprint.version_tuple() == (1, 0, 0, 0) >>> assert blueprint.version_string() == "1.0.0.0"
- wires : list[list[Association, WireConnectorID, Association, WireConnectorID]]¶
Serialized
This attribute is imported/exported from blueprint strings.
A list of all the wire connections in this blueprint.
Wires are specified as two pairs of
AssociationandWireConnectorID; the first pair represents the first entity, and the second pair represents the second entity. The association points to the corresponding entity in this collection, and the wire type enum indicates what type of connection it is.When exported to JSON, the associations and enums in each wire are resolved to integers corresponding to the given
entity_numberin the resultingentitieslist.Added in version 3.0.0: (Factorio 2.0)
- add_circuit_connection(
- color: 'red' | 'green',
- entity_1: EntityLike | int | str | Sequence[int | str],
- entity_2: EntityLike | int | str | Sequence[int | str],
- side_1: 'input' | 'output' =
'input', - side_2: 'input' | 'output' =
'input', Adds a circuit wire connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the
entitieslist, or it’s string ID. Color specifies the color of the wire to make the connection with, and is either"red"or"green".side1specifies which side of the first entity to connect to (if applicable), andside2specifies which side of the second entity to connect to (if applicable). Does nothing if the connection already exists.Raises
ConnectionSideWarningif the side of either of the entities is2when the entity is not dual-circuit-connectable.Raises
ConnectionRangeWarningif the distance between the two entities exceeds the maximum wire distance between the two.- Parameters:
- color: 'red' | 'green'¶
Color of the wire to make the connection with. Must be either
"red"or"green".- entity_1: EntityLike | int | str | Sequence[int | str]¶
ID or index of the first entity to join.
- entity_2: EntityLike | int | str | Sequence[int | str]¶
ID or index of the second entity to join.
- side_1: 'input' | 'output' =
'input'¶ Which side of
entity_1to connect to. Only necessary to specify for entities that areEntity.dual_circuit_connectable.- side_2: 'input' | 'output' =
'input'¶ Which side of
entity_2to connect to. Only necessary to specify for entities that areEntity.dual_circuit_connectable.
- Raises:
KeyError, IndexError – If
entity_1and/orentity_2are invalid ID’s or indices to the parent Collection.InvalidAssociationError – If
entity_1and/orentity_2are not inside the parent Collection.InvalidWireTypeError – If
coloris neither"red"nor"green".InvalidConnectionSideError – If
side_1orside_2are neither"input"nor"output".EntityNotCircuitConnectableError – If either entity_1 or entity_2 do not have the capability to be circuit wire connected.
- add_power_connection(
- entity_1: EntityLike | int | str | Sequence[int | str],
- entity_2: EntityLike | int | str | Sequence[int | str],
- side_1: 'input' | 'output' =
'input', - side_2: 'input' | 'output' =
'input', Adds a copper wire power connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the
entitieslist, or it’s string ID. Tuples of strings and ints mean to recursively search through theCollection‘sgroupsfor an entity at that tree “path”. For example:blueprint.entities.append("small-electric-pole") group = Group("group") # A type of `Collection` group.entities.append("small-electric-pole", tile_position=(5, 0)) blueprint.groups.append(group) # Add a connection between the first power pole and the first entity # in the group blueprint.add_power_connection(blueprint.entities[0], ("group", 0))Side specifies which side to connect to when establishing a connection to a dual-power-connectable entity (usually a power-switch). Does nothing if the connection already exists.
Raises
ConnectionRangeWarningif the distance between the two entities exceeds the maximum wire distance between the two.Raises
TooManyConnectionsWarningif either of the power poles exceed 5 connections when this connection is added.- Parameters:
- entity_1: EntityLike | int | str | Sequence[int | str]¶
EntityLike, ID, or index of the first entity to join.
- entity_2: EntityLike | int | str | Sequence[int | str]¶
EntityLike, ID or index of the second entity to join.
- side_1: 'input' | 'output' =
'input'¶ Which side of
entity_1to connect power to. Only necessary to specify for entities that areEntity.dual_power_connectable.- side_2: 'input' | 'output' =
'input'¶ Which side of
entity_2to connect power to. Only necessary to specify for entities that areEntity.dual_power_connectable.
- Raises:
KeyError, IndexError – If
entity_1and/orentity_2are invalid ID’s or indices to the parent Collection.InvalidAssociationError – If
entity_1and/orentity_2are not inside the parent Collection.EntityNotPowerConnectableError – If either entity_1 or entity_2 do not have the capability to be copper wire connected.
DraftsmanError – If both entity_1 and entity_2 are dual-power-connectable, of which a connection is forbidden.
- add_train_at_position(
- config: TrainConfiguration,
- position: Vector | tuple[int | float, int | float],
- direction: Direction,
- schedule: Schedule | None =
None, Adds a train with a specified configuration and schedule at a position facing a particular direction. Allows you to place a fully configured train in a single function call.
If schedule is
specified, then it’s checked if that schedule already exists within the collection’sschedules. If found, all the locomotives in the added train are added to that schedule’s locomotives; if not, a new schedule is appended to the list and the locomotives are added to that entry instead.- Parameters:
- config: TrainConfiguration¶
The
TrainConfigurationto use as a template for the created train, or a str that will be converted into one.- position: Vector | tuple[int | float, int | float]¶
A
Vectorspecifying the center of the starting wagon.- direction: Direction¶
A
Directionenum orintspecifying which direction the train is “facing”.- schedule: Schedule | None =
None¶ A
Scheduleobject specifying the schedule that the newly created train should inherit.
- add_train_at_station(
- config: TrainConfiguration,
- station: EntityLike | str | int,
- schedule: Schedule | None =
None, Adds a train with a specified configuration and schedule behind a specified train stop.
If schedule is
specified, then it’s checked if that schedule already exists within the collection’sschedules. If found, all the locomotives in the added train are added to that schedule’s locomotives; if not, a new schedule is appended to the list and the locomotives are added to that entry instead.- Parameters:
- config: TrainConfiguration¶
The
TrainConfigurationto use as a template for the created train, or a str that will be converted into one.- station: EntityLike | str | int¶
The ID or index of the train entity stop to spawn behind. Note that station names cannot be used; if you want to place a train behind a stop with a specific station name use
find_entities_filtered()to find candidates and then pick ones from there.- schedule: Schedule | None =
None¶ A
Scheduleobject specifying the schedule that the newly created train should inherit.
- ensure_reasonable_size(
- *,
- mode=
None, - error_list: list | None =
None, - warning_list: list | None =
None, - **kwargs,
Validator wrapper for
@classvalidator.
- find_entities( ) list[EntityLike]¶
Returns a
listof all entities within the areaaabb. Works similiarly to LuaSurface.find_entities. If noaabbis provided then the method simply returns all the entities in the blueprint.
- find_entities_filtered(
- position: Vector | None =
None, - radius: float | None =
None, - area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None =
None, - name: str | set[str] | None =
None, - type: str | set[str] | None =
None, - direction: Direction | None =
None, - invert: bool =
False, - limit: int | None =
None, Returns a filtered list of entities within the
Collection. Works similarly to LuaSurface.find_entities_filtered.Keywords are organized into two main categrories: region and criteria:
Region keywords¶ Name
Type
Description
positionVectororPrimitiveVectorGrid position to search.
radiusfloatRadius of the circle around position to search.
areaAABBorPrimitiveAABBAABB to search in.
If none of the above are specified, then the search area becomes the entire Collection. If
radiusis specified butpositionis not, the search area also becomes the entire Collection.Criteria keywords¶ Name
Type
Description
namestrorset{str}The name(s) of the entities that you want to search for.
typestrorset{str}The type(s) of the entities that you want to search for.
directionDirectionorset{Direction}The direction(s) of the entities that you want to search for.Excludes entities that have no direction.limitintLimit the maximum size of the returned list to this amount.Unlimited by default.invertboolWhether or not to return the inverse of the search.False by default.- Parameters:
- position: Vector | None =
None¶ The global position to search the source Collection. Can be used in conjunction with
radiusto search a circle instead of a single point. Takes precedence overarea.- radius: float | None =
None¶ The radius of the circle centered around
positionto search. Must be defined alongsidepositionin order to search in a circular area.- area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None =
None¶ The
AABBorPrimitiveAABBto search in.- name: str | set[str] | None =
None¶ Either a
str, or aset[str]where each entry is a name of an entity to be returned.- type: str | set[str] | None =
None¶ Either a
str, or aset[str]where each entry is a type of an entity to be returned.- direction: Direction | None =
None¶ Either a
Directionenum (or correspondingint), or aset[Direction]where each entry is a valid direction for each returned entity to match. Excludes entities that have no direction attribute.- invert: bool =
False¶ Whether or not to return the inversion of the search criteria.
- limit: int | None =
None¶ The total number of matching entities to return. Unlimited by default.
- position: Vector | None =
- Returns:
A list of Entity references inside the searched collection that satisfy the search criteria.
- find_entity( ) EntityLike¶
Finds an entity with
nameat a positionposition. If multiple entities exist at the queried position, the one that was first placed is returned.
- find_entity_at_position( ) EntityLike¶
Finds any entity at the position
position. If multiple entities exist at the queried position, the one that was first placed is returned.
- find_tile( ) list[Tile]¶
Returns a list containing all the tiles at the tile coordinate
position. If there are no tiles at that position, an empty list is returned.
- find_tiles_filtered(
- position: Vector | tuple[int | float, int | float] | None =
None, - radius: float | None =
None, - area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None =
None, - name: str | None =
None, - invert: bool =
False, - limit: int | None =
None, Returns a filtered list of tiles within the blueprint. Works similarly to LuaSurface.find_tiles_filtered.
Keywords are organized into two main categrories: region and criteria:
Region keywords¶ Name
Type
Description
positionVectororPrimitiveVectorGrid position to search.
radiusfloatRadius of the circle around position to search.
areaAABBorPrimitiveAABBAABB to search in.
Criteria keywords¶ Name
Type
Description
namestrorset{str}The name(s) of the entities that you want to search for.
limitintLimit the maximum size of the returned list to this amount.Unlimited by default.invertboolWhether or not to return the inverse of the search.Falseby default.- Parameters:
- position: Vector | tuple[int | float, int | float] | None =
None¶ The global position to search the source Collection. Can be used in conjunction with
radiusto search a circle instead of a single point. Takes precedence overarea.- radius: float | None =
None¶ The radius of the circle centered around
positionto search. Must be defined alongsidepositionin order to search in a circular area.- area: AABB | tuple[tuple[int | float, int | float], tuple[int | float, int | float]] | None =
None¶ The
AABBorPrimitiveAABBto search in.- name: str | None =
None¶ Either a
str, or aset[str]where each entry is a name of an entity to be returned.- invert: bool =
False¶ Whether or not to return the inversion of the search criteria.
- limit: int | None =
None¶ The total number of matching entities to return. Unlimited by default.
- position: Vector | tuple[int | float, int | float] | None =
- Returns:
A list of Tile references inside the searched collection that match the specified criteria.
- find_train_from_wagon( ) list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon]¶
Returns a list of rolling stock connected together. Allows you to grab all connected cars to a particular wagon if you know where one is, such as when iterating through the locomotives in a particular
Scheduleobject, cargo wagons with a particular item filter returned fromfind_entities_filtered(), etc.Note that this function may return a working train (rolling stock with at least one connected locomotive), but it also may not, since it’s only criteria is connection.
Warning
This function might also return false positives if rolling stock is located right next to each other in a fully-compresssed rail setups. PR’s to mitigate this are welcome.
- Parameters:
- wagon: Locomotive | CargoWagon | FluidWagon | ArtilleryWagon¶
The ID of the wagon or the wagon itself to search for neighbours.
- Returns:
A
listof references to all connected wagons in theCollection, includingwagonitself. The order of wagons is listed from end to end, where the first entry in the list is the outermost car in the direction thatwagonpoints.
- find_trains_filtered(
- train_length: int | tuple | None =
None, - orientation: Orientation | None =
None, - at_station: bool | set =
False, - num_type: dict | None =
None, - num_name: dict | None =
None, - config: TrainConfiguration | None =
None, - schedule: Schedule | None =
None, - invert: bool =
False, - limit: int | None =
None, Finds a set of trains that match the passed in parameters. Formally, a “train” in this context is a connected set of wagons which may or may not contain a locomotive. This is done so that the user can search a blueprint for unconnected rolling stock if any exists, and can filter for regular trains more broadly.
Note
When using the
configparameter, equality is strictly checked; which means that if a returned train doesn’t _exactly_ match the specified argument, the train is filtered from the result. This includes things like fuel requests and cargo wagon item filters, so check these values in the blueprints you’re searching and adjustconfigaccordingly.- Parameters:
- train_length: int | tuple | None =
None¶ Can either be specified as an
intrepresenting the exact length of trains to return, or as aSequenceof 2int``s representing the minimum and maximum length of trains to return (inclusive). Either the min or the max can also be set to ``Nonewhich indicates no minimum length and no maxiumum length respectively.- orientation: Orientation | None =
None¶ A
Orientation(or equivalentfloat) that describes the orientation that every car in the returned train list should have. Note that trains placed on curved rails will not be returned by this parameter, as _all_ train cars must equalorientation.- at_station: bool | set =
False¶ Can be specified as a
boolvalue which will return all trains at any station, astrvalue where it will return all trains at any station with that name, or as aset[str]where all of the trains behind any station with one of those names is returned.- num_type: dict | None =
None¶ A
dictof wagon types where each key is thestrtype of the wagon and the value is anintrepresenting the desired number of those wagons in the returned train. Allows to search for trains of a particular composition without regards to contents, order, or orientation. Also supports swapping theintwith aSequenceof 2int``s representing the minimum and maximum tolerable value of a wagon of that type, along with ``Nonefor no particular min or max.- num_name: dict | None =
None¶ Identical to
num_type, except that instead of wagon type it’s wagon name, in case there happen to be more than one Locomotive, CargoWagon, FluidWagon, or ArtilleryWagon. Useful for blueprints with modded trains, where you might want to distinguish between them.- config: TrainConfiguration | None =
None¶ A
TrainConfigurationobject to filter against. Performs a equality check between each of the train configuration’s cars and the cars in the returned trains.- schedule: Schedule | None =
None¶ A
Schedulethat the returned trains should match. Only trains who’s schedules match this one exactly will be returned.- invert: bool =
False¶ Whether or not to return the inversion of the search criteria.
- limit: int | None =
None¶ A maximum number of unique trains to return.
- train_length: int | tuple | None =
- Returns:
A
listoflists, where each sub-list represents a contiguous train. Trains are ordered such that the first index is the “front” of the train, as chosen by the orientation of the first found wagon in that group.
- flip(
- direction: 'horizontal' | 'vertical' =
'horizontal', Flip the blueprint across an axis, if possible. Flipping is done over the x or y axis, depeding on the input
direction.- Parameters:
- direction: 'horizontal' | 'vertical' =
'horizontal'¶ The direction to flip by; either
"horizontal"or"vertical"
- direction: 'horizontal' | 'vertical' =
- classmethod from_dict( ) Self¶
Attempts to construct a new instance of this class from a Python dictionary in JSON format.
- Parameters:
- d: dict¶
The dictionary to interpret.
- version: tuple[int, ...] | None =
None¶ The Factorio version that the input data is compliant with.
The given version tuple will automatically attempt to grab the closest applicable converter - meaning that specifying a version of
(1, 1, 96)will use the 1.0 converter, and a version of(2, 0, 32)will use the 2.0 converter.If no version is provided, it will default to current environment’s Factorio version, or to
draftsman.DEFAULT_FACTORIO_VERSIONif unable to read the current environment.
- classmethod from_string(string: str)¶
Creates a
Blueprintablewith the contents ofstring.Raises
UnknownKeywordWarningif there are any unrecognized keywords in the blueprint string for this particular blueprintable.- Parameters:
- string: str¶
The Factorio-encoded blueprint string to decode.
- Raises:
MalformedBlueprintStringError – If the input string is not decodable to a JSON object.
IncorrectBlueprintTypeError – If the input string is of a different type than the base class, such as trying to load the string of an upgrade planner into a
Blueprintobject.
- generate_power_connections(
- prefer_axis: bool =
True, - only_axis: bool =
False, Automatically create power connections between all electric poles.
The algorithm used is similar to demi-pixel’s generateElectricalConnections() function, but with some slight differences. Power poles are still prioritized closest first, but can be selected to prefer to connect neighbours on the same axis, as well as only connect to neighbours on the same axis. This function will only connect power poles that have less than 5 power connections already made, preserving power connections that were manually specified. This function does not generate connections between power-switches.
- Parameters:
- prefer_axis: bool =
True¶ Determines whether or not to rank power-poles on the same x or y coordinate higher than poles that are closer, but not on either axis. Used to prefer creating neat, regular grids when possible.
- only_axis: bool =
False¶ Removes any neighbour that does not lie on the same x or y axis from the candidate pool, preventing non-grid connections.
- prefer_axis: bool =
- get_dimensions() tuple[int, int]¶
Calculates the maximum extents of the blueprint along the x and y axis in tiles. Returns
(0, 0)if the blueprint’s world bounding box isNone.- Returns:
A 2-length tuple with the maximum tile width as the first entry and the maximum tile height as the second entry.
- get_world_bounding_box() AABB | None¶
Calculates the minimum AABB which encompasses all entities and tiles within this blueprint. If the blueprint is empty of entities or tiles, or if all of the entities contained within it have no known dimension, then this function returns
None.- Returns:
The smallest
AABBwhich encompasses all entities and tiles currently contained.
- remove_circuit_connection(
- color: 'red' | 'green',
- entity_1: EntityLike | int | str | Sequence[int | str],
- entity_2: EntityLike | int | str | Sequence[int | str],
- side_1: 'input' | 'output' =
'input', - side_2: 'input' | 'output' =
'input', Removes a circuit wire connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the
entitieslist, or it’s string ID.side1specifies which side of the first entity to remove the connection from (if applicable), andside2specifies which side of the second entity to remove the connection from (if applicable). Does nothing if the specified connection doesn’t exist.- Parameters:
- color: 'red' | 'green'¶
Color of the wire to remove. Either
"red"or"green".- entity_1: EntityLike | int | str | Sequence[int | str]¶
ID or index of the first entity to remove the connection to.
- entity_2: EntityLike | int | str | Sequence[int | str]¶
ID or index of the second entity to remove the connection to.
- side_1: 'input' | 'output' =
'input'¶ Which side of
entity_1to remove the connection from. Only necessary to specify for entities that areEntity.dual_circuit_connectable.- side_2: 'input' | 'output' =
'input'¶ Which side of
entity_2to remove the connection from. Only necessary to specify for entities that areEntity.dual_circuit_connectable.
- Raises:
KeyError, IndexError – If
entity_1and/orentity_2are invalid ID’s or indices to the parent Collection.InvalidAssociationError – If
entity_1and/orentity_2are not inside the parent Collection.
- remove_circuit_connections() None¶
Remove all circuit connections in the Collection. Recurses through all subgroups and removes circuit connections from them as well. Does nothing if there are no circuit connections in the Collection to remove.
- remove_power_connection(
- entity_1: EntityLike | int | str | Sequence[int | str],
- entity_2: EntityLike | int | str | Sequence[int | str],
- side_1: 'input' | 'output' =
'input', - side_2: 'input' | 'output' =
'input', Removes a copper wire power connection between two entities. Each entity can be either a reference to the original entity to connect, the index of the entity in the
entitieslist, or it’s string ID.sidespecifies which side to remove the connection from when removing a connection to a dual-power-connectable entity (usually a power-switch). Does nothing if the specified connection does not exist.- Parameters:
- entity_1: EntityLike | int | str | Sequence[int | str]¶
EntityLike, ID or index of the first entity to remove the connection to.
- entity_2: EntityLike | int | str | Sequence[int | str]¶
EntityLike, ID or index of the second entity to remove the connection to.
- side_1: 'input' | 'output' =
'input'¶ Which side of
entity_1to remove a power connection from. Only necessary to specify for entities that areEntity.dual_power_connectable.- side_2: 'input' | 'output' =
'input'¶ Which side of
entity_2to remove a power connection from. Only necessary to specify for entities that areEntity.dual_power_connectable.
- Raises:
KeyError, IndexError – If
entity_1and/orentity_2are invalid ID’s or indices to the parent Collection.InvalidAssociationError – If
entity_1and/orentity_2are not inside the parent Collection.
- remove_power_connections() None¶
Remove all power connections in the Collection, including any power connections between power switches. Recurses through any subgroups, and removes power connections from them as well. Does nothing if there are no power connections in the Collection.
- remove_train(cars: list[EntityLike]) None¶
Removes all of the rolling stock specified as the list
cars, and also takes care of removing any locomotive associations in any correspondingScheduleobject(s). Does nothing ifcarsis empty.- Parameters:
- cars: list[EntityLike]¶
A
listof references toEntityLikes within the collection.
- Raises:
KeyError – If the specified entities within the list do not exist within the collection being accessed.
- rotate(angle: int)¶
Rotate the blueprint by
angle, if possible. Operates the same as pressing ‘r’ with a blueprint selected.angleis specified in terms of Direction enum, meaning that a rotation of 4 is 90 degrees clockwise.Because eight-way rotatable entities exist in a weird gray area, this function behaves like the feature in-game and only rotates on 90 degree intervals. Attempting to rotate the blueprint an odd amount raises an
RotationError.- Parameters:
- angle: int¶
The angle to rotate the blueprint by.
- Raises:
RotationError – If the rotation is attempted with an odd value.
- set_train_schedule(
- train_cars: Locomotive | list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon],
- schedule: Schedule | None,
Sets the schedule of a particular locomotive, or an entire list of RollingStock. The list of rolling stock can include non-locomotive cars, they will just be skipped when setting schedules. The list of rolling stock can also include locomotives across multiple trains; in this case all connected train cars from every touched train will be given the new schedule. If
scheduleis set toNone, then any touched locomotive will have their schedule cleared instead of set.- Parameters:
- train_cars: Locomotive | list[Locomotive | CargoWagon | FluidWagon | ArtilleryWagon]¶
The single Locomotive, or a list of RollingStock.
- schedule: Schedule | None¶
The
Scheduleto give each connected train, orNoneto remove the schedule from each connected train.
- to_dict(
- version: tuple[int, ...] | None =
None, - exclude_none: bool =
True, - exclude_defaults: bool =
True, Export this object to a JSON dictionary, usually directly prior to encoding into the compressed blueprint string format.
- Parameters:
- version: tuple[int, ...] | None =
None¶ Which Factorio version format this entity should be exported with. The same Draftsman object can be converted to many version-specific output dictionaries, each of which may have different structures.
The given version tuple will automatically attempt to grab the closest applicable converter - meaning that specifying a version of
(1, 1, 96)will use the 1.0 converter, and a version of(2, 0, 32)will use the 2.0 converter.If no version is provided, it will default to current environment’s Factorio version, or to
draftsman.DEFAULT_FACTORIO_VERSIONif unable to read the current environment.- exclude_none: bool =
True¶ Whether or not
Noneproperties should be omitted from the output string. For certain properties this option has no effect, as they either must always be present or never be present ifNone.- exclude_defaults: bool =
True¶ Whether or not to exclude properties that are equivalent to their default values. Including these values in the generated output is redundant as Factorio will populate them automatically, but it is useful to disable for debug/illustation purposes.
- version: tuple[int, ...] | None =
-
to_string(version: tuple[int] | None =
None) str¶ Returns this object as an encoded Factorio blueprint string.
- Returns:
The zlib-compressed, base-64 encoded string.
- Example:
>>> from draftsman.blueprintable import ( ... Blueprint, DeconstructionPlanner, UpgradePlanner, BlueprintBook ... ) >>> Blueprint(version=(1, 0)).to_string() '0eNqrVkrKKU0tKMrMK1GyqlbKLEnNVbJCEtNRKkstKs7Mz1OyMrIwNDE3sTQ3Mzc0MDM1q60FAHmVE1M=' >>> DeconstructionPlanner(version=(1, 0)).to_string() '0eNqrVkpJTc7PKy4pKk0uyczPiy/ISczLSy1SsqpWyixJzVWyQlOgC1Ogo1SWWlQMFFGyMrIwNDE3sTQ3Mzc0MDM1q60FAHp9Hf0=' >>> UpgradePlanner(version=(1, 0)).to_string() '0eNqrViotSC9KTEmNL8hJzMtLLVKyqlbKLEnNVbKCyejCZHSUylKLijPz85SsjCwMTcxNLM3NzA0NzEzNamsBqdIX5Q==' >>> BlueprintBook(version=(1, 0)).to_string() '0eNqrVkrKKU0tKMrMK4lPys/PVrKqVsosSc1VskJI6IIldJTKUouKM/PzlKyMLAxNzE0szc3MDQ3MTM10lBKTSzLLUuMz81JSK5SsDGprATINHQI='
- translate(x: int, y: int) None¶
Translates all entities and tiles in the blueprint by
xandy. RaisesRailAlignmentWarningif the parent class contains double-grid-aligned entities and the translation amount is an odd value on either x or y.
- validate(
- mode: ValidationMode =
ValidationMode.STRICT, Validates the called object against it’s known format.
- Example:
>>> import draftsman >>> from draftsman.constants import ValidationMode >>> from draftsman.entity import Container >>> from draftsman.error import DataFormatError >>> c = Container("wooden-chest") >>> with draftsman.validators.set_mode(ValidationMode.DISABLED): ... c.bar = "incorrect" >>> try: ... c.validate().reissue_all() ... except DataFormatError as e: ... print("wrong!") wrong!- Parameters:
- mode: ValidationMode =
ValidationMode.STRICT¶ How strict to be when valiating the object, corresponding to the number and type of errors and warnings returned.
- mode: ValidationMode =
- Returns:
A
ValidationResultobject, which contains all errors and warnings from the validation pass.
- version_string() str¶
Returns the version of the
Blueprintablein human-readable string.- Returns:
a
strof 4 version numbers joined by a ‘.’ character.- Example:
>>> from draftsman.blueprintable import Blueprint >>> blueprint = Blueprint(version=(1, 2, 3)) >>> blueprint.version_string() '1.2.3.0'
- version_tuple() tuple[~typing.Annotated[int, <draftsman.validators._AndValidator object at 0x7e1ce9d4e8c0>], ~typing.Annotated[int, <draftsman.validators._AndValidator object at 0x7e1ce9d4e8c0>], ~typing.Annotated[int, <draftsman.validators._AndValidator object at 0x7e1ce9d4e8c0>], ~typing.Annotated[int, <draftsman.validators._AndValidator object at 0x7e1ce9d4e8c0>]]¶
Returns the version of the
Blueprintableas a 4-length tuple.- Returns:
A 4 length tuple in the format
(major, minor, patch, dev_ver).- Example:
>>> from draftsman.blueprintable import Blueprint >>> blueprint = Blueprint(version=281474976710656) >>> blueprint.version_tuple() (1, 0, 0, 0)