srctools.fgd

Parse FGD files, used to describe Hammer entities.

class srctools.fgd.ValueTypes(value)

Bases: Enum

Types which can be applied to a KeyValue.

VOID = 'void'
CHOICES = 'choices'
SPAWNFLAGS = 'flags'
STRING = 'string'
BOOL = 'boolean'
INT = 'integer'
FLOAT = 'float'
VEC = 'vector'
ANGLES = 'angle'
TARG_DEST = 'target_destination'

Aliases: ENT_HANDLE, EHANDLE

TARG_DEST_CLASS = 'target_name_or_class'
TARG_SOURCE = 'target_source'
TARG_NPC_CLASS = 'npcclass'
TARG_POINT_CLASS = 'pointentityclass'
TARG_FILTER_NAME = 'filterclass'
TARG_NODE_DEST = 'node_dest'
TARG_NODE_SOURCE = 'node_id'
STR_SCENE = 'scene'
STR_SOUND = 'sound'
STR_PARTICLE = 'particlesystem'
STR_SPRITE = 'sprite'
STR_DECAL = 'decal'
STR_MATERIAL = 'material'
STR_MODEL = 'studio'
STR_VSCRIPT = 'scriptlist'
STR_VSCRIPT_SINGLE = 'script'
ANGLE_NEG_PITCH = 'angle_negative_pitch'
VEC_LINE = 'vecline'
VEC_ORIGIN = 'origin'
VEC_AXIS = 'axis'
COLOR_1 = 'color1'
COLOR_255 = 'color255'
SIDE_LIST = 'sidelist'
INST_FILE = 'instance_file'
INST_VAR_DEF = 'instance_parm'
INST_VAR_REP = 'instance_variable'
EXT_STR_TEXTURE = 'texture'
EXT_VEC_DIRECTION = 'vec_dir'
EXT_VEC_LOCAL = 'vec_local'
EXT_ANGLE_PITCH = 'angle_pitch'
EXT_ANGLES_LOCAL = 'angle_local'
has_list

Is this a flag or choices value, and needs a [] list?

valid_for_io

Is this type valid for I/O definitions?

extension

Is this an extension to the format?

is_ent_name

Several types are simply a targetname.

class srctools.fgd.EntityTypes(value)

Bases: Enum

The kind of entity each definition is.

BASE = 'baseclass'
POINT = 'pointclass'
BRUSH = 'solidclass'
ROPES = 'keyframeclass'
TRACK = 'moveclass'
FILTER = 'filterclass'
NPC = 'npcclass'
class srctools.fgd.HelperTypes(value)

Bases: Enum

Types of functions in the entity header.

INHERIT = 'base'
HALF_GRID_SNAP = 'halfgridsnap'
CUBE = 'size'
BBOX = 'bbox'
TINT = 'color'
SPHERE = 'sphere'
LINE = 'line'
FRUSTUM = 'frustum'
CYLINDER = 'cylinder'
ORIGIN = 'origin'
VECLINE = 'vecline'
BRUSH_SIDES = 'sidelist'
BOUNDING_BOX_HELPER = 'wirebox'
SWEPT_HULL = 'sweptplayerhull'
ORIENTED_BBOX = 'obb'
SPRITE = 'iconsprite'
MODEL = 'studio'
MODEL_PROP = 'studioprop'
MODEL_NEG_PITCH = 'lightprop'
ENT_SPRITE = 'sprite'
ENT_INSTANCE = 'instance'
ENT_DECAL = 'decal'
ENT_OVERLAY = 'overlay'
ENT_OVERLAY_WATER = 'overlay_transition'
ENT_LIGHT = 'light'
ENT_LIGHT_CONE = 'lightcone'
ENT_ROPE = 'keyframe'
ENT_TRACK = 'animator'
ENT_BREAKABLE_SURF = 'quadbounds'
ENT_WORLDTEXT = 'worldtext'
ENT_CATAPULT = 'catapult'
ENT_LIGHT_CONE_BLACK_MESA = 'lightconenew'
EXT_APPLIES_TO = 'appliesto'
EXT_ORDERBY = 'orderby'
EXT_AUTO_VISGROUP = 'autovis'
extension

Is this an extension to the format?

class srctools.fgd.FGD

A FGD set for a game. May be composed of several files.

classmethod parse(
file: Union[File, str],
filesystem: Optional[FileSystem] = None,
) FGD

Parse an FGD file.

Parameters:
  • file – A :py:class:filesystem.File` representing the file to read, or a file path.
  • filesystem – The system to lookup files in. This is needed to resolve file inclusions. If not passed, file must be a :py:class:filesystem.File` to retrieve this automatically.
apply_bases() None

Fix base values in entities after parsing.

While parsing the classnames may be set as strings, so order in the file doesn’t matter. This fixes them to the real entity objects.

sorted_ents() Iterator[EntityDef]

Yield all entities in sorted order.

This ensures only all bases for an entity are yielded before the entity. Otherwise entities are ordered in alphabetical order.

collapse_bases() None

Collapse all bases into the entities that use them.

This operates in-place, and clears all the base attributes as a result.

export(file: TextIO) None
export() str

Write the FGD contents into a text file.

If none are provided, the text will be returned.

parse_file(
filesys: FileSystem,
file: File,
*,
eval_bases: bool = True,
encoding: str = 'cp1252',
) None

Parse one file (recursively if needed).

If eval_bases is False, bases will not be computed. This makes it impossible in some cases to evaluate these later, but it can help if it is not required.

classmethod engine_dbase() FGD

Load and return a database of entity keyvalues and I/O.

This can be used to identify the kind of keys present on an entity.

serialise(file: IO[bytes]) None

Write the FGD into a compacted binary format.

This is only readable by this module, and does not contain entity, keyvalue and IO help descriptions to keep the data small.

classmethod unserialise(file: IO[bytes]) FGD

Unpack data from FGD.serialise() to return the original data.

Help descriptions are not preserved, and are set to <BINARY>.

class srctools.fgd.EntityDef(
type: EntityTypes,
classname: str = '',
keyvalues: Dict[str, Dict[FrozenSet[str], KeyValues]] = NOTHING,
inputs: Dict[str, Dict[FrozenSet[str], IODef]] = NOTHING,
outputs: Dict[str, Dict[FrozenSet[str], IODef]] = NOTHING,
kv_order: List[str] = NOTHING,
bases: List[Union[EntityDef, str]] = NOTHING,
helpers: List[Helper] = NOTHING,
desc: str = '',
)

A definition for an entity.

classmethod parse(
fgd: FGD,
tok: BaseTokenizer,
ent_type: EntityTypes,
eval_bases: bool = True,
) None

Parse an entity definition.

get_helpers(typ: Type[HelperT]) Iterator[HelperT]
get_helpers(typ: str) Iterator[UnknownHelper]

Find all helpers with this specific type.

strip_tags(tags: FrozenSet[str]) None

Strip all tags from this entity, blanking them.

Only values matching the given tags will be kept.

export(file: TextIO) None

Write the entity out to a FGD file.

iter_bases(_done: Optional[Set[EntityDef]] = None) Iterator[EntityDef]

Yield all base entities for this one.

If an entity is repeated, it will only be yielded once.

serialise(file: IO[bytes], str_dict: BinStrDict) None

Write to the binary file.

static unserialise(
file: IO[bytes],
from_dict: Callable[[], str],
) EntityDef

Read from the binary file.

class srctools.fgd.KeyValues(
name: str,
type: ValueTypes,
disp_name: str,
default: str = '',
desc: str = '',
val_list: Union[None, List[Tuple[int, str, bool, FrozenSet[str]]], List[Tuple[str, str, FrozenSet[str]]]] = None,
readonly: bool = False,
reportable: bool = False,
)

Represents a generic keyvalue type.

If the type is choices or spawnflags, val_list is required: * For choices it’s a list of (value, name, tags) tuples. * For spawnflags it’s a list of (bitflag, name, default, tags) tuples.

property choices_list: List[Tuple[str, str, FrozenSet[str]]]

Check that the keyvalues are CHOICES type, and then return val_list.

This isolates the type ambiguity of the attr.

property flags_list: List[Tuple[int, str, bool, FrozenSet[str]]]

Check that the keyvalues are SPAWNFLAGS type, and then return val_list.

This isolates the type ambiguity of the attr.

copy() KeyValues

Create a duplicate of this keyvalue.

known_options() Iterator[str]

Use the default value and value list to determine values this can be set to.

export(
file: TextIO,
tags: Collection[str] = (),
) None

Write this back out to a FGD file.

serialise(file: IO[bytes], str_dict: BinStrDict) None

Write to the binary file.

static unserialise(
file: IO[bytes],
from_dict: Callable[[], str],
) KeyValues

Recover a KeyValue from a binary file.

class srctools.fgd.IODef(
name: str,
type: ValueTypes = ValueTypes.VOID,
desc: str = '',
)

Represents an input or output for an entity.

copy() IODef

Create a duplicate of this IODef.

export(
file: TextIO,
io_type: str,
tags: Collection[str] = (),
) None

Write this back out to a FGD file.

io_type should be “input” or “output”.

serialise(file: IO[bytes], dic: BinStrDict) None

Write to the binary file.

static unserialise(
file: IO[bytes],
from_dict: Callable[[], str],
) IODef

Recover an IODef from a binary file.

class srctools.fgd.Helper

Base class for representing helper() commands in the header of an entity.

These mainly add visual widgets in Hammer’s views for manipulating and previewing keyvalues.

This should not be instantiated, only subclasses in _fgd_helpers.

classmethod parse(args: List[str]) HelperT

Parse this helper from the given arguments.

The default implementation expects no arguments.

export() List[str]

Produce the argument text to recreate this helper type.

get_resources(entity: EntityDef) Iterable[str]

Return the resources used by this helper.

overrides() Collection[HelperTypes]

Specify which types can be overriden by this.

If any of these helper types are present before this type, they’re redundant and can be removed. For example size() is ignored if a studio() is present after it.

class srctools.fgd.UnknownHelper(name: str, args: List[str])

Represents an unknown helper.

export() List[str]

Produce the argument text to recreate this helper type.

class srctools.fgd.AutoVisgroup(
name: str,
parent: str,
ents: Set[str] = NOTHING,
)

Represents one of the autovisgroup options that can be set.

Due to how these are coded into Hammer, our representation is rather strange. We put all the groups into a single dictionary, and on each specify the name of the parent. Note they’re case-sensitive, and can include punctuation.

srctools.fgd.match_tags(
search: Container[str],
tags: Iterable[str],
) bool

Check if the search constraints satisfy tags.

The search tags should be uppercased.

All !tags or -tags cannot be present, all +tags must be present, and at lest one normal tag must be present (if they are) to pass.

srctools.fgd.validate_tags(
tags: ~typing.Collection[str], error: ~typing.Callable[[str], BaseException] = <class 'ValueError'>,
) FrozenSet[str]

Check these tags have valid values.

The error exception is raised if invalid.

class srctools.fgd.HelperBBox(bbox_min: Vec, bbox_max: Vec)

Helper implementation for bbox().

class srctools.fgd.HelperBoundingBox(min: str, max: str)

Displays bounding box between two keyvalues.

classmethod parse(args: List[str]) HelperBoundingBox

Parse wirebox(min, max)

export() List[str]

Produce the wirebox(min, max) arguments.

class srctools.fgd.HelperBreakableSurf

Specialized helper for func_breakable_surf.

class srctools.fgd.HelperBrushSides(key: str)

Highlights brush faces in a space-sepearated keyvalue.

class srctools.fgd.HelperCylinder(
r: float,
g: float,
b: float,
start_key: str,
start_value: str,
end_key: Optional[str] = None,
end_value: Optional[str] = None,
start_radius: Optional[str] = None,
end_radius: Optional[str] = None,
)

Helper implementation for cylinder().

Cylinder has the same sort of arguments as line(), plus radii for both positions.

classmethod parse(args: List[str]) HelperCylinder

Parse cylinder(r g b, start key/value/radius, end key/value/radius).

export() List[str]

Produce the correct line() arguments.

class srctools.fgd.HelperDecal

Specialized helper for infodecal.

class srctools.fgd.HelperEnvSprite(mat: Optional[str])

Variant of iconsprite() specifically for env_sprite.

class srctools.fgd.HelperFrustum(
fov: Union[str, float],
near_z: Union[str, float],
far_z: Union[str, float],
color: Union[str, Tuple[float, float, float]],
pitch_scale: Union[str, float],
)

Helper for env_projectedtexture visuals.

classmethod parse(args: List[str]) HelperFrustum

Parse frustum(fov, near, far, color, pitch_scale).

export() List[str]

Export back out frustrum() arguments.

class srctools.fgd.HelperHalfGridSnap

Helper implementation for halfgridsnap().

This causes the entity to snap to half a grid. This argument doesn’t use () in Valve’s files.

class srctools.fgd.HelperInherit

Helper implementation for base().

These specify the base classes for an entity def. This implementation isn’t used, the EntityDef special-cases it.

class srctools.fgd.HelperInstance

Specialized helper for func_instance.

class srctools.fgd.HelperLight

Specialized helper for omnidirectional lights.

class srctools.fgd.HelperLightSpot(
inner: str,
outer: str,
color: str,
pitch_scale: float,
)

Specialized helper for displaying spotlight previews.

classmethod parse(args: List[str]) HelperLightSpot

Parse lightcone(inner, outer, color, pitch_scale).

export() List[str]

Produce the arguments for lightcone().

class srctools.fgd.HelperLine(
r: float,
g: float,
b: float,
start_key: str,
start_value: str,
end_key: Optional[str] = None,
end_value: Optional[str] = None,
)

Helper implementation for line().

Line has the arguments line(r g b, start_key, start_value, end_key, end_value) It searches for the first entity where ent[start_key] == self[start_value]. If the second pair are present it does the same for those for the other line end.

classmethod parse(args: List[str]) HelperLine

Parse line(r g b, start_key, start_value, end_key, end_value).

export() List[str]

Produce the correct line() arguments.

class srctools.fgd.HelperModel(model: Optional[str])

Helper which displays models.

If the model is not provided, the ‘model’ key is used.

overrides() Collection[HelperTypes]

Avoid some issues where other helpers break this one.

classmethod parse(args: List[str]) ModelHelperT

Parse iconsprite(mat).

export() List[str]

Produce the arguments for iconsprite().

get_resources(entity: EntityDef) Iterable[str]

studio() uses a single model.

class srctools.fgd.HelperModelLight(model: Optional[str])

Special model helper, with inverted pitch.

class srctools.fgd.HelperModelProp(model: Optional[str])

Model helper which does not affect the bounding box.

class srctools.fgd.HelperOrientedBBox(min: str, max: str)

A bounding box oriented to angles.

class srctools.fgd.HelperOrigin(key: str)

Parse the origin() helper.

class srctools.fgd.HelperOverlay

Specialized helper for env_overlay.

class srctools.fgd.HelperOverlayTransition

Specialized helper for env_overlay_transition.

class srctools.fgd.HelperRenderColor(r: float, g: float, b: float)

Helper implementation for color().

overrides() Collection[HelperTypes]

Previous ones of these are overridden by this.

classmethod parse(args: List[str]) HelperRenderColor

Parse color(R G B).

export() List[str]

Produce color(R G B).

class srctools.fgd.HelperRope(name_kv: Optional[str])

Specialized helper for displaying move_rope and keyframe_rope.

classmethod parse(args: List[str]) HelperRope

Parse keyframe(name).

export() List[str]

Produce the arguments for keyframe().

class srctools.fgd.HelperSize(point1: Vec, point2: Vec)

Helper implementation for size().

This sets the bbox for the entity.

overrides() Collection[HelperTypes]

Additional versions of this are not available.

classmethod parse(args: List[str]) HelperSize

Parse size(x1 y1 z1, x2 y2 z2).

export() List[str]

Produce (x1 y1 z1, x2 y2 z2).

class srctools.fgd.HelperSphere(
r: float,
g: float,
b: float,
size_key: str,
)

Helper implementation for sphere().

classmethod parse(args: List[str]) HelperSphere

Parse sphere(radius, r g b).

export() List[str]

Export the helper.

class srctools.fgd.HelperSprite(mat: Optional[str])

The sprite helper, for editor icons.

If the material is not provided, the ‘model’ key is used.

overrides() Collection[HelperTypes]

Specify which types can be overriden by this.

If any of these helper types are present before this type, they’re redundant and can be removed. For example size() is ignored if a studio() is present after it.

classmethod parse(args: List[str]) SpriteHelperT

Parse iconsprite(mat).

export() List[str]

Produce the arguments for iconsprite().

get_resources(entity: EntityDef) Iterator[str]

iconsprite() uses a single material.

class srctools.fgd.HelperSweptPlayerHull

Draws the movement of a player-sized bounding box from A to B.

class srctools.fgd.HelperTrack

Specialized helper for path_track-style entities.

This no longer does anything.

class srctools.fgd.HelperVecLine(key: str)

A variant of line() which draws a line to the entity.

class srctools.fgd.HelperWorldText

Specialized helper for point_worldtext.

class srctools.fgd.HelperExtAppliesTo(tags: List[str] = NOTHING)

Allows specifying “tags” to indicate an entity is only used in certain games.

classmethod parse(args: List[str]) HelperExtAppliesTo

Parse this helper from the given arguments.

The default implementation expects no arguments.

export() List[str]

Produce the argument text to recreate this helper type.

class srctools.fgd.HelperExtAutoVisgroups(path: List[str] = NOTHING)

Convenience for parsing, adds @AutoVisgroups to entities.

‘Auto’ is implied at the start.

classmethod parse(args: List[str]) HelperExtAutoVisgroups

Parse this helper from the given arguments.

The default implementation expects no arguments.

export() List[str]

Produce the argument text to recreate this helper type.

class srctools.fgd.HelperExtOrderBy(order: List[str] = NOTHING)

Reorder keyvalues. Args = names in order.

classmethod parse(args: List[str]) HelperExtOrderBy

Parse this helper from the given arguments.

The default implementation expects no arguments.

export() List[str]

Produce the argument text to recreate this helper type.