-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscene.lua
More file actions
104 lines (88 loc) · 2.78 KB
/
scene.lua
File metadata and controls
104 lines (88 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
local json = require("dkjson")
local SceneSerializer = {}
function SceneSerializer.SaveScene(scene, filepath)
local jscene = {
entities = {}
}
for id, entity in pairs(scene:GetAllEntities()) do
local jent = {
id = entity.id,
name = entity.name,
position = {
entity.transform.position[1],
entity.transform.position[2],
entity.transform.position[3]
},
rotation = {
entity.transform.rotation[1],
entity.transform.rotation[2],
entity.transform.rotation[3]
},
scale = {
entity.transform.scale[1],
entity.transform.scale[2],
entity.transform.scale[3]
}
}
-- Check for MeshComponent
local mesh = entity:GetComponent("MeshComponent")
if mesh then
jent.mesh = mesh.meshPath
end
-- Check for RigidBodyComponent
local rb = entity:GetComponent("RigidBodyComponent")
if rb then
jent.rigidbody = {
mass = rb.mass,
isStatic = rb.isStatic
}
end
table.insert(jscene.entities, jent)
end
-- Write to file
local file = io.open(filepath, "w")
if file then
local encoded = json.encode(jscene, { indent = true })
file:write(encoded)
file:close()
end
end
function SceneSerializer.LoadScene(scene, filepath)
local file = io.open(filepath, "r")
if not file then
return
end
local content = file:read("*all")
file:close()
local jscene = json.decode(content)
if not jscene then
return
end
scene:Clear()
for _, jent in ipairs(jscene.entities) do
local id = scene:CreateEntity(jent.name)
local e = scene:GetEntity(id)
-- Set transform
for i = 1, 3 do
e.transform.position[i] = jent.position[i]
e.transform.rotation[i] = jent.rotation[i]
e.transform.scale[i] = jent.scale[i]
end
-- Add MeshComponent if exists
if jent.mesh then
local mesh = {
meshPath = jent.mesh
}
e:AddComponent("MeshComponent", mesh)
end
-- Add RigidBodyComponent if exists
if jent.rigidbody then
local rb = {
mass = jent.rigidbody.mass,
isStatic = jent.rigidbody.isStatic
}
e:AddComponent("RigidBodyComponent", rb)
end
end
end
return SceneSerializer