-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.js
More file actions
68 lines (56 loc) · 2.06 KB
/
encoder.js
File metadata and controls
68 lines (56 loc) · 2.06 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
import FIELDS from './data/fields'
// Class Encoder is the part that transforms an object into actual Slope code
class Encoder {
// encode transforms an object into Slope code
// The entry object must be close to what the parser returns
encode(data) {
this.checkRequired(data)
this.code = ''
this.appendInstruction('Slope', 1)
this.appendInstruction('Name', data.name)
this.appendInstruction('Desc', data.description)
this.appendInstruction('Grade', data.grade)
if (data.grid !== undefined)
this.appendInstruction('Grid', `${data.grid.width} ${data.grid.height}`)
let meta = []
Object.keys(data.meta).forEach(instruction => {
meta.push({
name: instruction,
value: data.meta[instruction]
})
})
this.appendBlock('Meta', '', meta)
data.holds.forEach(hold => {
this.appendBlock('Hold', hold.type, [
{ name: 'Pos', value: `${hold.position.x} ${hold.position.y} ${hold.position.z}` },
{ name: 'Rotation', value: `${hold.rotation.x} ${hold.rotation.y} ${hold.rotation.z}` },
{ name: 'Scale', value: `${hold.scale.x} ${hold.scale.y} ${hold.scale.z}` }
])
})
return this.code
}
// appendInstruction adds an instruction to the code
appendInstruction(instruction, value) {
this.code += `${instruction} ${value}\n`
}
// appendBlock adds a block with its instructions to the code
appendBlock(name, params, instructions) {
this.appendInstruction(name, `${params} (`)
instructions.forEach(instruction => {
this.appendInstruction(` ${instruction.name}`, instruction.value)
})
this.code += `)\n\n`
}
// checkRequired checks in the object if all the required fields are here
checkRequired(data) {
for (const field of FIELDS) {
if (!Object.keys(data).includes(field))
this.croak(`At least one ${name} instruction is required. Please insert one to make your code correct.`)
}
}
// croak throws an error
croak(message) {
throw new Error(`Error in encoding Slope data: ${message}`)
}
}
export default Encoder