18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-02 09:36:48 +01:00
Files
maszyna/model/eu07m/eu07m_load.cpp
T
maj00r 89405a6eaf feat(render): the geometry of the scenery models and the data of the textures streamed, on by default
The streaming of the geometry of EU07M models (modelstreaming) and the streaming of the textures (gfx.textures.streaming) are now
both on by default; either is turned off in eu07.ini with "no", and turned off the game does what it did before.

Geometry (modelstreaming yes, with modelformat eu07m):
- A scenery model (node ... model) of an .eu07m file of at least modelstreaming.minsize KiB (256), without skins, stars and texts of
  E3D and with BNDS, has only its structure read at the load: one read of the beginning of the file (eu07m::read_file() with
  read_options::streams false, validate_scope::structure). Vehicles, cabs, loads and every other model load whole, as before; a
  streamed model asked for by anything else gets its geometry loaded and kept (TModelsManager::GetModel(..., Streamable)).
- Its geometry bank keeps its chunks empty (gfx::residency). A bank without its data draws nothing and is asked of the streamer
  (rendering/geometrystreamer.h): threads read and unpack the streams and the GREF blocks, nearest first, and the main thread hands
  them to the banks, 64 MB or 3 ms a frame. A bank unused for modelstreaming.evictafter s (30) lets go of its data in memory and on
  the GPU; above modelstreaming.budget MB (0, no limit) sooner. Whatever reads the vertices (picking, editor, sky occlusion) gets
  them loaded at once. The walks kept by the GPU culling are made anew when a bank got its data.
- The nodes, materials, components, clips and channels stay loaded: the walk goes through an instance without its geometry as
  through any other (RaAnimate(), RaPrepare()), only its draws are left out, so animations, lights and the events at their ends
  keep their timing. The radius of a streamed model and the bounds of its branches come from BNDS instead of the vertices.
- rendering/common/modelprefetch.h goes through the cells within the draw range and 500 m, 32 a frame, and asks for the geometry
  of the streamed models ahead of their drawing.

Textures (gfx.textures.streaming yes):
- The same pass has the data of the textures of the instances, shapes and tracks in reach read ahead by the texture workers in the
  Vulkan renderer (the OpenGL renderer has its own pass); the read-ahead data not drawn for 5 minutes or left behind is dropped.
- The loading screen waits, two minutes at most, for the geometry and the textures around the start and, in Vulkan, for their
  images made on the GPU (vulkan14_texture::request_background(false), made()).

Measured on Tomaszewo, Vulkan, editor self-test flight start to Kaletnik, four runs on an idle machine, alternated:
- peak committed memory 11.0 GB without streaming, 7.0 GB with textures, 6.2 GB with both; working set 9.0 / 4.8 / 4.2 GB
  (the copies of the texture data were 4.5 GB, the geometry banks 1.55 GB);
- scenario load 104-145 s without, 95-97 s with;
- frame time over the flight the same (11.8-12.5 ms), draws without their texture at the start the same as without streaming and
  fewer in the flight (380 against 636); the prefetch costs the main thread 0.1-0.2 ms a frame.

Also: the self-test commands "modelstream evict|wait|stats" and "memory <label>" (rendering/common/memoryreport.h, a breakdown of
the memory of the process), file_parts (utilities/wholefile.h) for reads of parts of a file, and the docs in docs/eu07m-format.md
("Streaming of the geometry"). The format doesn't change and no asset change is needed. Unit tests: test_eu07m_streaming.cpp.
2026-11-29 20:39:47 +01:00

729 lines
32 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "model/Model3d.h"
#include "model/eu07m/eu07m_build.h"
#include "model/eu07m/eu07m_geometry.h"
#include "model/eu07m/eu07m_io.h"
#include "rendering/renderer.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/utilities.h"
#include "utilities/wholefile.h"
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <algorithm>
#include <atomic>
#include <filesystem>
#include <format>
#include <cstring>
#include <exception>
#include <functional>
#include <mutex>
#include <optional>
#include <span>
#include <thread>
// the loading of an EU07M model into the tree of submodels the rest of the game works with: each node becomes a submodel, with
// what E3D keeps in the submodel taken from the node, its material, its primitive and its components. the result is what
// TModel3d::LoadFromBinFile() makes of the E3D the model was converted from
namespace {
// the vertex streams of the file are the compact layout of the renderer, byte for byte
static_assert(sizeof(eu07m::position) == sizeof(glm::vec3));
static_assert(sizeof(eu07m::attributes) == sizeof(gfx::compact_attributes));
static_assert(offsetof(eu07m::attributes, qtangent) == offsetof(gfx::compact_attributes, qtangent));
static_assert(offsetof(eu07m::attributes, uv) == offsetof(gfx::compact_attributes, texture));
// what E3D keeps in the submodel and EU07M in the components of the node
struct legacy_parts {
std::optional<eu07m::payload::light> light;
std::uint32_t material{eu07m::no_index}; // of a node without geometry
TAnimType animation{TAnimType::at_None};
bool text{false};
std::span<std::byte const> stars; // the packed colours, one for each vertex of the mesh
};
legacy_parts parts_of(eu07m::model const &Model, eu07m::node_record const &Node) {
legacy_parts parts;
for (auto idx = Node.component_first; idx < Node.component_first + Node.component_count; ++idx) {
auto const type{Model.components[idx].type};
auto const data{Model.component_payload(idx)};
eu07m::payload_reader reader{data};
if (type == eu07m::component::light) {
if (eu07m::payload::light light; reader.get(light))
parts.light = light;
}
else if (type == eu07m::component::legacy_animation) {
if (eu07m::payload::legacy_animation animation; reader.get(animation))
parts.animation = static_cast<TAnimType>(animation.type);
}
else if (type == eu07m::component::legacy_text)
parts.text = true;
else if (type == eu07m::component::legacy_material) {
if (eu07m::payload::legacy_material material; reader.get(material))
parts.material = material.material;
}
else if (type == eu07m::component::legacy_stars && data.size() >= sizeof(eu07m::payload::legacy_stars))
parts.stars = data.subspan(sizeof(eu07m::payload::legacy_stars));
}
return parts;
}
glm::vec3 unpack_colour(std::span<std::byte const> const Colours, std::size_t const Index) {
std::uint32_t packed{0};
if ((Index + 1) * sizeof(packed) <= Colours.size())
std::memcpy(&packed, Colours.data() + Index * sizeof(packed), sizeof(packed));
return glm::vec3{static_cast<float>(packed & 0xFF), static_cast<float>((packed >> 8) & 0xFF), static_cast<float>((packed >> 16) & 0xFF)} / 255.f;
}
glm::vec4 to_vec4(std::array<float, 4> const &Value) {
return {Value[0], Value[1], Value[2], Value[3]};
}
// the vertices and the indices of a submodel, filled once the submodels are set up
struct geometry_job {
eu07m::primitive_record const *primitive{nullptr};
std::span<std::byte const> stars;
TSubModel *submodel{nullptr};
};
// a model with fewer vertices fills its submodels on the thread which loads it: starting threads would cost more
constexpr std::size_t parallel_vertex_threshold{100'000};
constexpr unsigned parallel_thread_limit{8};
// fills the submodels from the nodes of the model
class submodel_builder {
public:
submodel_builder(eu07m::model const &Model, std::vector<std::string> &Textures, std::vector<std::string> &Names, std::vector<float4x4> &Matrices)
: m_model(Model), m_textures(Textures), m_names(Names), m_matrices(Matrices), m_transforms(eu07m::local_transforms(Model)) {
// texture 0 is "none" in the submodels
m_textures.emplace_back();
}
void build(std::uint32_t Index, TSubModel &Submodel);
// the vertices and the indices of all the submodels, on several threads for a big model
void fill_geometry();
private:
void links(std::uint32_t Index, TSubModel &Submodel) const;
void transform(std::uint32_t Index, TSubModel &Submodel);
void material(std::uint32_t Material, TSubModel &Submodel);
static void light(eu07m::payload::light const &Light, TSubModel &Submodel);
void geometry(eu07m::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel);
void fill(geometry_job const &Job) const;
void indices(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const;
void skinned(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const;
int texture(std::string_view Name);
eu07m::model const &m_model;
std::vector<std::string> &m_textures;
std::vector<std::string> &m_names;
std::vector<float4x4> &m_matrices;
std::vector<glm::mat4> m_transforms;
std::vector<geometry_job> m_jobs;
int m_vertexoffset{0};
int m_indexoffset{0};
public:
int vertex_count{0};
int index_count{0};
};
void submodel_builder::build(std::uint32_t const Index, TSubModel &Submodel) {
auto const &node{m_model.nodes[Index]};
links(Index, Submodel);
if (node.name != eu07m::no_index) {
Submodel.iName = static_cast<int>(m_names.size());
m_names.emplace_back(m_model.string(node.name));
}
Submodel.iFlags = node.legacy_flags;
Submodel.fSquareMinDist = node.range_min_sq;
// 0 is no limit (a model made anew); a converted one carries the range of its E3D submodel. the submodel keeps its default
Submodel.fSquareMaxDist = node.range_max_sq > 0.f ? node.range_max_sq : Submodel.fSquareMaxDist;
transform(Index, Submodel);
// a model made anew has no E3D flags (legacy_flags 0): a node of it with a transform keeps it as one converted from E3D does
// (0x8000), or the walk and posed_transform() would leave it out, and with it the joints of the skins
if ((node.legacy_flags == 0) && (Submodel.iMatrix >= 0) && (m_transforms[Index] != glm::mat4{1.f}))
Submodel.iFlags |= 0x8000;
auto const parts{parts_of(m_model, node)};
Submodel.b_Anim = parts.animation;
Submodel.eType = TP_ROTATOR;
material(parts.material, Submodel);
if (parts.text)
Submodel.eType = TP_TEXT;
if (parts.light) {
Submodel.eType = TP_FREESPOTLIGHT;
light(*parts.light, Submodel);
}
if (node.mesh >= 0) {
auto const &mesh{m_model.meshes[node.mesh]};
if (mesh.primitive_count > 0)
geometry(m_model.primitives[mesh.primitive_first], parts, Submodel);
}
// as in E3D the rotations of the text model were done when it was made
Submodel.m_rotation_init_done = true;
}
// the submodels lie in the order of the nodes: the first child follows its parent, the next sibling follows the subtree
void submodel_builder::links(std::uint32_t const Index, TSubModel &Submodel) const {
auto const &node{m_model.nodes[Index]};
auto const count{static_cast<std::uint32_t>(m_model.nodes.size())};
Submodel.iChild = (Index + 1 < node.subtree_end) ? static_cast<int>(Index + 1) : 0;
auto const next{node.subtree_end};
Submodel.iNext = (next < count && m_model.nodes[next].parent == node.parent) ? static_cast<int>(next) : 0;
}
void submodel_builder::transform(std::uint32_t const Index, TSubModel &Submodel) {
if ((m_model.nodes[Index].flags & eu07m::node_flags::no_transform) != 0) {
Submodel.iMatrix = -1;
return;
}
Submodel.iMatrix = static_cast<int>(m_matrices.size());
m_matrices.emplace_back(glm::value_ptr(m_transforms[Index]));
}
int submodel_builder::texture(std::string_view const Name) {
if (auto const found{std::ranges::find(m_textures, Name)}; found != m_textures.end())
return static_cast<int>(std::distance(m_textures.begin(), found));
m_textures.emplace_back(Name);
return static_cast<int>(m_textures.size() - 1);
}
void submodel_builder::material(std::uint32_t const Material, TSubModel &Submodel) {
if (Material >= m_model.materials.size())
return;
auto const &material{m_model.materials[Material]};
if (material.replaceable != 0)
Submodel.iTexture = material.replaceable;
else if (material.name != eu07m::no_index)
Submodel.iTexture = texture(m_model.string(material.name));
Submodel.fLight = material.selfillum;
Submodel.f4Ambient = to_vec4(material.ambient);
Submodel.f4Diffuse = to_vec4(material.diffuse);
Submodel.f4Specular = to_vec4(material.specular);
Submodel.f4Emision = to_vec4(material.emission);
}
void submodel_builder::light(eu07m::payload::light const &Light, TSubModel &Submodel) {
namespace light_flags = eu07m::payload::light_flags;
Submodel.f4Diffuse = to_vec4(Light.color);
Submodel.fHotspotPower = Light.hotspot_power;
Submodel.fLightRadius = Light.radius;
Submodel.fNearAttenStart = Light.near_start;
Submodel.fNearAttenEnd = Light.near_end;
Submodel.iFarAttenDecay = Light.far_decay;
Submodel.fFarDecayRadius = Light.far_radius;
Submodel.fCosFalloffAngle = Light.cos_falloff;
Submodel.fCosHotspotAngle = Light.cos_hotspot;
Submodel.bShadeSelf = (Light.flags & light_flags::shade_self) != 0;
Submodel.bCastShadows = (Light.flags & light_flags::no_shadows) == 0;
Submodel.bSoftFalloff = (Light.flags & light_flags::soft_falloff) != 0;
Submodel.bLightOnly = (Light.flags & light_flags::light_only) != 0;
Submodel.bUseNearAtten = (Light.flags & light_flags::near_attenuation) != 0;
}
// what the submodel knows of its geometry; the vertices and the indices come later, in fill_geometry()
void submodel_builder::geometry(eu07m::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel) {
Submodel.eType = Parts.stars.empty() ? static_cast<int>(Primitive.flags & eu07m::primitive_flags::topology_mask) : TP_STARS;
material(Primitive.material, Submodel);
auto const indexed{(Primitive.flags & eu07m::primitive_flags::indexed) != 0};
Submodel.m_geometry.vertex_count = static_cast<int>(Primitive.vertex_count);
Submodel.m_geometry.vertex_offset = m_vertexoffset;
Submodel.m_geometry.index_count = indexed ? static_cast<int>(Primitive.index_count) : 0;
Submodel.m_geometry.index_offset = m_indexoffset;
m_vertexoffset += Submodel.m_geometry.vertex_count;
m_indexoffset += Submodel.m_geometry.index_count;
vertex_count += Submodel.m_geometry.vertex_count;
index_count += Submodel.m_geometry.index_count;
m_jobs.push_back({&Primitive, Parts.stars, &Submodel});
}
void submodel_builder::fill(geometry_job const &Job) const {
auto const &primitive{*Job.primitive};
auto &submodel{*Job.submodel};
auto const stars{false == Job.stars.empty()};
auto const userdata{m_model.vertex_userdata.size() == m_model.vertex_count()};
if (userdata) {
submodel.Userdata.clear();
submodel.Userdata.reserve(primitive.vertex_count);
for (auto const &data : std::span{m_model.vertex_userdata}.subspan(primitive.base_vertex, primitive.vertex_count))
submodel.Userdata.push_back({glm::vec4{data[0], data[1], data[2], data[3]}});
}
indices(primitive, submodel);
if (false == stars) {
// the streams of the file are the compact layout of the renderer: copied as they are (Insert_Compact())
submodel.CompactPositions.resize(primitive.vertex_count);
submodel.CompactAttributes.resize(primitive.vertex_count);
std::memcpy(submodel.CompactPositions.data(), m_model.positions.data() + primitive.base_vertex, primitive.vertex_count * sizeof(glm::vec3));
std::memcpy(submodel.CompactAttributes.data(), m_model.vertex_attributes.data() + primitive.base_vertex, primitive.vertex_count * sizeof(gfx::compact_attributes));
if (primitive.skin >= 0)
skinned(primitive, submodel);
return;
}
// the stars keep their colours in the normals of basic_vertex. each vertex is written once: reserved and appended, without the
// zeroes resize() would write first
submodel.Vertices.clear();
submodel.Vertices.reserve(primitive.vertex_count);
for (std::uint32_t idx = 0; idx < primitive.vertex_count; ++idx) {
auto const source{std::size_t{primitive.base_vertex} + idx};
auto const &position{m_model.positions[source]};
auto const &attribute{m_model.vertex_attributes[source]};
auto const frame{eu07m::decode_qtangent(attribute.qtangent)};
gfx::basic_vertex vertex;
vertex.position = {position[0], position[1], position[2]};
vertex.normal = unpack_colour(Job.stars, idx);
vertex.tangent = glm::vec4{frame.tangent, frame.handedness};
vertex.texture = {attribute.uv[0], attribute.uv[1]};
submodel.Vertices.push_back(vertex);
}
}
void submodel_builder::indices(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const {
if ((Primitive.flags & eu07m::primitive_flags::indexed) == 0)
return;
if ((Primitive.flags & eu07m::primitive_flags::index32) != 0) {
auto const source{std::span{m_model.indices32}.subspan(Primitive.first_index, Primitive.index_count)};
Submodel.Indices.assign(source.begin(), source.end());
}
else {
auto const source{std::span{m_model.indices16}.subspan(Primitive.first_index, Primitive.index_count)};
Submodel.Indices.assign(source.begin(), source.end());
}
}
// the bind pose and the weights of a skinned primitive, which the renderer moves by the joints of each instance. the bind pose goes to the
// renderer as well (Insert_Compact()), drawn as long as the joints stay in it
void submodel_builder::skinned(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const {
auto skin{std::make_shared<skinning::skinned_geometry>()};
skin->skin = Primitive.skin;
skin->indices = Submodel.Indices;
skin->rest.reserve(Primitive.vertex_count);
skin->weights.reserve(Primitive.vertex_count);
auto const wide{m_model.weights.size() != m_model.vertex_count()};
for (std::uint32_t idx = 0; idx < Primitive.vertex_count; ++idx) {
auto const source{std::size_t{Primitive.base_vertex} + idx};
auto const &position{m_model.positions[source]};
auto const &attribute{m_model.vertex_attributes[source]};
auto const frame{eu07m::decode_qtangent(attribute.qtangent)};
gfx::basic_vertex vertex;
vertex.position = {position[0], position[1], position[2]};
vertex.normal = frame.normal;
vertex.tangent = glm::vec4{frame.tangent, frame.handedness};
vertex.texture = {attribute.uv[0], attribute.uv[1]};
skin->rest.push_back(vertex);
if (wide) {
auto const &weights{m_model.weights_wide[source]};
skin->weights.push_back(skinning::unpack(weights.joints, weights.weights));
}
else {
auto const &weights{m_model.weights[source]};
std::array<std::uint16_t, 4> const joints{weights.joints[0], weights.joints[1], weights.joints[2], weights.joints[3]};
skin->weights.push_back(skinning::unpack(joints, weights.weights));
}
}
Submodel.m_skin = std::move(skin);
}
void submodel_builder::fill_geometry() {
auto const threads{static_cast<std::size_t>(vertex_count) < parallel_vertex_threshold ? 1u : std::clamp(std::thread::hardware_concurrency(), 1u, parallel_thread_limit)};
if (threads <= 1 || m_jobs.size() <= 1) {
for (auto const &job : m_jobs)
fill(job);
return;
}
// the biggest first, so the threads end at about the same time
std::ranges::sort(m_jobs, std::ranges::greater{}, [](geometry_job const &Job) { return Job.primitive->vertex_count; });
std::atomic<std::size_t> next{0};
// the first exception of a worker (no memory for the vertices) is thrown again here, after all of them ended: left in a
// thread of its own it would end the program instead of the model falling back to its .e3d
std::exception_ptr failure;
std::mutex failurelock;
auto const work{[this, &next, &failure, &failurelock] {
try {
while (true) {
auto const index{next.fetch_add(1)};
if (index >= m_jobs.size())
break;
fill(m_jobs[index]);
}
}
catch (...) {
std::scoped_lock lock{failurelock};
if (failure == nullptr)
failure = std::current_exception();
next = m_jobs.size();
}
}};
{
std::vector<std::jthread> workers;
workers.reserve(threads - 1);
for (unsigned idx = 1; idx < threads; ++idx)
workers.emplace_back(work);
work();
} // the workers join here
if (failure != nullptr)
std::rethrow_exception(failure);
}
// the track of the file as the game samples it: the rotations unpacked, the vectors as glm
animation::track make_track(eu07m::model const &Model, eu07m::track_record const &Record) {
animation::track track;
track.target = static_cast<animation::part>(Record.path);
track.interpolation = static_cast<animation::curve>(Record.interpolation);
auto const times{std::span{Model.key_times}.subspan(Record.time_first, Record.key_count)};
track.times.assign(times.begin(), times.end());
if (Record.path == eu07m::track_path::rotation) {
for (auto const &packed : std::span{Model.key_rotations}.subspan(Record.value_first, Record.key_count)) {
auto const value{eu07m::decode_rotation(packed)};
track.rotations.emplace_back(value[3], value[0], value[1], value[2]);
}
return track;
}
auto const count{std::size_t{Record.key_count} * (Record.interpolation == eu07m::track_interpolation::cubic ? 3u : 1u)};
for (auto const &value : std::span{Model.key_vectors}.subspan(Record.value_first, count))
track.vectors.emplace_back(value[0], value[1], value[2]);
return track;
}
// the tracks of the clip gathered by node, with the TRS of the node for the parts without one
animation::node_tracks &node_entry(animation::clip &Clip, eu07m::model const &Model, std::uint32_t const Node) {
if (auto const found{std::ranges::find(Clip.nodes, static_cast<int>(Node), &animation::node_tracks::node)}; found != Clip.nodes.end())
return *found;
auto const &record{Model.nodes[Node]};
animation::node_tracks entry;
entry.node = static_cast<int>(Node);
entry.rest_translation = {record.translation[0], record.translation[1], record.translation[2]};
entry.rest_rotation = glm::quat{record.rotation[3], record.rotation[0], record.rotation[1], record.rotation[2]};
entry.rest_scale = {record.scale[0], record.scale[1], record.scale[2]};
if ((record.flags & eu07m::node_flags::matrix) != 0) {
// the TRS fields of a node with a matrix (XFRM) are only an approximation of it: the parts the tracks leave are taken from
// the matrix itself, so the node doesn't jump when a clip starts moving one of its parts
auto const matrix{eu07m::local_transform(Model, Node)};
glm::vec3 scale{glm::length(glm::vec3{matrix[0]}), glm::length(glm::vec3{matrix[1]}), glm::length(glm::vec3{matrix[2]})};
if (glm::determinant(glm::mat3{matrix}) < 0.f)
scale.x = -scale.x; // a mirroring matrix: the rotation stays a proper one
if ((scale.x != 0.f) && (scale.y != 0.f) && (scale.z != 0.f)) {
glm::mat3 const rotation{glm::vec3{matrix[0]} / scale.x, glm::vec3{matrix[1]} / scale.y, glm::vec3{matrix[2]} / scale.z};
entry.rest_translation = glm::vec3{matrix[3]};
entry.rest_rotation = glm::normalize(glm::quat_cast(rotation));
entry.rest_scale = scale;
}
}
return Clip.nodes.emplace_back(entry);
}
animation::clip make_clip(eu07m::model const &Model, eu07m::clip_record const &Record) {
animation::clip clip;
clip.name = Model.string(Record.name);
clip.duration = Record.duration;
clip.loop = (Record.flags & eu07m::clip_flags::loop) != 0;
clip.autoplay = (Record.flags & eu07m::clip_flags::autoplay) != 0;
for (auto const &record : std::span{Model.clip_tracks}.subspan(Record.track_first, Record.track_count)) {
auto const index{static_cast<int>(clip.tracks.size())};
clip.tracks.push_back(make_track(Model, record));
auto &node{node_entry(clip, Model, record.node)};
switch (record.path) {
case eu07m::track_path::translation: node.translation = index; break;
case eu07m::track_path::rotation: node.rotation = index; break;
case eu07m::track_path::scale: node.scale = index; break;
}
}
return clip;
}
// the joint of a JOIN component of a node, moving the node from its own transform
std::optional<animation::joint_binding> make_joint(eu07m::model const &Model, std::uint32_t const Component, std::vector<glm::mat4> const &Locals) {
if (Component >= Model.components.size())
return std::nullopt;
auto const &record{Model.components[Component]};
if (record.type != eu07m::component::joint || record.kind != eu07m::target_kind::node || record.target >= Model.nodes.size())
return std::nullopt;
eu07m::payload::joint joint;
if (eu07m::payload_reader reader{Model.component_payload(Component)}; false == reader.get(joint))
return std::nullopt;
animation::joint_binding result;
result.node = static_cast<int>(record.target);
result.type = static_cast<animation::joint_type>(joint.kind);
result.axis = {joint.axis[0], joint.axis[1], joint.axis[2]};
result.limited = joint.limited != 0;
result.minimum = joint.minimum;
result.maximum = joint.maximum;
result.pitch = joint.pitch;
result.rest = Locals[record.target];
result.rest_value = joint.rest;
return result;
}
// the channel of a CHNL component, with the bindings the game knows (joints and clips); the others are left out
animation::channel make_channel(eu07m::model const &Model, std::uint32_t const Component, std::vector<glm::mat4> const &Locals) {
animation::channel channel;
eu07m::payload_reader reader{Model.component_payload(Component)};
eu07m::payload::channel record;
if (false == reader.get(record))
return channel;
channel.name = Model.string(record.name);
channel.minimum = record.minimum;
channel.maximum = record.maximum;
channel.initial = record.initial;
for (std::uint32_t idx = 0; idx < record.binding_count; ++idx) {
eu07m::payload::channel_binding binding;
if (false == reader.get(binding))
break;
animation::channel_binding result;
result.scale = binding.scale;
result.offset = binding.offset;
if (binding.kind == eu07m::payload::binding_kind::joint) {
auto const joint{make_joint(Model, binding.target, Locals)};
if (false == joint.has_value())
continue;
result.target = animation::binding_target::joint;
result.joint = *joint;
}
else if (binding.kind == eu07m::payload::binding_kind::clip && binding.target < Model.clips.size()) {
result.target = animation::binding_target::clip;
result.clip = binding.target;
}
else
continue;
channel.bindings.push_back(result);
}
return channel;
}
// the vertex and index streams of a streamed EU07M model (modelstreaming), read again from its file when its geometry bank needs them:
// the chunks in the order of eu07m::drawn_primitives(), as LoadFromEU07M() makes them
class streamed_geometry : public gfx::geometry_source {
public:
streamed_geometry(std::string Path, std::uint64_t const Hash, std::vector<unsigned int> Types) : m_path(std::move(Path)), m_hash(Hash), m_types(std::move(Types)) {}
bool load(gfx::bank_data &Data, bool const Plain, std::string &Error) const override {
eu07m::model model;
eu07m::read_options options{false, false};
options.blocks = eu07m::store_source(eu07m::family_store(m_path));
auto const result{eu07m::read_file(m_path, model, options)};
if (false == result.ok) {
Error = result.error;
return false;
}
if (result.content_hash != m_hash) {
Error = "the file changed since the model was loaded";
return false;
}
auto const primitives{eu07m::drawn_primitives(model)};
if (primitives.size() != m_types.size()) {
Error = "the file has other parts than when the model was loaded";
return false;
}
Data.clear();
Data.resize(primitives.size());
for (std::size_t idx = 0; idx < primitives.size(); ++idx)
fill_chunk(model, primitives[idx], m_types[idx], Plain, Data[idx]);
return true;
}
std::string const &name() const override {
return m_path;
}
private:
// the chunk as finish_binary() makes it: the compact streams as they are (Insert_Compact()), or the vertices made of them, as a
// renderer which draws basic_vertex only makes them
static void fill_chunk(eu07m::model const &Model, std::uint32_t const Primitive, unsigned int const Type, bool const Plain, gfx::chunk_data &Chunk) {
auto geometry{eu07m::geometry_of(Model, Primitive)};
Chunk.indices = std::move(geometry.indices);
Chunk.positions.resize(geometry.positions.size());
Chunk.attributes.resize(geometry.vertex_attributes.size());
if (false == geometry.positions.empty()) {
std::memcpy(Chunk.positions.data(), geometry.positions.data(), geometry.positions.size() * sizeof(glm::vec3));
std::memcpy(Chunk.attributes.data(), geometry.vertex_attributes.data(), geometry.vertex_attributes.size() * sizeof(gfx::compact_attributes));
}
Chunk.userdata.reserve(geometry.vertex_userdata.size());
for (auto const &data : geometry.vertex_userdata)
Chunk.userdata.push_back({glm::vec4{data[0], data[1], data[2], data[3]}});
if (false == Plain)
return;
Chunk.vertices = gfx::decode_compact(Chunk.positions, Chunk.attributes);
gfx::position_array().swap(Chunk.positions);
gfx::compact_array().swap(Chunk.attributes);
// the opengl renderer works the tangents out anew for a chunk without indices (opengl46_renderer::Insert())
if (Chunk.indices.empty())
gfx::calculate_tangents(Chunk.vertices, gfx::index_array(), static_cast<int>(Type));
}
std::string m_path;
std::uint64_t m_hash;
std::vector<unsigned int> m_types; // of the chunks
};
// the kind of geometry of the chunk of a submodel, as finish_binary() gives it
unsigned int chunk_type(TSubModel const &Submodel) {
if (Submodel.eType == TP_FREESPOTLIGHT || Submodel.eType == TP_STARS)
return GL_POINTS;
return static_cast<unsigned int>(Submodel.eType);
}
// what read_model() made of the file
struct model_read {
bool ok{false};
bool streamed{false}; // only the structure was read, the streams are read when the model is drawn (modelstreaming)
std::uint64_t hash{0}; // of the content of the file, which the reads of the streams check
};
// the model read from its file: whole, or a scenery model of a file large enough (modelstreaming) by its structure alone. the size of
// the file decides, so a smaller model is read once, whole, as without the streaming. returns: not ok with the reason in the log
model_read read_model(std::string const &FileName, bool const Streamable, eu07m::model &Model) {
model_read result;
// the game has no use for the sections it doesn't know; the geometry shared by the family comes from the store of the folder
eu07m::read_options options{false, false};
options.blocks = eu07m::store_source(eu07m::family_store(FileName));
std::error_code sizeerror;
auto const filesize{std::filesystem::file_size(FileName, sizeerror)};
auto const largeenough{(false == bool(sizeerror)) && (filesize >= static_cast<std::uint64_t>(std::max(0, Global.modelstreaming_minsize)) * 1024)};
if (Streamable && largeenough && GfxRenderer->Streams_Geometry()) {
auto structure{options};
structure.streams = false;
auto const structureread{eu07m::read_file(FileName, Model, structure)};
if (false == structureread.ok) {
ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + structureread.error, logtype::model);
return result;
}
result.hash = structureread.content_hash;
result.streamed = eu07m::not_streamable(Model).empty();
if (result.streamed) {
result.ok = true;
return result;
}
}
auto const file{read_whole_file(FileName)};
if (file.data == nullptr) {
ErrorLog("Bad model: can't read \"" + FileName + "\"", logtype::model);
return result;
}
if (auto const whole{eu07m::read(std::as_bytes(std::span{file.data.get(), file.size}), Model, options)}; false == whole.ok) {
ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + whole.error, logtype::model);
return result;
}
result.ok = true;
return result;
}
} // namespace
bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) {
WriteLog("Loading EU07M model data from \"" + FileName + "\"...", logtype::model);
eu07m::model model;
model_read read;
try {
read = read_model(FileName, m_streamable, model);
}
catch (std::exception const &Error) {
ErrorLog("Bad model: \"" + FileName + "\" can't be read: " + Error.what(), logtype::model);
return false;
}
if (false == read.ok)
return false;
if (model.nodes.empty()) {
ErrorLog("Bad model: \"" + FileName + "\" has no nodes", logtype::model);
return false;
}
Root = nullptr;
if (m_geometrybank == null_handle)
m_geometrybank = GfxRenderer->Create_Bank();
Textures.clear();
Names.clear();
Matrices.clear();
Matrices.reserve(model.nodes.size());
iSubModelsCount = static_cast<int>(model.nodes.size());
Root = new TSubModel[model.nodes.size()];
submodel_builder builder{model, Textures, Names, Matrices};
try {
for (std::uint32_t idx = 0; idx < model.nodes.size(); ++idx)
builder.build(idx, Root[idx]);
if (read.streamed)
stream_geometry(FileName, model, read.hash);
else
builder.fill_geometry();
}
catch (std::exception const &Error) {
// nothing of the model is kept, so its .e3d / .t3d is loaded in its place
SafeDeleteArray(Root);
iSubModelsCount = 0;
Textures.clear();
Names.clear();
Matrices.clear();
ErrorLog("Bad model: \"" + FileName + "\" can't be built: " + Error.what(), logtype::model);
return false;
}
// the skins, with their joints as the submodels of the nodes
m_skins.clear();
for (auto const &record : model.skins) {
skinning::skin skin;
for (auto const &joint : std::span{model.skin_joints}.subspan(record.joint_first, record.joint_count)) {
skin.joints.push_back(&Root[joint.node]);
auto const &bind{joint.inverse_bind};
skin.inverse_bind.emplace_back(glm::vec4{bind[0], bind[1], bind[2], 0.f}, glm::vec4{bind[3], bind[4], bind[5], 0.f}, glm::vec4{bind[6], bind[7], bind[8], 0.f},
glm::vec4{bind[9], bind[10], bind[11], 1.f});
}
m_skins.push_back(std::move(skin));
}
// the clips; the nodes they move keep a transform of their own, as animated ones (0x4000)
m_clips.clear();
for (auto const &record : model.clips) {
auto clip{make_clip(model, record)};
for (auto const &node : clip.nodes)
Root[node.node].WillBeAnimated();
m_clips.push_back(std::move(clip));
}
// the channels; the nodes of their joints are animated too
m_channels.clear();
auto const locals{eu07m::local_transforms(model)};
for (std::uint32_t idx = 0; idx < model.components.size(); ++idx) {
if (model.components[idx].type != eu07m::component::channel)
continue;
auto channel{make_channel(model, idx, locals)};
for (auto const &binding : channel.bindings) {
if (binding.target == animation::binding_target::joint)
Root[binding.joint.node].WillBeAnimated();
}
m_channels.push_back(std::move(channel));
}
m_vertexcount += builder.vertex_count;
m_indexcount += builder.index_count;
// the tangents come with the vertices
finish_binary(dynamic, true);
WriteLog(std::format("Finished loading EU07M model data from \"{}\"{}", FileName, m_streamed ? ", its geometry streamed" : ""), logtype::model);
return true;
}
// the geometry bank of the model takes the data of its chunks from the file when it's drawn (modelstreaming); the bounds of the nodes stand
// for the vertices meanwhile
void TModel3d::stream_geometry(std::string const &FileName, eu07m::model const &Model, std::uint64_t const Hash) {
m_nodebounds.clear();
m_nodebounds.reserve(Model.nodes.size());
for (std::size_t idx = 0; idx < Model.nodes.size(); ++idx) {
auto const &record{Model.bounds[idx]};
std::array<glm::vec3, 2> const bounds{glm::vec3{record.min[0], record.min[1], record.min[2]}, glm::vec3{record.max[0], record.max[1], record.max[2]}};
m_nodebounds.push_back(bounds);
}
std::vector<unsigned int> types;
for (std::size_t idx = 0; idx < Model.nodes.size(); ++idx) {
Root[idx].m_nodebounds = &m_nodebounds[idx];
if (Root[idx].m_geometry.vertex_count > 0)
types.push_back(chunk_type(Root[idx]));
}
GfxRenderer->Stream_Bank(m_geometrybank, std::make_shared<streamed_geometry>(FileName, Hash, std::move(types)));
m_streamed = true;
}