utils

Provides a number of common utility functions. These are primarily used internally by Draftsman, but can be useful outside of that scope and are provided to the user as-is.

Abstract Shape Classes

class Shape(position: Vector)

Abstract Shape class. Must be overwritten with an implementation. Contains a single attribute, a PrimitiveVector position.

abstract overlaps(other: Shape) bool

Determines if this Shape overlaps with another Shape.

Parameters:
other: Shape

The other Shape to check for intersection.

Returns:

True if the two shapes overlap, False otherwise.

class AABB(
x1: float,
y1: float,
x2: float,
y2: float,
position: Vector | tuple[int | float, int | float] = (0, 0),
)

Axis-Aligned Bounding-Box abstraction class. Contains a top_left point and a bot_right point, as well as an offset position. Provides an abstraction for CollisionSet and a number of convenience functions.

property world_bot_right : tuple[int | float, int | float]

Gets the bottom right of the AABB, as offset by it’s position. As the attribute suggests, this is typically the top-left of the box in world space. Read only.

property world_top_left : tuple[int | float, int | float]

Gets the top left of the AABB, as offset by it’s position. As the attribute suggests, this is typically the top-left of the box in world space. Read only.

static from_other(aabb: list[float] | tuple[float]) AABB

Converts a PrimitiveAABB to an AABB.

Parameters:
aabb: list[float] | tuple[float]

A PrimitiveAABB to convert from.

Returns:

An AABB instance.

get_bounding_box() AABB

Returns the minimum-encompassing bounding box around this AABB, which happens to be an new AABB offset by this AABB’s position. Used for broadphase collision-checking in SpatialDataStructure.

Returns:

A new AABB object with it’s top left and bottom right offset by this AABB’s position, and the new AABB’s position at (0, 0).

get_points() list[tuple[int | float, int | float]]

Returns all 4 points associated with the corners of the AABB, used for determining collision.

Returns:

a list of 4 Vector objects for each of the AABB corners.

overlaps(other: Shape) bool

Determines if this Shape overlaps with another Shape.

Parameters:
other: Shape

The other Shape to check for intersection.

Returns:

True if the two shapes overlap, False otherwise.

rotate(amt: int) AABB

Rotates the AABB by increments of 90 degrees and returns a new transformed instance.

amt is expressed in increments of Direction, such that 4 is a rotation of 90 degrees clockwise and -4 is a rotation of 90 degrees counter-clockwise.

Raises:

ValueError – If amt is not % 4, as AABB’s can only be rotated by 90 degrees.

Parameters:
amt: int

The amount to rotate, expressed as an increments of 22.5 degrees.

class Rectangle(
position: Vector | tuple[int | float, int | float],
width: float,
height: float,
angle: float,
)

A rotate-able rectangle abstraction class, distinguished from AABB. Specified as a width, height, an angle, and a position (it’s center).

get_bounding_box() AABB

Returns the minimum-encompassing bounding box around this Rectangle. Used for broadphase collision-checking in SpatialDataStructure.

Returns:

A new AABB object that circumscribes this Rectangle, with the returned AABB’s position at (0, 0).

get_points() list[tuple[int | float, int | float]]

Returns all 4 points associated with the corners of the Rectangle, used for determining collision.

Returns:

a list of 4 Vector objects for each of the Rectangle’s corners.

overlaps(other: Shape) bool

Determines if this Shape overlaps with another Shape.

Parameters:
other: Shape

The other Shape to check for intersection.

Returns:

True if the two shapes overlap, False otherwise.

rotate(amt: int) Rectangle

Rotates the Rectangle by increments of 45 degrees and returns a new transformed instance.

amt is expressed in increments of Direction, such that 2 is a rotation of 90 degrees clockwise and -2 is a rotation of 90 degrees counter-clockwise.

Parameters:
amt: int

The amount to rotate, expressed as an increments of 45 degrees.

Encoding/Decoding Operations

string_to_JSON(string: str) dict

Decodes a Factorio Blueprint string to a readable JSON Dict. Follows the data format specification here.

For the inverse operation, see JSON_to_string().

Parameters:
string: str

The input Factorio blueprint string.

Returns:

A JSON dict with the blueprint’s components as keys.

Raises:

MalformedBlueprintStringError – If the input string is not decodable to a JSON object.

JSON_to_string(JSON: dict) str

Encodes a JSON dict to a Factorio-readable blueprint string.

Follows the data format specification here.

For the inverse operation, see string_to_JSON().

Note

This function does not verify the data before encoding it. Attempting to import an incorrectly formatted blueprint dict will usually result with an error in Factorio. If you need format validation, consider using Blueprint instead.

Parameters:
JSON: dict

The input JSON dict object.

Returns:

A str which can be imported into Factorio.

encode_version(major: int, minor: int, patch: int = 0, dev_ver: int = 0) int

Converts version components to version number.

Encodes 4 16-bit version numbers into a 64 bit unsigned integer used to specify the version of a Factorio Blueprint or Blueprint Book.

For the inverse operation, see decode_version().

Parameters:
major: int

Major version number.

minor: int

Minor version number.

patch: int = 0

Patch version number.

dev_ver: int = 0

Development version number, used internally by Factorio.

Returns:

A 64 bit int with all components specified.

decode_version(version_number: int) tuple[int, int, int, int]

Converts version number to version components. Decodes a 64 bit unsigned integer into 4 unsigned shorts and returns them as a 4-length tuple, which is usually more readable than the combined format.

For the inverse operation, see encode_version().

Parameters:
version_number: int

The version number to decode.

Returns:

a 4 length tuple in the format (major, minor, patch, dev_ver).

version_string_to_tuple(version_string: str) tuple[int, int, int, int]

Converts a version string to a tuple.

Used extensively when parsing mod versions when updating the package’s data, provided to the user for convinience. Splits a string by the dot character and converts each component to an int. Pads the string with trailing zeros in order to match the 4-component version format Factorio uses.

For the inverse operation, see version_tuple_to_string().

Parameters:
version_string: str

The version string to separate.

Returns:

A 4-length tuple of the format (a, b, c, 0) from "a.b.c"

version_tuple_to_string(version_tuple: tuple[int, ...]) str

Converts a version tuple to a string.

Converts each element of the tuple to a string and then joins them with the ‘.’ character.

For the inverse operation, see, version_string_to_tuple().

Parameters:
version_tuple: tuple[int, ...]

The n-length tuple to interpret.

Returns:

A str of the format "a.b.c" from (a, b, c)

Vector Operations

distance(
point1: tuple[int | float, int | float],
point2: tuple[int | float, int | float],
) float

Gets the Euclidean distance between two points. This is mostly just for Python 2 compatability.

Parameters:
point1: tuple[int | float, int | float]

The first point to check between.

point2: tuple[int | float, int | float]

The first point to check between.

Returns:

The distance between.

rotate_point(
a: tuple[int | float, int | float],
angle: float,
) tuple[int | float, int | float]

Rotate a given vector by angle radians around the origin.

Parameters:
a: tuple[int | float, int | float]

The vector to rotate.

angle: float

The angle to rotate, in radians.

Returns:

A new PrimitiveVector with the resultant rotation.

dot_product(
a: tuple[int | float, int | float],
b: tuple[int | float, int | float],
) float

Gets the dot product between two 2D vectors.

Parameters:
a: tuple[int | float, int | float]

The first vector.

Parma b:

The second vector.

Returns:

The dot product of a and b.

magnitude(a: tuple[int | float, int | float]) float

Gets the magnitude of a point.

Parameters:
a: tuple[int | float, int | float]

The input vector to get the magnitude of.

Returns:

The distance from the origin of point a.

normalize(a: tuple[int | float, int | float]) tuple[int | float, int | float]

Normalizes a vector such that it’s magnitude is equal to 1.

Parameters:
a: tuple[int | float, int | float]

The input vector to normalize.

Returns:

A new PrimitiveVector equivalent to normalized a.

perpendicular(a: tuple[int | float, int | float]) tuple[int | float, int | float]

Returns a perpendicular 2D vector from another vector. Used to generate normal vectors for the Separating Axis Theorem.

Parameters:
a: tuple[int | float, int | float]

The original vector to calculate from.

Returns:

A perpendicular vector to a.

Collision Functions

point_in_aabb(p: tuple[int | float, int | float], a: AABB) bool

Checks to see if a PrimitiveVector p is located inside AABB a.

Parameters:
p: tuple[int | float, int | float]

A Vector with a first and second element.

a: AABB

An AABB with the region to check against.

Returns:

True if the point is inside the box, False otherwise.

aabb_overlaps_aabb(a: AABB, b: AABB) bool

Checks to see if AABB a overlaps AABB b.

Parameters:
a: AABB

2-Dimensional list where the first pair is the minimum coordinate and the second pair is the maximum coordinate.

b: AABB

Another AABB of the same format as a.

Returns:

True if they overlap, False otherwise.

point_in_circle(
p: tuple[int | float, int | float],
r: float,
c: tuple[int | float, int | float] = (0, 0),
) bool

Checks to see if a point p lies within radius r centered around point c. If c is not provided, the origin is assumed.

Parameters:
p: tuple[int | float, int | float]

A point sequence with a first and second element.

r: float

The radius of the circle.

c: tuple[int | float, int | float] = (0, 0)

A point sequence with a first and second element.

Returns:

True if the point is within the circle, False otherwise.

aabb_overlaps_circle(
a: AABB,
r: float,
c: tuple[int | float, int | float],
) bool

Checks to see if an AABB a overlaps a circle with radius r at point c. Algorithm pulled from https://stackoverflow.com/a/402010/8167625

Parameters:
a: AABB

2-Dimensional list where the first pair is the minimum coordinate and the second pair is the maximum coordinate.

r: float

The radius of the circle.

c: tuple[int | float, int | float]

The center of the circle. Defaults to the origin if not specified.

Returns:

True if the two shapes overlap, False otherwise.

rect_overlaps_rect(a: Rectangle, b: Rectangle) bool

Checks to see whether or not two (rotatable) Rectangles intersect with each other. Sourced from: https://github.com/qwertyquerty/collision/blob/master/collision/util.py

Parameters:
a: Rectangle

The first Recangle to check.

b: Rectangle

The second Recangle to check.

Returns:

True if the two shapes overlap, False otherwise.

extend_aabb(
a: AABB | None,
b: AABB | None,
) AABB | None

Gets the minimum AABB that encompasses two other bounding boxes. Used to ‘grow’ the size of a bounding box to encompass both inputs. If one of the inputs is None, then the opposite is returned; if both are None, then None is returned.

Parameters:
a: AABB | None

The first AABB to extend.

b: AABB | None

The second AABB to extend.

Returns:

The minumum bounding AABB between the two inputs.

aabb_to_dimensions(aabb: AABB | None) tuple[int, int]

Gets the tile-dimensions of an AABB, or the minimum number of tiles across each axis that the box would have to take up. If the input aabb is None, the function returns (0, 0).

Parameters:
aabb: AABB | None

2-Dimensional list where the first pair is the minimum coordinate and the second pair is the maximum coordinate.

Returns:

a tuple of the form (tile_width, tile_height)

Miscellaneous

get_first(entity_names: list[str])

Because python has no convenient get equivalent for lists, we use this method to return the first element of the list and None otherwise. Used to grab the default entity name if one is not supplied to the constructor of an Entity.

Parameters:
entity_names: list[str]

The list of entities to attempt to get the first entry from.

Returns:

entity_names[0], or None if no such entry exists.

flatten_entities(collection: Collection) list[Entity]

Iterates over a Collection with nested structures and returns a 1D, “flattened” list of those entities.

Parameters:
collection: Collection

The Collection instance to grab the entities from.

Returns:

A list containing all the entities in breadth-first sequence.

parse_energy(energy_string: str) int

Converts a Factorio energy description string into a integer number of Joules or Watts. Valid inputs match the following regex string:

"[0..9]+[kKMGTPEZY]?[JW]"

Correctly formatted strings start with a valid integer, followed by an optional magnitude character, finished with either “J” for Joules or “W” for Watts.

Behaves identically to util.parse_energy in Factorio’s source; if a Watt string is input, it will convert the output result to Joules/tick instead of Joules/second (1/60th Watts).

Parameters:
energy_string: str

The correctly formatted input string to parse.

Returns:

a properly-scaled integer representing the Joule or Watt amount input.

Raises:

ValueError – If the input string is missing it’s Joule/Watt identifier, it’s magnitude character is not recognized, or if the string remainder cannot be parsed to an integer.

@reissue_warnings

Function decorator that catches all warnings issued from a function and re-issues them to the calling function.

Parameters:
func

The function who’s errors are caught and re-issued.

Returns:

The result of the function.