├── run.sh ├── setup.sh ├── .gitignore ├── server.conf ├── src ├── mc_erl.app.src ├── mc_erl_server_sup.erl ├── mc_erl_app.erl ├── records.hrl ├── mc_erl_chunk_generator.erl ├── mc_erl_chat.erl ├── mc_erl_config.erl ├── mc_erl_server.erl ├── mc_erl_player_core.erl ├── mc_erl_dropped_item.erl ├── mc_erl_entity_manager.erl ├── mc_erl_blocks.erl ├── mc_erl_inventory.erl ├── mc_erl_chunk_manager.erl ├── mc_erl_packets.erl ├── mc_erl_protocol.erl └── mc_erl_player_logic.erl ├── apps.config ├── rebar.config ├── README.md ├── Makefile └── LICENSE.txt /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | erl -pa ./ebin ./deps/*/ebin -config apps.config -s mc_erl_app os_run 3 | -------------------------------------------------------------------------------- /setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | echo "setting up database..." 4 | erl -pa ./ebin -pa deps/*/ebin -config apps.config -s mc_erl_app os_setup 5 | 6 | echo "done!" 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.app 3 | *.beam 4 | *.dump 5 | *.log 6 | *.log.* 7 | *.swp 8 | *.zip 9 | 10 | .deps_plt 11 | key 12 | key.pub 13 | ebin/* 14 | deps/* 15 | Mnesia.* 16 | .eunit/* 17 | -------------------------------------------------------------------------------- /server.conf: -------------------------------------------------------------------------------- 1 | % The tcp port the server binds to. 2 | {port, 25565}. 3 | 4 | {description, "a ...err... lang server!"}. 5 | 6 | {motd, "Welcome to mc-erl, a custom Minecraft server written in Erlang! Feel free to build anything!"}. 7 | 8 | -------------------------------------------------------------------------------- /src/mc_erl.app.src: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Gregory Fefelov, Feiko Nanninga 2 | 3 | {application, mc_erl, 4 | [ 5 | {mod, {mc_erl_app, []}}, 6 | {description, "minecraft server"}, 7 | {vsn, "1"}, 8 | %{modules, []}, % added by rebar 9 | {registered, []}, 10 | {applications, [kernel, stdlib, lager, mnesia, cutkey]} 11 | ] 12 | }. 13 | -------------------------------------------------------------------------------- /apps.config: -------------------------------------------------------------------------------- 1 | [{lager, [{colored, true}, 2 | {handlers, 3 | [{lager_console_backend, 4 | [info, 5 | {lager_default_formatter, 6 | [time," [",severity,"] ", {module, [module, ": "], ""}, 7 | message, "\n"]}]}, 8 | {lager_file_backend, [{file, "error.log"}, {level, error}]}, 9 | {lager_file_backend, [{file, "console.log"}, {level, info}]} 10 | ]} 11 | ]}]. 12 | 13 | % vim: set filetype=erlang : 14 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {deps, [ 2 | {lager, "2.0.3", {git, "git://github.com/basho/lager.git", 3 | "b6b6cebcb27ccff8acc59ae775acebc2f52e4926"}}, 4 | {cutkey, ".*", {git, "git://github.com/brverbur/cutkey.git", 5 | "599eb463cd5f6f024e182d4bca11f4189d0cf6c9"}}, 6 | {cheatcraft, ".*", {git, "git://github.com/lordnull/CheatCraft.git", 7 | "4d6dcf881218abce0c69cf07b184127c6a1dfd7e"}} 8 | ]}. 9 | 10 | {erl_opts, [ 11 | {parse_transform, lager_transform} 12 | ]}. 13 | -------------------------------------------------------------------------------- /src/mc_erl_server_sup.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2013 Feiko Nanninga 2 | 3 | -module(mc_erl_server_sup). 4 | -behaviour(supervisor). 5 | 6 | -export([start_link/0, shutdown/0, init/1]). 7 | 8 | init(_Args) -> 9 | {ok, {{one_for_one, 3, 15}, 10 | [{mc_erl_config, {mc_erl_config, start_link, []}, 11 | permanent, 2000, worker, [mc_erl_config]}, 12 | {mc_erl_chunk_manager, {mc_erl_chunk_manager, start_link, []}, 13 | permanent, 2000, worker, [mc_erl_chunk_manager]}, 14 | {mc_erl_entity_manager, {mc_erl_entity_manager, start_link, []}, 15 | permanent, 2000, worker, [mc_erl_entity_manager]}, 16 | {mc_erl_server, {mc_erl_server, start_link, []}, 17 | permanent, 2000, worker, [mc_erl_server]} 18 | ]} 19 | }. 20 | 21 | start_link() -> supervisor:start_link(mc_erl_server_sup, []). 22 | shutdown() -> 23 | exit(whereis(?MODULE), shutdown). 24 | -------------------------------------------------------------------------------- /src/mc_erl_app.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_app). 4 | -export([setup/0, start/2, stop/1, os_setup/0, os_run/0]). 5 | 6 | %% initial server setup, needs to be done only once 7 | setup() -> 8 | mc_erl_chunk_manager:setup(). 9 | 10 | ensure_started(App) -> 11 | case application:start(App) of 12 | ok -> ok; 13 | {error, {already_started, App}} -> ok 14 | end. 15 | 16 | start(_StartType, _StartArgs) -> 17 | mc_erl_server_sup:start_link(). 18 | 19 | stop(_State) -> mc_erl_server_sup:shutdown(). 20 | 21 | %% to be called from OS' command line 22 | os_setup() -> 23 | ok = mnesia:create_schema([node()]), 24 | mnesia:start(), 25 | {atomic, ok} = setup(), 26 | mnesia:stop(), 27 | halt(). 28 | 29 | %% to be called from OS' command line 30 | os_run() -> 31 | lager:start(), 32 | ensure_started(mnesia), 33 | ensure_started(cutkey), 34 | ok = application:start(mc_erl). 35 | -------------------------------------------------------------------------------- /src/records.hrl: -------------------------------------------------------------------------------- 1 | 2 | % ====================================================================== 3 | % entities 4 | % ====================================================================== 5 | 6 | %% used for (RAM) entity table 7 | %% eid: [key] 8 | %% name: only used for players [index] 9 | %% type: player|mob|drop|falling_block 10 | %% item_id: hold item for players/mobs, Slot = {ItemId, Count, Metadata} for drops 11 | -record(entity, {eid, name, type, logic, location, item_id = empty}). 12 | 13 | %% used for persistent player table and within player_logic 14 | -record(player, {eid, name, location={0,0,0,0,0}, 15 | inventory=array:new(45, {default, empty}), selected_slot=0, 16 | mode=survival, fly_speed=12, walk_speed=25, can_fly=true}). 17 | 18 | % ====================================================================== 19 | % blocks/chunks 20 | % ====================================================================== 21 | 22 | -record(block_type, {id, name, maxstack=64, placeable=false}). 23 | 24 | -record(chunk_column_data, {full_column, chunks=[], add_data=[], biome}). 25 | -record(chunk_data, {types, metadata, block_light, sky_light}). 26 | 27 | -record(slot, {id, count=1, metadata=0, enchantments=[]}). 28 | -------------------------------------------------------------------------------- /src/mc_erl_chunk_generator.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Feiko Nanninga 2 | 3 | -module(mc_erl_chunk_generator). 4 | 5 | -export([gen_column/1]). 6 | 7 | -include("records.hrl"). 8 | 9 | gen_column({X, Y}) -> 10 | lager:notice("[~w] generated chunk ~p~n", [?MODULE, {chunk, X, Y}]), 11 | EmptyChunk = #chunk_data{types=binary:copy(<<0>>,16*16*16), 12 | metadata=binary:copy(<<0>>,16*16*8), 13 | block_light=binary:copy(<<255>>,16*16*8), 14 | sky_light=binary:copy(<<255>>,16*16*8)}, 15 | BedrockChunk = EmptyChunk#chunk_data{types=list_to_binary([binary:copy(<<7>>,256), 16 | binary:copy(<<1>>,256*15)])}, 17 | StoneChunk = EmptyChunk#chunk_data{types=binary:copy(<<1>>,16*16*16)}, 18 | TopChunk = EmptyChunk#chunk_data{types=list_to_binary([binary:copy(<<3>>,256*15), 19 | binary:copy(<<2>>,256)])}, 20 | #chunk_column_data{full_column=true, 21 | chunks=[{0, BedrockChunk}, 22 | {1, StoneChunk}, 23 | {2, StoneChunk}, 24 | {3, TopChunk}, 25 | {4, EmptyChunk}], 26 | biome=binary:copy(<<0>>,256)}. 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Prerequisites 2 | You'll need an Erlang compiler/vm! If you are on Linux, you can install Erlang using your distribution's package manager. E.g. on Debian/Ubuntu/Linux Mint this will do: 3 | 4 | sudo apt-get install erlang 5 | 6 | You will also need make and rebar, the commonly used Erlang build tool. 7 | 8 | ## Setup 9 | 10 | As we use an Mnesia database for storing data permanently, it has to be set up first. Always keep in mind that the table definitions can change on updates, introducing incompabilities. 11 | 12 | 1. Download (uncompress if necessary) (or use _git clone_) 13 | 2. $ make 14 | 3. $ ./setup.sh 15 | 16 | ### Starting: 17 | $ ./run.sh 18 | 19 | ### Stopping: 20 | Press Ctrl+C twice. 21 | 22 | The server runs at port 25565 (default). The port and other options can be set in "server.conf", restart the server for changes to take effect. 23 | 24 | If you want to talk to me (clonejo), I'm idling in #mcdevs on Freenode. 25 | 26 | ## Feature list 27 | * compatible to Minecraft 1.4.6 28 | * see other players 29 | * see block changes by other players 30 | * protocol encryption 31 | 32 | ### Todo 33 | * proper dropped item handling 34 | * configuration system (see erlconf) 35 | * plugin system 36 | * see player sneaking 37 | * have multiple entity movement routing processes in worlds with high load 38 | * update protocol to 1.7.4 39 | * move protocol implementation out as an external library 40 | -------------------------------------------------------------------------------- /src/mc_erl_chat.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_chat). 4 | 5 | -export([broadcast/1, broadcast/2, to_player/2, filter_message/1, is_valid_nickname/1]). 6 | 7 | -include("records.hrl"). 8 | 9 | -define(ALLOWED_CHARS, " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" 10 | "[\\]^_abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ" 11 | "ø£Ø×ƒáíóúñѪº¿®¬½¼¡«»"). 12 | 13 | broadcast(Player, Message) when is_record(Player, entity) andalso Player#entity.type =:= player -> 14 | broadcast(Player#entity.name ++ ": " ++ Message); 15 | 16 | broadcast(Player, Message) when is_record(Player, player) -> 17 | broadcast(Player#player.name ++ ": " ++ Message). 18 | 19 | broadcast(Message) -> 20 | Players = mc_erl_entity_manager:get_all_players(), 21 | lists:map(fun(Player) -> to_player(Player, filter_message(Message)) end, Players). 22 | 23 | 24 | 25 | %% Receiver = player record or name or pid 26 | to_player(Name, Message) when is_list(Name) andalso length(Name) > 0 -> 27 | Receiver = mc_erl_entity_manager:get_player(Name), 28 | to_player(Receiver, Message); 29 | 30 | to_player(Receiver, Message) when is_record(Receiver, entity) andalso Receiver#entity.type =:= player -> 31 | to_player(Receiver#entity.logic, Message); 32 | 33 | to_player(Logic, Message) when is_pid(Logic) -> 34 | Parts = split_message(Message), 35 | lists:map(fun(Part) -> mc_erl_player_logic:packet(Logic, {chat, Part}) end, Parts). 36 | 37 | is_valid_nickname(Nickname) -> 38 | lists:all(fun(X) -> 39 | ((X >= $a) and (X =< $z)) or ((X >= $A) and (X =< $Z)) or 40 | ((X >= $0) and (X =< $9)) or (X == $-) or (X == $_) end, Nickname). 41 | 42 | filter_message(Message) -> 43 | lists:filter(fun(X) -> lists:member(X, ?ALLOWED_CHARS) end, Message). 44 | 45 | split_message(Message) -> 46 | split_message(Message, []). 47 | 48 | split_message(Message, Output) -> 49 | if length(Message) =< 119 -> 50 | lists:reverse([Message|Output]); 51 | true -> 52 | {Part, Rest} = lists:split(119, Message), 53 | split_message(Rest, [Part|Output]) 54 | end. 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/mc_erl_config.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2013 Feiko Nanninga 2 | 3 | -module(mc_erl_config). 4 | -behaviour(gen_server). 5 | 6 | % gen_server callbacks 7 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). 8 | 9 | % api functions 10 | -export([start_link/0, get/2, set/2, reload/0]). 11 | 12 | -define(CONFIG_FILE, "server.conf"). % change pwd to have the server look elsewhere 13 | 14 | start_link() -> 15 | gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). 16 | 17 | get(Key, Default) -> 18 | gen_server:call(?MODULE, {get, Key, Default}). 19 | 20 | %% not implemented yet 21 | set(Key, Value) -> 22 | gen_server:call(?MODULE, {set, Key, Value}). 23 | 24 | reload() -> 25 | gen_server:cast(?MODULE, reload). 26 | 27 | % gen server stuff 28 | init([]) -> 29 | lager:info("[~s] starting~n", [?MODULE]), 30 | Entries = ets:new(void, [set, private]), 31 | try 32 | load_file(Entries, ?CONFIG_FILE) 33 | catch 34 | error:_ -> lager:critical("[~s] can't access server.conf~n", [?MODULE]) 35 | end, 36 | {ok, Entries}. 37 | 38 | handle_call({get, Key, Default}, _From, Entries) -> 39 | {reply, case ets:lookup(Entries, Key) of 40 | [] -> Default; 41 | [{Key, Value}] -> Value 42 | end, Entries}; 43 | 44 | handle_call(Message, _From, State) -> 45 | case Message of 46 | _ -> 47 | lager:notice("[~s] received call: ~p~n", [?MODULE, Message]), 48 | {noreply, State} 49 | end. 50 | 51 | handle_cast(reload, Entries) -> 52 | load_file(Entries, ?CONFIG_FILE), 53 | {noreply, Entries}; 54 | 55 | handle_cast(Message, State) -> 56 | lager:notice("[~s] received cast: ~p~n", [?MODULE, Message]), 57 | {noreply, State}. 58 | 59 | handle_info(Message, State) -> 60 | case Message of 61 | _ -> 62 | lager:notice("[~s] received info: ~p~n", [?MODULE, Message]), 63 | {noreply, State} 64 | end. 65 | 66 | terminate(_Reason, _State) -> 67 | ok. 68 | 69 | code_change(_OldVsn, State, _Extra) -> 70 | {ok, State}. 71 | 72 | % server internal stuff 73 | 74 | %% overwrites all options used in the config file, other options are NOT deleted! 75 | load_file(Entries, File) -> 76 | {ok, E} = file:consult(File), 77 | lists:map(fun(T) -> ets:insert(Entries, T) end, E). 78 | 79 | 80 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Copyright 2012 Erlware, LLC. All Rights Reserved. 2 | # 3 | # This file is provided to you under the Apache License, 4 | # Version 2.0 (the "License"); you may not use this file 5 | # except in compliance with the License. You may obtain 6 | # a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, 11 | # software distributed under the License is distributed on an 12 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | # KIND, either express or implied. See the License for the 14 | # specific language governing permissions and limitations 15 | # under the License. 16 | # 17 | 18 | ERLFLAGS= -pa $(CURDIR)/.eunit -pa $(CURDIR)/ebin -pa $(CURDIR)/deps/*/ebin 19 | 20 | DEPS_PLT=$(CURDIR)/.deps_plt 21 | DEPS=erts kernel stdlib crypto mnesia public_key 22 | 23 | # ============================================================================= 24 | # Verify that the programs we need to run are installed on this system 25 | # ============================================================================= 26 | ERL = $(shell which erl) 27 | 28 | ifeq ($(ERL),) 29 | $(error "Erlang not available on this system") 30 | endif 31 | 32 | REBAR=$(shell which rebar) 33 | 34 | ifeq ($(REBAR),) 35 | $(error "Rebar not available on this system") 36 | endif 37 | 38 | .PHONY: all compile doc clean test dialyzer typer shell distclean pdf \ 39 | update-deps clean-common-test-data rebuild 40 | 41 | all: deps compile dialyzer test 42 | 43 | # ============================================================================= 44 | # Rules to build the system 45 | # ============================================================================= 46 | 47 | deps: 48 | $(REBAR) get-deps 49 | $(REBAR) compile 50 | 51 | update-deps: 52 | $(REBAR) update-deps 53 | $(REBAR) compile 54 | 55 | compile: 56 | $(REBAR) skip_deps=true compile 57 | 58 | doc: 59 | $(REBAR) skip_deps=true doc 60 | 61 | eunit: compile clean-common-test-data 62 | $(REBAR) skip_deps=true eunit 63 | 64 | test: compile eunit 65 | 66 | $(DEPS_PLT): 67 | @echo Building local plt at $(DEPS_PLT) 68 | @echo 69 | dialyzer --output_plt $(DEPS_PLT) --build_plt \ 70 | --apps $(DEPS) -r deps 71 | 72 | dialyzer: $(DEPS_PLT) 73 | dialyzer --fullpath --plt $(DEPS_PLT) -Wrace_conditions -r ./ebin 74 | 75 | typer: 76 | typer --plt $(DEPS_PLT) -r ./src 77 | 78 | shell: deps compile 79 | # You often want *rebuilt* rebar tests to be available to the 80 | # shell you have to call eunit (to get the tests 81 | # rebuilt). However, eunit runs the tests, which probably 82 | # fails (thats probably why You want them in the shell). This 83 | # runs eunit but tells make to ignore the result. 84 | - @$(REBAR) skip_deps=true eunit 85 | @$(ERL) $(ERLFLAGS) 86 | 87 | pdf: 88 | pandoc README.md -o README.pdf 89 | 90 | clean: 91 | - rm -rf $(CURDIR)/test/*.beam 92 | - rm -rf $(CURDIR)/logs 93 | - rm -rf $(CURDIR)/ebin 94 | $(REBAR) skip_deps=true clean 95 | 96 | distclean: clean 97 | - rm -rf $(DEPS_PLT) 98 | - rm -rvf $(CURDIR)/deps 99 | 100 | rebuild: distclean deps compile escript dialyzer test 101 | -------------------------------------------------------------------------------- /src/mc_erl_server.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_server). 4 | -behaviour(gen_server). 5 | 6 | -export([start_link/0, stop/0]). 7 | 8 | -include("records.hrl"). 9 | 10 | -record(state, {listen, public_key, private_key}). 11 | 12 | -include_lib("public_key/include/OTP-PUB-KEY.hrl"). 13 | 14 | 15 | % gen_server callbacks 16 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). 17 | 18 | start_link() -> 19 | gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). 20 | 21 | stop() -> 22 | gen_server:cast(?MODULE, stop). 23 | 24 | 25 | % gen_server callbacks 26 | init([]) -> 27 | process_flag(trap_exit, true), 28 | lager:info("[~s] starting~n", [?MODULE]), 29 | %PublicKey = read_public_key("key.pub"), 30 | %PrivateKey = read_private_key("key"), 31 | 32 | {ok, PrivateKey} = cutkey:rsa(1024, 65537, [{return, key}]), 33 | #'RSAPrivateKey'{modulus=Modulus, publicExponent=PublicExponent} = PrivateKey, 34 | {'SubjectPublicKeyInfo', PublicKey, not_encrypted} = public_key:pem_entry_encode('SubjectPublicKeyInfo', #'RSAPublicKey'{modulus=Modulus, publicExponent=PublicExponent}), 35 | 36 | Port = mc_erl_config:get(port, 25565), 37 | {ok, Listen} = gen_tcp:listen(Port, [binary, {reuseaddr, true}, {active, false}, 38 | {packet, raw}, {nodelay, true}]), 39 | spawn_link(fun() -> acceptor(Listen) end), 40 | spawn_link(fun() -> ticker() end), 41 | {ok, #state{listen=Listen, public_key=PublicKey, private_key=PrivateKey}}. 42 | 43 | acceptor(Listen) -> 44 | lager:debug("[~s:acceptor] awaiting connection...~n", [?MODULE]), 45 | case gen_tcp:accept(Listen) of 46 | {ok, Socket} -> 47 | gen_server:cast(?MODULE, {new_connection, Socket}), 48 | acceptor(Listen); 49 | {error, closed} -> 50 | ok 51 | end. 52 | 53 | ticker() -> ticker(0). 54 | ticker(Time) -> 55 | gen_server:cast(?MODULE, {tick, Time}), 56 | timer:sleep(50), 57 | ticker(Time+1). 58 | 59 | handle_call(Message, _From, State) -> 60 | lager:notice("[~s] received call: ~p~n", [?MODULE, Message]), 61 | {noreply, State}. 62 | 63 | handle_cast({new_connection, Socket}, State) -> 64 | Pid = proc_lib:start(mc_erl_player_core, init_player, [Socket, State#state.public_key, State#state.private_key]), 65 | gen_tcp:controlling_process(Socket, Pid), 66 | {noreply, State}; 67 | 68 | handle_cast({tick, Time}=Tick, State) when is_integer(Time) -> 69 | mc_erl_entity_manager:broadcast(Tick), 70 | mc_erl_chunk_manager:tick(Time), 71 | {noreply, State}; 72 | 73 | handle_cast(stop, State) -> 74 | lager:info("[~s] stopping~n", [?MODULE]), 75 | {stop, normal, State}; 76 | 77 | handle_cast(Message, State) -> 78 | lager:notice("[~s] received cast: ~p~n", [?MODULE, Message]), 79 | {noreply, State}. 80 | 81 | handle_info(Message, State) -> 82 | lager:notice("[~s] received info: ~p~n", [?MODULE, Message]), 83 | {noreply, State}. 84 | 85 | terminate(Reason, _State) -> 86 | lager:notice("[~s] terminated with Reason=~p~n", [?MODULE, Reason]), 87 | ok. 88 | 89 | code_change(_OldVsn, State, _Extra) -> 90 | {ok, State}. 91 | 92 | -------------------------------------------------------------------------------- /src/mc_erl_player_core.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_player_core). 4 | -export([init_player/3, keep_alive_sender/1, write/2]). 5 | 6 | -include_lib("public_key/include/public_key.hrl"). 7 | 8 | init_player(Socket, PublicKey, PrivateKey) when is_record(PrivateKey, 'RSAPrivateKey') -> 9 | proc_lib:init_ack(self()), 10 | 11 | {ok, Packet} = mc_erl_protocol:decode_packet(Socket), 12 | case Packet of 13 | {server_list_ping, [1] } -> 14 | send(Socket, {disconnect,[lists:flatten([167, "1", 0, 15 | "51", 0, 16 | "1.4.6", 0, 17 | mc_erl_config:get(description, []), 0, 18 | integer_to_list(mc_erl_entity_manager:player_count()), 0, 19 | "101"])]}), 20 | gen_tcp:close(Socket); 21 | 22 | {handshake, [51, Name, _Host, _Port]} -> 23 | lager:notice("[~s] Player joining: ~s~n", [?MODULE, Name]), 24 | 25 | % generate token 26 | Token = crypto:strong_rand_bytes(4), 27 | 28 | % send encryption_key_request 29 | send(Socket, {encryption_key_request, ["-", PublicKey, Token]}), 30 | 31 | % wait for encryption_key_response 32 | {ok, {encryption_key_response, [EncrSymKey, EncrToken]}} = mc_erl_protocol:decode_packet(Socket), 33 | 34 | % check EncrToken 35 | DecrToken = public_key:decrypt_private(EncrToken, PrivateKey), 36 | case Token =:= DecrToken of 37 | true -> 38 | DecrSymKey = public_key:decrypt_private(EncrSymKey, PrivateKey), 39 | send(Socket, {encryption_key_response, [<<>>,<<>>]}), 40 | 41 | % encryption is in effect! 42 | 43 | Writer = proc_lib:spawn_link(fun() -> async_writer(Socket, DecrSymKey, DecrSymKey) end), 44 | Logic = mc_erl_player_logic:start_logic(Writer, Name), 45 | Self = self(), 46 | Decoder = spawn_link(fun() -> decoder(Self, Logic) end), 47 | mc_erl_player_logic:packet(Logic, login_sequence), 48 | 49 | decrypter(Socket, DecrSymKey, DecrSymKey, Decoder); 50 | false -> 51 | send(Socket, {disconnect, ["You suck."]}), 52 | gen_tcp:close(Socket) 53 | end; 54 | {handshake, [_, _, _, _]} -> 55 | send(Socket, {disconnect, ["You're too oldschool! (Wrong client version.)"]}), 56 | gen_tcp:close(Socket) 57 | end. 58 | 59 | decoder(Reader, Logic) when is_pid(Logic) -> 60 | case mc_erl_protocol:decode_packet(Reader) of 61 | {ok, Packet} -> 62 | mc_erl_player_logic:packet(Logic, {packet, Packet}), 63 | decoder(Reader, Logic); 64 | {error, closed} -> 65 | lager:warning("[~s] socket is closed~n", [?MODULE]), 66 | mc_erl_player_logic:packet(Logic, net_disconnect) 67 | end. 68 | 69 | decrypter(Socket, Key, IVec, Decoder) -> 70 | receive 71 | {get_bytes, N} -> 72 | try mc_erl_protocol:decrypt(Socket, Key, IVec, N) of 73 | {Bytes, NewIVec} -> 74 | Decoder ! {bytes, Bytes}, 75 | decrypter(Socket, Key, NewIVec, Decoder) 76 | catch 77 | connection_closed -> 78 | Decoder ! {error, closed} 79 | end 80 | end. 81 | 82 | 83 | % dummy sender, doesn't check for reply 84 | keep_alive_sender(Socket) -> 85 | send(Socket, {keep_alive, [0]}), 86 | receive 87 | {'EXIT', _, _} -> ok 88 | after 1000 -> 89 | keep_alive_sender(Socket) 90 | end. 91 | 92 | % asynchronous writer to pass on to logic 93 | async_writer(Socket, Key, IVec) -> 94 | receive 95 | stop -> 96 | gen_tcp:close(Socket), 97 | ok; 98 | {packet, Data} -> 99 | {PacketName, _} = Data, 100 | Encoded = mc_erl_protocol:encode_packet(Data), 101 | {Encr, NewIVec} = mc_erl_protocol:encrypt(Socket, Key, IVec, Encoded), 102 | gen_tcp:send(Socket, Encr), 103 | async_writer(Socket, Key, NewIVec) 104 | end. 105 | 106 | write(Writer, Packet) -> 107 | Writer ! {packet, Packet}. 108 | 109 | % Packet gets encoded, so unencrypted communication only! 110 | send(Socket, Packet) -> 111 | gen_tcp:send(Socket, mc_erl_protocol:encode_packet(Packet)). 112 | -------------------------------------------------------------------------------- /src/mc_erl_dropped_item.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_dropped_item). 4 | 5 | -export([new/2, spawn/3]). 6 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). 7 | 8 | -record(state, {entity, velocity={0,0,0}, moving=false, last_tick}). 9 | 10 | -include("records.hrl"). 11 | 12 | -define(pick_up_range, 1). % unit: m 13 | -define(gravity_acc, -0.0245). % unit: m/tick^2 14 | -define(life_length, 300). % unit: seconds 15 | 16 | 17 | floor(X) when X < 0 -> 18 | T = trunc(X), 19 | case X - T == 0 of 20 | true -> T; 21 | false -> T - 1 22 | end; 23 | floor(X) -> 24 | trunc(X). 25 | 26 | spawn({X, Y, Z}, {_VX, _VY, _VZ}=InitialVelocity, {_ItemId, _Count, _Metadata}=Data) -> 27 | new(#entity{type=dropped_item, location={X,Y,Z,0,0}, item_id=Data}, InitialVelocity). 28 | 29 | new(Entity, Velocity) when is_record(Entity, entity), Entity#entity.type =:= dropped_item -> 30 | {ok, Pid} = gen_server:start(?MODULE, {Entity, Velocity}, []), 31 | Pid. 32 | 33 | init({Entity, Velocity}) -> 34 | process_flag(trap_exit, true), 35 | erlang:send_after(?life_length * 1000, self(), suicide), 36 | {ok, #state{entity=mc_erl_entity_manager:register_dropped_item(Entity, Velocity), velocity=Velocity, moving=true}}. 37 | 38 | terminate(_Reason, State) -> 39 | mc_erl_entity_manager:delete_entity(State#state.entity), 40 | ok. 41 | 42 | code_change(_OldVsn, State, _Extra) -> 43 | {ok, State}. 44 | 45 | handle_info(suicide, State) -> 46 | {stop, normal, State}; 47 | 48 | handle_info(Info, State) -> 49 | lager:notice("[~s] got unknown info: ~p~n", [?MODULE, Info]), 50 | {noreply, State}. 51 | 52 | handle_call(get_state, _From, State) -> 53 | {reply, State, State}; 54 | 55 | handle_call(Req, _From, State) -> 56 | lager:notice("[~s] got unknown call: ~p~n", [?MODULE, Req]), 57 | {noreply, State}. 58 | 59 | handle_cast(Req, State) -> 60 | MyEntity = State#state.entity, 61 | MyEid = MyEntity#entity.eid, 62 | RetState = case Req of 63 | {tick, Tick} -> 64 | NewState = case State#state.moving of 65 | true -> 66 | {VX, VY, VZ} = State#state.velocity, 67 | {X, Y, Z, _, _} = MyEntity#entity.location, 68 | 69 | NVY = VY + ?gravity_acc, 70 | 71 | {PX, PY, PZ} = {X+VX, Y+NVY, Z+VZ}, 72 | ProposedBlock = {floor(PX), floor(PY), floor(PZ)}, 73 | case mc_erl_chunk_manager:get_block(ProposedBlock) of 74 | {0, _} -> 75 | NewLocation = {PX, PY, PZ, 0, 0}, 76 | NewVelocity = {VX, NVY, VZ}, 77 | IsMoving = true; 78 | _ -> 79 | NewLocation = {X, Y, Z, 0, 0}, 80 | NewVelocity = {0, 0, 0}, 81 | IsMoving = false 82 | end, 83 | 84 | mc_erl_entity_manager:move_entity(MyEid, NewLocation), 85 | State#state{entity=MyEntity#entity{location=NewLocation}, velocity=NewVelocity, moving=IsMoving, last_tick=Tick}; 86 | 87 | false -> 88 | State 89 | end, 90 | UpdatedLocation = NewState#state.entity#entity.location, 91 | if 92 | (Tick rem 20) == 0 -> mc_erl_entity_manager:move_entity(MyEid, UpdatedLocation); 93 | true -> ok 94 | end, 95 | NewState; 96 | 97 | % don't use these for movement simulation, register for events at chunk_manager 98 | {block_delta, _} -> State; 99 | {update_column, _} -> State; 100 | 101 | % adds or removes a player on the player list 102 | {player_list, _Player, _Mode} -> State; 103 | 104 | % === entity messages === 105 | {new_entity, Entity} -> 106 | pick_up_check(Entity, State); 107 | 108 | {delete_entity, Eid} -> 109 | case MyEid =:= Eid of 110 | true -> {stop, normal, entity_deleted}; 111 | false -> State 112 | end; 113 | 114 | {update_entity_position, {Entity}} when is_record(Entity, entity) -> 115 | pick_up_check(Entity, State); 116 | 117 | _UnknownMessage -> 118 | State 119 | end, 120 | case RetState of 121 | % ... 122 | 123 | % right path 124 | Res -> {noreply, Res} 125 | end. 126 | 127 | pick_up_check(Entity, State) when Entity#entity.type =:= player -> 128 | case in_range(Entity#entity.location, State) of 129 | true -> lager:notice("~p: player in range!~n", [State#state.entity#entity.eid]); 130 | false -> ok 131 | end, 132 | State; 133 | pick_up_check(_, State) -> State. 134 | 135 | % ==== Checks if (a player's) location is in pick up range 136 | in_range({X, Y, Z, _, _}, State) -> 137 | {MyX, MyY, MyZ, _, _} = State#state.entity#entity.location, 138 | math:sqrt(math:pow(MyX-X,2) + math:pow(MyY-Y,2) + math:pow(MyZ-Z,2)) < ?pick_up_range. 139 | 140 | 141 | -------------------------------------------------------------------------------- /src/mc_erl_entity_manager.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_entity_manager). 4 | -behaviour(gen_server). 5 | 6 | -export([start_link/0, stop/0, register_player/1, delete_player/1, register_dropped_item/2, 7 | move_entity/2, delete_entity/1, entity_details/1, get_all_entities/0, get_all_players/0, 8 | get_player/1, player_count/0, broadcast/1, broadcast_local/2, broadcast_visible/2]). 9 | -define(dev, void). 10 | -include("records.hrl"). 11 | 12 | % gen_server callbacks 13 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). 14 | 15 | -record(state, {next_eid=0}). 16 | 17 | start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). 18 | stop() -> gen_server:cast(?MODULE, stop). 19 | 20 | register_player(Player) -> gen_server:call(?MODULE, {register_player, Player, self()}). 21 | delete_player(Player) when is_record(Player, player) orelse is_list(Player) -> gen_server:call(?MODULE, {delete_player, Player}). 22 | 23 | register_dropped_item(Entity, Velocity) when is_record(Entity, entity)-> gen_server:call(?MODULE, {register_dropped_item, Entity, Velocity, self()}). 24 | 25 | move_entity(Eid, {_X, _Y, _Z, _Pitch, _Yaw}=NewLocation) -> 26 | case entity_details(Eid) of 27 | undefined -> delete_entity(Eid); 28 | Entity -> 29 | NewEntity = Entity#entity{location=NewLocation}, 30 | {atomic, ok} = mnesia:transaction(fun() -> mnesia:write(NewEntity) end), 31 | broadcast({update_entity_position, {NewEntity}}) 32 | end. 33 | 34 | delete_entity(Entity) when is_record(Entity, entity) -> delete_entity(Entity#entity.eid); 35 | delete_entity(Eid) when is_integer(Eid) -> 36 | broadcast({delete_entity, Eid}), 37 | {atomic, ok} = mnesia:transaction(fun() -> mnesia:delete({entity, Eid}) end), 38 | ok. 39 | 40 | get_all_players() -> 41 | {atomic, Players} = mnesia:transaction(fun() -> mnesia:match_object(#entity{type=player, _='_'}) end), 42 | Players. 43 | 44 | player_count() -> 45 | length(get_all_players()). 46 | 47 | get_all_entities() -> 48 | {atomic, Entities} = mnesia:transaction(fun() -> mnesia:match_object(#entity{_='_'}) end), 49 | Entities. 50 | 51 | get_player(Name) when is_list(Name), length(Name) > 0 -> 52 | {atomic, PlayerL} = mnesia:transaction(fun() -> mnesia:index_read(entity, Name, #entity.name) end), 53 | PlayerL. 54 | 55 | entity_details(Eid) -> 56 | case mnesia:transaction(fun() -> mnesia:read(entity, Eid) end) of 57 | {atomic, [Entity]} -> Entity; 58 | {atomic, []} -> undefined 59 | end. 60 | 61 | broadcast(Message) -> 62 | lists:map(fun(X) -> mc_erl_player_logic:packet(X#entity.logic, Message) end, get_all_entities()). 63 | 64 | broadcast_local(_Eid, Message) -> % a placeholder for a real local-only event 65 | broadcast(Message). 66 | 67 | broadcast_visible({_X, _Y, _Z}, Message) -> % a placeholder for a ranged event 68 | broadcast(Message). 69 | 70 | % gen_server callbacks 71 | init([]) -> 72 | lager:info("[~s] starting~n", [?MODULE]), 73 | %Entities = ets:new(entities, [set, private]), 74 | case mnesia:create_table(entity, [{attributes, record_info(fields, entity)}, 75 | {type, set}, {index, [name]}]) of 76 | {atomic, ok} -> ok; 77 | {aborted,{already_exists,entity}} -> ok 78 | end, 79 | {ok, #state{}}. 80 | 81 | handle_call({register_player, Player, Logic}, _From, State) when is_record(Player, player), is_pid(Logic) -> 82 | Eid = State#state.next_eid, 83 | NewPlayer = escape_player_name(Player#player{eid=Eid}, Eid), 84 | case get_player(NewPlayer#player.name) of 85 | [_] -> {reply, {error, name_in_use}, State}; 86 | [] -> 87 | Entity = #entity{eid=Eid, name=NewPlayer#player.name, type=player, logic=Logic, location = NewPlayer#player.location}, 88 | {atomic, ok} = mnesia:transaction(fun() -> mnesia:write(Entity) end), 89 | broadcast({new_entity, Entity}), 90 | {reply, NewPlayer, State#state{next_eid=Eid+1}} 91 | end; 92 | 93 | handle_call({delete_player, Name}, _From, State) when is_list(Name) -> 94 | case get_player(Name) of 95 | [Player] -> 96 | broadcast({delete_entity, Player#entity.eid}), 97 | 98 | {atomic, ok} = mnesia:transaction(fun() -> mnesia:delete({entity, Player#entity.eid}) end), 99 | {reply, ok, State}; 100 | [] -> 101 | {reply, name_not_found, State} 102 | end; 103 | 104 | handle_call({delete_player, Player}, _From, State) when is_record(Player, player) -> 105 | case entity_details(Player#player.eid) of 106 | undefined -> ok; 107 | Entity -> broadcast({delete_entity, Entity#entity.eid}) 108 | end, 109 | case mnesia:transaction(fun() -> mnesia:delete({entity, Player#player.eid}) end) of 110 | {atomic, ok} -> {reply, ok, State}; 111 | {aborted, _} -> {reply, not_found, State} 112 | end; 113 | 114 | % register_dropped_item 115 | handle_call({register_dropped_item, Entity, InitialVelocity, Logic}, _From, State) -> 116 | Eid = State#state.next_eid, 117 | NewEntity = Entity#entity{eid=Eid, logic=Logic}, 118 | {atomic, ok} = mnesia:transaction(fun() -> mnesia:write(NewEntity) end), 119 | broadcast({new_entity, NewEntity}), 120 | broadcast({set_entity_speed, NewEntity, InitialVelocity}), 121 | {reply, NewEntity, State#state{next_eid=Eid+1}}; 122 | 123 | handle_call(Message, _From, State) -> 124 | case Message of 125 | _ -> 126 | lager:notice("[~s] received call: ~p~n", [?MODULE, Message]), 127 | {noreply, State} 128 | end. 129 | 130 | handle_cast(stop, State) -> 131 | lager:info("[~s] stopping~n", [?MODULE]), 132 | {stop, normal, State}; 133 | 134 | handle_cast(Message, State) -> 135 | lager:notice("[~s] received cast: ~p~n", [?MODULE, Message]), 136 | {noreply, State}. 137 | 138 | handle_info(Message, State) -> 139 | case Message of 140 | _ -> 141 | lager:notice("[~s] received info: ~p~n", [?MODULE, Message]), 142 | {noreply, State} 143 | end. 144 | 145 | terminate(_Reason, _State) -> 146 | ok. 147 | 148 | code_change(_OldVsn, State, _Extra) -> 149 | {ok, State}. 150 | 151 | 152 | -ifdef(dev). 153 | escape_player_name(Player, Eid) -> 154 | Player#player{name=Player#player.name ++ "#" ++ integer_to_list(Eid)}. 155 | -else. 156 | escape_player_name(Player, _Eid) -> 157 | Player. 158 | -endif. 159 | 160 | -------------------------------------------------------------------------------- /src/mc_erl_blocks.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_blocks). 4 | 5 | -export([block_info/1, can_build/1]). 6 | 7 | -include("records.hrl"). 8 | 9 | %% currently only lists blocks placeable in creative 10 | block_info(Id) -> 11 | case Id of 12 | 0 -> #block_type{id= 0, name="air", placeable=true}; 13 | 1 -> #block_type{id= 1, name="stone", placeable=true}; 14 | 2 -> #block_type{id= 2, name="grass", placeable=true}; 15 | 3 -> #block_type{id= 3, name="dirt", placeable=true}; 16 | 4 -> #block_type{id= 4, name="cobblestone", placeable=true}; 17 | 5 -> #block_type{id= 5, name="wooden planks", placeable=true}; 18 | 6 -> #block_type{id= 6, name="saplings", placeable=true}; 19 | 7 -> #block_type{id= 7, name="bedrock", placeable=true}; 20 | 12 -> #block_type{id= 12, name="sand", placeable=true}; 21 | 13 -> #block_type{id= 13, name="gravel", placeable=true}; 22 | 14 -> #block_type{id= 14, name="gold ore", placeable=true}; 23 | 15 -> #block_type{id= 15, name="iron ore", placeable=true}; 24 | 16 -> #block_type{id= 16, name="coal ore", placeable=true}; 25 | 17 -> #block_type{id= 17, name="wood", placeable=true}; 26 | 18 -> #block_type{id= 18, name="leaves", placeable=true}; 27 | 19 -> #block_type{id= 19, name="sponge", placeable=true}; 28 | 20 -> #block_type{id= 20, name="glass", placeable=true}; 29 | 21 -> #block_type{id= 21, name="lapis lazuli ore", placeable=true}; 30 | 22 -> #block_type{id= 22, name="lapis lazuli block", placeable=true}; 31 | 23 -> #block_type{id= 23, name="dispenser", placeable=true}; 32 | 24 -> #block_type{id= 24, name="sandstone", placeable=true}; 33 | 25 -> #block_type{id= 25, name="note block", placeable=true}; 34 | 27 -> #block_type{id= 27, name="powered rail", placeable=true}; 35 | 28 -> #block_type{id= 28, name="detector rail", placeable=true}; 36 | 29 -> #block_type{id= 29, name="sticky piston", placeable=true}; 37 | 30 -> #block_type{id= 30, name="cobweb", placeable=true}; 38 | 31 -> #block_type{id= 31, name="tall grass", placeable=true}; 39 | 32 -> #block_type{id= 32, name="dead bush", placeable=true}; 40 | 33 -> #block_type{id= 33, name="piston", placeable=true}; 41 | 35 -> #block_type{id= 35, name="wool", placeable=true}; 42 | 37 -> #block_type{id= 37, name="dandelion", placeable=true}; 43 | 38 -> #block_type{id= 38, name="rose", placeable=true}; 44 | 39 -> #block_type{id= 39, name="brown mushroom", placeable=true}; 45 | 40 -> #block_type{id= 40, name="red mushroom", placeable=true}; 46 | 41 -> #block_type{id= 41, name="gold block", placeable=true}; 47 | 42 -> #block_type{id= 42, name="iron block", placeable=true}; 48 | 44 -> #block_type{id= 44, name="slabs", placeable=true}; 49 | 45 -> #block_type{id= 45, name="bricks", placeable=true}; 50 | 46 -> #block_type{id= 46, name="tnt", placeable=true}; 51 | 47 -> #block_type{id= 47, name="bookshelf", placeable=true}; 52 | 48 -> #block_type{id= 48, name="moss stone", placeable=true}; 53 | 49 -> #block_type{id= 49, name="obsidian", placeable=true}; 54 | 50 -> #block_type{id= 50, name="torch", placeable=true}; 55 | 53 -> #block_type{id= 53, name="wooden stairs", placeable=true}; 56 | 54 -> #block_type{id= 54, name="chest", placeable=true}; 57 | 56 -> #block_type{id= 56, name="diamond ore", placeable=true}; 58 | 57 -> #block_type{id= 57, name="diamond block", placeable=true}; 59 | 58 -> #block_type{id= 58, name="crafting table", placeable=true}; 60 | 61 -> #block_type{id= 61, name="furnace", placeable=true}; 61 | 65 -> #block_type{id= 65, name="ladders", placeable=true}; 62 | 66 -> #block_type{id= 66, name="rails", placeable=true}; 63 | 67 -> #block_type{id= 67, name="cobblestone stairs", placeable=true}; 64 | 69 -> #block_type{id= 69, name="lever", placeable=true}; 65 | 70 -> #block_type{id= 70, name="stone pressure plate", placeable=true}; 66 | 72 -> #block_type{id= 72, name="wooden pressure plate", placeable=true}; 67 | 73 -> #block_type{id= 73, name="redstone ore", placeable=true}; 68 | 76 -> #block_type{id= 76, name="redstone torch", placeable=true}; 69 | 77 -> #block_type{id= 77, name="stone button", placeable=true}; 70 | 79 -> #block_type{id= 79, name="ice", placeable=true}; 71 | 80 -> #block_type{id= 80, name="snow block", placeable=true}; 72 | 81 -> #block_type{id= 81, name="cactus", placeable=true}; 73 | 82 -> #block_type{id= 82, name="clay block", placeable=true}; 74 | 84 -> #block_type{id= 84, name="jukebox", placeable=true}; 75 | 85 -> #block_type{id= 85, name="fence", placeable=true}; 76 | 86 -> #block_type{id= 86, name="pumpkin", placeable=true}; 77 | 87 -> #block_type{id= 87, name="netherrack", placeable=true}; 78 | 88 -> #block_type{id= 88, name="soul sand", placeable=true}; 79 | 89 -> #block_type{id= 89, name="glowstoneg block", placeable=true}; 80 | 91 -> #block_type{id= 91, name="jack-o-lantern", placeable=true}; 81 | 96 -> #block_type{id= 96, name="trapdoor", placeable=true}; 82 | 98 -> #block_type{id= 98, name="stone bricks", placeable=true}; 83 | 101 -> #block_type{id=101, name="iron bars", placeable=true}; 84 | 102 -> #block_type{id=102, name="glass pane", placeable=true}; 85 | 103 -> #block_type{id=103, name="melon", placeable=true}; 86 | 106 -> #block_type{id=106, name="vines", placeable=true}; 87 | 107 -> #block_type{id=107, name="fence gate", placeable=true}; 88 | 108 -> #block_type{id=108, name="brick stairs", placeable=true}; 89 | 109 -> #block_type{id=109, name="stone brick stairs", placeable=true}; 90 | 110 -> #block_type{id=110, name="mycelium", placeable=true}; 91 | 111 -> #block_type{id=111, name="lily pad", placeable=true}; 92 | 112 -> #block_type{id=112, name="nether brick", placeable=true}; 93 | 113 -> #block_type{id=113, name="nether brick fence", placeable=true}; 94 | 114 -> #block_type{id=114, name="nether brick stairs", placeable=true}; 95 | 116 -> #block_type{id=116, name="enchantment table", placeable=true}; 96 | 121 -> #block_type{id=121, name="end stone", placeable=true}; 97 | 122 -> #block_type{id=122, name="dragon egg", placeable=true}; 98 | 123 -> #block_type{id=123, name="redstone lamp", placeable=true}; 99 | _ -> #block_type{} 100 | end. 101 | 102 | can_build(Id) -> 103 | (block_info(Id))#block_type.placeable. 104 | -------------------------------------------------------------------------------- /src/mc_erl_inventory.erl: -------------------------------------------------------------------------------- 1 | % @copyright 2014 Feiko Nanninga 2 | 3 | -module(mc_erl_inventory). 4 | 5 | -export([get_slot/2, send_inventory/2, inventory_add/3, inventory_add/5, 6 | items_equal/2, inventory_add_to_stack/4, update_slot/4]). 7 | 8 | -include("records.hrl"). 9 | 10 | send_inventory(Writer, Inv) -> 11 | mc_erl_player_core:write(Writer, {window_items, [0, array:to_list(Inv)]}). 12 | 13 | %% action = reduce | {replace, Slot} | empty 14 | update_slot(Writer, Inv, SlotNo, Action) -> 15 | NewSlot = case Action of 16 | empty -> 17 | empty; 18 | reduce -> 19 | case array:get(SlotNo, Inv) of 20 | empty -> empty; 21 | #slot{count=1} -> empty; 22 | #slot{} = S -> S#slot{count=S#slot.count-1} 23 | end; 24 | {replace, Slot} -> Slot 25 | end, 26 | NewInv = array:set(SlotNo, NewSlot, Inv), 27 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, NewSlot]}), 28 | NewInv. 29 | 30 | get_slot(Inventory, SlotNo) -> 31 | array:get(SlotNo, Inventory). 32 | 33 | items_equal(empty, empty) -> true; 34 | items_equal(_, empty) -> false; 35 | items_equal(empty, _) -> false; 36 | items_equal(Slot1, Slot2) when is_record(Slot1, slot), is_record(Slot2, slot) -> 37 | Slot1#slot.id =:= Slot2#slot.id 38 | andalso Slot1#slot.metadata =:= Slot2#slot.metadata 39 | andalso Slot1#slot.enchantments =:= Slot2#slot.enchantments. 40 | 41 | inventory_add(Writer, Inv, #slot{}=Slot) -> 42 | inventory_add(Writer, Inv, 9, 44, Slot). 43 | 44 | inventory_add(_Writer, Inventory, _SlotNo, _EndSlot, empty) -> 45 | {Inventory, empty}; 46 | inventory_add(Writer, Inventory, SlotNo, EndSlot, Rest) when EndSlot =:= SlotNo-1 -> 47 | inventory_add_to_free_slot(Writer, Inventory, 9, 44, Rest); 48 | inventory_add(Writer, Inventory, SlotNo, EndSlot, 49 | #slot{id=BlockId, count=Count, metadata=Metadata, 50 | enchantments=Enchantments}=Slot) -> 51 | MaxStack = (mc_erl_blocks:block_info(BlockId))#block_type.maxstack, 52 | case array:get(SlotNo, Inventory) of 53 | #slot{id=BlockId, count=OldCount, metadata=Metadata, 54 | enchantments=Enchantments} -> 55 | if 56 | OldCount >= MaxStack -> 57 | inventory_add(Writer, Inventory, SlotNo+1, EndSlot, Slot); 58 | OldCount+Count > MaxStack -> 59 | NewSlot = Slot#slot{count=MaxStack}, 60 | NewInv = array:set(SlotNo, NewSlot, Inventory), 61 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, NewSlot]}), 62 | RestCount = OldCount+Count - MaxStack, 63 | inventory_add(Writer, NewInv, SlotNo+1, EndSlot, 64 | Slot#slot{count=RestCount}); 65 | true -> 66 | NewSlot = Slot#slot{count=OldCount+Count}, 67 | NewInv = array:set(SlotNo, NewSlot, Inventory), 68 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, NewSlot]}), 69 | {NewInv, empty} 70 | end; 71 | empty -> 72 | if 73 | Count > MaxStack -> 74 | NewSlot = Slot#slot{count=MaxStack}, 75 | NewInv = array:set(SlotNo, NewSlot, Inventory), 76 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, NewSlot]}), 77 | RestCount = Count - MaxStack, 78 | inventory_add(Writer, NewInv, SlotNo+1, EndSlot, 79 | Slot#slot{count=RestCount}); 80 | true -> 81 | NewSlot = Slot#slot{count=Count}, 82 | NewInv = array:set(SlotNo, NewSlot, Inventory), 83 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, NewSlot]}), 84 | {NewInv, empty} 85 | end; 86 | _ -> 87 | inventory_add(Writer, Inventory, SlotNo+1, EndSlot, Slot) 88 | end. 89 | 90 | inventory_add_to_free_slot(_Writer, Inventory, SlotNo, EndSlot, Rest) 91 | when EndSlot =:= SlotNo-1 -> 92 | {Inventory, Rest}; 93 | inventory_add_to_free_slot(Writer, Inventory, SlotNo, EndSlot, 94 | #slot{id=BlockId, count=Count}=Slot) -> 95 | MaxStack = (mc_erl_blocks:block_info(BlockId))#block_type.maxstack, 96 | case array:get(SlotNo, Inventory) of 97 | empty -> 98 | if 99 | Count > MaxStack -> 100 | NewSlot = Slot#slot{count=MaxStack}, 101 | NewInv = array:set(SlotNo, NewSlot, Inventory), 102 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, NewSlot]}), 103 | RestCount = Count - MaxStack, 104 | inventory_add_to_free_slot(Writer, NewInv, SlotNo+1, EndSlot, 105 | Slot#slot{count=RestCount}); 106 | true -> 107 | NewInv = array:set(SlotNo, Slot, Inventory), 108 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, Slot]}), 109 | {NewInv, empty} 110 | end; 111 | _ -> 112 | inventory_add_to_free_slot(Writer, Inventory, SlotNo+1, EndSlot, Slot) 113 | end. 114 | 115 | inventory_add_to_stack(Writer, Inventory, SlotNo, #slot{id=BlockId, count=Count}=Slot) -> 116 | MaxStack = (mc_erl_blocks:block_info(BlockId))#block_type.maxstack, 117 | case array:get(SlotNo, Inventory) of 118 | #slot{count=OldCount} -> 119 | if 120 | OldCount >= MaxStack -> 121 | {Inventory, Slot}; 122 | OldCount+Count > MaxStack -> 123 | NewSlot = Slot#slot{count=MaxStack}, 124 | NewInv = array:set(SlotNo, NewSlot, Inventory), 125 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, NewSlot]}), 126 | RestCount = OldCount+Count - MaxStack, 127 | {NewInv, Slot#slot{count=RestCount}}; 128 | true -> 129 | NewSlot = Slot#slot{count=OldCount+Count}, 130 | NewInv = array:set(SlotNo, NewSlot, Inventory), 131 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, NewSlot]}), 132 | {NewInv, empty} 133 | end; 134 | empty -> 135 | NewInv = array:set(SlotNo, Slot, Inventory), 136 | mc_erl_player_core:write(Writer, {set_slot, [0, SlotNo, Slot]}), 137 | {NewInv, empty} 138 | end. 139 | -------------------------------------------------------------------------------- /src/mc_erl_chunk_manager.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_chunk_manager). 4 | -behaviour(gen_server). 5 | 6 | -export([setup/0, start_link/0, stop/0, clear_map/0, reset_chunk/1, coord_to_chunk/1, chunks_in_range/2, get_chunk/1, 7 | set_block/2, set_block/3, get_block/1, loaded_chunks/0, undirectional_block_coord/1, tick/1]). 8 | 9 | -include("records.hrl"). 10 | 11 | % gen_server callbacks 12 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). 13 | 14 | %% used for mnesia table 15 | -record(column, {pos, data}). 16 | 17 | %% set up mnesia table 18 | setup() -> 19 | mnesia:create_table(column, [{attributes, record_info(fields, column)}, 20 | {type, set}, {disc_copies, [node()]}]). 21 | 22 | start_link() -> 23 | gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). 24 | 25 | stop() -> 26 | gen_server:cast(?MODULE, stop). 27 | 28 | %% converts coordinates to chunk coordinates 29 | coord_to_chunk({X, _Y, Z}) -> 30 | {floor(X/16), floor(Z/16)}. 31 | 32 | coord_within_chunk({X, Y, Z}) -> 33 | {X - floor(X/16)*16, Y - floor(Y/16)*16, Z - floor(Z/16)*16}. 34 | 35 | floor(X) when X < 0 -> 36 | T = trunc(X), 37 | case X - T == 0 of 38 | true -> T; 39 | false -> T - 1 40 | end; 41 | floor(X) -> 42 | trunc(X). 43 | 44 | undirectional_block_coord({X, Y, Z, Direction}) -> 45 | case Direction of 46 | 0 -> {X, Y-1, Z}; 47 | 1 -> {X, Y+1, Z}; 48 | 2 -> {X, Y, Z-1}; 49 | 3 -> {X, Y, Z+1}; 50 | 4 -> {X-1, Y, Z}; 51 | 5 -> {X+1, Y, Z} 52 | end. 53 | 54 | %% returns a set of {chunk, X, Z} coordinates 55 | chunks_in_range({_, _, _}=Pos, Range) -> 56 | chunks_in_range(coord_to_chunk(Pos), Range); 57 | chunks_in_range({CX, CZ}, Range) -> 58 | sets:from_list(lists:flatten( 59 | [{X, Z} || X<-lists:seq(CX-Range, CX+Range), Z<-lists:seq(CZ-Range, CZ+Range)])). 60 | 61 | get_chunk({_, _, _}=Pos) -> 62 | get_chunk(coord_to_chunk(Pos)); 63 | get_chunk({_, _}=ChunkCoord) -> 64 | Q = fun() -> 65 | case mnesia:read(column, ChunkCoord) of 66 | [] -> 67 | C = mc_erl_chunk_generator:gen_column(ChunkCoord), 68 | mnesia:write(#column{pos=ChunkCoord, data=C}), 69 | C; 70 | [{column, ChunkCoord, C}] -> C 71 | end 72 | end, 73 | {atomic, R} = mnesia:transaction(Q), 74 | R. 75 | 76 | loaded_chunks() -> gen_server:call(?MODULE, loaded_chunks). 77 | 78 | tick(Time) -> 79 | gen_server:cast(?MODULE, {tick, Time}). 80 | 81 | clear_map() -> gen_server:cast(?MODULE, clear_map). 82 | 83 | reset_chunk({_X, _Z} = Coord) -> 84 | Q = fun() -> mnesia:delete({column, Coord}) end, 85 | {atomic, ok} = mnesia:transaction(Q), 86 | mc_erl_entity_manager:broadcast({update_column, Coord}). 87 | 88 | %get_compressed_chunk(... 89 | 90 | orientation(Yaw) -> 91 | Sin = math:sin((Yaw+45)/360*2*math:pi()), 92 | Cos = math:cos((Yaw+45)/360*2*math:pi()), 93 | if Sin =< 0 -> 94 | if Cos =< 0 -> 95 | north; 96 | true -> 97 | east 98 | end; 99 | true -> 100 | if Cos =< 0 -> 101 | west; 102 | true -> 103 | south 104 | end 105 | end. 106 | 107 | get_block({_X, Y, _Z}=Pos) -> 108 | Column = get_chunk(coord_to_chunk(Pos)), 109 | case proplists:get_value(Y div 16, Column#chunk_column_data.chunks) of 110 | undefined -> {0, 0}; % if the requested block is in the air-filled chunk, it is air 111 | Chunk -> 112 | % if it can possibly have something, find it out 113 | % starting with block id 114 | {RX, RY, RZ} = coord_within_chunk(Pos), 115 | ByteOffset = (RX+RZ*16+RY*256), 116 | BitOffset = ByteOffset * 8, 117 | <<_:BitOffset, BlockId:8, _/binary>> = Chunk#chunk_data.types, 118 | 119 | % and now metadata 120 | NibbleBitOffset = floor(ByteOffset/2)*8, 121 | <<_:NibbleBitOffset, M1:4, M2:4, _/binary>> = Chunk#chunk_data.metadata, 122 | 123 | MetadataValue = case ByteOffset rem 2 of 124 | 0 -> M2; 125 | 1 -> M1 126 | end, 127 | 128 | {BlockId, MetadataValue} 129 | end. 130 | 131 | 132 | set_block({_, _, _, Direction}=C, {BlockId, Metadata}, {_, _, _, Yaw, _}) -> 133 | {X, Y, Z} = BlockCoord = undirectional_block_coord(C), 134 | case mc_erl_blocks:can_build(BlockId) of 135 | true -> 136 | NewMetadata = if 137 | BlockId =:= 50 orelse BlockId =:= 75 orelse BlockId =:= 76 -> 138 | case Direction of 139 | 1 -> 5; 140 | 2 -> 4; 141 | 3 -> 3; 142 | 4 -> 2; 143 | 5 -> 1; 144 | _ -> 0 145 | end; 146 | BlockId =:= 53 orelse BlockId =:= 67 orelse BlockId =:= 67 147 | orelse BlockId =:= 108 orelse BlockId =:= 109 148 | orelse BlockId =:= 114 -> 149 | <> = <<0:5, 150 | (case Direction of 151 | 0 -> 1; 152 | _ -> 0 153 | end):1, 154 | (case orientation(Yaw) of 155 | east -> 0; 156 | west -> 1; 157 | south -> 2; 158 | north -> 3 159 | end):2>>, 160 | M; 161 | BlockId =:= 23 orelse BlockId =:= 54 orelse BlockId =:= 61 orelse BlockId =:= 65 -> 162 | case orientation(Yaw) of 163 | south -> 2; 164 | north -> 3; 165 | east -> 4; 166 | west -> 5 167 | end; 168 | true -> Metadata 169 | end, 170 | mc_erl_entity_manager:broadcast_visible({X, Y, Z}, {block_delta, {X, Y, Z, BlockId, NewMetadata}}), 171 | set_block(BlockCoord, {BlockId, NewMetadata}); 172 | false -> 173 | {error, forbidden_block_id, BlockCoord} 174 | end. 175 | 176 | set_block({X, Y, Z}=BlockCoord, {BlockId, Metadata}=BlockData) -> 177 | mc_erl_entity_manager:broadcast_visible(BlockCoord, {block_delta, {X, Y, Z, BlockId, Metadata}}), 178 | gen_server:cast(?MODULE, {set_block, BlockCoord, BlockData}). 179 | 180 | write_column(Coord, ColumnData) -> 181 | F = fun() -> mnesia:write(#column{pos=Coord, data=ColumnData}) end, 182 | {atomic, ok} = mnesia:transaction(F). 183 | 184 | % gen_server callbacks 185 | init([]) -> 186 | lager:info("[~s] starting~n", [?MODULE]), 187 | {ok, void}. 188 | 189 | handle_call(loaded_chunks, _From, Chunks) -> 190 | {reply, mnesia:table_info(column, size), Chunks}; 191 | 192 | handle_call(Message, _From, State) -> 193 | case Message of 194 | _ -> 195 | lager:notice("[~s] received call: ~p~n", [?MODULE, Message]), 196 | {noreply, State} 197 | end. 198 | 199 | 200 | handle_cast(clear_map, State) -> 201 | F = fun() -> mnesia:clear_table(column) end, 202 | {atomic, ok} = mnesia:transaction(F), 203 | {noreply, State}; 204 | 205 | handle_cast({set_block, {_X, Y, _Z}=Coord, {BlockId, Metadata}}, Chunks) -> 206 | Column = get_chunk(coord_to_chunk(Coord)), 207 | Chunk = case proplists:get_value(Y div 16, Column#chunk_column_data.chunks) of 208 | undefined -> #chunk_data{types=binary:copy(<<0>>,16*16*16), 209 | metadata=binary:copy(<<0>>,16*16*8), 210 | block_light=binary:copy(<<255>>,16*16*8), 211 | sky_light=binary:copy(<<255>>,16*16*8)}; 212 | C -> C 213 | end, 214 | 215 | % changing types 216 | {RX, RY, RZ} = coord_within_chunk(Coord), 217 | ByteOffset = RX+RZ*16+RY*256, 218 | {Head, Rest} = split_binary(Chunk#chunk_data.types, ByteOffset), 219 | {_, Tail} = split_binary(Rest, 1), 220 | NewTypes = list_to_binary([Head, BlockId, Tail]), 221 | 222 | % changing metadata value 223 | NibbleOffset = floor(ByteOffset/2), 224 | {MetaHead, MetaRest} = split_binary(Chunk#chunk_data.metadata, NibbleOffset), 225 | {<>, MetaTail} = split_binary(MetaRest, 1), % i hate nibble packing 226 | NewMetadataValue = case ByteOffset rem 2 of 227 | 0 -> <>; 228 | 1 -> <> 229 | end, 230 | NewMetadata = list_to_binary([MetaHead, NewMetadataValue, MetaTail]), 231 | 232 | NewChunk = Chunk#chunk_data{types=NewTypes, metadata=NewMetadata}, 233 | NewColumn = Column#chunk_column_data{ 234 | chunks=lists:keystore(Y div 16, 1, Column#chunk_column_data.chunks, 235 | {Y div 16, NewChunk})}, 236 | 237 | write_column(coord_to_chunk(Coord), NewColumn), 238 | {noreply, Chunks}; 239 | 240 | handle_cast({tick, _Time}, Chunks) -> 241 | {noreply, Chunks}; 242 | 243 | handle_cast(stop, State) -> 244 | lager:info("[~s] stopping~n", [?MODULE]), 245 | {stop, normal, State}; 246 | 247 | handle_cast(Message, State) -> 248 | lager:notice("[~s] received cast: ~p~n", [?MODULE, Message]), 249 | {noreply, State}. 250 | 251 | handle_info(Message, State) -> 252 | case Message of 253 | _ -> 254 | lager:notice("[~s] received info: ~p~n", [?MODULE, Message]), 255 | {noreply, State} 256 | end. 257 | 258 | terminate(_Reason, _State) -> 259 | ok. 260 | 261 | code_change(_OldVsn, State, _Extra) -> 262 | {ok, State}. 263 | 264 | 265 | -------------------------------------------------------------------------------- /src/mc_erl_packets.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_packets). 4 | -export([get_by_id/1, get_by_name/1, get_enchantment_by_id/1, get_enchantment_by_name/1]). 5 | 6 | get_by_id(Id) -> 7 | case Id of 8 | 0 -> 9 | {0, keep_alive, [int]}; 10 | 1 -> 11 | {1, login_request, [int, string, byte, byte, byte, ubyte, ubyte]}; 12 | 2 -> 13 | {2, handshake, [byte, string, string, int]}; 14 | 3 -> 15 | {3, chat_message, [string]}; 16 | 4 -> 17 | {4, time_update, [long, long]}; 18 | 5 -> 19 | {5, entity_equipment, [int, short, slot]}; 20 | 6 -> 21 | {6, spawn_position, [int, int, int]}; 22 | 7 -> 23 | {7, use_entity, [int, int, bool]}; 24 | 8 -> 25 | {8, update_health, [short, short, float]}; 26 | 9 -> 27 | {9, respawn, [int, byte, byte, short, string]}; 28 | 10 -> 29 | {10, player, [bool]}; 30 | 11 -> 31 | {11, player_position, [double, double, double, double, bool]}; 32 | 12 -> 33 | {12, player_look, [float, float, bool]}; 34 | 13 -> 35 | {13, player_position_look, [double, double, double, double, 36 | float, float, bool]}; 37 | 14 -> 38 | {14, player_digging, [byte, int, byte, int, byte]}; 39 | 15 -> 40 | {15, player_block_placement, [int, ubyte, int, byte, slot, byte, byte, byte]}; 41 | 16 -> 42 | {16, holding_change, [short]}; 43 | 17 -> 44 | {17, use_bed, [int, byte, int, byte, int]}; 45 | 18 -> 46 | {18, animation, [int, byte]}; 47 | 19 -> 48 | {19, entity_action, [int, byte]}; 49 | 20 -> 50 | {20, named_entity_spawn, [int, string, abs_int, abs_int, abs_int, 51 | byte, byte, short, metadata]}; 52 | 22 -> 53 | {22, collect_item, [int, int]}; 54 | 23 -> % no fireballs supported! 55 | {23, add_object, [int, byte, abs_int, abs_int, abs_int, byte, byte, projectile_data]}; 56 | 24 -> 57 | {24, mob_spawn, [int, byte, abs_int, abs_int, abs_int, byte, byte, byte, short, short, short, metadata]}; 58 | 26 -> 59 | {26, experience_orb, [int, int, int, int, short]}; 60 | 28 -> 61 | {28, entity_velocity, [int, short, short, short]}; 62 | 29 -> 63 | {29, destroy_entity, [{array, byte, int}]}; 64 | 31 -> 65 | {31, entity_move, [int, abs_byte, abs_byte, abs_byte]}; 66 | 32 -> 67 | {32, entity_look, [int, byte, byte]}; 68 | 33 -> 69 | {33, entity_look_move, [int, abs_byte, abs_byte, abs_byte, byte, byte]}; 70 | 34 -> 71 | {34, entity_teleport, [int, abs_int, abs_int, abs_int, byte, byte]}; 72 | 35 -> 73 | {35, entity_head_look, [int, byte]}; 74 | 38 -> 75 | {38, entity_status, [int, byte]}; 76 | 39 -> 77 | {39, attach_entity, [int, int]}; 78 | 40 -> 79 | {40, entity_metadata, [int, metadata]}; 80 | 41 -> 81 | {41, entity_effect, [int, byte, byte, short]}; 82 | 42 -> 83 | {42, remove_entity_effect, [int, byte]}; 84 | 43 -> 85 | {43, experience, [float, short, short]}; 86 | 51 -> 87 | {51, map_chunk, [int, int, chunk_data]}; 88 | 52 -> 89 | {52, multi_block_change, [int, int, multi_block_change_data]}; 90 | 53 -> 91 | {53, block_change, [int, byte, int, short, byte]}; 92 | 54 -> 93 | {54, block_action, [int, short, int, byte, byte, short]}; 94 | 55 -> 95 | {55, block_break_animation, [int, int, int, int, byte]}; 96 | 56 -> 97 | {56, map_chunk_bulk, [chunk_bulk]}; 98 | 60 -> 99 | {60, explosion, [double, double, double, float, coordinate_offsets, float, float, float]}; 100 | 61 -> 101 | {61, sound_particle_effect, [int, int, byte, int, int, bool]}; 102 | 62 -> 103 | {62, named_sound_effect, [string, int, int, int, float, byte]}; 104 | 70 -> 105 | {70, new_invalid_state, [byte, byte]}; 106 | 71 -> 107 | {71, thunderbolt, [int, bool, abs_int, abs_int, abs_int]}; 108 | 100 -> 109 | {100, open_window, [byte, byte, string, byte]}; 110 | 101 -> 111 | {101, close_window, [byte]}; 112 | 102 -> 113 | {102, window_click, [byte, short, byte, short, bool, slot]}; 114 | 103 -> 115 | {103, set_slot, [byte, short, slot]}; 116 | 104 -> 117 | {104, window_items, [byte, slots]}; 118 | 105 -> 119 | {105, update_window_property, [byte, short, short]}; 120 | 106 -> 121 | {106, transaction, [byte, short, bool]}; 122 | 107 -> 123 | {107, creative_inventory_action, [short, slot]}; 124 | 108 -> 125 | {108, enchant_item, [byte, byte]}; 126 | 130 -> 127 | {130, update_sign, [int, short, int, string, string, string, string]}; 128 | 131 -> 129 | {131, item_data, [short, short, {array, short, binary}]}; 130 | 132 -> 131 | {132, update_tile_entity, [int, short, int, byte, short]}; % TODO! 132 | 200 -> 133 | {200, increment_statistic, [int, byte]}; 134 | 201 -> 135 | {201, player_list_item, [string, bool, short]}; 136 | 202 -> 137 | {202, player_abilities, [byte, byte, byte]}; 138 | 203 -> 139 | {203, tab_complete, [string]}; 140 | 204 -> 141 | {204, client_settings, [string, byte, byte, byte, bool]}; 142 | 205 -> 143 | {205, client_statuses, [byte]}; 144 | 250 -> 145 | {250, plugin_message, [string, {array, short, byte}]}; 146 | 252 -> 147 | {252, encryption_key_response, [{array, short, binary}, {array, short, binary}]}; 148 | 253 -> 149 | {253, encryption_key_request, [string, {array, short, binary}, {array, short, binary}]}; 150 | 254 -> 151 | {254, server_list_ping, [byte]}; 152 | 255 -> 153 | {255, disconnect, [string]}; 154 | X -> 155 | {error, {unknown_id, X}} 156 | end. 157 | 158 | get_by_name(Name) -> 159 | get_by_id(case Name of 160 | keep_alive -> 0; 161 | login_request -> 1; 162 | handshake -> 2; 163 | chat_message -> 3; 164 | time_update -> 4; 165 | entity_equipment -> 5; 166 | spawn_position -> 6; 167 | use_entity -> 7; 168 | update_health -> 8; 169 | respawn -> 9; 170 | player -> 10; 171 | player_position -> 11; 172 | player_look -> 12; 173 | player_position_look -> 13; 174 | player_digging -> 14; 175 | player_block_placement -> 15; 176 | holding_change -> 16; 177 | use_bed -> 17; 178 | animation -> 18; 179 | entity_action -> 19; 180 | named_entity_spawn -> 20; 181 | collect_item -> 22; 182 | add_object -> 23; 183 | mob_spawn -> 24; 184 | experience_orb -> 26; 185 | entity_velocity -> 28; 186 | destroy_entity -> 29; 187 | entity_move -> 31; 188 | entity_look -> 32; 189 | entity_look_move -> 33; 190 | entity_teleport -> 34; 191 | entity_head_look -> 35; 192 | entity_status -> 38; 193 | attach_entity -> 39; 194 | entity_metadata -> 40; 195 | entity_effect -> 41; 196 | remove_entity_effect -> 42; 197 | experience -> 43; 198 | map_chunk -> 51; 199 | multi_block_change -> 52; 200 | block_change -> 53; 201 | block_action -> 54; 202 | explosion -> 60; 203 | sound_particle_effect -> 61; 204 | new_invalid_state -> 70; 205 | thunderbolt -> 71; 206 | open_window -> 100; 207 | close_window -> 101; 208 | window_click -> 102; 209 | set_slot -> 103; 210 | window_items -> 104; 211 | update_window_property -> 105; 212 | transaction -> 106; 213 | creative_inventory_action -> 107; 214 | enchant_item -> 108; 215 | update_sign -> 130; 216 | item_data -> 131; 217 | update_tile_entity -> 132; 218 | increment_statistic -> 200; 219 | player_list_item -> 201; 220 | player_abilities -> 202; 221 | client_settings -> 204; 222 | client_statuses -> 205; 223 | encryption_key_response -> 252; 224 | encryption_key_request -> 253; 225 | server_list_ping -> 254; 226 | disconnect -> 255; 227 | X -> 228 | {error, {unknown_name, X}} 229 | end). 230 | 231 | get_enchantment_by_id(Id) -> 232 | case Id of 233 | 0 -> {0, protection, [helmet, chestplate, leggings, boots], 4}; 234 | 1 -> {1, fire_protection, [helmet, chestplate, leggings, boots], 4}; 235 | 2 -> {2, feather_falling, [boots], 4}; 236 | 3 -> {3, blast_protection, [helmet, chestplate, leggings, boots], 4}; 237 | 4 -> {4, projectile_protection, [helmet, chestplate, leggings, boots], 4}; 238 | 5 -> {5, respiration, [helmet], 3}; 239 | 6 -> {6, aqua_affinity, [helmet], 1}; 240 | 241 | 16 -> {16, sharpness, [sword], 5}; 242 | 17 -> {17, smite, [sword], 5}; 243 | 18 -> {18, bane_of_anthropods, [sword], 5}; 244 | 19 -> {19, knockback, [sword], 2}; 245 | 20 -> {20, fire_aspect, [sword], 2}; 246 | 21 -> {21, looting, [sword], 3}; 247 | 248 | 48 -> {48, 'power', [bow], 5}; 249 | 49 -> {49, punch, [bow], 2}; 250 | 50 -> {50, flame, [bow], 1}; 251 | 51 -> {51, 'infinity', [bow], 1}; 252 | 253 | 32 -> {32, efficiency, [pickaxe, shovel, axe], 5}; 254 | 33 -> {33, silk_touch, [pickaxe, shovel, axe], 1}; 255 | 34 -> {34, unbreaking, [pickaxe, shovel, axe], 3}; 256 | 35 -> {35, fortune, [pickaxe, shovel, axe], 3} 257 | end. 258 | 259 | get_enchantment_by_name(Name) -> 260 | get_enchantment_by_id(case Name of 261 | protection -> 0; 262 | fire_protection -> 1; 263 | feather_falling -> 2; 264 | blast_protection -> 3; 265 | projectile_protection -> 4; 266 | respiration -> 5; 267 | aqua_affinity -> 6; 268 | 269 | sharpness -> 16; 270 | smite -> 17; 271 | bane_of_anthropods -> 18; 272 | knockback -> 19; 273 | fire_aspect -> 20; 274 | looting -> 21; 275 | 276 | 'power' -> 48; 277 | punch -> 49; 278 | flame -> 50; 279 | 'infinity' -> 51; 280 | 281 | efficiency -> 32; 282 | silk_touch -> 33; 283 | unbreaking -> 34; 284 | fortune -> 35 285 | end). 286 | 287 | -------------------------------------------------------------------------------- /src/mc_erl_protocol.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_protocol). 4 | 5 | -export([decode_packet/1, encode_packet/1, decrypt/4, encrypt/4, print_hex/1]). 6 | 7 | -include("records.hrl"). 8 | 9 | -define(timeout, 10000). 10 | 11 | % Protocol weirdness handling 12 | to_absint(Value) when is_float(Value) orelse is_integer(Value) -> 13 | trunc(Value*32). 14 | 15 | from_absint(Value) when is_integer(Value) -> 16 | Value/32. 17 | 18 | % ====================================================================== 19 | % cryptography 20 | % ====================================================================== 21 | 22 | decrypt(Socket, Key, IVec, BytesCount) -> 23 | decrypt(Socket, Key, IVec, BytesCount, []). 24 | 25 | decrypt(_Socket, _Key, IVec, 0, Return) -> 26 | {list_to_binary(lists:reverse(Return)), IVec}; 27 | decrypt(Socket, Key, IVec, BytesCount, Return) -> 28 | case gen_tcp:recv(Socket, 1, ?timeout) of 29 | {error, closed} -> 30 | throw(connection_closed); 31 | {ok, <>=B} -> 32 | %mc_erl_protocol:print_hex(Bin), 33 | Cipher = <>, 34 | Text = crypto:block_decrypt(aes_cfb128, Key, IVec, Cipher), 35 | 36 | %mc_erl_protocol:print_hex(Text), 37 | 38 | <> = Text, 39 | decrypt(Socket, Key, gen_ivec(IVec, B), BytesCount-1, [Ret|Return]) 40 | end. 41 | 42 | encrypt(Socket, Key, IVec, Text) when is_binary(Text) -> 43 | encrypt(Socket, Key, IVec, binary_to_list(Text), []). 44 | 45 | encrypt(_, _, IVec, [], Return) -> 46 | {lists:reverse(Return), IVec}; 47 | encrypt(Socket, Key, IVec, [Text|Rest], Return) -> 48 | Cipher = crypto:block_encrypt(aes_cfb128, Key, IVec, 49 | <>), 50 | <> = Cipher, 51 | encrypt(Socket, Key, gen_ivec(IVec, Ret), Rest, [Ret|Return]). 52 | 53 | 54 | gen_ivec(OldIVec, Data) when byte_size(Data) =:= 1 -> 55 | %L = size(Data), 56 | <<_:1/binary, IVPart/binary>> = OldIVec, 57 | list_to_binary([IVPart, Data]). 58 | 59 | 60 | % ====================================================================== 61 | % decoding 62 | % ====================================================================== 63 | 64 | decode_packet(Reader) -> 65 | Recv = get_bytes(Reader, 1), 66 | case Recv of 67 | {ok, <>} -> 68 | {Id, Name, TypeParamList} = mc_erl_packets:get_by_id(Id), 69 | ParamList = decode_param_list(Reader, TypeParamList, []), 70 | {ok, {Name, ParamList}}; 71 | {error, Reason} -> 72 | {error, Reason} 73 | end. 74 | 75 | decode_param_list(_Reader, [], Output) -> 76 | lists:reverse(Output); 77 | 78 | decode_param_list(Reader, [TypeParam|TypeParamList], Output) -> 79 | decode_param_list(Reader, TypeParamList, 80 | [read_value(Reader, TypeParam)|Output]). 81 | 82 | read_value(Reader, Type) -> 83 | case Type of 84 | bool -> read_bool(Reader); 85 | byte -> read_byte(Reader); 86 | ubyte -> read_ubyte(Reader); 87 | abs_byte -> from_absint(read_byte(Reader)); 88 | short -> read_short(Reader); 89 | ushort -> read_ushort(Reader); 90 | int -> read_int(Reader); 91 | abs_int -> from_absint(read_int(Reader)); 92 | long -> read_long(Reader); 93 | float -> read_float(Reader); 94 | double -> read_double(Reader); 95 | string -> read_string(Reader); 96 | metadata -> read_metadata(Reader); 97 | slots -> read_slots(Reader); 98 | slot -> read_slot(Reader); 99 | chunk_data -> read_chunk_data(Reader); 100 | multi_block_change_data -> read_multi_block_change_data(Reader); 101 | coordinate_offsets -> read_coordinate_offsets(Reader); 102 | projectile_data -> read_projectile_data(Reader); 103 | {array, CountType, PayloadType} -> read_array(Reader, CountType, PayloadType); 104 | _ -> 105 | lager:emergency("[~w] unknown datatype: ~p~n", [?MODULE, Type]), 106 | {error, unknown_datatype, Type} 107 | end. 108 | 109 | read_bool(Reader) -> 110 | {ok, <>} = get_bytes(Reader, 1), 111 | N =:= 1. 112 | 113 | read_byte(Reader) -> 114 | {ok, <>} = get_bytes(Reader, 1), 115 | N. 116 | 117 | read_ubyte(Reader) -> 118 | {ok, <>} = get_bytes(Reader, 1), 119 | N. 120 | 121 | read_short(Reader) -> 122 | {ok, <>} = get_bytes(Reader, 2), 123 | N. 124 | 125 | read_ushort(Reader) -> 126 | {ok, <>} = get_bytes(Reader, 2), 127 | N. 128 | 129 | read_int(Reader) -> 130 | {ok, <>} = get_bytes(Reader, 4), 131 | N. 132 | 133 | read_long(Reader) -> 134 | {ok, <>} = get_bytes(Reader, 8), 135 | N. 136 | 137 | read_float(Reader) -> 138 | {ok, <>} = get_bytes(Reader, 4), 139 | N. 140 | 141 | read_double(Reader) -> 142 | {ok, <>} = get_bytes(Reader, 8), 143 | N. 144 | 145 | read_bit_set(Reader, Bytes) -> 146 | {ok, Bin} = get_bytes(Reader, Bytes), 147 | parse_bit_set(binary_to_list(Bin), []). 148 | 149 | parse_bit_set([], Output) -> 150 | List = lists:flatten(Output), 151 | L2 = [round(math:pow(2,N)) || N <- List], 152 | lists:filter(fun(N) -> not (N =:= 0) end, L2); 153 | parse_bit_set([B|Bytes], Output) -> 154 | <> = <>, 155 | parse_bit_set(Bytes, [[B7, B6, B5, B4, B3, B2, B1, B0]|Output]). 156 | 157 | read_string(Reader) -> 158 | case read_short(Reader) of 159 | 0 -> []; 160 | Length -> 161 | BinLength = Length * 2, 162 | {ok, Bin} = get_bytes(Reader, BinLength), 163 | decode_ucs_2(Bin, []) 164 | end. 165 | 166 | decode_ucs_2(<<>>, Output) -> 167 | lists:reverse(Output); 168 | decode_ucs_2(Bin, Output) -> 169 | {No, Rest} = split_binary(Bin, 2), 170 | <> = No, 171 | decode_ucs_2(Rest, [N|Output]). 172 | 173 | read_metadata(Reader) -> 174 | read_metadata(Reader, []). 175 | 176 | read_metadata(Reader, Output) -> 177 | X = read_ubyte(Reader), 178 | case X of 179 | 127 -> lists:reverse(Output); 180 | X -> 181 | <> = <>, 182 | O = {Key, case Type of 183 | 0 -> {byte, read_byte(Reader)}; 184 | 1 -> {short, read_short(Reader)}; 185 | 2 -> {int, read_int(Reader)}; 186 | 3 -> {float, read_float(Reader)}; 187 | 4 -> {string, read_string(Reader)}; 188 | 5 -> {short_byte_short, [read_short(Reader), read_byte(Reader), 189 | read_short(Reader)]}; 190 | 6 -> {int_int_int, [read_int(Reader), read_int(Reader), 191 | read_int(Reader)]}; 192 | N -> {error, unknown_metadata_type, N} 193 | end}, 194 | read_metadata(Reader, [O|Output]) 195 | end. 196 | 197 | read_slot(Reader) -> 198 | case read_short(Reader) of 199 | -1 -> empty; 200 | ItemId -> 201 | ItemCount = read_byte(Reader), 202 | Metadata = read_short(Reader), 203 | case read_short(Reader) of 204 | -1 -> 205 | #slot{id=ItemId, count=ItemCount, metadata=Metadata}; 206 | BinLength -> 207 | {ok, BinEnchantments} = get_bytes(Reader, BinLength), 208 | #slot{id=ItemId, count=ItemCount, metadata=Metadata, enchantments=read_enchantments(BinEnchantments)} 209 | end 210 | end. 211 | 212 | 213 | read_enchantments(BinEnchantments) -> 214 | EnchNbtBin = zlib:gunzip(BinEnchantments), 215 | EnchData = nbt:decode(EnchNbtBin), 216 | 217 | % I am really sorry for the following, but that NBT library has this crazy format. 218 | % Note, however, that variable Enchantments becomes bound after this line, populated 219 | % by a list of [{<<"id">>, {short, Eid}}, {<<"lvl">>, {short, Lvl}}]. 220 | {<<"tag">>,{compound,[{<<"ench">>,{compound, Enchantments}}]}} = EnchData, 221 | 222 | % This cryptic fun makes enchantments readable. get_enchantment_by_id return 223 | % a tuple, structured as {ench_name, [applicable_item_classes], max_lvl}. 224 | % Validation is performed in server implementation. 225 | lists:map(fun(X) -> 226 | [{<<"id">>, {short, Eid}}, {<<"lvl">>, {short, Lvl}}] = X, 227 | {_EnchId, EnchName, _AppliedTo, _MaxLvl} = mc_erl_packets:get_enchantment_by_id(Eid), 228 | {EnchName, Lvl} end, 229 | Enchantments). 230 | 231 | 232 | read_slots(Reader) -> 233 | Count = read_short(Reader), 234 | read_slots(Reader, [], Count). 235 | 236 | read_slots(_Reader, Output, 0) -> 237 | lists:reverse(Output); 238 | 239 | read_slots(Reader, Output, RemainingSlots) -> 240 | read_slots(Reader, [read_slot(Reader)|Output], RemainingSlots-1). 241 | 242 | read_chunk_data(Reader) -> 243 | FullColumn = read_bool(Reader), 244 | ContainedChunks = read_bit_set(Reader, 2), 245 | ChunksCount = lists:sum(ContainedChunks), 246 | _AddChunks = read_bit_set(Reader, 2), 247 | Length = read_int(Reader), 248 | {ok, Bin} = get_bytes(Reader, Length), 249 | Uncompressed = zlib:uncompress(Bin), 250 | {TypeBin, Rest1} = split_binary(Uncompressed, 4096*ChunksCount), 251 | {MetadataBin, Rest2} = split_binary(Rest1, 2048*ChunksCount), 252 | {BlockLightBin, Rest3} = split_binary(Rest2, 2048*ChunksCount), 253 | {SkyLightBin, Rest4} = split_binary(Rest3, 2048*ChunksCount), 254 | 255 | BiomeBin = case FullColumn of 256 | true -> element(1, split_binary(Rest4, 256)); 257 | false -> undefined 258 | end, 259 | 260 | Types = split_chunks(TypeBin, 4096), 261 | Metadata = split_chunks(MetadataBin, 2048), 262 | BlockLight = split_chunks(BlockLightBin, 2048), 263 | SkyLight = split_chunks(SkyLightBin, 2048), 264 | Chunks = [{N, #chunk_data{types=T, metadata=M, block_light=BL, sky_light=SL}} || 265 | N <- ContainedChunks, T <- Types, M <- Metadata, BL <- BlockLight, 266 | SL <- SkyLight], 267 | {parsed, #chunk_column_data{full_column=FullColumn, chunks=Chunks, 268 | biome=BiomeBin}}. 269 | 270 | split_chunks(Bin, ChunkSize) -> 271 | split_chunks(Bin, ChunkSize, []). 272 | 273 | split_chunks(<<>>, _ChunkSize, Output) -> 274 | lists:reverse(Output); 275 | split_chunks(Bin, ChunkSize, Output) -> 276 | {Chunk, Rest} = split_binary(Bin, ChunkSize), 277 | split_chunks(Rest, ChunkSize, [Chunk|Output]). 278 | 279 | 280 | read_multi_block_change_data(Reader) -> 281 | RecordCount = read_short(Reader), 282 | _ = read_int(Reader), 283 | {multi_block_change_data, RecordCount, read_multi_block_change_datasets(Reader, RecordCount)}. 284 | 285 | read_multi_block_change_datasets(Reader, RecordCount) -> read_multi_block_change_datasets(Reader, RecordCount, []). 286 | 287 | read_multi_block_change_datasets(_Reader, 0, DeltaBlocks) -> lists:reverse(DeltaBlocks); 288 | read_multi_block_change_datasets(Reader, RecordCount, DeltaBlocks) -> 289 | {ok, Raw} = get_bytes(Reader, 4), 290 | <> = Raw, 291 | read_multi_block_change_datasets(Reader, RecordCount - 1, [{DX, DZ, DY, BlockID, Metadata}|DeltaBlocks]). 292 | 293 | read_projectile_data(Reader) -> 294 | case read_int(Reader) of 295 | 0 -> {projectile, none}; 296 | Owner -> 297 | SpeedX = read_short(Reader), 298 | SpeedY = read_short(Reader), 299 | SpeedZ = read_short(Reader), 300 | {projectile, {Owner, SpeedX, SpeedY, SpeedZ}} 301 | end. 302 | 303 | %% coordinates are also unparsed 304 | read_coordinate_offsets(Reader) -> 305 | OffsetsNum = read_int(Reader), 306 | {ok, Bin} = get_bytes(Reader, 3*OffsetsNum), 307 | {raw, OffsetsNum, Bin}. 308 | 309 | read_array(Reader, CountType, binary) -> 310 | Num = read_value(Reader, CountType), 311 | {ok, Bytes} = get_bytes(Reader, Num), 312 | Bytes; 313 | read_array(Reader, CountType, PayloadType) -> 314 | Num = read_value(Reader, CountType), 315 | [ read_value(Reader, PayloadType) || _ <- lists:seq(1, Num) ]. 316 | 317 | % ====================================================================== 318 | % encoding 319 | % ====================================================================== 320 | 321 | encode_packet({Name, ParamList}) -> 322 | {Id, Name, TypeParamList} = mc_erl_packets:get_by_name(Name), 323 | case length(TypeParamList) of 324 | 0 -> 325 | <>; 326 | _N -> 327 | case encode_param_list(ParamList, TypeParamList) of 328 | Bin when is_binary(Bin) -> 329 | R = list_to_binary([Id, Bin]), 330 | R; 331 | {error, not_enough_arguments, OutputSoFar} -> 332 | lager:emergency("[~s] Error encoding ~p: not enough arguments!~nOutput so far: ~p~n", [?MODULE, Name, OutputSoFar]), 333 | {error, not_enough_arguments} 334 | end 335 | end. 336 | 337 | encode_param_list(ParamList, TypeParamList) -> 338 | encode_param_list(ParamList, TypeParamList, []). 339 | 340 | encode_param_list([], [], Output) -> 341 | list_to_binary(lists:reverse(Output)); 342 | encode_param_list([], _TypeList, Output) -> 343 | {error, not_enough_arguments, Output}; 344 | encode_param_list([P|ParamList], [T|TypeParamList], Output) -> 345 | O = encode_value(T, P), 346 | encode_param_list(ParamList, TypeParamList, [O|Output]). 347 | 348 | encode_value(Type, P) -> 349 | case Type of 350 | bool -> encode_bool(P); 351 | byte -> encode_byte(P); 352 | ubyte -> encode_ubyte(P); 353 | abs_byte -> encode_byte(to_absint(P)); 354 | short -> encode_short(P); 355 | ushort -> encode_ushort(P); 356 | int -> encode_int(P); 357 | abs_int -> encode_int(to_absint(P)); 358 | long -> encode_long(P); 359 | float -> encode_float(P); 360 | double -> encode_double(P); 361 | string -> encode_string(P); 362 | metadata -> encode_metadata(P); 363 | slot -> encode_slot(P); 364 | slots -> encode_slots(P); 365 | chunk_data -> encode_chunk_data(P); 366 | multi_block_change_data -> encode_multi_block_change_data(P); 367 | coordinate_offsets -> encode_coordinate_offsets(P); 368 | projectile_data -> encode_projectile_data(P); 369 | {array, CountType, PayloadType} -> encode_array(P, CountType, PayloadType); 370 | X -> {error, unknown_datatype, X} 371 | end. 372 | 373 | encode_bool(N) -> 374 | if 375 | N =:= true -> <<1>>; 376 | true -> <<0>> 377 | end. 378 | 379 | encode_byte(B) when byte_size(B) =:= 1 -> 380 | B; 381 | encode_byte(N) -> 382 | <>. 383 | 384 | encode_ubyte(N) -> 385 | <>. 386 | 387 | encode_short(N) -> 388 | <>. 389 | 390 | encode_ushort(N) -> 391 | <>. 392 | 393 | encode_int(N) -> 394 | <>. 395 | 396 | encode_long(N) -> 397 | <>. 398 | 399 | encode_float(N) -> 400 | <>. 401 | 402 | encode_double(N) -> 403 | <>. 404 | 405 | encode_string(String) -> 406 | encode_string(String, [], length(String)). 407 | 408 | encode_bit_set(BitsSet, Length) -> 409 | N = set_bits(BitsSet), 410 | BitLength = Length*8, 411 | <>. 412 | 413 | set_bits(Bits) -> set_bits(Bits, 0). 414 | set_bits([], Result) -> Result; 415 | set_bits([Bit|Rest], Result) -> set_bits(Rest, Result bor (1 bsl Bit)). 416 | 417 | encode_string([], Output, Length) -> 418 | list_to_binary([encode_short(Length), lists:reverse(Output)]); 419 | encode_string([C|Rest], Output, Length) -> 420 | O = <>, 421 | encode_string(Rest, [O|Output], Length). 422 | 423 | encode_metadata(P) -> 424 | encode_metadata(P, []). 425 | 426 | encode_metadata([], Output) -> 427 | list_to_binary(lists:reverse([127|Output])); 428 | 429 | encode_metadata([P|Rest], Output) -> 430 | {Key, {Type, Data}} = P, 431 | TypeBin = case Type of 432 | byte -> 0; 433 | short -> 1; 434 | int -> 2; 435 | float -> 3; 436 | string -> 4; 437 | short_byte_short -> 5; 438 | int_int_int -> 6 439 | end, 440 | Comp = <>, 441 | DataBin = case Type of 442 | byte -> encode_byte(Data); 443 | short -> encode_short(Data); 444 | int -> encode_int(Data); 445 | 'float' -> encode_float(Data); 446 | string -> encode_string(Data); 447 | short_byte_short -> 448 | [D1, D2, D3] = Data, 449 | [encode_short(D1), encode_byte(D2), encode_short(D3)]; 450 | int_int_int -> 451 | [encode_int(D) || D <- Data] 452 | end, 453 | encode_metadata(Rest, [ [Comp, DataBin] | Output ]). 454 | 455 | encode_slot(empty) -> encode_short(-1); 456 | encode_slot(#slot{}=S) -> 457 | case S of 458 | #slot{enchantments=[]} -> 459 | [encode_short(S#slot.id), encode_byte(S#slot.count), 460 | encode_short(S#slot.metadata), encode_short(-1)]; 461 | #slot{} -> 462 | NbtEncoded = encode_enchantments(S#slot.enchantments), 463 | [encode_short(S#slot.id), encode_byte(S#slot.count), 464 | encode_short(S#slot.metadata), encode_short(byte_size(NbtEncoded)), NbtEncoded] 465 | end. 466 | 467 | 468 | encode_enchantments(EnchList) -> 469 | EnchNbtList = lists:map(fun(X) -> 470 | {EnchName, Lvl} = X, 471 | {Eid, _EName, _AppliedTo, _MaxLvl} = mc_erl_packets:get_enchantment_by_name(EnchName), 472 | [{<<"id">>, {short, Eid}}, {<<"lvl">>, {short, Lvl}}] end, 473 | EnchList), 474 | 475 | EnchNbt = {<<"tag">>,{compound,[{<<"ench">>,{compound, EnchNbtList}}]}}, 476 | zlib:gzip(nbt:encode(EnchNbt)). 477 | 478 | 479 | 480 | encode_slots(P) -> 481 | Length = length(P), 482 | encode_slots(P, [encode_short(Length)]). 483 | 484 | encode_slots([], Output) -> 485 | lists:reverse(Output); 486 | 487 | encode_slots([Slot|Rest], Output) -> 488 | encode_slots(Rest, [encode_slot(Slot)|Output]). 489 | 490 | encode_chunk_data(unload) -> 491 | [encode_bool(true), encode_short(0), encode_short(0), encode_int(0)]; 492 | 493 | encode_chunk_data({raw, Bin}) -> 494 | [encode_int(byte_size(Bin)), encode_int(0), Bin]; 495 | 496 | encode_chunk_data({uncompressed, Uncompressed}) -> 497 | Bin = zlib:compress(Uncompressed), 498 | [encode_int(byte_size(Bin)), encode_int(0), Bin]; 499 | 500 | encode_chunk_data({parsed, Column=#chunk_column_data{}}) -> 501 | FullColumn = Column#chunk_column_data.full_column, 502 | ContainedChunks = lists:map(fun(X) -> element(1, X) end, Column#chunk_column_data.chunks), 503 | AddChunks = lists:map(fun(X) -> element(1, X) end, Column#chunk_column_data.add_data), 504 | Chunks = Column#chunk_column_data.chunks, 505 | Types = lists:map(fun(X) -> element(2, element(2, X)) end, Chunks), 506 | Metadata = lists:map(fun(X) -> element(3, element(2, X)) end, Chunks), 507 | BlockLight = lists:map(fun(X) -> element(4, element(2, X)) end, Chunks), 508 | SkyLight = lists:map(fun(X) -> element(5, element(2, X)) end, Chunks), 509 | BiomeData = Column#chunk_column_data.biome, 510 | BinData = list_to_binary([Types, Metadata, BlockLight, SkyLight, BiomeData]), 511 | CompressedData = zlib:compress(BinData), 512 | 513 | [encode_bool(FullColumn), encode_bit_set(ContainedChunks, 2), encode_bit_set(AddChunks, 2), 514 | encode_int(byte_size(CompressedData)), CompressedData]. 515 | 516 | encode_multi_block_change_datasets(BlockDelta) -> encode_multi_block_change_datasets(BlockDelta, []). 517 | 518 | encode_multi_block_change_datasets([], Delta) -> lists:reverse(Delta); 519 | encode_multi_block_change_datasets([{DX, DZ, DY, BlockID, Metadata}|Rest], Delta) -> 520 | encode_multi_block_change_datasets(Rest, [<>|Delta]). 521 | 522 | encode_multi_block_change_data({multi_block_change_data, RecordsNum, BlockDelta}) -> 523 | Delta = list_to_binary(encode_multi_block_change_datasets(BlockDelta)), 524 | [encode_short(RecordsNum), encode_int(byte_size(Delta)), Delta]. 525 | 526 | encode_coordinate_offsets({raw, OffsetsNum, Bin}) -> 527 | [encode_int(OffsetsNum), Bin]. 528 | 529 | encode_projectile_data({projectile, none}) -> 530 | encode_int(0); 531 | encode_projectile_data({projectile, {Owner, SpeedX, SpeedY, SpeedZ}}) -> 532 | [encode_int(Owner), encode_short(SpeedX), encode_short(SpeedY), encode_short(SpeedZ)]. 533 | 534 | encode_array(PayloadList, CountType, binary) when is_binary(PayloadList) -> 535 | list_to_binary([encode_value(CountType, byte_size(PayloadList)), PayloadList]); 536 | encode_array(PayloadList, CountType, PayloadType) when is_list(PayloadList) -> 537 | list_to_binary([encode_value(CountType, length(PayloadList)), [ encode_value(PayloadType, Id) || Id <- PayloadList ]]). 538 | 539 | 540 | % ====================================================================== 541 | % helper stuff 542 | % ====================================================================== 543 | 544 | % read from decrypting process 545 | get_bytes(Reader, N) when is_pid(Reader) -> 546 | Reader ! {get_bytes, N}, 547 | receive 548 | {bytes, Bin} -> {ok, Bin} 549 | end; 550 | 551 | % read directly from socket 552 | get_bytes(Socket, N) -> 553 | gen_tcp:recv(Socket, N, ?timeout). 554 | 555 | print_hex(<<>>) -> ok; 556 | print_hex(Bin) when byte_size(Bin) < 16 -> 557 | Bytes = binary_to_list(Bin), 558 | [ io:format("~2.16b ", [Byte]) || Byte <- Bytes ], 559 | [ io:format(" ") || _ <- lists:seq(1, 16-length(Bytes)) ], 560 | [ if B >= 16#21, B =< 16#7e; B >= 16#41, B =< 16#7a -> io:format("~c", [B]); true -> io:format(".") end || B <- Bytes ], 561 | io:format("~n"); 562 | print_hex(Bin) -> 563 | <> = Bin, 564 | Bytes = binary_to_list(Head), 565 | [ io:format("~2.16b ", [Byte]) || Byte <- Bytes ], 566 | [ if B >= 16#21, B =< 16#7e; B >= 16#41, B =< 16#7a -> io:format("~c", [B]); true -> io:format(".") end || B <- Bytes ], 567 | io:format("~n"), 568 | print_hex(Rest). 569 | -------------------------------------------------------------------------------- /src/mc_erl_player_logic.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2012-2013 Gregory Fefelov, Feiko Nanninga 2 | 3 | -module(mc_erl_player_logic). 4 | % only pure erlang, only pure hardcore 5 | -export([start_logic/2, packet/2]). 6 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, 7 | code_change/3]). 8 | 9 | -record(state, {writer, player, mode=creative, chunks=none, cursor_item=empty, 10 | logged_in=false, known_entities=dict:new(), last_tick, 11 | pos={0.5, 70, 0.5, 0, 0}}). 12 | 13 | -record(ke_metadata, {relocations=0}). 14 | 15 | -include("records.hrl"). 16 | 17 | start_logic(Writer, Name) -> 18 | {ok, Pid} = gen_server:start_link(?MODULE, [Writer, Name], []), 19 | Pid. 20 | 21 | packet(Logic, Packet) -> 22 | gen_server:cast(Logic, Packet). 23 | 24 | init([Writer, Name]) -> 25 | process_flag(trap_exit, true), 26 | {ok, #state{writer=Writer, player=#player{name=Name}}}. 27 | 28 | terminate(_Reason, State) when is_record(State, state) -> 29 | State#state.writer ! stop, 30 | case State#state.logged_in of 31 | true -> 32 | mc_erl_chat:broadcast(State#state.player#player.name 33 | ++ " has left the server."), 34 | mc_erl_entity_manager:delete_player(State#state.player); 35 | false -> ok 36 | end, 37 | ok. 38 | 39 | code_change(_OldVsn, State, _Extra) -> 40 | {ok, State}. 41 | 42 | handle_info(Info, State) -> 43 | lager:notice("[~s] got unknown info: ~p~n", [?MODULE, Info]), 44 | {noreply, State}. 45 | 46 | handle_call(Req, _From, State) -> 47 | lager:notice("[~s] got unknown packet: ~p~n", [?MODULE, Req]), 48 | {noreply, State}. 49 | 50 | handle_cast(Req, State) -> 51 | Writer = State#state.writer, 52 | MyPlayer = State#state.player, 53 | MyEid = MyPlayer#player.eid, 54 | RetState = case Req of 55 | % protocol reactions begin 56 | login_sequence -> 57 | IsValid = mc_erl_chat:is_valid_nickname(State#state.player#player.name), 58 | case IsValid of 59 | true -> 60 | case mc_erl_entity_manager:register_player(State#state.player) of 61 | {error, name_in_use} -> 62 | lager:warning("[~s] Someone with the same name is already logged in, kicked~n", [?MODULE]), 63 | write(Writer, {disconnect, ["Someone with the same name is already logged in :("]}), 64 | {disconnect, {multiple_login, State#state.player#player.name}, State}; 65 | 66 | NewPlayer -> 67 | Mode = case NewPlayer#player.mode of 68 | creative -> 1; 69 | survival -> 0 70 | end, 71 | receive after 2000 -> ok end, 72 | write(Writer, {login_request, [NewPlayer#player.eid, "DEFAULT", Mode, 0, 0, 0, 100]}), 73 | 74 | send_player_abilities(State), 75 | mc_erl_inventory:send_inventory(Writer, NewPlayer#player.inventory), 76 | write(Writer, {spawn_position, [0, 0, 0]}), 77 | {X, Y, Z, Yaw, Pitch} = StartPos = State#state.pos, 78 | 79 | Chunks = check_chunks(Writer, {X, Y, Z}), 80 | 81 | send_player_list(State), 82 | write(Writer, {player_position_look, [X,Y+1.62,Y,Z,Yaw,Pitch,1]}), 83 | 84 | mc_erl_entity_manager:move_entity(NewPlayer#player.eid, StartPos), 85 | 86 | mc_erl_chat:broadcast(NewPlayer#player.name ++ " has joined."), 87 | mc_erl_chat:to_player(self(), mc_erl_config:get(motd, "")), 88 | 89 | %proc_lib:spawn_link(fun() -> process_flag(trap_exit, true), mc_erl_player_core:keep_alive_sender(Writer) end), 90 | 91 | State#state{player=NewPlayer, chunks=Chunks, logged_in=true} 92 | end; 93 | false -> 94 | lager:warning("[~s] Someone with the wrong nickname has tried to log in, kicked~n", [?MODULE]), 95 | write(Writer, {disconnect, ["Invalid username :("]}), 96 | {disconnect, {invalid_username, MyPlayer#player.name}, State} 97 | end; 98 | 99 | {packet, {keep_alive, [_]}} -> 100 | State; 101 | 102 | {packet, {locale_view_distance,[_,_,_,_]}} -> 103 | State; 104 | 105 | {packet, {player, _OnGround}} -> 106 | State; 107 | 108 | {packet, {player_position, [X, Y, _Stance, Z, _OnGround]}} -> 109 | {_OldX, _OldY, _OldZ, Yaw, Pitch} = State#state.pos, 110 | NewPos = {X, Y, Z, Yaw, Pitch}, 111 | mc_erl_entity_manager:move_entity(MyEid, NewPos), 112 | 113 | NewState = State#state{chunks=check_chunks(Writer, {X, Y, Z}, State#state.chunks), pos=NewPos}, 114 | NewState; 115 | 116 | {packet, {player_look, [Yaw, Pitch, _OnGround]}} -> 117 | {X, Y, Z, _OldYaw, _OldPitch} = State#state.pos, 118 | NewPos = {X, Y, Z, Yaw, Pitch}, 119 | mc_erl_entity_manager:move_entity(MyEid, NewPos), 120 | State#state{pos=NewPos}; 121 | 122 | {packet, {player_position_look, [X, Y, _Stance, Z, Yaw, Pitch, _OnGround]}} -> 123 | NewPos = {X, Y, Z, Yaw, Pitch}, 124 | mc_erl_entity_manager:move_entity(MyEid, NewPos), 125 | State#state{chunks=check_chunks(State#state.writer, {X, Y, Z}, State#state.chunks), pos=NewPos}; 126 | 127 | {packet, net_disconnect} -> 128 | {disconnect, {graceful, "Lost connection"}, State}; 129 | 130 | {packet, {disconnect, [Message]}} -> 131 | {disconnect, {graceful, Message}, State}; 132 | 133 | {packet, {holding_change, [N]}} when N >= 0, N =< 8 -> 134 | NewPlayer = MyPlayer#player{selected_slot=N}, 135 | State#state{player=NewPlayer}; 136 | 137 | % started digging 138 | {packet, {player_digging, [0, X, Y, Z, _]}} -> 139 | case MyPlayer#player.mode of 140 | creative -> mc_erl_chunk_manager:set_block({X, Y, Z}, {0, 0}); 141 | survival -> void 142 | end, 143 | State; 144 | 145 | % cancelled digging 146 | {packet, {player_digging, [1, _X, _Y, _Z, _]}} -> 147 | State; 148 | 149 | % finished digging 150 | {packet, {player_digging, [2, X, Y, Z, _]}} -> 151 | case MyPlayer#player.mode of 152 | creative -> State; 153 | survival -> 154 | {BlockId, Metadata} = mc_erl_chunk_manager:get_block({X, Y, Z}), 155 | %mc_erl_dropped_item:spawn({X, Y, Z}, {0.1, 0, 0}, {BlockId, 1, Metadata}), 156 | mc_erl_chunk_manager:set_block({X, Y, Z}, {0, 0}), 157 | {NewInv, _Rest} = mc_erl_inventory:inventory_add(Writer, MyPlayer#player.inventory, #slot{id=BlockId, count=1, metadata=Metadata}), 158 | State#state{player=State#state.player#player{inventory=NewInv}} 159 | end; 160 | 161 | {packet, {player_block_placement, [-1, 255, -1, -1, #slot{}, _, _, _]}} -> 162 | % handle right click when no block selected 163 | % handle held item state update (eating food etc.) TODO: recheck this 164 | State; 165 | 166 | {packet, {player_block_placement, [_, _, _, _, empty, _, _, _]}} -> 167 | State; 168 | 169 | {packet, {player_block_placement, [X, Y, Z, Direction, _, _, _, _]}} -> 170 | SelectedSlot = MyPlayer#player.selected_slot+36, 171 | Inv = MyPlayer#player.inventory, 172 | case array:get(SelectedSlot, Inv) of 173 | empty -> 174 | State; 175 | #slot{id=BlockId, metadata=Metadata} -> 176 | case mc_erl_chunk_manager:set_block({X, Y, Z, Direction}, {BlockId, Metadata}, State#state.pos) of 177 | ok -> 178 | NewInv = mc_erl_inventory:update_slot(Writer, State#state.player#player.inventory, SelectedSlot, reduce), 179 | State#state{player=State#state.player#player{inventory=NewInv}}; 180 | {error, forbidden_block_id, {_RX, _RY, _RZ}} -> 181 | lager:warning("[~s] ~s tried to set a forbidden block (~p)~n", [?MODULE, MyPlayer#player.name, BlockId]) 182 | end 183 | end; 184 | 185 | {packet, {entity_action, [MyEid, _P]}} -> 186 | % crouching, leaving bed, sprinting 187 | State; 188 | 189 | {packet, {chat_message, [Message]}} -> 190 | mc_erl_chat:broadcast(State#state.player, Message), 191 | State; 192 | 193 | {packet, {animation, [MyEid, AnimationId]}} -> 194 | mc_erl_entity_manager:broadcast_local(MyEid, {animate, MyEid, AnimationId}), 195 | State; 196 | 197 | {packet, {entity_action, [MyEid, 1]}} -> % crouch 198 | mc_erl_entity_manager:broadcast_local(MyEid, {entity_metadata, MyEid, [{0, {byte, 2}}]}), 199 | State; 200 | 201 | {packet, {entity_action, [MyEid, 2]}} -> % uncrouch 202 | mc_erl_entity_manager:broadcast_local(MyEid, {entity_metadata, MyEid, [{0, {byte, 0}}]}), 203 | State; 204 | 205 | {packet, {entity_action, [MyEid, _N]}} -> 206 | % sprinting, leaving bed 207 | State; 208 | 209 | {packet, {player_abilities, [_, _Flying, _, _]}} -> 210 | State; 211 | 212 | {packet, {window_click, [0, -999, _, _TransactionId, _, _Item]}} -> 213 | State#state{cursor_item=empty}; 214 | 215 | {packet, {window_click, [0, SlotNo, 0, _TransactionId, false, _Item]}} -> % left click 216 | SelectedSlot = mc_erl_inventory:get_slot(State#state.player#player.inventory, SlotNo), 217 | CursorItem = State#state.cursor_item, 218 | Equal = mc_erl_inventory:items_equal(SelectedSlot, CursorItem), 219 | if 220 | SelectedSlot =:= empty -> 221 | NewInv = mc_erl_inventory:update_slot(Writer, State#state.player#player.inventory, SlotNo, {replace, CursorItem}), 222 | State#state{cursor_item=empty, player=State#state.player#player{inventory=NewInv}}; 223 | Equal -> 224 | {NewInv, Rest} = mc_erl_inventory:inventory_add_to_stack(Writer, MyPlayer#player.inventory, SlotNo, CursorItem), 225 | State#state{player=MyPlayer#player{inventory=NewInv}, cursor_item=Rest}; 226 | true -> 227 | NewInv = mc_erl_inventory:update_slot(Writer, State#state.player#player.inventory, SlotNo, {replace, CursorItem}), 228 | State#state{cursor_item=SelectedSlot, player=State#state.player#player{inventory=NewInv}} 229 | end; 230 | 231 | {packet, {window_click, [0, SlotNo, 1, _TransactionId, false, _Item]}} -> % right click 232 | SelectedSlot = mc_erl_inventory:get_slot(State#state.player#player.inventory, SlotNo), 233 | CursorItem = State#state.cursor_item, 234 | Equal = mc_erl_inventory:items_equal(SelectedSlot, CursorItem), 235 | case {CursorItem, SelectedSlot, Equal} of 236 | {empty, empty, _} -> State; 237 | {empty, #slot{count=Count}, _} -> 238 | SelectedCount = Count div 2, 239 | CursorCount = Count - SelectedCount, 240 | NewInv = mc_erl_inventory:update_slot(Writer, State#state.player#player.inventory, SlotNo, {replace, SelectedSlot#slot{count=SelectedCount}}), 241 | State#state{cursor_item=SelectedSlot#slot{count=CursorCount}, player=State#state.player#player{inventory=NewInv}}; 242 | {#slot{}, #slot{}, false} -> 243 | NewInv = mc_erl_inventory:update_slot(Writer, State#state.player#player.inventory, SlotNo, {replace, CursorItem}), 244 | State#state{cursor_item=SelectedSlot, player=State#state.player#player{inventory=NewInv}}; 245 | {#slot{count=CursorCount}, empty, _} -> 246 | {NewInv, empty} = mc_erl_inventory:inventory_add_to_stack(Writer, MyPlayer#player.inventory, SlotNo, CursorItem#slot{count=1}), 247 | NewCursorSlot = case CursorCount of 248 | 1 -> empty; 249 | OldCount -> CursorItem#slot{count=OldCount-1} 250 | end, 251 | State#state{cursor_item=NewCursorSlot, player=State#state.player#player{inventory=NewInv}}; 252 | {#slot{count=CursorCount}, #slot{}, true} -> 253 | case mc_erl_inventory:inventory_add_to_stack(Writer, MyPlayer#player.inventory, SlotNo, CursorItem#slot{count=1}) of 254 | {NewInv, empty} -> 255 | NewCursorSlot = case CursorCount of 256 | 1 -> empty; 257 | OldCount -> CursorItem#slot{count=OldCount-1} 258 | end, 259 | State#state{cursor_item=NewCursorSlot, player=State#state.player#player{inventory=NewInv}}; 260 | {_, _} -> 261 | State 262 | end 263 | end; 264 | 265 | {packet, {window_click, [0, SlotNo, _, _TransactionId, true, _Item]}} -> % shift click 266 | Inv = MyPlayer#player.inventory, 267 | SelectedSlot = mc_erl_inventory:get_slot(Inv, SlotNo), 268 | Inv2 = mc_erl_inventory:update_slot(Writer, Inv, SlotNo, empty), 269 | if 270 | SlotNo >= 9, SlotNo =< 35 -> 271 | case mc_erl_inventory:inventory_add(Writer, Inv2, 36, 44, SelectedSlot) of 272 | {NewInv, empty} -> 273 | State#state{player=State#state.player#player{inventory=NewInv}}; 274 | {NewInv, Rest} -> 275 | io:format("rest1~n"), 276 | NewInv2 = mc_erl_inventory:update_slot(Writer, NewInv, SlotNo, Rest), 277 | State#state{player=State#state.player#player{inventory=NewInv2}} 278 | end; 279 | SlotNo >= 36, SlotNo =< 44 -> 280 | case mc_erl_inventory:inventory_add(Writer, Inv2, 9, 35, SelectedSlot) of 281 | {NewInv, empty} -> 282 | State#state{player=State#state.player#player{inventory=NewInv}}; 283 | {NewInv, Rest} -> 284 | io:format("rest2~n"), 285 | NewInv2 = mc_erl_inventory:update_slot(Writer, NewInv, SlotNo, Rest), 286 | State#state{player=State#state.player#player{inventory=NewInv2}} 287 | end; 288 | true -> 289 | State 290 | end; 291 | 292 | {packet, {window_click, [_, _, _, TransactionId, _, _]}} -> 293 | write(Writer, {transaction, [0, TransactionId, false]}), 294 | State; 295 | 296 | {packet, {close_window, [0]}} -> 297 | State#state{cursor_item=empty}; 298 | 299 | {packet, {player_abilities, _}} -> 300 | State; %% probably check for proper flying/walking change 301 | 302 | {packet, UnknownPacket} -> 303 | lager:notice("[~s] unhandled packet: ~p~n", [?MODULE, UnknownPacket]), 304 | State; 305 | % protocol reactions end 306 | 307 | % chat 308 | {chat, Message} -> 309 | write(Writer, {chat_message, [Message]}), 310 | State; 311 | 312 | {animate, Eid, AnimationId} -> 313 | case dict:is_key(Eid, State#state.known_entities) of 314 | true -> write(Writer, {animation, [Eid, AnimationId]}); 315 | false -> ok 316 | end, 317 | State; 318 | 319 | {entity_metadata, Eid, Metadata} -> 320 | case dict:is_key(Eid, State#state.known_entities) of 321 | true -> write(Writer, {entity_metadata, [Eid, Metadata]}); 322 | false -> ok 323 | end, 324 | State; 325 | 326 | {tick, Tick} -> 327 | if 328 | (Tick rem 20) == 0 -> 329 | write(Writer, {time_update, [Tick, Tick]}); 330 | true -> ok 331 | end, 332 | FinalState = State#state{last_tick=Tick}, 333 | FinalState; 334 | 335 | {block_delta, {X, Y, Z, BlockId, Metadata}} -> 336 | case in_range({X, Y, Z}, State) of 337 | true -> 338 | write(Writer, {block_change, [X, Y, Z, BlockId, Metadata]}); 339 | false -> ok 340 | end, 341 | State; 342 | 343 | % just a notification, player_logic pulls column if necessary 344 | % possible enhancement: when compressed columns are cached, chunk_manager can send compressed chunk (hence binaries are referenced!) 345 | {update_column, {X, Z}=Coord} -> 346 | case sets:is_element(Coord, State#state.chunks) of 347 | false -> ok; 348 | true -> 349 | ChunkData = mc_erl_chunk_manager:get_chunk(Coord), 350 | write(Writer, {map_chunk, [X, Z, {parsed, ChunkData}]}) 351 | end, 352 | State; 353 | 354 | % adds or removes a player on the player list 355 | {player_list, Player, Mode} -> 356 | write(Writer, {player_list_item, [Player#player.name, 357 | case Mode of 358 | new -> true; 359 | delete -> false 360 | end, 1]}), 361 | State; 362 | 363 | % === entity messages === 364 | {new_entity, Entity} -> 365 | case MyEid =:= Entity#entity.eid of 366 | true -> State; 367 | false -> 368 | NewState = spawn_new_entity(Entity, State), 369 | NewState 370 | end; 371 | 372 | {set_entity_speed, Entity, {VX, VY, VZ}} -> 373 | Eid = Entity#entity.eid, 374 | AVx = trunc(VX*32000), 375 | AVy = trunc(VY*32000), 376 | AVz = trunc(VZ*32000), 377 | write(Writer, {entity_velocity, [Eid, AVx, AVy, AVz]}), 378 | State; 379 | 380 | 381 | {delete_entity, Eid} -> 382 | NewState = delete_entity(Eid, State), 383 | NewState; 384 | 385 | {update_entity_position, {Entity}} when is_record(Entity, entity) -> 386 | NewState = update_entity(Entity, State), 387 | NewState; 388 | 389 | net_disconnect -> 390 | {disconnect, net_disconnect, State}; 391 | 392 | {debug_exec, Fun} -> 393 | Fun(State); 394 | 395 | UnknownMessage -> 396 | lager:notice("[~s] unknown message: ~p~n", [?MODULE, UnknownMessage]), 397 | State 398 | end, 399 | case RetState of 400 | % graceful stops 401 | {disconnect, net_disconnect, DisconnectState} -> 402 | lager:warning("[~s] Connection lost with ~s~n", [?MODULE, DisconnectState#state.player#player.name]), 403 | {stop, normal, DisconnectState}; 404 | 405 | {disconnect, {graceful, _QuitMessage}, DisconnectState} -> 406 | lager:info("[~s] Player ~s has quit~n", [?MODULE, DisconnectState#state.player#player.name]), 407 | {stop, normal, DisconnectState}; 408 | 409 | % not graceful stops 410 | {disconnect, {invalid_username, AttemptedName}, DisconnectState} -> 411 | lager:info("[~s] Invalid username trying to log in: ~s~n", [?MODULE, AttemptedName]), 412 | {stop, normal, DisconnectState}; 413 | 414 | {disconnect, {multiple_login, AttemptedName}, DisconnectState} -> 415 | lager:info("[~s] Multiple login: ~s~n", [?MODULE, AttemptedName]), 416 | {stop, normal, DisconnectState}; 417 | 418 | {disconnect, {cheating, Reason}, DisconnectState} -> 419 | lager:notice("[~s] player is kicked due cheating: ~p~n", [?MODULE, Reason]), 420 | {stop, normal, DisconnectState}; 421 | 422 | {disconnect, Reason, DisconnectState} -> {stop, Reason, DisconnectState}; 423 | 424 | % right path 425 | Res -> {noreply, Res} 426 | end. 427 | 428 | write(none, _) -> not_sent; 429 | write(Writer, Packet) -> Writer ! {packet, Packet}. 430 | 431 | % === entities === 432 | spawn_new_entity(Entity, State) when is_record(Entity, entity) -> 433 | Eid = Entity#entity.eid, 434 | {X, Y, Z, Yaw, Pitch} = Entity#entity.location, 435 | Writer = State#state.writer, 436 | case Entity#entity.type of 437 | player -> 438 | PName = Entity#entity.name, 439 | PHolding = Entity#entity.item_id, 440 | write(Writer, {named_entity_spawn, 441 | [Eid, PName, X, Y, Z, trunc(Yaw*256/360), trunc(Yaw*256/360), 442 | case PHolding of 443 | empty -> 0; 444 | N when is_integer(N) -> N 445 | end, [{0, {byte, 0}}, {1, {short, 300}}, {8, {int, 0}}] ]}), 446 | NewKnownEntities = dict:store(Eid, {X, Y, Z, Yaw, Pitch, #ke_metadata{}}, State#state.known_entities), 447 | State#state{known_entities=NewKnownEntities}; 448 | dropped_item -> 449 | {Item, Count, Meta} = Entity#entity.item_id, 450 | write(Writer, {pickup_spawn, [Eid, Item, Count, Meta, X, Y, Z, 0, 0, 0]}), 451 | NewKnownEntities = dict:store(Eid, {X, Y, Z, Yaw, Pitch, #ke_metadata{}}, State#state.known_entities), 452 | State#state{known_entities=NewKnownEntities}; 453 | _ -> 454 | State 455 | end. 456 | 457 | delete_entity(Eid, State) -> 458 | case dict:is_key(Eid, State#state.known_entities) of 459 | true -> 460 | write(State#state.writer, {destroy_entity, [[Eid]]}), 461 | NewKnownEntities = dict:erase(Eid, State#state.known_entities), 462 | State#state{known_entities=NewKnownEntities}; 463 | false -> 464 | State 465 | end. 466 | 467 | % updates an entity's location 468 | update_entity(Entity, State) when is_record(Entity, entity) -> 469 | Eid = Entity#entity.eid, 470 | {X, Y, Z, _, _} = Entity#entity.location, 471 | if 472 | Eid == State#state.player#player.eid -> 473 | State; 474 | true -> case in_range({X, Y, Z}, State) of 475 | false -> 476 | case dict:is_key(Eid, State#state.known_entities) of 477 | true -> delete_entity(Eid, State); 478 | false -> State 479 | end; 480 | true -> 481 | case dict:is_key(Eid, State#state.known_entities) of 482 | true -> move_known_entity(Entity, State); 483 | false -> spawn_new_entity(Entity, State) 484 | end 485 | end 486 | end. 487 | 488 | move_known_entity(Entity, State) when is_record(Entity, entity) -> 489 | Eid = Entity#entity.eid, 490 | {X, Y, Z, Yaw, Pitch} = Entity#entity.location, 491 | Writer = State#state.writer, 492 | {OldX, OldY, OldZ, _OldYaw, _OldPitch, KEMetadata} = dict:fetch(Eid, State#state.known_entities), 493 | RelativeRelocations = KEMetadata#ke_metadata.relocations, 494 | DX = X - OldX, 495 | DY = Y - OldY, 496 | DZ = Z - OldZ, 497 | DDistance = lists:max([DX, DY, DZ]), 498 | FracYaw = trunc(Yaw*256/360), 499 | FracPitch = trunc(Pitch*256/360), 500 | 501 | ChangePackets = if 502 | (DDistance >= 4) or (RelativeRelocations >= 20) -> 503 | NewKnownEntities = dict:store(Eid, {X, Y, Z, Yaw, Pitch, KEMetadata#ke_metadata{relocations=0}}, State#state.known_entities), 504 | [{entity_teleport, [Eid, X, Y, Z, FracYaw, FracPitch]}]; 505 | true -> 506 | NewKnownEntities = dict:store(Eid, {X, Y, Z, Yaw, Pitch, KEMetadata#ke_metadata{relocations=RelativeRelocations + 1}}, State#state.known_entities), 507 | case Entity#entity.type of 508 | player -> [{entity_look_move, [Eid, DX, DY, DZ, FracYaw, FracPitch]}, 509 | {entity_head_look, [Eid, FracYaw]}]; 510 | dropped_item -> [{entity_teleport, [Eid, X, Y, Z, 0, 0]}] 511 | end 512 | end, 513 | lists:map(fun(Packet) -> write(Writer, Packet) end, ChangePackets), 514 | State#state{known_entities=NewKnownEntities}. 515 | 516 | 517 | send_player_list(State) -> 518 | Writer = State#state.writer, 519 | Players = mc_erl_entity_manager:get_all_players(), 520 | lists:foreach(fun(Player) -> write(Writer, {player_list_item, 521 | [Player#entity.name, true, 1]}) end, 522 | Players). 523 | 524 | send_player_abilities(State) when is_record(State, state) -> 525 | Player = State#state.player, 526 | CanFly = case Player#player.can_fly of true -> 1; false -> 0 end, 527 | Creative = case Player#player.mode of survival -> 0; creative -> 1 end, 528 | Flags = <<0:4, 0:1, CanFly:1, 0:1, Creative:1>>, 529 | write(State#state.writer, {player_abilities, [Flags, Player#player.fly_speed, 530 | Player#player.walk_speed]}). 531 | 532 | 533 | % ==== Checks if location is in visible range 534 | in_range({X, Y, Z}, State) -> 535 | ChunkPos = mc_erl_chunk_manager:coord_to_chunk({X, Y, Z}), 536 | sets:is_element(ChunkPos, State#state.chunks). 537 | 538 | % ==== Chunks loading 539 | check_chunks(Writer, PlayerChunk) -> 540 | check_chunks(Writer, PlayerChunk, sets:new()). 541 | 542 | check_chunks(Writer, PlayerChunk, LoadedChunks) -> 543 | NeededChunks = mc_erl_chunk_manager:chunks_in_range(PlayerChunk, 7), 544 | unload_chunks(Writer, sets:to_list(sets:subtract(LoadedChunks, NeededChunks))), 545 | load_chunks(Writer, sets:to_list(sets:subtract(NeededChunks, LoadedChunks))), 546 | NeededChunks. 547 | 548 | load_chunks(_Writer, []) -> ok; 549 | load_chunks(Writer, [{X, Z}|Rest]) -> 550 | ChunkData = mc_erl_chunk_manager:get_chunk({X, Z}), 551 | write(Writer, {map_chunk, [X, Z, {parsed, ChunkData}]}), 552 | load_chunks(Writer, Rest). 553 | 554 | unload_chunks(_Writer, []) -> ok; 555 | unload_chunks(Writer, [{X, Z}|Rest]) -> 556 | write(Writer, {map_chunk, [X, Z, unload]}), 557 | unload_chunks(Writer, Rest). 558 | 559 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------