Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "ObjectEntry.h"
21 :
22 : #include "graphics/Decal.h"
23 : #include "graphics/Material.h"
24 : #include "graphics/MaterialManager.h"
25 : #include "graphics/MeshManager.h"
26 : #include "graphics/Model.h"
27 : #include "graphics/ModelAbstract.h"
28 : #include "graphics/ModelDef.h"
29 : #include "graphics/ModelDummy.h"
30 : #include "graphics/ObjectBase.h"
31 : #include "graphics/ObjectManager.h"
32 : #include "graphics/ParticleEmitter.h"
33 : #include "graphics/ParticleManager.h"
34 : #include "graphics/SkeletonAnim.h"
35 : #include "graphics/SkeletonAnimManager.h"
36 : #include "graphics/Texture.h"
37 : #include "graphics/TextureManager.h"
38 : #include "lib/debug.h"
39 : #include "lib/rand.h"
40 : #include "lib/utf8.h"
41 : #include "maths/Vector4D.h"
42 : #include "ps/CLogger.h"
43 : #include "ps/CStrIntern.h"
44 : #include "ps/CStrInternStatic.h"
45 : #include "renderer/Renderer.h"
46 : #include "renderer/SceneRenderer.h"
47 : #include "renderer/backend/Sampler.h"
48 :
49 : #include <algorithm>
50 : #include <cstddef>
51 : #include <sstream>
52 : #include <utility>
53 :
54 : namespace
55 : {
56 :
57 0 : bool ShouldInterpretTextureAsSRGB(const CObjectBase::Samp& sampler, const CMaterial& material)
58 : {
59 0 : const auto requiredSamplers{material.GetRequiredSamplers()};
60 0 : auto it{std::find_if(requiredSamplers.begin(), requiredSamplers.end(),
61 0 : [&](const CMaterial::RequiredSampler& requiredSampler)
62 : {
63 0 : return requiredSampler.name == sampler.m_SamplerName;
64 : })};
65 0 : return it != requiredSamplers.end() && it->sRGB;
66 0 : }
67 :
68 : }
69 :
70 1 : CObjectEntry::CObjectEntry(const std::shared_ptr<CObjectBase>& base, const CSimulation2& simulation) :
71 1 : m_Base(base), m_Color(1.0f, 1.0f, 1.0f, 1.0f), m_Simulation(simulation)
72 : {
73 1 : }
74 :
75 3 : CObjectEntry::~CObjectEntry() = default;
76 :
77 1 : bool CObjectEntry::BuildVariation(const std::vector<const std::set<CStr>*>& completeSelections,
78 : const std::vector<std::uint8_t>& variationKey, CObjectManager& objectManager)
79 : {
80 1 : CObjectBase::Variation variation = m_Base->BuildVariation(variationKey);
81 :
82 : // Copy the chosen data onto this model:
83 :
84 1 : for (std::multimap<CStr, CObjectBase::Samp>::iterator it = variation.samplers.begin(); it != variation.samplers.end(); ++it)
85 0 : m_Samplers.push_back(it->second);
86 :
87 1 : m_ModelName = variation.model;
88 :
89 1 : if (! variation.color.empty())
90 : {
91 0 : std::stringstream str;
92 0 : str << variation.color;
93 0 : int r, g, b;
94 0 : if (! (str >> r >> g >> b)) // Any trailing data is ignored
95 : {
96 0 : LOGERROR("Actor '{}' has invalid RGB color '{}'", m_Base->GetIdentifier(),
97 : variation.color);
98 : }
99 : else
100 0 : m_Color = CColor(r/255.0f, g/255.0f, b/255.0f, 1.0f);
101 0 : }
102 :
103 1 : if (variation.decal.m_SizeX && variation.decal.m_SizeZ)
104 : {
105 0 : CMaterial material = g_Renderer.GetSceneRenderer().GetMaterialManager().LoadMaterial(m_Base->m_Material);
106 :
107 0 : for (const CObjectBase::Samp& samp : m_Samplers)
108 : {
109 0 : CTextureProperties textureProps(samp.m_SamplerFile);
110 : // TODO: replace all samplers by CLAMP_TO_EDGE after decals
111 : // refactoring. Also we need to avoid custom border colors.
112 0 : textureProps.SetAddressMode(
113 0 : samp.m_SamplerName == str_baseTex
114 : ? Renderer::Backend::Sampler::AddressMode::CLAMP_TO_BORDER
115 : : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
116 0 : CTexturePtr texture = g_Renderer.GetTextureManager().CreateTexture(textureProps);
117 : // TODO: Should check which material is selected and only preload the necessary textures.
118 0 : texture->Prefetch();
119 0 : material.AddSampler(CMaterial::TextureSampler(samp.m_SamplerName, texture));
120 0 : }
121 :
122 0 : SDecal decal(material,
123 : variation.decal.m_SizeX, variation.decal.m_SizeZ,
124 : variation.decal.m_Angle, variation.decal.m_OffsetX, variation.decal.m_OffsetZ,
125 0 : m_Base->m_Properties.m_FloatOnWater);
126 0 : m_Model = std::make_unique<CModelDecal>(objectManager.GetTerrain(), decal);
127 :
128 0 : return true;
129 0 : }
130 :
131 1 : if (!variation.particles.empty())
132 : {
133 0 : CParticleEmitterType* particleEmitterType{
134 0 : g_Renderer.GetSceneRenderer().GetParticleManager().LoadEmitterType(variation.particles)};
135 0 : if (!particleEmitterType)
136 : {
137 0 : LOGERROR("CObjectEntry::BuildVariation(): Failed to load particles {}",
138 : variation.particles.string8());
139 0 : return false;
140 : }
141 0 : m_Model = std::make_unique<CModelParticleEmitter>(*particleEmitterType);
142 0 : return true;
143 : }
144 :
145 1 : if (variation.model.empty())
146 : {
147 0 : m_Model = std::make_unique<CModelDummy>();
148 0 : return true;
149 : }
150 :
151 1 : std::vector<CObjectBase::Prop> props;
152 :
153 1 : for (std::multimap<CStr, CObjectBase::Prop>::iterator it = variation.props.begin(); it != variation.props.end(); ++it)
154 0 : props.push_back(it->second);
155 :
156 : // Build the model:
157 :
158 : // try and create a model
159 1 : CModelDefPtr modeldef (objectManager.GetMeshManager().GetMesh(m_ModelName));
160 1 : if (!modeldef)
161 : {
162 0 : LOGERROR("CObjectEntry::BuildVariation(): Model {} failed to load", m_ModelName.string8());
163 0 : return false;
164 : }
165 :
166 : // delete old model, create new
167 1 : CMaterial material = g_Renderer.GetSceneRenderer().GetMaterialManager().LoadMaterial(m_Base->m_Material);
168 1 : material.AddStaticUniform("objectColor", CVector4D(m_Color.r, m_Color.g, m_Color.b, m_Color.a));
169 :
170 1 : if (m_Samplers.empty())
171 3 : LOGERROR("Actor '{}' has no textures.", m_Base->GetIdentifier());
172 :
173 1 : for (const CObjectBase::Samp& samp : m_Samplers)
174 : {
175 0 : CTextureProperties textureProps(samp.m_SamplerFile);
176 0 : textureProps.SetAddressMode(Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
177 0 : textureProps.SetSRGB(ShouldInterpretTextureAsSRGB(samp, material));
178 0 : CTexturePtr texture = g_Renderer.GetTextureManager().CreateTexture(textureProps);
179 : // if we've loaded this model we're probably going to render it soon, so prefetch its texture.
180 : // All textures are prefetched even in the fixed pipeline, including the normal maps etc.
181 : // TODO: Should check which material is selected and only preload the necessary textures.
182 0 : texture->Prefetch();
183 0 : material.AddSampler(CMaterial::TextureSampler(samp.m_SamplerName, texture));
184 0 : }
185 :
186 1 : std::unique_ptr<CModel> newModel = std::make_unique<CModel>(m_Simulation, material, modeldef);
187 1 : CModel* model = newModel.get();
188 1 : m_Model = std::move(newModel);
189 :
190 1 : for (const auto& requiredSampler : model->GetMaterial().GetRequiredSamplers())
191 : {
192 0 : if (std::find_if(m_Samplers.begin(), m_Samplers.end(),
193 0 : [&](const CObjectBase::Samp& sampler) { return sampler.m_SamplerName == requiredSampler.name; }) == m_Samplers.end())
194 : {
195 0 : LOGERROR("Actor {}: required texture sampler {} not found (material {})",
196 : m_Base->GetIdentifier(), requiredSampler.name.string(),
197 : m_Base->m_Material.string8());
198 : }
199 : }
200 :
201 : // calculate initial object space bounds, based on vertex positions
202 1 : model->CalcStaticObjectBounds();
203 :
204 : // load the animations
205 1 : for (std::multimap<CStr, CObjectBase::Anim>::iterator it = variation.anims.begin(); it != variation.anims.end(); ++it)
206 : {
207 0 : CStr name = it->first.LowerCase();
208 :
209 0 : if (it->second.m_FileName.empty())
210 0 : continue;
211 0 : std::unique_ptr<CSkeletonAnim> anim = objectManager.GetSkeletonAnimManager().BuildAnimation(
212 0 : it->second.m_FileName,
213 : name,
214 0 : it->second.m_ID,
215 0 : it->second.m_Frequency,
216 0 : it->second.m_Speed,
217 0 : it->second.m_ActionPos,
218 0 : it->second.m_ActionPos2,
219 0 : it->second.m_SoundPos);
220 0 : if (anim)
221 0 : m_Animations.emplace(name, std::move(anim));
222 0 : }
223 :
224 : // ensure there's always an idle animation
225 1 : if (m_Animations.find("idle") == m_Animations.end())
226 : {
227 1 : std::unique_ptr<CSkeletonAnim> anim = std::make_unique<CSkeletonAnim>();
228 1 : anim->m_Name = "idle";
229 1 : anim->m_ID = "";
230 1 : anim->m_AnimDef = NULL;
231 1 : anim->m_Frequency = 0;
232 1 : anim->m_Speed = 0.f;
233 1 : anim->m_ActionPos = 0.f;
234 1 : anim->m_ActionPos2 = 0.f;
235 1 : anim->m_SoundPos = 0.f;
236 1 : SkeletonAnimMap::const_iterator it = m_Animations.emplace("idle", std::move(anim));
237 :
238 : // Ignore errors, since they're probably saying this is a non-animated model
239 1 : model->SetAnimation(it->second.get());
240 1 : }
241 : else
242 : {
243 : // start up idling
244 0 : if (!model->SetAnimation(GetRandomAnimation("idle")))
245 0 : LOGERROR("Failed to set idle animation in model \"{}\"", m_ModelName.string8());
246 : }
247 :
248 : // build props - TODO, RC - need to fix up bounds here
249 : // TODO: Make sure random variations get handled correctly when a prop fails
250 1 : for (const CObjectBase::Prop& prop : props)
251 : {
252 : // Pluck out the special attachpoint 'projectile'
253 0 : if (prop.m_PropPointName == "projectile")
254 : {
255 0 : m_ProjectileModelName = prop.m_ModelName;
256 0 : continue;
257 : }
258 :
259 0 : CObjectEntry* oe = nullptr;
260 0 : if (auto [success, actorDef] = objectManager.FindActorDef(prop.m_ModelName.c_str()); success)
261 0 : oe = objectManager.FindObjectVariation(actorDef.GetBase(m_Base->m_QualityLevel), completeSelections);
262 :
263 0 : if (!oe)
264 : {
265 0 : LOGERROR("Failed to build prop model \"{}\" on actor \"{}\"",
266 : utf8_from_wstring(prop.m_ModelName), m_Base->GetIdentifier());
267 0 : continue;
268 0 : }
269 :
270 : // If we don't have a projectile but this prop does (e.g. it's our rider), then
271 : // use that as our projectile too
272 0 : if (m_ProjectileModelName.empty() && !oe->m_ProjectileModelName.empty())
273 0 : m_ProjectileModelName = oe->m_ProjectileModelName;
274 :
275 0 : CStr ppn = prop.m_PropPointName;
276 0 : bool isAmmo = false;
277 :
278 : // Handle the special attachpoint 'loaded-<proppoint>'
279 0 : if (ppn.starts_with("loaded-"))
280 : {
281 0 : ppn = prop.m_PropPointName.substr(7);
282 0 : isAmmo = true;
283 : }
284 :
285 0 : const SPropPoint* proppoint = modeldef->FindPropPoint(ppn.c_str());
286 0 : if (proppoint)
287 : {
288 0 : std::unique_ptr<CModelAbstract> propmodel = oe->m_Model->Clone();
289 0 : if (propmodel->ToCModel())
290 0 : propmodel->ToCModel()->SetAnimation(oe->GetRandomAnimation("idle"));
291 0 : if (isAmmo)
292 0 : model->AddAmmoProp(proppoint, std::move(propmodel), oe);
293 : else
294 0 : model->AddProp(proppoint, std::move(propmodel), oe, prop.m_minHeight, prop.m_maxHeight, prop.m_selectable);
295 0 : }
296 : else
297 0 : LOGERROR("Failed to find matching prop point called \"{}\" in model \"{}\" for actor "
298 : "\"{}\"", ppn, m_ModelName.string8(), m_Base->GetIdentifier());
299 0 : }
300 :
301 : // Setup flags.
302 1 : if (m_Base->m_Properties.m_CastShadows)
303 : {
304 1 : model->SetFlags(model->GetFlags() | ModelFlag::CAST_SHADOWS);
305 : }
306 :
307 1 : if (m_Base->m_Properties.m_FloatOnWater)
308 : {
309 0 : model->SetFlags(model->GetFlags() | ModelFlag::FLOAT_ON_WATER);
310 : }
311 :
312 1 : return true;
313 2 : }
314 :
315 2 : CSkeletonAnim* CObjectEntry::GetRandomAnimation(const CStr& animationName, const CStr& ID) const
316 : {
317 2 : std::vector<CSkeletonAnim*> anims = GetAnimations(animationName, ID);
318 :
319 2 : int totalFreq = 0;
320 4 : for (CSkeletonAnim* anim : anims)
321 2 : totalFreq += anim->m_Frequency;
322 :
323 2 : if (totalFreq == 0)
324 2 : return anims[rand(0, anims.size())];
325 :
326 0 : int r = rand(0, totalFreq);
327 0 : for (CSkeletonAnim* anim : anims)
328 : {
329 0 : r -= anim->m_Frequency;
330 0 : if (r < 0)
331 0 : return anim;
332 : }
333 : return NULL;
334 2 : }
335 :
336 3 : std::vector<CSkeletonAnim*> CObjectEntry::GetAnimations(const CStr& animationName, const CStr& ID) const
337 : {
338 3 : std::vector<CSkeletonAnim*> anims;
339 :
340 3 : SkeletonAnimMap::const_iterator lower = m_Animations.lower_bound(animationName);
341 3 : SkeletonAnimMap::const_iterator upper = m_Animations.upper_bound(animationName);
342 :
343 6 : for (SkeletonAnimMap::const_iterator it = lower; it != upper; ++it)
344 : {
345 3 : if (ID.empty() || it->second->m_ID == ID)
346 3 : anims.push_back(it->second.get());
347 : }
348 :
349 3 : if (anims.empty())
350 : {
351 0 : lower = m_Animations.lower_bound("idle");
352 0 : upper = m_Animations.upper_bound("idle");
353 0 : for (SkeletonAnimMap::const_iterator it = lower; it != upper; ++it)
354 0 : anims.push_back(it->second.get());
355 : }
356 :
357 3 : ENSURE(!anims.empty());
358 3 : return anims;
359 0 : }
|