Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

NIF / Havok format

Implemented in CreationEngineFormats/Nif/. There is no official NIF specification; the reference is niftools’ nif.xml, the description NifSkope is built from. Layouts below are for version 20.2.0.7, BS version 100 (Skyrim Special Edition).

The parser covers what a map needs from a model: the positions, normals, UVs and triangles of its BSTriShape blocks placed in the model’s space, the diffuse texture of each shape and how it is mapped, its alpha test, the vertex colors a shader tints it with, and the Havok collision a footprint is built from. It reads no materials, particles or animation: a skinned shape is posed by its bones as the file stores them. debug:dump:plugin:interior-collision-shapes measures which collision shapes resolve in practice. Truncated or inconsistent data makes NifReader.Parse, TriShapeReader and NifSceneReader throw InvalidDataException; the other block readers return false.

NifReader, nif.xml Header and BSStreamHeader.

FieldTypeCondition
Header stringASCII, ends with \n
Versionuint32
Endian typeuint8
User versionuint32
Block countuint32
BS versionuint32
AuthorExportString
Unknown intuint32BS version > 130
Process scriptExportStringBS version < 131
Export scriptExportString
Max filepathExportStringBS version >= 103
Block type count, block typesuint16, SizedString[]
Block type indexuint16[block count]
Block sizeuint32[block count]
String count, max length, stringsuint32, uint32, SizedString[]
Group count, groupsuint32, uint32[]

A SizedString is a uint32 length and the characters. An ExportString is a byte length, counting a null terminator, and the characters. Blocks follow the header back to back, so NifDocument locates block i from the sizes without parsing the blocks before it.

Blocks

BlockFields readReader
NiNode and subtypesName (string index), extra data refs (skipped), controller, flags (uint32), translation, rotation (row-major 3x3), scale, collision object ref, children refsNiNodeReader
bhkCollisionObjectTarget (skipped), flags (uint16), body refCollisionObjectReader
bhkRigidBody, bhkRigidBodyTShape ref, the first fieldCollisionObjectReader
BSShaderTextureSetint32 count, SizedString textures; slot 0 is the diffuse map, slot 1 the normal map, slot 2 the glow map of a Glow shaderShaderTextureSetReader
BSTriShapeSee BSTriShapeTriShapeReader
BSLightingShaderPropertyShader type (uint32, before the name), NiObjectNET, two uint32 flags (flag 1 bit 12 Model_Space_Normals, bits 26 and 27 Decal and Dynamic_Decal, flag 2 bit 5 Vertex_Colors), UV offset and scale (2 floats each), texture set ref, emissive color and multiple (4 floats), texture clamp mode (uint32), alpha (float)ShaderPropertyReader
NiAlphaPropertyNiObjectNET, flags (uint16), threshold (uint8)AlphaPropertyReader
BSEffectShaderPropertyNiObjectNET, two uint32 flags (flag 1 bits 3 to 6 Vertex_Alpha, Greyscale_To_PaletteColor, Greyscale_To_PaletteAlpha, Use_Falloff, bit 30 Soft_Effect; flag 2 bit 5 Vertex_Colors), UV offset and scale, source texture (SizedString), texture clamp mode (uint8), three bytes skipped, falloff start and stop angles and opacities (4 floats), base color (Color4), base color scale (float), soft falloff depth (float), greyscale texture (SizedString)ShaderPropertyReader
BSWaterShaderPropertyNiObjectNET, two uint32 flags, UV offset and scale, water shader flags (uint32); only its block type is used: it marks a water surfaceNifSceneShape.ShaderType

NiNodeReader accepts NiNode, BSFadeNode, BSLeafAnimNode, BSMultiBoundNode, BSOrderedNode and BSTreeNode: they share NiNode’s layout up to the children list. BSFadeNode is the usual root of static meshes.

The rotation of a NiAVObject is nine floats. The code reads them as a row-major matrix and applies it to column vectors; nif.xml calls the storage column-major without saying how a point is multiplied. See Spec deviations.

BSTriShape

TriShapeReader, nif.xml BSTriShape and BSVertexDataSSE. The layout is read for BS version 100 only: Fallout 4 (130) widens the triangle count to uint32.

FieldTypeRead
NiObjectNET, NiAVObjectAs for NiNodeName, local transform
Bounding sphereCenter (Vector3), radius (float)Skipped
SkinRefYes, see Skinned shapes
Shader propertyRefYes
Alpha propertyRefYes
Vertex descuint64 bitfieldVertex size, UV, normal, tangent and color offsets, attributes
Triangle countuint16Yes
Vertex countuint16Yes
Data sizeuint32Checked against the counts
Vertex dataVertex count × vertex size bytesPositions, UVs, normals, tangents, bitangents, colors
TrianglesTriangle count × three uint16Yes

Vertex data and triangles are present only when the data size is above 0. A skinned shape stores its geometry in its NiSkinPartition instead, see Skinned shapes.

The vertex desc (nif.xml BSVertexDesc) gives the vertex size, the offsets of the UVs, normal, tangent, colors and skinning data, and the attribute flags; its offsets count in units of 4 bytes, see assumptions. The reader takes the position (always full precision in SSE, so Full_Precision is ignored), the HalfTexCoord UVs (v grows down the texture’s rows), the ByteColor4 vertex colors and the bone weights and indices. An offset that leaves no room for its field in the vertex throws.

The tangent frame follows each field’s condition in BSVertexDataSSE:

FieldWhereRead when
NormalThree normbytes at the normal offsetNormals
Bitangent YThe normbyte after the normalNormals
TangentThree normbytes at the tangent offsetVertex, Normals and Tangents
Bitangent ZThe normbyte after the tangentVertex, Normals and Tangents
Bitangent XThe float after the positionVertex, Normals and Tangents

A normbyte maps 0 to 255 onto -1 to 1, see assumptions. NifSceneShape.Normals turns the normals into the model’s space by the shape’s model transform, without its scale, and brings them back to unit length; Tangents and Bitangents are turned the same way.

A shape takes its vertex colors only when its shader property also sets Vertex_Colors, bit 5 of its second flags (NifSceneShape.VertexColors): the vertex desc says the colors are stored, the shader that it multiplies its color by them. Without a shader, or with a truncated one, the shape is untinted.

The data size must equal vertex size × vertex count + 6 × triangle count, and every triangle index must be below the vertex count; otherwise the reader throws.

A shape’s diffuse texture comes from its shader property: slot 0 of the BSShaderTextureSet a BSLightingShaderProperty points at, or the source texture of a BSEffectShaderProperty. Other shader types (sky, water) have none. A lighting shader also gives its normal map, slot 1 (NormalTexturePath), and whether it sets Model_Space_Normals (ModelSpaceNormals): the map then holds normals in the model’s space instead of the vertices’ tangent space. It gives what the shape emits (Emissive), with on a Glow shader its glow map, slot 2 (GlowTexturePath), and whether it is a decal (Decal). A texture set with fewer slots, an empty slot or a truncated one gives no path. The scene also gives each shape the block type of its shader property (ShaderType), so a reader can tell an effect from a lit surface.

A lighting or effect shader also gives the shape its TextureMapping: a texture coordinate is uv × UV Scale + UV Offset, then wrapped or clamped along u (S) and v (T) by the clamp mode (TexClampMode: 0 clamps both, 1 clamps S and wraps T, 2 wraps S and clamps T, 3 wraps both; a byte in an effect shader). An effect shader also gives the shape its material (NifSceneShape.Effect), the fields after its source texture. Any other shader, or a truncated block, gives the nif.xml defaults: no offset, a scale of 1, wrapped both ways.

The shape’s NiAlphaProperty gives its alpha test (test function and threshold) and its blending (source and destination AlphaFunction), with nif.xml’s flag layout. A missing or truncated block gives no alpha property.

A shape also takes its lighting shader’s material opacity, the Alpha float after Texture Clamp Mode (NifSceneShape.MaterialAlpha, 1 for any other shader or a truncated one), and its vertex alphas when the vertex desc stores colors and its shader sets Vertex_Alpha, bit 3 of its first flags (NifSceneShape.VertexAlphas), whatever Vertex_Colors says. How a map uses them is in Blending.

Skinned shapes

SkinReader, nif.xml NiSkinInstance, NiSkinData, NiSkinPartition and SkinPartition. A BSTriShape whose skin ref points at a NiSkinInstance or a BSDismemberSkinInstance has a data size of 0 and takes its geometry from the skin:

BlockFieldRead
NiSkinInstanceData, skin partitionRefs, checked against their block type
NiSkinInstanceSkeleton rootSkipped
NiSkinInstanceBonesNode refs
NiSkinDataSkin transformSkipped
NiSkinDataBone listEach bone’s skin transform; bounding sphere and weights skipped
NiSkinPartitionVertex desc, vertex dataAs for BSTriShape, bone weights and indices included
SkinPartitionTriangles copyIndices into the vertex data; every other field skipped

A skin data with fewer bones than its instance, a vertex data size that isn’t a whole number of vertices, a bone index past the bones, a triangle past the vertices or a bone that isn’t a node under the root throws.

NifSceneReader poses each vertex: every bone with a weight above 0 moves it by its skin transform, then by the bone node’s transform in the model’s space, and the results are blended by the weights. The bone index of a vertex points into the instance’s bones. The pose is the one the file stores the bone nodes in; the game’s tree animations aren’t played. The shape’s own transform and the skin data’s overall transform aren’t applied to a weighted vertex. See Spec deviations. The same bones and weights turn the vertex normals, tangents and bitangents, by the rotation of each, before they’re brought back to unit length. Most vanilla trees are skinned, so their crowns keep their normals this way.

Scene graph

NifSceneReader walks the graph depth-first from block 0:

  • A node of a type NiNodeReader supports composes its transform with its parent’s and visits its children. A null child ref (-1) is skipped; a ref past the block table throws.
  • A NiSwitchNode visits only the child at its Index, read after the NiNode effects, and none when Index is past its children. See Spec deviations.
  • A BSTriShape is read with TriShapeReader. Its model transform is every node’s transform from the root down, then its own. The root’s transform is included. A skinned shape’s positions, normals, tangents and bitangents are posed in the model’s space instead, under an identity model transform.
  • A node or shape named EditorMarker is left out with its subtree: it holds geometry the editor shows and the game doesn’t. See Spec deviations.
  • A node or shape whose NiAVObject flags set bit 0, hidden, is left out with its subtree. In vanilla, those are particle emitter meshes, forge markers and the spare parts of some weapons and tools. See Spec deviations.
  • Any other child type is skipped and reported once in SkippedBlockTypes: NiTriShape, NiTriStrips, BSLODTriShape, BSDynamicTriShape, particle systems, and nodes whose children aren’t all drawn as is, such as NiBillboardNode (turned to the camera).
  • A child ref back to a node on the current path is not followed, so a malformed cycle ends.

A transform is a rotation, a translation and a uniform scale, applied as rotation × (point × scale) + translation. Two compose into one transform of the same form.

Havok shapes

HavokShapeReader. All Havok lengths are scaled by 69.9915 to game units, see Spec deviations.

ShapeLayout readFootprint
bhkBoxShapeHalf extents (Vector3) at offset 168 corners
bhkSphereShapeRadius at offset 48-point circle
bhkCapsuleShapeAt offset 16: point 1, radius 1, point 2, radius 2Two circles
bhkConvexVerticesShapeAt offset 32: uint32 count, Vector4 verticesThe vertices
bhkConvexTransformShapeShape ref, then a 4x4 matrix at offset 20Wrapped shape, transformed
bhkListShapeuint32 count, shape refsUnion of the resolvable sub-shapes
bhkMoppBvTreeShapeShape ref, the first field; the MOPP code is skippedWrapped shape
bhkPackedNiTriStripsShapeData ref at offset 52See hkPackedNiTriStripsData
hkPackedNiTriStripsDataTriangles (8 bytes each, skipped), uint32 vertex count, compressed flag, Vector3 or half-float verticesThe vertices
bhkCompressedMeshShapeData ref at offset 52See bhkCompressedMeshShapeData
bhkCompressedMeshShapeDataSee belowBig vertices and chunk vertices

Shapes reached through bhkMoppBvTreeShape are static room geometry and flagged IsArchitecture.

bhkCompressedMeshShapeData starts with 54 bytes of bit counts, masks, AABB and type bytes, then four counted material arrays and a named material count, all skipped. Then:

FieldLayout
Chunk transformsuint32 count, then per transform: translation (Vector4), rotation (hkQuaternion, x y z w)
Big verticesuint32 count, Vector4 each, full precision
Big trianglesuint32 count, 12 bytes each, skipped
Chunksuint32 count, then per chunk: translation (Vector4), material index, reference, transform index (uint16), uint32 vertex component count (3 per vertex), uint16 vertices in Havok units × 1000, then indices, strips and welding info, each a counted uint16 array

A chunk vertex is rotation(chunkTranslation + vertex / 1000) + transformTranslation. That order is unverified.

Findings from real data

  • Top groups aren’t all flat: DIAL has nested topic children, so the base object lookup skips nested groups.
  • bhkMoppBvTreeShape wraps bhkCompressedMeshShape in vanilla interiors, not bhkPackedNiTriStripsShape: most placed interior objects resolve through it.
  • NifSceneReader reads every NIF of the Anniversary Edition archives plus the Moon and Star and Vominheim mods without an error. A few are Skyrim LE (BS version 82 or 83), whose NiTriShape geometry the walk skips.
  • EditorMarker is always spelled that way.