SceneMeta.java 2.38 KB
Newer Older
Akka's avatar
Akka committed
1
2
package emu.grasscutter.scripts.data;

3
4
import com.github.davidmoten.rtreemulti.RTree;
import com.github.davidmoten.rtreemulti.geometry.Geometry;
Akka's avatar
Akka committed
5
6
7
import emu.grasscutter.Grasscutter;
import emu.grasscutter.scripts.SceneIndexManager;
import emu.grasscutter.scripts.ScriptLoader;
Akka's avatar
Akka committed
8
9
import lombok.Setter;
import lombok.ToString;
Akka's avatar
Akka committed
10
11
12
13
14
15
16
17
18
19

import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static emu.grasscutter.Configuration.SCRIPT;

Akka's avatar
Akka committed
20
21
@ToString
@Setter
Akka's avatar
Akka committed
22
23
24
25
26
27
28
public class SceneMeta {

    public SceneConfig config;
    public Map<Integer, SceneBlock> blocks;

    public Bindings context;

29
    public RTree<SceneBlock, Geometry> sceneBlockIndex;
Akka's avatar
Akka committed
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

    public static SceneMeta of(int sceneId) {
        return new SceneMeta().load(sceneId);
    }

    public SceneMeta load(int sceneId){
        // Get compiled script if cached
        CompiledScript cs = ScriptLoader.getScriptByPath(
                SCRIPT("Scene/" + sceneId + "/scene" + sceneId + "." + ScriptLoader.getScriptType()));

        if (cs == null) {
            Grasscutter.getLogger().warn("No script found for scene " + sceneId);
            return null;
        }

        // Create bindings
        context = ScriptLoader.getEngine().createBindings();

        // Eval script
        try {
            cs.eval(context);

            this.config = ScriptLoader.getSerializer().toObject(SceneConfig.class, context.get("scene_config"));

            // TODO optimize later
            // Create blocks
            List<Integer> blockIds = ScriptLoader.getSerializer().toList(Integer.class, context.get("blocks"));
            List<SceneBlock> blocks = ScriptLoader.getSerializer().toList(SceneBlock.class, context.get("block_rects"));

            for (int i = 0; i < blocks.size(); i++) {
                SceneBlock block = blocks.get(i);
                block.id = blockIds.get(i);

            }

            this.blocks = blocks.stream().collect(Collectors.toMap(b -> b.id, b -> b));
66
67
            this.sceneBlockIndex = SceneIndexManager.buildIndex(2, blocks, SceneBlock::toRectangle);

Akka's avatar
Akka committed
68
69
70
71
72
73
74
75
        } catch (ScriptException e) {
            Grasscutter.getLogger().error("Error running script", e);
            return null;
        }
        Grasscutter.getLogger().info("scene {} metadata is loaded successfully.", sceneId);
        return this;
    }
}