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