]> git.localhorst.tv Git - blank.git/blob - src/shared/cli.cpp
less restrictive teleport command
[blank.git] / src / shared / cli.cpp
1 #include "CLI.hpp"
2 #include "CLIContext.hpp"
3 #include "commands.hpp"
4
5 #include "../io/TokenStreamReader.hpp"
6 #include "../world/Entity.hpp"
7 #include "../world/Player.hpp"
8
9 #include <iostream>
10 #include <sstream>
11 #include <glm/gtx/io.hpp>
12
13 using namespace std;
14
15
16 namespace blank {
17
18 CLI::CLI(World &world)
19 : world(world)
20 , commands() {
21         AddCommand("tp", new TeleportCommand);
22 }
23
24 CLI::~CLI() {
25         for (auto &entry : commands) {
26                 delete entry.second;
27         }
28 }
29
30 void CLI::AddCommand(const string &name, Command *cmd) {
31         commands[name] = cmd;
32 }
33
34 void CLI::Execute(CLIContext &ctx, const string &line) {
35         stringstream s(line);
36         TokenStreamReader args(s);
37         if (!args.HasMore()) {
38                 // ignore empty command line
39                 return;
40         }
41         if (args.Peek().type != Token::IDENTIFIER) {
42                 ctx.Error("I don't understand");
43                 return;
44         }
45         string name;
46         args.ReadIdentifier(name);
47         auto entry = commands.find(name);
48         if (entry == commands.end()) {
49                 ctx.Error(name + ": command not found");
50                 return;
51         }
52         try {
53                 entry->second->Execute(*this, ctx, args);
54         } catch (exception &e) {
55                 ctx.Error(name + ": " + e.what());
56         } catch (...) {
57                 ctx.Error(name + ": unknown execution error");
58         }
59 }
60
61 CLI::Command::~Command() {
62
63 }
64
65
66 CLIContext::CLIContext(Player *p, Entity *e)
67 : original_player(p)
68 , effective_player(p)
69 , original_entity(e)
70 , effective_entity(e) {
71         if (!e && p) {
72                 original_entity = effective_entity = &p->GetEntity();
73         }
74 }
75
76
77 void TeleportCommand::Execute(CLI &, CLIContext &ctx, TokenStreamReader &args) {
78         if (!ctx.HasEntity()) {
79                 ctx.Error("teleport needs entity to operate on");
80                 return;
81         }
82
83         glm::vec3 pos(args.GetFloat(), args.GetFloat(), args.GetFloat());
84         EntityState state = ctx.GetEntity().GetState();
85         state.pos = ExactLocation(pos).Sanitize();
86         ctx.GetEntity().SetState(state);
87
88         stringstream msg;
89         msg << ctx.GetEntity().Name() << " teleported to " << pos;
90         ctx.Broadcast(msg.str());
91 }
92
93 }