NoJobEngine 2.0.7
Loading...
Searching...
No Matches
PrefabSerializer.cpp
Go to the documentation of this file.
2#include "Engine/Core/Log.h"
8#include <fstream>
9#include <iomanip>
10#include <unordered_map>
11#include <algorithm>
12#include <functional>
14
15namespace NoJob {
16namespace {
17void WriteMaterial(std::ostream& o,const std::shared_ptr<Material>& m)
18{
19 if(!m){o<<"MAT_NONE\n";return;}
20 auto c=m->GetColor(); auto e=m->EmissiveColor();
21 o<<"MAT "<<c.r<<' '<<c.g<<' '<<c.b<<' '<<c.a<<' '<<m->Metallic()<<' '<<m->Roughness()<<' '
22 <<m->AmbientOcclusion()<<' '<<m->NormalStrength()<<' '<<e.r<<' '<<e.g<<' '<<e.b<<' '
23 <<m->EmissiveStrength()<<' '<<(m->UseTexture()?1:0)<<' '<<(int)m->SurfaceMode()<<' '<<m->AlphaCutoff()<<'\n';
24 o<<"TEX "<<std::quoted(AssetManager::GetTexturePath(m->GetTexture()).generic_string())<<' '
25 <<std::quoted(AssetManager::GetTexturePath(m->GetNormalTexture()).generic_string())<<' '
26 <<std::quoted(AssetManager::GetTexturePath(m->GetMetallicTexture()).generic_string())<<' '
27 <<std::quoted(AssetManager::GetTexturePath(m->GetRoughnessTexture()).generic_string())<<' '
28 <<std::quoted(AssetManager::GetTexturePath(m->GetAOTexture()).generic_string())<<' '
29 <<std::quoted(AssetManager::GetTexturePath(m->GetEmissiveTexture()).generic_string())<<"\n";
30}
31void WriteEntity(std::ostream& o,Entity e,Scene& scene,int parentLocal,int& nextLocal)
32{
33 const int local=nextLocal++;
34 auto& tag=e.GetComponent<TagComponent>(); auto& x=e.GetComponent<TransformComponent>();
35 o<<"ENTITY "<<local<<' '<<parentLocal<<' '<<std::quoted(tag.Tag)<<'\n';
36 o<<"TRANSFORM "<<x.Position.x<<' '<<x.Position.y<<' '<<x.Position.z<<' '
37 <<x.Rotation.x<<' '<<x.Rotation.y<<' '<<x.Rotation.z<<' '
38 <<x.Scale.x<<' '<<x.Scale.y<<' '<<x.Scale.z<<'\n';
39 if(e.HasComponent<MeshComponent>())
40 {
41 const auto meshPath = AssetManager::GetMeshPath(e.GetComponent<MeshComponent>().MeshAsset).generic_string();
42 // Procedural meshes (currently the editor cube) are not registered as file assets.
43 // Preserve them explicitly instead of serializing an empty path.
44 o<<"MESH "<<std::quoted(meshPath.empty() ? std::string("CUBE") : meshPath)<<"\n";
45 }
46 else o<<"MESH "<<std::quoted(std::string())<<"\n";
47 if(e.HasComponent<MeshRendererComponent>()){
48 auto& r=e.GetComponent<MeshRendererComponent>();
49 const size_t count=r.Materials.empty()?(r.MaterialAsset?1:0):r.Materials.size();
50 o<<"MATERIALS "<<count<<"\n";
51 for(size_t i=0;i<count;++i) WriteMaterial(o,r.Materials.empty()?r.MaterialAsset:r.Materials[i]);
52 } else o<<"MATERIALS 0\n";
53 if(e.HasComponent<AnimatorComponent>())
54 {
55 auto& a=e.GetComponent<AnimatorComponent>();
56 const std::string source=a.Animation ? a.Animation->SourcePath().generic_string() : std::string();
57 o<<"ANIMATOR "<<std::quoted(source)<<' '<<a.ClipIndex<<' '<<a.Speed<<' '
58 <<(a.Playing?1:0)<<' '<<(a.Loop?1:0)<<"\n";
59 }
60 if(e.HasComponent<AudioSourceComponent>())
61 {
62 auto& a=e.GetComponent<AudioSourceComponent>();
63 o<<"AUDIO_SOURCE "<<std::quoted(a.ClipPath)<<' '<<a.PlayOnAwake<<' '<<a.Loop<<' '
64 <<a.Volume<<' '<<a.Pitch<<' '<<a.SpatialBlend<<' '<<a.MinDistance<<' '
65 <<a.MaxDistance<<' '<<a.DopplerFactor<<"\n";
66 }
67 if(e.HasComponent<AudioListenerComponent>())
68 {
69 o<<"AUDIO_LISTENER "<<e.GetComponent<AudioListenerComponent>().Enabled<<"\n";
70 }
71 if(e.HasComponent<ParticleSystemComponent>())
72 {
73 auto& v=e.GetComponent<ParticleSystemComponent>();
74 o<<"PARTICLE_SYSTEM_V2 "<<v.Playing<<' '<<v.Loop<<' '<<v.Duration<<' '<<v.StartLifetime<<' '
75 <<v.LifetimeRandom<<' '<<v.StartSpeed<<' '<<v.SpeedRandom<<' '<<v.StartSize<<' '<<v.SizeRandom<<' '
76 <<v.StartColor.r<<' '<<v.StartColor.g<<' '<<v.StartColor.b<<' '<<v.StartColor.a<<' '
77 <<v.EndColor.r<<' '<<v.EndColor.g<<' '<<v.EndColor.b<<' '<<v.EndColor.a<<' '
78 <<v.EndSizeMultiplier<<' '<<v.EmissionRate<<' '<<v.MaxParticles<<' '
79 <<v.Direction.x<<' '<<v.Direction.y<<' '<<v.Direction.z<<' '
80 <<v.Gravity.x<<' '<<v.Gravity.y<<' '<<v.Gravity.z<<' '
81 <<static_cast<int>(v.Shape)<<' '<<v.ShapeRadius<<' '<<v.ConeAngle<<' '
82 <<static_cast<int>(v.BlendMode)<<' '<<std::quoted(v.TexturePath)<<"\n";
83 }
84 if(e.HasComponent<NativeScriptComponent>())
85 {
86 auto& script=e.GetComponent<NativeScriptComponent>();
87 o<<"SCRIPT_V2 "<<script.Enabled<<' '<<std::quoted(script.ScriptName)<<"\n";
88 for(const auto& [fieldName,value]:script.Fields)
89 {
90 o<<"SCRIPT_FIELD "<<std::quoted(fieldName)<<' '<<int(value.Type)<<' ';
91 if(value.Type==ScriptFieldType::Float)o<<value.Float;
92 else if(value.Type==ScriptFieldType::Int)o<<value.Int;
93 else if(value.Type==ScriptFieldType::Bool)o<<value.Bool;
94 else if(value.Type==ScriptFieldType::String)o<<std::quoted(value.String);
95 else o<<value.Vec3.x<<' '<<value.Vec3.y<<' '<<value.Vec3.z;
96 o<<"\n";
97 }
98 }
99 o<<"END_ENTITY\n";
100 for(Entity child:scene.GetChildren(e)) WriteEntity(o,child,scene,local,nextLocal);
101}
102std::shared_ptr<Texture2D> LoadTex(const std::string& p,const std::filesystem::path& prefabPath)
103{
104 if(p.empty()) return {};
105 try
106 {
107 // Current assets normally store project-relative paths.
108 auto tex=AssetManager::LoadTexture(p);
109 if(tex) return tex;
110 }
111 catch(...){Log::Warn("Prefab asset load failed; trying fallback.");}
112 try
113 {
114 // Compatibility/fallback for paths that were serialized relative to the prefab itself.
115 const auto candidate=(prefabPath.parent_path()/p).lexically_normal();
116 if(std::filesystem::exists(candidate)) return AssetManager::LoadTexture(candidate);
117 }
118 catch(...){Log::Warn("Prefab asset load failed; trying fallback.");}
119 return {};
120}
121}
122bool PrefabSerializer::Save(Entity root,const std::filesystem::path& p)
123{
124 if(!root)return false; std::filesystem::create_directories(p.parent_path()); std::ofstream o(p); if(!o)return false;
125 o<<"NOJOB_PREFAB 6\n"; int next=0;
126 // Entity keeps its Scene private; derive hierarchy through the root's relationship is not enough.
127 // PrefabSerializer is intentionally a Scene friend via Entity access is unavailable, so V4 Save is
128 // rooted by recursively following handles through a lightweight local lambda in the public Scene API.
129 // Root scene pointer is available here because PrefabSerializer is declared friend below in Entity.h.
130 Scene& scene=*root.m_Scene;
131 WriteEntity(o,root,scene,-1,next);
132 return true;
133}
134Entity PrefabSerializer::Instantiate(Scene& s,const std::filesystem::path& p,const std::shared_ptr<Mesh>& fallback,const std::shared_ptr<Material>& base)
135{
136 std::ifstream i(p); if(!i)return{}; std::string magic;int version=0;i>>magic>>version;
137 if(magic!="NOJOB_PREFAB") return {};
138 if(version<4)
139 {
140 std::string k,name="Prefab",mp,a,n,me,r,aop,em;
141 glm::vec3 pos{},rot{},sc{1},ec{};glm::vec4 col{1};
142 float mt=0,ro=.5f,ao=1,ns=1,es=0;bool hm=false,useTexture=false;
143 while(i>>k){
144 if(k=="NAME")i>>std::quoted(name);
145 else if(k=="TRANSFORM")i>>pos.x>>pos.y>>pos.z>>rot.x>>rot.y>>rot.z>>sc.x>>sc.y>>sc.z;
146 else if(k=="MESH")i>>std::quoted(mp);
147 else if(k=="MATERIAL"){i>>col.r>>col.g>>col.b>>col.a>>mt>>ro>>ao>>ns>>ec.r>>ec.g>>ec.b>>es;hm=true;}
148 else if(k=="USE_TEXTURE"){int enabled=0;i>>enabled;useTexture=enabled!=0;}
149 else if(k=="TEXTURES")i>>std::quoted(a)>>std::quoted(n)>>std::quoted(me)>>std::quoted(r)>>std::quoted(aop)>>std::quoted(em);
150 }
151 auto e=s.CreateEntity(name);auto& tr=e.GetComponent<TransformComponent>();tr.Position=pos;tr.Rotation=rot;tr.Scale=sc;
152 if(!mp.empty()){try{e.AddComponent<MeshComponent>(mp=="CUBE"?fallback:AssetManager::LoadMesh(mp));}catch(...){Log::Warn("Prefab mesh load failed; using fallback mesh.");if(fallback)e.AddComponent<MeshComponent>(fallback);}}
153 if(hm&&base){
154 auto m=std::make_shared<Material>(*base);m->GetColor()=col;m->Metallic()=mt;m->Roughness()=ro;m->AmbientOcclusion()=ao;
155 m->NormalStrength()=ns;m->EmissiveColor()=ec;m->EmissiveStrength()=es;m->UseTexture()=false;
156 m->SetTexture(LoadTex(a,p));if(version<3&&!a.empty())useTexture=true;m->UseTexture()=useTexture&&(m->GetTexture()!=nullptr);
157 m->SetNormalTexture(LoadTex(n,p));m->SetMetallicTexture(LoadTex(me,p));m->SetRoughnessTexture(LoadTex(r,p));
158 m->SetAOTexture(LoadTex(aop,p));m->SetEmissiveTexture(LoadTex(em,p));e.AddComponent<MeshRendererComponent>(m);
159 }
160 e.AddComponent<PrefabInstanceComponent>(PrefabInstanceComponent{p.generic_string(),true});
161 return e;
162 }
163 std::unordered_map<int,Entity> made; Entity root{};
164 std::string k;
165 while(i>>k){
166 if(k!="ENTITY"){std::string skip;std::getline(i,skip);continue;}
167 int id,parent;i>>id>>parent;std::string name;i>>std::quoted(name);
168 Entity e=s.CreateEntity(name);made[id]=e;if(!root)root=e;
169 glm::vec3 pos{},rot{},sc{1};std::string meshPath;size_t matCount=0;
170 std::string animationPath; int animationClip=0; float animationSpeed=1.0f;
171 bool animationPlaying=true,animationLoop=true;
172 bool hasScript=false; NativeScriptComponent nativeScript;
173 bool hasAudioSource=false; AudioSourceComponent audioSource;
174 bool hasAudioListener=false; AudioListenerComponent audioListener;
175 bool hasParticleSystem=false; ParticleSystemComponent particleSystem;
176 while(i>>k && k!="END_ENTITY"){
177 if(k=="TRANSFORM"){i>>pos.x>>pos.y>>pos.z>>rot.x>>rot.y>>rot.z>>sc.x>>sc.y>>sc.z;}
178 else if(k=="MESH"){i>>std::quoted(meshPath);}
179 else if(k=="ANIMATOR"){
180 int playing=1,loop=1;
181 i>>std::quoted(animationPath)>>animationClip>>animationSpeed>>playing>>loop;
182 animationPlaying=playing!=0; animationLoop=loop!=0;
183 }
184 else if(k=="AUDIO_SOURCE"){
185 i>>std::quoted(audioSource.ClipPath)>>audioSource.PlayOnAwake>>audioSource.Loop
186 >>audioSource.Volume>>audioSource.Pitch>>audioSource.SpatialBlend
187 >>audioSource.MinDistance>>audioSource.MaxDistance>>audioSource.DopplerFactor;
188 hasAudioSource=true;
189 }
190 else if(k=="AUDIO_LISTENER"){
191 i>>audioListener.Enabled; hasAudioListener=true;
192 }
193 else if(k=="PARTICLE_SYSTEM"){
194 i>>particleSystem.Playing>>particleSystem.Loop>>particleSystem.Duration
195 >>particleSystem.StartLifetime>>particleSystem.StartSpeed>>particleSystem.StartSize
196 >>particleSystem.StartColor.r>>particleSystem.StartColor.g>>particleSystem.StartColor.b>>particleSystem.StartColor.a
197 >>particleSystem.EmissionRate>>particleSystem.MaxParticles
198 >>particleSystem.Direction.x>>particleSystem.Direction.y>>particleSystem.Direction.z
199 >>particleSystem.Gravity.x>>particleSystem.Gravity.y>>particleSystem.Gravity.z;
200 hasParticleSystem=true;
201 }
202 else if(k=="PARTICLE_SYSTEM_V2"){
203 int shape=0,blend=0;
204 i>>particleSystem.Playing>>particleSystem.Loop>>particleSystem.Duration
205 >>particleSystem.StartLifetime>>particleSystem.LifetimeRandom
206 >>particleSystem.StartSpeed>>particleSystem.SpeedRandom
207 >>particleSystem.StartSize>>particleSystem.SizeRandom
208 >>particleSystem.StartColor.r>>particleSystem.StartColor.g>>particleSystem.StartColor.b>>particleSystem.StartColor.a
209 >>particleSystem.EndColor.r>>particleSystem.EndColor.g>>particleSystem.EndColor.b>>particleSystem.EndColor.a
210 >>particleSystem.EndSizeMultiplier>>particleSystem.EmissionRate>>particleSystem.MaxParticles
211 >>particleSystem.Direction.x>>particleSystem.Direction.y>>particleSystem.Direction.z
212 >>particleSystem.Gravity.x>>particleSystem.Gravity.y>>particleSystem.Gravity.z
213 >>shape>>particleSystem.ShapeRadius>>particleSystem.ConeAngle>>blend>>std::quoted(particleSystem.TexturePath);
214 particleSystem.Shape=static_cast<ParticleShape>(shape);
215 particleSystem.BlendMode=static_cast<ParticleBlendMode>(blend);
216 hasParticleSystem=true;
217 }
218 else if(k=="SCRIPT_V2"){
219 i>>nativeScript.Enabled>>std::quoted(nativeScript.ScriptName); hasScript=true;
220 }
221 else if(k=="SCRIPT_FIELD" && hasScript){
222 std::string fieldName; int type=0; i>>std::quoted(fieldName)>>type;
223 ScriptFieldValue value; value.Type=ScriptFieldType(type);
224 if(value.Type==ScriptFieldType::Float)i>>value.Float;
225 else if(value.Type==ScriptFieldType::Int)i>>value.Int;
226 else if(value.Type==ScriptFieldType::Bool)i>>value.Bool;
227 else if(value.Type==ScriptFieldType::String)i>>std::quoted(value.String);
228 else i>>value.Vec3.x>>value.Vec3.y>>value.Vec3.z;
229 nativeScript.Fields[fieldName]=value;
230 }
231 else if(k=="MATERIALS"){
232 i>>matCount; std::vector<std::shared_ptr<Material>> mats;
233 for(size_t m=0;m<matCount;++m){
234 std::string mk;i>>mk;if(mk=="MAT_NONE"){mats.push_back({});continue;}
235 if(mk!="MAT")continue;
236 auto mat=std::make_shared<Material>(*base);auto& c=mat->GetColor();auto& ec=mat->EmissiveColor();
237 int use=0,mode=0;i>>c.r>>c.g>>c.b>>c.a>>mat->Metallic()>>mat->Roughness()>>mat->AmbientOcclusion()
238 >>mat->NormalStrength()>>ec.r>>ec.g>>ec.b>>mat->EmissiveStrength()>>use>>mode>>mat->AlphaCutoff();
239 mat->SurfaceMode()=(MaterialSurfaceMode)mode;
240 std::string tk,a,n,me,r,ao,em;i>>tk>>std::quoted(a)>>std::quoted(n)>>std::quoted(me)>>std::quoted(r)>>std::quoted(ao)>>std::quoted(em);
241 mat->SetTexture(LoadTex(a,p));mat->UseTexture()=use&&mat->GetTexture();
242 mat->SetNormalTexture(LoadTex(n,p));mat->SetMetallicTexture(LoadTex(me,p));mat->SetRoughnessTexture(LoadTex(r,p));
243 mat->SetAOTexture(LoadTex(ao,p));mat->SetEmissiveTexture(LoadTex(em,p));mats.push_back(mat);
244 }
245 if(!mats.empty()) e.AddComponent<MeshRendererComponent>().SetMaterials(std::move(mats));
246 }
247 }
248 auto& tr=e.GetComponent<TransformComponent>();tr.Position=pos;tr.Rotation=rot;tr.Scale=sc;
249 if(!meshPath.empty()){
250 try{e.AddComponent<MeshComponent>(meshPath=="CUBE"?fallback:AssetManager::LoadMesh(meshPath));}
251 catch(...){Log::Warn("Prefab mesh load failed; using fallback mesh.");if(fallback)e.AddComponent<MeshComponent>(fallback);}
252 }
253 if(!animationPath.empty()){
254 try{
255 const auto resolvedAnimationPath =
256 AssetManager::ResolveProjectPath(std::filesystem::path(animationPath));
257 auto animation=AnimationAsset::Load(resolvedAnimationPath);
258 if(animation&&animation->HasAnimations()){
259 AnimatorComponent animator;
260 animator.Animation=std::move(animation);
261 animator.ClipIndex=std::clamp(animationClip,0,(int)animator.Animation->Clips().size()-1);
262 animator.TimeSeconds=0.0f;
263 animator.Speed=animationSpeed;
264 animator.Playing=animationPlaying;
265 animator.Loop=animationLoop;
266 e.AddComponent<AnimatorComponent>(std::move(animator));
267 }
268 }catch(...){Log::Warn("Prefab animation load failed: " + animationPath);}
269 }
270 if(hasAudioSource)e.AddComponent<AudioSourceComponent>(std::move(audioSource));
271 if(hasAudioListener)e.AddComponent<AudioListenerComponent>(audioListener);
272 if(hasParticleSystem)e.AddComponent<ParticleSystemComponent>(particleSystem);
273 if(hasScript)e.AddComponent<NativeScriptComponent>(std::move(nativeScript));
274 if(parent>=0&&made.contains(parent))s.SetParent(e,made[parent],false);
275 }
276 if(root)root.AddComponent<PrefabInstanceComponent>(PrefabInstanceComponent{p.generic_string(),true});
277 return root;
278}
279bool PrefabSerializer::Apply(Entity instance,const std::filesystem::path& p){return Save(instance,p);}
280
281Entity PrefabSerializer::Revert(Entity instance,const std::shared_ptr<Mesh>& fallback,const std::shared_ptr<Material>& base)
282{
283 if(!instance || !instance.HasComponent<PrefabInstanceComponent>()) return {};
284 Scene* scene=instance.m_Scene;
285 const auto source=instance.GetComponent<PrefabInstanceComponent>().SourcePath;
286 Entity parent=scene->GetParent(instance);
287
288 // Destroy the whole current instance hierarchy. Scene::DestroyEntity normally
289 // preserves children as roots, which is not what prefab Revert should do.
290 std::function<void(Entity)> destroyTree=[&](Entity e){
291 auto children=scene->GetChildren(e);
292 for(Entity child:children) destroyTree(child);
293 scene->DestroyEntity(e);
294 };
295 destroyTree(instance);
296
297 Entity fresh=Instantiate(*scene,source,fallback,base);
298 if(fresh && parent) scene->SetParent(fresh,parent,false);
299 return fresh;
300}
301}
Animation declarations for the Animation subsystem.
AssetManager declarations for the Asset subsystem.
Components declarations for the Scenes and Native Scripting subsystem.
Log declarations for the Core subsystem.
Material declarations for the Rendering subsystem.
PrefabSerializer declarations for the Asset Management subsystem.
Scene declarations for the Scenes and Native Scripting subsystem.
Texture declarations for the Rendering subsystem.
static std::shared_ptr< AnimationAsset > Load(const std::filesystem::path &path)
Definition Animation.cpp:24
static std::filesystem::path GetTexturePath(const std::shared_ptr< Texture2D > &texture)
static std::shared_ptr< Mesh > LoadMesh(const std::filesystem::path &path)
static std::shared_ptr< Texture2D > LoadTexture(const std::filesystem::path &path)
static std::filesystem::path GetMeshPath(const std::shared_ptr< Mesh > &mesh)
static std::filesystem::path ResolveProjectPath(const std::filesystem::path &path)
T & GetComponent()
Definition Scene.h:851
T & AddComponent(Args &&... args)
Definition Scene.h:836
bool HasComponent() const
Definition Scene.h:865
static void Warn(std::string_view message)
Definition Log.h:18
static Entity Instantiate(Scene &, const std::filesystem::path &, const std::shared_ptr< Mesh > &, const std::shared_ptr< Material > &)
static Entity Revert(Entity instance, const std::shared_ptr< Mesh > &fallback, const std::shared_ptr< Material > &base)
static bool Apply(Entity instance, const std::filesystem::path &)
static bool Save(Entity root, const std::filesystem::path &)
bool SetParent(Entity child, Entity parent, bool keepWorldTransform=true)
Definition Scene.cpp:1610
Entity GetParent(Entity entity)
Definition Scene.cpp:1522
std::vector< Entity > GetChildren(Entity entity)
Definition Scene.cpp:1545
Entity CreateEntity(const std::string &name="Entity")
Definition Scene.cpp:133
void DestroyEntity(Entity entity)
Definition Scene.cpp:161
ParticleBlendMode
Definition Components.h:164
MaterialSurfaceMode
Definition Material.h:16
ParticleShape
Definition Components.h:163
ScriptFieldType
Definition Components.h:297
std::shared_ptr< AnimationAsset > Animation
Definition Components.h:325
std::shared_ptr< Mesh > MeshAsset
Definition Components.h:341
std::vector< std::shared_ptr< Material > > Materials
Definition Components.h:347
std::unordered_map< std::string, ScriptFieldValue > Fields
Definition Components.h:319
ParticleBlendMode BlendMode
Definition Components.h:189
ScriptFieldType Type
Definition Components.h:301