summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorBjørn Lindeijer <bjorn@lindeijer.nl>2009-03-22 19:45:03 +0100
committerBjørn Lindeijer <bjorn@lindeijer.nl>2009-03-22 19:45:56 +0100
commit0c43d04b438d41c277ae80402d4b4888db1a0b64 (patch)
tree3aaeb75ecd1bcbe85decedab5f1fa426fe0411e3 /src
parenta7f5eaeb7f643658d356533a608f0f18d85b6d32 (diff)
parent401802c1d7a1b3d659bdc53a45d9a6292fc1121e (diff)
downloadmana-0c43d04b438d41c277ae80402d4b4888db1a0b64.tar.gz
mana-0c43d04b438d41c277ae80402d4b4888db1a0b64.tar.bz2
mana-0c43d04b438d41c277ae80402d4b4888db1a0b64.tar.xz
mana-0c43d04b438d41c277ae80402d4b4888db1a0b64.zip
Merged the tmwserv client with the eAthena client
This merge involved major changes on both sides, and as such took several weeks. Lots of things are expected to be broken now, however, we now have a single code base to improve and extend, which can be compiled to support either eAthena or tmwserv. In the coming months, the plan is to work towards a client that supports both eAthena and tmwserv, without needing to be recompiled. Conflicts: Everywhere!
Diffstat (limited to 'src')
-rw-r--r--src/CMakeLists.txt94
-rw-r--r--src/Makefile.am202
-rw-r--r--src/being.cpp315
-rw-r--r--src/being.h142
-rw-r--r--src/beingmanager.cpp80
-rw-r--r--src/beingmanager.h50
-rw-r--r--src/channel.cpp33
-rw-r--r--src/channel.h74
-rw-r--r--src/channelmanager.cpp85
-rw-r--r--src/channelmanager.h48
-rw-r--r--src/commandhandler.cpp323
-rw-r--r--src/commandhandler.h123
-rw-r--r--src/configuration.h1
-rw-r--r--src/effectmanager.cpp3
-rw-r--r--src/engine.cpp26
-rw-r--r--src/engine.h10
-rw-r--r--src/equipment.cpp42
-rw-r--r--src/equipment.h36
-rw-r--r--src/game.cpp281
-rw-r--r--src/game.h24
-rw-r--r--src/gui/browserbox.cpp1
-rw-r--r--src/gui/browserbox.h1
-rw-r--r--src/gui/buddywindow.cpp68
-rw-r--r--src/gui/buddywindow.h60
-rw-r--r--src/gui/buy.cpp24
-rw-r--r--src/gui/buy.h20
-rw-r--r--src/gui/changeemaildialog.cpp167
-rw-r--r--src/gui/changeemaildialog.h71
-rw-r--r--src/gui/changepassworddialog.cpp193
-rw-r--r--src/gui/changepassworddialog.h72
-rw-r--r--src/gui/char_select.cpp354
-rw-r--r--src/gui/char_select.h64
-rw-r--r--src/gui/char_server.cpp2
-rw-r--r--src/gui/chat.cpp290
-rw-r--r--src/gui/chat.h168
-rw-r--r--src/gui/chatinput.h2
-rw-r--r--src/gui/connection.cpp23
-rw-r--r--src/gui/connection.h13
-rw-r--r--src/gui/equipmentwindow.cpp57
-rw-r--r--src/gui/equipmentwindow.h27
-rw-r--r--src/gui/gui.cpp6
-rw-r--r--src/gui/guildlistbox.cpp130
-rw-r--r--src/gui/guildlistbox.h65
-rw-r--r--src/gui/guildwindow.cpp273
-rw-r--r--src/gui/guildwindow.h135
-rw-r--r--src/gui/icon.cpp58
-rw-r--r--src/gui/icon.h68
-rw-r--r--src/gui/inventorywindow.cpp141
-rw-r--r--src/gui/inventorywindow.h43
-rw-r--r--src/gui/item_amount.cpp19
-rw-r--r--src/gui/item_amount.h5
-rw-r--r--src/gui/itemcontainer.cpp432
-rw-r--r--src/gui/itemcontainer.h81
-rw-r--r--src/gui/itempopup.cpp2
-rw-r--r--src/gui/itemshortcutcontainer.cpp14
-rw-r--r--src/gui/itemshortcutwindow.cpp71
-rw-r--r--src/gui/itemshortcutwindow.h61
-rw-r--r--src/gui/linkhandler.h2
-rw-r--r--src/gui/login.cpp40
-rw-r--r--src/gui/login.h14
-rw-r--r--src/gui/magic.cpp92
-rw-r--r--src/gui/magic.h75
-rw-r--r--src/gui/menuwindow.cpp58
-rw-r--r--src/gui/minimap.cpp11
-rw-r--r--src/gui/ministatus.cpp35
-rw-r--r--src/gui/ministatus.h2
-rw-r--r--src/gui/npc_text.cpp2
-rw-r--r--src/gui/npclistdialog.cpp5
-rw-r--r--src/gui/npclistdialog.h5
-rw-r--r--src/gui/npcpostdialog.cpp101
-rw-r--r--src/gui/npcpostdialog.h55
-rw-r--r--src/gui/partywindow.cpp145
-rw-r--r--src/gui/partywindow.h96
-rw-r--r--src/gui/passwordfield.h2
-rw-r--r--src/gui/playerbox.cpp13
-rw-r--r--src/gui/popupmenu.cpp46
-rw-r--r--src/gui/progressbar.cpp41
-rw-r--r--src/gui/progressbar.h19
-rw-r--r--src/gui/quitdialog.cpp135
-rw-r--r--src/gui/quitdialog.h70
-rw-r--r--src/gui/register.cpp60
-rw-r--r--src/gui/register.h22
-rw-r--r--src/gui/sell.cpp28
-rw-r--r--src/gui/sell.h12
-rw-r--r--src/gui/serverdialog.cpp214
-rw-r--r--src/gui/serverdialog.h123
-rw-r--r--src/gui/setup.cpp8
-rw-r--r--src/gui/setup_audio.cpp1
-rw-r--r--src/gui/setup_video.cpp17
-rw-r--r--src/gui/setup_video.h2
-rw-r--r--src/gui/shop.cpp14
-rw-r--r--src/gui/shop.h10
-rw-r--r--src/gui/skilldialog.cpp263
-rw-r--r--src/gui/skilldialog.h139
-rw-r--r--src/gui/speechbubble.cpp1
-rw-r--r--src/gui/speechbubble.h1
-rw-r--r--src/gui/status.cpp16
-rw-r--r--src/gui/status.h2
-rw-r--r--src/gui/statuswindow.cpp370
-rw-r--r--src/gui/statuswindow.h105
-rw-r--r--src/gui/textdialog.cpp91
-rw-r--r--src/gui/textdialog.h66
-rw-r--r--src/gui/trade.cpp170
-rw-r--r--src/gui/trade.h61
-rw-r--r--src/gui/unregisterdialog.cpp141
-rw-r--r--src/gui/unregisterdialog.h70
-rw-r--r--src/gui/updatewindow.cpp4
-rw-r--r--src/gui/updatewindow.h2
-rw-r--r--src/gui/viewport.cpp158
-rw-r--r--src/gui/viewport.h27
-rw-r--r--src/gui/widgets/avatar.cpp53
-rw-r--r--src/gui/widgets/avatar.h59
-rw-r--r--src/gui/window.cpp8
-rw-r--r--src/gui/window.h2
-rw-r--r--src/guild.cpp69
-rw-r--r--src/guild.h108
-rw-r--r--src/inventory.cpp19
-rw-r--r--src/inventory.h12
-rw-r--r--src/item.cpp17
-rw-r--r--src/item.h11
-rw-r--r--src/itemshortcut.cpp6
-rw-r--r--src/joystick.cpp4
-rw-r--r--src/localplayer.cpp531
-rw-r--r--src/localplayer.h313
-rw-r--r--src/lockedarray.h27
-rw-r--r--src/logindata.h32
-rw-r--r--src/main.cpp963
-rw-r--r--src/main.h90
-rw-r--r--src/map.cpp162
-rw-r--r--src/map.h43
-rw-r--r--src/monster.cpp34
-rw-r--r--src/monster.h20
-rw-r--r--src/net/accountserver/account.cpp107
-rw-r--r--src/net/accountserver/account.h54
-rw-r--r--src/net/accountserver/accountserver.cpp81
-rw-r--r--src/net/accountserver/accountserver.h47
-rw-r--r--src/net/accountserver/internal.cpp32
-rw-r--r--src/net/accountserver/internal.h35
-rw-r--r--src/net/beinghandler.cpp753
-rw-r--r--src/net/beinghandler.h26
-rw-r--r--src/net/buysellhandler.cpp111
-rw-r--r--src/net/buysellhandler.h2
-rw-r--r--src/net/charserverhandler.cpp310
-rw-r--r--src/net/charserverhandler.h37
-rw-r--r--src/net/chathandler.cpp318
-rw-r--r--src/net/chathandler.h53
-rw-r--r--src/net/chatserver/chatserver.cpp146
-rw-r--r--src/net/chatserver/chatserver.h60
-rw-r--r--src/net/chatserver/guild.cpp95
-rw-r--r--src/net/chatserver/guild.h69
-rw-r--r--src/net/chatserver/internal.cpp32
-rw-r--r--src/net/chatserver/internal.h35
-rw-r--r--src/net/chatserver/party.cpp70
-rw-r--r--src/net/chatserver/party.h57
-rw-r--r--src/net/connection.cpp103
-rw-r--r--src/net/connection.h80
-rw-r--r--src/net/ea/beinghandler.cpp542
-rw-r--r--src/net/ea/beinghandler.h39
-rw-r--r--src/net/ea/buysellhandler.cpp133
-rw-r--r--src/net/ea/buysellhandler.h35
-rw-r--r--src/net/ea/charserverhandler.cpp235
-rw-r--r--src/net/ea/charserverhandler.h65
-rw-r--r--src/net/ea/chathandler.cpp175
-rw-r--r--src/net/ea/chathandler.h35
-rw-r--r--src/net/ea/equipmenthandler.cpp (renamed from src/net/equipmenthandler.cpp)58
-rw-r--r--src/net/ea/equipmenthandler.h (renamed from src/net/equipmenthandler.h)4
-rw-r--r--src/net/ea/inventoryhandler.cpp227
-rw-r--r--src/net/ea/inventoryhandler.h35
-rw-r--r--src/net/ea/loginhandler.cpp158
-rw-r--r--src/net/ea/loginhandler.h45
-rw-r--r--src/net/ea/maploginhandler.cpp (renamed from src/net/maploginhandler.cpp)26
-rw-r--r--src/net/ea/maploginhandler.h (renamed from src/net/maploginhandler.h)4
-rw-r--r--src/net/ea/network.cpp436
-rw-r--r--src/net/ea/network.h118
-rw-r--r--src/net/ea/npchandler.cpp111
-rw-r--r--src/net/ea/npchandler.h35
-rw-r--r--src/net/ea/partyhandler.cpp122
-rw-r--r--src/net/ea/partyhandler.h39
-rw-r--r--src/net/ea/playerhandler.cpp417
-rw-r--r--src/net/ea/playerhandler.h35
-rw-r--r--src/net/ea/protocol.cpp (renamed from src/net/protocol.cpp)0
-rw-r--r--src/net/ea/protocol.h162
-rw-r--r--src/net/ea/skillhandler.cpp (renamed from src/net/skillhandler.cpp)42
-rw-r--r--src/net/ea/skillhandler.h (renamed from src/net/skillhandler.h)4
-rw-r--r--src/net/ea/tradehandler.cpp220
-rw-r--r--src/net/ea/tradehandler.h37
-rw-r--r--src/net/effecthandler.cpp58
-rw-r--r--src/net/effecthandler.h38
-rw-r--r--src/net/gameserver/gameserver.cpp49
-rw-r--r--src/net/gameserver/gameserver.h39
-rw-r--r--src/net/gameserver/internal.cpp32
-rw-r--r--src/net/gameserver/internal.h35
-rw-r--r--src/net/gameserver/player.cpp202
-rw-r--r--src/net/gameserver/player.h71
-rw-r--r--src/net/guildhandler.cpp240
-rw-r--r--src/net/guildhandler.h40
-rw-r--r--src/net/internal.cpp27
-rw-r--r--src/net/internal.h30
-rw-r--r--src/net/inventoryhandler.cpp212
-rw-r--r--src/net/inventoryhandler.h2
-rw-r--r--src/net/itemhandler.cpp49
-rw-r--r--src/net/itemhandler.h2
-rw-r--r--src/net/loginhandler.cpp289
-rw-r--r--src/net/loginhandler.h28
-rw-r--r--src/net/logouthandler.cpp215
-rw-r--r--src/net/logouthandler.h62
-rw-r--r--src/net/messagehandler.cpp16
-rw-r--r--src/net/messagehandler.h9
-rw-r--r--src/net/messagein.cpp89
-rw-r--r--src/net/messagein.h37
-rw-r--r--src/net/messageout.cpp106
-rw-r--r--src/net/messageout.h43
-rw-r--r--src/net/network.cpp435
-rw-r--r--src/net/network.h143
-rw-r--r--src/net/npchandler.cpp103
-rw-r--r--src/net/npchandler.h2
-rw-r--r--src/net/partyhandler.cpp145
-rw-r--r--src/net/partyhandler.h26
-rw-r--r--src/net/playerhandler.cpp482
-rw-r--r--src/net/playerhandler.h5
-rw-r--r--src/net/protocol.h419
-rw-r--r--src/net/tradehandler.cpp217
-rw-r--r--src/net/tradehandler.h22
-rw-r--r--src/npc.cpp48
-rw-r--r--src/npc.h21
-rw-r--r--src/particle.cpp3
-rw-r--r--src/particle.h3
-rw-r--r--src/party.cpp2
-rw-r--r--src/player.cpp63
-rw-r--r--src/player.h69
-rw-r--r--src/resources/buddylist.cpp128
-rw-r--r--src/resources/buddylist.h79
-rw-r--r--src/resources/image.h2
-rw-r--r--src/resources/itemdb.cpp140
-rw-r--r--src/resources/itemdb.h2
-rw-r--r--src/resources/iteminfo.cpp21
-rw-r--r--src/resources/iteminfo.h91
-rw-r--r--src/resources/mapreader.cpp3
-rw-r--r--src/resources/monsterdb.cpp16
-rw-r--r--src/resources/monsterinfo.cpp45
-rw-r--r--src/resources/monsterinfo.h28
-rw-r--r--src/resources/spritedef.cpp32
-rw-r--r--src/resources/spritedef.h14
-rw-r--r--src/shopitem.h1
-rw-r--r--src/sound.h2
-rw-r--r--src/utils/sha256.cpp275
-rw-r--r--src/utils/sha256.h35
-rw-r--r--src/utils/strprintf.cpp1
-rw-r--r--src/winver.h6
249 files changed, 19017 insertions, 3557 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 38d3d82e..94688e66 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -2,6 +2,8 @@ FIND_PACKAGE(SDL REQUIRED)
FIND_PACKAGE(SDL_image REQUIRED)
FIND_PACKAGE(SDL_mixer REQUIRED)
FIND_PACKAGE(SDL_net REQUIRED)
+FIND_PACKAGE(SDL_ttf REQUIRED)
+FIND_PACKAGE(ENet REQUIRED)
FIND_PACKAGE(CURL REQUIRED)
FIND_PACKAGE(LibXml2 REQUIRED)
FIND_PACKAGE(PhysFS REQUIRED)
@@ -28,6 +30,8 @@ INCLUDE_DIRECTORIES(
${SDLIMAGE_INCLUDE_DIR}
${SDLMIXER_INCLUDE_DIR}
${SDLNET_INCLUDE_DIR}
+ ${SDLTTF_INCLUDE_DIR}
+ ${ENET_INCLUDE_DIR}
${PNG_INCLUDE_DIR}
${PHYSFS_INCLUDE_DIR}
${CURL_INCLUDE_DIR}
@@ -49,6 +53,8 @@ MARK_AS_ADVANCED(SDL_INCLUDE_DIR)
MARK_AS_ADVANCED(SDL_LIBRARY)
SET(SRCS
+ gui/widgets/avatar.cpp
+ gui/widgets/avatar.h
gui/widgets/dropdown.cpp
gui/widgets/dropdown.h
gui/widgets/resizegrip.cpp
@@ -71,6 +77,10 @@ SET(SRCS
gui/buy.h
gui/buysell.cpp
gui/buysell.h
+ gui/changeemaildialog.cpp
+ gui/changeemaildialog.h
+ gui/changepassworddialog.cpp
+ gui/changepassworddialog.h
gui/char_server.cpp
gui/char_server.h
gui/char_select.cpp
@@ -103,8 +113,14 @@ SET(SRCS
gui/gccontainer.h
gui/gui.cpp
gui/gui.h
+ gui/guildlistbox.cpp
+ gui/guildlistbox.h
+ gui/guildwindow.cpp
+ gui/guildwindow.h
gui/help.cpp
gui/help.h
+ gui/icon.cpp
+ gui/icon.h
gui/inttextfield.cpp
gui/inttextfield.h
gui/inventorywindow.cpp
@@ -124,6 +140,8 @@ SET(SRCS
gui/listbox.h
gui/login.cpp
gui/login.h
+ gui/magic.cpp
+ gui/magic.h
gui/menuwindow.cpp
gui/menuwindow.h
gui/minimap.cpp
@@ -136,10 +154,14 @@ SET(SRCS
gui/npclistdialog.h
gui/npcstringdialog.cpp
gui/npcstringdialog.h
+ gui/npcpostdialog.cpp
+ gui/npcpostdialog.h
gui/npc_text.cpp
gui/npc_text.h
gui/ok_dialog.cpp
gui/ok_dialog.h
+ gui/partywindow.h
+ gui/partywindow.cpp
gui/passwordfield.cpp
gui/passwordfield.h
gui/playerbox.cpp
@@ -148,6 +170,8 @@ SET(SRCS
gui/popupmenu.h
gui/progressbar.cpp
gui/progressbar.h
+ gui/quitdialog.cpp
+ gui/quitdialog.h
gui/radiobutton.cpp
gui/radiobutton.h
gui/recorder.cpp
@@ -160,6 +184,8 @@ SET(SRCS
gui/sdlinput.h
gui/sell.cpp
gui/sell.h
+ gui/serverdialog.cpp
+ gui/serverdialog.h
gui/setup.cpp
gui/setup.h
gui/setup_audio.cpp
@@ -197,36 +223,48 @@ SET(SRCS
gui/table_model.h
gui/textbox.cpp
gui/textbox.h
+ gui/textdialog.cpp
+ gui/textdialog.h
gui/textfield.cpp
gui/textfield.h
gui/trade.cpp
gui/trade.h
gui/truetypefont.cpp
gui/truetypefont.h
- gui/updatewindow.h
+ gui/unregisterdialog.cpp
+ gui/unregisterdialog.h
gui/updatewindow.cpp
+ gui/updatewindow.h
gui/viewport.cpp
gui/viewport.h
gui/window.cpp
gui/window.h
gui/windowcontainer.cpp
gui/windowcontainer.h
- net/beinghandler.h
net/beinghandler.cpp
- net/buysellhandler.h
+ net/beinghandler.h
net/buysellhandler.cpp
- net/charserverhandler.h
+ net/buysellhandler.h
net/charserverhandler.cpp
- net/chathandler.h
+ net/charserverhandler.h
net/chathandler.cpp
- net/equipmenthandler.h
+ net/chathandler.h
+ net/connection.cpp
+ net/connection.h
net/equipmenthandler.cpp
- net/inventoryhandler.h
+ net/equipmenthandler.h
+ net/guildhandler.cpp
+ net/guildhandler.h
+ net/internal.cpp
+ net/internal.h
net/inventoryhandler.cpp
- net/itemhandler.h
+ net/inventoryhandler.h
net/itemhandler.cpp
- net/loginhandler.h
+ net/itemhandler.h
net/loginhandler.cpp
+ net/loginhandler.h
+ net/logouthandler.cpp
+ net/logouthandler.h
net/maploginhandler.cpp
net/maploginhandler.h
net/messagehandler.cpp
@@ -249,12 +287,36 @@ SET(SRCS
net/skillhandler.h
net/tradehandler.cpp
net/tradehandler.h
+ net/effecthandler.cpp
+ net/effecthandler.h
+ net/accountserver/account.cpp
+ net/accountserver/account.h
+ net/accountserver/accountserver.cpp
+ net/accountserver/accountserver.h
+ net/accountserver/internal.cpp
+ net/accountserver/internal.h
+ net/chatserver/chatserver.cpp
+ net/chatserver/chatserver.h
+ net/chatserver/guild.cpp
+ net/chatserver/guild.h
+ net/chatserver/internal.cpp
+ net/chatserver/internal.h
+ net/chatserver/party.cpp
+ net/chatserver/party.h
+ net/gameserver/gameserver.cpp
+ net/gameserver/gameserver.h
+ net/gameserver/internal.cpp
+ net/gameserver/internal.h
+ net/gameserver/player.cpp
+ net/gameserver/player.h
resources/action.cpp
resources/action.h
resources/ambientoverlay.cpp
resources/ambientoverlay.h
resources/animation.cpp
resources/animation.h
+ resources/buddylist.cpp
+ resources/buddylist.h
resources/colordb.cpp
resources/colordb.h
resources/dye.cpp
@@ -296,6 +358,8 @@ SET(SRCS
utils/dtor.h
utils/fastsqrt.h
utils/gettext.h
+ utils/sha256.h
+ utils/sha256.cpp
utils/stringutils.cpp
utils/stringutils.h
utils/strprintf.cpp
@@ -310,6 +374,12 @@ SET(SRCS
being.h
beingmanager.cpp
beingmanager.h
+ channel.cpp
+ channel.h
+ channelmanager.cpp
+ channelmanager.h
+ commandhandler.cpp
+ commandhandler.h
configlistener.h
configuration.cpp
configuration.h
@@ -330,6 +400,8 @@ SET(SRCS
graphics.cpp
graphics.h
guichanfwd.h
+ guild.cpp
+ guild.h
imageparticle.cpp
imageparticle.h
inventory.cpp
@@ -391,6 +463,8 @@ SET(SRCS
tileset.h
vector.cpp
vector.h
+ effectmanager.cpp
+ effectmanager.h
)
ADD_EXECUTABLE(tmw ${SRCS})
@@ -400,6 +474,8 @@ TARGET_LINK_LIBRARIES(tmw
${SDLIMAGE_LIBRARY}
${SDLMIXER_LIBRARY}
${SDLNET_LIBRARY}
+ ${SDLTTF_LIBRARY}
+ ${ENET_LIBRARIES}
${PNG_LIBRARIES}
${PHYSFS_LIBRARY}
${CURL_LIBRARIES}
diff --git a/src/Makefile.am b/src/Makefile.am
index e8e9a695..ce51b12d 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,7 +1,13 @@
AUTOMAKE_OPTIONS = subdir-objects
bin_PROGRAMS = tmw
-tmw_SOURCES = gui/widgets/dropdown.cpp \
+
+tmw_CXXFLAGS = -DPKG_DATADIR=\""$(pkgdatadir)/"\" \
+ -DLOCALEDIR=\""$(localedir)"\"
+
+tmw_SOURCES = gui/widgets/avatar.cpp \
+ gui/widgets/avatar.h \
+ gui/widgets/dropdown.cpp \
gui/widgets/dropdown.h \
gui/widgets/layout.cpp \
gui/widgets/layout.h \
@@ -23,8 +29,6 @@ tmw_SOURCES = gui/widgets/dropdown.cpp \
gui/buysell.h \
gui/char_select.cpp \
gui/char_select.h \
- gui/char_server.cpp \
- gui/char_server.h \
gui/chat.cpp \
gui/chat.h \
gui/chatinput.cpp \
@@ -35,8 +39,6 @@ tmw_SOURCES = gui/widgets/dropdown.cpp \
gui/color.h \
gui/confirm_dialog.cpp \
gui/confirm_dialog.h \
- gui/connection.cpp \
- gui/connection.h \
gui/debugwindow.cpp \
gui/debugwindow.h \
gui/emotecontainer.cpp \
@@ -55,8 +57,10 @@ tmw_SOURCES = gui/widgets/dropdown.cpp \
gui/gui.h \
gui/help.cpp \
gui/help.h \
- gui/inttextfield.h \
+ gui/icon.cpp \
+ gui/icon.h \
gui/inttextfield.cpp \
+ gui/inttextfield.h \
gui/inventorywindow.cpp \
gui/inventorywindow.h \
gui/itemcontainer.cpp \
@@ -133,72 +137,40 @@ tmw_SOURCES = gui/widgets/dropdown.cpp \
gui/shortcutwindow.h \
gui/shortcutcontainer.cpp \
gui/shortcutcontainer.h \
- gui/skill.cpp \
- gui/skill.h \
gui/slider.cpp \
gui/slider.h \
gui/speechbubble.cpp \
gui/speechbubble.h \
- gui/status.cpp \
- gui/status.h \
gui/table.cpp \
gui/table.h \
gui/table_model.cpp \
gui/table_model.h \
gui/textbox.cpp \
gui/textbox.h \
+ gui/textdialog.cpp \
+ gui/textdialog.h \
gui/textfield.cpp \
gui/textfield.h \
gui/trade.cpp \
gui/trade.h \
gui/truetypefont.cpp \
gui/truetypefont.h \
- gui/updatewindow.h \
gui/updatewindow.cpp \
+ gui/updatewindow.h \
gui/viewport.cpp \
gui/viewport.h \
gui/window.cpp \
gui/window.h \
gui/windowcontainer.cpp \
gui/windowcontainer.h \
- net/beinghandler.h \
- net/beinghandler.cpp \
- net/buysellhandler.h \
- net/buysellhandler.cpp \
- net/charserverhandler.h \
- net/charserverhandler.cpp \
- net/chathandler.h \
- net/chathandler.cpp \
- net/equipmenthandler.h \
- net/equipmenthandler.cpp \
- net/inventoryhandler.h \
- net/inventoryhandler.cpp \
net/itemhandler.h \
net/itemhandler.cpp \
- net/loginhandler.h \
- net/loginhandler.cpp \
- net/maploginhandler.cpp \
- net/maploginhandler.h \
net/messagehandler.cpp \
net/messagehandler.h \
net/messagein.cpp \
net/messagein.h \
net/messageout.cpp \
net/messageout.h \
- net/network.cpp \
- net/network.h \
- net/npchandler.cpp \
- net/npchandler.h \
- net/partyhandler.cpp \
- net/partyhandler.h \
- net/playerhandler.cpp \
- net/playerhandler.h \
- net/protocol.cpp \
- net/protocol.h \
- net/skillhandler.cpp \
- net/skillhandler.h \
- net/tradehandler.cpp \
- net/tradehandler.h \
resources/action.cpp \
resources/action.h \
resources/ambientoverlay.cpp \
@@ -246,6 +218,8 @@ tmw_SOURCES = gui/widgets/dropdown.cpp \
utils/dtor.h \
utils/fastsqrt.h \
utils/gettext.h \
+ utils/sha256.cpp \
+ utils/sha256.h \
utils/stringutils.cpp \
utils/stringutils.h \
utils/strprintf.cpp \
@@ -261,6 +235,10 @@ tmw_SOURCES = gui/widgets/dropdown.cpp \
being.h \
beingmanager.cpp \
beingmanager.h \
+ channel.cpp \
+ channel.h \
+ channelmanager.cpp \
+ channelmanager.h \
configlistener.h \
configuration.cpp \
configuration.h \
@@ -316,8 +294,6 @@ tmw_SOURCES = gui/widgets/dropdown.cpp \
particleemitter.cpp \
particleemitter.h \
particleemitterprop.h \
- party.cpp \
- party.h \
player.cpp \
player.h \
player_relations.cpp \
@@ -347,8 +323,140 @@ tmw_SOURCES = gui/widgets/dropdown.cpp \
vector.cpp \
vector.h
+if SERVER_TMWSERV
+tmw_CXXFLAGS += -DTMWSERV_SUPPORT
+tmw_SOURCES += \
+ gui/buddywindow.cpp \
+ gui/buddywindow.h \
+ gui/changeemaildialog.cpp \
+ gui/changeemaildialog.h \
+ gui/changepassworddialog.cpp \
+ gui/changepassworddialog.h \
+ gui/connection.cpp \
+ gui/connection.h \
+ gui/guildlistbox.cpp \
+ gui/guildlistbox.h \
+ gui/guildwindow.cpp \
+ gui/guildwindow.h \
+ gui/magic.cpp \
+ gui/magic.h \
+ gui/npcpostdialog.cpp \
+ gui/npcpostdialog.h \
+ gui/partywindow.cpp \
+ gui/partywindow.h \
+ gui/quitdialog.cpp \
+ gui/quitdialog.h \
+ gui/serverdialog.cpp \
+ gui/serverdialog.h \
+ gui/skilldialog.cpp \
+ gui/skilldialog.h \
+ gui/statuswindow.cpp \
+ gui/statuswindow.h \
+ gui/unregisterdialog.cpp \
+ gui/unregisterdialog.h \
+ net/accountserver/account.cpp \
+ net/accountserver/account.h \
+ net/accountserver/accountserver.cpp \
+ net/accountserver/accountserver.h \
+ net/accountserver/internal.cpp \
+ net/accountserver/internal.h \
+ net/chatserver/chatserver.cpp \
+ net/chatserver/chatserver.h \
+ net/chatserver/guild.cpp \
+ net/chatserver/guild.h \
+ net/chatserver/internal.cpp \
+ net/chatserver/internal.h \
+ net/chatserver/party.cpp \
+ net/chatserver/party.h \
+ net/gameserver/gameserver.cpp \
+ net/gameserver/gameserver.h \
+ net/gameserver/internal.cpp \
+ net/gameserver/internal.h \
+ net/gameserver/player.cpp \
+ net/gameserver/player.h \
+ net/beinghandler.cpp \
+ net/beinghandler.h \
+ net/buysellhandler.cpp \
+ net/buysellhandler.h \
+ net/charserverhandler.cpp \
+ net/charserverhandler.h \
+ net/chathandler.cpp \
+ net/chathandler.h \
+ net/connection.cpp \
+ net/connection.h \
+ net/effecthandler.cpp \
+ net/effecthandler.h \
+ net/guildhandler.cpp \
+ net/guildhandler.h \
+ net/internal.cpp \
+ net/internal.h \
+ net/inventoryhandler.cpp \
+ net/inventoryhandler.h \
+ net/loginhandler.cpp \
+ net/loginhandler.h \
+ net/logouthandler.cpp \
+ net/logouthandler.h \
+ net/network.cpp \
+ net/network.h \
+ net/npchandler.cpp \
+ net/npchandler.h \
+ net/partyhandler.cpp \
+ net/partyhandler.h \
+ net/playerhandler.cpp \
+ net/playerhandler.h \
+ net/protocol.h \
+ net/tradehandler.cpp \
+ net/tradehandler.h \
+ resources/buddylist.cpp \
+ resources/buddylist.h \
+ commandhandler.cpp \
+ commandhandler.h \
+ guild.cpp \
+ guild.h
+endif
+
+if SERVER_EATHENA
+tmw_CXXFLAGS += -DEATHENA_SUPPORT
+tmw_SOURCES += \
+ gui/char_server.cpp \
+ gui/char_server.h \
+ gui/skill.cpp \
+ gui/skill.h \
+ gui/status.cpp \
+ gui/status.h \
+ net/ea/beinghandler.cpp \
+ net/ea/beinghandler.h \
+ net/ea/buysellhandler.cpp \
+ net/ea/buysellhandler.h \
+ net/ea/charserverhandler.cpp \
+ net/ea/charserverhandler.h \
+ net/ea/chathandler.cpp \
+ net/ea/chathandler.h \
+ net/ea/equipmenthandler.cpp \
+ net/ea/equipmenthandler.h \
+ net/ea/inventoryhandler.cpp \
+ net/ea/inventoryhandler.h \
+ net/ea/loginhandler.cpp \
+ net/ea/loginhandler.h \
+ net/ea/maploginhandler.cpp \
+ net/ea/maploginhandler.h \
+ net/ea/network.cpp \
+ net/ea/network.h \
+ net/ea/npchandler.cpp \
+ net/ea/npchandler.h \
+ net/ea/partyhandler.cpp \
+ net/ea/partyhandler.h \
+ net/ea/playerhandler.cpp \
+ net/ea/playerhandler.h \
+ net/ea/protocol.cpp \
+ net/ea/protocol.h \
+ net/ea/skillhandler.cpp \
+ net/ea/skillhandler.h \
+ net/ea/tradehandler.cpp \
+ net/ea/tradehandler.h \
+ party.cpp \
+ party.h
+endif
+
# set the include path found by configure
-INCLUDES = \
- $(all_includes) \
- -DPKG_DATADIR=\""$(pkgdatadir)/"\" \
- -DLOCALEDIR=\""$(localedir)"\"
+INCLUDES = $(all_includes)
diff --git a/src/being.cpp b/src/being.cpp
index 43480eba..7f5a7d33 100644
--- a/src/being.cpp
+++ b/src/being.cpp
@@ -55,6 +55,11 @@
#include <cassert>
#include <cmath>
+namespace {
+const bool debug_movement = true;
+}
+
+
#define BEING_EFFECTS_FILE "effects.xml"
#define HAIR_FILE "hair.xml"
@@ -69,21 +74,30 @@ static const int DEFAULT_WIDTH = 32;
static const int DEFAULT_HEIGHT = 32;
Being::Being(int id, int job, Map *map):
- mJob(job),
+#ifdef EATHENA_SUPPORT
mX(0), mY(0),
- mAction(STAND),
mWalkTime(0),
+#endif
mEmotion(0), mEmotionTime(0),
mAttackSpeed(350),
+ mAction(STAND),
+ mJob(job),
mId(id),
- mWalkSpeed(150),
mDirection(DOWN),
+#ifdef TMWSERV_SUPPORT
+ mSpriteDirection(DIRECTION_DOWN),
+#endif
mMap(NULL),
mName(""),
mIsGM(false),
mParticleEffects(config.getValue("particleeffects", 1)),
mEquippedWeapon(NULL),
- mHairStyle(1), mHairColor(0),
+#ifdef TMWSERV_SUPPORT
+ mHairStyle(0),
+#else
+ mHairStyle(1),
+#endif
+ mHairColor(0),
mGender(GENDER_UNSPECIFIED),
mSpeechTime(0),
mPx(0), mPy(0),
@@ -94,6 +108,11 @@ Being::Being(int id, int job, Map *map):
mStatusParticleEffects(&mStunParticleEffects, false),
mChildParticleEffects(&mStatusParticleEffects, false),
mMustResetParticles(false),
+#ifdef TMWSERV_SUPPORT
+ mWalkSpeed(100),
+#else
+ mWalkSpeed(150),
+#endif
mUsedTargetCursor(NULL)
{
setMap(map);
@@ -150,12 +169,188 @@ Being::~Being()
delete mText;
}
+void Being::setPosition(const Vector &pos)
+{
+ mPos = pos;
+ mDest = pos;
+ mPath.clear();
+}
+
+#ifdef EATHENA_SUPPORT
void Being::setDestination(Uint16 destX, Uint16 destY)
{
if (mMap)
- setPath(mMap->findPath(mX, mY, destX, destY));
+ setPath(mMap->findPath(mX, mY, destX, destY, getWalkMask()));
+}
+#endif
+
+#ifdef TMWSERV_SUPPORT
+void Being::adjustCourse(int srcX, int srcY, int dstX, int dstY)
+{
+ if (debug_movement)
+ printf("%p adjustCourse(%d, %d, %d, %d)\n",
+ (void*) this, srcX, srcY, dstX, dstY);
+
+ mDest.x = dstX;
+ mDest.y = dstY;
+
+ // Find a path to the destination when it is at least a tile away
+ if (mMap && fabsf((mDest - mPos).length()) > 32) {
+ setPath(mMap->findPath((int) mPos.x / 32, (int) mPos.y / 32,
+ dstX / 32, dstY / 32, getWalkMask()));
+ } else {
+ setPath(Path());
+ }
+
+ // TODO: Evaluate the implementation of this method
+ /*
+ if (mX / 32 == dstX / 32 && mY / 32 == dstY / 32)
+ {
+ // The being is already on the last tile of the path.
+ Path p;
+ p.push_back(Position(dstX, dstY));
+ setPath(p);
+ return;
+ }
+
+ Path p1;
+ int p1_size, p1_length;
+ Uint16 *p1_dist;
+ int onPath = -1;
+ if (srcX / 32 == dstX / 32 && srcY / 32 == dstY / 32)
+ {
+ p1_dist = new Uint16[1];
+ p1_size = 1;
+ p1_dist[0] = 0;
+ p1_length = 0;
+ }
+ else
+ {
+ p1 = mMap->findPath(srcX / 32, srcY / 32, dstX / 32, dstY / 32, getWalkMask());
+ if (p1.empty())
+ {
+ // No path, but don't teleport since it could be user input.
+ setPath(p1);
+ return;
+ }
+ p1_size = p1.size();
+ p1_dist = new Uint16[p1_size];
+ int j = 0;
+ // Remove last tile so that it can be replaced by the exact destination.
+ p1.pop_back();
+ for (Path::iterator i = p1.begin(), i_end = p1.end(); i != i_end; ++i)
+ {
+ // Get distance from source to tile i.
+ p1_dist[j] = mMap->getMetaTile(i->x, i->y)->Gcost;
+ // Check if the being is already walking on the path.
+ if (i->x == mX / 32 && i->y == mY / 32)
+ {
+ onPath = j;
+ }
+ // Do not set any offset for intermediate steps.
+ i->x = i->x * 32;
+ i->y = i->y * 32;
+ ++j;
+ }
+ p1_length = mMap->getMetaTile(dstX / 32, dstY / 32)->Gcost;
+ p1_dist[p1_size - 1] = p1_length;
+ }
+ p1.push_back(Position(dstX, dstY));
+
+ if (mX / 32 == srcX / 32 && mY / 32 == srcY / 32)
+ {
+ // The being is at the start of the path.
+ setPath(p1);
+ delete[] p1_dist;
+ return;
+ }
+
+ if (onPath >= 0)
+ {
+ // The being is already on the path, but it needs to be slowed down.
+ for (int j = onPath; j >= 0; --j)
+ {
+ p1.pop_front();
+ }
+ int r = p1_length - p1_dist[onPath]; // remaining length
+ assert(r > 0);
+ setPath(p1, p1_length * 1024 / r);
+ delete[] p1_dist;
+ return;
+ }
+
+ Path bestPath;
+ int bestRating = -1, bestStart = 0, bestLength = 0;
+ int j = 0;
+
+ for (Path::iterator i = p1.begin(), i_end = p1.end(); i != i_end; ++i)
+ {
+ // Look if it is worth passing by tile i.
+ Path p2 = mMap->findPath(mX / 32, mY / 32, i->x / 32, i->y / 32, getWalkMask());
+ if (!p2.empty())
+ {
+ int l1 = mMap->getMetaTile(i->x / 32, i->y / 32)->Gcost;
+ int l2 = p1_length - p1_dist[j];
+ int r = l1 + l2 / 2; // TODO: tune rating formula
+ assert(r > 0);
+ if (bestRating < 0 || r < bestRating)
+ {
+ bestPath.swap(p2);
+ bestRating = r;
+ bestStart = j;
+ bestLength = l1 + l2;
+ }
+ }
+ ++j;
+ }
+
+ if (bestRating < 0)
+ {
+ // Unable to reach the path? Still, don't teleport since it could be
+ // user input instead of server command.
+ setPath(p1);
+ delete[] p1_dist;
+ return;
+ }
+
+ bestPath.pop_back();
+ for (Path::iterator i = bestPath.begin(), i_end = bestPath.end(); i != i_end; ++i)
+ {
+ i->x = i->x * 32;
+ i->y = i->y * 32;
+ }
+
+ // Concatenate paths.
+ for (int j = bestStart; j > 0; --j)
+ {
+ p1.pop_front();
+ }
+ p1.splice(p1.begin(), bestPath);
+
+ assert(bestLength > 0);
+ setPath(p1, p1_length * 1024 / bestLength);
+ delete[] p1_dist;
+ */
}
+void Being::adjustCourse(int srcX, int srcY)
+{
+ if (debug_movement)
+ printf("%p adjustCourse(%d, %d)\n", (void*) this, srcX, srcY);
+
+ if (!mPath.empty())
+ adjustCourse(srcX, srcY, mPath.back().x * 32, mPath.back().y * 32);
+}
+
+void Being::setDestination(int destX, int destY)
+{
+ if (debug_movement)
+ printf("%p setDestination(%d, %d)\n", (void*) this, destX, destY);
+
+ adjustCourse((int) mPos.x, (int) mPos.y, destX, destY);
+}
+#endif // TMWSERV_SUPPORT
+
void Being::clearPath()
{
mPath.clear();
@@ -164,12 +359,15 @@ void Being::clearPath()
void Being::setPath(const Path &path)
{
mPath = path;
-
+#ifdef TMWSERV_SUPPORT
+ std::cout << this << " New path: " << path << std::endl;
+#else
if (mAction != WALK && mAction != DEAD)
{
nextStep();
mWalkTime = tick_time;
}
+#endif
}
void Being::setHairStyle(int style, int color)
@@ -178,7 +376,7 @@ void Being::setHairStyle(int style, int color)
mHairColor = color < 0 ? mHairColor : color % ColorDB::size();
}
-void Being::setSprite(int slot, int id, std::string color)
+void Being::setSprite(int slot, int id, const std::string &color)
{
assert(slot >= BASE_SPRITE && slot < VECTOREND_SPRITE);
mSpriteIDs[slot] = id;
@@ -245,7 +443,12 @@ void Being::takeDamage(int amount)
// Show damage number
particleEngine->addTextSplashEffect(damage, 255, 255, 255, font,
+#ifdef TMWSERV_SUPPORT
+ (int) mPos.x + 16,
+ (int) mPos.y + 16);
+#else
mPx + 16, mPy + 16);
+#endif
effectManager->trigger(26, this);
}
@@ -255,11 +458,17 @@ void Being::showCrit()
}
+#ifdef TMWSERV_SUPPORT
+void Being::handleAttack()
+#else
void Being::handleAttack(Being *victim, int damage)
+#endif
{
setAction(Being::ATTACK);
+#ifdef EATHENA_SUPPORT
mFrame = 0;
mWalkTime = tick_time;
+#endif
}
void Being::setMap(Map *map)
@@ -284,7 +493,7 @@ void Being::controlParticle(Particle *particle)
mChildParticleEffects.addLocally(particle);
}
-void Being::setAction(Action action)
+void Being::setAction(Action action, int attackType)
{
SpriteAction currentAction = ACTION_INVALID;
@@ -340,8 +549,27 @@ void Being::setDirection(Uint8 direction)
if (mDirection == direction)
return;
+#ifdef TMWSERV_SUPPORT
+ // if the direction does not change much, keep the common component
+ int mFaceDirection = mDirection & direction;
+ if (!mFaceDirection)
+ mFaceDirection = direction;
+ mDirection = direction;
+
+ SpriteDirection dir;
+ if (mFaceDirection & UP)
+ dir = DIRECTION_UP;
+ else if (mFaceDirection & DOWN)
+ dir = DIRECTION_DOWN;
+ else if (mFaceDirection & RIGHT)
+ dir = DIRECTION_RIGHT;
+ else
+ dir = DIRECTION_LEFT;
+ mSpriteDirection = dir;
+#else
mDirection = direction;
SpriteDirection dir = getSpriteDirection();
+#endif
for (int i = 0; i < VECTOREND_SPRITE; i++)
{
@@ -350,6 +578,7 @@ void Being::setDirection(Uint8 direction)
}
}
+#ifdef EATHENA_SUPPORT
SpriteDirection Being::getSpriteDirection() const
{
SpriteDirection dir;
@@ -397,7 +626,7 @@ void Being::nextStep()
setDirection(dir);
- if (mMap->tileCollides(pos.x, pos.y))
+ if (!mMap->getWalk(pos.x, pos.y, getWalkMask()))
{
setAction(STAND);
return;
@@ -408,12 +637,13 @@ void Being::nextStep()
setAction(WALK);
mWalkTime += mWalkSpeed / 10;
}
+#endif
void Being::logic()
{
// Reduce the time that speech is still displayed
if (mSpeechTime > 0)
- mSpeechTime--;
+ mSpeechTime--;
// Remove text if speech boxes aren't being used
if (mSpeechTime == 0 && mText)
@@ -422,6 +652,42 @@ void Being::logic()
mText = 0;
}
+#ifdef TMWSERV_SUPPORT
+ const Vector dest = (mPath.empty()) ?
+ mDest : Vector(mPath.front().x * 32 + 16,
+ mPath.front().y * 32 + 16);
+
+ Vector dir = dest - mPos;
+ const float length = dir.length();
+
+ // When we're over 2 pixels from our destination, move to it
+ // TODO: Should be possible to make it even pixel exact, but this solves
+ // the jigger caused by moving too far.
+ if (length > 2.0f) {
+ const float speed = mWalkSpeed / 100.0f;
+ mPos += dir / (length / speed);
+
+ if (mAction != WALK)
+ setAction(WALK);
+
+ // Update the player sprite direction
+ int direction = 0;
+ const float dx = std::abs(dir.x);
+ const float dy = std::abs(dir.y);
+ if (dx > dy)
+ direction |= (dir.x > 0) ? RIGHT : LEFT;
+ else
+ direction |= (dir.y > 0) ? DOWN : UP;
+ setDirection(direction);
+ }
+ else if (!mPath.empty()) {
+ // TODO: Pop as soon as there is a direct unblocked line to the next
+ // point on the path.
+ mPath.pop_front();
+ } else if (mAction == WALK) {
+ setAction(STAND);
+ }
+#else
int oldPx = mPx;
int oldPy = mPy;
@@ -433,6 +699,7 @@ void Being::logic()
{
updateCoords();
}
+#endif
if (mEmotion != 0)
{
@@ -463,15 +730,23 @@ void Being::logic()
}
// Update particle effects
+#ifdef TMWSERV_SUPPORT
mChildParticleEffects.moveTo((float) mPx + 16.0f,
(float) mPy + 32.0f);
-
+#else
+ mChildParticleEffects.moveTo(mPos.x, mPos.y);
+#endif
}
void Being::draw(Graphics *graphics, int offsetX, int offsetY) const
{
+#ifdef TMWSERV_SUPPORT
+ int px = (int) mPos.x + offsetX;
+ int py = (int) mPos.y + offsetY;
+#else
int px = mPx + offsetX;
int py = mPy + offsetY;
+#endif
if (mUsedTargetCursor)
{
@@ -482,7 +757,13 @@ void Being::draw(Graphics *graphics, int offsetX, int offsetY) const
{
if (mSprites[i])
{
+#ifdef TMWSERV_SUPPORT
+ // TODO: Eventually, we probably should fix all sprite offsets so
+ // that this translation isn't necessary anymore.
+ mSprites[i]->draw(graphics, px - 16, py - 32);
+#else
mSprites[i]->draw(graphics, px, py);
+#endif
}
}
}
@@ -492,8 +773,13 @@ void Being::drawEmotion(Graphics *graphics, int offsetX, int offsetY)
if (!mEmotion)
return;
+#ifdef TMWSERV_SUPPORT
+ const int px = (int) mPos.x + offsetX + 3;
+ const int py = (int) mPos.y + offsetY - 60;
+#else
const int px = mPx + offsetX + 3;
const int py = mPy + offsetY - 60;
+#endif
const int emotionIndex = mEmotion - 1;
if (emotionIndex >= 0 && emotionIndex <= EmoteDB::getLast())
@@ -502,8 +788,13 @@ void Being::drawEmotion(Graphics *graphics, int offsetX, int offsetY)
void Being::drawSpeech(int offsetX, int offsetY)
{
+#ifdef TMWSERV_SUPPORT
+ int px = (int) mPos.x + offsetX;
+ int py = (int) mPos.y + offsetY;
+#else
const int px = mPx + offsetX;
const int py = mPy + offsetY;
+#endif
const int speech = (int) config.getValue("speech", NAME_IN_BUBBLE);
// Draw speech above this being
@@ -612,6 +903,7 @@ void Being::setStatusEffect(int index, bool active)
}
}
+#ifdef EATHENA_SUPPORT
int Being::getOffset(char pos, char neg) const
{
// Check whether we're walking in the requested direction
@@ -637,6 +929,7 @@ int Being::getOffset(char pos, char neg) const
return offset;
}
+#endif
int Being::getWidth() const
{
diff --git a/src/being.h b/src/being.h
index ef830e3a..a704b3df 100644
--- a/src/being.h
+++ b/src/being.h
@@ -30,9 +30,11 @@
#include <string>
#include <vector>
+#include "map.h"
#include "particlecontainer.h"
#include "position.h"
#include "sprite.h"
+#include "vector.h"
#include "resources/spritedef.h"
@@ -78,7 +80,9 @@ class Being : public Sprite
};
/**
- * Action the being is currently performing.
+ * Action the being is currently performing
+ * WARNING: Has to be in sync with the same enum in the Being class
+ * of the server!
*/
enum Action
{
@@ -96,14 +100,20 @@ class Being : public Sprite
SHOE_SPRITE,
BOTTOMCLOTHES_SPRITE,
TOPCLOTHES_SPRITE,
+#ifdef EATHENA_SUPPORT
MISC1_SPRITE,
MISC2_SPRITE,
+#endif
HAIR_SPRITE,
HAT_SPRITE,
+#ifdef EATHENA_SUPPORT
CAPE_SPRITE,
GLOVES_SPRITE,
+#endif
WEAPON_SPRITE,
+#ifdef EATHENA_SUPPORT
SHIELD_SPRITE,
+#endif
VECTOREND_SPRITE
};
@@ -129,15 +139,17 @@ class Being : public Sprite
*/
enum { DOWN = 1, LEFT = 2, UP = 4, RIGHT = 8 };
- Uint16 mJob; /**< Job (player job, npc, monster, ) */
+#ifdef EATHENA_SUPPORT
Uint16 mX, mY; /**< Tile coordinates */
- Action mAction; /**< Action the being is performing */
Uint16 mFrame;
Uint16 mWalkTime;
+#endif
Uint8 mEmotion; /**< Currently showing emotion */
Uint8 mEmotionTime; /**< Time until emotion disappears */
Uint16 mAttackSpeed; /**< Attack speed */
+ Action mAction; /**< Action the being is performing */
+ Uint16 mJob; /**< Job (player job, npc, monster, creature ) */
/**
* Constructor.
@@ -157,7 +169,26 @@ class Being : public Sprite
/**
* Sets a new destination for this being to walk to.
*/
+#ifdef EATHENA_SUPPORT
virtual void setDestination(Uint16 destX, Uint16 destY);
+#else
+ void setDestination(int x, int y);
+
+ /**
+ * Returns the destination for this being.
+ */
+ const Vector &getDestination() const { return mDest; }
+
+ /**
+ * Adjusts course to expected start point.
+ */
+ void adjustCourse(int srcX, int srcY);
+
+ /**
+ * Adjusts course to expected start and end points.
+ */
+ void adjustCourse(int srcX, int srcY, int destX, int destY);
+#endif
/**
* Puts a "speech balloon" above this being for the specified amount
@@ -186,7 +217,11 @@ class Being : public Sprite
* @param victim The attacked being.
* @param damage The amount of damage dealt (0 means miss).
*/
+#ifdef TMWSERV_SUPPORT
+ virtual void handleAttack();
+#else
virtual void handleAttack(Being *victim, int damage);
+#endif
/**
* Returns the name of the being.
@@ -227,7 +262,8 @@ class Being : public Sprite
/**
* Sets visible equipments for this being.
*/
- virtual void setSprite(int slot, int id, std::string color = "");
+ virtual void setSprite(int slot, int id,
+ const std::string &color = "");
/**
* Sets the gender of this being.
@@ -239,10 +275,12 @@ class Being : public Sprite
*/
Gender getGender() const { return mGender; }
+#ifdef EATHENA_SUPPORT
/**
* Makes this being take the next step of his path.
*/
virtual void nextStep();
+#endif
/**
* Triggers whether or not to show the name as a GM name.
@@ -274,16 +312,17 @@ class Being : public Sprite
/**
* Gets the walk speed.
+ * @see setWalkSpeed(int)
*/
- Uint16 getWalkSpeed() const { return mWalkSpeed; }
+ int getWalkSpeed() const { return mWalkSpeed; }
/**
- * Sets the walk speed.
+ * Sets the walk speed (in pixels per second).
*/
- void setWalkSpeed(Uint16 speed) { mWalkSpeed = speed; }
+ void setWalkSpeed(int speed) { mWalkSpeed = speed; }
/**
- * Gets the sprite id.
+ * Gets the being id.
*/
Uint32 getId() const { return mId; }
@@ -300,7 +339,12 @@ class Being : public Sprite
/**
* Sets the current action.
*/
- virtual void setAction(Action action);
+ virtual void setAction(Action action, int attackType = 0);
+
+ /**
+ * Gets the current action.
+ */
+ bool isAlive() { return mAction != DEAD; }
/**
* Returns the current direction.
@@ -312,15 +356,22 @@ class Being : public Sprite
*/
void setDirection(Uint8 direction);
+#ifdef EATHENA_SUPPORT
/**
* Gets the current action.
*/
int getWalkTime() { return mWalkTime; }
+#endif
/**
* Returns the direction the being is facing.
*/
+#ifdef TMWSERV_SUPPORT
+ SpriteDirection getSpriteDirection() const
+ { return SpriteDirection(mSpriteDirection); }
+#else
SpriteDirection getSpriteDirection() const;
+#endif
/**
* Draws this being to the given graphics context.
@@ -332,15 +383,24 @@ class Being : public Sprite
/**
* Returns the pixel X coordinate.
*/
+#ifdef TMWSERV_SUPPORT
+ int getPixelX() const { return (int) mPos.x; }
+#else
int getPixelX() const { return mPx; }
+#endif
/**
* Returns the pixel Y coordinate.
*
* @see Sprite::getPixelY()
*/
+#ifdef TMWSERV_SUPPORT
+ int getPixelY() const { return (int) mPos.y; }
+#else
int getPixelY() const { return mPy; }
+#endif
+#ifdef EATHENA_SUPPORT
/**
* Get the current X pixel offset.
*/
@@ -352,14 +412,37 @@ class Being : public Sprite
*/
int getYOffset() const
{ return getOffset(UP, DOWN); }
+#endif
/**
- * Returns the horizontal size of the current base sprite of the being
+ * Sets the position of this being. When the being was walking, it also
+ * clears the destination and the path.
+ */
+ void setPosition(const Vector &pos);
+
+ /**
+ * Overloaded method provided for convenience.
+ *
+ * @see setPosition(const Vector &pos)
+ */
+ void setPosition(float x, float y, float z = 0.0f)
+ {
+ setPosition(Vector(x, y, z));
+ }
+
+ /**
+ * Returns the position of this being.
+ */
+ const Vector &getPosition() const { return mPos; }
+
+
+ /**
+ * Returns the horizontal size of the current base sprite of the being.
*/
virtual int getWidth() const;
/**
- * Returns the vertical size of the current base sprite of the being
+ * Returns the vertical size of the current base sprite of the being.
*/
virtual int getHeight() const;
@@ -375,6 +458,18 @@ class Being : public Sprite
void controlParticle(Particle *particle);
/**
+ * Gets the way the object is blocked by other objects.
+ */
+ virtual unsigned char getWalkMask() const
+ { return 0x00; } //can walk through everything
+
+ /**
+ * Returns the path this being is following. An empty path is returned
+ * when this being isn't following any path currently.
+ */
+ const Path &getPath() const { return mPath; }
+
+ /**
* Sets the target animation for this being.
*/
void setTargetAnimation(SimpleAnimation* animation);
@@ -449,6 +544,12 @@ class Being : public Sprite
virtual void updateCoords() {}
/**
+ * Gets the way the object blocks pathfinding for other objects
+ */
+ virtual Map::BlockType getBlockType() const
+ { return Map::BLOCKTYPE_NONE; }
+
+ /**
* Trigger visual effect, with components
*
* \param effectId ID of the effect to trigger
@@ -478,8 +579,10 @@ class Being : public Sprite
virtual void handleStatusEffect(StatusEffect *effect, int effectId);
Uint32 mId; /**< Unique sprite id */
- Uint16 mWalkSpeed; /**< Walking speed */
Uint8 mDirection; /**< Facing direction */
+#ifdef TMWSERV_SUPPORT
+ Uint8 mSpriteDirection; /**< Facing direction */
+#endif
Map *mMap; /**< Map on which this being resides */
std::string mName; /**< Name of character */
SpriteIterator mSpriteIterator;
@@ -494,7 +597,8 @@ class Being : public Sprite
Path mPath;
std::string mSpeech;
Text *mText;
- Uint16 mHairStyle, mHairColor;
+ int mHairStyle;
+ int mHairColor;
Gender mGender;
Uint32 mSpeechTime;
Sint32 mPx, mPy; /**< Pixel coordinates */
@@ -511,18 +615,30 @@ class Being : public Sprite
ParticleList mChildParticleEffects;
private:
+#ifdef EATHENA_SUPPORT
/**
* Calculates the offset in the given directions.
* If walking in direction 'neg' the value is negated.
*/
int getOffset(char pos, char neg) const;
+#endif
/** Reset particle status effects on next redraw? */
bool mMustResetParticles;
+#ifdef TMWSERV_SUPPORT
+ static const int DEFAULT_WIDTH = 32;
+ static const int DEFAULT_HEIGHT = 32;
+#endif
+
// Speech Bubble components
SpeechBubble *mSpeechBubble;
+ int mWalkSpeed; /**< Walking speed (pixels/sec) */
+
+ Vector mPos;
+ Vector mDest;
+
// Target cursor being used
SimpleAnimation* mUsedTargetCursor;
diff --git a/src/beingmanager.cpp b/src/beingmanager.cpp
index 3c8edf86..e9d598c7 100644
--- a/src/beingmanager.cpp
+++ b/src/beingmanager.cpp
@@ -26,8 +26,12 @@
#include "npc.h"
#include "player.h"
+#ifdef EATHENA_SUPPORT
#include "net/messageout.h"
+#include "net/ea/protocol.h"
+#else
#include "net/protocol.h"
+#endif
#include "utils/dtor.h"
@@ -39,8 +43,14 @@ class FindBeingFunctor
bool operator() (Being *being)
{
Uint16 other_y = y + ((being->getType() == Being::NPC) ? 1 : 0);
+#ifdef TMWSERV_SUPPORT
+ const Vector &pos = being->getPosition();
+ return ((int) pos.x / 32 == x &&
+ ((int) pos.y / 32 == y || (int) pos.y / 32 == other_y) &&
+#else
return (being->mX == x &&
(being->mY == y || being->mY == other_y) &&
+#endif
being->mAction != Being::DEAD &&
(type == Being::UNKNOWN || being->getType() == type));
}
@@ -49,10 +59,12 @@ class FindBeingFunctor
Being::Type type;
} beingFinder;
+#ifdef EATHENA_SUPPORT
BeingManager::BeingManager(Network *network):
mNetwork(network)
{
}
+#endif
void BeingManager::setMap(Map *map)
{
@@ -67,10 +79,30 @@ void BeingManager::setPlayer(LocalPlayer *player)
mBeings.push_back(player);
}
+#ifdef TMWSERV_SUPPORT
+Being* BeingManager::createBeing(int id, int type, int subtype)
+#else
Being* BeingManager::createBeing(Uint32 id, Uint16 job)
+#endif
{
Being *being;
+#ifdef TMWSERV_SUPPORT
+ switch (type)
+ {
+ case OBJECT_PLAYER:
+ being = new Player(id, subtype, mMap);
+ break;
+ case OBJECT_NPC:
+ being = new NPC(id, subtype, mMap);
+ break;
+ case OBJECT_MONSTER:
+ being = new Monster(id, subtype, mMap);
+ break;
+ default:
+ assert(false);
+ }
+#else
if (job < 10)
being = new Player(id, job, mMap);
else if (job >= 50 && job < 1002)
@@ -87,15 +119,19 @@ Being* BeingManager::createBeing(Uint32 id, Uint16 job)
outMsg.writeInt16(0x0094);
outMsg.writeInt32(id);//readLong(2));
}
+#endif
mBeings.push_back(being);
-
return being;
}
void BeingManager::destroyBeing(Being *being)
{
mBeings.remove(being);
+#ifdef TMWSERV_SUPPORT
+ if(being == player_node->getTarget())
+ player_node->setTarget(NULL);
+#endif
delete being;
}
@@ -131,15 +167,15 @@ Being* BeingManager::findBeingByPixel(Uint16 x, Uint16 y)
{
Being *being = (*itr);
- int xtol = being->getWidth();
- int uptol = being->getHeight() / 2;
+ int xtol = being->getWidth() / 2;
+ int uptol = being->getHeight();
if ((being->mAction != Being::DEAD) &&
(being != player_node) &&
- (being->getPixelX() <= x) &&
+ (being->getPixelX() - xtol <= x) &&
(being->getPixelX() + xtol >= x) &&
(being->getPixelY() - uptol <= y) &&
- (being->getPixelY() + uptol >= y))
+ (being->getPixelY() >= y))
{
return being;
}
@@ -175,12 +211,15 @@ void BeingManager::logic()
being->logic();
+#ifdef EATHENA_SUPPORT
if (being->mAction == Being::DEAD && being->mFrame >= 20)
{
delete being;
i = mBeings.erase(i);
}
- else {
+ else
+#endif
+ {
i++;
}
}
@@ -208,13 +247,30 @@ Being* BeingManager::findNearestLivingBeing(Uint16 x, Uint16 y, int maxdist,
Being *closestBeing = NULL;
int dist = 0;
+#ifdef TMWSERV_SUPPORT
+ //Why do we do this:
+ //For some reason x,y passed to this function is always
+ //in map coords, while down below its in pixels
+ //
+ //I believe there is a deeper problem under this, but
+ //for a temp solution we'll convert to coords to pixels
+ x = x * 32;
+ y = y * 32;
+ maxdist = maxdist * 32;
+#endif
+
BeingIterator itr = mBeings.begin();
BeingIterator itr_end = mBeings.end();
for (; itr != itr_end; ++itr)
{
Being *being = (*itr);
+#ifdef TMWSERV_SUPPORT
+ const Vector &pos = being->getPosition();
+ int d = abs(((int) pos.x) - x) + abs(((int) pos.y) - y);
+#else
int d = abs(being->mX - x) + abs(being->mY - y);
+#endif
if ((being->getType() == type || type == Being::UNKNOWN)
&& (d < dist || closestBeing == NULL) // it is closer
@@ -234,13 +290,25 @@ Being* BeingManager::findNearestLivingBeing(Being *aroundBeing, int maxdist,
{
Being *closestBeing = NULL;
int dist = 0;
+#ifdef TMWSERV_SUPPORT
+ const Vector &apos = aroundBeing->getPosition();
+ int x = apos.x;
+ int y = apos.y;
+ maxdist = maxdist * 32;
+#else
int x = aroundBeing->mX;
int y = aroundBeing->mY;
+#endif
for (BeingIterator i = mBeings.begin(); i != mBeings.end(); i++)
{
Being *being = (*i);
+#ifdef TMWSERV_SUPPORT
+ const Vector &pos = being->getPosition();
+ int d = abs(((int) pos.x) - x) + abs(((int) pos.y) - y);
+#else
int d = abs(being->mX - x) + abs(being->mY - y);
+#endif
if ((being->getType() == type || type == Being::UNKNOWN)
&& (d < dist || closestBeing == NULL) // it is closer
diff --git a/src/beingmanager.h b/src/beingmanager.h
index 11721709..726a73ec 100644
--- a/src/beingmanager.h
+++ b/src/beingmanager.h
@@ -26,7 +26,9 @@
class LocalPlayer;
class Map;
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
typedef std::list<Being*> Beings;
typedef Beings::iterator BeingIterator;
@@ -34,7 +36,9 @@ typedef Beings::iterator BeingIterator;
class BeingManager
{
public:
+#ifdef EATHENA_SUPPORT
BeingManager(Network *network);
+#endif
/**
* Sets the map on which beings are created
@@ -49,7 +53,11 @@ class BeingManager
/**
* Create a being and add it to the list of beings.
*/
+#ifdef TMWSERV_SUPPORT
+ Being *createBeing(int id, int type, int subtype);
+#else
Being *createBeing(Uint32 id, Uint16 job);
+#endif
/**
* Remove a Being.
@@ -57,39 +65,39 @@ class BeingManager
void destroyBeing(Being *being);
/**
- * Return a specific id Being.
+ * Returns a specific id Being.
*/
Being* findBeing(Uint32 id);
- Being* findBeingByPixel(Uint16 x, Uint16 y);
/**
* Returns a being at specific coordinates.
*/
Being* findBeing(Uint16 x, Uint16 y, Being::Type type = Being::UNKNOWN);
+ Being* findBeingByPixel(Uint16 x, Uint16 y);
- /**
- * Returns a being nearest to specific coordinates.
- *
- * @param x X coordinate.
- * @param y Y coordinate.
- * @param maxdist Maximal distance. If minimal distance is larger,
- * no being is returned.
- * @param type The type of being to look for.
- */
+ /**
+ * Returns a being nearest to specific coordinates.
+ *
+ * @param x X coordinate.
+ * @param y Y coordinate.
+ * @param maxdist Maximal distance. If minimal distance is larger,
+ * no being is returned.
+ * @param type The type of being to look for.
+ */
Being* findNearestLivingBeing(Uint16 x, Uint16 y, int maxdist,
Being::Type type = Being::UNKNOWN);
- /**
- * Finds a being by name and (optionally) by type.
- */
+ /**
+ * Finds a being by name and (optionally) by type.
+ */
Being* findBeingByName(std::string name, Being::Type type = Being::UNKNOWN);
- /**
- * Returns a being nearest to another being.
- *
- * \param maxdist maximal distance. If minimal distance is larger,
- * no being is returned
- */
+ /**
+ * Returns a being nearest to another being.
+ *
+ * \param maxdist maximal distance. If minimal distance is larger,
+ * no being is returned
+ */
Being* findNearestLivingBeing(Being *aroundBeing, int maxdist,
Being::Type type = Being::UNKNOWN);
@@ -111,7 +119,9 @@ class BeingManager
protected:
Beings mBeings;
Map *mMap;
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
};
extern BeingManager *beingManager;
diff --git a/src/channel.cpp b/src/channel.cpp
new file mode 100644
index 00000000..c62d6590
--- /dev/null
+++ b/src/channel.cpp
@@ -0,0 +1,33 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+#include "channel.h"
+
+Channel::Channel(short id,
+ const std::string &name,
+ const std::string &announcement) :
+ mId(id),
+ mName(name),
+ mAnnouncement(announcement)
+{
+
+}
diff --git a/src/channel.h b/src/channel.h
new file mode 100644
index 00000000..01bd2728
--- /dev/null
+++ b/src/channel.h
@@ -0,0 +1,74 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <string>
+#include <vector>
+
+class Channel
+{
+ public:
+
+ /**
+ * Constructor.
+ *
+ * @param id the id associated with the channel.
+ * @param name the name of the channel.
+ * @param announcement a welcome message.
+ */
+ Channel(short id,
+ const std::string &name,
+ const std::string &announcement = std::string());
+
+ /**
+ * Get the id associated witht his channel
+ */
+ int getId() const { return mId; }
+
+ /**
+ * Get this channel's name
+ */
+ const std::string& getName() const
+ { return mName; }
+
+ /**
+ * Get the announcement message for this channel
+ */
+ const std::string& getAnnouncement() const
+ { return mAnnouncement; }
+
+ /**
+ * Sets the name of the channel.
+ */
+ void setName(const std::string &channelName)
+ { mName = channelName; }
+
+ /**
+ * Sets the announcement string of the channel.
+ */
+ void setAnnouncement(const std::string &channelAnnouncement)
+ { mAnnouncement = channelAnnouncement; }
+
+ private:
+
+ unsigned short mId;
+ std::string mName;
+ std::string mAnnouncement;
+};
diff --git a/src/channelmanager.cpp b/src/channelmanager.cpp
new file mode 100644
index 00000000..a9654de9
--- /dev/null
+++ b/src/channelmanager.cpp
@@ -0,0 +1,85 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "channelmanager.h"
+#include "channel.h"
+
+#include "utils/dtor.h"
+
+ChannelManager::ChannelManager()
+{
+}
+
+ChannelManager::~ChannelManager()
+{
+ delete_all(mChannels);
+ mChannels.clear();
+}
+
+Channel *ChannelManager::findById(int id) const
+{
+ Channel *channel = 0;
+ for (std::list<Channel*>::const_iterator itr = mChannels.begin(),
+ end = mChannels.end();
+ itr != end;
+ itr++)
+ {
+ Channel *c = (*itr);
+ if (c->getId() == id)
+ {
+ channel = c;
+ break;
+ }
+ }
+ return channel;
+}
+
+Channel *ChannelManager::findByName(const std::string &name) const
+{
+ Channel *channel = 0;
+ if (!name.empty())
+ {
+ for (std::list<Channel*>::const_iterator itr = mChannels.begin(),
+ end = mChannels.end();
+ itr != end;
+ itr++)
+ {
+ Channel *c = (*itr);
+ if (c->getName() == name)
+ {
+ channel = c;
+ break;
+ }
+ }
+ }
+ return channel;
+}
+
+void ChannelManager::addChannel(Channel *channel)
+{
+ mChannels.push_back(channel);
+}
+
+void ChannelManager::removeChannel(Channel *channel)
+{
+ mChannels.remove(channel);
+ delete channel;
+}
diff --git a/src/channelmanager.h b/src/channelmanager.h
new file mode 100644
index 00000000..e42a5960
--- /dev/null
+++ b/src/channelmanager.h
@@ -0,0 +1,48 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_CHANNELMANAGER_H
+#define _TMW_CHANNELMANAGER_H
+
+#include <list>
+#include <string>
+
+class Channel;
+
+class ChannelManager
+{
+public:
+ ChannelManager();
+ ~ChannelManager();
+
+ Channel *findById(int id) const;
+ Channel *findByName(const std::string &name) const;
+
+ void addChannel(Channel *channel);
+ void removeChannel(Channel *channel);
+
+private:
+ std::list<Channel*> mChannels;
+};
+
+extern ChannelManager *channelManager;
+
+#endif
diff --git a/src/commandhandler.cpp b/src/commandhandler.cpp
new file mode 100644
index 00000000..0f4d0f2f
--- /dev/null
+++ b/src/commandhandler.cpp
@@ -0,0 +1,323 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+#include "commandhandler.h"
+#include "channelmanager.h"
+#include "channel.h"
+#include "game.h"
+#include "localplayer.h"
+#include "gui/chat.h"
+#include "net/chatserver/chatserver.h"
+#include "net/gameserver/player.h"
+
+void CommandHandler::handleCommand(const std::string &command)
+{
+ std::string::size_type pos = command.find(' ');
+ std::string type(command, 0, pos);
+ std::string args(command, pos == std::string::npos ? command.size() : pos + 1);
+
+ if (type == "announce")
+ {
+ handleAnnounce(args);
+ }
+ else if (type == "help")
+ {
+ handleHelp(args);
+ }
+ else if (type == "where")
+ {
+ handleWhere();
+ }
+ else if (type == "who")
+ {
+ handleWho();
+ }
+ else if (type == "msg")
+ {
+ handleMsg(args);
+ }
+ else if (type == "join")
+ {
+ handleJoin(args);
+ }
+ else if (type == "list")
+ {
+ handleListChannels();
+ }
+ else if (type == "users")
+ {
+ handleListUsers();
+ }
+ else if (type == "quit")
+ {
+ handleQuit();
+ }
+ else if (type == "topic")
+ {
+ handleTopic(args);
+ }
+ else if (type == "clear")
+ {
+ handleClear();
+ }
+ else if (type == "party")
+ {
+ handleParty(args);
+ }
+ else if (type == "op")
+ {
+ handleOp(args);
+ }
+ else if (type == "kick")
+ {
+ handleKick(args);
+ }
+ else
+ {
+ chatWindow->chatLog("Unknown command");
+ }
+}
+
+void CommandHandler::handleAnnounce(const std::string &args)
+{
+ Net::ChatServer::announce(args);
+}
+
+void CommandHandler::handleHelp(const std::string &args)
+{
+ if (args == "")
+ {
+ chatWindow->chatLog("-- Help --");
+ chatWindow->chatLog("/help > Display this help.");
+ chatWindow->chatLog("/announce > Global announcement (GM only)");
+ chatWindow->chatLog("/where > Display map name");
+ chatWindow->chatLog("/who > Display number of online users");
+ chatWindow->chatLog("/msg > Send a private message to a user");
+ chatWindow->chatLog("/list > Display all public channels");
+ chatWindow->chatLog("/users > Lists the users in the current channel");
+ chatWindow->chatLog("/join > Join or create a channel");
+ chatWindow->chatLog("/topic > Set the topic of the current channel");
+ chatWindow->chatLog("/quit > Leave a channel");
+ chatWindow->chatLog("/clear > Clears this window");
+ chatWindow->chatLog("/party > Invite a user to party");
+ chatWindow->chatLog("/op > Make a user a channel operator");
+ chatWindow->chatLog("/kick > Kick a user from the channel");
+ chatWindow->chatLog("For more information, type /help <command>");
+ }
+ else if (args == "announce")
+ {
+ chatWindow->chatLog("Command: /announce <msg>");
+ chatWindow->chatLog("*** only available to a GM ***");
+ chatWindow->chatLog("This command sends the message <msg> to "
+ "all players currently online.");
+ }
+ else if (args == "clear")
+ {
+ chatWindow->chatLog("Command: /clear");
+ chatWindow->chatLog("This command clears the chat log of previous chat.");
+ }
+ else if (args == "help")
+ {
+ chatWindow->chatLog("Command: /help");
+ chatWindow->chatLog("This command displays a list of all commands available.");
+ chatWindow->chatLog("Command: /help <command>");
+ chatWindow->chatLog("This command displays help on <command>.");
+ }
+ else if (args == "join")
+ {
+ chatWindow->chatLog("Command: /join <channel>");
+ chatWindow->chatLog("This command makes you enter <channel>.");
+ chatWindow->chatLog("If <channel> doesn't exist, it's created.");
+ }
+ else if (args == "kick")
+ {
+ chatWindow->chatLog("Command: /kick <nick>");
+ chatWindow->chatLog("This command makes <nick> leave the channel.");
+ chatWindow->chatLog("If the <nick> has spaces in it, enclose it in "
+ "double quotes (\").");
+ }
+ else if (args == "list")
+ {
+ chatWindow->chatLog("Command: /list");
+ chatWindow->chatLog("This command shows a list of all channels.");
+ }
+ else if (args == "msg")
+ {
+ chatWindow->chatLog("Command: /msg <nick> <message>");
+ chatWindow->chatLog("This command sends the text <message> to <nick>.");
+ chatWindow->chatLog("If the <nick> has spaces in it, enclose it in "
+ "double quotes (\").");
+ }
+ else if (args == "op")
+ {
+ chatWindow->chatLog("Command: /op <nick>");
+ chatWindow->chatLog("This command makes <nick> a channel operator.");
+ chatWindow->chatLog("If the <nick> has spaces in it, enclose it in "
+ "double quotes (\").");
+ chatWindow->chatLog("Channel operators can kick and op other users "
+ "from the channel.");
+ }
+ else if (args == "party")
+ {
+ chatWindow->chatLog("Command: /party <nick>");
+ chatWindow->chatLog("This command invites <nick> to party with you.");
+ chatWindow->chatLog("If the <nick> has spaces in it, enclose it in "
+ "double quotes (\").");
+ }
+ else if (args == "quit")
+ {
+ chatWindow->chatLog("Command: /quit");
+ chatWindow->chatLog("This command leaves the current channel.");
+ chatWindow->chatLog("If you're the last person in the channel, it will be deleted.");
+ }
+ else if (args == "topic")
+ {
+ chatWindow->chatLog("Command: /topic <message>");
+ chatWindow->chatLog("This command sets the topic to <message>.");
+ }
+ else if (args == "users")
+ {
+ chatWindow->chatLog("Command: /users <channel>");
+ chatWindow->chatLog("This command shows the users in <channel>.");
+ }
+ else if (args == "where")
+ {
+ chatWindow->chatLog("Command: /where");
+ chatWindow->chatLog("This command displays the name of the current map.");
+ }
+ else if (args == "who")
+ {
+ chatWindow->chatLog("Command: /who");
+ chatWindow->chatLog("This command displays the number of players currently "
+ "online.");
+ }
+ else
+ {
+ chatWindow->chatLog("Unknown command.");
+ chatWindow->chatLog("Type /help for a list of commands.");
+ }
+}
+
+void CommandHandler::handleWhere()
+{
+ chatWindow->chatLog(map_path, BY_SERVER);
+}
+
+void CommandHandler::handleWho()
+{
+
+}
+
+void CommandHandler::handleMsg(const std::string &args)
+{
+ std::string::size_type pos = args.find(' ');
+ std::string recipient(args, 0, pos);
+ std::string text(args, pos+1);
+ Net::ChatServer::privMsg(recipient, text);
+}
+
+void CommandHandler::handleJoin(const std::string &args)
+{
+ std::string::size_type pos = args.find(' ');
+ std::string name(args, 0, pos);
+ std::string password(args, pos+1);
+ chatWindow->chatLog("Requesting to join channel " + name);
+ Net::ChatServer::enterChannel(name, password);
+}
+
+void CommandHandler::handleListChannels()
+{
+ Net::ChatServer::getChannelList();
+}
+
+void CommandHandler::handleListUsers()
+{
+ Net::ChatServer::getUserList(chatWindow->getFocused());
+}
+
+void CommandHandler::handleTopic(const std::string &args)
+{
+ if (Channel *channel = channelManager->findByName(chatWindow->getFocused()))
+ {
+ Net::ChatServer::setChannelTopic(channel->getId(), args);
+ }
+ else
+ {
+ chatWindow->chatLog("Unable to set this channel's topic", BY_CHANNEL);
+ }
+}
+
+void CommandHandler::handleQuit()
+{
+ if (Channel *channel = channelManager->findByName(chatWindow->getFocused()))
+ {
+ Net::ChatServer::quitChannel(channel->getId());
+ }
+ else
+ {
+ chatWindow->chatLog("Unable to quit this channel", BY_CHANNEL);
+ }
+}
+
+void CommandHandler::handleClear()
+{
+ chatWindow->clearTab(chatWindow->getFocused());
+}
+
+void CommandHandler::handleParty(const std::string &args)
+{
+ if (args != "")
+ {
+ player_node->inviteToParty(args);
+ }
+}
+
+void CommandHandler::handleOp(const std::string &args)
+{
+ if (Channel *channel = channelManager->findByName(chatWindow->getFocused()))
+ {
+ // set the user mode 'o' to op a user
+ if (args != "")
+ {
+ Net::ChatServer::setUserMode(channel->getId(), args, 'o');
+ }
+ }
+ else
+ {
+ chatWindow->chatLog("Unable to set this user's mode", BY_CHANNEL);
+ }
+}
+
+void CommandHandler::handleKick(const std::string &args)
+{
+ if (Channel *channel = channelManager->findByName(chatWindow->getFocused()))
+ {
+ if (args != "")
+ {
+ Net::ChatServer::kickUser(channel->getId(), args);
+ }
+ }
+ else
+ {
+ chatWindow->chatLog("Unable to kick user", BY_CHANNEL);
+ }
+}
diff --git a/src/commandhandler.h b/src/commandhandler.h
new file mode 100644
index 00000000..eab0f077
--- /dev/null
+++ b/src/commandhandler.h
@@ -0,0 +1,123 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_COMMANDHANDLER_H
+#define _TMW_COMMANDHANDLER_H
+
+#include <string>
+
+/**
+ * A class to parse and handle user commands
+ */
+class CommandHandler
+{
+ public:
+ /**
+ * Constructor
+ */
+ CommandHandler() {}
+
+ /**
+ * Destructor
+ */
+ ~CommandHandler() {}
+
+ /**
+ * Parse and handle the given command.
+ */
+ void handleCommand(const std::string &command);
+
+ private:
+ /**
+ * Handle an announce command.
+ */
+ void handleAnnounce(const std::string &args);
+
+ /**
+ * Handle a help command.
+ */
+ void handleHelp(const std::string &args);
+
+ /**
+ * Handle a where command.
+ */
+ void handleWhere();
+
+ /**
+ * Handle a who command.
+ */
+ void handleWho();
+
+ /**
+ * Handle a msg command.
+ */
+ void handleMsg(const std::string &args);
+
+ /**
+ * Handle a join command.
+ */
+ void handleJoin(const std::string &args);
+
+ /**
+ * Handle a listchannels command.
+ */
+ void handleListChannels();
+
+ /**
+ * Handle a listusers command.
+ */
+ void handleListUsers();
+
+ /**
+ * Handle a topic command.
+ */
+ void handleTopic(const std::string &args);
+
+ /**
+ * Handle a quit command.
+ */
+ void handleQuit();
+
+ /**
+ * Handle a clear command.
+ */
+ void handleClear();
+
+ /**
+ * Handle a party command.
+ */
+ void handleParty(const std::string &args);
+
+ /**
+ * Handle a op command.
+ */
+ void handleOp(const std::string &args);
+
+ /**
+ * Handle a kick command.
+ */
+ void handleKick(const std::string &args);
+
+};
+
+extern CommandHandler *commandHandler;
+
+#endif //_TMW_COMMANDHANDLER_H
diff --git a/src/configuration.h b/src/configuration.h
index 0b2dc446..0134f29a 100644
--- a/src/configuration.h
+++ b/src/configuration.h
@@ -226,6 +226,7 @@ class Configuration : public ConfigurationObject
std::string mConfigPath; /**< Location of config file */
};
+extern Configuration branding;
extern Configuration config;
#endif
diff --git a/src/effectmanager.cpp b/src/effectmanager.cpp
index f004a450..d9234f66 100644
--- a/src/effectmanager.cpp
+++ b/src/effectmanager.cpp
@@ -45,8 +45,6 @@ EffectManager::EffectManager()
for_each_xml_child_node(node, root)
{
- //int id;
-
if (xmlStrEqual(node->name, BAD_CAST "effect"))
{
EffectDescription ed;
@@ -60,7 +58,6 @@ EffectManager::EffectManager()
EffectManager::~EffectManager()
{
-
}
bool EffectManager::trigger(int id, Being* being)
diff --git a/src/engine.cpp b/src/engine.cpp
index a67d379f..872ecd57 100644
--- a/src/engine.cpp
+++ b/src/engine.cpp
@@ -33,19 +33,27 @@
#include "gui/minimap.h"
#include "gui/viewport.h"
+#ifdef EATHENA_SUPPORT
#include "net/messageout.h"
-#include "net/protocol.h"
+#include "net/ea/protocol.h"
+#endif
#include "resources/mapreader.h"
+#include "resources/monsterdb.h"
#include "resources/resourcemanager.h"
#include "utils/stringutils.h"
char itemCurrenyQ[10] = "0";
+#ifdef TMWSERV_SUPPORT
+Engine::Engine():
+ mCurrentMap(NULL)
+#else
Engine::Engine(Network *network):
mCurrentMap(NULL),
mNetwork(network)
+#endif
{
}
@@ -59,6 +67,7 @@ void Engine::changeMap(const std::string &mapPath)
// Clean up floor items, beings and particles
floorItemManager->clear();
beingManager->clear();
+ particleEngine->clear();
// Unset the map of the player so that its particles are cleared before
// being deleted in the next step
@@ -68,7 +77,11 @@ void Engine::changeMap(const std::string &mapPath)
particleEngine->clear();
// Store full map path in global var
+#ifdef TMWSERV_SUPPORT
+ map_path = "maps/" + mapPath + ".tmx";
+#else
map_path = "maps/" + mapPath.substr(0, mapPath.rfind(".")) + ".tmx";
+#endif
ResourceManager *resman = ResourceManager::getInstance();
if (!resman->exists(map_path))
map_path += ".gz";
@@ -106,6 +119,12 @@ void Engine::changeMap(const std::string &mapPath)
else
minimap->setProportion(0.5);
}
+ if (newMap->hasProperty("name"))
+ {
+ minimap->setCaption(newMap->getProperty("name"));
+ } else {
+ minimap->setCaption("Map");
+ }
minimap->setMapImage(mapImage);
beingManager->setMap(newMap);
particleEngine->setMap(newMap);
@@ -131,15 +150,18 @@ void Engine::changeMap(const std::string &mapPath)
mCurrentMap = newMap;
mMapName = mapPath;
+#ifdef EATHENA_SUPPORT
// Send "map loaded"
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_MAP_LOADED);
+#endif
}
void Engine::logic()
{
beingManager->logic();
particleEngine->update();
- mCurrentMap->update();
+ if (mCurrentMap)
+ mCurrentMap->update();
gui->logic();
}
diff --git a/src/engine.h b/src/engine.h
index 7ad6d894..60b1f6c8 100644
--- a/src/engine.h
+++ b/src/engine.h
@@ -25,7 +25,9 @@
#include <string>
class Map;
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
/**
* Game engine. Actually hardly does anything anymore except keeping track of
@@ -37,7 +39,11 @@ class Engine
/**
* Constructor.
*/
+#ifdef EATHENA_SUPPORT
Engine(Network *network);
+#else
+ Engine();
+#endif
/**
* Destructor.
@@ -57,13 +63,15 @@ class Engine
void changeMap(const std::string &mapName);
/**
- * Performs engine logic.
+ * Performs engine logic. This method is called 100 times per second.
*/
void logic();
private:
Map *mCurrentMap;
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
std::string mMapName;
};
diff --git a/src/equipment.cpp b/src/equipment.cpp
index cb7acd44..63743263 100644
--- a/src/equipment.cpp
+++ b/src/equipment.cpp
@@ -21,15 +21,51 @@
#include "equipment.h"
#include "item.h"
+#ifdef EATHENA_SUPPORT
#include "inventory.h"
#include "localplayer.h"
+#endif
-Equipment::Equipment():
- mArrows(0)
+#include <algorithm>
+
+Equipment::Equipment()
+#ifdef EATHENA_SUPPORT
+ : mArrows(0)
+#endif
{
+#ifdef TMWSERV_SUPPORT
+ std::fill_n(mEquipment, EQUIPMENT_SIZE, (Item*) 0);
+#else
std::fill_n(mEquipment, EQUIPMENT_SIZE, 0);
+#endif
+}
+
+#ifdef TMWSERV_SUPPORT
+
+Equipment::~Equipment()
+{
+ clear();
}
+void Equipment::clear()
+{
+ for (int i = 0; i < EQUIPMENT_SIZE; ++i)
+ delete mEquipment[i];
+
+ std::fill_n(mEquipment, EQUIPMENT_SIZE, (Item*) 0);
+}
+
+void Equipment::setEquipment(int index, int id)
+{
+ if (mEquipment[index] && mEquipment[index]->getId() == id)
+ return;
+
+ delete mEquipment[index];
+ mEquipment[index] = (id > 0) ? new Item(id) : 0;
+}
+
+#else
+
void Equipment::setEquipment(int index, int inventoryIndex)
{
mEquipment[index] = inventoryIndex;
@@ -37,3 +73,5 @@ void Equipment::setEquipment(int index, int inventoryIndex)
if (item)
item->setEquipped(true);
}
+
+#endif
diff --git a/src/equipment.h b/src/equipment.h
index ace76e63..7605175a 100644
--- a/src/equipment.h
+++ b/src/equipment.h
@@ -22,9 +22,13 @@
#ifndef EQUIPMENT_H
#define EQUIPMENT_H
-class Item;
-
+#ifdef TMWSERV_SUPPORT
+#define EQUIPMENT_SIZE 11
+#else
#define EQUIPMENT_SIZE 10
+#endif
+
+class Item;
class Equipment
{
@@ -34,17 +38,40 @@ class Equipment
*/
Equipment();
+#ifdef TMWSERV_SUPPORT
+ /**
+ * Destructor.
+ */
+ ~Equipment();
+#endif
+
/**
* Get equipment at the given slot.
*/
+#ifdef TMWSERV_SUPPORT
+ Item* getEquipment(int index)
+#else
int getEquipment(int index) const
+#endif
{ return mEquipment[index]; }
+#ifdef TMWSERV_SUPPORT
+ /**
+ * Clears equipment.
+ */
+ void clear();
+#endif
+
/**
* Set equipment at the given slot.
*/
+#ifdef TMWSERV_SUPPORT
+ void setEquipment(int index, int id);
+#else
void setEquipment(int index, int inventoryIndex);
+#endif
+#ifdef EATHENA_SUPPORT
/**
* Remove equipment from the given slot.
*/
@@ -59,10 +86,15 @@ class Equipment
* Set the item used in the arrow slot.
*/
void setArrows(int arrows) { mArrows = arrows; }
+#endif
private:
+#ifdef TMWSERV_SUPPORT
+ Item* mEquipment[EQUIPMENT_SIZE];
+#else
int mEquipment[EQUIPMENT_SIZE];
int mArrows;
+#endif
};
#endif
diff --git a/src/game.cpp b/src/game.cpp
index cc5121fd..cf1aa220 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -27,6 +27,10 @@
#include <guichan/exception.hpp>
#include "beingmanager.h"
+#ifdef TMWSERV_SUPPORT
+#include "channelmanager.h"
+#include "commandhandler.h"
+#endif
#include "configuration.h"
#include "effectmanager.h"
#include "emoteshortcut.h"
@@ -71,20 +75,38 @@
#include "gui/status.h"
#include "gui/trade.h"
#include "gui/viewport.h"
+#ifdef TMWSERV_SUPPORT
+#include "gui/buddywindow.h"
+#include "gui/guildwindow.h"
+#include "gui/magic.h"
+#include "gui/npcpostdialog.h"
+#include "gui/partywindow.h"
+#include "gui/quitdialog.h"
+#endif
-#include "net/beinghandler.h"
-#include "net/buysellhandler.h"
#include "net/chathandler.h"
-#include "net/equipmenthandler.h"
-#include "net/inventoryhandler.h"
#include "net/itemhandler.h"
-#include "net/messageout.h"
-#include "net/network.h"
#include "net/npchandler.h"
#include "net/playerhandler.h"
-#include "net/protocol.h"
-#include "net/skillhandler.h"
#include "net/tradehandler.h"
+#ifdef TMWSERV_SUPPORT
+#include "net/network.h"
+#include "net/beinghandler.h"
+#include "net/buysellhandler.h"
+#include "net/effecthandler.h"
+#include "net/guildhandler.h"
+#include "net/inventoryhandler.h"
+#include "net/partyhandler.h"
+#else
+#include "net/ea/network.h"
+#include "net/ea/beinghandler.h"
+#include "net/ea/buysellhandler.h"
+#include "net/ea/equipmenthandler.h"
+#include "net/ea/inventoryhandler.h"
+#include "net/ea/protocol.h"
+#include "net/ea/skillhandler.h"
+#include "net/messageout.h"
+#endif
#include "resources/imagewriter.h"
@@ -103,7 +125,11 @@ Joystick *joystick = NULL;
extern Window *weightNotice;
extern Window *deathNotice;
+#ifdef TMWSERV_SUPPORT
+QuitDialog *quitDialog = NULL;
+#else
ConfirmDialog *exitConfirm = NULL;
+#endif
OkDialog *disconnectedDialog = NULL;
ChatWindow *chatWindow;
@@ -120,6 +146,13 @@ NpcListDialog *npcListDialog;
NpcTextDialog *npcTextDialog;
NpcStringDialog *npcStringDialog;
SkillDialog *skillDialog;
+#ifdef TMWSERV_SUPPORT
+BuddyWindow *buddyWindow;
+GuildWindow *guildWindow;
+MagicDialog *magicDialog;
+NpcPostDialog *npcPostDialog;
+PartyWindow *partyWindow;
+#endif
Setup* setupWindow;
Minimap *minimap;
EquipmentWindow *equipmentWindow;
@@ -131,6 +164,10 @@ ShortcutWindow *emoteShortcutWindow;
BeingManager *beingManager = NULL;
FloorItemManager *floorItemManager = NULL;
+#ifdef TMWSERV_SUPPORT
+ChannelManager *channelManager = NULL;
+CommandHandler *commandHandler = NULL;
+#endif
Particle* particleEngine = NULL;
EffectManager *effectManager = NULL;
@@ -147,7 +184,9 @@ namespace {
if (event.getId() == "yes" || event.getId() == "ok") {
done = true;
}
+#ifdef EATHENA_SUPPORT
exitConfirm = NULL;
+#endif
disconnectedDialog = NULL;
}
} exitListener;
@@ -189,15 +228,34 @@ int get_elapsed_time(int start_time)
/**
* Create all the various globally accessible gui windows
*/
+#ifdef TMWSERV_SUPPORT
+void createGuiWindows()
+#else
void createGuiWindows(Network *network)
+#endif
{
// Create dialogs
+#ifdef TMWSERV_SUPPORT
+ chatWindow = new ChatWindow;
+ buyDialog = new BuyDialog;
+ sellDialog = new SellDialog;
+ tradeWindow = new TradeWindow;
+ npcPostDialog = new NpcPostDialog();
+ magicDialog = new MagicDialog();
+ equipmentWindow = new EquipmentWindow(player_node->mEquipment.get());
+ buddyWindow = new BuddyWindow();
+ guildWindow = new GuildWindow();
+ partyWindow = new PartyWindow();
+#else
chatWindow = new ChatWindow(network);
+ buyDialog = new BuyDialog(network);
+ sellDialog = new SellDialog(network);
+ tradeWindow = new TradeWindow(network);
+ equipmentWindow = new EquipmentWindow;
+#endif
menuWindow = new MenuWindow;
statusWindow = new StatusWindow(player_node);
miniStatusWindow = new MiniStatusWindow;
- buyDialog = new BuyDialog(network);
- sellDialog = new SellDialog(network);
buySellDialog = new BuySellDialog;
inventoryWindow = new InventoryWindow;
emoteWindow = new EmoteWindow;
@@ -208,8 +266,6 @@ void createGuiWindows(Network *network)
skillDialog = new SkillDialog;
setupWindow = new Setup;
minimap = new Minimap;
- equipmentWindow = new EquipmentWindow;
- tradeWindow = new TradeWindow(network);
helpWindow = new HelpWindow;
debugWindow = new DebugWindow;
itemShortcutWindow = new ShortcutWindow("ItemShortcut",new ItemShortcutContainer);
@@ -233,6 +289,11 @@ void createGuiWindows(Network *network)
emoteShortcutWindow->getWindowName() + "Visible", true));
minimap->setVisible((bool) config.getValue(
minimap->getWindowName() + "Visible", true));
+
+ if (config.getValue("logToChat", 0))
+ {
+ logger->setChatWindow(chatWindow);
+ }
}
/**
@@ -254,6 +315,13 @@ void destroyGuiWindows()
delete npcListDialog;
delete npcTextDialog;
delete npcStringDialog;
+#ifdef TMWSERV_SUPPORT
+ delete npcPostDialog;
+ delete magicDialog;
+ delete buddyWindow;
+ delete guildWindow;
+ delete partyWindow;
+#endif
delete skillDialog;
delete setupWindow;
delete minimap;
@@ -265,33 +333,56 @@ void destroyGuiWindows()
delete emoteShortcutWindow;
}
+#ifdef TMWSERV_SUPPORT
+Game::Game():
+ mBeingHandler(new BeingHandler()),
+ mGuildHandler(new GuildHandler()),
+ mPartyHandler(new PartyHandler()),
+ mEffectHandler(new EffectHandler()),
+#else
Game::Game(Network *network):
mNetwork(network),
mBeingHandler(new BeingHandler(config.getValue("EnableSync", 0) == 1)),
+ mEquipmentHandler(new EquipmentHandler),
+ mSkillHandler(new SkillHandler),
+#endif
mBuySellHandler(new BuySellHandler),
mChatHandler(new ChatHandler),
- mEquipmentHandler(new EquipmentHandler),
mInventoryHandler(new InventoryHandler),
mItemHandler(new ItemHandler),
mNpcHandler(new NPCHandler),
mPlayerHandler(new PlayerHandler),
- mSkillHandler(new SkillHandler),
- mTradeHandler(new TradeHandler)
+ mTradeHandler(new TradeHandler),
+ mLogicCounterId(0), mSecondsCounterId(0)
{
+ done = false;
+
+#ifdef TMWSERV_SUPPORT
+ createGuiWindows();
+ engine = new Engine;
+
+ beingManager = new BeingManager;
+#else
createGuiWindows(network);
engine = new Engine(network);
beingManager = new BeingManager(network);
+#endif
+
floorItemManager = new FloorItemManager;
+#ifdef TMWSERV_SUPPORT
+ channelManager = new ChannelManager();
+ commandHandler = new CommandHandler();
+#endif
effectManager = new EffectManager;
particleEngine = new Particle(NULL);
particleEngine->setupEngine();
- // Initialize timers
+ // Initialize logic and seconds counters
tick_time = 0;
- SDL_AddTimer(10, nextTick, NULL); // Logic counter
- SDL_AddTimer(1000, nextSecond, NULL); // Seconds counter
+ mLogicCounterId = SDL_AddTimer(10, nextTick, NULL);
+ mSecondsCounterId = SDL_AddTimer(1000, nextSecond, NULL);
// Initialize frame limiting
config.addListener("fpslimit", this);
@@ -299,7 +390,9 @@ Game::Game(Network *network):
// Initialize beings
beingManager->setPlayer(player_node);
+#ifdef EATHENA_SUPPORT
player_node->setNetwork(network);
+#endif
Joystick::init();
// TODO: The user should be able to choose which one to use
@@ -307,6 +400,19 @@ Game::Game(Network *network):
if (Joystick::getNumberOfJoysticks() > 0)
joystick = new Joystick(0);
+#ifdef TMWSERV_SUPPORT
+ Net::registerHandler(mBeingHandler.get());
+ Net::registerHandler(mBuySellHandler.get());
+ Net::registerHandler(mChatHandler.get());
+ Net::registerHandler(mGuildHandler.get());
+ Net::registerHandler(mInventoryHandler.get());
+ Net::registerHandler(mItemHandler.get());
+ Net::registerHandler(mNpcHandler.get());
+ Net::registerHandler(mPartyHandler.get());
+ Net::registerHandler(mPlayerHandler.get());
+ Net::registerHandler(mTradeHandler.get());
+ Net::registerHandler(mEffectHandler.get());
+#else
network->registerHandler(mBeingHandler.get());
network->registerHandler(mBuySellHandler.get());
network->registerHandler(mChatHandler.get());
@@ -332,22 +438,36 @@ Game::Game(Network *network):
msg.writeInt32(tick_time);
engine->changeMap(map_path);
+#endif
}
Game::~Game()
{
+#ifdef TMWSERV_SUPPORT
+ Net::clearHandlers();
+#endif
+
delete player_node;
destroyGuiWindows();
delete beingManager;
delete floorItemManager;
+#ifdef TMWSERV_SUPPORT
+ delete channelManager;
+ delete commandHandler;
+#endif
delete joystick;
delete particleEngine;
delete engine;
+ viewport->setMap(NULL);
+ player_node = NULL;
beingManager = NULL;
floorItemManager = NULL;
joystick = NULL;
+
+ SDL_RemoveTimer(mLogicCounterId);
+ SDL_RemoveTimer(mSecondsCounterId);
}
static bool saveScreenshot()
@@ -458,6 +578,10 @@ void Game::logic()
}
// Handle network stuff
+#ifdef TMWSERV_SUPPORT
+ Net::flush();
+ // TODO: Fix notification when the connection is lost
+#else
mNetwork->flush();
mNetwork->dispatchMessages();
@@ -472,6 +596,7 @@ void Game::logic()
disconnectedDialog->requestMoveToTop();
}
}
+#endif
}
}
@@ -500,6 +625,23 @@ void Game::handleInput()
return;
}
+#ifdef TMWSERV_SUPPORT
+ // send straight to gui for certain windows
+ if (npcPostDialog->isVisible())
+ {
+ try
+ {
+ guiInput->pushInput(event);
+ }
+ catch (gcn::Exception e)
+ {
+ const char* err = e.getMessage().c_str();
+ logger->log("Warning: guichan input exception: %s", err);
+ }
+ return;
+ }
+#endif
+
// Mode switch to emotes
if (keyboard.isKeyActive(keyboard.KEY_EMOTE))
{
@@ -521,10 +663,16 @@ void Game::handleInput()
deathNotice ||
weightNotice))
{
+#ifdef TMWSERV_SUPPORT
+ // Don not focus chat input when quit dialog is active
+ if (quitDialog != NULL && quitDialog->isVisible())
+ continue;
+#else
// Quit by pressing Enter if the exit confirm is there
if (exitConfirm &&
keyboard.isKeyActive(keyboard.KEY_TOGGLE_CHAT))
done = true;
+#endif
// Close the Browser if opened
else if (helpWindow->isVisible() &&
keyboard.isKeyActive(keyboard.KEY_OK))
@@ -549,6 +697,12 @@ void Game::handleInput()
else if (npcIntegerDialog->isVisible() &&
keyboard.isKeyActive(keyboard.KEY_OK))
npcIntegerDialog->action(gcn::ActionEvent(NULL, "ok"));
+ /*
+ else if (guildWindow->isVisible())
+ {
+ // TODO: Check if a dialog is open and close it if so
+ }
+ */
else if (!(keyboard.getKeyValue(
KeyboardConfig::KEY_TOGGLE_CHAT) ==
keyboard.getKeyValue(
@@ -597,6 +751,17 @@ void Game::handleInput()
break;
// Quitting confirmation dialog
case KeyboardConfig::KEY_QUIT:
+#ifdef TMWSERV_SUPPORT
+ if (!quitDialog)
+ {
+ quitDialog = new QuitDialog(&done, &quitDialog);
+ quitDialog->requestMoveToTop();
+ }
+ else
+ {
+ quitDialog->action(gcn::ActionEvent(NULL, "cancel"));
+ }
+#else
if (!exitConfirm)
{
exitConfirm = new ConfirmDialog(_("Quit"),
@@ -609,6 +774,7 @@ void Game::handleInput()
{
exitConfirm->action(gcn::ActionEvent(NULL, _("no")));
}
+#endif
break;
default:
break;
@@ -639,24 +805,31 @@ void Game::handleInput()
{
case KeyboardConfig::KEY_PICKUP:
{
+#ifdef TMWSERV_SUPPORT
+ const Vector &pos = player_node->getPosition();
+ Uint16 x = (int) pos.x / 32;
+ Uint16 y = (int) pos.y / 32;
+#else
+ Uint16 x = player_node->mX;
+ Uint16 y = player_node->mY;
+#endif
FloorItem *item =
- floorItemManager->findByCoordinates(
- player_node->mX, player_node->mY);
+ floorItemManager->findByCoordinates(x, y);
// If none below the player, try the tile in front
// of the player
if (!item)
{
- Uint16 x = player_node->mX;
- Uint16 y = player_node->mY;
- if (player_node->getDirection() & Being::UP)
- y--;
- if (player_node->getDirection() & Being::DOWN)
- y++;
- if (player_node->getDirection() & Being::LEFT)
- x--;
- if (player_node->getDirection() & Being::RIGHT)
- x++;
+ // Temporary until tile-based picking is
+ // removed.
+ switch (player_node->getSpriteDirection())
+ {
+ case DIRECTION_UP : --y; break;
+ case DIRECTION_DOWN : ++y; break;
+ case DIRECTION_LEFT : --x; break;
+ case DIRECTION_RIGHT: ++x; break;
+ default: break;
+ }
item = floorItemManager->findByCoordinates(
x, y);
@@ -685,6 +858,10 @@ void Game::handleInput()
equipmentWindow->setVisible(false);
helpWindow->setVisible(false);
debugWindow->setVisible(false);
+#ifdef TMWSERV_SUPPORT
+ guildWindow->setVisible(false);
+ buddyWindow->setVisible(false);
+#endif
}
break;
case KeyboardConfig::KEY_WINDOW_STATUS:
@@ -783,6 +960,7 @@ void Game::handleInput()
logger->log("Warning: guichan input exception: %s", err);
}
}
+
} // End while
// If the user is configuring the keys then don't respond.
@@ -791,7 +969,10 @@ void Game::handleInput()
// Moving player around
if (player_node->mAction != Being::DEAD &&
- current_npc == 0 && !chatWindow->isInputFocused())
+#ifdef EATHENA_SUPPORT
+ current_npc == 0 &&
+#endif
+ !chatWindow->isInputFocused())
{
// Get the state of the keyboard keys
keyboard.refreshActiveKeys();
@@ -805,33 +986,60 @@ void Game::handleInput()
return;
}
+#ifdef TMWSERV_SUPPORT
+ const Vector &pos = player_node->getPosition();
+ const Uint16 x = (int) pos.x / 32;
+ const Uint16 y = (int) pos.y / 32;
+#else
const Uint16 x = player_node->mX;
const Uint16 y = player_node->mY;
+#endif
unsigned char direction = 0;
// Translate pressed keys to movement and direction
if (keyboard.isKeyActive(keyboard.KEY_MOVE_UP) ||
- (joystick && joystick->isUp()))
+ (joystick && joystick->isUp()))
{
direction |= Being::UP;
}
else if (keyboard.isKeyActive(keyboard.KEY_MOVE_DOWN) ||
- (joystick && joystick->isDown()))
+ (joystick && joystick->isDown()))
{
direction |= Being::DOWN;
}
if (keyboard.isKeyActive(keyboard.KEY_MOVE_LEFT) ||
- (joystick && joystick->isLeft()))
+ (joystick && joystick->isLeft()))
{
direction |= Being::LEFT;
}
else if (keyboard.isKeyActive(keyboard.KEY_MOVE_RIGHT) ||
- (joystick && joystick->isRight()))
+ (joystick && joystick->isRight()))
{
direction |= Being::RIGHT;
}
+#ifdef TMWSERV_SUPPORT
+ // First if player is pressing key for the direction he is already
+ // going
+ if (direction == player_node->getWalkingDir())
+ {
+ player_node->setWalkingDir(direction);
+ }
+ // Else if he is pressing a key, and its different from what he has
+ // been pressing, stop (do not send this stop to the server) and
+ // start in the new direction
+ else if (direction && direction != player_node->getWalkingDir())
+ {
+ player_node->stopWalking(false);
+ player_node->setWalkingDir(direction);
+ }
+ // Else, he is not pressing a key, stop (sending to server)
+ else
+ {
+ player_node->stopWalking(true);
+ }
+#else
player_node->setWalkingDir(direction);
// Attacking monsters
@@ -864,6 +1072,7 @@ void Game::handleInput()
player_node->attack(target, newTarget);
}
+#endif
// Target the nearest player if 'q' is pressed
if ( keyboard.isKeyActive(keyboard.KEY_TARGET_PLAYER) &&
@@ -916,11 +1125,13 @@ void Game::handleInput()
}
}
+#ifdef EATHENA_SUPPORT
// Stop attacking if shift is pressed
if (keyboard.isKeyActive(keyboard.KEY_TARGET))
{
player_node->stopAttack();
}
+#endif
if (joystick)
{
diff --git a/src/game.h b/src/game.h
index d7d2a562..7eecc036 100644
--- a/src/game.h
+++ b/src/game.h
@@ -24,10 +24,14 @@
#include <memory>
+#include "SDL.h"
+
#include "configlistener.h"
class MessageHandler;
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
extern std::string map_path;
extern volatile int fps;
@@ -36,7 +40,11 @@ extern volatile int tick_time;
class Game : public ConfigListener
{
public:
+#ifdef TMWSERV_SUPPORT
+ Game();
+#else
Game(Network *network);
+#endif
~Game();
void logic();
@@ -46,7 +54,9 @@ class Game : public ConfigListener
void optionChanged(const std::string &name);
private:
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
/** Used to determine whether to draw the next frame. */
int mDrawTime;
@@ -56,15 +66,25 @@ class Game : public ConfigListener
typedef const std::auto_ptr<MessageHandler> MessageHandlerPtr;
MessageHandlerPtr mBeingHandler;
+#ifdef TMWSERV_SUPPORT
+ MessageHandlerPtr mGuildHandler;
+ MessageHandlerPtr mPartyHandler;
+ MessageHandlerPtr mEffectHandler;
+#else
+ MessageHandlerPtr mEquipmentHandler;
+ MessageHandlerPtr mSkillHandler;
+#endif
MessageHandlerPtr mBuySellHandler;
MessageHandlerPtr mChatHandler;
- MessageHandlerPtr mEquipmentHandler;
MessageHandlerPtr mInventoryHandler;
MessageHandlerPtr mItemHandler;
MessageHandlerPtr mNpcHandler;
MessageHandlerPtr mPlayerHandler;
- MessageHandlerPtr mSkillHandler;
+ MessageHandlerPtr mPostHandler;
MessageHandlerPtr mTradeHandler;
+
+ SDL_TimerID mLogicCounterId;
+ SDL_TimerID mSecondsCounterId;
};
/**
diff --git a/src/gui/browserbox.cpp b/src/gui/browserbox.cpp
index a06b9a6e..7c0ae1a7 100644
--- a/src/gui/browserbox.cpp
+++ b/src/gui/browserbox.cpp
@@ -415,4 +415,3 @@ void BrowserBox::draw(gcn::Graphics *graphics)
setHeight((mTextRows.size() + wrappedLines) * font->getHeight());
}
}
-
diff --git a/src/gui/browserbox.h b/src/gui/browserbox.h
index 5dde402e..090c03e1 100644
--- a/src/gui/browserbox.h
+++ b/src/gui/browserbox.h
@@ -162,4 +162,3 @@ class BrowserBox : public gcn::Widget, public gcn::MouseListener
};
#endif
-
diff --git a/src/gui/buddywindow.cpp b/src/gui/buddywindow.cpp
new file mode 100644
index 00000000..25084593
--- /dev/null
+++ b/src/gui/buddywindow.cpp
@@ -0,0 +1,68 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "buddywindow.h"
+#include "chat.h"
+#include "icon.h"
+
+#include "widgets/avatar.h"
+
+#include "../resources/resourcemanager.h"
+#include "../utils/gettext.h"
+
+extern ChatWindow *chatWindow;
+
+BuddyWindow::BuddyWindow():
+ Window(_("Buddy"))
+{
+ setVisible(false);
+ setWindowName("Buddy Window");
+ setCaption(_("Buddy List"));
+ setResizable(true);
+ setCloseButton(true);
+ setMinWidth(110);
+ setMinHeight(200);
+ setDefaultSize(124, 41, 288, 330);
+
+ Image *addImg = ResourceManager::getInstance()->getImage("buddyadd.png");
+ Image *delImg = ResourceManager::getInstance()->getImage("buddydel.png");
+
+ if (addImg && delImg)
+ {
+ Icon *addBuddy = new Icon(addImg);
+ Icon *delBuddy = new Icon(delImg);
+
+ add(addBuddy);
+ add(delBuddy);
+ }
+
+ loadWindowState();
+}
+
+void BuddyWindow::action(const gcn::ActionEvent &event)
+{
+
+}
+
+void BuddyWindow::draw(gcn::Graphics *graphics)
+{
+ Window::draw(graphics);
+}
diff --git a/src/gui/buddywindow.h b/src/gui/buddywindow.h
new file mode 100644
index 00000000..dfe356d5
--- /dev/null
+++ b/src/gui/buddywindow.h
@@ -0,0 +1,60 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_BUDDYWINDOW_H
+#define _TMW_BUDDYWINDOW_H
+
+#include <guichan/actionlistener.hpp>
+#include <guichan/actionevent.hpp>
+
+#include "window.h"
+
+class Avatar;
+
+/**
+ * Window showing buddy list.
+ *
+ * \ingroup Interface
+ */
+class BuddyWindow : public Window, public gcn::ActionListener
+{
+ public:
+ /**
+ * Constructor.
+ */
+ BuddyWindow();
+
+ /**
+ * Performs action.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ /**
+ * Draws the window
+ */
+ void draw(gcn::Graphics *graphics);
+
+
+ private:
+ std::list<Avatar*> mBuddyList;
+};
+
+#endif /* _TMW_BUDDYWINDOW_H */
diff --git a/src/gui/buy.cpp b/src/gui/buy.cpp
index b31d48e1..15a558a3 100644
--- a/src/gui/buy.cpp
+++ b/src/gui/buy.cpp
@@ -33,14 +33,25 @@
#include "../npc.h"
#include "../units.h"
+#ifdef TMWSERV_SUPPORT
+#include "../net/gameserver/player.h"
+#else
#include "../net/messageout.h"
-#include "../net/protocol.h"
+#include "../net/ea/protocol.h"
+#endif
#include "../utils/gettext.h"
#include "../utils/strprintf.h"
+#ifdef TMWSERV_SUPPORT
+BuyDialog::BuyDialog():
+#else
BuyDialog::BuyDialog(Network *network):
- Window(_("Buy")), mNetwork(network),
+#endif
+ Window(_("Buy")),
+#ifndef TMWSERV_SUPPORT
+ mNetwork(network),
+#endif
mMoney(0), mAmountItems(0), mMaxItems(0)
{
setWindowName("Buy");
@@ -119,9 +130,9 @@ void BuyDialog::reset()
setMoney(0);
}
-void BuyDialog::addItem(short id, int price)
+void BuyDialog::addItem(int id, int amount, int price)
{
- mShopItems->addItem(id, price);
+ mShopItems->addItem(id, amount, price);
mShopItemList->adjustSize();
}
@@ -166,11 +177,16 @@ void BuyDialog::action(const gcn::ActionEvent &event)
else if (event.getId() == "buy" && mAmountItems > 0 &&
mAmountItems <= mMaxItems)
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::tradeWithNPC
+ (mShopItems->at(selectedItem)->getId(), mAmountItems);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_BUY_REQUEST);
outMsg.writeInt16(8);
outMsg.writeInt16(mAmountItems);
outMsg.writeInt16(mShopItems->at(selectedItem)->getId());
+#endif
// Update money and adjust the max number of items that can be bought
mMaxItems -= mAmountItems;
diff --git a/src/gui/buy.h b/src/gui/buy.h
index 0f1cfede..5510ccc6 100644
--- a/src/gui/buy.h
+++ b/src/gui/buy.h
@@ -25,11 +25,13 @@
#include <guichan/actionlistener.hpp>
#include <guichan/selectionlistener.hpp>
-#include <SDL_types.h>
-
#include "window.h"
+#include "../guichanfwd.h"
+
+#ifndef TMWSERV_SUPPORT
class Network;
+#endif
class ShopItems;
class ShopListBox;
class ListBox;
@@ -48,7 +50,11 @@ class BuyDialog : public Window, public gcn::ActionListener,
*
* @see Window::Window
*/
+#ifdef TMWSERV_SUPPORT
+ BuyDialog();
+#else
BuyDialog(Network *network);
+#endif
/**
* Destructor
@@ -68,7 +74,7 @@ class BuyDialog : public Window, public gcn::ActionListener,
/**
* Adds an item to the shop inventory.
*/
- void addItem(short id, int price);
+ void addItem(int id, int amount, int price);
/**
* Called when receiving actions from the widgets.
@@ -96,7 +102,9 @@ class BuyDialog : public Window, public gcn::ActionListener,
void updateButtonsAndLabels();
private:
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
gcn::Button *mBuyButton;
gcn::Button *mQuitButton;
gcn::Button *mIncreaseButton;
@@ -111,9 +119,9 @@ class BuyDialog : public Window, public gcn::ActionListener,
ShopItems *mShopItems;
- Uint32 mMoney;
- Uint32 mAmountItems;
- Uint32 mMaxItems;
+ int mMoney;
+ int mAmountItems;
+ int mMaxItems;
};
#endif
diff --git a/src/gui/changeemaildialog.cpp b/src/gui/changeemaildialog.cpp
new file mode 100644
index 00000000..c9bc2570
--- /dev/null
+++ b/src/gui/changeemaildialog.cpp
@@ -0,0 +1,167 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "changeemaildialog.h"
+
+#include <string>
+#include <sstream>
+
+#include <guichan/widgets/label.hpp>
+
+#include "../main.h"
+#include "../log.h"
+#include "../logindata.h"
+
+#include "button.h"
+#include "register.h"
+#include "textfield.h"
+#include "ok_dialog.h"
+
+#include "../utils/gettext.h"
+#include "../utils/strprintf.h"
+
+ChangeEmailDialog::ChangeEmailDialog(Window *parent, LoginData *loginData):
+ Window(_("Change Email Address"), true, parent),
+ mWrongDataNoticeListener(new WrongDataNoticeListener()),
+ mLoginData(loginData)
+{
+ gcn::Label *accountLabel = new gcn::Label(strprintf(_("Account: %s"),
+ mLoginData->username.c_str()));
+ gcn::Label *newEmailLabel = new gcn::Label(_("Type New Email Address twice:"));
+ mFirstEmailField = new TextField();
+ mSecondEmailField = new TextField();
+ mChangeEmailButton = new Button(_("Change Email Address"), "change_email", this);
+ mCancelButton = new Button(_("Cancel"), "cancel", this);
+
+ const int width = 200;
+ const int height = 130;
+ setContentSize(width, height);
+
+ accountLabel->setPosition(5, 5);
+ accountLabel->setWidth(130);
+
+ newEmailLabel->setPosition(
+ 5, accountLabel->getY() + accountLabel->getHeight() + 7);
+ newEmailLabel->setWidth(width - 5);
+
+ mFirstEmailField->setPosition(
+ 5, newEmailLabel->getY() + newEmailLabel->getHeight() + 7);
+ mFirstEmailField->setWidth(130);
+
+ mSecondEmailField->setPosition(
+ 5, mFirstEmailField->getY() + mFirstEmailField->getHeight() + 7);
+ mSecondEmailField->setWidth(130);
+
+ mCancelButton->setPosition(
+ width - 5 - mCancelButton->getWidth(),
+ height - 5 - mCancelButton->getHeight());
+ mChangeEmailButton->setPosition(
+ mCancelButton->getX() - 5 - mChangeEmailButton->getWidth(),
+ mCancelButton->getY());
+
+ add(accountLabel);
+ add(newEmailLabel);
+ add(mFirstEmailField);
+ add(mSecondEmailField);
+ add(mChangeEmailButton);
+ add(mCancelButton);
+
+ setLocationRelativeTo(getParent());
+ setVisible(true);
+ mFirstEmailField->requestFocus();
+
+ mFirstEmailField->setActionEventId("change_email");
+ mSecondEmailField->setActionEventId("change_email");
+}
+
+ChangeEmailDialog::~ChangeEmailDialog()
+{
+ delete mWrongDataNoticeListener;
+}
+
+void
+ChangeEmailDialog::action(const gcn::ActionEvent &event)
+{
+ if (event.getId() == "cancel")
+ {
+ scheduleDelete();
+ }
+ else if (event.getId() == "change_email")
+ {
+
+ const std::string username = mLoginData->username.c_str();
+ const std::string newFirstEmail = mFirstEmailField->getText();
+ const std::string newSecondEmail = mSecondEmailField->getText();
+ logger->log("ChangeEmailDialog::Email change, Username is %s",
+ username.c_str());
+
+ std::stringstream errorMsg;
+ int error = 0;
+
+ if (newFirstEmail.length() < LEN_MIN_PASSWORD)
+ {
+ // First email address too short
+ errorMsg << "The new email address needs to be at least "
+ << LEN_MIN_PASSWORD
+ << " characters long.";
+ error = 1;
+ }
+ else if (newFirstEmail.length() > LEN_MAX_PASSWORD - 1 )
+ {
+ // First email address too long
+ errorMsg << "The new email address needs to be less than "
+ << LEN_MAX_PASSWORD
+ << " characters long.";
+ error = 1;
+ }
+ else if (newFirstEmail != newSecondEmail)
+ {
+ // Second Pass mismatch
+ errorMsg << "The email address entries mismatch.";
+ error = 2;
+ }
+
+ if (error > 0)
+ {
+ if (error == 1)
+ {
+ mWrongDataNoticeListener->setTarget(this->mFirstEmailField);
+ }
+ else if (error == 2)
+ {
+ mWrongDataNoticeListener->setTarget(this->mSecondEmailField);
+ }
+
+ OkDialog *dlg = new OkDialog("Error", errorMsg.str());
+ dlg->addActionListener(mWrongDataNoticeListener);
+ }
+ else
+ {
+ // No errors detected, change account password.
+ mChangeEmailButton->setEnabled(false);
+ // Set the new email address
+ mLoginData->newEmail = newFirstEmail;
+ state = STATE_CHANGEEMAIL_ATTEMPT;
+ scheduleDelete();
+ }
+
+ }
+}
diff --git a/src/gui/changeemaildialog.h b/src/gui/changeemaildialog.h
new file mode 100644
index 00000000..8ec3705d
--- /dev/null
+++ b/src/gui/changeemaildialog.h
@@ -0,0 +1,71 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_GUI_CHANGEEMAIL_H
+#define _TMW_GUI_CHANGEEMAIL_H
+
+#include <iosfwd>
+#include <guichan/actionlistener.hpp>
+
+#include "window.h"
+#include "../guichanfwd.h"
+
+class LoginData;
+class OkDialog;
+class WrongDataNoticeListener;
+
+/**
+ * The Change email dialog.
+ *
+ * \ingroup Interface
+ */
+class ChangeEmailDialog : public Window, public gcn::ActionListener {
+ public:
+ /**
+ * Constructor.
+ *
+ * @see Window::Window
+ */
+ ChangeEmailDialog(Window *parent, LoginData *loginData);
+
+ /**
+ * Destructor.
+ */
+ ~ChangeEmailDialog();
+
+ /**
+ * Called when receiving actions from the widgets.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ private:
+ gcn::TextField *mFirstEmailField;
+ gcn::TextField *mSecondEmailField;
+
+ gcn::Button *mChangeEmailButton;
+ gcn::Button *mCancelButton;
+
+ WrongDataNoticeListener *mWrongDataNoticeListener;
+
+ LoginData *mLoginData;
+};
+
+#endif
diff --git a/src/gui/changepassworddialog.cpp b/src/gui/changepassworddialog.cpp
new file mode 100644
index 00000000..8d667790
--- /dev/null
+++ b/src/gui/changepassworddialog.cpp
@@ -0,0 +1,193 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "changepassworddialog.h"
+
+#include <string>
+#include <sstream>
+
+#include <guichan/widgets/label.hpp>
+
+#include "../main.h"
+#include "../log.h"
+#include "../logindata.h"
+
+#include "button.h"
+#include "register.h"
+#include "passwordfield.h"
+#include "textfield.h"
+#include "ok_dialog.h"
+
+#include "../utils/gettext.h"
+#include "../utils/strprintf.h"
+
+ChangePasswordDialog::ChangePasswordDialog(Window *parent, LoginData *loginData):
+ Window(_("Change Password"), true, parent),
+ mWrongDataNoticeListener(new WrongDataNoticeListener()),
+ mLoginData(loginData)
+{
+ gcn::Label *accountLabel = new gcn::Label(strprintf(_("Account: %s"),
+ mLoginData->username.c_str()));
+ gcn::Label *oldPassLabel = new gcn::Label(_("Password:"));
+ mOldPassField = new PasswordField();
+ gcn::Label *newPassLabel = new gcn::Label(_("Type New Password twice:"));
+ mFirstPassField = new PasswordField();
+ mSecondPassField = new PasswordField();
+ mChangePassButton = new Button(_("Change Password"), "change_password", this);
+ mCancelButton = new Button(_("Cancel"), "cancel", this);
+
+ const int width = 200;
+ const int height = 170;
+ setContentSize(width, height);
+
+ accountLabel->setPosition(5, 5);
+ accountLabel->setWidth(130);
+ oldPassLabel->setPosition(
+ 5, accountLabel->getY() + accountLabel->getHeight() + 7);
+ oldPassLabel->setWidth(130);
+
+ mOldPassField->setPosition(
+ 5, oldPassLabel->getY() + oldPassLabel->getHeight() + 7);
+ mOldPassField->setWidth(130);
+
+ newPassLabel->setPosition(
+ 5, mOldPassField->getY() + mOldPassField->getHeight() + 7);
+ newPassLabel->setWidth(width - 5);
+
+ mFirstPassField->setPosition(
+ 5, newPassLabel->getY() + newPassLabel->getHeight() + 7);
+ mFirstPassField->setWidth(130);
+
+ mSecondPassField->setPosition(
+ 5, mFirstPassField->getY() + mFirstPassField->getHeight() + 7);
+ mSecondPassField->setWidth(130);
+
+ mCancelButton->setPosition(
+ width - 5 - mCancelButton->getWidth(),
+ height - 5 - mCancelButton->getHeight());
+ mChangePassButton->setPosition(
+ mCancelButton->getX() - 5 - mChangePassButton->getWidth(),
+ mCancelButton->getY());
+
+ add(accountLabel);
+ add(oldPassLabel);
+ add(mOldPassField);
+ add(newPassLabel);
+ add(mFirstPassField);
+ add(mSecondPassField);
+ add(mChangePassButton);
+ add(mCancelButton);
+
+ setLocationRelativeTo(getParent());
+ setVisible(true);
+ mOldPassField->requestFocus();
+
+ mOldPassField->setActionEventId("change_password");
+ mFirstPassField->setActionEventId("change_password");
+ mSecondPassField->setActionEventId("change_password");
+}
+
+ChangePasswordDialog::~ChangePasswordDialog()
+{
+ delete mWrongDataNoticeListener;
+}
+
+void
+ChangePasswordDialog::action(const gcn::ActionEvent &event)
+{
+ if (event.getId() == "cancel")
+ {
+ scheduleDelete();
+ }
+ else if (event.getId() == "change_password")
+ {
+
+ const std::string username = mLoginData->username.c_str();
+ const std::string oldPassword = mOldPassField->getText();
+ const std::string newFirstPass = mFirstPassField->getText();
+ const std::string newSecondPass = mSecondPassField->getText();
+ logger->log("ChangePasswordDialog::Password change, Username is %s",
+ username.c_str());
+
+ std::stringstream errorMsg;
+ int error = 0;
+
+ // Check old Password
+ if (oldPassword.empty())
+ {
+ // No old password
+ errorMsg << "Enter the old Password first.";
+ error = 1;
+ }
+ else if (newFirstPass.length() < LEN_MIN_PASSWORD)
+ {
+ // First password too short
+ errorMsg << "The new password needs to be at least "
+ << LEN_MIN_PASSWORD
+ << " characters long.";
+ error = 2;
+ }
+ else if (newFirstPass.length() > LEN_MAX_PASSWORD - 1 )
+ {
+ // First password too long
+ errorMsg << "The new password needs to be less than "
+ << LEN_MAX_PASSWORD
+ << " characters long.";
+ error = 2;
+ }
+ else if (newFirstPass != newSecondPass)
+ {
+ // Second Pass mismatch
+ errorMsg << "The new password entries mismatch.";
+ error = 3;
+ }
+
+ if (error > 0)
+ {
+ if (error == 1)
+ {
+ mWrongDataNoticeListener->setTarget(this->mOldPassField);
+ }
+ else if (error == 2)
+ {
+ mWrongDataNoticeListener->setTarget(this->mFirstPassField);
+ }
+ else if (error == 3)
+ {
+ mWrongDataNoticeListener->setTarget(this->mSecondPassField);
+ }
+
+ OkDialog *dlg = new OkDialog("Error", errorMsg.str());
+ dlg->addActionListener(mWrongDataNoticeListener);
+ }
+ else
+ {
+ // No errors detected, change account password.
+ mChangePassButton->setEnabled(false);
+ // Set the new password
+ mLoginData->password = oldPassword;
+ mLoginData->newPassword = newFirstPass;
+ state = STATE_CHANGEPASSWORD_ATTEMPT;
+ scheduleDelete();
+ }
+
+ }
+}
diff --git a/src/gui/changepassworddialog.h b/src/gui/changepassworddialog.h
new file mode 100644
index 00000000..0cf744da
--- /dev/null
+++ b/src/gui/changepassworddialog.h
@@ -0,0 +1,72 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_CHANGEPASSWORDDIALOG_H
+#define _TMW_CHANGEPASSWORDDIALOG_H
+
+#include <iosfwd>
+#include <guichan/actionlistener.hpp>
+
+#include "window.h"
+#include "../guichanfwd.h"
+
+class LoginData;
+class OkDialog;
+class WrongDataNoticeListener;
+
+/**
+ * The Change password dialog.
+ *
+ * \ingroup Interface
+ */
+class ChangePasswordDialog : public Window, public gcn::ActionListener {
+ public:
+ /**
+ * Constructor
+ *
+ * @see Window::Window
+ */
+ ChangePasswordDialog(Window *parent,LoginData *loginData);
+
+ /**
+ * Destructor
+ */
+ ~ChangePasswordDialog();
+
+ /**
+ * Called when receiving actions from the widgets.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ private:
+ gcn::TextField *mOldPassField;
+ gcn::TextField *mFirstPassField;
+ gcn::TextField *mSecondPassField;
+
+ gcn::Button *mChangePassButton;
+ gcn::Button *mCancelButton;
+
+ WrongDataNoticeListener *mWrongDataNoticeListener;
+
+ LoginData *mLoginData;
+};
+
+#endif
diff --git a/src/gui/char_select.cpp b/src/gui/char_select.cpp
index 34218477..84270d10 100644
--- a/src/gui/char_select.cpp
+++ b/src/gui/char_select.cpp
@@ -32,6 +32,19 @@
#include "playerbox.h"
#include "textfield.h"
+#ifdef TMWSERV_SUPPORT
+#include "radiobutton.h"
+#include "slider.h"
+
+#include "unregisterdialog.h"
+#include "changepassworddialog.h"
+#include "changeemaildialog.h"
+
+#include "../logindata.h"
+
+#include "../net/accountserver/account.h"
+#endif
+
#include "widgets/layout.h"
#include "../game.h"
@@ -80,22 +93,72 @@ void CharDeleteConfirm::action(const gcn::ActionEvent &event)
ConfirmDialog::action(event);
}
+#ifdef TMWSERV_SUPPORT
+CharSelectDialog::CharSelectDialog(LockedArray<LocalPlayer*> *charInfo,
+ LoginData *loginData):
+ Window(_("Account and Character Management")),
+ mCharInfo(charInfo), mCharSelected(false), mLoginData(loginData)
+#else
CharSelectDialog::CharSelectDialog(Network *network,
LockedArray<LocalPlayer*> *charInfo,
Gender gender):
Window(_("Select Character")), mNetwork(network),
- mCharInfo(charInfo), mGender(gender), mCharSelected(false)
+ mCharInfo(charInfo),
+ mCharSelected(false),
+ mGender(gender)
+#endif
{
+ mSelectButton = new Button(_("Ok"), "ok", this);
+ mCancelButton = new Button(_("Cancel"), "cancel", this);
+ mPreviousButton = new Button(_("Previous"), "previous", this);
+ mNextButton = new Button(_("Next"), "next", this);
+ mNameLabel = new gcn::Label(strprintf(_("Name: %s"), ""));
+ mLevelLabel = new gcn::Label(strprintf(_("Level: %d"), 0));
+#ifdef TMWSERV_SUPPORT
+ mNewCharButton = new Button(_("New"), "new", this);
+ mDelCharButton = new Button(_("Delete"), "delete", this);
+ mUnRegisterButton = new Button(_("Unregister"), "unregister", this);
+ mChangePasswordButton = new Button(_("Change Password"), "change_password", this);
+ mChangeEmailButton = new Button(_("Change Email Address"), "change_email", this);
+
+ mAccountNameLabel = new gcn::Label(strprintf(_("Account: %s"), mLoginData->username.c_str()));
+ mNameLabel = new gcn::Label(strprintf(_("Name: %s"), ""));
+ mLevelLabel = new gcn::Label(strprintf(_("Level: %d"), 0));
+ mMoneyLabel = new gcn::Label(strprintf(_("Money: %d"), 0));
+
+ // Control that shows the Player
+ mPlayerBox = new PlayerBox;
+ mPlayerBox->setWidth(74);
+
+ ContainerPlacer place;
+ place = getPlacer(0, 0);
+ place(0, 0, mAccountNameLabel);
+ place(0, 1, mUnRegisterButton);
+ place(0, 2, mChangePasswordButton);
+ place(1, 2, mChangeEmailButton);
+ place = getPlacer(0, 1);
+ place(0, 0, mPlayerBox, 1, 5).setPadding(3);
+ place(1, 0, mNameLabel, 3);
+ place(1, 1, mLevelLabel, 3);
+ place(1, 2, mMoneyLabel, 3);
+ place(1, 3, mPreviousButton);
+ place(2, 3, mNextButton);
+ place(1, 4, mNewCharButton);
+ place(2, 4, mDelCharButton);
+ place.getCell().matchColWidth(1, 2);
+ place = getPlacer(0, 2);
+ place(0, 0, mSelectButton);
+ place(1, 0, mCancelButton);
+ reflowLayout(265, 0);
+#else
mCharInfo->select(0);
LocalPlayer *pi = mCharInfo->getEntry();
if (pi)
- mMoney = Units::formatCurrency(pi->mGp);
+ mMoney = Units::formatCurrency(pi->getMoney());
// Control that shows the Player
mPlayerBox = new PlayerBox;
mPlayerBox->setWidth(74);
- mNameLabel = new gcn::Label(strprintf(_("Name: %s"), ""));
- mLevelLabel = new gcn::Label(strprintf(_("Level: %d"), 0));
mJobLevelLabel = new gcn::Label(strprintf(_("Job Level: %d"), 0));
mMoneyLabel = new gcn::Label(strprintf(_("Money: %s"), mMoney.c_str()));
@@ -103,11 +166,7 @@ CharSelectDialog::CharSelectDialog(Network *network,
getFont()->getWidth(_("Delete")) ?
_("Delete") : _("New");
- mPreviousButton = new Button(_("Previous"), "previous", this);
- mNextButton = new Button(_("Next"), "next", this);
mNewDelCharButton = new Button(tempString, "newdel", this);
- mSelectButton = new Button(_("Ok"), "ok", this);
- mCancelButton = new Button(_("Cancel"), "cancel", this);
ContainerPlacer place;
place = getPlacer(0, 0);
@@ -126,6 +185,7 @@ CharSelectDialog::CharSelectDialog(Network *network,
place(5, 0, mSelectButton);
reflowLayout(250, 0);
+#endif
setLocationRelativeTo(getParent());
setVisible(true);
@@ -135,10 +195,21 @@ CharSelectDialog::CharSelectDialog(Network *network,
void CharSelectDialog::action(const gcn::ActionEvent &event)
{
+#ifdef TMWSERV_SUPPORT
+ // The pointers are set to NULL if there is no character stored
+ if (event.getId() == "ok" && (mCharInfo->getEntry()))
+#else
if (event.getId() == "ok" && n_character > 0)
+#endif
{
// Start game
+#ifdef TMWSERV_SUPPORT
+ mNewCharButton->setEnabled(false);
+ mDelCharButton->setEnabled(false);
+ mUnRegisterButton->setEnabled(false);
+#else
mNewDelCharButton->setEnabled(false);
+#endif
mSelectButton->setEnabled(false);
mPreviousButton->setEnabled(false);
mNextButton->setEnabled(false);
@@ -147,8 +218,35 @@ void CharSelectDialog::action(const gcn::ActionEvent &event)
}
else if (event.getId() == "cancel")
{
- state = EXIT_STATE;
+#ifdef TMWSERV_SUPPORT
+ mCharInfo->clear();
+ state = STATE_SWITCH_ACCOUNTSERVER_ATTEMPT;
+#else
+ state = STATE_EXIT;
+#endif
+ }
+#ifdef TMWSERV_SUPPORT
+ else if (event.getId() == "new")
+ {
+ // TODO: Search the first free slot, and start CharCreateDialog
+ // maybe add that search to the constructor.
+ if (!(mCharInfo->getEntry()))
+ {
+ // Start new character dialog
+ CharCreateDialog *charCreateDialog =
+ new CharCreateDialog(this, mCharInfo->getPos());
+ charServerHandler.setCharCreateDialog(charCreateDialog);
+ }
+ }
+ else if (event.getId() == "delete")
+ {
+ // Delete character
+ if (mCharInfo->getEntry())
+ {
+ new CharDeleteConfirm(this);
+ }
}
+#else
else if (event.getId() == "newdel")
{
// Check for a character
@@ -165,20 +263,35 @@ void CharSelectDialog::action(const gcn::ActionEvent &event)
charServerHandler.setCharCreateDialog(charCreateDialog);
}
}
+#endif
else if (event.getId() == "previous")
{
mCharInfo->prev();
LocalPlayer *pi = mCharInfo->getEntry();
if (pi)
- mMoney = Units::formatCurrency(pi->mGp);
+ mMoney = Units::formatCurrency(pi->getMoney());
}
else if (event.getId() == "next")
{
mCharInfo->next();
LocalPlayer *pi = mCharInfo->getEntry();
if (pi)
- mMoney = Units::formatCurrency(pi->mGp);
+ mMoney = Units::formatCurrency(pi->getMoney());
+ }
+#ifdef TMWSERV_SUPPORT
+ else if (event.getId() == "unregister")
+ {
+ new UnRegisterDialog(this, mLoginData);
}
+ else if (event.getId() == "change_password")
+ {
+ new ChangePasswordDialog(this, mLoginData);
+ }
+ else if (event.getId() == "change_email")
+ {
+ new ChangeEmailDialog(this, mLoginData);
+ }
+#endif
}
void CharSelectDialog::updatePlayerInfo()
@@ -189,13 +302,20 @@ void CharSelectDialog::updatePlayerInfo()
{
mNameLabel->setCaption(strprintf(_("Name: %s"),
pi->getName().c_str()));
- mLevelLabel->setCaption(strprintf(_("Level: %d"), pi->mLevel));
+ mLevelLabel->setCaption(strprintf(_("Level: %d"), pi->getLevel()));
+#ifndef TMWSERV_SUPPORT
mJobLevelLabel->setCaption(strprintf(_("Job Level: %d"),
pi->mJobLevel));
+#endif
mMoneyLabel->setCaption(strprintf(_("Money: %s"), mMoney.c_str()));
if (!mCharSelected)
{
+#ifdef TMWSERV_SUPPORT
+ mNewCharButton->setEnabled(false);
+ mDelCharButton->setEnabled(true);
+#else
mNewDelCharButton->setCaption(_("Delete"));
+#endif
mSelectButton->setEnabled(true);
}
}
@@ -203,9 +323,16 @@ void CharSelectDialog::updatePlayerInfo()
{
mNameLabel->setCaption(strprintf(_("Name: %s"), ""));
mLevelLabel->setCaption(strprintf(_("Level: %d"), 0));
+#ifndef TMWSERV_SUPPORT
mJobLevelLabel->setCaption(strprintf(_("Job Level: %d"), 0));
+#endif
mMoneyLabel->setCaption(strprintf(_("Money: %s"), ""));
+#ifdef TMWSERV_SUPPORT
+ mNewCharButton->setEnabled(true);
+ mDelCharButton->setEnabled(false);
+#else
mNewDelCharButton->setCaption(_("New"));
+#endif
mSelectButton->setEnabled(false);
}
@@ -214,20 +341,28 @@ void CharSelectDialog::updatePlayerInfo()
void CharSelectDialog::attemptCharDelete()
{
+#ifdef TMWSERV_SUPPORT
+ Net::AccountServer::Account::deleteCharacter(mCharInfo->getPos());
+#else
// Request character deletion
MessageOut outMsg(mNetwork);
outMsg.writeInt16(0x0068);
outMsg.writeInt32(mCharInfo->getEntry()->mCharId);
outMsg.writeString("a@a.com", 40);
+#endif
mCharInfo->lock();
}
void CharSelectDialog::attemptCharSelect()
{
+#ifdef TMWSERV_SUPPORT
+ Net::AccountServer::Account::selectCharacter(mCharInfo->getPos());
+#else
// Request character selection
MessageOut outMsg(mNetwork);
outMsg.writeInt16(0x0066);
outMsg.writeInt8(mCharInfo->getPos());
+#endif
mCharInfo->lock();
}
@@ -259,16 +394,29 @@ bool CharSelectDialog::selectByName(const std::string &name)
return false;
}
+#ifdef TMWSERV_SUPPORT
+CharCreateDialog::CharCreateDialog(Window *parent, int slot):
+#else
CharCreateDialog::CharCreateDialog(Window *parent, int slot, Network *network,
Gender gender):
- Window(_("Create Character"), true, parent), mNetwork(network), mSlot(slot)
+#endif
+ Window(_("Create Character"), true, parent),
+#ifndef TMWSERV_SUPPORT
+ mNetwork(network),
+#endif
+ mSlot(slot)
{
mPlayer = new Player(0, 0, NULL);
+#ifdef TMWSERV_SUPPORT
+ mPlayer->setGender(GENDER_MALE);
+#else
mPlayer->setGender(gender);
+#endif
int numberOfHairColors = ColorDB::size();
- mPlayer->setHairStyle(rand() % mPlayer->getNumOfHairstyles(), rand() % numberOfHairColors);
+ mPlayer->setHairStyle(rand() % mPlayer->getNumOfHairstyles(),
+ rand() % numberOfHairColors);
mNameField = new TextField("");
mNameLabel = new gcn::Label(_("Name:"));
@@ -280,6 +428,19 @@ CharCreateDialog::CharCreateDialog(Window *parent, int slot, Network *network,
mHairStyleLabel = new gcn::Label(_("Hair Style:"));
mCreateButton = new Button(_("Create"), "create", this);
mCancelButton = new Button(_("Cancel"), "cancel", this);
+#ifdef TMWSERV_SUPPORT
+ mMale = new RadioButton(_("Male"), "gender");
+ mFemale = new RadioButton(_("Female"), "gender");
+
+ // Default to a Male character
+ mMale->setSelected(true);
+
+ mMale->setActionEventId("gender");
+ mFemale->setActionEventId("gender");
+
+ mMale->addActionListener(this);
+ mFemale->addActionListener(this);
+#endif
mPlayerBox = new PlayerBox(mPlayer);
mPlayerBox->setWidth(74);
@@ -287,6 +448,81 @@ CharCreateDialog::CharCreateDialog(Window *parent, int slot, Network *network,
mNameField->setActionEventId("create");
mNameField->addActionListener(this);
+#ifdef TMWSERV_SUPPORT
+ mAttributeLabel[0] = new gcn::Label(_("Strength:"));
+ mAttributeLabel[1] = new gcn::Label(_("Agility:"));
+ mAttributeLabel[2] = new gcn::Label(_("Dexterity:"));
+ mAttributeLabel[3] = new gcn::Label(_("Vitality:"));
+ mAttributeLabel[4] = new gcn::Label(_("Intelligence:"));
+ mAttributeLabel[5] = new gcn::Label(_("Willpower:"));
+ for (int i = 0; i < 6; i++)
+ {
+ mAttributeLabel[i]->setWidth(70);
+ mAttributeSlider[i] = new Slider(1, 20);
+ mAttributeValue[i] = new gcn::Label("1");
+ };
+
+ mAttributesLeft = new gcn::Label(strprintf(_("Please distribute %d points"), 99));
+
+ int w = 200;
+ int h = 330;
+ setContentSize(w, h);
+ mPlayerBox->setDimension(gcn::Rectangle(80, 30, 110, 85));
+ mNameLabel->setPosition(5, 5);
+ mNameField->setDimension(
+ gcn::Rectangle(45, 5, w - 45 - 7, mNameField->getHeight()));
+ mPrevHairColorButton->setPosition(90, 35);
+ mNextHairColorButton->setPosition(165, 35);
+ mHairColorLabel->setPosition(5, 40);
+ mPrevHairStyleButton->setPosition(90, 64);
+ mNextHairStyleButton->setPosition(165, 64);
+ mHairStyleLabel->setPosition(5, 70);
+ for (int i=0; i<6; i++)
+ {
+ mAttributeSlider[i]->setValue(10);
+ mAttributeSlider[i]->setDimension(gcn::Rectangle( 75, 140 + i*20,
+ 100, 10));
+ mAttributeSlider[i]->setActionEventId("statslider");
+ mAttributeSlider[i]->addActionListener(this);
+ mAttributeValue[i]->setPosition(180, 140 + i*20);
+ mAttributeLabel[i]->setPosition(5, 140 + i*20);
+ };
+ mAttributesLeft->setPosition(15, 280);
+ UpdateSliders();
+ mCancelButton->setPosition(
+ w - 5 - mCancelButton->getWidth(),
+ h - 5 - mCancelButton->getHeight());
+ mCreateButton->setPosition(
+ mCancelButton->getX() - 5 - mCreateButton->getWidth(),
+ h - 5 - mCancelButton->getHeight());
+
+ mMale->setPosition(30, 120);
+ mFemale->setPosition(100, 120);
+
+ add(mPlayerBox);
+ add(mNameField);
+ add(mNameLabel);
+ add(mNextHairColorButton);
+ add(mPrevHairColorButton);
+ add(mHairColorLabel);
+ add(mNextHairStyleButton);
+ add(mPrevHairStyleButton);
+ add(mHairStyleLabel);
+ for (int i = 0; i < 6; i++)
+ {
+ add(mAttributeSlider[i]);
+ add(mAttributeValue[i]);
+ add(mAttributeLabel[i]);
+ };
+ add(mAttributesLeft);
+ add(mCreateButton);
+ add(mCancelButton);
+
+ add(mMale);
+ add(mFemale);
+
+#else
+
ContainerPlacer place;
place = getPlacer(0, 0);
@@ -305,6 +541,7 @@ CharCreateDialog::CharCreateDialog(Window *parent, int slot, Network *network,
place(5, 0, mCreateButton);
reflowLayout(225, 0);
+#endif
setLocationRelativeTo(getParent());
setVisible(true);
@@ -328,12 +565,35 @@ void CharCreateDialog::action(const gcn::ActionEvent &event)
{
// Attempt to create the character
mCreateButton->setEnabled(false);
+#ifdef TMWSERV_SUPPORT
+ unsigned int genderSelected;
+ if (mMale->isSelected()) {
+ genderSelected = GENDER_MALE;
+ } else {
+ genderSelected = GENDER_FEMALE;
+ }
+
+ Net::AccountServer::Account::createCharacter(
+ getName(),
+ mPlayer->getHairStyle(),
+ mPlayer->getHairColor(),
+ genderSelected, // gender
+ (int) mAttributeSlider[0]->getValue(), // STR
+ (int) mAttributeSlider[1]->getValue(), // AGI
+ (int) mAttributeSlider[2]->getValue(), // DEX
+ (int) mAttributeSlider[3]->getValue(), // VIT
+ (int) mAttributeSlider[4]->getValue(), // INT
+ (int) mAttributeSlider[5]->getValue() // WILL
+ );
+#else
attemptCharCreate();
+#endif
}
else
{
- new OkDialog("Error",
- "Your name needs to be at least 4 characters.", this);
+ new OkDialog(_("Error"),
+ _("Your name needs to be at least 4 characters."),
+ this);
}
}
else if (event.getId() == "cancel")
@@ -352,6 +612,18 @@ void CharCreateDialog::action(const gcn::ActionEvent &event)
mPlayer->setHairStyle(mPlayer->getHairStyle() +
mPlayer->getNumOfHairstyles() - 1,
mPlayer->getHairColor());
+#ifdef TMWSERV_SUPPORT
+ else if (event.getId() == "statslider") {
+ UpdateSliders();
+ }
+ else if (event.getId() == "gender"){
+ if (mMale->isSelected()) {
+ mPlayer->setGender(GENDER_MALE);
+ } else {
+ mPlayer->setGender(GENDER_FEMALE);
+ }
+ }
+#endif
}
std::string CharCreateDialog::getName()
@@ -361,11 +633,60 @@ std::string CharCreateDialog::getName()
return name;
}
+#ifdef TMWSERV_SUPPORT
+void CharCreateDialog::UpdateSliders()
+{
+ for (int i = 0; i < 6; i++)
+ {
+ // Update captions
+ mAttributeValue[i]->setCaption(
+ toString((int) (mAttributeSlider[i]->getValue())));
+ mAttributeValue[i]->adjustSize();
+ }
+
+ // Update distributed points
+ int pointsLeft = 60 - getDistributedPoints();
+ if (pointsLeft == 0)
+ {
+ mAttributesLeft->setCaption(_("Character stats OK"));
+ mCreateButton->setEnabled(true);
+ }
+ else
+ {
+ mCreateButton->setEnabled(false);
+ if (pointsLeft > 0)
+ {
+ mAttributesLeft->setCaption(strprintf(_("Please distribute %d points"), pointsLeft));
+ }
+ else
+ {
+ mAttributesLeft->setCaption(strprintf(_("Please remove %d points"), -pointsLeft));
+ }
+ }
+
+ mAttributesLeft->adjustSize();
+}
+#endif
+
void CharCreateDialog::unlock()
{
mCreateButton->setEnabled(true);
}
+#ifdef TMWSERV_SUPPORT
+int CharCreateDialog::getDistributedPoints()
+{
+ int points = 0;
+
+ for (int i = 0; i < 6; i++)
+ {
+ points += (int) mAttributeSlider[i]->getValue();
+ }
+ return points;
+}
+#endif
+
+#ifndef TMWSERV_SUPPORT
void CharCreateDialog::attemptCharCreate()
{
// Send character infos
@@ -382,3 +703,4 @@ void CharCreateDialog::attemptCharCreate()
outMsg.writeInt16(mPlayer->getHairColor());
outMsg.writeInt16(mPlayer->getHairStyle());
}
+#endif
diff --git a/src/gui/char_select.h b/src/gui/char_select.h
index 28091a18..0ff1d18f 100644
--- a/src/gui/char_select.h
+++ b/src/gui/char_select.h
@@ -27,10 +27,16 @@
#include "window.h"
#include "../being.h"
+#include "../guichanfwd.h"
#include "../lockedarray.h"
-class LocalPlayer;
+#ifdef TMWSERV_SUPPORT
+#include "../logindata.h"
+#else
class Network;
+#endif
+
+class LocalPlayer;
class Player;
class PlayerBox;
@@ -46,9 +52,14 @@ class CharSelectDialog : public Window, public gcn::ActionListener
/**
* Constructor.
*/
+#ifdef TMWSERV_SUPPORT
+ CharSelectDialog(LockedArray<LocalPlayer*> *charInfo,
+ LoginData *loginData);
+#else
CharSelectDialog(Network *network,
LockedArray<LocalPlayer*> *charInfo,
Gender gender);
+#endif
void action(const gcn::ActionEvent &event);
@@ -59,25 +70,40 @@ class CharSelectDialog : public Window, public gcn::ActionListener
bool selectByName(const std::string &name);
private:
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
LockedArray<LocalPlayer*> *mCharInfo;
gcn::Button *mSelectButton;
gcn::Button *mCancelButton;
- gcn::Button *mNewDelCharButton;
gcn::Button *mPreviousButton;
gcn::Button *mNextButton;
gcn::Label *mNameLabel;
gcn::Label *mLevelLabel;
- gcn::Label *mJobLevelLabel;
- gcn::Label *mMoneyLabel; std::string mMoney;
+ gcn::Label *mMoneyLabel;
+ std::string mMoney;
PlayerBox *mPlayerBox;
- Gender mGender;
bool mCharSelected;
+#ifdef TMWSERV_SUPPORT
+ gcn::Button *mNewCharButton;
+ gcn::Button *mDelCharButton;
+ gcn::Button *mUnRegisterButton;
+ gcn::Button *mChangePasswordButton;
+ gcn::Button *mChangeEmailButton;
+ gcn::Label *mAccountNameLabel;
+
+ LoginData *mLoginData;
+#else
+ gcn::Button *mNewDelCharButton;
+ gcn::Label *mJobLevelLabel;
+ Gender mGender;
+#endif
+
/**
* Communicate character deletion to the server.
*/
@@ -92,7 +118,7 @@ class CharSelectDialog : public Window, public gcn::ActionListener
/**
* Character creation dialog.
*
- * \ingroup GUI
+ * \ingroup Interface
*/
class CharCreateDialog : public Window, public gcn::ActionListener
{
@@ -100,8 +126,12 @@ class CharCreateDialog : public Window, public gcn::ActionListener
/**
* Constructor.
*/
+#ifdef TMWSERV_SUPPORT
+ CharCreateDialog(Window *parent, int slot);
+#else
CharCreateDialog(Window *parent, int slot, Network *network,
Gender gender);
+#endif
/**
* Destructor.
@@ -116,6 +146,12 @@ class CharCreateDialog : public Window, public gcn::ActionListener
void unlock();
private:
+#ifdef TMWSERV_SUPPORT
+ int getDistributedPoints();
+
+ void UpdateSliders();
+#endif
+
/**
* Returns the name of the character to create.
*/
@@ -126,7 +162,9 @@ class CharCreateDialog : public Window, public gcn::ActionListener
*/
void attemptCharCreate();
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
gcn::TextField *mNameField;
gcn::Label *mNameLabel;
gcn::Button *mNextHairColorButton;
@@ -135,6 +173,20 @@ class CharCreateDialog : public Window, public gcn::ActionListener
gcn::Button *mNextHairStyleButton;
gcn::Button *mPrevHairStyleButton;
gcn::Label *mHairStyleLabel;
+
+#ifdef TMWSERV_SUPPORT
+ gcn::RadioButton *mMale;
+ gcn::RadioButton *mFemale;
+
+ gcn::Slider *mAttributeSlider[6];
+ gcn::Label *mAttributeLabel[6];
+ gcn::Label *mAttributeValue[6];
+ gcn::Label *mAttributesLeft;
+
+ static const int mMaxPoints = 60;
+ int mUsedPoints;
+#endif
+
gcn::Button *mCreateButton;
gcn::Button *mCancelButton;
diff --git a/src/gui/char_server.cpp b/src/gui/char_server.cpp
index 89bfa93a..fa03bdc2 100644
--- a/src/gui/char_server.cpp
+++ b/src/gui/char_server.cpp
@@ -107,7 +107,7 @@ void ServerSelectDialog::action(const gcn::ActionEvent &event)
state = mNextState;
}
else if (event.getId() == "cancel")
- state = LOGIN_STATE;
+ state = STATE_LOGIN;
}
int ServerListModel::getNumberOfElements()
diff --git a/src/gui/chat.cpp b/src/gui/chat.cpp
index ac13355c..37250091 100644
--- a/src/gui/chat.cpp
+++ b/src/gui/chat.cpp
@@ -31,25 +31,44 @@
#include "windowcontainer.h"
#include "widgets/layout.h"
+#include "widgets/tab.h"
+#include "widgets/tabbedarea.h"
#include "../beingmanager.h"
+#ifdef TMWSERV_SUPPORT
+#include "../commandhandler.h"
+#endif
+#include "../channelmanager.h"
+#include "../channel.h"
#include "../configuration.h"
#include "../game.h"
#include "../localplayer.h"
-#include "../party.h"
+#ifdef TMWSERV_SUPPORT
+#include "../net/chatserver/chatserver.h"
+#include "../net/gameserver/player.h"
+#else
+#include "../party.h"
#include "../net/messageout.h"
-#include "../net/protocol.h"
+#include "../net/ea/protocol.h"
+#endif
#include "../resources/iteminfo.h"
#include "../resources/itemdb.h"
+#include "../utils/dtor.h"
#include "../utils/gettext.h"
#include "../utils/strprintf.h"
#include "../utils/stringutils.h"
+#ifdef TMWSERV_SUPPORT
+ChatWindow::ChatWindow():
+ Window("Chat"),
+#else
ChatWindow::ChatWindow(Network * network):
-Window(""), mNetwork(network), mTmpVisible(false)
+ Window(""), mNetwork(network),
+#endif
+ mTmpVisible(false)
{
setWindowName("Chat");
@@ -64,18 +83,21 @@ Window(""), mNetwork(network), mTmpVisible(false)
mChatInput->setActionEventId("chatinput");
mChatInput->addActionListener(this);
- mTextOutput = new BrowserBox(BrowserBox::AUTO_WRAP);
- mTextOutput->setOpaque(false);
- mTextOutput->setMaxRow((int) config.getValue("ChatLogLength", 0));
- mTextOutput->setLinkHandler(mItemLinkHandler);
+ BrowserBox *textOutput = new BrowserBox(BrowserBox::AUTO_WRAP);
+ textOutput->setOpaque(false);
+ textOutput->setMaxRow((int) config.getValue("ChatLogLength", 0));
+ textOutput->setLinkHandler(mItemLinkHandler);
- mScrollArea = new ScrollArea(mTextOutput);
- mScrollArea->setScrollPolicy(gcn::ScrollArea::SHOW_NEVER,
+ ScrollArea *scrollArea = new ScrollArea(textOutput);
+ scrollArea->setScrollPolicy(gcn::ScrollArea::SHOW_NEVER,
gcn::ScrollArea::SHOW_ALWAYS);
- mScrollArea->setScrollAmount(0, 1);
- mScrollArea->setOpaque(false);
+ scrollArea->setScrollAmount(0, 1);
+ scrollArea->setOpaque(false);
+
+ mChatTabs = new TabbedArea();
+ mChatTabs->addTab("General", scrollArea);
- place(0, 0, mScrollArea, 5, 5).setPadding(0);
+ place(0, 0, mChatTabs, 5, 5).setPadding(0);
place(0, 5, mChatInput, 5).setPadding(1);
Layout &layout = getLayout();
@@ -88,6 +110,7 @@ Window(""), mNetwork(network), mTmpVisible(false)
mChatInput->addKeyListener(this);
mCurHist = mHistory.end();
+#ifdef EATHENA_SUPPORT
// Read the party prefix
std::string partyPrefix = config.getValue("PartyPrefix", "$");
mPartyPrefix = (partyPrefix.empty() ? '$' : partyPrefix.at(0));
@@ -99,19 +122,75 @@ Window(""), mNetwork(network), mTmpVisible(false)
// run the @assert command for the player again. Convenience for GMs.
if (config.getValue(player_node->getName() + "GMassert", 0))
chatSend(player_node->getName(), "@assert");
+#endif
}
ChatWindow::~ChatWindow()
{
+#ifdef EATHENA_SUPPORT
char partyPrefix[2] = ".";
*partyPrefix = mPartyPrefix;
config.setValue("PartyPrefix", partyPrefix);
config.setValue("ReturnToggles", mReturnToggles ? "1" : "0");
delete mRecorder;
+#endif
+}
+
+void ChatWindow::widgetResized(const gcn::Event &event)
+{
+ Window::widgetResized(event);
+
+ const gcn::Rectangle area = getChildrenArea();
+
+ mChatInput->setPosition(mChatInput->getFrameSize(),
+ area.height - mChatInput->getHeight() -
+ mChatInput->getFrameSize());
+ mChatInput->setWidth(area.width - 2 * mChatInput->getFrameSize());
+
+ mChatTabs->setWidth(area.width - 2 * mChatTabs->getFrameSize());
+ mChatTabs->setHeight(area.height - 2 * mChatTabs->getFrameSize());
+
+ const std::string &channelName = getFocused();
+ ChannelMap::const_iterator chan = mChannels.find(channelName);
+ if (chan != mChannels.end()) {
+ ScrollArea *scroll = chan->second.scroll;
+ scroll->setWidth(area.width - 2 * scroll->getFrameSize());
+ scroll->setHeight(area.height - 2 * scroll->getFrameSize() -
+ mChatInput->getHeight() - 5);
+ scroll->logic();
+ }
+}
+
+void ChatWindow::logic()
+{
+ Window::logic();
+
+ const gcn::Rectangle area = getChildrenArea();
+
+ const std::string &channelName = getFocused();
+ ChannelMap::const_iterator chan = mChannels.find(channelName);
+ if (chan != mChannels.end()) {
+ ScrollArea *scroll = chan->second.scroll;
+ scroll->setWidth(area.width - 2 * scroll->getFrameSize());
+ scroll->setHeight(area.height - 2 * scroll->getFrameSize() -
+ mChatInput->getHeight() - 5);
+ scroll->logic();
+ }
}
-void ChatWindow::chatLog(std::string line, int own, bool ignoreRecord)
+void ChatWindow::chatLog(std::string line, int own, std::string channelName,
+ bool ignoreRecord)
{
+ if(channelName.empty())
+ channelName = getFocused();
+
+ ChannelMap::const_iterator chan = mChannels.find(channelName);
+ if (chan == mChannels.end())
+ return;
+
+ BrowserBox * const output = chan->second.browser;
+ ScrollArea * const scroll = chan->second.scroll;
+
// Trim whitespace
trim(line);
@@ -180,10 +259,17 @@ void ChatWindow::chatLog(std::string line, int own, bool ignoreRecord)
tmp.text = line;
lineColor = "##S";
break;
+ case BY_CHANNEL:
+ tmp.nick = "";
+ // TODO: Use a predefined color
+ lineColor = "##2"; // Equiv. to BrowserBox::GREEN
+ break;
+#ifdef EATHENA_SUPPORT
case BY_PARTY:
tmp.nick += CAT_NORMAL;
lineColor = "##P";
break;
+#endif
case ACT_WHISPER:
tmp.nick = strprintf(_("%s whispers:"), tmp.nick.c_str());
tmp.nick += " ";
@@ -206,10 +292,12 @@ void ChatWindow::chatLog(std::string line, int own, bool ignoreRecord)
lineColor = "##S";
}
+#ifdef EATHENA_SUPPORT
if (tmp.nick.empty() && tmp.text.substr(0, 17) == "Visible GM status")
{
player_node->setGM();
}
+#endif
// Get the current system time
time_t t;
@@ -228,25 +316,38 @@ void ChatWindow::chatLog(std::string line, int own, bool ignoreRecord)
// We look if the Vertical Scroll Bar is set at the max before
// adding a row, otherwise the max will always be a row higher
// at comparison.
- if (mScrollArea->getVerticalScrollAmount() ==
- mScrollArea->getVerticalMaxScroll())
+ if (scroll->getVerticalScrollAmount() >= scroll->getVerticalMaxScroll())
{
- mTextOutput->addRow(line);
- mScrollArea->setVerticalScrollAmount(mScrollArea->
- getVerticalMaxScroll());
+ output->addRow(line);
+ scroll->setVerticalScrollAmount(scroll->getVerticalMaxScroll());
}
else
{
- mTextOutput->addRow(line);
+ output->addRow(line);
}
+ scroll->logic();
mRecorder->record(line.substr(3));
}
+#ifdef EATHENA_SUPPORT
void ChatWindow::chatLog(CHATSKILL act)
{
chatLog(const_msg(act), BY_SERVER);
}
+#endif
+
+const std::string &ChatWindow::getFocused() const
+{
+ return mChatTabs->getSelectedTab()->getCaption();
+}
+
+void ChatWindow::clearTab(const std::string &tab)
+{
+ ChannelMap::const_iterator chan = mChannels.find(tab);
+ if (chan != mChannels.end())
+ chan->second.browser->clearRows();
+}
void ChatWindow::action(const gcn::ActionEvent &event)
{
@@ -265,7 +366,11 @@ void ChatWindow::action(const gcn::ActionEvent &event)
mCurHist = mHistory.end();
// Send the message to the server
+#ifdef TMWSERV_SUPPORT
+ chatSend(message);
+#else
chatSend(player_node->getName(), message);
+#endif
// Clear the text from the chat input
mChatInput->setText("");
@@ -343,6 +448,8 @@ void ChatWindow::whisper(const std::string &nick, std::string msg)
if (tempNick.compare(playerName) == 0 || msg.empty())
return;
+ // TODO: Implement whispering on tmwserv
+#ifdef EATHENA_SUPPORT
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_CHAT_WHISPER);
outMsg.writeInt16(msg.length() + 28);
@@ -352,8 +459,123 @@ void ChatWindow::whisper(const std::string &nick, std::string msg)
chatLog(strprintf(_("Whispering to %s: %s"),
recvnick.c_str(), msg.c_str()),
BY_PLAYER);
+#endif
+}
+
+#ifdef TMWSERV_SUPPORT
+
+void ChatWindow::chatSend(std::string &msg)
+{
+ if (msg.empty()) return;
+
+ // check for item link
+ std::string::size_type start = msg.find('[');
+ if (start != std::string::npos && msg[start+1] != '@')
+ {
+ std::string::size_type end = msg.find(']', start);
+ if (end != std::string::npos)
+ {
+ std::string temp = msg.substr(start+1, end-1);
+ ItemInfo itemInfo = ItemDB::get(temp);
+ msg.insert(end, "@@");
+ msg.insert(start+1, "|");
+ msg.insert(start+1, toString(itemInfo.getId()));
+ msg.insert(start+1, "@@");
+
+ }
+ }
+
+
+ // Prepare ordinary message
+ if (msg[0] != '/')
+ {
+ if (getFocused() == "General")
+ {
+ Net::GameServer::Player::say(msg);
+ }
+ else
+ {
+ Channel *channel = channelManager->findByName(getFocused());
+ if (channel)
+ {
+ Net::ChatServer::chat(channel->getId(), msg);
+ }
+ }
+ }
+ else
+ {
+ commandHandler->handleCommand(std::string(msg, 1));
+ }
+}
+
+void ChatWindow::removeChannel(short channelId)
+{
+ removeChannel(channelManager->findById(channelId));
+}
+
+void ChatWindow::removeChannel(const std::string &channelName)
+{
+ removeChannel(channelManager->findByName(channelName));
+}
+
+void ChatWindow::removeChannel(Channel *channel)
+{
+ if (channel)
+ {
+ Tab *tab = mChatTabs->getTab(channel->getName());
+ if (!tab)
+ return;
+ clearTab(channel->getName());
+ mChatTabs->removeTab(tab);
+ mChannels.erase(channel->getName());
+ channelManager->removeChannel(channel);
+
+ logic();
+ }
+}
+
+void ChatWindow::createNewChannelTab(const std::string &channelName)
+{
+ // Create new channel
+ BrowserBox *textOutput = new BrowserBox(BrowserBox::AUTO_WRAP);
+ textOutput->setOpaque(false);
+ textOutput->disableLinksAndUserColors();
+ textOutput->setMaxRow((int) config.getValue("ChatLogLength", 0));
+ ScrollArea *scrollArea = new ScrollArea(textOutput);
+ scrollArea->setPosition(scrollArea->getFrameSize(), scrollArea->getFrameSize());
+ scrollArea->setScrollPolicy(gcn::ScrollArea::SHOW_NEVER, gcn::ScrollArea::SHOW_ALWAYS);
+ scrollArea->setOpaque(false);
+ scrollArea->setWidth(getChildrenArea().width - 2 * scrollArea->getFrameSize());
+ scrollArea->setHeight(getChildrenArea().height - 2 * scrollArea->getFrameSize() -
+ mChatInput->getHeight() - 5);
+ scrollArea->logic();
+ textOutput->setWidth(scrollArea->getChildrenArea().width);
+ textOutput->setHeight(scrollArea->getChildrenArea().height);
+
+ // Add channel to the tabbed area
+ mChatTabs->addTab(channelName, scrollArea);
+ mChannels.insert(
+ std::make_pair(channelName, ChatArea(textOutput, scrollArea)));
+
+ // Update UI
+ logic();
+}
+
+void ChatWindow::sendToChannel(short channelId,
+ const std::string &user,
+ const std::string &msg)
+{
+ Channel *channel = channelManager->findById(channelId);
+ if (channel)
+ {
+ std::string channelName = channel->getName();
+ chatLog(user + ": " + msg, user == player_node->getName() ? BY_PLAYER : BY_OTHER, channelName);
+ mChatTabs->getTab(channelName)->setHighlighted(true);
+ }
}
+#else
+
void ChatWindow::chatSend(const std::string &nick, std::string msg)
{
/* Some messages are managed client side, while others
@@ -488,7 +710,7 @@ void ChatWindow::chatSend(const std::string &nick, std::string msg)
outMsg.writeInt16(0x00c1);
}
else if (command == "clear")
- mTextOutput->clearRows();
+ clearTab(getFocused());
else if (command == "whisper" || command == "msg" || command == "w")
whisper(nick, msg);
else if (command == "record")
@@ -608,7 +830,7 @@ void ChatWindow::chatSend(const std::string &nick, std::string msg)
mRecorder->record(timeStr.str() + _("Present: ") + response + ".");
- chatLog(_("Attendance written to record log."), BY_SERVER, true);
+ chatLog(_("Attendance written to record log."), BY_SERVER, std::string(), true);
}
else
{
@@ -712,16 +934,25 @@ std::string ChatWindow::const_msg(CHATSKILL act)
return msg;
}
+#endif
+
void ChatWindow::scroll(int amount)
{
if (!isVisible())
return;
- int range = mScrollArea->getHeight() / 8 * amount;
+ ChannelMap::const_iterator chan = mChannels.find(getFocused());
+ if (chan == mChannels.end())
+ return;
+
+ BrowserBox *browser = chan->second.browser;
+ ScrollArea *scroll = chan->second.scroll;
+
+ int range = scroll->getHeight() / 8 * amount;
gcn::Rectangle scr;
- scr.y = mScrollArea->getVerticalScrollAmount() + range;
+ scr.y = scroll->getVerticalScrollAmount() + range;
scr.height = abs(range);
- mTextOutput->showPart(scr);
+ browser->showPart(scr);
}
void ChatWindow::keyPressed(gcn::KeyEvent &event)
@@ -774,10 +1005,10 @@ void ChatWindow::setVisible(bool isVisible)
* For whatever reason, if setVisible is called, the mTmpVisible effect
* should be disabled.
*/
-
mTmpVisible = false;
}
+#ifdef EATHENA_SUPPORT
void ChatWindow::party(const std::string & command, const std::string & rest)
{
if (command == "prefix")
@@ -809,6 +1040,7 @@ void ChatWindow::party(const std::string & command, const std::string & rest)
else
mParty->respond(command, rest);
}
+#endif
void ChatWindow::help(const std::string & msg1, const std::string & msg2)
{
@@ -861,10 +1093,12 @@ void ChatWindow::help(const std::string & msg1, const std::string & msg2)
chatLog(_("This command tell others you are (doing) <msg>."),
BY_SERVER);
}
+#ifdef EATHENA_SUPPORT
else if (msg1 == "party")
{
mParty->help(msg2);
}
+#endif
else if (msg1 == "present")
{
chatLog(_("Command: /present"), BY_SERVER);
@@ -921,3 +1155,9 @@ void ChatWindow::help(const std::string & msg1, const std::string & msg2)
chatLog(_("Type /help for a list of commands."), BY_SERVER);
}
}
+
+bool ChatWindow::tabExists(const std::string &tabName)
+{
+ Tab *tab = mChatTabs->getTab(tabName);
+ return tab != 0;
+}
diff --git a/src/gui/chat.h b/src/gui/chat.h
index 2fadb014..bbca76ad 100644
--- a/src/gui/chat.h
+++ b/src/gui/chat.h
@@ -24,6 +24,7 @@
#include <list>
#include <string>
+#include <map>
#include <guichan/actionlistener.hpp>
#include <guichan/keylistener.hpp>
@@ -31,22 +32,30 @@
#include "window.h"
class BrowserBox;
-class Network;
+class Channel;
class Recorder;
-class Party;
class ScrollArea;
+class TabbedArea;
class ItemLinkHandler;
+#ifdef EATHENA_SUPPORT
+class Network;
+class Party;
+#endif
-#define BY_GM 0 // those should be self-explanatory =)
-#define BY_PLAYER 1
-#define BY_OTHER 2
-#define BY_SERVER 3
-#define BY_PARTY 4
-
-#define ACT_WHISPER 5 // getting whispered at
-#define ACT_IS 6 // equivalent to "/me" on IRC
-
-#define BY_LOGGER 7
+enum
+{
+ BY_GM,
+#ifdef EATHENA_SUPPORT
+ BY_PARTY,
+#endif
+ BY_PLAYER,
+ BY_OTHER,
+ BY_SERVER,
+ BY_CHANNEL,
+ ACT_WHISPER, // getting whispered at
+ ACT_IS, // equivalent to "/me" on IRC
+ BY_LOGGER
+};
/**
* gets in between usernick and message text depending on
@@ -56,6 +65,7 @@ class ItemLinkHandler;
#define CAT_IS ""
#define CAT_WHISPER " whispers: "
+#ifdef EATHENA_SUPPORT
/** job dependend identifiers (?) */
#define SKILL_BASIC 0x0001
#define SKILL_WARP 0x001b
@@ -88,8 +98,6 @@ class ItemLinkHandler;
/** should always be zero if failed */
#define SKILL_FAILED 0x00
-#define DEFAULT_CHAT_WINDOW_SCROLL 7 // 1 means `1/8th of the window size'.
-
struct CHATSKILL
{
short skill;
@@ -98,20 +106,28 @@ struct CHATSKILL
char success;
char reason;
};
+#endif
+
+#define DEFAULT_CHAT_WINDOW_SCROLL 7 // 1 means `1/8th of the window size'.
/**
* The chat window.
*
* \ingroup Interface
*/
-class ChatWindow : public Window, public gcn::ActionListener,
+class ChatWindow : public Window,
+ public gcn::ActionListener,
public gcn::KeyListener
{
public:
/**
* Constructor.
*/
+#ifdef TMWSERV_SUPPORT
+ ChatWindow();
+#else
ChatWindow(Network *network);
+#endif
/**
* Destructor: used to write back values to the config file
@@ -119,17 +135,41 @@ class ChatWindow : public Window, public gcn::ActionListener,
~ChatWindow();
/**
+ * Called when the widget changes size. Used for adapting the size of
+ * the tabbed area.
+ */
+ void widgetResized(const gcn::Event &event);
+
+ void logic();
+
+ /**
* Adds a line of text to our message list. Parameters:
*
* @param line Text message.
* @parem own Type of message (usually the owner-type).
+ * @param channelName which channel to send the message to.
*/
- void chatLog(std::string line, int own, bool ignoreRecord = false);
+ void chatLog(std::string line,
+ int own = BY_SERVER,
+ std::string channelName = "",
+ bool ignoreRecord = false);
+#ifdef EATHENA_SUPPORT
/**
* Calls original chat_log() after processing the packet.
*/
void chatLog(CHATSKILL);
+#endif
+
+ /**
+ * Gets the focused tab's name
+ */
+ const std::string& getFocused() const;
+
+ /**
+ * Clear the tab with the given name
+ */
+ void clearTab(const std::string &tab);
/**
* Performs action.
@@ -146,6 +186,32 @@ class ChatWindow : public Window, public gcn::ActionListener,
*/
bool isInputFocused();
+#ifdef TMWSERV_SUPPORT
+ /**
+ * Determines whether the message is a command or message, then
+ * sends the given message to the game server to be said, or to the
+ * command handler
+ *
+ * @param msg The message text which is to be sent.
+ *
+ */
+ void chatSend(std::string &msg);
+
+ /** Called to remove the channel from the channel manager */
+ void removeChannel(short channelId);
+
+ void removeChannel(const std::string &channelName);
+
+ void removeChannel(Channel *channel);
+
+ /** Called to create a new channel tab */
+ void createNewChannelTab(const std::string &channelName);
+
+ /** Called to output text to a specific channel */
+ void sendToChannel(short channel,
+ const std::string &user,
+ const std::string &msg);
+#else
/**
* Determines whether to send a command or an ordinary message, then
* contructs packets & sends them.
@@ -171,6 +237,7 @@ class ChatWindow : public Window, public gcn::ActionListener,
* chatlog.chat_send("Zaeiru", "Hello to all users on the screen!");
*/
void chatSend(const std::string &nick, std::string msg);
+#endif
/** Called when key is pressed */
void keyPressed(gcn::KeyEvent &event);
@@ -184,15 +251,19 @@ class ChatWindow : public Window, public gcn::ActionListener,
/** Override to reset mTmpVisible */
void setVisible(bool visible);
- /**
- * Scrolls the chat window
- *
- * @param amount direction and amount to scroll. Negative numbers scroll
- * up, positive numbers scroll down. The absolute amount indicates the
- * amount of 1/8ths of chat window real estate that should be scrolled.
- */
+ /** Check if tab with that name already exists */
+ bool tabExists(const std::string &tabName);
+
+ /**
+ * Scrolls the chat window
+ *
+ * @param amount direction and amount to scroll. Negative numbers scroll
+ * up, positive numbers scroll down. The absolute amount indicates the
+ * amount of 1/8ths of chat window real estate that should be scrolled.
+ */
void scroll(int amount);
+#ifdef EATHENA_SUPPORT
/**
* party implements the partying chat commands
*
@@ -200,6 +271,7 @@ class ChatWindow : public Window, public gcn::ActionListener,
* @param msg is the remainder of the message
*/
void party(const std::string &command, const std::string &msg);
+#endif
/**
* help implements the /help command
@@ -210,10 +282,14 @@ class ChatWindow : public Window, public gcn::ActionListener,
void help(const std::string &msg1, const std::string &msg2);
private:
-
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
bool mTmpVisible;
+ int mItems;
+ int mItemsKeep;
+
void whisper(const std::string &nick, std::string msg);
/** One item in the chat log */
@@ -224,25 +300,51 @@ class ChatWindow : public Window, public gcn::ActionListener,
int own;
};
+#ifdef EATHENA_SUPPORT
/** Constructs failed messages for actions */
std::string const_msg(CHATSKILL);
+#endif
+
+ /**
+ * A structure combining a BrowserBox with its ScrollArea.
+ */
+ struct ChatArea
+ {
+ ChatArea(BrowserBox *b, ScrollArea *s):
+ browser(b), scroll(s)
+ {}
+
+ BrowserBox *browser;
+ ScrollArea *scroll;
+ };
+
+ /** Used for showing item popup on clicking links **/
+ ItemLinkHandler *mItemLinkHandler;
+
+ /** Tabbed area for holding each channel. */
+ TabbedArea *mChatTabs;
+
+ /** Input box for typing chat messages. */
+ gcn::TextField *mChatInput;
+
+ typedef std::map<const std::string, ChatArea> ChannelMap;
+ /** Map each tab to its browser and scroll area. */
+ ChannelMap mChannels;
- gcn::TextField *mChatInput; /**< Input box for typing chat messages */
- BrowserBox *mTextOutput; /**< Text box for displaying chat history */
- ScrollArea *mScrollArea; /**< Scroll area around text output */
- ItemLinkHandler *mItemLinkHandler; /** Used for showing item popup on
- clicking links **/
typedef std::list<std::string> History;
typedef History::iterator HistoryIterator;
- History mHistory; /**< Command history */
- HistoryIterator mCurHist; /**< History iterator */
+ History mHistory; /**< Command history. */
+ HistoryIterator mCurHist; /**< History iterator. */
Recorder *mRecorder; /**< Recording class */
- char mPartyPrefix; /**< Messages beginning with the prefix are sent to
- the party */
bool mReturnToggles; /**< Marks whether <Return> toggles the chat log
or not */
+#ifdef EATHENA_SUPPORT
+ char mPartyPrefix; /**< Messages beginning with the prefix are sent to
+ the party */
Party *mParty;
+#endif
};
+
extern ChatWindow *chatWindow;
#endif
diff --git a/src/gui/chatinput.h b/src/gui/chatinput.h
index a4a50502..3bc16928 100644
--- a/src/gui/chatinput.h
+++ b/src/gui/chatinput.h
@@ -26,6 +26,8 @@
#include "textfield.h"
+#include <guichan/focuslistener.hpp>
+
/**
* The chat input hides when it loses focus. It is also invisible by default.
*/
diff --git a/src/gui/connection.cpp b/src/gui/connection.cpp
index a69698e9..fbf127de 100644
--- a/src/gui/connection.cpp
+++ b/src/gui/connection.cpp
@@ -19,8 +19,6 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include <guichan/actionlistener.hpp>
-
#include <guichan/widgets/label.hpp>
#include "button.h"
@@ -28,23 +26,16 @@
#include "progressbar.h"
#include "../main.h"
+#include "../log.h"
#include "../utils/gettext.h"
-namespace
-{
- struct ConnectionActionListener : public gcn::ActionListener
- {
- void action(const gcn::ActionEvent &event) { state = EXIT_STATE; }
- } listener;
-}
-
-ConnectionDialog::ConnectionDialog():
- Window("Info"), mProgress(0)
+ConnectionDialog::ConnectionDialog(int previousState):
+ Window("Info"), mProgress(0), mPreviousState(previousState)
{
setContentSize(200, 100);
- Button *cancelButton = new Button(_("Cancel"), "cancelButton", &listener);
+ Button *cancelButton = new Button(_("Cancel"), "cancelButton", this);
mProgressBar = new ProgressBar(0.0, 200 - 10, 20, 128, 128, 128);
gcn::Label *label = new gcn::Label(_("Connecting..."));
@@ -60,6 +51,12 @@ ConnectionDialog::ConnectionDialog():
setVisible(true);
}
+void ConnectionDialog::action(gcn::ActionEvent const &)
+{
+ logger->log("Cancel pressed");
+ state = mPreviousState;
+}
+
void ConnectionDialog::logic()
{
mProgress += 0.005f;
diff --git a/src/gui/connection.h b/src/gui/connection.h
index 3caa611f..0e347266 100644
--- a/src/gui/connection.h
+++ b/src/gui/connection.h
@@ -22,6 +22,8 @@
#ifndef CONNECTION_H
#define CONNECTION_H
+#include <guichan/actionlistener.hpp>
+
#include "window.h"
class ProgressBar;
@@ -31,7 +33,7 @@ class ProgressBar;
*
* \ingroup Interface
*/
-class ConnectionDialog : public Window
+class ConnectionDialog : public Window, gcn::ActionListener
{
public:
/**
@@ -39,13 +41,20 @@ class ConnectionDialog : public Window
*
* @see Window::Window
*/
- ConnectionDialog();
+ ConnectionDialog(int previousState);
+
+ /**
+ * Called when the user presses Cancel. Restores the global state to
+ * the previous one.
+ */
+ void action(gcn::ActionEvent const &);
void logic();
private:
ProgressBar *mProgressBar;
float mProgress;
+ int mPreviousState;
};
#endif
diff --git a/src/gui/equipmentwindow.cpp b/src/gui/equipmentwindow.cpp
index 02a0729b..a44ae3ec 100644
--- a/src/gui/equipmentwindow.cpp
+++ b/src/gui/equipmentwindow.cpp
@@ -36,6 +36,7 @@
#include "../item.h"
#include "../localplayer.h"
+#include "../resources/image.h"
#include "../resources/iteminfo.h"
#include "../resources/resourcemanager.h"
@@ -57,8 +58,16 @@ static const int boxPosition[][2] = {
{129, 78} // EQUIP_AMMO_SLOT
};
+#ifdef TMWSERV_SUPPORT
+EquipmentWindow::EquipmentWindow(Equipment *equipment):
+#else
EquipmentWindow::EquipmentWindow():
+#endif
Window(_("Equipment")),
+#ifdef TMWSERV_SUPPORT
+ mEquipment(equipment),
+#endif
+ mBackground(NULL),
mSelected(-1)
{
mItemPopup = new ItemPopup;
@@ -81,19 +90,31 @@ EquipmentWindow::EquipmentWindow():
add(mPlayerBox);
add(mUnequip);
+#ifdef TMWSERV_SUPPORT
+ for (int i = 0; i < EQUIPMENT_SIZE; i++)
+#else
for (int i = EQUIP_LEGS_SLOT; i < EQUIP_VECTOREND; i++)
+#endif
{
mEquipBox[i].posX = boxPosition[i][0] + getPadding();
mEquipBox[i].posY = boxPosition[i][1] + getTitleBarHeight();
}
+ ResourceManager *resman = ResourceManager::getInstance();
+ mBackground = resman->getImage("graphics/gui/equip_bg.png");
+ mBackground->setAlpha(0.3);
+
+#ifdef EATHENA_SUPPORT
mEquipment = player_node->mEquipment.get();
mInventory = player_node->getInventory();
+#endif
}
EquipmentWindow::~EquipmentWindow()
{
+ mBackground->decRef();
delete mItemPopup;
+ delete mUnequip;
}
void EquipmentWindow::draw(gcn::Graphics *graphics)
@@ -101,22 +122,29 @@ void EquipmentWindow::draw(gcn::Graphics *graphics)
// Draw window graphics
Window::draw(graphics);
- Item* item;
-
Graphics *g = static_cast<Graphics*>(graphics);
Window::drawChildren(graphics);
+#ifdef TMWSERV_SUPPORT
+ for (int i = 0; i < EQUIPMENT_SIZE; i++)
+#else
for (int i = EQUIP_LEGS_SLOT; i < EQUIP_VECTOREND; i++)
+#endif
{
- item = (i != EQUIP_AMMO_SLOT) ?
+#ifdef TMWSERV_SUPPORT
+ Item *item = mEquipment->getEquipment(i);
+#else
+ Item *item = (i != EQUIP_AMMO_SLOT) ?
mInventory->getItem(mEquipment->getEquipment(i)) :
mInventory->getItem(mEquipment->getArrows());
+#endif
if (item)
{
// Draw Item.
- Image* image = item->getImage();
+ Image *image = item->getImage();
g->drawImage(image, mEquipBox[i].posX, mEquipBox[i].posY);
+#ifdef EATHENA_SUPPORT
if (i == EQUIP_AMMO_SLOT)
{
g->setColor(gcn::Color(0, 0, 0));
@@ -125,6 +153,7 @@ void EquipmentWindow::draw(gcn::Graphics *graphics)
mEquipBox[i].posY - getFont()->getHeight(),
gcn::Graphics::CENTER);
}
+#endif
}
if (i == mSelected)
@@ -148,26 +177,38 @@ void EquipmentWindow::action(const gcn::ActionEvent &event)
{
if (event.getId() == "unequip" && mSelected > -1)
{
+#ifdef TMWSERV_SUPPORT
+ player_node->unequipItem(mSelected);
+#else
Item* item = (mSelected != EQUIP_AMMO_SLOT) ?
mInventory->getItem(mEquipment->getEquipment(mSelected)) :
mInventory->getItem(mEquipment->getArrows());
player_node->unequipItem(item);
+#endif
mSelected = -1;
}
}
Item* EquipmentWindow::getItem(int x, int y) const
{
+#ifdef TMWSERV_SUPPORT
+ for (int i = 0; i < EQUIPMENT_SIZE; i++)
+#else
for (int i = EQUIP_LEGS_SLOT; i < EQUIP_VECTOREND; i++)
+#endif
{
gcn::Rectangle tRect(mEquipBox[i].posX, mEquipBox[i].posY,
BOX_WIDTH, BOX_HEIGHT);
if (tRect.isPointInRect(x, y))
{
+#ifdef TMWSERV_SUPPORT
+ return mEquipment->getEquipment(i);
+#else
return (i != EQUIP_AMMO_SLOT) ?
mInventory->getItem(mEquipment->getEquipment(i)) :
mInventory->getItem(mEquipment->getArrows());
+#endif
}
}
return NULL;
@@ -185,11 +226,19 @@ void EquipmentWindow::mousePressed(gcn::MouseEvent& mouseEvent)
if (mouseEvent.getButton() == gcn::MouseEvent::LEFT)
{
// Checks if any of the presses were in the equip boxes.
+#ifdef TMWSERV_SUPPORT
+ for (int i = 0; i < EQUIPMENT_SIZE; i++)
+#else
for (int i = EQUIP_LEGS_SLOT; i < EQUIP_VECTOREND; i++)
+#endif
{
+#ifdef TMWSERV_SUPPORT
+ item = mEquipment->getEquipment(i);
+#else
item = (i != EQUIP_AMMO_SLOT) ?
mInventory->getItem(mEquipment->getEquipment(i)) :
mInventory->getItem(mEquipment->getArrows());
+#endif
gcn::Rectangle tRect(mEquipBox[i].posX, mEquipBox[i].posY,
BOX_WIDTH, BOX_HEIGHT);
diff --git a/src/gui/equipmentwindow.h b/src/gui/equipmentwindow.h
index 24438477..7f7150ff 100644
--- a/src/gui/equipmentwindow.h
+++ b/src/gui/equipmentwindow.h
@@ -27,6 +27,7 @@
#include "window.h"
class Equipment;
+class Image;
class Inventory;
class Item;
class ItemPopup;
@@ -52,7 +53,11 @@ class EquipmentWindow : public Window, public gcn::ActionListener
/**
* Constructor.
*/
+#ifdef TMWSERV_SUPPORT
+ EquipmentWindow(Equipment *equipment);
+#else
EquipmentWindow();
+#endif
/**
* Destructor.
@@ -68,6 +73,23 @@ class EquipmentWindow : public Window, public gcn::ActionListener
void mousePressed(gcn::MouseEvent& mouseEvent);
+#ifdef TMWSERV_SUPPORT
+ enum{
+ // Equipment rules:
+ EQUIP_TORSO_SLOT = 0,
+ EQUIP_ARMS_SLOT = 1,
+ EQUIP_HEAD_SLOT = 2,
+ EQUIP_LEGS_SLOT = 3,
+ EQUIP_FEET_SLOT = 4,
+ EQUIP_RING1_SLOT = 5,
+ EQUIP_RING2_SLOT = 6,
+ EQUIP_NECKLACE_SLOT = 7,
+ EQUIP_FIGHT1_SLOT = 8,
+ EQUIP_FIGHT2_SLOT = 9,
+ EQUIP_PROJECTILE_SLOT = 10,
+ EQUIP_VECTOREND
+ };
+#else
enum {
// Equipment rules:
EQUIP_LEGS_SLOT = 0,
@@ -83,7 +105,7 @@ class EquipmentWindow : public Window, public gcn::ActionListener
EQUIP_AMMO_SLOT,
EQUIP_VECTOREND
};
-
+#endif
private:
void mouseExited(gcn::MouseEvent &event);
@@ -92,8 +114,11 @@ class EquipmentWindow : public Window, public gcn::ActionListener
Item* getItem(int x, int y) const;
Equipment *mEquipment;
+#ifdef EATHENA_SUPPORT
Inventory *mInventory;
+#endif
gcn::Button *mUnequip; /**< Button for unequipping. */
+ Image *mBackground; /**< Background Image. */
EquipBox mEquipBox[EQUIP_VECTOREND]; /**< Equipment Boxes. */
ItemPopup *mItemPopup;
diff --git a/src/gui/gui.cpp b/src/gui/gui.cpp
index 9b9e74f4..1ef0219a 100644
--- a/src/gui/gui.cpp
+++ b/src/gui/gui.cpp
@@ -107,7 +107,8 @@ Gui::Gui(Graphics *graphics):
ResourceManager *resman = ResourceManager::getInstance();
// Set global font
- std::string path = resman->getPath("fonts/dejavusans.ttf");
+ std::string path = resman->getPath(
+ branding.getValue("font", "fonts/dejavusans.ttf"));
try
{
const int fontSize = (int)config.getValue("fontSize", 11);
@@ -120,7 +121,8 @@ Gui::Gui(Graphics *graphics):
}
// Set bold font
- path = resman->getPath("fonts/dejavusans-bold.ttf");
+ path = resman->getPath(
+ branding.getValue("boldFont", "fonts/dejavusans.ttf"));
try
{
const int fontSize = (int)config.getValue("fontSize", 11);
diff --git a/src/gui/guildlistbox.cpp b/src/gui/guildlistbox.cpp
new file mode 100644
index 00000000..556df3fe
--- /dev/null
+++ b/src/gui/guildlistbox.cpp
@@ -0,0 +1,130 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "guildlistbox.h"
+
+#include "../graphics.h"
+
+#include "../resources/image.h"
+#include "../resources/resourcemanager.h"
+
+#include <guichan/font.hpp>
+
+GuildListBox::GuildListBox():
+ ListBox(NULL)
+{
+ onlineIcon = ResourceManager::getInstance()->getImage("graphics/gui/circle-green.png");
+ offlineIcon = ResourceManager::getInstance()->getImage("graphics/gui/circle-gray.png");
+}
+
+void GuildListBox::draw(gcn::Graphics *gcnGraphics)
+{
+ if (!mListModel)
+ return;
+
+ Graphics *graphics = static_cast<Graphics*>(gcnGraphics);
+
+ graphics->setColor(gcn::Color(110, 160, 255));
+ graphics->setFont(getFont());
+
+ int fontHeight = getFont()->getHeight();
+
+ // Draw rectangle below the selected list element
+ if (mSelected >= 0) {
+ graphics->fillRectangle(gcn::Rectangle(0, fontHeight * mSelected,
+ getWidth(), fontHeight));
+ }
+
+ // Draw the list elements
+ for (int i = 0, y = 0;
+ i < mListModel->getNumberOfElements();
+ ++i, y += fontHeight)
+ {
+ // Draw online status
+ bool online = false;
+ UserMap::iterator itr = mUsers.find(mListModel->getElementAt(i));
+ if (itr != mUsers.end())
+ {
+ online = itr->second;
+ }
+ Image *icon = online ? onlineIcon : offlineIcon;
+ if (icon)
+ graphics->drawImage(icon, 1, y);
+ // Draw Name
+ graphics->setColor(gcn::Color(0, 0, 0));
+ graphics->drawText(mListModel->getElementAt(i), 33, y);
+ }
+}
+/*
+void GuildListBox::setSelected(int selected)
+{
+ if (!mListModel)
+ {
+ mSelected = -1;
+ }
+ else
+ {
+ // Update mSelected with bounds checking
+ mSelected = std::min(mListModel->getNumberOfElements() - 1,
+ std::max(-1, selected));
+
+ gcn::Widget *parent;
+ parent = (gcn::Widget*)getParent();
+ if (parent)
+ {
+ gcn::Rectangle scroll;
+ scroll.y = (mSelected < 0) ? 0 : getFont()->getHeight() * mSelected;
+ scroll.height = getFont()->getHeight();
+ parent->showWidgetPart(this, scroll);
+ }
+ }
+
+ distributeValueChangedEvent();
+}
+*/
+void GuildListBox::mousePressed(gcn::MouseEvent &event)
+{
+ if (event.getButton() == gcn::MouseEvent::LEFT)
+ {
+ int y = event.getY();
+ setSelected(y / getFont()->getHeight());
+ distributeActionEvent();
+ }
+ // TODO: Add guild functions, ie private messaging
+ if (event.getButton() == gcn::MouseEvent::RIGHT)
+ {
+ // Show context menu
+ }
+}
+
+void GuildListBox::setOnlineStatus(const std::string &user, bool online)
+{
+ UserMap::iterator itr = mUsers.find(user);
+ if (itr == mUsers.end())
+ {
+ mUsers.insert(std::pair<std::string, bool>(user, online));
+ }
+ else
+ {
+ itr->second = online;
+ }
+ adjustSize();
+}
diff --git a/src/gui/guildlistbox.h b/src/gui/guildlistbox.h
new file mode 100644
index 00000000..cc8e3ce7
--- /dev/null
+++ b/src/gui/guildlistbox.h
@@ -0,0 +1,65 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_GUI_GUILDLISTBOX_H
+#define _TMW_GUI_GUILDLISTBOX_H
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "listbox.h"
+
+class Image;
+
+class GuildListBox : public ListBox
+{
+public:
+ /**
+ * Constructor
+ */
+ GuildListBox();
+
+ /**
+ * Draws the list box.
+ */
+ void draw(gcn::Graphics *gcnGraphics);
+
+ void mousePressed(gcn::MouseEvent &event);
+
+ /**
+ * Sets the index of the selected element.
+ */
+// void setSelected(int selected);
+
+ /**
+ * Set whether a member is online or offline
+ */
+ void setOnlineStatus(const std::string &user, bool online);
+
+private:
+ Image *onlineIcon;
+ Image *offlineIcon;
+ typedef std::map<std::string, bool> UserMap;
+ UserMap mUsers;
+};
+
+#endif
diff --git a/src/gui/guildwindow.cpp b/src/gui/guildwindow.cpp
new file mode 100644
index 00000000..0596c75e
--- /dev/null
+++ b/src/gui/guildwindow.cpp
@@ -0,0 +1,273 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * $$
+ */
+
+#include "guildwindow.h"
+
+#include "button.h"
+#include "chat.h"
+#include "confirm_dialog.h"
+#include "guildlistbox.h"
+#include "scrollarea.h"
+#include "textdialog.h"
+#include "windowcontainer.h"
+
+#include "widgets/layout.h"
+#include "widgets/tabbedarea.h"
+
+#include "../guild.h"
+#include "../log.h"
+#include "../localplayer.h"
+
+#include "../net/chatserver/guild.h"
+#include "../utils/dtor.h"
+#include "../utils/gettext.h"
+
+#include <algorithm>
+
+#include <guichan/widgets/tab.hpp>
+
+GuildWindow::GuildWindow():
+ Window(_("Guild")),
+ mFocus(false)
+{
+ setWindowName("Guild");
+ setCaption(_("Guild"));
+ setResizable(false);
+ setCloseButton(true);
+ setMinWidth(200);
+ setMinHeight(280);
+ setDefaultSize(124, 41, 288, 330);
+
+ // Set button events Id
+ mGuildButton[0] = new Button(_("Create Guild"), "CREATE_GUILD", this);
+ mGuildButton[1] = new Button(_("Invite User"), "INVITE_USER", this);
+ mGuildButton[2] = new Button(_("Quit Guild"), "QUIT_GUILD", this);
+ mGuildButton[1]->setEnabled(false);
+ mGuildButton[2]->setEnabled(false);
+
+ mGuildTabs = new TabbedArea();
+
+ place(0, 0, mGuildButton[0]);
+ place(1, 0, mGuildButton[1]);
+ place(2, 0, mGuildButton[2]);
+ place(0, 1, mGuildTabs);
+ Layout &layout = getLayout();
+ layout.setColWidth(0, 48);
+ layout.setColWidth(1, 65);
+
+ loadWindowState();
+}
+
+GuildWindow::~GuildWindow()
+{
+ delete mGuildTabs;
+}
+
+void GuildWindow::update()
+{
+ updateTab();
+
+ if (mGuildButton[2]->isEnabled() && mGuildTabs->getNumberOfTabs() <= 0)
+ {
+ mGuildButton[2]->setEnabled(false);
+ mGuildButton[1]->setEnabled(false);
+ }
+}
+
+void GuildWindow::draw(gcn::Graphics *g)
+{
+ update();
+
+ Window::draw(g);
+}
+
+void GuildWindow::action(const gcn::ActionEvent &event)
+{
+ const std::string &eventId = event.getId();
+
+ // Stats Part
+ if (eventId == "CREATE_GUILD")
+ {
+ // Set focus so that guild name to be created can be typed.
+ mFocus = true;
+ guildDialog = new TextDialog("Guild Name", "Choose your guild's name", this);
+ guildDialog->setOKButtonActionId("CREATE_GUILD_OK");
+ guildDialog->addActionListener(this);
+ }
+ else if (eventId == "INVITE_USER")
+ {
+ // TODO - Give feedback on whether the invite succeeded
+ mFocus = true;
+ inviteDialog = new TextDialog("Member Invite", "Who would you like to invite?", this);
+ inviteDialog->setOKButtonActionId("INVITE_USER_OK");
+ inviteDialog->addActionListener(this);
+ }
+ else if (eventId == "QUIT_GUILD")
+ {
+ short guild = getSelectedGuild();
+ if (guild)
+ {
+ Net::ChatServer::Guild::quitGuild(guild);
+ chatWindow->chatLog("Guild " + mGuildTabs->getSelectedTab()->getCaption() + " quit", BY_SERVER);
+ }
+ }
+ else if (eventId == "CREATE_GUILD_OK")
+ {
+ std::string name = guildDialog->getText();
+ if(name.size() > 16)
+ {
+ // TODO : State too many characters in input.
+ return;
+ }
+ // Process guild name to be created, and unfocus.
+ Net::ChatServer::Guild::createGuild(name);
+
+ // Defocus dialog
+ mFocus = false;
+ chatWindow->chatLog("Creating Guild called " + name, BY_SERVER);
+ guildDialog->scheduleDelete();
+ }
+ else if (eventId == "INVITE_USER_OK")
+ {
+ std::string name = inviteDialog->getText();
+ short selectedGuild = getSelectedGuild();
+
+ // Process invited user to be created and unfocus.
+ Net::ChatServer::Guild::invitePlayer(name, selectedGuild);
+
+ // Defocus dialog
+ mFocus = false;
+ chatWindow->chatLog("Invited user " + name, BY_SERVER);
+ inviteDialog->scheduleDelete();
+ }
+ else if (eventId == "yes")
+ {
+ logger->log("Sending invitation acceptance.");
+ Net::ChatServer::Guild::acceptInvite(invitedGuild);
+ }
+}
+
+void GuildWindow::newGuildTab(const std::string &guildName)
+{
+ // Create new tab
+ GuildListBox *list = new GuildListBox();
+ list->setListModel(player_node->getGuild(guildName));
+ ScrollArea *sa = new ScrollArea(list);
+ sa->setDimension(gcn::Rectangle(5, 5, 135, 250));
+
+ // Add the listbox to the map
+ mGuildLists.insert(std::pair<std::string, GuildListBox*>(guildName, list));
+
+ mGuildTabs->addTab(guildName, sa);
+ mGuildTabs->setDimension(gcn::Rectangle(28,35,140,250));
+
+ updateTab();
+}
+
+void GuildWindow::updateTab()
+{
+ gcn::Tab *tab = mGuildTabs->getSelectedTab();
+ if (tab)
+ {
+ setTab(tab->getCaption());
+ }
+ mGuildTabs->logic();
+}
+
+void GuildWindow::setTab(const std::string &guildName)
+{
+ // Only enable invite button if user has rights
+ if(player_node->checkInviteRights(guildName))
+ {
+ mGuildButton[1]->setEnabled(true);
+ }
+ else
+ {
+ mGuildButton[1]->setEnabled(false);
+ }
+
+ mGuildButton[2]->setEnabled(true);
+}
+
+bool GuildWindow::isWindowFocused()
+{
+ return mFocus;
+}
+
+short GuildWindow::getSelectedGuild()
+{
+ if (mGuildTabs->getNumberOfTabs() > 0)
+ {
+
+ Guild *guild = player_node->getGuild(mGuildTabs->getSelectedTab()->getCaption());
+
+ if (guild)
+ {
+ return guild->getId();
+ }
+ }
+
+ return 0;
+}
+
+void GuildWindow::openAcceptDialog(const std::string &inviterName,
+ const std::string &guildName)
+{
+ std::string msg = inviterName + " has invited you to join the guild " + guildName;
+ chatWindow->chatLog(msg, BY_SERVER);
+
+ acceptDialog = new ConfirmDialog("Accept Guild Invite", msg, this);
+ acceptDialog->addActionListener(this);
+
+ invitedGuild = guildName;
+}
+
+void GuildWindow::requestMemberList(short guildId)
+{
+ // Get the list of members for displaying in the guild window.
+ Net::ChatServer::Guild::getGuildMembers(guildId);
+}
+
+void GuildWindow::removeTab(int guildId)
+{
+ Guild* guild = player_node->getGuild(guildId);
+ if (guild)
+ {
+ Tab *tab = mGuildTabs->getTab(guild->getName());
+ if (tab)
+ {
+ mGuildTabs->removeTab(tab);
+ }
+ updateTab();
+ }
+ mGuildTabs->logic();
+}
+
+void GuildWindow::setOnline(const std::string &guildName, const std::string &member,
+ bool online)
+{
+ GuildListMap::iterator itr = mGuildLists.find(guildName);
+ if (itr != mGuildLists.end())
+ {
+ itr->second->setOnlineStatus(member, online);
+ }
+}
diff --git a/src/gui/guildwindow.h b/src/gui/guildwindow.h
new file mode 100644
index 00000000..4f6b9cbb
--- /dev/null
+++ b/src/gui/guildwindow.h
@@ -0,0 +1,135 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_GUI_GUILDWINDOW_H
+#define _TMW_GUI_GUILDWINDOW_H
+
+#include <iosfwd>
+#include <map>
+#include <vector>
+
+#include <guichan/actionlistener.hpp>
+#include <guichan/widgets/listbox.hpp>
+
+#include "window.h"
+
+#include "../guichanfwd.h"
+
+class LocalPlayer;
+class TextDialog;
+class ConfirmDialog;
+class GuildListBox;
+class ScrollArea;
+class GCContainer;
+class TabbedArea;
+
+class GuildWindow : public Window, public gcn::ActionListener
+{
+public:
+ /**
+ * Constructor.
+ */
+ GuildWindow();
+
+ /**
+ * Destructor.
+ */
+ ~GuildWindow();
+
+ /**
+ * Called when receiving actions from widget.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ /**
+ * Draw this window.
+ */
+ void draw(gcn::Graphics *graphics);
+
+ /**
+ * Updates this dialog.
+ */
+ void update();
+
+ /**
+ * Create a new tab for a guild list.
+ */
+ void newGuildTab(const std::string &guildName);
+
+ /**
+ * Display guild's member list to active tab
+ */
+ void setTab(const std::string &guildName);
+
+ /**
+ * Update the contents of the active tab
+ */
+ void updateTab();
+
+ /**
+ * Check if the window is in focus.
+ */
+ bool isWindowFocused();
+
+ /**
+ * Create a dialog for accepting an invite
+ */
+ void openAcceptDialog(const std::string &inviterName, const std::string &guildName);
+
+ /**
+ * Request member list
+ */
+ void requestMemberList(short guildId);
+
+ /**
+ * Removes the selected tab
+ */
+ void removeTab(int guildId);
+
+ /**
+ * Set guild member status in userlist
+ */
+ void setOnline(const std::string &guildName, const std::string &member,
+ bool online);
+
+protected:
+ /**
+ * Get selected guild tab
+ * @return Returns selected guild
+ */
+ short getSelectedGuild();
+
+private:
+ gcn::Button *mGuildButton[3];
+ TextDialog *guildDialog;
+ TextDialog *inviteDialog;
+ ConfirmDialog *acceptDialog;
+ TabbedArea *mGuildTabs;
+ ScrollArea *mScrollArea;
+ bool mFocus;
+ std::string invitedGuild;
+ typedef std::map<std::string, GuildListBox*> GuildListMap;
+ GuildListMap mGuildLists;
+};
+
+extern GuildWindow *guildWindow;
+
+#endif
diff --git a/src/gui/icon.cpp b/src/gui/icon.cpp
new file mode 100644
index 00000000..1e352292
--- /dev/null
+++ b/src/gui/icon.cpp
@@ -0,0 +1,58 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "icon.h"
+
+#include "../graphics.h"
+
+#include "../resources/image.h"
+#include "../resources/resourcemanager.h"
+
+Icon::Icon(const std::string &file)
+ : mImage(0)
+{
+ mImage = ResourceManager::getInstance()->getImage(file);
+ setSize(mImage->getWidth(), mImage->getHeight());
+
+}
+
+Icon::Icon(Image *image)
+ : mImage(image)
+{
+ setSize(mImage->getWidth(), mImage->getHeight());
+}
+
+void Icon::setImage(Image *image)
+{
+ mImage = image;
+ setSize(mImage->getWidth(), mImage->getHeight());
+}
+
+void Icon::draw(gcn::Graphics *g)
+{
+ if(mImage)
+ {
+ Graphics *graphics = static_cast<Graphics*>(g);
+ const int x = (getWidth() - mImage->getWidth()) / 2;
+ const int y = (getHeight() - mImage->getHeight()) / 2;
+ graphics->drawImage(mImage, x, y);
+ }
+}
diff --git a/src/gui/icon.h b/src/gui/icon.h
new file mode 100644
index 00000000..9baf1a99
--- /dev/null
+++ b/src/gui/icon.h
@@ -0,0 +1,68 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+#ifndef _TMW_ICON_H
+#define _TMW_ICON_H
+
+#include <guichan/widget.hpp>
+
+class Image;
+
+
+/**
+ * An icon.
+ *
+ * \ingroup GUI
+ */
+class Icon : public gcn::Widget {
+ public:
+ /**
+ * Constructor.
+ */
+ Icon(const std::string &filename);
+
+ /**
+ * Constructor, uses an existing Image.
+ */
+ Icon(Image *image);
+
+ /**
+ * Gets the current Image.
+ */
+ Image* getImage() { return mImage; }
+
+ /**
+ * Sets the image to display.
+ */
+ void setImage(Image *image);
+
+ /**
+ * Draws the Icon.
+ */
+ void draw(gcn::Graphics *g);
+
+ private:
+
+ Image *mImage;
+};
+
+#endif
diff --git a/src/gui/inventorywindow.cpp b/src/gui/inventorywindow.cpp
index fea86b81..d18490a4 100644
--- a/src/gui/inventorywindow.cpp
+++ b/src/gui/inventorywindow.cpp
@@ -32,31 +32,39 @@
#include "itemcontainer.h"
#include "progressbar.h"
#include "scrollarea.h"
+#include "sdlinput.h"
#include "viewport.h"
#include "widgets/layout.h"
#include "../inventory.h"
#include "../item.h"
+#include "../localplayer.h"
+#include "../log.h"
#include "../units.h"
#include "../resources/iteminfo.h"
#include "../utils/gettext.h"
-#include "../utils/strprintf.h"
#include "../utils/stringutils.h"
+#include "../utils/strprintf.h"
InventoryWindow::InventoryWindow(int invSize):
Window(_("Inventory")),
mMaxSlots(invSize),
+ mSplit(false),
mItemDesc(false)
{
setWindowName("Inventory");
- setResizable(true);
+ setResizable(false);
setCloseButton(true);
-
+ // LEEOR/TODO: Since this window is not resizable, do we really need to set these
+ // values or can we drop them?
+ setMinWidth(375);
+ setMinHeight(283);
// If you adjust these defaults, don't forget to adjust the trade window's.
- setDefaultSize(115, 25, 375, 300);
+ setDefaultSize(115, 30, 375, 283);
+ addKeyListener(this);
std::string longestUseString = getFont()->getWidth(_("Equip")) >
getFont()->getWidth(_("Use")) ?
@@ -70,8 +78,15 @@ InventoryWindow::InventoryWindow(int invSize):
mUseButton = new Button(longestUseString, "use", this);
mDropButton = new Button(_("Drop"), "drop", this);
-
- mItems = new ItemContainer(player_node->getInventory(), 2);
+#ifdef TMWSERV_SUPPORT
+ mSplitButton = new Button(_("Split"), "split", this);
+#endif
+
+#ifdef TMWSERV_SUPPORT
+ mItems = new ItemContainer(player_node->getInventory(), 10, 5);
+#else
+ mItems = new ItemContainer(player_node->getInventory(), 10, 5, 2);
+#endif
mItems->addSelectionListener(this);
mInvenScroll = new ScrollArea(mItems);
@@ -94,15 +109,17 @@ InventoryWindow::InventoryWindow(int invSize):
place(1, 0, mWeightBar, 3);
place(4, 0, mSlotsLabel).setPadding(3);
place(5, 0, mSlotsBar, 2);
- place(0, 1, mInvenScroll, 7, 4);
- place(5, 5, mDropButton);
- place(6, 5, mUseButton);
+ place(0, 1, mInvenScroll, 100).setPadding(3);
+ place(0, 2, mUseButton);
+ place(1, 2, mDropButton);
+#ifdef TMWSERV_SUPPORT
+ place(2, 2, mSplitButton);
+#endif
Layout &layout = getLayout();
- layout.setRowHeight(0, mDropButton->getHeight());
+ layout.setRowHeight(0, Layout::AUTO_SET);
loadWindowState();
- setLocationRelativeTo(getParent());
}
InventoryWindow::~InventoryWindow()
@@ -118,21 +135,21 @@ void InventoryWindow::logic()
// redesign of InventoryWindow and ItemContainer probably.
updateButtons();
- if (mMaxWeight != player_node->mMaxWeight ||
- mTotalWeight != player_node->mTotalWeight ||
+ if (mMaxWeight != player_node->getMaxWeight() ||
+ mTotalWeight != player_node->getTotalWeight() ||
mUsedSlots != toString(player_node->getInventory()->getNumberOfSlotsUsed()))
{
- mTotalWeight = player_node->mTotalWeight;
- mMaxWeight = player_node->mMaxWeight;
+ mTotalWeight = player_node->getTotalWeight();
+ mMaxWeight = player_node->getMaxWeight();
mUsedSlots = toString(player_node->getInventory()->getNumberOfSlotsUsed());
// Weight Bar coloration
- if (int(player_node->mTotalWeight) < int(player_node->mMaxWeight / 3))
+ if (int(player_node->getTotalWeight()) < int(player_node->getMaxWeight() / 3))
{
mWeightBar->setColor(0, 0, 255); // Blue
}
- else if (int(player_node->mTotalWeight) <
- int((player_node->mMaxWeight / 3) * 2))
+ else if (int(player_node->getTotalWeight()) <
+ int((player_node->getMaxWeight() / 3) * 2))
{
mWeightBar->setColor(255, 255, 0); // Yellow
}
@@ -144,8 +161,8 @@ void InventoryWindow::logic()
// Adjust progress bars
mSlotsBar->setProgress((float)
player_node->getInventory()->getNumberOfSlotsUsed() / mMaxSlots);
- mWeightBar->setProgress((float) player_node->mTotalWeight /
- player_node->mMaxWeight);
+ mWeightBar->setProgress((float) player_node->getTotalWeight() /
+ player_node->getMaxWeight());
mSlotsBar->setText(strprintf("%s/%d", mUsedSlots.c_str(), mMaxSlots));
mWeightBar->setText(strprintf("%s/%s",
@@ -163,6 +180,14 @@ void InventoryWindow::action(const gcn::ActionEvent &event)
if (event.getId() == "use")
{
+#ifdef TMWSERV_SUPPORT
+ if (item->isEquipment()) {
+ player_node->equipItem(item);
+ }
+ else {
+ player_node->useItem(item->getInvIndex());
+ }
+#else
if (item->isEquipment())
{
if (item->isEquipped())
@@ -172,19 +197,33 @@ void InventoryWindow::action(const gcn::ActionEvent &event)
}
else
player_node->useItem(item);
+#endif
}
else if (event.getId() == "drop")
{
- if (item->getQuantity() == 1)
- player_node->dropItem(item, 1);
- else
- {
+ if (item->getQuantity() > 1) {
// Choose amount of items to drop
new ItemAmountWindow(AMOUNT_ITEM_DROP, this, item);
}
+ else {
+ player_node->dropItem(item, 1);
+ }
+ mItems->selectNone();
+ }
+ else if (event.getId() == "split")
+ {
+ if (item && !item->isEquipment() && item->getQuantity() > 1) {
+ new ItemAmountWindow(AMOUNT_ITEM_SPLIT, this, item,
+ (item->getQuantity() - 1));
+ }
}
}
+Item* InventoryWindow::getSelectedItem() const
+{
+ return mItems->getSelectedItem();
+}
+
void InventoryWindow::mouseClicked(gcn::MouseEvent &event)
{
Window::mouseClicked(event);
@@ -205,15 +244,55 @@ void InventoryWindow::mouseClicked(gcn::MouseEvent &event)
}
}
+#ifdef TMWSERV_SUPPORT
+void InventoryWindow::keyPressed(gcn::KeyEvent &event)
+{
+ switch (event.getKey().getValue())
+ {
+ case Key::LEFT_SHIFT:
+ case Key::RIGHT_SHIFT:
+ mSplit = true;
+ break;
+ }
+}
+
+void InventoryWindow::keyReleased(gcn::KeyEvent &event)
+{
+ switch (event.getKey().getValue())
+ {
+ case Key::LEFT_SHIFT:
+ case Key::RIGHT_SHIFT:
+ mSplit = false;
+ break;
+ }
+}
+#endif
+
+void InventoryWindow::valueChanged(const gcn::SelectionEvent &event)
+{
+ if (mSplit)
+ {
+ Item *item = mItems->getSelectedItem();
+
+ if (item && !item->isEquipment() && item->getQuantity() > 1)
+ {
+ mSplit = false;
+ new ItemAmountWindow(AMOUNT_ITEM_SPLIT, this, item, (item->getQuantity() - 1));
+ }
+ }
+}
+
void InventoryWindow::updateButtons()
{
const Item *selectedItem = mItems->getSelectedItem();
if (selectedItem && selectedItem->isEquipment())
{
+#ifdef EATHENA_SUPPORT
if (selectedItem->isEquipped())
mUseButton->setCaption(_("Unequip"));
else
+#endif
mUseButton->setCaption(_("Equip"));
}
else
@@ -221,9 +300,15 @@ void InventoryWindow::updateButtons()
mUseButton->setEnabled(selectedItem != 0);
mDropButton->setEnabled(selectedItem != 0);
-}
-Item* InventoryWindow::getSelectedItem() const
-{
- return mItems->getSelectedItem();
+#ifdef TMWSERV_SUPPORT
+ if (selectedItem && !selectedItem->isEquipment() &&
+ selectedItem->getQuantity() > 1)
+ {
+ mSplitButton->setEnabled(true);
+ }
+ else {
+ mSplitButton->setEnabled(false);
+ }
+#endif
}
diff --git a/src/gui/inventorywindow.h b/src/gui/inventorywindow.h
index 45796e74..6a51c66d 100644
--- a/src/gui/inventorywindow.h
+++ b/src/gui/inventorywindow.h
@@ -24,6 +24,7 @@
#include <guichan/actionlistener.hpp>
#include <guichan/selectionlistener.hpp>
+#include <guichan/keylistener.hpp>
#include "window.h"
@@ -39,14 +40,20 @@ class TextBox;
*
* \ingroup Interface
*/
-class InventoryWindow : public Window, gcn::ActionListener,
- gcn::SelectionListener
+class InventoryWindow : public Window,
+ public gcn::ActionListener,
+ public gcn::KeyListener,
+ public gcn::SelectionListener
{
public:
/**
* Constructor.
*/
+#ifdef TMWSERV_SUPPORT
+ InventoryWindow(int invSize = (INVENTORY_SIZE));
+#else
InventoryWindow(int invSize = (INVENTORY_SIZE - 2));
+#endif
/**
* Destructor.
@@ -68,8 +75,28 @@ class InventoryWindow : public Window, gcn::ActionListener,
*/
Item* getSelectedItem() const;
+ /**
+ * Handles the mouse clicks.
+ */
void mouseClicked(gcn::MouseEvent &event);
+#ifdef TMWSERV_SUPPORT
+ /**
+ * Handles the key presses.
+ */
+ void keyPressed(gcn::KeyEvent &event);
+
+ /**
+ * Handles the key releases.
+ */
+ void keyReleased(gcn::KeyEvent &event);
+#endif
+
+ /**
+ * Updates labels to currently selected item.
+ */
+ void valueChanged(const gcn::SelectionEvent &event);
+
private:
void updateButtons(); /**< Updates button states. */
@@ -78,10 +105,13 @@ class InventoryWindow : public Window, gcn::ActionListener,
std::string mWeight;
std::string mSlots;
std::string mUsedSlots;
- Uint32 mTotalWeight, mMaxWeight;
- gcn::Button *mUseButton, *mDropButton;
- gcn::ScrollArea *mInvenScroll;
-
+ int mTotalWeight, mMaxWeight;
+ gcn::Button *mUseButton;
+ gcn::Button *mDropButton;
+#ifdef TMWSERV_SUPPORT
+ gcn::Button *mSplitButton;
+#endif
+ gcn::ScrollArea *mInvenScroll; /**< Inventory Scroll Area. */
gcn::Label *mWeightLabel;
gcn::Label *mSlotsLabel;
@@ -90,6 +120,7 @@ class InventoryWindow : public Window, gcn::ActionListener,
int mMaxSlots;
+ bool mSplit;
bool mItemDesc;
};
diff --git a/src/gui/item_amount.cpp b/src/gui/item_amount.cpp
index 92be3d6e..3bd388f4 100644
--- a/src/gui/item_amount.cpp
+++ b/src/gui/item_amount.cpp
@@ -32,11 +32,15 @@
#include "../utils/gettext.h"
-ItemAmountWindow::ItemAmountWindow(int usage, Window *parent, Item *item):
+ItemAmountWindow::ItemAmountWindow(int usage, Window *parent, Item *item,
+ int maxRange):
Window("", true, parent),
mItem(item)
{
- const int maxRange = mItem->getQuantity();
+ if (!maxRange)
+ {
+ maxRange = mItem->getQuantity();
+ }
// Integer field
mItemAmountTextField = new IntTextField(1);
@@ -80,6 +84,10 @@ ItemAmountWindow::ItemAmountWindow(int usage, Window *parent, Item *item):
setCaption(_("Select amount of items to drop."));
okButton->setActionEventId("Drop");
break;
+ case AMOUNT_ITEM_SPLIT:
+ setCaption(_("Select amount of items to split."));
+ okButton->setActionEventId("Split");
+ break;
default:
break;
}
@@ -123,6 +131,13 @@ void ItemAmountWindow::action(const gcn::ActionEvent &event)
tradeWindow->tradeItem(mItem, mItemAmountTextField->getValue());
scheduleDelete();
}
+#ifdef TMWSERV_SUPPORT
+ else if (event.getId() == "Split")
+ {
+ player_node->splitItem(mItem, mItemAmountTextField->getValue());
+ scheduleDelete();
+ }
+#endif
mItemAmountTextField->setValue(amount);
mItemAmountSlide->setValue(amount);
}
diff --git a/src/gui/item_amount.h b/src/gui/item_amount.h
index 618d7d51..4fdb8dc6 100644
--- a/src/gui/item_amount.h
+++ b/src/gui/item_amount.h
@@ -31,9 +31,10 @@ class Item;
#define AMOUNT_TRADE_ADD 1
#define AMOUNT_ITEM_DROP 2
+#define AMOUNT_ITEM_SPLIT 3
/**
- * Window used for selecting the amount of items to drop or trade.
+ * Window used for selecting the amount of items to drop, trade or split.
*
* \ingroup Interface
*/
@@ -43,7 +44,7 @@ class ItemAmountWindow : public Window, public gcn::ActionListener
/**
* Constructor.
*/
- ItemAmountWindow(int usage, Window *parent, Item *item);
+ ItemAmountWindow(int usage, Window *parent, Item *item, int maxRange = 0);
/**
* Called when receiving actions from widget.
diff --git a/src/gui/itemcontainer.cpp b/src/gui/itemcontainer.cpp
index eed31f7a..bdae9ada 100644
--- a/src/gui/itemcontainer.cpp
+++ b/src/gui/itemcontainer.cpp
@@ -20,13 +20,14 @@
*/
#include "itemcontainer.h"
+#include "chat.h"
#include "itempopup.h"
#include <guichan/mouseinput.hpp>
#include <guichan/selectionlistener.hpp>
-#include <SDL_mouse.h>
+#include "sdlinput.h"
#include "../graphics.h"
#include "../inventory.h"
@@ -40,28 +41,48 @@
#include "../utils/stringutils.h"
-const int ItemContainer::gridWidth = 36; // item icon width + 4
-const int ItemContainer::gridHeight = 42; // item icon height + 10
+// TODO: Add support for adding items to the item shortcut window (global
+// itemShortcut).
-static const int NO_ITEM = -1;
+static const int BOX_WIDTH = 36;
+static const int BOX_HEIGHT = 44;
-ItemContainer::ItemContainer(Inventory *inventory, int offset):
+enum
+{
+ SEL_NONE = 0,
+ SEL_SELECTED,
+ SEL_SELECTING,
+ SEL_DESELECTING,
+ SEL_DRAGGING
+};
+
+ItemContainer::ItemContainer(Inventory *inventory,
+ int gridColumns,
+ int gridRows,
+ int offset):
mInventory(inventory),
- mSelectedItemIndex(NO_ITEM),
- mLastSelectedItemId(NO_ITEM),
- mOffset(offset)
+ mGridColumns(gridColumns),
+ mGridRows(gridRows),
+ mOffset(offset),
+ mSelectedItem(NULL),
+ mHighlightedItem(NULL),
+ mSelectionStatus(SEL_NONE),
+ mSwapItems(false),
+ mDescItems(false)
{
- mItemPopup = new ItemPopup;
+ mItemPopup = new ItemPopup();
+ setFocusable(true);
ResourceManager *resman = ResourceManager::getInstance();
mSelImg = resman->getImage("graphics/gui/selection.png");
if (!mSelImg) logger->error("Unable to load selection.png");
- mMaxItems = mInventory->getLastUsedSlot() - 1; // Count from 0, usage from 2
-
+ addKeyListener(this);
addMouseListener(this);
- addWidgetListener(this);
+
+ setSize((BOX_WIDTH - 1) * mGridColumns + 1,
+ (BOX_HEIGHT - 1) * mGridRows + 1);
}
ItemContainer::~ItemContainer()
@@ -70,187 +91,214 @@ ItemContainer::~ItemContainer()
delete mItemPopup;
}
-void ItemContainer::logic()
-{
- gcn::Widget::logic();
-
- int i = mInventory->getLastUsedSlot() - 1; // Count from 0, usage from 2
-
- if (i != mMaxItems)
- {
- mMaxItems = i;
- recalculateHeight();
- }
-}
-
void ItemContainer::draw(gcn::Graphics *graphics)
{
- int columns = getWidth() / gridWidth;
+ Graphics *g = static_cast<Graphics*>(graphics);
- // Have at least 1 column
- if (columns < 1)
+ for (int i = 0; i < mGridColumns; i++)
{
- columns = 1;
- }
+ for (int j = 0; j < mGridRows; j++)
+ {
+ // Items positions made to overlap on another.
+ int itemX = i * (BOX_WIDTH - 1);
+ int itemY = j * (BOX_HEIGHT - 1);
- /*
- * mOffset is used to compensate for some weirdness that eAthena inherited from
- * Ragnarok Online. Inventory slots and cart slots are +2 from their actual index,
- * while storage slots are +1.
- */
- for (int i = mOffset; i < mInventory->getSize(); i++)
- {
- Item *item = mInventory->getItem(i);
+ // Set color to black.
+ g->setColor(gcn::Color(0, 0, 0));
+ // Draw box border.
+ g->drawRectangle(
+ gcn::Rectangle(itemX, itemY, BOX_WIDTH, BOX_HEIGHT));
- if (!item || item->getQuantity() <= 0)
- continue;
+ Item *item = mInventory->getItem((j * mGridColumns) + i);
- int itemX = ((i - 2) % columns) * gridWidth;
- int itemY = ((i - 2) / columns) * gridHeight;
+ if (!item || item->getId() == 0)
+ continue;
- // Draw selection image below selected item
- if (mSelectedItemIndex == i)
- {
- static_cast<Graphics*>(graphics)->drawImage(
- mSelImg, itemX, itemY);
- }
+ Image *image = item->getImage();
+ if (image)
+ {
+ if (item == mSelectedItem)
+ {
+ if (mSelectionStatus == SEL_DRAGGING) {
+ // Reposition the coords to that of the cursor.
+ itemX = mDragPosX - (BOX_WIDTH / 2);
+ itemY = mDragPosY - (BOX_HEIGHT / 2);
+ }
+ else {
+ // Draw selected image.
+ g->drawImage(mSelImg, itemX, itemY);
+ }
+ }
+ g->drawImage(image, itemX, itemY);
+ }
+ if (item->getQuantity() > 1) {
+ // Draw item caption
+ g->drawText(
+ toString(item->getQuantity()),
+ itemX + BOX_WIDTH / 2,
+ itemY + BOX_HEIGHT - 14,
+ gcn::Graphics::CENTER);
+ }
- // Draw item icon
- Image* image = item->getImage();
- if (image)
- {
- static_cast<Graphics*>(graphics)->drawImage(
- image, itemX, itemY);
}
-
- // Draw item caption
- graphics->setFont(getFont());
- graphics->setColor(gcn::Color(0, 0, 0));
- graphics->drawText(
- (item->isEquipped() ? "Eq." : toString(item->getQuantity())),
- itemX + gridWidth / 2,
- itemY + gridHeight - 11,
- gcn::Graphics::CENTER);
}
-}
-void ItemContainer::widgetResized(const gcn::Event &event)
-{
- recalculateHeight();
+ if (isFocused() && mHighlightedItem) {
+ // Items positions made to overlap on another.
+ const int i = mHighlightedItem->getInvIndex();
+ const int itemX = (i % mGridColumns) * (BOX_WIDTH - 1);
+ const int itemY = (i / mGridColumns) * (BOX_HEIGHT - 1);
+ // Set color to orange.
+ g->setColor(gcn::Color(255, 128, 0));
+ // Draw box border.
+ g->drawRectangle(gcn::Rectangle(itemX, itemY, BOX_WIDTH, BOX_HEIGHT));
+ }
}
-void ItemContainer::recalculateHeight()
+void ItemContainer::selectNone()
{
- int cols = getWidth() / gridWidth;
-
- if (cols < 1)
- cols = 1;
-
- const int rows = (mMaxItems / cols) + (mMaxItems % cols > 0 ? 1 : 0);
- const int height = rows * gridHeight + 8;
-
- if (height != getHeight())
- setHeight(height);
+ setSelectedItem(NULL);
}
-Item *ItemContainer::getSelectedItem()
+void ItemContainer::setSelectedItem(Item *item)
{
- refindSelectedItem(); // Make sure that we're still current
-
- if (mSelectedItemIndex == NO_ITEM)
- return NULL;
-
- return mInventory->getItem(mSelectedItemIndex);
+ if (mSelectedItem != item)
+ {
+ mSelectedItem = item;
+ distributeValueChangedEvent();
+ }
}
-void ItemContainer::selectNone()
+void ItemContainer::distributeValueChangedEvent()
{
- setSelectedItemIndex(NO_ITEM);
-}
+ SelectionListenerIterator iter;
-void ItemContainer::refindSelectedItem()
-{
- if (mSelectedItemIndex != NO_ITEM)
+ for (iter = mSelectionListeners.begin(); iter != mSelectionListeners.end();
+ ++iter)
{
- if (mInventory->getItem(mSelectedItemIndex) &&
- mInventory->getItem(mSelectedItemIndex)->getId() == mLastSelectedItemId)
- return; // we're already fine
-
- // Otherwise ensure the invariant: we must point to an item of the specified last ID,
- // or nowhere at all.
-
- for (int i = 0; i <= mMaxItems + 1; i++)
- if (mInventory->getItem(i) &&
- mInventory->getItem(i)->getId() == mLastSelectedItemId)
- {
- mSelectedItemIndex = i;
- return;
- }
+ gcn::SelectionEvent event(this);
+ (*iter)->valueChanged(event);
}
-
- mLastSelectedItemId = mSelectedItemIndex = NO_ITEM;
}
-void ItemContainer::setSelectedItemIndex(int index)
+void ItemContainer::keyPressed(gcn::KeyEvent &event)
{
- int newSelectedItemIndex;
-
- /*
- * mOffset is used to compensate for some weirdness that eAthena inherited from
- * Ragnarok Online. Inventory slots and cart slots are +2 from their actual index,
- * while storage slots are +1.
- */
- if (index < 0 || index > mMaxItems + mOffset || mInventory->getItem(index) == NULL)
- newSelectedItemIndex = NO_ITEM;
- else
- newSelectedItemIndex = index;
-
- if (mSelectedItemIndex != newSelectedItemIndex)
+ switch (event.getKey().getValue())
{
- mSelectedItemIndex = newSelectedItemIndex;
-
- if (mSelectedItemIndex == NO_ITEM)
- mLastSelectedItemId = NO_ITEM;
- else
- mLastSelectedItemId = mInventory->getItem(index)->getId();
-
- distributeValueChangedEvent();
+ case Key::LEFT:
+ moveHighlight(MOVE_SELECTED_LEFT);
+ break;
+ case Key::RIGHT:
+ moveHighlight(MOVE_SELECTED_RIGHT);
+ break;
+ case Key::UP:
+ moveHighlight(MOVE_SELECTED_UP);
+ break;
+ case Key::DOWN:
+ moveHighlight(MOVE_SELECTED_DOWN);
+ break;
+ case Key::SPACE:
+ keyAction();
+ break;
+ case Key::LEFT_ALT:
+ case Key::RIGHT_ALT:
+ mSwapItems = true;
+ break;
+ case Key::RIGHT_CONTROL:
+ mDescItems = true;
+ break;
}
}
-void ItemContainer::distributeValueChangedEvent()
+void ItemContainer::keyReleased(gcn::KeyEvent &event)
{
- gcn::SelectionEvent event(this);
- std::list<gcn::SelectionListener*>::iterator i_end = mListeners.end();
- std::list<gcn::SelectionListener*>::iterator i;
-
- for (i = mListeners.begin(); i != i_end; ++i)
+ switch (event.getKey().getValue())
{
- (*i)->valueChanged(event);
+ case Key::LEFT_ALT:
+ case Key::RIGHT_ALT:
+ mSwapItems = false;
+ break;
+ case Key::RIGHT_CONTROL:
+ mDescItems = false;
+ break;
}
}
void ItemContainer::mousePressed(gcn::MouseEvent &event)
{
const int button = event.getButton();
-
if (button == gcn::MouseEvent::LEFT || button == gcn::MouseEvent::RIGHT)
{
- int columns = getWidth() / gridWidth;
- int mx = event.getX();
- int my = event.getY();
- int index = mx / gridWidth + ((my / gridHeight) * columns) + mOffset;
-
- itemShortcut->setItemSelected(-1);
- setSelectedItemIndex(index);
+ const int index = getSlotIndex(event.getX(), event.getY());
+ if (index == Inventory::NO_SLOT_INDEX) {
+ return;
+ }
Item *item = mInventory->getItem(index);
- if (item)
+ // put item name into chat window
+ if (mDescItems)
+ {
+ chatWindow->addItemText(item->getInfo().getName());
+ }
+
+ if (mSelectedItem && mSelectedItem == item)
+ {
+ mSelectionStatus = SEL_DESELECTING;
+ }
+ else if (item && item->getId())
+ {
+ setSelectedItem(item);
+ mSelectionStatus = SEL_SELECTING;
+
itemShortcut->setItemSelected(item->getId());
+ }
+ else
+ {
+ setSelectedItem(NULL);
+ mSelectionStatus = SEL_NONE;
+ }
+ }
+}
+
+void ItemContainer::mouseDragged(gcn::MouseEvent &event)
+{
+ if (mSelectionStatus != SEL_NONE)
+ {
+ mSelectionStatus = SEL_DRAGGING;
+ mDragPosX = event.getX();
+ mDragPosY = event.getY();
}
}
+void ItemContainer::mouseReleased(gcn::MouseEvent &event)
+{
+ switch (mSelectionStatus)
+ {
+ case SEL_SELECTING:
+ mSelectionStatus = SEL_SELECTED;
+ return;
+ case SEL_DESELECTING:
+ setSelectedItem(NULL);
+ mSelectionStatus = SEL_NONE;
+ return;
+ case SEL_DRAGGING:
+ mSelectionStatus = SEL_SELECTED;
+ break;
+ default:
+ return;
+ };
+
+ int index = getSlotIndex(event.getX(), event.getY());
+ if (index == Inventory::NO_SLOT_INDEX) return;
+ Item *item = mInventory->getItem(index);
+ if (item == mSelectedItem) return;
+ player_node->moveInvItem(mSelectedItem, index);
+ setSelectedItem(NULL);
+ mSelectionStatus = SEL_NONE;
+}
+
+
// Show ItemTooltip
void ItemContainer::mouseMoved(gcn::MouseEvent &event)
{
@@ -277,11 +325,97 @@ void ItemContainer::mouseExited(gcn::MouseEvent &event)
mItemPopup->setVisible(false);
}
-int ItemContainer::getSlotIndex(int posX, int posY) const
+int ItemContainer::getSlotIndex(const int posX, const int posY) const
+{
+ if (getDimension().isPointInRect(posX, posY))
+ {
+ // Takes into account, boxes are overlapping each other.
+ return (posY / (BOX_HEIGHT - 1)) * mGridColumns + (posX / (BOX_WIDTH - 1));
+ }
+ return Inventory::NO_SLOT_INDEX;
+}
+
+void ItemContainer::keyAction()
{
- int columns = getWidth() / gridWidth;
- int index = posX / gridWidth + ((posY / gridHeight) * columns) + mOffset;
+ // If there is no highlight then return.
+ if (!mHighlightedItem)
+ return;
- return (index);
+ // If the highlight is on the selected item, then deselect it.
+ if (mHighlightedItem == mSelectedItem)
+ {
+ setSelectedItem(NULL);
+ mSelectionStatus = SEL_NONE;
+ }
+ // Check and swap items if necessary.
+ else if (mSwapItems &&
+ mSelectedItem &&
+ mHighlightedItem->getId())
+ {
+ player_node->moveInvItem(
+ mSelectedItem, mHighlightedItem->getInvIndex());
+ setSelectedItem(mHighlightedItem);
+ }
+ // If the highlight is on an item then select it.
+ else if (mHighlightedItem->getId())
+ {
+ setSelectedItem(mHighlightedItem);
+ mSelectionStatus = SEL_SELECTED;
+ }
+ // If the highlight is on a blank space then move it.
+ else if (mSelectedItem)
+ {
+ player_node->moveInvItem(
+ mSelectedItem, mHighlightedItem->getInvIndex());
+ setSelectedItem(NULL);
+ mSelectionStatus = SEL_NONE;
+ }
}
+void ItemContainer::moveHighlight(int direction)
+{
+ if (!mHighlightedItem)
+ {
+ if (mSelectedItem) {
+ mHighlightedItem = mSelectedItem;
+ }
+ else {
+ mHighlightedItem = mInventory->getItem(0);
+ }
+ return;
+ }
+
+ switch (direction)
+ {
+ case MOVE_SELECTED_LEFT:
+ if (mHighlightedItem->getInvIndex() % mGridColumns == 0)
+ {
+ mHighlightedItem += mGridColumns;
+ }
+ mHighlightedItem--;
+ break;
+ case MOVE_SELECTED_RIGHT:
+ if ((mHighlightedItem->getInvIndex() % mGridColumns) ==
+ (mGridColumns - 1))
+ {
+ mHighlightedItem -= mGridColumns;
+ }
+ mHighlightedItem++;
+ break;
+ case MOVE_SELECTED_UP:
+ if (mHighlightedItem->getInvIndex() / mGridColumns == 0)
+ {
+ mHighlightedItem += (mGridColumns * mGridRows);
+ }
+ mHighlightedItem -= mGridColumns;
+ break;
+ case MOVE_SELECTED_DOWN:
+ if ((mHighlightedItem->getInvIndex() / mGridColumns) ==
+ (mGridRows - 1))
+ {
+ mHighlightedItem -= (mGridColumns * mGridRows);
+ }
+ mHighlightedItem += mGridColumns;
+ break;
+ }
+}
diff --git a/src/gui/itemcontainer.h b/src/gui/itemcontainer.h
index 5ad140be..38eaba01 100644
--- a/src/gui/itemcontainer.h
+++ b/src/gui/itemcontainer.h
@@ -24,9 +24,9 @@
#include <list>
+#include <guichan/keylistener.hpp>
#include <guichan/mouselistener.hpp>
#include <guichan/widget.hpp>
-#include <guichan/widgetlistener.hpp>
class Image;
class Inventory;
@@ -43,14 +43,19 @@ namespace gcn {
* \ingroup GUI
*/
class ItemContainer : public gcn::Widget,
- public gcn::MouseListener,
- public gcn::WidgetListener
+ public gcn::KeyListener,
+ public gcn::MouseListener
{
public:
/**
* Constructor. Initializes the graphic.
+ * @param inventory
+ * @param gridColumns Amount of columns in grid.
+ * @param gridRows Amount of rows in grid.
+ * @param offset Index offset
*/
- ItemContainer(Inventory *inventory, int offset);
+ ItemContainer(Inventory *inventory, int gridColumns, int gridRows,
+ int offset = 0);
/**
* Destructor.
@@ -58,19 +63,19 @@ class ItemContainer : public gcn::Widget,
virtual ~ItemContainer();
/**
- * Handles the logic of the ItemContainer
+ * Draws the items.
*/
- void logic();
+ void draw(gcn::Graphics *graphics);
/**
- * Draws the items.
+ * Handles the key presses.
*/
- void draw(gcn::Graphics *graphics);
+ void keyPressed(gcn::KeyEvent &event);
/**
- * Called whenever the widget changes size.
+ * Handles the key releases.
*/
- void widgetResized(const gcn::Event &event);
+ void keyReleased(gcn::KeyEvent &event);
/**
* Handles mouse click.
@@ -78,9 +83,20 @@ class ItemContainer : public gcn::Widget,
void mousePressed(gcn::MouseEvent &event);
/**
+ * Handles mouse dragged.
+ */
+ void mouseDragged(gcn::MouseEvent &event);
+
+ /**
+ * Handles mouse released.
+ */
+ void mouseReleased(gcn::MouseEvent &event);
+
+ /**
* Returns the selected item.
*/
- Item* getSelectedItem();
+ Item* getSelectedItem() const
+ { return mSelectedItem; }
/**
* Sets selected item to NULL.
@@ -93,7 +109,7 @@ class ItemContainer : public gcn::Widget,
*/
void addSelectionListener(gcn::SelectionListener *listener)
{
- mListeners.push_back(listener);
+ mSelectionListeners.push_back(listener);
}
/**
@@ -102,18 +118,35 @@ class ItemContainer : public gcn::Widget,
*/
void removeSelectionListener(gcn::SelectionListener *listener)
{
- mListeners.remove(listener);
+ mSelectionListeners.remove(listener);
}
+ enum {
+ MOVE_SELECTED_LEFT, // 0
+ MOVE_SELECTED_RIGHT, // 1
+ MOVE_SELECTED_UP, // 2
+ MOVE_SELECTED_DOWN // 3
+ };
private:
+ /**
+ * Execute all the functionality associated with the action key.
+ */
+ void keyAction();
+
void mouseExited(gcn::MouseEvent &event);
void mouseMoved(gcn::MouseEvent &event);
/**
+ * Moves the highlight in the direction specified.
+ *
+ * @param direction The move direction of the highlighter.
+ */
+ void moveHighlight(int direction);
- * Sets the currently selected item. Invalid (e.g., negative) indices set `no item'.
+ /**
+ * Sets the currently selected item.
*/
- void setSelectedItemIndex(int index);
+ void setSelectedItem(Item *item);
/**
* Find the current item index by the most recently used item ID
@@ -140,19 +173,21 @@ class ItemContainer : public gcn::Widget,
int getSlotIndex(int posX, int posY) const;
Inventory *mInventory;
- Image *mSelImg;
-
- int mSelectedItemIndex;
- int mLastSelectedItemId; // last selected item ID. If we lose the item, find again by ID.
- int mMaxItems;
+ int mGridColumns, mGridRows;
int mOffset;
+ Image *mSelImg;
+ Item *mSelectedItem, *mHighlightedItem;
+ int mSelectionStatus;
+ bool mSwapItems;
+ bool mDescItems;
+ int mDragPosX, mDragPosY;
ItemPopup *mItemPopup;
- std::list<gcn::SelectionListener*> mListeners;
+ typedef std::list<gcn::SelectionListener*> SelectionListenerList;
+ typedef SelectionListenerList::iterator SelectionListenerIterator;
- static const int gridWidth;
- static const int gridHeight;
+ SelectionListenerList mSelectionListeners;
};
#endif
diff --git a/src/gui/itempopup.cpp b/src/gui/itempopup.cpp
index 48aa7c8c..25e6e78e 100644
--- a/src/gui/itempopup.cpp
+++ b/src/gui/itempopup.cpp
@@ -106,7 +106,9 @@ ItemPopup::~ItemPopup()
void ItemPopup::setItem(const ItemInfo &item)
{
mItemName->setCaption(item.getName());
+#ifdef EATHENA_SUPPORT
mItemName->setForegroundColor(getColor(item.getType()));
+#endif
mItemName->setWidth(boldFont->getWidth(item.getName()));
mItemDesc->setTextWrapped(item.getDescription(), 196);
mItemEffect->setTextWrapped(item.getEffect(), 196);
diff --git a/src/gui/itemshortcutcontainer.cpp b/src/gui/itemshortcutcontainer.cpp
index e5990a28..8864cbd9 100644
--- a/src/gui/itemshortcutcontainer.cpp
+++ b/src/gui/itemshortcutcontainer.cpp
@@ -102,14 +102,18 @@ void ItemShortcutContainer::draw(gcn::Graphics *graphics)
Item *item =
player_node->getInventory()->findItem(itemShortcut->getItem(i));
- if (item) {
+ if (item)
+ {
// Draw item icon.
- const std::string label =
- item->isEquipped() ? "Eq." : toString(item->getQuantity());
Image* image = item->getImage();
- if (image) {
+
+ if (image)
+ {
const std::string label =
- item->isEquipped() ? "Eq." : toString(item->getQuantity());
+#ifdef EATHENA_SUPPORT
+ item->isEquipped() ? "Eq." :
+#endif
+ toString(item->getQuantity());
g->drawImage(image, itemX, itemY);
g->drawText(
label,
diff --git a/src/gui/itemshortcutwindow.cpp b/src/gui/itemshortcutwindow.cpp
new file mode 100644
index 00000000..e21f421b
--- /dev/null
+++ b/src/gui/itemshortcutwindow.cpp
@@ -0,0 +1,71 @@
+/*
+ * The Mana World
+ * Copyright 2007 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "itemshortcutwindow.h"
+
+#include "itemshortcutcontainer.h"
+#include "scrollarea.h"
+
+static const int SCROLL_PADDING = 0;
+
+ItemShortcutWindow::ItemShortcutWindow()
+{
+ setWindowName("ItemShortcut");
+ // no title presented, title bar is padding so window can be moved.
+ gcn::Window::setTitleBarHeight(gcn::Window::getPadding());
+ setShowTitle(false);
+ setResizable(true);
+ setDefaultSize(758, 174, 42, 426);
+
+ mItems = new ItemShortcutContainer;
+
+ const int border = SCROLL_PADDING * 2 + getPadding() * 2;
+ setMinWidth(mItems->getBoxWidth() + border);
+ setMinHeight(mItems->getBoxHeight() + border);
+ setMaxWidth(mItems->getBoxWidth() * mItems->getMaxItems() + border);
+ setMaxHeight(mItems->getBoxHeight() * mItems->getMaxItems() + border);
+
+ mScrollArea = new ScrollArea(mItems);
+ mScrollArea->setPosition(SCROLL_PADDING, SCROLL_PADDING);
+ mScrollArea->setHorizontalScrollPolicy(gcn::ScrollArea::SHOW_NEVER);
+ mScrollArea->setOpaque(false);
+
+ add(mScrollArea);
+
+ loadWindowState();
+}
+
+ItemShortcutWindow::~ItemShortcutWindow()
+{
+ delete mItems;
+ delete mScrollArea;
+}
+
+void ItemShortcutWindow::widgetResized(const gcn::Event &event)
+{
+ Window::widgetResized(event);
+
+ const gcn::Rectangle &area = getChildrenArea();
+
+ mScrollArea->setSize(
+ area.width - SCROLL_PADDING,
+ area.height - SCROLL_PADDING);
+}
diff --git a/src/gui/itemshortcutwindow.h b/src/gui/itemshortcutwindow.h
new file mode 100644
index 00000000..017df5ec
--- /dev/null
+++ b/src/gui/itemshortcutwindow.h
@@ -0,0 +1,61 @@
+/*
+ * The Mana World
+ * Copyright 2007 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_ITEMSHORTCUTWINDOW_H
+#define _TMW_ITEMSHORTCUTWINDOW_H
+
+#include "window.h"
+
+class ItemShortcutContainer;
+class ScrollArea;
+
+/**
+ * A window around the ItemShortcutContainer.
+ *
+ * \ingroup Interface
+ */
+class ItemShortcutWindow : public Window
+{
+ public:
+ /**
+ * Constructor.
+ */
+ ItemShortcutWindow();
+
+ /**
+ * Destructor.
+ */
+ ~ItemShortcutWindow();
+
+ /**
+ * Called whenever the widget changes size.
+ */
+ void widgetResized(const gcn::Event &event);
+
+ private:
+ ItemShortcutContainer *mItems;
+
+ ScrollArea *mScrollArea;
+};
+
+extern ItemShortcutWindow *itemShortcutWindow;
+
+#endif
diff --git a/src/gui/linkhandler.h b/src/gui/linkhandler.h
index ecc05b13..fc9da6da 100644
--- a/src/gui/linkhandler.h
+++ b/src/gui/linkhandler.h
@@ -24,6 +24,8 @@
#include <string>
+#include <string>
+
/**
* A simple interface to windows that need to handle links from BrowserBox
* widget.
diff --git a/src/gui/login.cpp b/src/gui/login.cpp
index e91f7616..e68a8da1 100644
--- a/src/gui/login.cpp
+++ b/src/gui/login.cpp
@@ -50,6 +50,7 @@ LoginDialog::LoginDialog(LoginData *loginData):
{
gcn::Label *userLabel = new gcn::Label(_("Name:"));
gcn::Label *passLabel = new gcn::Label(_("Password:"));
+#ifdef EATHENA_SUPPORT
gcn::Label *serverLabel = new gcn::Label(_("Server:"));
gcn::Label *portLabel = new gcn::Label(_("Port:"));
gcn::Label *dropdownLabel = new gcn::Label(_("Recent:"));
@@ -61,15 +62,18 @@ LoginDialog::LoginDialog(LoginData *loginData):
MAX_SERVER_LIST_SIZE);
mServerListBox = new ListBox(mServerList);
mServerScrollArea = new ScrollArea;
+#endif
mUserField = new TextField(mLoginData->username);
mPassField = new PasswordField(mLoginData->password);
+#ifdef EATHENA_SUPPORT
mServerField = new TextField(mServerList->getServerAt(0));
mPortField = new TextField(mServerList->getPortAt(0));
mServerDropDown = new DropDown(mServerList,
mServerScrollArea,
mServerListBox);
mServerDropDown->setOpaque(false);
+#endif
mKeepCheck = new CheckBox(_("Remember Username"), mLoginData->remember);
mOkButton = new Button(_("OK"), "ok", this);
@@ -78,32 +82,42 @@ LoginDialog::LoginDialog(LoginData *loginData):
mUserField->setActionEventId("ok");
mPassField->setActionEventId("ok");
+#ifdef EATHENA_SUPPORT
mServerField->setActionEventId("ok");
mPortField->setActionEventId("ok");
mServerDropDown->setActionEventId("changeSelection");
+#endif
mUserField->addKeyListener(this);
mPassField->addKeyListener(this);
+#ifdef EATHENA_SUPPORT
mServerField->addKeyListener(this);
mPortField->addKeyListener(this);
mServerDropDown->addKeyListener(this);
+#endif
mUserField->addActionListener(this);
mPassField->addActionListener(this);
+#ifdef EATHENA_SUPPORT
mServerField->addActionListener(this);
mPortField->addActionListener(this);
mServerDropDown->addActionListener(this);
mKeepCheck->addActionListener(this);
+#endif
place(0, 0, userLabel);
place(0, 1, passLabel);
+#ifdef EATHENA_SUPPORT
place(0, 2, serverLabel);
place(0, 3, portLabel);
place(0, 4, dropdownLabel);
+#endif
place(1, 0, mUserField, 3).setPadding(1);
place(1, 1, mPassField, 3).setPadding(1);
+#ifdef EATHENA_SUPPORT
place(1, 2, mServerField, 3).setPadding(1);
place(1, 3, mPortField, 3).setPadding(1);
place(1, 4, mServerDropDown, 3).setPadding(1);
+#endif
place(0, 5, mKeepCheck, 4);
place(0, 6, mRegisterButton).setHAlign(LayoutCell::LEFT);
place(2, 6, mCancelButton);
@@ -126,8 +140,10 @@ void LoginDialog::action(const gcn::ActionEvent &event)
{
if (event.getId() == "ok" && canSubmit())
{
+#ifdef EATHENA_SUPPORT
mLoginData->hostname = mServerField->getText();
mLoginData->port = getUShort(mPortField->getText());
+#endif
mLoginData->username = mUserField->getText();
mLoginData->password = mPassField->getText();
mLoginData->remember = mKeepCheck->isSelected();
@@ -135,21 +151,32 @@ void LoginDialog::action(const gcn::ActionEvent &event)
mOkButton->setEnabled(false);
mRegisterButton->setEnabled(false);
+#ifdef EATHENA_SUPPORT
mServerList->save(mServerField->getText(), mPortField->getText());
- state = ACCOUNT_STATE;
+ state = STATE_ACCOUNT;
+#else
+ state = STATE_LOGIN_ATTEMPT;
+#endif
}
+#ifdef EATHENA_SUPPORT
else if (event.getId() == "changeSelection")
{
int selected = mServerListBox->getSelected();
mServerField->setText(mServerList->getServerAt(selected));
mPortField->setText(mServerList->getPortAt(selected));
}
+#endif
else if (event.getId() == "cancel")
{
- state = EXIT_STATE;
+#ifdef TMWSERV_SUPPORT
+ state = STATE_SWITCH_ACCOUNTSERVER;
+#else
+ state = STATE_EXIT;
+#endif
}
else if (event.getId() == "register")
{
+#ifdef EATHENA_SUPPORT
// Transfer these fields on to the register dialog
mLoginData->hostname = mServerField->getText();
if (isUShort(mPortField->getText()))
@@ -160,10 +187,11 @@ void LoginDialog::action(const gcn::ActionEvent &event)
{
mLoginData->port = 6901;
}
+#endif
mLoginData->username = mUserField->getText();
mLoginData->password = mPassField->getText();
- state = REGISTER_STATE;
+ state = STATE_REGISTER;
}
}
@@ -176,11 +204,14 @@ bool LoginDialog::canSubmit()
{
return !mUserField->getText().empty() &&
!mPassField->getText().empty() &&
+#ifdef EATHENA_SUPPORT
!mServerField->getText().empty() &&
isUShort(mPortField->getText()) &&
- state == LOGIN_STATE;
+#endif
+ state == STATE_LOGIN;
}
+#ifdef EATHENA_SUPPORT
bool LoginDialog::isUShort(const std::string &str)
{
if (str.empty())
@@ -312,3 +343,4 @@ std::string LoginDialog::DropDownList::getPortAt(int i)
}
return mPorts.at(i);
}
+#endif
diff --git a/src/gui/login.h b/src/gui/login.h
index 1f0f2ddb..9a97cd4d 100644
--- a/src/gui/login.h
+++ b/src/gui/login.h
@@ -27,13 +27,17 @@
#include <guichan/actionlistener.hpp>
#include <guichan/keylistener.hpp>
+#ifdef EATHENA_SUPPORT
#include <guichan/listmodel.hpp>
+#endif
#include "window.h"
-class DropDown;
class LoginData;
+#ifdef EATHENA_SUPPORT
+class DropDown;
class ScrollArea;
+#endif
/**
* The login dialog.
@@ -68,6 +72,7 @@ class LoginDialog : public Window, public gcn::ActionListener,
*/
bool canSubmit();
+#ifdef EATHENA_SUPPORT
/**
* Function to decide whether string is an unsigned short or not
*
@@ -86,11 +91,14 @@ class LoginDialog : public Window, public gcn::ActionListener,
*/
static unsigned short getUShort(const std::string &str);
- DropDown *mServerDropDown;
+#endif
gcn::TextField *mUserField;
gcn::TextField *mPassField;
+#ifdef EATHENA_SUPPORT
gcn::TextField *mServerField;
gcn::TextField *mPortField;
+ DropDown *mServerDropDown;
+#endif
gcn::CheckBox *mKeepCheck;
gcn::Button *mOkButton;
gcn::Button *mCancelButton;
@@ -98,6 +106,7 @@ class LoginDialog : public Window, public gcn::ActionListener,
LoginData *mLoginData;
+#ifdef EATHENA_SUPPORT
/**
* Helper class to keep a list of all the recent entries for the
* dropdown
@@ -125,6 +134,7 @@ class LoginDialog : public Window, public gcn::ActionListener,
DropDownList *mServerList;
gcn::ListBox *mServerListBox;
gcn::ScrollArea *mServerScrollArea;
+#endif
};
#endif
diff --git a/src/gui/magic.cpp b/src/gui/magic.cpp
new file mode 100644
index 00000000..0e56e853
--- /dev/null
+++ b/src/gui/magic.cpp
@@ -0,0 +1,92 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <guichan/widgets/label.hpp>
+#include <guichan/widgets/container.hpp>
+
+#include "magic.h"
+
+#include "button.h"
+
+#include "../localplayer.h"
+
+#include "../utils/dtor.h"
+#include "../utils/gettext.h"
+
+MagicDialog::MagicDialog():
+ Window(_("Magic"))
+{
+ setWindowName("Magic");
+ setCloseButton(true);
+ setDefaultSize(255, 30, 175, 225);
+
+ gcn::Button *spellButton1 = new Button(_("Cast Test Spell 1"), "spell_1", this);
+ gcn::Button *spellButton2 = new Button(_("Cast Test Spell 2"), "spell_2", this);
+ gcn::Button *spellButton3 = new Button(_("Cast Test Spell 3"), "spell_3", this);
+
+ spellButton1->setPosition(10, 30);
+ spellButton2->setPosition(10, 60);
+ spellButton3->setPosition(10, 90);
+
+ add(spellButton1);
+ add(spellButton2);
+ add(spellButton3);
+
+ update();
+
+ setLocationRelativeTo(getParent());
+ loadWindowState();
+}
+
+MagicDialog::~MagicDialog()
+{
+}
+
+void MagicDialog::action(const gcn::ActionEvent &event)
+{
+ if (event.getId() == "spell_1")
+ {
+ player_node->useSpecial(1);
+ }
+ if (event.getId() == "spell_2")
+ {
+ player_node->useSpecial(2);
+ }
+ if (event.getId() == "spell_3")
+ {
+ player_node->useSpecial(3);
+ }
+ else if (event.getId() == "close")
+ {
+ setVisible(false);
+ }
+}
+
+void MagicDialog::draw(gcn::Graphics *g)
+{
+ update();
+
+ Window::draw(g);
+}
+
+void MagicDialog::update()
+{
+}
diff --git a/src/gui/magic.h b/src/gui/magic.h
new file mode 100644
index 00000000..48146b9c
--- /dev/null
+++ b/src/gui/magic.h
@@ -0,0 +1,75 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_MAGIC_H
+#define _TMW_MAGIC_H
+
+#include <guichan/actionlistener.hpp>
+
+#include "window.h"
+#include "gccontainer.h"
+
+#include "../guichanfwd.h"
+
+
+/**
+ * The skill dialog.
+ *
+ * \ingroup Interface
+ */
+class MagicDialog : public Window, public gcn::ActionListener
+{
+ public:
+ /**
+ * Constructor.
+ */
+ MagicDialog();
+
+ /**
+ * Destructor.
+ */
+ ~MagicDialog();
+
+ /**
+ * Called when receiving actions from widget.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ /**
+ * Update the tabs in this dialog
+ */
+ void update();
+
+ /**
+ * Draw this window.
+ */
+ void draw(gcn::Graphics *g);
+
+ private:
+
+};
+
+
+
+
+extern MagicDialog *magicDialog;
+
+#endif
diff --git a/src/gui/menuwindow.cpp b/src/gui/menuwindow.cpp
index 0dcc999f..25ece461 100644
--- a/src/gui/menuwindow.cpp
+++ b/src/gui/menuwindow.cpp
@@ -37,6 +37,11 @@ extern Window *emoteWindow;
extern Window *setupWindow;
extern Window *skillDialog;
extern Window *statusWindow;
+#ifdef TMWSERV_SUPPORT
+extern Window *buddyWindow;
+extern Window *guildWindow;
+extern Window *magicDialog;
+#endif
namespace {
struct MenuWindowListener : public gcn::ActionListener
@@ -49,7 +54,7 @@ namespace {
}
MenuWindow::MenuWindow():
- Window("")
+ Window()
{
setResizable(false);
setWindowName("Menu");
@@ -59,14 +64,19 @@ MenuWindow::MenuWindow():
// Buttons
static const char *buttonNames[] =
{
- _("Chat"),
- _("Status"),
- _("Equipment"),
- _("Inventory"),
- _("Skills"),
- _("Shortcut"),
- _("Emote"),
- _("Setup"),
+ N_("Chat"),
+ N_("Status"),
+ N_("Equipment"),
+ N_("Inventory"),
+ N_("Skills"),
+#ifdef TMWSERV_SUPPORT
+ N_("Magic"),
+ N_("Guilds"),
+ N_("Buddys"),
+#endif
+ N_("Shortcut"),
+ N_("Emote"),
+ N_("Setup"),
0
};
int x = 0, h = 0;
@@ -94,35 +104,49 @@ void MenuWindowListener::action(const gcn::ActionEvent &event)
{
Window *window = NULL;
- if (event.getId() == _("Chat"))
+ if (event.getId() == "Chat")
{
window = chatWindow;
}
- else if (event.getId() == _("Status"))
+ else if (event.getId() == "Status")
{
window = statusWindow;
}
- else if (event.getId() == _("Equipment"))
+ else if (event.getId() == "Equipment")
{
window = equipmentWindow;
}
- else if (event.getId() == _("Inventory"))
+ else if (event.getId() == "Inventory")
{
window = inventoryWindow;
}
- else if (event.getId() == _("Skills"))
+ else if (event.getId() == "Skills")
{
window = skillDialog;
}
- else if (event.getId() == _("Shortcut"))
+#ifdef TMWSERV_SUPPORT
+ else if (event.getId() == "Magic")
+ {
+ window = magicDialog;
+ }
+ else if (event.getId() == "Guilds")
+ {
+ window = guildWindow;
+ }
+ else if (event.getId() == "Buddys")
+ {
+ window = buddyWindow;
+ }
+#endif
+ else if (event.getId() == "Shortcut")
{
window = itemShortcutWindow;
}
- else if (event.getId() == _("Emote"))
+ else if (event.getId() == "Emote")
{
window = emoteWindow;
}
- else if (event.getId() == _("Setup"))
+ else if (event.getId() == "Setup")
{
window = setupWindow;
}
diff --git a/src/gui/minimap.cpp b/src/gui/minimap.cpp
index 55c6b3c5..4347c9cc 100644
--- a/src/gui/minimap.cpp
+++ b/src/gui/minimap.cpp
@@ -129,8 +129,14 @@ void Minimap::draw(gcn::Graphics *graphics)
if (mMapImage->getWidth() > a.width ||
mMapImage->getHeight() > a.height)
{
+#ifdef TMWSERV_SUPPORT
+ const Vector &p = player_node->getPosition();
+ mapOriginX = (int) (((a.width) / 2) - (int) (p.x * mProportion) / 32);
+ mapOriginY = (int) (((a.height) / 2) - (int) (p.y * mProportion) / 32);
+#else
mapOriginX = (int) (((a.width) / 2) - (player_node->mX * mProportion));
mapOriginY = (int) (((a.height) / 2) - (player_node->mY * mProportion));
+#endif
const int minOriginX = a.width - mMapImage->getWidth();
const int minOriginY = a.height - mMapImage->getHeight();
@@ -181,10 +187,11 @@ void Minimap::draw(gcn::Graphics *graphics)
}
const int offset = (int) ((dotSize - 1) * mProportion);
+ const Vector &pos = being->getPosition();
graphics->fillRectangle(gcn::Rectangle(
- (int) (being->mX * mProportion) + mapOriginX - offset,
- (int) (being->mY * mProportion) + mapOriginY - offset,
+ (int) (pos.x * mProportion) / 32 + mapOriginX - offset,
+ (int) (pos.x * mProportion) / 32 + mapOriginY - offset,
dotSize, dotSize));
}
diff --git a/src/gui/ministatus.cpp b/src/gui/ministatus.cpp
index 25f17bd3..5bc25bdb 100644
--- a/src/gui/ministatus.cpp
+++ b/src/gui/ministatus.cpp
@@ -30,8 +30,7 @@
#include "../utils/stringutils.h"
-MiniStatusWindow::MiniStatusWindow():
- Window("")
+MiniStatusWindow::MiniStatusWindow()
{
setWindowName("MiniStatus");
setResizable(false);
@@ -39,19 +38,30 @@ MiniStatusWindow::MiniStatusWindow():
setTitleBarHeight(0);
mHpBar = new ProgressBar(1.0f, 100, 20, 0, 171, 34);
+#ifdef EATHENA_SUPPORT
mMpBar = new ProgressBar(1.0f, 100, 20, 26, 102, 230);
mXpBar = new ProgressBar(1.0f, 100, 20, 143, 192, 211);
+#endif
mHpBar->setPosition(0, 3);
+#ifdef EATHENA_SUPPORT
mMpBar->setPosition(mHpBar->getWidth() + 3, 3);
mXpBar->setPosition(mMpBar->getX() + mMpBar->getWidth() + 3, 3);
+#endif
add(mHpBar);
+#ifdef EATHENA_SUPPORT
add(mMpBar);
add(mXpBar);
+#endif
+#ifdef EATHENA_SUPPORT
setContentSize(mXpBar->getX() + mXpBar->getWidth(),
mXpBar->getY() + mXpBar->getHeight());
+#else
+ setContentSize(mHpBar->getX() + mHpBar->getWidth(),
+ mHpBar->getY() + mHpBar->getHeight());
+#endif
setDefaultSize(0, 0, getWidth(), getHeight());
loadWindowState();
}
@@ -77,11 +87,13 @@ extern volatile int tick_time;
void MiniStatusWindow::update()
{
// HP Bar coloration
- if (player_node->mHp < int(player_node->mMaxHp / 3))
+ int maxHp = player_node->getMaxHp();
+ int hp = player_node->getHp();
+ if (hp < int(maxHp / 3))
{
mHpBar->setColor(223, 32, 32); // Red
}
- else if (player_node->mHp < int((player_node->mMaxHp / 3) * 2))
+ else if (hp < int((maxHp / 3) * 2))
{
mHpBar->setColor(230, 171, 34); // Orange
}
@@ -90,18 +102,23 @@ void MiniStatusWindow::update()
mHpBar->setColor(0, 171, 34); // Green
}
+#ifdef EATHENA_SUPPORT
float xp = (float) player_node->getXp() / player_node->mXpForNextLevel;
if (xp != xp) xp = 0.0f; // check for NaN
if (xp < 0.0f) xp = 0.0f; // make sure the experience isn't negative (uninitialized pointer most likely)
if (xp > 1.0f) xp = 1.0f;
+#endif
- mHpBar->setProgress((float) player_node->mHp / player_node->mMaxHp);
+ mHpBar->setProgress((float) hp / maxHp);
+#ifdef EATHENA_SUPPORT
mMpBar->setProgress((float) player_node->mMp / player_node->mMaxMp);
mXpBar->setProgress(xp);
+#endif
// Update labels
- mHpBar->setText(toString(player_node->mHp));
+ mHpBar->setText(toString(player_node->getHp()));
+#ifdef EATHENA_SUPPORT
mMpBar->setText(toString(player_node->mMp));
std::stringstream updatedText;
@@ -121,11 +138,11 @@ void MiniStatusWindow::update()
*/
mXpBar->setText(updatedText.str());
+#endif
for (unsigned int i = 0; i < mIcons.size(); i++)
if (mIcons[i])
mIcons[i]->update(tick_time * 10);
-
}
void MiniStatusWindow::draw(gcn::Graphics *graphics)
@@ -137,7 +154,11 @@ void MiniStatusWindow::draw(gcn::Graphics *graphics)
void MiniStatusWindow::drawIcons(Graphics *graphics)
{
// Draw icons
+#ifdef TMWSERV_SUPPORT
+ int icon_x = mHpBar->getX() + mHpBar->getWidth() + 4;
+#else
int icon_x = mXpBar->getX() + mXpBar->getWidth() + 4;
+#endif
for (unsigned int i = 0; i < mIcons.size(); i++) {
if (mIcons[i]) {
mIcons[i]->draw(graphics, icon_x, 3);
diff --git a/src/gui/ministatus.h b/src/gui/ministatus.h
index f262a2a0..b69f9a14 100644
--- a/src/gui/ministatus.h
+++ b/src/gui/ministatus.h
@@ -66,8 +66,10 @@ class MiniStatusWindow : public Window
* Mini Status Bars
*/
ProgressBar *mHpBar;
+#ifdef EATHENA_SUPPORT
ProgressBar *mMpBar;
ProgressBar *mXpBar;
+#endif
std::vector<AnimatedSprite *> mIcons;
};
diff --git a/src/gui/npc_text.cpp b/src/gui/npc_text.cpp
index e6f039a0..48f2adb7 100644
--- a/src/gui/npc_text.cpp
+++ b/src/gui/npc_text.cpp
@@ -95,7 +95,7 @@ void NpcTextDialog::action(const gcn::ActionEvent &event)
current_npc->nextDialog();
addText("\n> Next\n");
} else if (mState == NPC_TEXT_STATE_CLOSE ||
- mState == NPC_TEXT_STATE_NEXT && !current_npc) {
+ (mState == NPC_TEXT_STATE_NEXT && !current_npc)) {
setText("");
setVisible(false);
if (current_npc) current_npc->handleDeath();
diff --git a/src/gui/npclistdialog.cpp b/src/gui/npclistdialog.cpp
index 78d43fd2..82e05fd5 100644
--- a/src/gui/npclistdialog.cpp
+++ b/src/gui/npclistdialog.cpp
@@ -76,6 +76,11 @@ std::string NpcListDialog::getElementAt(int i)
return mItems[i];
}
+void NpcListDialog::addItem(const std::string &item)
+{
+ mItems.push_back(item);
+}
+
void NpcListDialog::parseItems(const std::string &itemString)
{
std::istringstream iss(itemString);
diff --git a/src/gui/npclistdialog.h b/src/gui/npclistdialog.h
index 57d6247a..7e37c7e6 100644
--- a/src/gui/npclistdialog.h
+++ b/src/gui/npclistdialog.h
@@ -61,6 +61,11 @@ class NpcListDialog : public Window, public gcn::ActionListener,
std::string getElementAt(int i);
/**
+ * Adds an item to the option list.
+ */
+ void addItem(const std::string &);
+
+ /**
* Fills the options list for an NPC dialog.
*
* @param itemString A string with the options separated with colons.
diff --git a/src/gui/npcpostdialog.cpp b/src/gui/npcpostdialog.cpp
new file mode 100644
index 00000000..3a72b21b
--- /dev/null
+++ b/src/gui/npcpostdialog.cpp
@@ -0,0 +1,101 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "npcpostdialog.h"
+#include "textbox.h"
+#include "textfield.h"
+#include "button.h"
+#include "scrollarea.h"
+#include "chat.h"
+
+#include "../net/gameserver/player.h"
+#include "../utils/gettext.h"
+
+#include <guichan/widgets/label.hpp>
+
+NpcPostDialog::NpcPostDialog():
+ Window(_("NPC"))
+{
+ setContentSize(400, 180);
+
+ // create text field for receiver
+ gcn::Label *senderText = new gcn::Label("To:");
+ senderText->setPosition(5, 5);
+ mSender = new TextField();
+ mSender->setPosition(senderText->getWidth() + 5, 5);
+ mSender->setWidth(65);
+
+ // create button for sending
+ Button *sendButton = new Button(_("Send"), "send", this);
+ sendButton->setPosition(400-sendButton->getWidth(),
+ 170-sendButton->getHeight());
+ Button *cancelButton = new Button(_("Cancel"), "cancel", this);
+ cancelButton->setPosition(sendButton->getX() - (cancelButton->getWidth() + 2),
+ sendButton->getY());
+
+ // create textfield for letter
+ mText = new TextBox();
+ mText->setHeight(400 - (mSender->getHeight() + sendButton->getHeight()));
+ mText->setEditable(true);
+
+ // create scroll box for letter text
+ ScrollArea *scrollArea = new ScrollArea(mText);
+ scrollArea->setHorizontalScrollPolicy(gcn::ScrollArea::SHOW_NEVER);
+ scrollArea->setDimension(gcn::Rectangle(
+ 5, mSender->getHeight() + 5,
+ 380, 140 - (mSender->getHeight() + sendButton->getHeight())));
+
+ add(senderText);
+ add(mSender);
+ add(scrollArea);
+ add(sendButton);
+ add(cancelButton);
+
+ setLocationRelativeTo(getParent());
+}
+
+void NpcPostDialog::action(const gcn::ActionEvent &event)
+{
+ if (event.getId() == "send")
+ {
+ if (mSender->getText().empty() || mText->getText().empty())
+ {
+ chatWindow->chatLog("Failed to send as sender or letter invalid");
+ }
+ else
+ {
+ Net::GameServer::Player::sendLetter(mSender->getText(), mText->getText());
+ }
+ setVisible(false);
+ clear();
+ }
+ else if (event.getId() == "cancel")
+ {
+ setVisible(false);
+ clear();
+ }
+}
+
+void NpcPostDialog::clear()
+{
+ mSender->setText("");
+ mText->setText("");
+}
diff --git a/src/gui/npcpostdialog.h b/src/gui/npcpostdialog.h
new file mode 100644
index 00000000..1956c877
--- /dev/null
+++ b/src/gui/npcpostdialog.h
@@ -0,0 +1,55 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_GUI_NPCPOSTDIALOG_H
+#define _TMW_GUI_NPCPOSTDIALOG_H
+
+#include <guichan/actionlistener.hpp>
+
+#include "window.h"
+
+class TextBox;
+class TextField;
+
+class NpcPostDialog : public Window, public gcn::ActionListener
+{
+public:
+ /**
+ * Constructor
+ */
+ NpcPostDialog();
+
+ /**
+ * Called when receiving actions from the widgets.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ /**
+ * Clear the contents of the dialog
+ */
+ void clear();
+
+private:
+ TextBox *mText;
+ TextField *mSender;
+};
+
+#endif
diff --git a/src/gui/partywindow.cpp b/src/gui/partywindow.cpp
new file mode 100644
index 00000000..c4a1c780
--- /dev/null
+++ b/src/gui/partywindow.cpp
@@ -0,0 +1,145 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "partywindow.h"
+#include "chat.h"
+
+#include "widgets/avatar.h"
+
+#include "../utils/gettext.h"
+#include "../net/chatserver/party.h"
+
+PartyWindow::PartyWindow() : Window(_("Party"))
+{
+ setWindowName("Party");
+ setVisible(false);
+ setResizable(false);
+ setCaption(_("Party"));
+ setCloseButton(true);
+ setMinWidth(110);
+ setMinHeight(200);
+ setDefaultSize(620, 300, 110, 200);
+
+ loadWindowState();
+}
+
+PartyWindow::~PartyWindow()
+{
+ mPartyMembers.clear();
+}
+
+void PartyWindow::draw(gcn::Graphics *graphics)
+{
+ Window::draw(graphics);
+}
+
+void PartyWindow::addPartyMember(const std::string &memberName)
+{
+ // check to see if player is already in the party
+ PartyList::iterator itr = mPartyMembers.begin(),
+ itr_end = mPartyMembers.end();
+
+ while (itr != itr_end)
+ {
+ if ((*itr).name == memberName)
+ {
+ // already in the party, dont add
+ return;
+ }
+ ++itr;
+ }
+
+ // create new party member
+ PartyMember player;
+ player.name = memberName;
+ mPartyMembers.push_back(player);
+
+ // add avatar of the new member to window
+ Avatar *avatar = new Avatar(memberName);
+ add(avatar, 0, (mPartyMembers.size() - 1)*14);
+
+ // show the window
+ if (mPartyMembers.size() > 0)
+ {
+ setVisible(true);
+ }
+}
+
+void PartyWindow::removePartyMember(const std::string &memberName)
+{
+ // remove the party member
+ PartyList::iterator itr = mPartyMembers.begin(),
+ itr_end = mPartyMembers.end();
+
+ while (itr != itr_end)
+ {
+ if ((*itr).name == memberName)
+ {
+ mPartyMembers.erase(itr);
+ break;
+ }
+ ++itr;
+ }
+
+ // if no-one left, remove the party window
+ if (mPartyMembers.size() < 1)
+ {
+ setVisible(false);
+ }
+}
+
+void PartyWindow::showPartyInvite(const std::string &inviter)
+{
+ // check there isnt already an invite showing
+ if (mPartyInviter != "")
+ {
+ chatWindow->chatLog("Received party request, but one already exists",
+ BY_SERVER);
+ return;
+ }
+
+ // log invite
+ std::string msg = inviter + " has invited you to join their party";
+ chatWindow->chatLog(msg, BY_SERVER);
+
+ // show invite
+ acceptDialog = new ConfirmDialog("Accept Party Invite", msg, this);
+ acceptDialog->addActionListener(this);
+
+ mPartyInviter = inviter;
+}
+
+void PartyWindow::action(const gcn::ActionEvent &event)
+{
+ const std::string &eventId = event.getId();
+
+ // check if they accepted the invite
+ if (eventId == "yes")
+ {
+ chatWindow->chatLog("Accepted invite from " + mPartyInviter);
+ Net::ChatServer::Party::acceptInvite(mPartyInviter);
+ mPartyInviter = "";
+ }
+ else if (eventId == "no")
+ {
+ mPartyInviter = "";
+ }
+}
diff --git a/src/gui/partywindow.h b/src/gui/partywindow.h
new file mode 100644
index 00000000..e79bf392
--- /dev/null
+++ b/src/gui/partywindow.h
@@ -0,0 +1,96 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_PARTYWINDOW_H
+#define _TMW_PARTYWINDOW_H
+
+#include "window.h"
+#include "confirm_dialog.h"
+
+#include <string>
+#include <vector>
+
+#include <guichan/actionevent.hpp>
+#include <guichan/actionlistener.hpp>
+
+/**
+ * Party Member
+ * Used for storing players in the party
+ */
+struct PartyMember
+{
+ std::string name;
+ int vitality;
+};
+
+/**
+ * Party Window.
+ *
+ * \ingroup Interface
+ */
+class PartyWindow : public Window, gcn::ActionListener
+{
+ public:
+ /**
+ * Constructor.
+ */
+ PartyWindow();
+
+ /**
+ * Release all the players created
+ */
+ ~PartyWindow();
+
+ /**
+ * Draws the party window
+ */
+ void draw(gcn::Graphics *graphics);
+
+ /**
+ * Add party member
+ */
+ void addPartyMember(const std::string &memberName);
+
+ /**
+ * Remove party member
+ */
+ void removePartyMember(const std::string &memberName);
+
+ /**
+ * Show party invite
+ */
+ void showPartyInvite(const std::string &inviter);
+
+ /**
+ * Handle events
+ */
+ void action(const gcn::ActionEvent &event);
+
+ private:
+ typedef std::vector<PartyMember> PartyList;
+ PartyList mPartyMembers;
+ std::string mPartyInviter;
+ ConfirmDialog *acceptDialog;
+};
+
+extern PartyWindow *partyWindow;
+
+#endif
diff --git a/src/gui/passwordfield.h b/src/gui/passwordfield.h
index 42f8d187..86195bd1 100644
--- a/src/gui/passwordfield.h
+++ b/src/gui/passwordfield.h
@@ -22,8 +22,6 @@
#ifndef PASSWORDFIELD_H
#define PASSWORDFIELD_H
-#include <string>
-
#include "textfield.h"
/**
diff --git a/src/gui/playerbox.cpp b/src/gui/playerbox.cpp
index f99ce6ef..2bfa798c 100644
--- a/src/gui/playerbox.cpp
+++ b/src/gui/playerbox.cpp
@@ -81,10 +81,14 @@ void PlayerBox::draw(gcn::Graphics *graphics)
if (mPlayer)
{
// Draw character
- int x, y, bs;
- bs = getFrameSize();
- x = getWidth() / 2 - 16 + bs;
- y = getHeight() / 2 + bs;
+ const int bs = getFrameSize();
+#ifdef TMWSERV_SUPPORT
+ const int x = getWidth() / 2 + bs;
+ const int y = getHeight() - bs - 8;
+ mPlayer->draw(static_cast<Graphics*>(graphics), x, y);
+#else
+ const int x = getWidth() / 2 - 16 + bs;
+ const int y = getHeight() / 2 + bs;
for (int i = 0; i < Being::VECTOREND_SPRITE; i++)
{
if (mPlayer->getSprite(i))
@@ -92,6 +96,7 @@ void PlayerBox::draw(gcn::Graphics *graphics)
mPlayer->getSprite(i)->draw(static_cast<Graphics*>(graphics), x, y);
}
}
+#endif
}
if (config.getValue("guialpha", 0.8) != mAlpha)
diff --git a/src/gui/popupmenu.cpp b/src/gui/popupmenu.cpp
index 62e44794..ced44f42 100644
--- a/src/gui/popupmenu.cpp
+++ b/src/gui/popupmenu.cpp
@@ -36,8 +36,10 @@
#include "../npc.h"
#include "../player_relations.h"
+#ifdef EATHENA_SUPPORT
#include "../net/messageout.h"
-#include "../net/protocol.h"
+#include "../net/ea/protocol.h"
+#endif
#include "../resources/itemdb.h"
@@ -102,6 +104,8 @@ void PopupMenu::showPopup(int x, int y, Being *being)
//mBrowserBox->addRow(_("@@follow|Follow ") + name + "@@");
//mBrowserBox->addRow(_("@@buddy|Add ") + name + " to Buddy List@@");
+ mBrowserBox->addRow(strprintf(_("@@guild|Invite %s@@"), name.c_str()));
+ mBrowserBox->addRow(strprintf(_("@@party|Invite %s to join your party@@"), name.c_str()));
mBrowserBox->addRow("##3---");
mBrowserBox->addRow(strprintf(_("@@party-invite|Invite %s to party@@"), name.c_str()));
@@ -163,7 +167,7 @@ void PopupMenu::handleLink(const std::string& link)
player_node->trade(being);
tradePartnerName = being->getName();
}
-
+#ifdef EATHENA_SUPPORT
// Attack action
else if (link == "attack" &&
being &&
@@ -171,7 +175,7 @@ void PopupMenu::handleLink(const std::string& link)
{
player_node->attack(being, true);
}
-
+#endif
else if (link == "unignore" &&
being &&
being->getType() == Being::PLAYER)
@@ -199,7 +203,21 @@ void PopupMenu::handleLink(const std::string& link)
{
player_relations.setRelation(being->getName(), PlayerRelation::FRIEND);
}
+#ifdef TMWSERV_SUPPORT
+ // Guild action
+ else if (link == "guild" &&
+ being != NULL &&
+ being->getType() == Being::PLAYER)
+ {
+ player_node->inviteToGuild(being);
+ }
+ // Add player to your party
+ else if (link == "party")
+ {
+ player_node->inviteToParty(being->getName());
+ }
+#endif
/*
// Follow Player action
else if (link == "follow")
@@ -232,6 +250,9 @@ void PopupMenu::handleLink(const std::string& link)
assert(mItem);
if (mItem->isEquipment())
{
+#ifdef TMWSERV_SUPPORT
+ player_node->equipItem(mItem);
+#else
if (mItem->isEquipped())
{
player_node->unequipItem(mItem);
@@ -240,10 +261,15 @@ void PopupMenu::handleLink(const std::string& link)
{
player_node->equipItem(mItem);
}
+#endif
}
else
{
+#ifdef TMWSERV_SUPPORT
+ player_node->useItem(mItem->getInvIndex());
+#else
player_node->useItem(mItem);
+#endif
}
}
@@ -252,10 +278,15 @@ void PopupMenu::handleLink(const std::string& link)
chatWindow->addItemText(mItem->getInfo().getName());
}
+ else if (link == "split")
+ {
+ new ItemAmountWindow(AMOUNT_ITEM_SPLIT, inventoryWindow, mItem);
+ }
else if (link == "drop")
{
new ItemAmountWindow(AMOUNT_ITEM_DROP, inventoryWindow, mItem);
}
+#ifdef EATHENA_SUPPORT
else if (link == "party-invite" &&
being &&
being->getType() == Being::PLAYER)
@@ -264,6 +295,7 @@ void PopupMenu::handleLink(const std::string& link)
outMsg.writeInt16(CMSG_PARTY_INVITE);
outMsg.writeInt32(being->getId());
}
+#endif
// Unknown actions
else
@@ -286,15 +318,23 @@ void PopupMenu::showPopup(int x, int y, Item *item)
if (item->isEquipment())
{
+#ifdef TMWSERV_SUPPORT
+ mBrowserBox->addRow(_("@@use|Equip@@"));
+#else
if (item->isEquipped())
mBrowserBox->addRow(_("@@use|Unequip@@"));
else
mBrowserBox->addRow(_("@@use|Equip@@"));
+#endif
}
else
mBrowserBox->addRow(_("@@use|Use@@"));
mBrowserBox->addRow(_("@@drop|Drop@@"));
+#ifdef TMWSERV_SUPPORT
+ if (!item->isEquipment())
+ mBrowserBox->addRow(_("@@split|Split@@"));
+#endif
mBrowserBox->addRow(_("@@chat|Add to Chat@@"));
mBrowserBox->addRow("##3---");
mBrowserBox->addRow(_("@@cancel|Cancel@@"));
diff --git a/src/gui/progressbar.cpp b/src/gui/progressbar.cpp
index 0f59371a..85f21604 100644
--- a/src/gui/progressbar.cpp
+++ b/src/gui/progressbar.cpp
@@ -41,6 +41,9 @@ ProgressBar::ProgressBar(float progress,
mRed(red), mGreen(green), mBlue(blue),
mRedToGo(red), mGreenToGo(green), mBlueToGo(blue)
{
+ mProgressToGo = mProgress = 0.0f;
+ mSmoothProgress = mSmoothColorChange = true;
+
setProgress(progress);
setWidth(width);
setHeight(height);
@@ -90,13 +93,31 @@ ProgressBar::~ProgressBar()
void ProgressBar::logic()
{
- // Smoothly changing the color for a nicer effect.
- if (mRedToGo > mRed) mRed++;
- if (mRedToGo < mRed) mRed--;
- if (mGreenToGo > mGreen) mGreen++;
- if (mGreenToGo < mGreen) mGreen--;
- if (mBlueToGo > mBlue) mBlue++;
- if (mBlueToGo < mBlue) mBlue--;
+ if (mSmoothColorChange)
+ {
+ // Smoothly changing the color for a nicer effect.
+ if (mRedToGo > mRed) mRed++;
+ if (mRedToGo < mRed) mRed--;
+ if (mGreenToGo > mGreen) mGreen++;
+ if (mGreenToGo < mGreen) mGreen--;
+ if (mBlueToGo > mBlue) mBlue++;
+ if (mBlueToGo < mBlue) mBlue--;
+ }
+ else
+ {
+ mRed = mRedToGo;
+ mGreen = mGreenToGo;
+ mBlue = mBlueToGo;
+ }
+
+ if (mSmoothProgress)
+ {
+ // Smoothly showing the progressbar changes.
+ if (mProgressToGo > mProgress) mProgress = mProgress + 0.005f;
+ if (mProgressToGo < mProgress) mProgress = mProgress - 0.005f;
+ }
+ else
+ mProgress = mProgressToGo;
}
void ProgressBar::draw(gcn::Graphics *graphics)
@@ -149,9 +170,9 @@ void ProgressBar::draw(gcn::Graphics *graphics)
void ProgressBar::setProgress(float progress)
{
- if (progress < 0.0f) mProgress = 0.0;
- else if (progress > 1.0f) mProgress = 1.0;
- else mProgress = progress;
+ if (progress < 0.0f) mProgressToGo = 0.0;
+ else if (progress > 1.0f) mProgressToGo = 1.0;
+ else mProgressToGo = progress;
}
void ProgressBar::setColor(Uint8 red, Uint8 green, Uint8 blue)
diff --git a/src/gui/progressbar.h b/src/gui/progressbar.h
index 2c1b22da..49bc3edd 100644
--- a/src/gui/progressbar.h
+++ b/src/gui/progressbar.h
@@ -102,10 +102,27 @@ class ProgressBar : public gcn::Widget
const std::string &text() const
{ return mText; }
+ /**
+ * Set wether the progress is moved smoothly.
+ */
+ void setSmoothProgress(bool smoothProgress)
+ { mSmoothProgress = smoothProgress; }
+
+ /**
+ * Set wether the color changing is made smoothly.
+ */
+ void setSmoothColorChange(bool smoothColorChange)
+ { mSmoothColorChange = smoothColorChange; }
+
+
private:
- float mProgress;
+ float mProgress, mProgressToGo;
+ bool mSmoothProgress;
+
Uint8 mRed, mGreen, mBlue;
Uint8 mRedToGo, mGreenToGo, mBlueToGo;
+ bool mSmoothColorChange;
+
std::string mText;
static ImageRect mBorder;
diff --git a/src/gui/quitdialog.cpp b/src/gui/quitdialog.cpp
new file mode 100644
index 00000000..563ed34a
--- /dev/null
+++ b/src/gui/quitdialog.cpp
@@ -0,0 +1,135 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "quitdialog.h"
+#include <iostream>
+#include <string>
+
+#include <guichan/widgets/label.hpp>
+
+#include "../main.h"
+
+#include "button.h"
+#include "radiobutton.h"
+
+#include "../utils/gettext.h"
+
+QuitDialog::QuitDialog(bool* quitGame, QuitDialog** pointerToMe):
+ Window(_("Quit"), true, NULL), mQuitGame(quitGame), mMyPointer(pointerToMe)
+{
+
+ mLogoutQuit = new RadioButton(_("Quit"), "quitdialog");
+ mForceQuit = new RadioButton(_("Quit"), "quitdialog");
+ mSwitchAccountServer = new RadioButton(_("Switch server"), "quitdialog");
+ mSwitchCharacter = new RadioButton(_("Switch character"), "quitdialog");
+ mOkButton = new Button(_("Ok"), "ok", this);
+ mCancelButton = new Button(_("Cancel"), "cancel", this);
+
+ setContentSize(200, 91);
+
+ mLogoutQuit->setPosition(5, 5);
+ mForceQuit->setPosition(5, 5);
+ mSwitchAccountServer->setPosition(5, 14 + mLogoutQuit->getHeight());
+ mSwitchCharacter->setPosition(5,
+ 23 + mLogoutQuit->getHeight() + mSwitchAccountServer->getHeight());
+ mCancelButton->setPosition(
+ 200 - mCancelButton->getWidth() - 5,
+ 91 - mCancelButton->getHeight() - 5);
+ mOkButton->setPosition(
+ mCancelButton->getX() - mOkButton->getWidth() - 5,
+ 91 - mOkButton->getHeight() - 5);
+
+ //All states, when we're not logged in to someone.
+ if (state == STATE_CHOOSE_SERVER ||
+ state == STATE_CONNECT_ACCOUNT ||
+ state == STATE_LOGIN ||
+ state == STATE_LOGIN_ATTEMPT ||
+ state == STATE_UPDATE)
+ {
+ mForceQuit->setSelected(true);
+ add(mForceQuit);
+ }
+ else
+ {
+ // Only added if we are connected to an accountserver or gameserver
+ mLogoutQuit->setSelected(true);
+ add(mLogoutQuit);
+ add(mSwitchAccountServer);
+
+ // Only added if we are connected to a gameserver
+ if (state == STATE_GAME) add(mSwitchCharacter);
+ }
+
+ add(mOkButton);
+ add(mCancelButton);
+
+ setLocationRelativeTo(getParent());
+ setVisible(true);
+
+ mOkButton->requestFocus();
+
+}
+
+QuitDialog::~QuitDialog()
+{
+ if (mMyPointer) *mMyPointer = NULL;
+ // Optional widgets, so delete them by hand.
+ delete mForceQuit;
+ delete mLogoutQuit;
+ delete mSwitchAccountServer;
+ delete mSwitchCharacter;
+}
+
+void
+QuitDialog::action(const gcn::ActionEvent &event)
+{
+ if (event.getId() == "ok")
+ {
+ if (mForceQuit->isSelected())
+ {
+ state = STATE_FORCE_QUIT;
+ }
+ else if (mLogoutQuit->isSelected())
+ {
+ if ((state == STATE_GAME) && (mQuitGame))
+ {
+ *mQuitGame = true;
+ }
+ state = STATE_EXIT;
+ }
+ else if (mSwitchAccountServer->isSelected())
+ {
+ if ((state == STATE_GAME) && (mQuitGame))
+ {
+ *mQuitGame = true;
+ }
+ state = STATE_SWITCH_ACCOUNTSERVER_ATTEMPT;
+ }
+ else if (mSwitchCharacter->isSelected())
+ {
+ if (mQuitGame) *mQuitGame = true;
+
+ state = STATE_SWITCH_CHARACTER;
+ }
+
+ }
+ scheduleDelete();
+}
diff --git a/src/gui/quitdialog.h b/src/gui/quitdialog.h
new file mode 100644
index 00000000..018f1e52
--- /dev/null
+++ b/src/gui/quitdialog.h
@@ -0,0 +1,70 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_QUITDIALOG_H
+#define _TMW_QUITDIALOG_H
+
+#include <iosfwd>
+#include <guichan/actionlistener.hpp>
+
+#include "window.h"
+#include "../guichanfwd.h"
+#include "../main.h"
+
+/**
+ * The quit dialog.
+ *
+ * \ingroup Interface
+ */
+class QuitDialog : public Window, public gcn::ActionListener {
+ public:
+ /**
+ * Constructor
+ *
+ * @quitGame; to be used for getting out of the while loop in Game
+ * @pointerToMe; will be set to NULL when the QuitDialog is destroyed
+ */
+ QuitDialog(bool* quitGame, QuitDialog** pointerToMe);
+
+ /**
+ * Destructor
+ */
+ ~QuitDialog();
+
+ /**
+ * Called when receiving actions from the widgets.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ private:
+ gcn::RadioButton *mLogoutQuit;
+ gcn::RadioButton *mForceQuit;
+ gcn::RadioButton *mSwitchAccountServer;
+ gcn::RadioButton *mSwitchCharacter;
+ gcn::Button *mOkButton;
+ gcn::Button *mCancelButton;
+
+ bool* mQuitGame;
+ QuitDialog** mMyPointer;
+
+};
+
+#endif
diff --git a/src/gui/register.cpp b/src/gui/register.cpp
index c2190501..216ac211 100644
--- a/src/gui/register.cpp
+++ b/src/gui/register.cpp
@@ -41,19 +41,6 @@
#include "../utils/strprintf.h"
#include "../utils/stringutils.h"
-/**
- * Listener used while dealing with wrong data. It is used to direct the focus
- * to the field which contained wrong data when the Ok button was pressed on
- * the error notice.
- */
-class WrongDataNoticeListener : public gcn::ActionListener {
- public:
- void setTarget(gcn::TextField *textField);
- void action(const gcn::ActionEvent &event);
- private:
- gcn::TextField *mTarget;
-};
-
void WrongDataNoticeListener::setTarget(gcn::TextField *textField)
{
mTarget = textField;
@@ -76,15 +63,19 @@ RegisterDialog::RegisterDialog(LoginData *loginData):
gcn::Label *userLabel = new gcn::Label(_("Name:"));
gcn::Label *passwordLabel = new gcn::Label(_("Password:"));
gcn::Label *confirmLabel = new gcn::Label(_("Confirm:"));
+#ifdef EATHENA_SUPPORT
gcn::Label *serverLabel = new gcn::Label(_("Server:"));
gcn::Label *portLabel = new gcn::Label(_("Port:"));
+#endif
mUserField = new TextField(loginData->username);
mPasswordField = new PasswordField(loginData->password);
mConfirmField = new PasswordField;
+#ifdef EATHENA_SUPPORT
mServerField = new TextField(loginData->hostname);
mPortField = new TextField(toString(loginData->port));
mMaleButton = new RadioButton(_("Male"), "sex", true);
mFemaleButton = new RadioButton(_("Female"), "sex", false);
+#endif
mRegisterButton = new Button(_("Register"), "register", this);
mCancelButton = new Button(_("Cancel"), "cancel", this);
@@ -93,15 +84,19 @@ RegisterDialog::RegisterDialog(LoginData *loginData):
place(0, 0, userLabel);
place(0, 1, passwordLabel);
place(0, 2, confirmLabel);
+#ifdef EATHENA_SUPPORT
place(1, 3, mMaleButton);
place(2, 3, mFemaleButton);
place(0, 4, serverLabel);
place(0, 5, portLabel);
+#endif
place(1, 0, mUserField, 3).setPadding(2);
place(1, 1, mPasswordField, 3).setPadding(2);
place(1, 2, mConfirmField, 3).setPadding(2);
+#ifdef EATHENA_SUPPORT
place(1, 4, mServerField, 3).setPadding(2);
place(1, 5, mPortField, 3).setPadding(2);
+#endif
place = getPlacer(0, 2);
place(1, 0, mRegisterButton);
place(2, 0, mCancelButton);
@@ -110,8 +105,10 @@ RegisterDialog::RegisterDialog(LoginData *loginData):
mUserField->addKeyListener(this);
mPasswordField->addKeyListener(this);
mConfirmField->addKeyListener(this);
+#ifdef EATHENA_SUPPORT
mServerField->addKeyListener(this);
mPortField->addKeyListener(this);
+#endif
/* TODO:
* This is a quick and dirty way to respond to the ENTER key, regardless of
@@ -121,14 +118,18 @@ RegisterDialog::RegisterDialog(LoginData *loginData):
mUserField->setActionEventId("register");
mPasswordField->setActionEventId("register");
mConfirmField->setActionEventId("register");
- mServerField->setActionEventId("register");
- mPortField->setActionEventId("register");
mUserField->addActionListener(this);
mPasswordField->addActionListener(this);
mConfirmField->addActionListener(this);
+
+#ifdef EATHENA_SUPPORT
+ mServerField->setActionEventId("register");
+ mPortField->setActionEventId("register");
+
mServerField->addActionListener(this);
mPortField->addActionListener(this);
+#endif
setLocationRelativeTo(getParent());
setVisible(true);
@@ -147,7 +148,7 @@ void RegisterDialog::action(const gcn::ActionEvent &event)
{
if (event.getId() == "cancel")
{
- state = LOGIN_STATE;
+ state = STATE_LOGIN;
}
else if (event.getId() == "register" && canSubmit())
{
@@ -196,6 +197,8 @@ void RegisterDialog::action(const gcn::ActionEvent &event)
error = 2;
}
+ // TODO: Check if a valid email address was given
+
if (error > 0)
{
if (error == 1)
@@ -211,23 +214,30 @@ void RegisterDialog::action(const gcn::ActionEvent &event)
mWrongDataNoticeListener->setTarget(this->mPasswordField);
}
- OkDialog *mWrongRegisterNotice =
- new OkDialog(_("Error"), errorMsg);
- mWrongRegisterNotice->addActionListener(mWrongDataNoticeListener);
+ OkDialog *dlg = new OkDialog(_("Error"), errorMsg);
+ dlg->addActionListener(mWrongDataNoticeListener);
}
else
{
// No errors detected, register the new user.
mRegisterButton->setEnabled(false);
- mLoginData->hostname = mServerField->getText();
- mLoginData->port = getUShort(mPortField->getText());
mLoginData->username = mUserField->getText();
mLoginData->password = mPasswordField->getText();
+#ifdef EATHENA_SUPPORT
+ mLoginData->hostname = mServerField->getText();
+ mLoginData->port = getUShort(mPortField->getText());
mLoginData->username += mFemaleButton->isSelected() ? "_F" : "_M";
+#else
+ mLoginData->email = mEmailField->getText();
+#endif
mLoginData->registerLogin = true;
- state = ACCOUNT_STATE;
+#ifdef TMWSERV_SUPPORT
+ state = STATE_REGISTER_ATTEMPT;
+#else
+ state = STATE_ACCOUNT;
+#endif
}
}
}
@@ -242,11 +252,14 @@ bool RegisterDialog::canSubmit() const
return !mUserField->getText().empty() &&
!mPasswordField->getText().empty() &&
!mConfirmField->getText().empty() &&
+#ifdef EATHENA_SUPPORT
!mServerField->getText().empty() &&
isUShort(mPortField->getText()) &&
- state == REGISTER_STATE;
+#endif
+ state == STATE_REGISTER;
}
+#ifdef EATHENA_SUPPORT
bool RegisterDialog::isUShort(const std::string &str)
{
if (str.empty())
@@ -280,3 +293,4 @@ unsigned short RegisterDialog::getUShort(const std::string &str)
}
return static_cast<unsigned short>(l);
}
+#endif
diff --git a/src/gui/register.h b/src/gui/register.h
index 9588e07e..fde82a40 100644
--- a/src/gui/register.h
+++ b/src/gui/register.h
@@ -31,7 +31,19 @@
class LoginData;
class OkDialog;
-class WrongDataNoticeListener;
+
+/**
+ * Listener used while dealing with wrong data. It is used to direct the focus
+ * to the field which contained wrong data when the Ok button was pressed on
+ * the error notice.
+ */
+class WrongDataNoticeListener : public gcn::ActionListener {
+ public:
+ void setTarget(gcn::TextField *textField);
+ void action(const gcn::ActionEvent &event);
+ private:
+ gcn::TextField *mTarget;
+};
/**
* The registration dialog.
@@ -72,6 +84,7 @@ class RegisterDialog : public Window, public gcn::ActionListener,
*/
bool canSubmit() const;
+#ifdef EATHENA_SUPPORT
/**
* Function to decide whether string is an unsigned short or not
*
@@ -89,17 +102,24 @@ class RegisterDialog : public Window, public gcn::ActionListener,
* @return the value str represents
*/
static unsigned short getUShort(const std::string &str);
+#endif
gcn::TextField *mUserField;
gcn::TextField *mPasswordField;
gcn::TextField *mConfirmField;
+#ifdef EATHENA_SUPPORT
gcn::TextField *mServerField;
gcn::TextField *mPortField;
+#else
+ gcn::TextField *mEmailField;
+#endif
gcn::Button *mRegisterButton;
gcn::Button *mCancelButton;
+#ifdef EATHENA_SUPPORT
gcn::RadioButton *mMaleButton;
gcn::RadioButton *mFemaleButton;
+#endif
WrongDataNoticeListener *mWrongDataNoticeListener;
diff --git a/src/gui/sell.cpp b/src/gui/sell.cpp
index dad6af21..957ff861 100644
--- a/src/gui/sell.cpp
+++ b/src/gui/sell.cpp
@@ -34,14 +34,23 @@
#include "../units.h"
#include "../net/messageout.h"
-#include "../net/protocol.h"
+#ifdef TMWSERV_SUPPORT
+#include "../net/gameserver/player.h"
+#else
+#include "../net/ea/protocol.h"
+#endif
#include "../utils/gettext.h"
#include "../utils/strprintf.h"
+#ifdef TMWSERV_SUPPORT
+SellDialog::SellDialog():
+ Window(_("Sell")),
+#else
SellDialog::SellDialog(Network *network):
Window(_("Sell")),
mNetwork(network),
+#endif
mMaxItems(0), mAmountItems(0)
{
setWindowName("Sell");
@@ -112,6 +121,16 @@ void SellDialog::reset()
updateButtonsAndLabels();
}
+#ifdef TMWSERV_SUPPORT
+
+void SellDialog::addItem(int item, int amount, int price)
+{
+ mShopItems->addItem(item, amount, price);
+ mShopItemList->adjustSize();
+}
+
+#else
+
void SellDialog::addItem(const Item *item, int price)
{
if (!item)
@@ -124,6 +143,8 @@ void SellDialog::addItem(const Item *item, int price)
mShopItemList->adjustSize();
}
+#endif
+
void SellDialog::action(const gcn::ActionEvent &event)
{
int selectedItem = mShopItemList->getSelected();
@@ -162,12 +183,17 @@ void SellDialog::action(const gcn::ActionEvent &event)
else if (event.getId() == "sell" && mAmountItems > 0
&& mAmountItems <= mMaxItems)
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::tradeWithNPC
+ (mShopItems->at(selectedItem)->getId(), mAmountItems);
+#else
// Attempt sell
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_SELL_REQUEST);
outMsg.writeInt16(8);
outMsg.writeInt16(mShopItems->at(selectedItem)->getInvIndex());
outMsg.writeInt16(mAmountItems);
+#endif
mMaxItems -= mAmountItems;
mShopItems->getShop()->at(selectedItem)->setQuantity(mMaxItems);
diff --git a/src/gui/sell.h b/src/gui/sell.h
index c11a7b7c..f64a6fd5 100644
--- a/src/gui/sell.h
+++ b/src/gui/sell.h
@@ -30,7 +30,9 @@
#include "window.h"
class Item;
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
class ShopItems;
class ShopListBox;
@@ -47,7 +49,11 @@ class SellDialog : public Window, gcn::ActionListener, gcn::SelectionListener
*
* @see Window::Window
*/
+#ifdef TMWSERV_SUPPORT
+ SellDialog();
+#else
SellDialog(Network *network);
+#endif
/**
* Destructor
@@ -62,7 +68,11 @@ class SellDialog : public Window, gcn::ActionListener, gcn::SelectionListener
/**
* Adds an item to the inventory.
*/
+#ifdef TMWSERV_SUPPORT
+ void addItem(int item, int amount, int price);
+#else
void addItem(const Item *item, int price);
+#endif
/**
* Called when receiving actions from the widgets.
@@ -87,7 +97,9 @@ class SellDialog : public Window, gcn::ActionListener, gcn::SelectionListener
*/
void updateButtonsAndLabels();
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
gcn::Button *mSellButton;
gcn::Button *mQuitButton;
gcn::Button *mIncreaseButton;
diff --git a/src/gui/serverdialog.cpp b/src/gui/serverdialog.cpp
new file mode 100644
index 00000000..a8074b0c
--- /dev/null
+++ b/src/gui/serverdialog.cpp
@@ -0,0 +1,214 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <cstdlib>
+#include <iostream>
+#include <string>
+
+#include <guichan/widgets/label.hpp>
+
+#include "serverdialog.h"
+
+#include "button.h"
+#include "listbox.h"
+#include "ok_dialog.h"
+#include "scrollarea.h"
+#include "textfield.h"
+
+#include "widgets/layout.h"
+
+#include "../configuration.h"
+#include "../log.h"
+#include "../logindata.h"
+#include "../main.h"
+
+#include "../utils/gettext.h"
+#include "../utils/stringutils.h"
+
+const short MAX_SERVERLIST = 5;
+
+int ServersListModel::getNumberOfElements()
+{
+ return servers.size();
+}
+
+std::string ServersListModel::getElementAt(int elementIndex)
+{
+ std::string myServer = "";
+ myServer = servers.at(elementIndex).serverName;
+ myServer += ":";
+ myServer += toString(servers.at(elementIndex).port);
+ return myServer;
+}
+
+void ServersListModel::addFirstElement(Server server)
+{
+ // Equivalent to push_front
+ std::vector<Server>::iterator MyIterator = servers.begin();
+ servers.insert(MyIterator, 1, server);
+}
+
+void ServersListModel::addElement(Server server)
+{
+ servers.push_back(server);
+}
+
+ServerDialog::ServerDialog(LoginData *loginData):
+ Window(_("Choose your server")), mLoginData(loginData)
+{
+ gcn::Label *serverLabel = new gcn::Label(_("Server:"));
+ gcn::Label *portLabel = new gcn::Label(_("Port:"));
+ mServerNameField = new TextField(mLoginData->hostname);
+ mPortField = new TextField(toString(mLoginData->port));
+
+ // Add the most used servers from config
+ mMostUsedServersListModel = new ServersListModel();
+ Server currentServer;
+ std::string currentConfig = "";
+ for (int i=0; i<=MAX_SERVERLIST; i++)
+ {
+ currentServer.serverName = "";
+ currentServer.port = 0;
+
+ currentConfig = "MostUsedServerName" + toString(i);
+ currentServer.serverName = config.getValue(currentConfig, "");
+
+ currentConfig = "MostUsedServerPort" + toString(i);
+ currentServer.port = (short)atoi(config.getValue(currentConfig, "").c_str());
+ if (!currentServer.serverName.empty() || currentServer.port != 0)
+ {
+ mMostUsedServersListModel->addElement(currentServer);
+ }
+ }
+
+ mMostUsedServersListBox = new ListBox(NULL);
+ mMostUsedServersListBox->setListModel(mMostUsedServersListModel);
+ mMostUsedServersScrollArea = new ScrollArea();
+ mMostUsedServersDropDown = new DropDown(mMostUsedServersListModel,
+ mMostUsedServersScrollArea, mMostUsedServersListBox);
+
+ mOkButton = new Button(_("Ok"), "connect", this);
+ mCancelButton = new Button(_("Cancel"), "cancel", this);
+
+ mServerNameField->setActionEventId("connect");
+ mPortField->setActionEventId("connect");
+ mMostUsedServersDropDown->setActionEventId("changeSelection");
+
+ mServerNameField->addActionListener(this);
+ mPortField->addActionListener(this);
+ mMostUsedServersDropDown->addActionListener(this);
+
+ place(0, 0, serverLabel);
+ place(0, 1, portLabel);
+ place(1, 0, mServerNameField, 3).setPadding(2);
+ place(1, 1, mPortField, 3).setPadding(2);
+ place(0, 2, mMostUsedServersDropDown, 4).setPadding(2);
+ place(2, 3, mOkButton);
+ place(3, 3, mCancelButton);
+ reflowLayout(250, 0);
+
+ setLocationRelativeTo(getParent());
+ setVisible(true);
+
+ if (mServerNameField->getText().empty()) {
+ mServerNameField->requestFocus();
+ } else {
+ if (mPortField->getText().empty()) {
+ mPortField->requestFocus();
+ } else {
+ mOkButton->requestFocus();
+ }
+ }
+}
+
+ServerDialog::~ServerDialog()
+{
+ delete mMostUsedServersListModel;
+ delete mMostUsedServersScrollArea;
+}
+
+void
+ServerDialog::action(const gcn::ActionEvent &event)
+{
+ if (event.getId() == "ok")
+ {
+ // Give focus back to the server dialog.
+ mServerNameField->requestFocus();
+ }
+ else if (event.getId() == "changeSelection")
+ {
+ // Change the textField Values according to new selection
+ Server myServer = mMostUsedServersListModel->getServer
+ (mMostUsedServersListBox->getSelected());
+ mServerNameField->setText(myServer.serverName);
+ mPortField->setText(toString(myServer.port));
+ }
+ else if (event.getId() == "connect")
+ {
+ // Check login
+ if (mServerNameField->getText().empty() || mPortField->getText().empty())
+ {
+ OkDialog *dlg = new OkDialog(_("Error"),
+ _("Please type both the address and the port of a server."));
+ dlg->addActionListener(this);
+ }
+ else
+ {
+ mLoginData->hostname = mServerNameField->getText();
+ mLoginData->port = (short) atoi(mPortField->getText().c_str());
+ mOkButton->setEnabled(false);
+ mCancelButton->setEnabled(false);
+
+ // First, look if the entry is a new one.
+ Server currentServer;
+ bool newEntry = true;
+ for (int i = 0; i < mMostUsedServersListModel->getNumberOfElements(); i++)
+ {
+ currentServer = mMostUsedServersListModel->getServer(i);
+ if (currentServer.serverName == mLoginData->hostname &&
+ currentServer.port == mLoginData->port)
+ newEntry = false;
+ }
+ // Then, add it to config if it's really new
+ currentServer.serverName = mLoginData->hostname;
+ currentServer.port = mLoginData->port;
+ if (newEntry)
+ mMostUsedServersListModel->addFirstElement(currentServer);
+ // Write the entry in config
+ std::string currentConfig = "";
+ for (int i = 0; i < mMostUsedServersListModel->getNumberOfElements(); i++)
+ {
+ currentServer = mMostUsedServersListModel->getServer(i);
+
+ currentConfig = "MostUsedServerName" + toString(i);
+ config.setValue(currentConfig, currentServer.serverName);
+
+ currentConfig = "MostUsedServerPort" + toString(i);
+ config.setValue(currentConfig, toString(currentServer.port));
+ }
+ state = STATE_CONNECT_ACCOUNT;
+ }
+ }
+ else if (event.getId() == "cancel")
+ {
+ state = STATE_FORCE_QUIT;
+ }
+}
diff --git a/src/gui/serverdialog.h b/src/gui/serverdialog.h
new file mode 100644
index 00000000..268b1baf
--- /dev/null
+++ b/src/gui/serverdialog.h
@@ -0,0 +1,123 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_SERVERDIALOG_H
+#define _TMW_SERVERDIALOG_H
+
+#include <iosfwd>
+#include <vector>
+
+#include <guichan/actionlistener.hpp>
+#include <guichan/listmodel.hpp>
+#include "./widgets/dropdown.h"
+
+#include "login.h"
+#include "window.h"
+
+#include "../guichanfwd.h"
+
+#include "../net/network.h"
+
+class LoginData;
+
+/**
+ * A server structure to keep pairs of servers and ports.
+ */
+struct Server {
+ Server():
+ serverName(""),
+ port(0) {};
+
+ std::string serverName;
+ short port;
+};
+
+/**
+ * Server and Port List Model
+ */
+class ServersListModel : public gcn::ListModel
+{
+ public:
+ /**
+ * Used to get number of line in the list
+ */
+ int getNumberOfElements();
+ /**
+ * Used to get an element from the list
+ */
+ std::string getElementAt(int elementIndex);
+ /**
+ * Used to get the corresponding Server struct
+ */
+ Server getServer(int elementIndex) { return servers[elementIndex]; };
+ /**
+ * Add an Element at the end of the server list
+ */
+ void addElement(Server server);
+ /**
+ * Add an Element at the beginning of the server list
+ */
+ void addFirstElement(Server server);
+
+ private:
+ std::vector<Server> servers;
+};
+
+/**
+ * The server choice dialog.
+ *
+ * \ingroup Interface
+ */
+class ServerDialog : public Window, public gcn::ActionListener
+{
+ public:
+ /**
+ * Constructor
+ *
+ * @see Window::Window
+ */
+ ServerDialog(LoginData *loginData);
+
+ /**
+ * Destructor
+ */
+ ~ServerDialog();
+
+ /**
+ * Called when receiving actions from the widgets.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ private:
+ gcn::TextField *mServerNameField;
+ gcn::TextField *mPortField;
+ gcn::Button *mOkButton;
+ gcn::Button *mCancelButton;
+
+ DropDown *mMostUsedServersDropDown;
+ gcn::ListBox *mMostUsedServersListBox;
+ gcn::ScrollArea *mMostUsedServersScrollArea;
+ ServersListModel *mMostUsedServersListModel;
+
+ LoginData *mLoginData;
+};
+
+#endif
diff --git a/src/gui/setup.cpp b/src/gui/setup.cpp
index 148e8b75..c8b7f900 100644
--- a/src/gui/setup.cpp
+++ b/src/gui/setup.cpp
@@ -44,6 +44,10 @@ extern Window *itemShortcutWindow;
extern Window *emoteShortcutWindow;
extern Window *emoteWindow;
extern Window *tradeWindow;
+#ifdef TMWSERV_SUPPORT
+extern Window *magicDialog;
+extern Window *guildWindow;
+#endif
Setup::Setup():
Window(_("Setup"))
@@ -138,5 +142,9 @@ void Setup::action(const gcn::ActionEvent &event)
emoteShortcutWindow->resetToDefaultSize();
emoteWindow->resetToDefaultSize();
tradeWindow->resetToDefaultSize();
+#ifdef TMWSERV_SUPPORT
+ magicDialog->resetToDefaultSize();
+ guildWindow->resetToDefaultSize();
+#endif
}
}
diff --git a/src/gui/setup_audio.cpp b/src/gui/setup_audio.cpp
index a4bc05ae..43cc28e6 100644
--- a/src/gui/setup_audio.cpp
+++ b/src/gui/setup_audio.cpp
@@ -43,6 +43,7 @@ Setup_Audio::Setup_Audio():
mMusicSlider(new Slider(0, 128))
{
setOpaque(false);
+ setDimension(gcn::Rectangle(0, 0, 250, 200));
gcn::Label *sfxLabel = new gcn::Label(_("Sfx volume"));
gcn::Label *musicLabel = new gcn::Label(_("Music volume"));
diff --git a/src/gui/setup_video.cpp b/src/gui/setup_video.cpp
index aa39dd36..526c67ce 100644
--- a/src/gui/setup_video.cpp
+++ b/src/gui/setup_video.cpp
@@ -107,6 +107,7 @@ Setup_Video::Setup_Video():
mFullScreenEnabled(config.getValue("screen", false)),
mOpenGLEnabled(config.getValue("opengl", false)),
mCustomCursorEnabled(config.getValue("customcursor", true)),
+ mVisibleNamesEnabled(config.getValue("visiblenames", 1)),
mParticleEffectsEnabled(config.getValue("particleeffects", true)),
mNameEnabled(config.getValue("showownname", false)),
mOpacity(config.getValue("guialpha", 0.8)),
@@ -117,6 +118,7 @@ Setup_Video::Setup_Video():
mFsCheckBox(new CheckBox(_("Full screen"), mFullScreenEnabled)),
mOpenGLCheckBox(new CheckBox(_("OpenGL"), mOpenGLEnabled)),
mCustomCursorCheckBox(new CheckBox(_("Custom cursor"), mCustomCursorEnabled)),
+ mVisibleNamesCheckBox(new CheckBox(_("Visible names"), mVisibleNamesEnabled)),
mParticleEffectsCheckBox(new CheckBox(_("Particle effects"), mParticleEffectsEnabled)),
mNameCheckBox(new CheckBox(_("Show name"), mNameEnabled)),
mSpeechSlider(new Slider(0, 3)),
@@ -168,6 +170,7 @@ Setup_Video::Setup_Video():
mModeList->setActionEventId("videomode");
mCustomCursorCheckBox->setActionEventId("customcursor");
+ mVisibleNamesCheckBox->setActionEventId("visiblenames");
mParticleEffectsCheckBox->setActionEventId("particleeffects");
mNameCheckBox->setActionEventId("showownname");
mAlphaSlider->setActionEventId("guialpha");
@@ -185,6 +188,7 @@ Setup_Video::Setup_Video():
mModeList->addActionListener(this);
mCustomCursorCheckBox->addActionListener(this);
+ mVisibleNamesCheckBox->addActionListener(this);
mParticleEffectsCheckBox->addActionListener(this);
mNameCheckBox->addActionListener(this);
mAlphaSlider->addActionListener(this);
@@ -263,8 +267,9 @@ Setup_Video::Setup_Video():
place(1, 0, mFsCheckBox, 3);
place(1, 1, mOpenGLCheckBox, 3);
place(1, 2, mCustomCursorCheckBox, 3);
- place(1, 3, mNameCheckBox, 3);
- place(1, 4, mParticleEffectsCheckBox, 3);
+ place(1, 3, mVisibleNamesCheckBox, 3);
+ place(1, 4, mNameCheckBox, 3);
+ place(1, 5, mParticleEffectsCheckBox, 3);
place(0, 6, mAlphaSlider);
place(0, 7, mFpsSlider);
@@ -348,6 +353,7 @@ void Setup_Video::apply()
// We sync old and new values at apply time
mFullScreenEnabled = config.getValue("screen", false);
mCustomCursorEnabled = config.getValue("customcursor", true);
+ mVisibleNamesEnabled = config.getValue("visiblenames", 1);
mParticleEffectsEnabled = config.getValue("particleeffects", true);
mNameEnabled = config.getValue("showownname", false);
mSpeechMode = (int) config.getValue("speech", 3);
@@ -381,6 +387,7 @@ void Setup_Video::cancel()
mFsCheckBox->setSelected(mFullScreenEnabled);
mOpenGLCheckBox->setSelected(mOpenGLEnabled);
mCustomCursorCheckBox->setSelected(mCustomCursorEnabled);
+ mVisibleNamesCheckBox->setSelected(mVisibleNamesEnabled);
mParticleEffectsCheckBox->setSelected(mParticleEffectsEnabled);
mSpeechSlider->setValue(mSpeechMode);
mNameCheckBox->setSelected(mNameEnabled);
@@ -395,6 +402,7 @@ void Setup_Video::cancel()
config.setValue("screen", mFullScreenEnabled ? true : false);
config.setValue("customcursor", mCustomCursorEnabled ? true : false);
+ config.setValue("visiblenames", mVisibleNamesEnabled ? 1 : 0);
config.setValue("particleeffects", mParticleEffectsEnabled ? true : false);
config.setValue("speech", mSpeechMode);
config.setValue("showownname", mNameEnabled ? true : false);
@@ -426,6 +434,11 @@ void Setup_Video::action(const gcn::ActionEvent &event)
config.setValue("customcursor",
mCustomCursorCheckBox->isSelected() ? true : false);
}
+ else if (event.getId() == "visiblenames")
+ {
+ config.setValue("visiblenames",
+ mVisibleNamesCheckBox->isSelected() ? 1 : 0);
+ }
else if (event.getId() == "particleeffects")
{
config.setValue("particleeffects",
diff --git a/src/gui/setup_video.h b/src/gui/setup_video.h
index e57e33cc..44ecdfe5 100644
--- a/src/gui/setup_video.h
+++ b/src/gui/setup_video.h
@@ -50,6 +50,7 @@ class Setup_Video : public SetupTab, public gcn::ActionListener,
bool mFullScreenEnabled;
bool mOpenGLEnabled;
bool mCustomCursorEnabled;
+ bool mVisibleNamesEnabled;
bool mParticleEffectsEnabled;
bool mNameEnabled;
double mOpacity;
@@ -69,6 +70,7 @@ class Setup_Video : public SetupTab, public gcn::ActionListener,
gcn::CheckBox *mFsCheckBox;
gcn::CheckBox *mOpenGLCheckBox;
gcn::CheckBox *mCustomCursorCheckBox;
+ gcn::CheckBox *mVisibleNamesCheckBox;
gcn::CheckBox *mParticleEffectsCheckBox;
gcn::CheckBox *mNameCheckBox;
diff --git a/src/gui/shop.cpp b/src/gui/shop.cpp
index a5f59bac..7b28cef4 100644
--- a/src/gui/shop.cpp
+++ b/src/gui/shop.cpp
@@ -38,17 +38,19 @@ std::string ShopItems::getElementAt(int i)
return mShopItems.at(i)->getDisplayName();
}
-void ShopItems::addItem(int inventoryIndex, short id, int amount, int price)
+void ShopItems::addItem(int id, int amount, int price)
{
- ShopItem *item = new ShopItem(id, amount, price);
- item->setInvIndex(inventoryIndex);
- mShopItems.push_back(item);
+ mShopItems.push_back(new ShopItem(id, amount, price));
}
-void ShopItems::addItem(short id, int price)
+#ifdef EATHENA_SUPPORT
+void ShopItems::addItem(int inventoryIndex, int id, int amount, int price)
{
- mShopItems.push_back(new ShopItem(id, 0, price));
+ ShopItem *item = new ShopItem(id, amount, price);
+ item->setInvIndex(inventoryIndex);
+ mShopItems.push_back(item);
}
+#endif
ShopItem* ShopItems::at(int i) const
{
diff --git a/src/gui/shop.h b/src/gui/shop.h
index e0db4c59..aa72bf2a 100644
--- a/src/gui/shop.h
+++ b/src/gui/shop.h
@@ -40,14 +40,16 @@ class ShopItems : public gcn::ListModel
~ShopItems();
/**
- * Adds an item to the list (used by sell dialog).
+ * Adds an item to the list.
*/
- void addItem(int inventoryIndex, short id, int amount, int price);
+ void addItem(int id, int amount, int price);
+#ifdef EATHENA_SUPPORT
/**
- * Adds an item to the list (used by buy dialog).
+ * Adds an item to the list (used by eAthena sell dialog).
*/
- void addItem(short id, int price);
+ void addItem(int inventoryIndex, int id, int amount, int price);
+#endif
/**
* Returns the number of items in the shop.
diff --git a/src/gui/skilldialog.cpp b/src/gui/skilldialog.cpp
new file mode 100644
index 00000000..22d1db60
--- /dev/null
+++ b/src/gui/skilldialog.cpp
@@ -0,0 +1,263 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <guichan/widgets/label.hpp>
+#include <guichan/widgets/container.hpp>
+#include <guichan/widgets/icon.hpp>
+
+#include "skilldialog.h"
+
+#include "icon.h"
+#include "button.h"
+#include "listbox.h"
+#include "scrollarea.h"
+#include "windowcontainer.h"
+#include "progressbar.h"
+
+#include "widgets/tabbedarea.h"
+
+#include "../localplayer.h"
+
+#include "../utils/dtor.h"
+#include "../utils/gettext.h"
+#include "../utils/stringutils.h"
+
+SkillDialog::SkillDialog():
+ Window(_("Skills"))
+{
+ setWindowName("Skills");
+ setCloseButton(true);
+ setDefaultSize(windowContainer->getWidth() - 280, 30, 275, 425);
+
+ TabbedArea *panel = new TabbedArea();
+ panel->setDimension(gcn::Rectangle(5, 5, 270, 420));
+
+ Skill_Tab* tab;
+
+ // Add each type of skill tab to the panel
+ tab = new Skill_Tab("Weapon");
+ panel->addTab(_("Weapons"), tab);
+ mTabs.push_back(tab);
+
+ tab = new Skill_Tab("Magic");
+ panel->addTab(_("Magic"), tab);
+ mTabs.push_back(tab);
+
+ tab = new Skill_Tab("Craft");
+ panel->addTab(_("Crafts"), tab);
+ mTabs.push_back(tab);
+
+ add(panel);
+
+ update();
+
+ setLocationRelativeTo(getParent());
+ loadWindowState();
+}
+
+SkillDialog::~SkillDialog()
+{
+ delete_all(mTabs);
+}
+
+void SkillDialog::action(const gcn::ActionEvent &event)
+{
+ if (event.getId() == "skill")
+ {
+ }
+ else if (event.getId() == "close")
+ {
+ setVisible(false);
+ }
+}
+
+void SkillDialog::draw(gcn::Graphics *g)
+{
+ update();
+
+ Window::draw(g);
+}
+
+void SkillDialog::update()
+{
+ for(std::list<Skill_Tab*>::const_iterator i = mTabs.begin();
+ i != mTabs.end(); ++i)
+ {
+ (*i)->update();
+ }
+}
+
+Skill_Tab::Skill_Tab(const std::string &type): type(type)
+{
+ setOpaque(false);
+ setDimension(gcn::Rectangle(0, 0, 270, 420));
+ int skillNum = getSkillNum();
+
+ mSkillIcons.resize(skillNum);
+ mSkillNameLabels.resize(skillNum);
+ mSkillLevelLabels.resize(skillNum);
+ mSkillExpLabels.resize(skillNum);
+ mSkillProgress.resize(skillNum);
+
+ // Set the initial positions of the skill information
+ for (int a=0; a < skillNum; a++)
+ {
+ mSkillIcons.at(a) = getIcon(a);
+ mSkillIcons.at(a)->setPosition(1, a*32);
+ add(mSkillIcons.at(a));
+
+ mSkillNameLabels.at(a) = new gcn::Label("");
+ mSkillNameLabels.at(a)->setPosition(35, a*32 );
+ add(mSkillNameLabels.at(a));
+
+ mSkillProgress.at(a) = new ProgressBar(0.0f, 200, 20, 150, 150, 150);
+ mSkillProgress.at(a)->setPosition(35, a*32 + 13);
+ add(mSkillProgress.at(a));
+
+ mSkillExpLabels.at(a) = new gcn::Label("");
+ mSkillExpLabels.at(a)->setPosition(45, a*32 + 16);
+ add(mSkillExpLabels.at(a));
+
+ mSkillLevelLabels.at(a) = new gcn::Label("");
+ mSkillLevelLabels.at(a)->setPosition(165, a*32);
+ add(mSkillLevelLabels.at(a));
+ }
+
+ update();
+
+}
+
+int Skill_Tab::getSkillNum()
+{
+ int skillNum = 0;
+
+ if (type == "Weapon")
+ {
+ skillNum = CHAR_SKILL_WEAPON_NB;
+ return skillNum;
+ }
+ else if (type == "Magic")
+ {
+ skillNum = CHAR_SKILL_MAGIC_NB;
+ return skillNum;
+ }
+ else if (type == "Craft")
+ {
+ skillNum = CHAR_SKILL_CRAFT_NB;
+ return skillNum;
+ }
+ else return skillNum;
+}
+
+int Skill_Tab::getSkillBegin()
+{
+ int skillBegin = 0;
+
+ if (type == "Weapon")
+ {
+ skillBegin = CHAR_SKILL_WEAPON_BEGIN - CHAR_SKILL_BEGIN;
+ return skillBegin;
+ }
+ else if (type == "Magic")
+ {
+ skillBegin = CHAR_SKILL_MAGIC_BEGIN - CHAR_SKILL_BEGIN;
+ return skillBegin;
+ }
+ else if (type == "Craft")
+ {
+ skillBegin = CHAR_SKILL_CRAFT_BEGIN - CHAR_SKILL_BEGIN;
+ return skillBegin;
+ }
+ else return skillBegin;
+}
+
+Icon* Skill_Tab::getIcon(int index)
+{
+ int skillBegin = getSkillBegin();
+ std::string icon = LocalPlayer::getSkillInfo(index + skillBegin).icon;
+ return new Icon(icon);
+}
+
+void Skill_Tab::updateSkill(int index)
+{
+ int skillBegin = getSkillBegin();
+
+ int baseLevel = player_node->getAttributeBase(index +
+ skillBegin +
+ CHAR_SKILL_BEGIN);
+
+ int effLevel = player_node->getAttributeEffective(index +
+ skillBegin +
+ CHAR_SKILL_BEGIN);
+ if(baseLevel <= 0)
+ {
+ mSkillProgress.at(index)->setVisible(false);
+ mSkillExpLabels.at(index)->setVisible(false);
+ mSkillLevelLabels.at(index)->setVisible(false);
+ mSkillNameLabels.at(index)->setVisible(false);
+ mSkillIcons.at(index)->setVisible(false);
+ }
+ else
+ {
+ mSkillProgress.at(index)->setVisible(true);
+ mSkillExpLabels.at(index)->setVisible(true);
+ mSkillLevelLabels.at(index)->setVisible(true);
+ mSkillNameLabels.at(index)->setVisible(true);
+ mSkillIcons.at(index)->setVisible(true);
+ std::string skillLevel("Lvl: " + toString(baseLevel));
+ if (effLevel < baseLevel)
+ {
+ skillLevel.append(" - " + toString(baseLevel - effLevel));
+ }
+ else if (effLevel > baseLevel)
+ {
+ skillLevel.append(" + " + toString(effLevel - baseLevel));
+ }
+ mSkillLevelLabels.at(index)->setCaption(skillLevel);
+
+ std::pair<int, int> exp = player_node->getExperience(index + skillBegin);
+ std::string sExp (toString(exp.first) + " / " + toString(exp.second));
+
+
+ mSkillNameLabels.at(index)->setCaption(LocalPlayer::getSkillInfo(index + skillBegin).name);
+ mSkillNameLabels.at(index)->adjustSize();
+ mSkillLevelLabels.at(index)->adjustSize();
+ mSkillExpLabels.at(index)->setCaption(sExp);
+ mSkillExpLabels.at(index)->adjustSize();
+ mSkillExpLabels.at(index)->setAlignment(gcn::Graphics::RIGHT);
+
+ // More intense red as exp grows
+ int color = 150 - (int)(150 * ((float) exp.first / exp.second));
+ mSkillProgress.at(index)->setColor(244, color, color);
+ mSkillProgress.at(index)->setProgress((float) exp.first / exp.second);
+ }
+}
+
+void Skill_Tab::update()
+{
+ int skillNum = getSkillNum();
+
+ // Update the skill information for reach skill
+ for (int a = 0; a < skillNum; a++)
+ {
+ updateSkill(a);
+ }
+}
diff --git a/src/gui/skilldialog.h b/src/gui/skilldialog.h
new file mode 100644
index 00000000..3d010daa
--- /dev/null
+++ b/src/gui/skilldialog.h
@@ -0,0 +1,139 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_SKILL_H
+#define _TMW_SKILL_H
+
+#include <vector>
+#include <list>
+
+#include <guichan/listmodel.hpp>
+#include <guichan/actionlistener.hpp>
+
+#include "window.h"
+#include "gccontainer.h"
+
+#include "../guichanfwd.h"
+
+class ProgressBar;
+class Icon;
+
+class Skill_Tab : public GCContainer, public gcn::ActionListener
+{
+ public:
+ /**
+ * The type of this skill tab
+ */
+ const std::string type;
+
+ /**
+ * Constructor
+ */
+ Skill_Tab(const std::string &type);
+
+ /**
+ * Update this tab
+ */
+ void update();
+
+ /**
+ * Called when receiving actions from widget.
+ */
+ void action(const gcn::ActionEvent &event) {}
+
+ private:
+ /**
+ * Update the information of a skill at
+ * the given index
+ */
+ void updateSkill(int index);
+
+ /**
+ * Gets the number of skills in this particular
+ * type of tab.
+ */
+ int getSkillNum();
+
+ /**
+ * Get the first enumeration of this skill tab's
+ * skill type.
+ */
+ int getSkillBegin();
+
+ /**
+ * Get the icon associated with the given index
+ */
+ Icon* getIcon(int index);
+
+ std::vector<Icon *> mSkillIcons;
+ std::vector<gcn::Label *> mSkillNameLabels;
+ std::vector<gcn::Label *> mSkillLevelLabels;
+ std::vector<gcn::Label *> mSkillExpLabels;
+ std::vector<ProgressBar *> mSkillProgress;
+};
+
+
+/**
+ * The skill dialog.
+ *
+ * \ingroup Interface
+ */
+class SkillDialog : public Window, public gcn::ActionListener
+{
+ public:
+ /**
+ * Constructor.
+ */
+ SkillDialog();
+
+ /**
+ * Destructor.
+ */
+ ~SkillDialog();
+
+ /**
+ * Called when receiving actions from widget.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ /**
+ * Update the tabs in this dialog
+ */
+ void update();
+
+ /**
+ * Draw this window.
+ */
+ void draw(gcn::Graphics *g);
+
+ private:
+
+
+ std::list<Skill_Tab*> mTabs;
+
+};
+
+
+
+
+extern SkillDialog *skillDialog;
+
+#endif
diff --git a/src/gui/speechbubble.cpp b/src/gui/speechbubble.cpp
index f63b02c3..165d216f 100644
--- a/src/gui/speechbubble.cpp
+++ b/src/gui/speechbubble.cpp
@@ -1,6 +1,7 @@
/*
* Speech bubbles
* Copyright (C) 2008 The Legend of Mazzeroth Development Team
+ * Copyright (C) 2008 The Mana World Development Team
*
* This file is part of The Mana World.
*
diff --git a/src/gui/speechbubble.h b/src/gui/speechbubble.h
index 6daff8fb..5d582b1d 100644
--- a/src/gui/speechbubble.h
+++ b/src/gui/speechbubble.h
@@ -1,6 +1,7 @@
/*
* Speech bubbles
* Copyright (C) 2008 The Legend of Mazzeroth Development Team
+ * Copyright (C) 2008 The Mana World Development Team
*
* This file is part of The Mana World.
*
diff --git a/src/gui/status.cpp b/src/gui/status.cpp
index b1a973fe..3c48d045 100644
--- a/src/gui/status.cpp
+++ b/src/gui/status.cpp
@@ -168,21 +168,21 @@ void StatusWindow::update()
{
// Status Part
// -----------
- mLvlLabel->setCaption(strprintf(_("Level: %d"), mPlayer->mLevel));
+ mLvlLabel->setCaption(strprintf(_("Level: %d"), mPlayer->getLevel()));
mLvlLabel->adjustSize();
mJobLvlLabel->setCaption(strprintf(_("Job: %d"), mPlayer->mJobLevel));
mJobLvlLabel->adjustSize();
- if (mCurrency != mPlayer->mGp) {
- mCurrency = mPlayer->mGp;
+ if (mCurrency != mPlayer->getMoney()) {
+ mCurrency = mPlayer->getMoney();
mGpLabel->setCaption(strprintf(_("Money: %s"),
Units::formatCurrency(mCurrency).c_str()));
mGpLabel->adjustSize();
}
- mHpBar->setText(toString(mPlayer->mHp) +
- "/" + toString(mPlayer->mMaxHp));
+ mHpBar->setText(toString(mPlayer->getHp()) +
+ "/" + toString(mPlayer->getMaxHp()));
mMpBar->setText(toString(mPlayer->mMp) +
"/" + toString(mPlayer->mMaxMp));
@@ -194,11 +194,11 @@ void StatusWindow::update()
"/" + toString(mPlayer->mJobXpForNextLevel));
// HP Bar coloration
- if (mPlayer->mHp < int(mPlayer->mMaxHp / 3))
+ if (mPlayer->getHp() < int(mPlayer->getMaxHp() / 3))
{
mHpBar->setColor(223, 32, 32); // Red
}
- else if (mPlayer->mHp < int((mPlayer->mMaxHp / 3) * 2))
+ else if (mPlayer->getHp() < int((mPlayer->getMaxHp() / 3) * 2))
{
mHpBar->setColor(230, 171, 34); // Orange
}
@@ -207,7 +207,7 @@ void StatusWindow::update()
mHpBar->setColor(0, 171, 34); // Green
}
- mHpBar->setProgress((float) mPlayer->mHp / (float) mPlayer->mMaxHp);
+ mHpBar->setProgress((float) mPlayer->getHp() / (float) mPlayer->getMaxHp());
mMpBar->setProgress((float) mPlayer->mMp / (float) mPlayer->mMaxMp);
mXpBar->setProgress(
diff --git a/src/gui/status.h b/src/gui/status.h
index 136c6c3f..9e4de3fd 100644
--- a/src/gui/status.h
+++ b/src/gui/status.h
@@ -65,7 +65,7 @@ class StatusWindow : public Window, public gcn::ActionListener
*/
gcn::Label *mLvlLabel, *mJobLvlLabel;
gcn::Label *mGpLabel;
- Uint32 mCurrency;
+ int mCurrency;
gcn::Label *mHpLabel, *mMpLabel, *mXpLabel, *mJobLabel;
ProgressBar *mHpBar, *mMpBar;
ProgressBar *mXpBar, *mJobBar;
diff --git a/src/gui/statuswindow.cpp b/src/gui/statuswindow.cpp
new file mode 100644
index 00000000..bcac0a90
--- /dev/null
+++ b/src/gui/statuswindow.cpp
@@ -0,0 +1,370 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "statuswindow.h"
+
+#include <guichan/widgets/label.hpp>
+
+#include "button.h"
+#include "progressbar.h"
+#include "windowcontainer.h"
+
+#include "../localplayer.h"
+
+#include "../utils/strprintf.h"
+#include "../utils/stringutils.h"
+
+StatusWindow::StatusWindow(LocalPlayer *player):
+ Window(player->getName()),
+ mPlayer(player)
+{
+ setWindowName("Status");
+ setResizable(true);
+ setCloseButton(true);
+ setDefaultSize((windowContainer->getWidth() - 365) / 2,
+ (windowContainer->getHeight() - 255) / 2, 365, 275);
+ loadWindowState();
+
+ // ----------------------
+ // Status Part
+ // ----------------------
+
+ mLvlLabel = new gcn::Label("Level:");
+ mMoneyLabel = new gcn::Label("Money:");
+
+ mHpLabel = new gcn::Label("HP:");
+ mHpBar = new ProgressBar(1.0f, 80, 15, 0, 171, 34);
+ mHpValueLabel = new gcn::Label("");
+
+ int y = 3;
+ int x = 5;
+
+ mLvlLabel->setPosition(x, y);
+ x += mLvlLabel->getWidth() + 40;
+ mMoneyLabel->setPosition(x, y);
+
+ y += mLvlLabel->getHeight() + 5; // Next Row
+ x = 5;
+
+ mHpLabel->setPosition(x, y);
+ x += mHpLabel->getWidth() + 5;
+ mHpBar->setPosition(x, y);
+ x += mHpBar->getWidth() + 5;
+ mHpValueLabel->setPosition(x, y);
+
+ y += mHpLabel->getHeight() + 5; // Next Row
+ x = 5;
+
+ add(mLvlLabel);
+ add(mMoneyLabel);
+ add(mHpLabel);
+ add(mHpValueLabel);
+ add(mHpBar);
+
+ // ----------------------
+ // Stats Part
+ // ----------------------
+
+ // Static Labels
+ gcn::Label *mStatsTitleLabel = new gcn::Label("Stats");
+ gcn::Label *mStatsTotalLabel = new gcn::Label("Total");
+
+ // Derived Stats
+/*
+ mStatsAttackLabel = new gcn::Label("Attack:");
+ mStatsDefenseLabel= new gcn::Label("Defense:");
+ mStatsMagicAttackLabel = new gcn::Label("M.Attack:");
+ mStatsMagicDefenseLabel = new gcn::Label("M.Defense:");
+ mStatsAccuracyLabel = new gcn::Label("% Accuracy:");
+ mStatsEvadeLabel = new gcn::Label("% Evade:");
+ mStatsReflexLabel = new gcn::Label("% Reflex:");
+
+ mStatsAttackPoints = new gcn::Label("");
+ mStatsDefensePoints = new gcn::Label("");
+ mStatsMagicAttackPoints = new gcn::Label("");
+ mStatsMagicDefensePoints = new gcn::Label("");
+ mStatsAccuracyPoints = new gcn::Label("% Accuracy:");
+ mStatsEvadePoints = new gcn::Label("% Evade:");
+ mStatsReflexPoints = new gcn::Label("% Reflex:");
+*/
+ // New labels
+ for (int i = 0; i < 6; i++) {
+ mStatsLabel[i] = new gcn::Label();
+ mStatsDisplayLabel[i] = new gcn::Label();
+ }
+ mCharacterPointsLabel = new gcn::Label();
+ mCorrectionPointsLabel = new gcn::Label();
+
+ // Set button events Id
+ mStatsPlus[0] = new Button("+", "STR+", this);
+ mStatsPlus[1] = new Button("+", "AGI+", this);
+ mStatsPlus[2] = new Button("+", "DEX+", this);
+ mStatsPlus[3] = new Button("+", "VIT+", this);
+ mStatsPlus[4] = new Button("+", "INT+", this);
+ mStatsPlus[5] = new Button("+", "WIL+", this);
+
+ mStatsMinus[0] = new Button("-", "STR-", this);
+ mStatsMinus[1] = new Button("-", "AGI-", this);
+ mStatsMinus[2] = new Button("-", "DEX-", this);
+ mStatsMinus[3] = new Button("-", "VIT-", this);
+ mStatsMinus[4] = new Button("-", "INT-", this);
+ mStatsMinus[5] = new Button("-", "WIL-", this);
+
+
+
+ // Set position
+ mStatsTitleLabel->setPosition(mHpLabel->getX(), mHpLabel->getY() + 23 );
+ mStatsTotalLabel->setPosition(110, mStatsTitleLabel->getY() + 15);
+ int totalLabelY = mStatsTotalLabel->getY();
+
+ for (int i = 0; i < 6; i++)
+ {
+ mStatsLabel[i]->setPosition(5,
+ mStatsTotalLabel->getY() + (i * 23) + 15);
+ mStatsMinus[i]->setPosition(85, totalLabelY + (i * 23) + 15);
+ mStatsDisplayLabel[i]->setPosition(125,
+ totalLabelY + (i * 23) + 15);
+ mStatsPlus[i]->setPosition(185, totalLabelY + (i * 23) + 15);
+ }
+
+ mCharacterPointsLabel->setPosition(5, mStatsDisplayLabel[5]->getY() + 25);
+ mCorrectionPointsLabel->setPosition(5, mStatsDisplayLabel[5]->getY() + 35);
+/*
+ mStatsAttackLabel->setPosition(220, mStatsLabel[0]->getY());
+ mStatsDefenseLabel->setPosition(220, mStatsLabel[1]->getY());
+ mStatsMagicAttackLabel->setPosition(220, mStatsLabel[2]->getY());
+ mStatsMagicDefenseLabel->setPosition(220, mStatsLabel[3]->getY());
+ mStatsAccuracyLabel->setPosition(220, mStatsLabel[4]->getY());
+ mStatsEvadeLabel->setPosition(220, mStatsLabel[5]->getY());
+ mStatsReflexLabel->setPosition(220, mStatsLabel[6]->getY());
+
+ mStatsAttackPoints->setPosition(310, mStatsLabel[0]->getY());
+ mStatsDefensePoints->setPosition(310, mStatsLabel[1]->getY());
+ mStatsMagicAttackPoints->setPosition(310, mStatsLabel[2]->getY());
+ mStatsMagicDefensePoints->setPosition(310, mStatsLabel[3]->getY());
+ mStatsAccuracyPoints->setPosition(310, mStatsLabel[4]->getY());
+ mStatsEvadePoints->setPosition(310, mStatsLabel[5]->getY());
+ mStatsReflexPoints->setPosition(310, mStatsLabel[6]->getY());
+*/
+ // Assemble
+ add(mStatsTitleLabel);
+ add(mStatsTotalLabel);
+ for(int i = 0; i < 6; i++)
+ {
+ add(mStatsLabel[i]);
+ add(mStatsDisplayLabel[i]);
+ add(mStatsPlus[i]);
+ add(mStatsMinus[i]);
+ }/*
+ add(mStatsAttackLabel);
+ add(mStatsDefenseLabel);
+ add(mStatsMagicAttackLabel);
+ add(mStatsMagicDefenseLabel);
+ add(mStatsAccuracyLabel);
+ add(mStatsEvadeLabel);
+ add(mStatsReflexLabel);
+
+ add(mStatsAttackPoints);
+ add(mStatsDefensePoints);
+ add(mStatsMagicAttackPoints);
+ add(mStatsMagicDefensePoints);
+ add(mStatsAccuracyPoints);
+ add(mStatsEvadePoints);
+ add(mStatsReflexPoints);*/
+
+ add(mCharacterPointsLabel);
+ add(mCorrectionPointsLabel);
+}
+
+void StatusWindow::update()
+{
+ // Status Part
+ // -----------
+ mLvlLabel->setCaption( "Level: " +
+ toString(mPlayer->getLevel()) +
+ " (" +
+ toString(mPlayer->getLevelProgress()) +
+ "%)");
+ mLvlLabel->adjustSize();
+
+ mMoneyLabel->setCaption("Money: " + toString(mPlayer->getMoney()) + " GP");
+ mMoneyLabel->adjustSize();
+
+ int hp = mPlayer->getHp();
+ int maxHp = mPlayer->getMaxHp();
+
+ mHpValueLabel->setCaption(toString(hp) +
+ " / " + toString(maxHp));
+ mHpValueLabel->adjustSize();
+
+ // HP Bar coloration
+ if (hp < int(maxHp / 3))
+ {
+ mHpBar->setColor(223, 32, 32); // Red
+ }
+ else if (hp < int((maxHp / 3) * 2))
+ {
+ mHpBar->setColor(230, 171, 34); // Orange
+ }
+ else
+ {
+ mHpBar->setColor(0, 171, 34); // Green
+ }
+
+ mHpBar->setProgress((float) hp / maxHp);
+
+ // Stats Part
+ // ----------
+ const std::string attrNames[6] = {
+ "Strength",
+ "Agility",
+ "Dexterity",
+ "Vitality",
+ "Intelligence",
+ "Willpower"
+ };
+ int characterPoints = mPlayer->getCharacterPoints();
+ int correctionPoints = mPlayer->getCorrectionPoints();
+ // Update labels
+ for (int i = 0; i < 6; i++)
+ {
+ mStatsLabel[i]->setCaption(attrNames[i]);
+ mStatsDisplayLabel[i]->setCaption(
+ strprintf("%d / %d",
+ mPlayer->getAttributeEffective(CHAR_ATTR_BEGIN + i),
+ mPlayer->getAttributeBase(CHAR_ATTR_BEGIN + i)));
+
+ mStatsLabel[i]->adjustSize();
+ mStatsDisplayLabel[i]->adjustSize();
+
+ mStatsPlus[i]->setEnabled(characterPoints);
+ mStatsMinus[i]->setEnabled(correctionPoints);
+ }
+ mCharacterPointsLabel->setCaption("Character Points: " +
+ toString(characterPoints));
+ mCharacterPointsLabel->adjustSize();
+
+ mCorrectionPointsLabel->setCaption("Correction Points: " +
+ toString(correctionPoints));
+ mCorrectionPointsLabel->adjustSize();
+/*
+ // Derived Stats Points
+
+ // Attack TODO: Count equipped Weapons and items attack bonuses
+ mStatsAttackPoints->setCaption(
+ toString(mPlayer->ATK + mPlayer->ATK_BONUS));
+ mStatsAttackPoints->adjustSize();
+
+ // Defense TODO: Count equipped Armors and items defense bonuses
+ mStatsDefensePoints->setCaption(
+ toString(mPlayer->DEF + mPlayer->DEF_BONUS));
+ mStatsDefensePoints->adjustSize();
+
+ // Magic Attack TODO: Count equipped items M.Attack bonuses
+ mStatsMagicAttackPoints->setCaption(
+ toString(mPlayer->MATK + mPlayer->MATK_BONUS));
+ mStatsMagicAttackPoints->adjustSize();
+
+ // Magic Defense TODO: Count equipped items M.Defense bonuses
+ mStatsMagicDefensePoints->setCaption(
+ toString(mPlayer->MDEF + mPlayer->MDEF_BONUS));
+ mStatsMagicDefensePoints->adjustSize();
+
+ // Accuracy %
+ mStatsAccuracyPoints->setCaption(toString(mPlayer->HIT));
+ mStatsAccuracyPoints->adjustSize();
+
+ // Evasion %
+ mStatsEvadePoints->setCaption(toString(mPlayer->FLEE));
+ mStatsEvadePoints->adjustSize();
+
+ // Reflex %
+ mStatsReflexPoints->setCaption(toString(mPlayer->DEX / 4)); // + counter
+ mStatsReflexPoints->adjustSize();
+*/
+ // Update Second column widgets position
+ mMoneyLabel->setPosition(mLvlLabel->getX() + mLvlLabel->getWidth() + 20,
+ mLvlLabel->getY());
+
+}
+
+void StatusWindow::draw(gcn::Graphics *g)
+{
+ update();
+
+ Window::draw(g);
+}
+
+void StatusWindow::action(const gcn::ActionEvent &event)
+{
+ const std::string &eventId = event.getId();
+
+ // Stats Part
+ if (eventId == "STR+")
+ {
+ mPlayer->raiseAttribute(LocalPlayer::STR);
+ }
+ else if (eventId == "AGI+")
+ {
+ mPlayer->raiseAttribute(LocalPlayer::AGI);
+ }
+ else if (eventId == "DEX+")
+ {
+ mPlayer->raiseAttribute(LocalPlayer::DEX);
+ }
+ else if (eventId == "VIT+")
+ {
+ mPlayer->raiseAttribute(LocalPlayer::VIT);
+ }
+ else if (eventId == "INT+")
+ {
+ mPlayer->raiseAttribute(LocalPlayer::INT);
+ }
+ else if (eventId == "WIL+")
+ {
+ mPlayer->raiseAttribute(LocalPlayer::WIL);
+ }
+
+ else if (eventId == "STR-")
+ {
+ mPlayer->lowerAttribute(LocalPlayer::STR);
+ }
+ else if (eventId == "AGI-")
+ {
+ mPlayer->lowerAttribute(LocalPlayer::AGI);
+ }
+ else if (eventId == "DEX-")
+ {
+ mPlayer->lowerAttribute(LocalPlayer::DEX);
+ }
+ else if (eventId == "VIT-")
+ {
+ mPlayer->lowerAttribute(LocalPlayer::VIT);
+ }
+ else if (eventId == "INT-")
+ {
+ mPlayer->lowerAttribute(LocalPlayer::INT);
+ }
+ else if (eventId == "WIL-")
+ {
+ mPlayer->lowerAttribute(LocalPlayer::WIL);
+ }
+}
diff --git a/src/gui/statuswindow.h b/src/gui/statuswindow.h
new file mode 100644
index 00000000..262b89f6
--- /dev/null
+++ b/src/gui/statuswindow.h
@@ -0,0 +1,105 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_STATUS_H
+#define _TMW_STATUS_H
+
+#include <iosfwd>
+
+#include <guichan/actionlistener.hpp>
+
+#include "window.h"
+
+#include "../guichanfwd.h"
+
+class LocalPlayer;
+class ProgressBar;
+
+
+/**
+ * The player status dialog.
+ *
+ * \ingroup Interface
+ */
+class StatusWindow : public Window, public gcn::ActionListener
+{
+ public:
+ /**
+ * Constructor.
+ */
+ StatusWindow(LocalPlayer *player);
+
+ /**
+ * Called when receiving actions from widget.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ /**
+ * Draw this window
+ */
+ void draw(gcn::Graphics *graphics);
+
+ /**
+ * Updates this dialog with values from PLAYER_INFO *char_info
+ */
+ void update();
+
+ private:
+ LocalPlayer *mPlayer;
+
+ /**
+ * Status Part
+ */
+ gcn::Label *mLvlLabel, *mMoneyLabel, *mHpLabel, *mHpValueLabel;
+ ProgressBar *mHpBar;
+
+ /**
+ * Derived Statistics captions
+ */
+/*
+ gcn::Label *mStatsAttackLabel, *mStatsDefenseLabel;
+ gcn::Label *mStatsMagicAttackLabel, *mStatsMagicDefenseLabel;
+ gcn::Label *mStatsAccuracyLabel, *mStatsEvadeLabel;
+ gcn::Label *mStatsReflexLabel;
+
+ gcn::Label *mStatsAttackPoints, *mStatsDefensePoints;
+ gcn::Label *mStatsMagicAttackPoints, *mStatsMagicDefensePoints;
+ gcn::Label *mStatsAccuracyPoints, *mStatsEvadePoints;
+ gcn::Label *mStatsReflexPoints;
+*/
+ /**
+ * Stats captions.
+ */
+ gcn::Label *mStatsLabel[6];
+ gcn::Label *mStatsDisplayLabel[6];
+ gcn::Label *mCharacterPointsLabel;
+ gcn::Label *mCorrectionPointsLabel;
+
+ /**
+ * Stats buttons.
+ */
+ gcn::Button *mStatsPlus[6];
+ gcn::Button *mStatsMinus[6];
+};
+
+extern StatusWindow *statusWindow;
+
+#endif
diff --git a/src/gui/textdialog.cpp b/src/gui/textdialog.cpp
new file mode 100644
index 00000000..05e43906
--- /dev/null
+++ b/src/gui/textdialog.cpp
@@ -0,0 +1,91 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "textdialog.h"
+
+#include <guichan/widgets/label.hpp>
+#include <guichan/widgets/textfield.hpp>
+
+#include "button.h"
+
+TextDialog::TextDialog(const std::string &title, const std::string &msg,
+ Window *parent):
+ Window(title, true, parent),
+ textField(new TextField(""))
+{
+ gcn::Label *textLabel = new gcn::Label(msg);
+ okButton = new Button("OK", "OK", this);
+ gcn::Button *cancelButton = new Button("Cancel", "CANCEL", this);
+
+ int w = textLabel->getWidth() + 20;
+ int inWidth = okButton->getWidth() + cancelButton->getWidth() + 5;
+ int h = textLabel->getHeight() + 25 + okButton->getHeight() + textField->getHeight();
+
+ if (w < inWidth + 10) {
+ w = inWidth + 10;
+ }
+
+ setContentSize(w, h);
+ textLabel->setPosition(10, 10);
+ textField->setWidth(85);
+ textField->setPosition(10,20 + textLabel->getHeight());
+ okButton->setPosition((w - inWidth) / 2,
+ h - 5 - cancelButton->getHeight());
+ cancelButton->setPosition(okButton->getX() + okButton->getWidth() + 5,
+ h - 5 - cancelButton->getHeight());
+
+ add(textLabel);
+ add(textField);
+ add(okButton);
+ add(cancelButton);
+
+ if (getParent()) {
+ setLocationRelativeTo(getParent());
+ getParent()->moveToTop(this);
+ }
+ setVisible(true);
+ textField->requestFocus();
+}
+
+void TextDialog::action(const gcn::ActionEvent &event)
+{
+ // Proxy button events to our listeners
+ ActionListenerIterator i;
+ for (i = mActionListeners.begin(); i != mActionListeners.end(); ++i)
+ {
+ (*i)->action(event);
+ }
+
+ if(event.getId() == "CANCEL" || event.getId() == "OK")
+ {
+ scheduleDelete();
+ }
+}
+
+const std::string& TextDialog::getText() const
+{
+ return textField->getText();
+}
+
+void TextDialog::setOKButtonActionId(const std::string &name)
+{
+ okButton->setActionEventId(name);
+}
diff --git a/src/gui/textdialog.h b/src/gui/textdialog.h
new file mode 100644
index 00000000..8b4e2cc3
--- /dev/null
+++ b/src/gui/textdialog.h
@@ -0,0 +1,66 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_GUI_GUILD_DIALOG_H
+#define _TMW_GUI_GUILD_DIALOG_H
+
+#include <guichan/actionlistener.hpp>
+#include "textfield.h"
+
+#include "window.h"
+
+
+/**
+* An option dialog.
+ *
+ * \ingroup GUI
+ */
+class TextDialog : public Window, public gcn::ActionListener {
+public:
+ /**
+ * Constructor.
+ *
+ * @see Window::Window
+ */
+ TextDialog(const std::string &title, const std::string &msg,
+ Window *parent = NULL);
+
+ /**
+ * Called when receiving actions from the widgets.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ /**
+ * Get the text in the textfield
+ */
+ const std::string& getText() const;
+
+ /**
+ * Set the OK button action id
+ */
+ void setOKButtonActionId(const std::string &name);
+
+private:
+ TextField *textField;
+ gcn::Button *okButton;
+};
+
+#endif
diff --git a/src/gui/trade.cpp b/src/gui/trade.cpp
index 2f6007a9..98214a79 100644
--- a/src/gui/trade.cpp
+++ b/src/gui/trade.cpp
@@ -21,6 +21,7 @@
#include <sstream>
+#include <guichan/font.hpp>
#include <guichan/widgets/label.hpp>
#include "button.h"
@@ -39,49 +40,67 @@
#include "../localplayer.h"
#include "../units.h"
+#ifdef TMWSERV_SUPPORT
+#include "../net/gameserver/player.h"
+#else
#include "../net/messageout.h"
-#include "../net/protocol.h"
+#include "../net/ea/protocol.h"
+#endif
#include "../utils/gettext.h"
-#include "../utils/strprintf.h"
#include "../utils/stringutils.h"
+#include "../utils/strprintf.h"
+#ifdef TMWSERV_SUPPORT
+TradeWindow::TradeWindow():
+#else
TradeWindow::TradeWindow(Network *network):
+#endif
Window(_("Trade: You")),
+#ifdef EATHENA_SUPPORT
mNetwork(network),
+#endif
mMyInventory(new Inventory(INVENTORY_SIZE)),
mPartnerInventory(new Inventory(INVENTORY_SIZE))
+#ifdef TMWSERV_SUPPORT
+ , mStatus(PREPARING)
+#endif
{
setWindowName("Trade");
- setDefaultSize(115, 227, 342, 209);
setResizable(true);
+ setDefaultSize(115, 197, 332, 209);
- setMinWidth(342);
- setMinHeight(209);
-
- mAddButton = new Button(_("Add"), "add", this);
+ Button *mAddButton = new Button(_("Add"), "add", this);
+#ifdef EATHENA_SUPPORT
mOkButton = new Button(_("Ok"), "ok", this);
- mCancelButton = new Button(_("Cancel"), "cancel", this);
- mTradeButton = new Button(_("Trade"), "trade", this);
-
- mTradeButton->setEnabled(false);
-
- mMyItemContainer = new ItemContainer(mMyInventory.get(), 2);
- mMyItemContainer->setWidth(160);
+#endif
+ Button *mCancelButton = new Button(_("Cancel"), "cancel", this);
+ mTradeButton = new Button(_("Propose trade"), "trade", this);
+ mTradeButton->setWidth(8 + std::max(
+ mTradeButton->getFont()->getWidth(_("Propose trade")),
+ mTradeButton->getFont()->getWidth(_("Confirm trade"))));
+
+#ifdef TMWSERV_SUPPORT
+ mMyItemContainer = new ItemContainer(mMyInventory.get(), 4, 3, 0);
+#else
+ mMyItemContainer = new ItemContainer(mMyInventory.get(), 4, 3, 2);
+#endif
mMyItemContainer->addSelectionListener(this);
+ ScrollArea *mMyScroll = new ScrollArea(mMyItemContainer);
- mMyScroll = new ScrollArea(mMyItemContainer);
-
- mPartnerItemContainer = new ItemContainer(mPartnerInventory.get(), 2);
- mPartnerItemContainer->setWidth(160);
+#ifdef TMWSERV_SUPPORT
+ mPartnerItemContainer = new ItemContainer(mPartnerInventory.get(), 4, 3, 0);
+#else
+ mPartnerItemContainer = new ItemContainer(mPartnerInventory.get(), 4, 3, 2);
+#endif
mPartnerItemContainer->addSelectionListener(this);
+ ScrollArea *mPartnerScroll = new ScrollArea(mPartnerItemContainer);
- mPartnerScroll = new ScrollArea(mPartnerItemContainer);
-
- mMoneyLabel = new gcn::Label(strprintf(_("You get %s."), ""));
- mMoneyLabel2 = new gcn::Label(_("You give:"));
+ mMoneyLabel = new gcn::Label(strprintf(_("You get %d GP."), 0));
+ gcn::Label *mMoneyLabel2 = new gcn::Label(_("You give:"));
mMoneyField = new TextField;
- mMoneyField->setWidth(50);
+ mMoneyField->setWidth(40);
+ Button *mMoneyChange = new Button(_("Change"), "money", this);
place(1, 0, mMoneyLabel);
place(0, 1, mMyScroll).setPadding(3);
@@ -90,9 +109,12 @@ TradeWindow::TradeWindow(Network *network):
place = getPlacer(0, 0);
place(0, 0, mMoneyLabel2);
place(1, 0, mMoneyField);
+ place(2, 0, mMoneyChange).setHAlign(LayoutCell::LEFT);
place = getPlacer(0, 2);
place(0, 0, mAddButton);
+#ifdef EATHENA_SUPPORT
place(1, 0, mOkButton);
+#endif
place(2, 0, mTradeButton);
place(3, 0, mCancelButton);
Layout &layout = getLayout();
@@ -109,44 +131,37 @@ TradeWindow::~TradeWindow()
{
}
-void TradeWindow::widgetResized(const gcn::Event &event)
-{
- mMyItemContainer->setWidth(mMyScroll->getWidth());
- mPartnerItemContainer->setWidth(mPartnerScroll->getWidth());
-
- Window::widgetResized(event);
-}
-
-
-void TradeWindow::addMoney(int amount)
+void TradeWindow::setMoney(int amount)
{
mMoneyLabel->setCaption(strprintf(_("You get %s."),
Units::formatCurrency(amount).c_str()));
mMoneyLabel->adjustSize();
+#ifdef TMWSERV_SUPPORT
+ setStatus(PREPARING);
+#endif
}
+#ifdef TMWSERV_SUPPORT
+void TradeWindow::addItem(int id, bool own, int quantity)
+{
+ (own ? mMyInventory : mPartnerInventory)->addItem(id, quantity);
+ setStatus(PREPARING);
+}
+#endif
+
+#ifdef EATHENA_SUPPORT
void TradeWindow::addItem(int id, bool own, int quantity, bool equipment)
{
if (own)
{
- mMyItemContainer->setWidth(mMyScroll->getWidth());
mMyInventory->addItem(id, quantity, equipment);
}
else
{
- mPartnerItemContainer->setWidth(mPartnerScroll->getWidth());
mPartnerInventory->addItem(id, quantity, equipment);
}
}
-void TradeWindow::removeItem(int id, bool own)
-{
- if (own)
- mMyInventory->removeItem(id);
- else
- mPartnerInventory->removeItem(id);
-}
-
void TradeWindow::changeQuantity(int index, bool own, int quantity)
{
if (own)
@@ -162,20 +177,35 @@ void TradeWindow::increaseQuantity(int index, bool own, int quantity)
else
mPartnerInventory->getItem(index)->increaseQuantity(quantity);
}
+#endif
void TradeWindow::reset()
{
mMyInventory->clear();
mPartnerInventory->clear();
+#ifdef EATHENA_SUPPORT
mTradeButton->setEnabled(false);
mOkButton->setEnabled(true);
mOkOther = false;
mOkMe = false;
+#endif
mMoneyLabel->setCaption(strprintf(_("You get %s."), ""));
mMoneyField->setEnabled(true);
mMoneyField->setText("");
+#ifdef TMWSERV_SUPPORT
+ setStatus(PREPARING);
+#endif
}
+#ifdef TMWSERV_SUPPORT
+
+void TradeWindow::receivedOk()
+{
+ setStatus(ACCEPTING);
+}
+
+#else
+
void TradeWindow::setTradeButton(bool enabled)
{
mTradeButton->setEnabled(enabled);
@@ -213,12 +243,20 @@ void TradeWindow::receivedOk(bool own)
}
}
+#endif
+
void TradeWindow::tradeItem(Item *item, int quantity)
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::tradeItem(item->getInvIndex(), quantity);
+ addItem(item->getId(), true, quantity);
+ item->increaseQuantity(-quantity);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_TRADE_ITEM_ADD_REQUEST);
outMsg.writeInt16(item->getInvIndex());
outMsg.writeInt32(quantity);
+#endif
}
void TradeWindow::valueChanged(const gcn::SelectionEvent &event)
@@ -235,6 +273,18 @@ void TradeWindow::valueChanged(const gcn::SelectionEvent &event)
mMyItemContainer->selectNone();
}
+#ifdef TMWSERV_SUPPORT
+void TradeWindow::setStatus(Status s)
+{
+ if (s == mStatus) return;
+ mStatus = s;
+
+ mTradeButton->setCaption
+ (s == PREPARING ? _("Propose trade") : _("Confirm trade"));
+ mTradeButton->setEnabled(s != PROPOSING);
+}
+#endif
+
void TradeWindow::action(const gcn::ActionEvent &event)
{
Item *item = inventoryWindow->getSelectedItem();
@@ -247,10 +297,9 @@ void TradeWindow::action(const gcn::ActionEvent &event)
if (mMyInventory->getFreeSlot() < 1)
return;
- if (mMyInventory->contains(item))
- {
- chatWindow->chatLog(_("Failed adding item. You can not "
- "overlap one kind of item on the window."), BY_SERVER);
+ if (mMyInventory->contains(item)) {
+ chatWindow->chatLog("Failed adding item. You can not "
+ "overlap one kind of item on the window.", BY_SERVER);
return;
}
@@ -263,12 +312,24 @@ void TradeWindow::action(const gcn::ActionEvent &event)
// Choose amount of items to trade
new ItemAmountWindow(AMOUNT_TRADE_ADD, this, item);
}
+
+#ifdef TMWSERV_SUPPORT
+ setStatus(PREPARING);
+#endif
}
else if (event.getId() == "cancel")
{
+ setVisible(false);
+ reset();
+ player_node->setTrading(false);
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::acceptTrade(false);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_TRADE_CANCEL_REQUEST);
+#endif
}
+#ifdef EATHENA_SUPPORT
else if (event.getId() == "ok")
{
std::stringstream tempMoney(mMoneyField->getText());
@@ -290,9 +351,24 @@ void TradeWindow::action(const gcn::ActionEvent &event)
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_TRADE_ADD_COMPLETE);
}
+#endif
else if (event.getId() == "trade")
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::acceptTrade(true);
+ setStatus(PROPOSING);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_TRADE_OK);
+#endif
+ }
+#ifdef TMWSERV_SUPPORT
+ else if (event.getId() == "money")
+ {
+ int v = atoi(mMoneyField->getText().c_str());
+ Net::GameServer::Player::tradeMoney(v);
+ mMoneyField->setText(strprintf("%d", v));
+ setStatus(PREPARING);
}
+#endif
}
diff --git a/src/gui/trade.h b/src/gui/trade.h
index df724038..bde0481c 100644
--- a/src/gui/trade.h
+++ b/src/gui/trade.h
@@ -34,7 +34,9 @@
class Inventory;
class Item;
class ItemContainer;
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
class ScrollArea;
/**
@@ -48,7 +50,11 @@ class TradeWindow : public Window, gcn::ActionListener, gcn::SelectionListener
/**
* Constructor.
*/
+#ifdef TMWSERV_SUPPORT
+ TradeWindow();
+#else
TradeWindow(Network *network);
+#endif
/**
* Destructor.
@@ -56,31 +62,25 @@ class TradeWindow : public Window, gcn::ActionListener, gcn::SelectionListener
~TradeWindow();
/**
- * Called when resizing the window.
- *
- * @param event The calling event
- */
- void widgetResized(const gcn::Event &event);
-
- /**
- * Add money to the trade window.
+ * Displays expected money in the trade window.
*/
- void addMoney(int quantity);
+ void setMoney(int quantity);
/**
* Add an item to the trade window.
*/
- void addItem(int id, bool own, int quantity, bool equipment);
+ void addItem(int id, bool own, int quantity);
/**
- * Remove a item from the trade window.
+ * Reset both item containers
*/
- void removeItem(int id, bool own);
+ void reset();
+#ifdef EATHENA_SUPPORT
/**
- * Reset both item containers
+ * Add an item to the trade window.
*/
- void reset();
+ void addItem(int id, bool own, int quantity, bool equipment);
/**
* Change quantity of an item.
@@ -96,11 +96,16 @@ class TradeWindow : public Window, gcn::ActionListener, gcn::SelectionListener
* Set trade Button disabled
*/
void setTradeButton(bool enabled);
+#endif
/**
* Player received ok message from server
*/
+#ifdef TMWSERV_SUPPORT
+ void receivedOk();
+#else
void receivedOk(bool own);
+#endif
/**
* Send trade packet.
@@ -119,7 +124,23 @@ class TradeWindow : public Window, gcn::ActionListener, gcn::SelectionListener
void action(const gcn::ActionEvent &event);
private:
+#ifdef TMWSERV_SUPPORT
+ enum Status
+ {
+ PREPARING, /**< Players are adding items. */
+ PROPOSING, /**< Local player is proposing a trade. */
+ ACCEPTING /**< Distant player is proposing a trade. */
+ };
+
+ /**
+ * Sets the current status of the trade.
+ */
+ void setStatus(Status);
+#endif
+
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
typedef const std::auto_ptr<Inventory> InventoryPtr;
InventoryPtr mMyInventory;
@@ -129,11 +150,17 @@ class TradeWindow : public Window, gcn::ActionListener, gcn::SelectionListener
ItemContainer *mPartnerItemContainer;
gcn::Label *mMoneyLabel;
- gcn::Label *mMoneyLabel2;
- gcn::Button *mAddButton, *mOkButton, *mCancelButton, *mTradeButton;
- ScrollArea *mMyScroll, *mPartnerScroll;
+ gcn::Button *mTradeButton;
+#ifdef EATHENA_SUPPORT
+ gcn::Button *mOkButton;
+#endif
gcn::TextField *mMoneyField;
+
+#ifdef TMWSERV_SUPPORT
+ Status mStatus;
+#else
bool mOkOther, mOkMe;
+#endif
};
extern TradeWindow *tradeWindow;
diff --git a/src/gui/unregisterdialog.cpp b/src/gui/unregisterdialog.cpp
new file mode 100644
index 00000000..1e09ca23
--- /dev/null
+++ b/src/gui/unregisterdialog.cpp
@@ -0,0 +1,141 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "unregisterdialog.h"
+
+#include <string>
+#include <sstream>
+
+#include <guichan/widgets/label.hpp>
+
+#include "../main.h"
+#include "../log.h"
+#include "../logindata.h"
+
+#include "button.h"
+#include "checkbox.h"
+#include "register.h"
+#include "passwordfield.h"
+#include "textfield.h"
+#include "ok_dialog.h"
+
+#include "../utils/gettext.h"
+#include "../utils/strprintf.h"
+
+UnRegisterDialog::UnRegisterDialog(Window *parent, LoginData *loginData):
+ Window("Unregister", true, parent),
+ mWrongDataNoticeListener(new WrongDataNoticeListener()),
+ mLoginData(loginData)
+{
+ gcn::Label *userLabel = new gcn::Label(strprintf(_("Name: %s"), mLoginData->username.c_str()));
+ gcn::Label *passwordLabel = new gcn::Label(_("Password:"));
+ mPasswordField = new PasswordField(mLoginData->password);
+ mUnRegisterButton = new Button(_("Unregister"), "unregister", this);
+ mCancelButton = new Button(_("Cancel"), "cancel", this);
+
+ const int width = 210;
+ const int height = 80;
+ setContentSize(width, height);
+
+ userLabel->setPosition(5, 5);
+ userLabel->setWidth(width - 5);
+ mPasswordField->setPosition(
+ 68, userLabel->getY() + userLabel->getHeight() + 7);
+ mPasswordField->setWidth(130);
+
+ passwordLabel->setPosition(5, mPasswordField->getY() + 1);
+
+ mCancelButton->setPosition(
+ width - 5 - mCancelButton->getWidth(),
+ height - 5 - mCancelButton->getHeight());
+ mUnRegisterButton->setPosition(
+ mCancelButton->getX() - 5 - mUnRegisterButton->getWidth(),
+ mCancelButton->getY());
+
+ add(userLabel);
+ add(passwordLabel);
+ add(mPasswordField);
+ add(mUnRegisterButton);
+ add(mCancelButton);
+
+ setLocationRelativeTo(getParent());
+ setVisible(true);
+ mPasswordField->requestFocus();
+ mPasswordField->setActionEventId("cancel");
+}
+
+UnRegisterDialog::~UnRegisterDialog()
+{
+ delete mWrongDataNoticeListener;
+}
+
+void
+UnRegisterDialog::action(const gcn::ActionEvent &event)
+{
+ if (event.getId() == "cancel")
+ {
+ scheduleDelete();
+ }
+ else if (event.getId() == "unregister")
+ {
+ const std::string username = mLoginData->username.c_str();
+ const std::string password = mPasswordField->getText();
+ logger->log("UnregisterDialog::unregistered, Username is %s",
+ username.c_str());
+
+ std::stringstream errorMsg;
+ bool error = false;
+
+ // Check password
+ if (password.length() < LEN_MIN_PASSWORD)
+ {
+ // Pass too short
+ errorMsg << "The password needs to be at least "
+ << LEN_MIN_PASSWORD
+ << " characters long.";
+ error = true;
+ }
+ else if (password.length() > LEN_MAX_PASSWORD - 1 )
+ {
+ // Pass too long
+ errorMsg << "The password needs to be less than "
+ << LEN_MAX_PASSWORD
+ << " characters long.";
+ error = true;
+ }
+
+ if (error)
+ {
+ mWrongDataNoticeListener->setTarget(this->mPasswordField);
+
+ OkDialog *dlg = new OkDialog("Error", errorMsg.str());
+ dlg->addActionListener(mWrongDataNoticeListener);
+ }
+ else
+ {
+ // No errors detected, unregister the new user.
+ mUnRegisterButton->setEnabled(false);
+ mLoginData->password = password;
+ state = STATE_UNREGISTER_ATTEMPT;
+ scheduleDelete();
+ }
+ }
+}
diff --git a/src/gui/unregisterdialog.h b/src/gui/unregisterdialog.h
new file mode 100644
index 00000000..1e3cc88f
--- /dev/null
+++ b/src/gui/unregisterdialog.h
@@ -0,0 +1,70 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef UNREGISTERDIALOG_H
+#define UNREGISTERDIALOG_H
+
+#include <iosfwd>
+#include <guichan/actionlistener.hpp>
+
+#include "window.h"
+#include "../guichanfwd.h"
+
+class LoginData;
+class OkDialog;
+class WrongDataNoticeListener;
+
+/**
+ * The Unregister dialog.
+ *
+ * \ingroup Interface
+ */
+class UnRegisterDialog : public Window, public gcn::ActionListener {
+ public:
+ /**
+ * Constructor
+ *
+ * @see Window::Window
+ */
+ UnRegisterDialog(Window *parent,LoginData *loginData);
+
+ /**
+ * Destructor
+ */
+ ~UnRegisterDialog();
+
+ /**
+ * Called when receiving actions from the widgets.
+ */
+ void action(const gcn::ActionEvent &event);
+
+ private:
+ gcn::TextField *mPasswordField;
+
+ gcn::Button *mUnRegisterButton;
+ gcn::Button *mCancelButton;
+
+ WrongDataNoticeListener *mWrongDataNoticeListener;
+
+ LoginData *mLoginData;
+};
+
+#endif
diff --git a/src/gui/updatewindow.cpp b/src/gui/updatewindow.cpp
index 6ec62337..ca41dbda 100644
--- a/src/gui/updatewindow.cpp
+++ b/src/gui/updatewindow.cpp
@@ -185,7 +185,7 @@ void UpdaterWindow::action(const gcn::ActionEvent &event)
}
else if (event.getId() == "play")
{
- state = LOADDATA_STATE;
+ state = STATE_LOADDATA;
}
}
@@ -232,7 +232,7 @@ int UpdaterWindow::updateProgress(void *ptr,
uw->mCurrentFile + " (" + toString((int) (progress * 100)) + "%)");
uw->setProgress(progress);
- if (state != UPDATE_STATE || uw->mDownloadStatus == UPDATE_ERROR)
+ if (state != STATE_UPDATE || uw->mDownloadStatus == UPDATE_ERROR)
{
// If the action was canceled return an error code to stop the mThread
return -1;
diff --git a/src/gui/updatewindow.h b/src/gui/updatewindow.h
index 4ada3c3a..ace398b4 100644
--- a/src/gui/updatewindow.h
+++ b/src/gui/updatewindow.h
@@ -31,6 +31,8 @@
#include "../utils/mutex.h"
+#include "../utils/mutex.h"
+
class BrowserBox;
class Button;
class ProgressBar;
diff --git a/src/gui/viewport.cpp b/src/gui/viewport.cpp
index a1a02e1e..cbd1f3f7 100644
--- a/src/gui/viewport.cpp
+++ b/src/gui/viewport.cpp
@@ -26,6 +26,7 @@
#include "../beingmanager.h"
#include "../configuration.h"
#include "../flooritemmanager.h"
+#include "../game.h"
#include "../graphics.h"
#include "../keyboardconfig.h"
#include "../localplayer.h"
@@ -48,8 +49,13 @@ Viewport::Viewport():
mTileViewX(0),
mTileViewY(0),
mShowDebugPath(false),
+ mVisibleNames(false),
mPlayerFollowMouse(false),
+#ifdef TMWSERV_SUPPORT
+ mLocalWalkTime(-1)
+#else
mWalkTime(0)
+#endif
{
setOpaque(false);
addMouseListener(this);
@@ -58,9 +64,11 @@ Viewport::Viewport():
mScrollRadius = (int) config.getValue("ScrollRadius", 0);
mScrollCenterOffsetX = (int) config.getValue("ScrollCenterOffsetX", 0);
mScrollCenterOffsetY = (int) config.getValue("ScrollCenterOffsetY", 0);
+ mVisibleNames = config.getValue("visiblenames", 1);
config.addListener("ScrollLaziness", this);
config.addListener("ScrollRadius", this);
+ config.addListener("visiblenames", this);
mPopupMenu = new PopupMenu;
}
@@ -68,6 +76,8 @@ Viewport::Viewport():
Viewport::~Viewport()
{
delete mPopupMenu;
+
+ config.removeListener("visiblenames", this);
}
void Viewport::setMap(Map *map)
@@ -97,6 +107,14 @@ void Viewport::draw(gcn::Graphics *gcnGraphics)
}
// Calculate viewpoint
+#ifdef TMWSERV_SUPPORT
+ int midTileX = (graphics->getWidth() + mScrollCenterOffsetX) / 2;
+ int midTileY = (graphics->getHeight() + mScrollCenterOffsetX) / 2;
+
+ const Vector &playerPos = player_node->getPosition();
+ const int player_x = (int) playerPos.x - midTileX;
+ const int player_y = (int) playerPos.y - midTileY;
+#else
int midTileX = (graphics->getWidth() + mScrollCenterOffsetX) / 32 / 2;
int midTileY = (graphics->getHeight() + mScrollCenterOffsetY) / 32 / 2;
@@ -104,6 +122,7 @@ void Viewport::draw(gcn::Graphics *gcnGraphics)
player_node->getXOffset();
int player_y = (player_node->mY - midTileY) * 32 +
player_node->getYOffset();
+#endif
if (mScrollLaziness < 1)
mScrollLaziness = 1; // Avoids division by zero
@@ -142,8 +161,10 @@ void Viewport::draw(gcn::Graphics *gcnGraphics)
};
// Don't move camera so that the end of the map is on screen
- int viewXmax = (mMap->getWidth() * 32) - graphics->getWidth();
- int viewYmax = (mMap->getHeight() * 32) - graphics->getHeight();
+ const int viewXmax =
+ mMap->getWidth() * mMap->getTileWidth() - graphics->getWidth();
+ const int viewYmax =
+ mMap->getHeight() * mMap->getTileHeight() - graphics->getHeight();
if (mMap)
{
if (mPixelViewX < 0) {
@@ -168,28 +189,13 @@ void Viewport::draw(gcn::Graphics *gcnGraphics)
{
mMap->draw(graphics, (int) mPixelViewX, (int) mPixelViewY);
- // Find a path from the player to the mouse, and draw it. This is for debug
- // purposes.
- if (mShowDebugPath)
- {
- // Get the current mouse position
- int mouseX, mouseY;
- SDL_GetMouseState(&mouseX, &mouseY);
-
- int mouseTileX = mouseX / 32 + mTileViewX;
- int mouseTileY = mouseY / 32 + mTileViewY;
-
- Path debugPath = mMap->findPath(player_node->mX, player_node->mY, mouseTileX, mouseTileY);
-
- graphics->setColor(gcn::Color(255, 0, 0));
- for (PathIterator i = debugPath.begin(); i != debugPath.end(); i++)
- {
- int squareX = i->x * 32 - (int) mPixelViewX + 12;
- int squareY = i->y * 32 - (int) mPixelViewY + 12;
-
- graphics->fillRectangle(gcn::Rectangle(squareX, squareY, 8, 8));
- graphics->drawText(toString(mMap->getMetaTile(i->x, i->y)->Gcost), squareX + 4, squareY + 12, gcn::Graphics::CENTER);
- }
+ if (mShowDebugPath) {
+ mMap->drawCollision(graphics,
+ (int) mPixelViewX,
+ (int) mPixelViewY);
+#if 0
+ drawDebugPath(graphics);
+#endif
}
}
@@ -232,11 +238,52 @@ void Viewport::logic()
Uint8 button = SDL_GetMouseState(&mouseX, &mouseY);
if (mPlayerFollowMouse && button & SDL_BUTTON(1) &&
+#ifdef TMWSERV_SUPPORT
+ get_elapsed_time(mLocalWalkTime) >= walkingMouseDelay)
+ {
+ mLocalWalkTime = tick_time;
+ player_node->setDestination(mouseX + (int) mPixelViewX,
+ mouseY + (int) mPixelViewY);
+#else
mWalkTime != player_node->mWalkTime)
{
player_node->setDestination(mouseX / 32 + mTileViewX,
mouseY / 32 + mTileViewY);
mWalkTime = player_node->mWalkTime;
+#endif
+ }
+}
+
+void Viewport::drawDebugPath(Graphics *graphics)
+{
+ // Get the current mouse position
+ int mouseX, mouseY;
+ SDL_GetMouseState(&mouseX, &mouseY);
+
+ const int mouseTileX = (mouseX + (int) mPixelViewX) / 32;
+ const int mouseTileY = (mouseY + (int) mPixelViewY) / 32;
+ const Vector &playerPos = player_node->getPosition();
+
+ Path debugPath = mMap->findPath(
+ (int) playerPos.x / 32,
+ (int) playerPos.y / 32,
+ mouseTileX, mouseTileY, 0xFF);
+
+ drawPath(graphics, debugPath);
+}
+
+void Viewport::drawPath(Graphics *graphics, const Path &path)
+{
+ graphics->setColor(gcn::Color(255, 0, 0));
+ for (Path::const_iterator i = path.begin(); i != path.end(); ++i)
+ {
+ int squareX = i->x * 32 - (int) mPixelViewX + 12;
+ int squareY = i->y * 32 - (int) mPixelViewY + 12;
+
+ graphics->fillRectangle(gcn::Rectangle(squareX, squareY, 8, 8));
+ graphics->drawText(
+ toString(mMap->getMetaTile(i->x, i->y)->Gcost),
+ squareX + 4, squareY + 12, gcn::Graphics::CENTER);
}
}
@@ -252,10 +299,10 @@ void Viewport::mousePressed(gcn::MouseEvent &event)
mPlayerFollowMouse = false;
- const int tilex = event.getX() / 32 + mTileViewX;
- const int tiley = event.getY() / 32 + mTileViewY;
- const int x = (int)((float) event.getX() + mPixelViewX);
- const int y = (int)((float) event.getY() + mPixelViewY);
+ const int pixelx = event.getX() + (int) mPixelViewX;
+ const int pixely = event.getY() + (int) mPixelViewY;
+ const int tilex = pixelx / mMap->getTileWidth();
+ const int tiley = pixely / mMap->getTileHeight();
// Right click might open a popup
if (event.getButton() == gcn::MouseEvent::RIGHT)
@@ -263,7 +310,7 @@ void Viewport::mousePressed(gcn::MouseEvent &event)
Being *being;
FloorItem *floorItem;
- if ((being = beingManager->findBeingByPixel(x, y)) &&
+ if ((being = beingManager->findBeingByPixel(pixelx, pixely)) &&
being != player_node)
{
mPopupMenu->showPopup(event.getX(), event.getY(), being);
@@ -287,12 +334,13 @@ void Viewport::mousePressed(gcn::MouseEvent &event)
// Left click can cause different actions
if (event.getButton() == gcn::MouseEvent::LEFT)
{
- Being *being;
FloorItem *item;
+#ifdef EATHENA_SUPPORT
+ Being *being;
// Interact with some being
// if ((being = beingManager->findBeing(tilex, tiley)))
- if ((being = beingManager->findBeingByPixel(x, y)))
+ if ((being = beingManager->findBeingByPixel(pixelx, pixely)))
{
switch (being->getType())
{
@@ -321,26 +369,42 @@ void Viewport::mousePressed(gcn::MouseEvent &event)
}
}
// Pick up some item
- else if ((item = floorItemManager->findByCoordinates(tilex, tiley)))
+ else
+#endif
+ if ((item = floorItemManager->findByCoordinates(tilex, tiley)))
{
player_node->pickUp(item);
}
// Just walk around
else
{
+#ifdef TMWSERV_SUPPORT
+ // FIXME: REALLY UGLY!
+ Uint8 *keys = SDL_GetKeyState(NULL);
+ if (!(keys[SDLK_LSHIFT] || keys[SDLK_RSHIFT]) &&
+ get_elapsed_time(mLocalWalkTime) >= walkingMouseDelay)
+ {
+ mLocalWalkTime = tick_time;
+ player_node->setDestination(event.getX() + (int) mPixelViewX,
+ event.getY() + (int) mPixelViewY);
+ }
+#else
player_node->stopAttack();
player_node->setDestination(tilex, tiley);
+#endif
mPlayerFollowMouse = true;
}
}
else if (event.getButton() == gcn::MouseEvent::MIDDLE)
{
// Find the being nearest to the clicked position
- Being *target = beingManager->findBeingByPixel(x, y);
+ Being *target = beingManager->findNearestLivingBeing(
+ tilex, tiley,
+ 20, Being::MONSTER);
if (target)
{
- player_node->setTarget(target);
+ player_node->setTarget(target);
}
}
}
@@ -350,12 +414,22 @@ void Viewport::mouseDragged(gcn::MouseEvent &event)
if (!mMap || !player_node)
return;
+#ifdef TMWSERV_SUPPORT
+ if (mPlayerFollowMouse
+ && get_elapsed_time(mLocalWalkTime) >= walkingMouseDelay)
+ {
+ mLocalWalkTime = tick_time;
+ player_node->setDestination(event.getX() + (int) mPixelViewX,
+ event.getY() + (int) mPixelViewY);
+ }
+#else
if (mPlayerFollowMouse && mWalkTime == player_node->mWalkTime)
{
int destX = event.getX() / 32 + mTileViewX;
int destY = event.getY() / 32 + mTileViewY;
player_node->setDestination(destX, destY);
}
+#endif
}
void Viewport::mouseReleased(gcn::MouseEvent &event)
@@ -372,4 +446,20 @@ void Viewport::optionChanged(const std::string &name)
{
mScrollLaziness = (int) config.getValue("ScrollLaziness", 32);
mScrollRadius = (int) config.getValue("ScrollRadius", 32);
+
+ if (name == "visiblenames") {
+ mVisibleNames = config.getValue("visiblenames", 1);
+ }
+}
+
+void Viewport::mouseMoved(gcn::MouseEvent &event)
+{
+ // Check if we are on the map
+ if (!mMap || !player_node)
+ return;
+
+ const int tilex = (event.getX() + (int) mPixelViewX) / 32;
+ const int tiley = (event.getY() + (int) mPixelViewY) / 32;
+
+ mSelectedBeing = beingManager->findBeing(tilex, tiley);
}
diff --git a/src/gui/viewport.h b/src/gui/viewport.h
index 522ea734..a097a4ac 100644
--- a/src/gui/viewport.h
+++ b/src/gui/viewport.h
@@ -29,6 +29,7 @@
#include "../configlistener.h"
#include "../position.h"
+class Being;
class FloorItem;
class Graphics;
class ImageSet;
@@ -36,6 +37,9 @@ class Item;
class Map;
class PopupMenu;
+/** Delay between two mouse calls when dragging mouse and move the player */
+const int walkingMouseDelay = 500;
+
/**
* The viewport on the map. Displays the current map and handles mouse input
* and the popup menu.
@@ -94,6 +98,11 @@ class Viewport : public WindowContainer, public gcn::MouseListener,
void mouseReleased(gcn::MouseEvent &event);
/**
+ * Handles mouse move on map.
+ */
+ void mouseMoved(gcn::MouseEvent &event);
+
+ /**
* Shows a popup for an item.
* TODO Find some way to get rid of Item here
*/
@@ -120,6 +129,17 @@ class Viewport : public WindowContainer, public gcn::MouseListener,
void scrollBy(float x, float y) { mPixelViewX += x; mPixelViewY += y; }
private:
+ /**
+ * Finds a path from the player to the mouse, and draws it. This is for
+ * debug purposes.
+ */
+ void drawDebugPath(Graphics *graphics);
+
+ /**
+ * Draws the given path.
+ */
+ void drawPath(Graphics *graphics, const Path &path);
+
Map *mMap; /**< The current map. */
int mScrollRadius;
@@ -131,11 +151,18 @@ class Viewport : public WindowContainer, public gcn::MouseListener,
int mTileViewX; /**< Current viewpoint in tiles. */
int mTileViewY; /**< Current viewpoint in tiles. */
bool mShowDebugPath; /**< Show a path from player to pointer. */
+ bool mVisibleNames; /**< Show target names. */
bool mPlayerFollowMouse;
+#ifdef TMWSERV_SUPPORT
+ int mLocalWalkTime; /**< Timestamp before the next walk can be sent. */
+#else
int mWalkTime;
+#endif
PopupMenu *mPopupMenu; /**< Popup menu. */
+ Being *mSelectedBeing; /**< Current selected being. */
+
};
extern Viewport *viewport; /**< The viewport */
diff --git a/src/gui/widgets/avatar.cpp b/src/gui/widgets/avatar.cpp
new file mode 100644
index 00000000..9fcd00a6
--- /dev/null
+++ b/src/gui/widgets/avatar.cpp
@@ -0,0 +1,53 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "avatar.h"
+
+#include "../icon.h"
+
+#include "../../resources/image.h"
+#include "../../resources/resourcemanager.h"
+
+Avatar::Avatar(const std::string &name):
+ mName(name)
+{
+ setSize(110, 12);
+ mLabel = new gcn::Label(name);
+ mLabel->setSize(85, 12);
+ mLabel->setPosition(25, 0);
+ ResourceManager *resman = ResourceManager::getInstance();
+ mStatusOffline = resman->getImage("graphics/gui/circle-gray.png");
+ mStatusOnline = resman->getImage("graphics/gui/circle-green.png");
+ mStatus = new Icon(mStatusOffline);
+ mStatus->setSize(25, 12);
+ mStatus->setPosition(0, 0);
+}
+
+void Avatar::setOnline(bool online)
+{
+ mStatus->setImage(online ? mStatusOnline : mStatusOffline);
+}
+
+void Avatar::draw(gcn::Graphics *g)
+{
+ mLabel->draw(g);
+ mStatus->draw(g);
+}
diff --git a/src/gui/widgets/avatar.h b/src/gui/widgets/avatar.h
new file mode 100644
index 00000000..c6151020
--- /dev/null
+++ b/src/gui/widgets/avatar.h
@@ -0,0 +1,59 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_AVATAR_H
+#define _TMW_AVATAR_H
+
+#include <string>
+#include <guichan/widget.hpp>
+#include <guichan/widgets/label.hpp>
+
+class Image;
+class Icon;
+
+class Avatar : public gcn::Widget
+{
+public:
+ /**
+ * Constructor.
+ * @param name Character name
+ */
+ Avatar(const std::string &name);
+
+ /**
+ * Set the avatar online status.
+ */
+ void setOnline(bool online);
+
+ /**
+ * Draws the avatar.
+ */
+ void draw(gcn::Graphics *g);
+
+private:
+ std::string mName;
+ Icon *mStatus;
+ Image *mStatusOnline;
+ Image *mStatusOffline;
+ gcn::Label *mLabel;
+};
+
+#endif
diff --git a/src/gui/window.cpp b/src/gui/window.cpp
index ee5613bc..58439316 100644
--- a/src/gui/window.cpp
+++ b/src/gui/window.cpp
@@ -534,24 +534,24 @@ void Window::setGuiAlpha()
mAlphaChanged = false;
}
-void Window::loadSkin(const std::string &filename)
+void Window::loadSkin(const std::string &fileName)
{
const std::string windowId = Window::getId();
ResourceManager *resman = ResourceManager::getInstance();
- logger->log("Loading Window Skin '%s'.", filename.c_str());
+ logger->log("Loading Window Skin '%s'.", fileName.c_str());
logger->log("Loading Window ID '%s'.", windowId.c_str());
- if (filename.empty())
+ if (fileName.empty())
logger->error("Window::loadSkin(): Invalid File Name.");
// TODO:
// If there is an error loading the specified file, we should try to revert
// to a 'default' skin file. Only if the 'default' skin file can't be loaded
// should we have a terminating error.
- XML::Document doc(filename);
+ XML::Document doc(fileName);
xmlNodePtr rootNode = doc.rootNode();
if (!rootNode || !xmlStrEqual(rootNode->name, BAD_CAST "skinset"))
diff --git a/src/gui/window.h b/src/gui/window.h
index 518de6e9..3806342a 100644
--- a/src/gui/window.h
+++ b/src/gui/window.h
@@ -263,7 +263,7 @@ class Window : public gcn::Window, gcn::WidgetListener
/**
* Loads a window skin
*/
- void loadSkin(const std::string &filename);
+ void loadSkin(const std::string &fileName);
/**
* Adds a widget to the window and sets it at given cell.
diff --git a/src/guild.cpp b/src/guild.cpp
new file mode 100644
index 00000000..68e65cb9
--- /dev/null
+++ b/src/guild.cpp
@@ -0,0 +1,69 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "guild.h"
+
+Guild::Guild(short id, short rights):
+ mId(id),
+ mCanInviteUsers(false)
+{
+ // to invite, rights must be greater than 0
+ if (rights > 0)
+ mCanInviteUsers = true;
+}
+
+void Guild::addMember(const std::string &name)
+{
+ if (!isMember(name))
+ {
+ mMembers.push_back(name);
+ }
+}
+
+void Guild::removeMember(const std::string &name)
+{
+ std::vector<std::string>::iterator itr = mMembers.begin(),
+ itr_end = mMembers.end();
+ while(itr != itr_end)
+ {
+ if((*itr) == name)
+ {
+ mMembers.erase(itr);
+ }
+ ++itr;
+ }
+}
+
+bool Guild::isMember(const std::string &name)
+{
+ std::vector<std::string>::iterator itr = mMembers.begin(),
+ itr_end = mMembers.end();
+ while(itr != itr_end)
+ {
+ if((*itr) == name)
+ {
+ return true;
+ }
+ ++itr;
+ }
+
+ return false;
+}
diff --git a/src/guild.h b/src/guild.h
new file mode 100644
index 00000000..7c85fe31
--- /dev/null
+++ b/src/guild.h
@@ -0,0 +1,108 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TMW_GUILD_H
+#define TMW_GUILD_H
+
+#include <string>
+#include <guichan/listmodel.hpp>
+
+#include "player.h"
+
+class Guild : public gcn::ListModel
+{
+public:
+ /**
+ * Constructor with guild id passed to it
+ */
+ Guild(short id, short rights);
+
+ /**
+ * Set the guild's name
+ */
+ void setName(const std::string &name)
+ {
+ mName = name;
+ }
+
+ /**
+ * Add member to the list
+ */
+ void addMember(const std::string &name);
+
+ /**
+ * Get the name of the guild
+ * @return returns name of the guild
+ */
+ const std::string& getName() const
+ {
+ return mName;
+ }
+
+ /**
+ * Get the id of the guild
+ * @return Returns the id of the guild
+ */
+ short getId() const
+ {
+ return mId;
+ }
+
+ /**
+ * Remove member from the guild
+ */
+ void removeMember(const std::string &name);
+
+ /**
+ * Get size of members list
+ * @return Returns the number of members in the guild.
+ */
+ int getNumberOfElements() {
+ return mMembers.size();
+ }
+
+ /**
+ * Get member at i
+ * @return Returns the name of member.
+ */
+ std::string getElementAt(int i) {
+ return mMembers[i];
+ }
+
+ /**
+ * Get whether user can invite users to this guild
+ * @return Returns true if user can invite users
+ */
+ bool getInviteRights()
+ {
+ return mCanInviteUsers;
+ }
+
+ bool isMember(const std::string &name);
+
+private:
+ std::string mName;
+ short mId;
+ std::vector<std::string> mMembers;
+ bool mCanInviteUsers;
+};
+
+#endif
diff --git a/src/inventory.cpp b/src/inventory.cpp
index 3ca26e1e..cdd7b61c 100644
--- a/src/inventory.cpp
+++ b/src/inventory.cpp
@@ -29,7 +29,11 @@ struct SlotUsed : public std::unary_function<Item*, bool>
{
bool operator()(const Item *item) const
{
+#ifdef TMWSERV_SUPPORT
+ return item && item->getId() && item->getQuantity();
+#else
return item && item->getId() != -1 && item->getQuantity() > 0;
+#endif
}
};
@@ -50,7 +54,11 @@ Inventory::~Inventory()
Item* Inventory::getItem(int index) const
{
- if (index < 0 || index >= INVENTORY_SIZE || !mItems[index] || mItems[index]->getQuantity() <= 0)
+#ifdef TMWSERV_SUPPORT
+ if (index < 0 || index >= mSize)
+#else
+ if (index < 0 || index >= mSize || !mItems[index] || mItems[index]->getQuantity() <= 0)
+#endif
return 0;
return mItems[index];
@@ -126,7 +134,11 @@ bool Inventory::contains(Item *item) const
int Inventory::getFreeSlot() const
{
+#ifdef TMWSERV_SUPPORT
+ Item **i = std::find_if(mItems, mItems + mSize,
+#else
Item **i = std::find_if(mItems + 2, mItems + mSize,
+#endif
std::not1(SlotUsed()));
return (i == mItems + mSize) ? -1 : (i - mItems);
}
@@ -144,8 +156,3 @@ int Inventory::getLastUsedSlot() const
return -1;
}
-
-int Inventory::getInventorySize() const
-{
- return INVENTORY_SIZE - 2;
-}
diff --git a/src/inventory.h b/src/inventory.h
index 2c5d99e3..d2a81edf 100644
--- a/src/inventory.h
+++ b/src/inventory.h
@@ -24,8 +24,6 @@
class Item;
-#define INVENTORY_SIZE 102
-
class Inventory
{
public:
@@ -60,12 +58,12 @@ class Inventory
/**
* Adds a new item in a free slot.
*/
- void addItem(int id, int quantity, bool equipment);
+ void addItem(int id, int quantity, bool equipment = false);
/**
* Sets the item at the given position.
*/
- void setItem(int index, int id, int quantity, bool equipment);
+ void setItem(int index, int id, int quantity, bool equipment = false);
/**
* Remove a item from the inventory.
@@ -102,11 +100,7 @@ class Inventory
*/
int getLastUsedSlot() const;
- /**
- * Returns the number of slots available in the inventory.
- */
- int getInventorySize() const;
-
+ static const int NO_SLOT_INDEX = -1; /**< Slot has no index. */
protected:
Item **mItems; /**< The holder of items */
int mSize; /**< The max number of inventory items */
diff --git a/src/item.cpp b/src/item.cpp
index 9165c6c8..042c3800 100644
--- a/src/item.cpp
+++ b/src/item.cpp
@@ -24,11 +24,17 @@
#include "resources/image.h"
#include "resources/resourcemanager.h"
-Item::Item(int id, int quantity, bool equipment, bool equipped):
+Item::Item(int id, int quantity, bool equipment
+#ifdef EATHENA_SUPPORT
+ , bool equipped
+#endif
+ ):
mImage(0),
mQuantity(quantity),
- mEquipment(equipment),
- mEquipped(equipped)
+ mEquipment(equipment)
+#ifdef EATHENA_SUPPORT
+ , mEquipped(equipped)
+#endif
{
setId(id);
}
@@ -43,6 +49,11 @@ void Item::setId(int id)
{
mId = id;
+#ifdef TMWSERV_SUPPORT
+ // Types 0 and 1 are not equippable items.
+ mEquipment = id && getInfo().getType() >= 2;
+#endif
+
// Load the associated image
if (mImage)
mImage->decRef();
diff --git a/src/item.h b/src/item.h
index 3ea4a905..1fd1ee88 100644
--- a/src/item.h
+++ b/src/item.h
@@ -35,8 +35,11 @@ class Item
/**
* Constructor.
*/
- Item(int id = -1, int quantity = 0,
- bool equipment = false, bool equipped = false);
+ Item(int id = -1, int quantity = 0, bool equipment = false
+#ifdef EATHENA_SUPPORT
+ , bool equipped = false
+#endif
+ );
/**
* Destructor.
@@ -83,6 +86,7 @@ class Item
*/
bool isEquipment() const { return mEquipment; }
+#ifdef EATHENA_SUPPORT
/**
* Sets whether this item is equipped.
*/
@@ -92,6 +96,7 @@ class Item
* Returns whether this item is equipped.
*/
bool isEquipped() const { return mEquipped; }
+#endif
/**
* Sets the inventory index of this item.
@@ -113,7 +118,9 @@ class Item
Image *mImage; /**< Item image. */
int mQuantity; /**< Number of items. */
bool mEquipment; /**< Item is equipment. */
+#ifdef EATHENA_SUPPORT
bool mEquipped; /**< Item is equipped. */
+#endif
int mInvIndex; /**< Inventory index. */
};
diff --git a/src/itemshortcut.cpp b/src/itemshortcut.cpp
index b1dfb618..2dea8c56 100644
--- a/src/itemshortcut.cpp
+++ b/src/itemshortcut.cpp
@@ -72,14 +72,20 @@ void ItemShortcut::useItem(int index)
{
if (item->isEquipment())
{
+#ifdef EATHENA_SUPPORT
if (item->isEquipped())
player_node->unequipItem(item);
else
+#endif
player_node->equipItem(item);
}
else
{
+#ifdef TMWSERV_SUPPORT
+ player_node->useItem(item->getInvIndex());
+#else
player_node->useItem(item);
+#endif
}
}
}
diff --git a/src/joystick.cpp b/src/joystick.cpp
index 7e9a2285..b72c9103 100644
--- a/src/joystick.cpp
+++ b/src/joystick.cpp
@@ -19,12 +19,12 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include <cassert>
-
#include "configuration.h"
#include "joystick.h"
#include "log.h"
+#include <cassert>
+
int Joystick::joystickCount = 0;
void Joystick::init()
diff --git a/src/localplayer.cpp b/src/localplayer.cpp
index b9654e63..21ee3a22 100644
--- a/src/localplayer.cpp
+++ b/src/localplayer.cpp
@@ -39,44 +39,85 @@
#include "gui/gui.h"
#include "gui/ministatus.h"
+#ifdef TMWSERV_SUPPORT
+#include "effectmanager.h"
+#include "guild.h"
+
+#include "net/gameserver/player.h"
+#include "net/chatserver/guild.h"
+#include "net/chatserver/party.h"
+#endif
+
+#ifdef EATHENA_SUPPORT
#include "net/messageout.h"
-#include "net/protocol.h"
+#include "net/ea/protocol.h"
+#endif
#include "resources/animation.h"
#include "resources/imageset.h"
#include "resources/resourcemanager.h"
+#include "utils/gettext.h"
#include "utils/stringutils.h"
+#ifdef TMWSERV_SUPPORT
+const short walkingKeyboardDelay = 100;
+#endif
+
LocalPlayer *player_node = NULL;
static const int NAME_X_OFFSET = 15;
static const int NAME_Y_OFFSET = 30;
+#ifdef TMWSERV_SUPPORT
+LocalPlayer::LocalPlayer():
+ Player(65535, 0, NULL),
+ mEquipment(new Equipment),
+ mAttributeBase(NB_CHARACTER_ATTRIBUTES, -1),
+ mAttributeEffective(NB_CHARACTER_ATTRIBUTES, -1),
+ mExpCurrent(CHAR_SKILL_NB, -1),
+ mExpNext(CHAR_SKILL_NB, -1),
+ mCharacterPoints(-1),
+ mCorrectionPoints(-1),
+ mLevelProgress(0),
+#else
LocalPlayer::LocalPlayer(Uint32 id, Uint16 job, Map *map):
Player(id, job, map),
mCharId(0),
mJobXp(0),
- mLevel(0),
mJobLevel(0),
mXpForNextLevel(0), mJobXpForNextLevel(0),
- mHp(0), mMaxHp(0), mMp(0), mMaxMp(0),
- mGp(0),
+ mMp(0), mMaxMp(0),
mAttackRange(0),
- mTotalWeight(0), mMaxWeight(0),
ATK(0), MATK(0), DEF(0), MDEF(0), HIT(0), FLEE(0),
ATK_BONUS(0), MATK_BONUS(0), DEF_BONUS(0), MDEF_BONUS(0), FLEE_BONUS(0),
mStatPoint(0), mSkillPoint(0),
mStatsPointsToAttribute(0),
mEquipment(new Equipment),
- mXp(0), mNetwork(0),
+ mNetwork(0),
+ mXp(0),
+ mInStorage(false),
+ mTargetTime(-1),
+ mLastTarget(-1),
+#endif
+ mLevel(1),
+ mMoney(0),
+ mTotalWeight(1), mMaxWeight(1),
+ mHp(1), mMaxHp(1),
mTarget(NULL), mPickUpTarget(NULL),
mTrading(false), mGoingToTarget(false),
- mTargetTime(-1), mLastAction(-1),
- mLastTarget(-1), mWalkingDir(0),
+ mLastAction(-1),
+ mWalkingDir(0),
mDestX(0), mDestY(0),
- mInventory(new Inventory(INVENTORY_SIZE)),
- mStorage(new Inventory(STORAGE_SIZE))
+#ifdef TMWSERV_SUPPORT
+ mLocalWalkTime(-1),
+#endif
+ mInventory(new Inventory(INVENTORY_SIZE))
+#ifdef EATHENA_SUPPORT
+ , mStorage(new Inventory(STORAGE_SIZE))
+#else
+ , mExpMessageTime(0)
+#endif
{
// Variable to keep the local player from doing certain actions before a map
// is initialized. e.g. drawing a player's name using the TextManager, since
@@ -91,7 +132,9 @@ LocalPlayer::LocalPlayer(Uint32 id, Uint16 job, Map *map):
LocalPlayer::~LocalPlayer()
{
delete mInventory;
+#ifdef EATHENA_SUPPORT
delete mStorage;
+#endif
for (int i = Being::TC_SMALL; i < Being::NUM_TC; i++)
{
@@ -104,6 +147,7 @@ LocalPlayer::~LocalPlayer()
void LocalPlayer::logic()
{
+#ifdef EATHENA_SUPPORT
switch (mAction) {
case STAND:
break;
@@ -118,7 +162,7 @@ void LocalPlayer::logic()
break;
case WALK:
- mFrame = (get_elapsed_time(mWalkTime) * 6) / mWalkSpeed;
+ mFrame = (get_elapsed_time(mWalkTime) * 6) / getWalkSpeed();
if (mFrame >= 6)
nextStep();
break;
@@ -136,11 +180,30 @@ void LocalPlayer::logic()
break;
}
+#endif
// Actions are allowed once per second
if (get_elapsed_time(mLastAction) >= 1000)
mLastAction = -1;
+#ifdef TMWSERV_SUPPORT
+ // Show XP messages
+ if (!mExpMessages.empty())
+ {
+ if (mExpMessageTime == 0)
+ {
+ const Vector &pos = getPosition();
+ particleEngine->addTextRiseFadeOutEffect(mExpMessages.front(),
+ 0, 128, 255,
+ gui->getFont(),
+ (int) pos.x + 16,
+ (int) pos.y - 16);
+ mExpMessages.pop_front();
+ mExpMessageTime = 30;
+ }
+ mExpMessageTime--;
+ }
+#else
// Targeting allowed 4 times a second
if (get_elapsed_time(mLastTarget) >= 250)
mLastTarget = -1;
@@ -170,6 +233,7 @@ void LocalPlayer::logic()
if (mKeepAttacking && mTarget)
attack(mTarget, true);
}
+#endif
Being::logic();
}
@@ -198,6 +262,8 @@ void LocalPlayer::setName(const std::string &name)
void LocalPlayer::nextStep()
{
+ // TODO: Fix picking up when reaching target (this method is obsolete)
+ // TODO: Fix holding walking button to keep walking smoothly
if (mPath.empty())
{
if (mPickUpTarget)
@@ -207,10 +273,13 @@ void LocalPlayer::nextStep()
walk(mWalkingDir);
}
+ // TODO: Fix automatically walking within range of target, when wanted
if (mGoingToTarget && mTarget && withinAttackRange(mTarget))
{
mAction = Being::STAND;
+#ifdef EATHENA_SUPPORT
attack(mTarget, true);
+#endif
mGoingToTarget = false;
mPath.clear();
return;
@@ -221,17 +290,99 @@ void LocalPlayer::nextStep()
mPath.clear();
}
+#ifdef EATHENA_SUPPORT
Player::nextStep();
+#endif
+}
+
+#ifdef TMWSERV_SUPPORT
+bool LocalPlayer::checkInviteRights(const std::string &guildName)
+{
+ Guild *guild = getGuild(guildName);
+ if (guild)
+ {
+ return guild->getInviteRights();
+ }
+
+ return false;
+}
+
+void LocalPlayer::inviteToGuild(Being *being)
+{
+ // TODO: Allow user to choose which guild to invite being to
+ // For now, just invite to the first guild you have permissions to invite with
+ std::map<int, Guild*>::iterator itr = mGuilds.begin();
+ std::map<int, Guild*>::iterator itr_end = mGuilds.end();
+ for (; itr != itr_end; ++itr)
+ {
+ if (checkInviteRights(itr->second->getName()))
+ {
+ Net::ChatServer::Guild::invitePlayer(being->getName(), itr->second->getId());
+ return;
+ }
+ }
+}
+
+void LocalPlayer::inviteToParty(const std::string &name)
+{
+ Net::ChatServer::Party::invitePlayer(name);
+}
+
+void LocalPlayer::clearInventory()
+{
+ mEquipment->clear();
+ mInventory->clear();
+}
+
+void LocalPlayer::setInvItem(int index, int id, int amount)
+{
+ mInventory->setItem(index, id, amount);
+}
+
+#endif
+
+void LocalPlayer::moveInvItem(Item *item, int newIndex)
+{
+ // special case, the old and new cannot copy over each other.
+ if (item->getInvIndex() == newIndex)
+ return;
+
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::moveItem(
+ item->getInvIndex(), newIndex, item->getQuantity());
+#endif
+ // TODO: eAthena support
}
void LocalPlayer::equipItem(Item *item)
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::equip(item->getInvIndex());
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_PLAYER_EQUIP);
outMsg.writeInt16(item->getInvIndex());
outMsg.writeInt16(0);
+#endif
}
+#ifdef TMWSERV_SUPPORT
+
+void LocalPlayer::unequipItem(int slot)
+{
+ Net::GameServer::Player::unequip(slot);
+
+ // Tidy equipment directly to avoid weapon still shown bug, for instance
+ mEquipment->setEquipment(slot, 0);
+}
+
+void LocalPlayer::useItem(int slot)
+{
+ Net::GameServer::Player::useItem(slot);
+}
+
+#else
+
void LocalPlayer::unequipItem(Item *item)
{
if (!item)
@@ -254,48 +405,102 @@ void LocalPlayer::useItem(Item *item)
// Note: id is dest of item, usually player_node->account_ID ??
}
+#endif
+
void LocalPlayer::dropItem(Item *item, int quantity)
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::drop(item->getInvIndex(), quantity);
+#else
// TODO: Fix wrong coordinates of drops, serverside?
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_PLAYER_INVENTORY_DROP);
outMsg.writeInt16(item->getInvIndex());
outMsg.writeInt16(quantity);
+#endif
+}
+
+#ifdef TMWSERV_SUPPORT
+void LocalPlayer::splitItem(Item *item, int quantity)
+{
+ int newIndex = mInventory->getFreeSlot();
+ if (newIndex > Inventory::NO_SLOT_INDEX)
+ {
+ Net::GameServer::Player::moveItem(
+ item->getInvIndex(), newIndex, quantity);
+ }
}
+#endif
void LocalPlayer::pickUp(FloorItem *item)
{
+#ifdef TMWSERV_SUPPORT
+ int dx = item->getX() - (int) getPosition().x / 32;
+ int dy = item->getY() - (int) getPosition().y / 32;
+#else
int dx = item->getX() - mX;
int dy = item->getY() - mY;
+#endif
if (dx * dx + dy * dy < 4)
{
+#ifdef TMWSERV_SUPPORT
+ int id = item->getId();
+ Net::GameServer::Player::pickUp(id >> 16, id & 0xFFFF);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_ITEM_PICKUP);
outMsg.writeInt32(item->getId());
+#endif
mPickUpTarget = NULL;
}
else
{
+#ifdef TMWSERV_SUPPORT
+ setDestination(item->getX() * 32 + 16, item->getY() * 32 + 16);
+#else
setDestination(item->getX(), item->getY());
+#endif
mPickUpTarget = item;
+#ifdef EATHENA_SUPPORT
stopAttack();
+#endif
}
}
void LocalPlayer::walk(unsigned char dir)
{
+ // TODO: Evaluate the implementation of this method for tmwserv
if (!mMap || !dir)
return;
+#ifdef TMWSERV_SUPPORT
+ const Vector &pos = getPosition();
+ int dScaler; // Distance to walk
+#endif
+
if (mAction == WALK && !mPath.empty())
{
// Just finish the current action, otherwise we get out of sync
+#ifdef TMWSERV_SUPPORT
+ Being::setDestination(pos.x, pos.y);
+#else
Being::setDestination(mX, mY);
+#endif
return;
}
- Sint16 dx = 0, dy = 0;
+ int dx = 0, dy = 0;
+#ifdef TMWSERV_SUPPORT
+ if (dir & UP)
+ dy -= 32;
+ if (dir & DOWN)
+ dy += 32;
+ if (dir & LEFT)
+ dx -= 32;
+ if (dir & RIGHT)
+ dx += 32;
+#else
if (dir & UP)
dy--;
if (dir & DOWN)
@@ -304,26 +509,65 @@ void LocalPlayer::walk(unsigned char dir)
dx--;
if (dir & RIGHT)
dx++;
+#endif
+
// Prevent skipping corners over colliding tiles
- if (dx && mMap->tileCollides(mX + dx, mY))
+#ifdef TMWSERV_SUPPORT
+ if (dx && !mMap->getWalk(((int) pos.x + dx) / 32,
+ (int) pos.y / 32, getWalkMask()))
+ dx = 16 - (int) pos.x % 32;
+ if (dy && !mMap->getWalk((int) pos.x / 32,
+ ((int) pos.y + dy) / 32, getWalkMask()))
+ dy = 16 - (int) pos.y % 32;
+#else
+ if (dx && !mMap->getWalk(mX + dx, mY, getWalkMask()))
dx = 0;
- if (dy && mMap->tileCollides(mX, mY + dy))
+ if (dy && !mMap->getWalk(mX, mY + dy, getWalkMask()))
dy = 0;
+#endif
// Choose a straight direction when diagonal target is blocked
- if (dx && dy && mMap->tileCollides(mX + dx, mY + dy))
+#ifdef TMWSERV_SUPPORT
+ if (dx && dy && !mMap->getWalk((pos.x + dx) / 32,
+ (pos.y + dy) / 32, getWalkMask()))
+ dx = 16 - (int) pos.x % 32;
+
+ // Checks our path up to 5 tiles, if a blocking tile is found
+ // We go to the last good tile, and break out of the loop
+ for (dScaler = 1; dScaler <= 10; dScaler++)
+ {
+ if ( (dx || dy) &&
+ !mMap->getWalk( ((int) pos.x + (dx * dScaler)) / 32,
+ ((int) pos.y + (dy * dScaler)) / 32, getWalkMask()) )
+ {
+ dScaler--;
+ break;
+ }
+ }
+
+ if (dScaler >= 0)
+ {
+ setDestination((int) pos.x + (dx * dScaler), (int) pos.y + (dy * dScaler));
+ }
+#else
+ if (dx && dy && !mMap->getWalk(mX + dx, mY + dy, getWalkMask()))
dx = 0;
// Walk to where the player can actually go
- if ((dx || dy) && !mMap->tileCollides(mX + dx, mY + dy))
+ if ((dx || dy) && mMap->getWalk(mX + dx, mY + dy, getWalkMask()))
{
setDestination(mX + dx, mY + dy);
}
+#endif
else if (dir)
{
// If the being can't move, just change direction
- // TODO: Communicate this to the server (waiting on tmwserv)
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::changeDir(dir);
+#else
+ // TODO: Communicate this to the server
+#endif
setDirection(dir);
}
}
@@ -335,6 +579,7 @@ Being* LocalPlayer::getTarget() const
void LocalPlayer::setTarget(Being *target)
{
+#ifdef EATHENA_SUPPORT
if (mLastTarget != -1 || target == this)
return;
@@ -352,6 +597,7 @@ void LocalPlayer::setTarget(Being *target)
mKeepAttacking = false;
mTargetTime = -1;
}
+#endif
if (mTarget)
mTarget->untarget();
@@ -365,19 +611,49 @@ void LocalPlayer::setTarget(Being *target)
static_cast<Monster *>(target)->showName(true);
}
+#ifdef TMWSERV_SUPPORT
+void LocalPlayer::setDestination(int x, int y)
+#else
void LocalPlayer::setDestination(Uint16 x, Uint16 y)
+#endif
{
+#ifdef TMWSERV_SUPPORT
+ // Fix coordinates so that the player does not seem to dig into walls.
+ const int tx = x / 32;
+ const int ty = y / 32;
+ int fx = x % 32;
+ int fy = y % 32;
+
+ if (fx != 16 && !mMap->getWalk(tx + fx / 16 * 2 - 1, ty, getWalkMask()))
+ fx = 16;
+ if (fy != 16 && !mMap->getWalk(tx, ty + fy / 16 * 2 - 1, getWalkMask()))
+ fy = 16;
+ if (fx != 16 && fy != 16 && !mMap->getWalk(tx + fx / 16 * 2 - 1,
+ ty + fy / 16 * 2 - 1,
+ getWalkMask()))
+ fx = 16;
+
+ x = tx * 32 + fx;
+ y = ty * 32 + fy;
+#endif
+
// Only send a new message to the server when destination changes
if (x != mDestX || y != mDestY)
{
mDestX = x;
mDestY = y;
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::walk(x, y);
+ //Debugging fire burst
+ effectManager->trigger(15,x,y);
+#else
char temp[4] = "";
MessageOut outMsg(mNetwork);
set_coordinates(temp, x, y, mDirection);
outMsg.writeInt16(0x0085);
outMsg.writeString(temp, 3);
+#endif
}
mPickUpTarget = NULL;
@@ -389,12 +665,33 @@ void LocalPlayer::setWalkingDir(int dir)
mWalkingDir = dir;
// If we're not already walking, start walking.
- if (mAction != WALK && dir)
+ if (mAction != WALK && dir
+#ifdef TMWSERV_SUPPORT
+ && get_elapsed_time(mLocalWalkTime) >= walkingKeyboardDelay
+#endif
+ )
{
walk(dir);
}
}
+#ifdef TMWSERV_SUPPORT
+void LocalPlayer::stopWalking(bool sendToServer)
+{
+ if (mAction == WALK && mWalkingDir) {
+ mWalkingDir = 0;
+ mLocalWalkTime = 0;
+ Being::setDestination(getPosition().x,getPosition().y);
+ if (sendToServer)
+ Net::GameServer::Player::walk(getPosition().x, getPosition().y);
+ setAction(STAND);
+ }
+
+ clearPath();
+}
+#endif
+
+#ifdef EATHENA_SUPPORT
void LocalPlayer::raiseAttribute(Attribute attr)
{
MessageOut outMsg(mNetwork);
@@ -438,6 +735,7 @@ void LocalPlayer::raiseSkill(Uint16 skillId)
outMsg.writeInt16(CMSG_SKILL_LEVELUP_REQUEST);
outMsg.writeInt16(skillId);
}
+#endif
void LocalPlayer::toggleSit()
{
@@ -445,18 +743,23 @@ void LocalPlayer::toggleSit()
return;
mLastAction = tick_time;
- char type;
+ Being::Action newAction;
switch (mAction)
{
- case STAND: type = 2; break;
- case SIT: type = 3; break;
+ case STAND: newAction = SIT; break;
+ case SIT: newAction = STAND; break;
default: return;
}
+#ifdef TMWSERV_SUPPORT
+ setAction(newAction);
+ Net::GameServer::Player::changeAction(newAction);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(0x0089);
outMsg.writeInt32(0);
- outMsg.writeInt8(type);
+ outMsg.writeInt8((newAction == SIT) ? 2 : 3);
+#endif
}
void LocalPlayer::emote(Uint8 emotion)
@@ -465,11 +768,15 @@ void LocalPlayer::emote(Uint8 emotion)
return;
mLastAction = tick_time;
+ // XXX Convert for new server
+#ifdef EATHENA_SUPPORT
MessageOut outMsg(mNetwork);
outMsg.writeInt16(0x00bf);
outMsg.writeInt8(emotion);
+#endif
}
+#ifdef EATHENA_SUPPORT
void LocalPlayer::tradeReply(bool accept)
{
if (!accept)
@@ -479,12 +786,21 @@ void LocalPlayer::tradeReply(bool accept)
outMsg.writeInt16(CMSG_TRADE_RESPONSE);
outMsg.writeInt8(accept ? 3 : 4);
}
+#endif
void LocalPlayer::trade(Being *being) const
{
+#ifdef TMWSERV_SUPPORT
+ extern std::string tradePartnerName;
+ extern int tradePartnerID;
+ tradePartnerName = being->getName();
+ tradePartnerID = being->getId();
+ Net::GameServer::Player::requestTrade(tradePartnerID);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_TRADE_REQUEST);
outMsg.writeInt32(being->getId());
+#endif
}
bool LocalPlayer::tradeRequestOk() const
@@ -492,6 +808,65 @@ bool LocalPlayer::tradeRequestOk() const
return !mTrading;
}
+#ifdef TMWSERV_SUPPORT
+
+void LocalPlayer::attack()
+{
+ if (mLastAction != -1)
+ return;
+
+ // Can only attack when standing still
+ if (mAction != STAND && mAction != ATTACK)
+ return;
+
+ //Face direction of the target
+ if(mTarget){
+ unsigned char dir = 0;
+ int x = 0, y = 0;
+ Vector plaPos = this->getPosition();
+ Vector tarPos = mTarget->getPosition();
+ x = plaPos.x - tarPos.x;
+ y = plaPos.y - tarPos.y;
+ if(abs(x) < abs(y)){
+ //Check to see if target is above me or below me
+ if(y > 0){
+ dir = UP;
+ } else {
+ dir = DOWN;
+ }
+ } else {
+ //check to see if the target is to the left or right of me
+ if(x > 0){
+ dir = LEFT;
+ } else {
+ dir = RIGHT;
+ }
+ }
+ setDirection(dir);
+ }
+
+ mLastAction = tick_time;
+
+ setAction(ATTACK);
+
+ if (mEquippedWeapon)
+ {
+ std::string soundFile = mEquippedWeapon->getSound(EQUIP_EVENT_STRIKE);
+ if (soundFile != "") sound.playSfx(soundFile);
+ }
+ else {
+ sound.playSfx("sfx/fist-swish.ogg");
+ }
+ Net::GameServer::Player::attack(getSpriteDirection());
+}
+
+void LocalPlayer::useSpecial(int special)
+{
+ Net::GameServer::Player::useSpecial(special);
+}
+
+#else
+
void LocalPlayer::attack(Being *target, bool keep)
{
mKeepAttacking = keep;
@@ -567,13 +942,87 @@ void LocalPlayer::stopAttack()
mLastTarget = -1;
}
+#endif // no TMWSERV_SUPPORT
+
void LocalPlayer::revive()
{
+ // XXX Convert for new server
+#ifdef EATHENA_SUPPORT
MessageOut outMsg(mNetwork);
outMsg.writeInt16(0x00b2);
outMsg.writeInt8(0);
+#endif
}
+#ifdef TMWSERV_SUPPORT
+
+void LocalPlayer::raiseAttribute(size_t attr)
+{
+ // we assume that the server allows the change. When not we will undo it later.
+ mCharacterPoints--;
+ mAttributeBase.at(attr)++;
+ Net::GameServer::Player::raiseAttribute(attr + CHAR_ATTR_BEGIN);
+}
+
+void LocalPlayer::lowerAttribute(size_t attr)
+{
+ // we assume that the server allows the change. When not we will undo it later.
+ mCorrectionPoints--;
+ mCharacterPoints++;
+ mAttributeBase.at(attr)--;
+ Net::GameServer::Player::lowerAttribute(attr + CHAR_ATTR_BEGIN);
+}
+
+const struct LocalPlayer::SkillInfo& LocalPlayer::getSkillInfo(int skill)
+{
+ static const SkillInfo skills[CHAR_SKILL_NB + 1] =
+ {
+ { _("Unarmed"), "graphics/images/unarmed.png" }, // CHAR_SKILL_WEAPON_NONE
+ { _("Knife"), "graphics/images/knife.png" }, // CHAR_SKILL_WEAPON_KNIFE
+ { _("Sword"), "graphics/images/sword.png" }, // CHAR_SKILL_WEAPON_SWORD
+ { _("Polearm"), "graphics/images/polearm.png" }, // CHAR_SKILL_WEAPON_POLEARM
+ { _("Staff"), "graphics/images/staff.png" }, // CHAR_SKILL_WEAPON_STAFF
+ { _("Whip"), "graphics/images/whip.png" }, // CHAR_SKILL_WEAPON_WHIP
+ { _("Bow"), "graphics/images/bow.png" }, // CHAR_SKILL_WEAPON_BOW
+ { _("Shooting"), "graphics/images/shooting.png" }, // CHAR_SKILL_WEAPON_SHOOTING
+ { _("Mace"), "graphics/images/mace.png" }, // CHAR_SKILL_WEAPON_MACE
+ { _("Axe"), "graphics/images/axe.png" }, // CHAR_SKILL_WEAPON_AXE
+ { _("Thrown"), "graphics/images/thrown.png" }, // CHAR_SKILL_WEAPON_THROWN
+ { _("Magic"), "graphics/images/magic.png" }, // CHAR_SKILL_MAGIC_IAMJUSTAPLACEHOLDER
+ { _("Craft"), "graphics/images/craft.png" }, // CHAR_SKILL_CRAFT_IAMJUSTAPLACEHOLDER
+ { _("Unknown Skill"), "graphics/images/unknown.png" }
+ };
+
+ if ((skill < 0) || (skill > CHAR_SKILL_NB))
+ {
+ return skills[CHAR_SKILL_NB];
+ }
+ else
+ {
+ return skills[skill];
+ }
+}
+
+void LocalPlayer::setExperience(int skill, int current, int next)
+{
+ int diff = current - mExpCurrent.at(skill);
+ if (mMap && mExpCurrent.at(skill) != -1 && diff > 0)
+ {
+ const std::string text = toString(diff) + " " + getSkillInfo(skill).name + " xp";
+ mExpMessages.push_back(text);
+ }
+
+ mExpCurrent.at(skill) = current;
+ mExpNext.at(skill) = next;
+}
+
+std::pair<int, int> LocalPlayer::getExperience(int skill)
+{
+ return std::pair<int, int> (mExpCurrent.at(skill), mExpNext.at(skill));
+}
+
+#else
+
void LocalPlayer::setXp(int xp)
{
if (mMap && xp > mXp)
@@ -581,14 +1030,42 @@ void LocalPlayer::setXp(int xp)
const std::string text = toString(xp - mXp) + " xp";
// Show XP number
- particleEngine->addTextRiseFadeOutEffect(text, hitYellowFont,
+ particleEngine->addTextRiseFadeOutEffect(text,
+ 255, 255, 0,
+ hitYellowFont,
mPx + 16, mPy - 16);
}
mXp = xp;
}
+#endif
+
+int LocalPlayer::getAttackRange()
+{
+#ifdef TMWSERV_SUPPORT
+ Item *weapon = mEquipment->getEquipment(EQUIP_FIGHT1_SLOT);
+ if (weapon)
+ {
+ const ItemInfo info = weapon->getInfo();
+ return info.getAttackRange();
+ }
+ return 32; // unarmed range
+#else
+ return mAttackRange;
+#endif
+}
+
bool LocalPlayer::withinAttackRange(Being *target)
{
+#ifdef TMWSERV_SUPPORT
+ const Vector &targetPos = target->getPosition();
+ const Vector &pos = getPosition();
+ const int dx = abs(targetPos.x - pos.x);
+ const int dy = abs(targetPos.y - pos.y);
+ const int range = getAttackRange();
+
+ return !(dx > range || dy > range);
+#else
int dist_x = abs(target->mX - mX);
int dist_y = abs(target->mY - mY);
@@ -598,14 +1075,22 @@ bool LocalPlayer::withinAttackRange(Being *target)
}
return true;
+#endif
}
void LocalPlayer::setGotoTarget(Being *target)
{
+#ifdef TMWSERV_SUPPORT
+ mTarget = target;
+ mGoingToTarget = true;
+ const Vector &targetPos = target->getPosition();
+ setDestination(targetPos.x, targetPos.y);
+#else
mLastTarget = -1;
setTarget(target);
mGoingToTarget = true;
setDestination(target->mX, target->mY);
+#endif
}
diff --git a/src/localplayer.h b/src/localplayer.h
index 5f02de4f..7ced3fdf 100644
--- a/src/localplayer.h
+++ b/src/localplayer.h
@@ -27,11 +27,15 @@
#include "player.h"
+#ifdef EATHENA_SUPPORT
// TODO move into some sane place...
#define MAX_SLOT 2
#define INVENTORY_SIZE 102
#define STORAGE_SIZE 301
+#else
+#define INVENTORY_SIZE 50
+#endif
class Equipment;
class FloorItem;
@@ -39,7 +43,96 @@ class ImageSet;
class Inventory;
class Item;
class Map;
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
+
+#ifdef TMWSERV_SUPPORT
+
+/**
+ * Attributes used during combat. Available to all the beings.
+ */
+enum
+{
+BASE_ATTR_BEGIN = 0,
+ BASE_ATTR_PHY_ATK_MIN = BASE_ATTR_BEGIN,
+ BASE_ATTR_PHY_ATK_DELTA,
+ /**< Physical attack power. */
+ BASE_ATTR_MAG_ATK, /**< Magical attack power. */
+ BASE_ATTR_PHY_RES, /**< Resistance to physical damage. */
+ BASE_ATTR_MAG_RES, /**< Resistance to magical damage. */
+ BASE_ATTR_EVADE, /**< Ability to avoid hits. */
+ BASE_ATTR_HIT, /**< Ability to hit stuff. */
+ BASE_ATTR_HP, /**< Hit Points (Base value: maximum, Modded value: current) */
+ BASE_ATTR_HP_REGEN,/**< number of HP regenerated every 10 game ticks */
+ BASE_ATTR_END,
+ BASE_ATTR_NB = BASE_ATTR_END - BASE_ATTR_BEGIN,
+
+ BASE_ELEM_BEGIN = BASE_ATTR_END,
+ BASE_ELEM_NEUTRAL = BASE_ELEM_BEGIN,
+ BASE_ELEM_FIRE,
+ BASE_ELEM_WATER,
+ BASE_ELEM_EARTH,
+ BASE_ELEM_AIR,
+ BASE_ELEM_SACRED,
+ BASE_ELEM_DEATH,
+ BASE_ELEM_END,
+ BASE_ELEM_NB = BASE_ELEM_END - BASE_ELEM_BEGIN,
+
+ NB_BEING_ATTRIBUTES = BASE_ELEM_END
+};
+
+/**
+ * Attributes of characters. Used to derive being attributes.
+ */
+enum
+{
+ CHAR_ATTR_BEGIN = NB_BEING_ATTRIBUTES,
+ CHAR_ATTR_STRENGTH = CHAR_ATTR_BEGIN,
+ CHAR_ATTR_AGILITY,
+ CHAR_ATTR_DEXTERITY,
+ CHAR_ATTR_VITALITY,
+ CHAR_ATTR_INTELLIGENCE,
+ CHAR_ATTR_WILLPOWER,
+ CHAR_ATTR_END,
+ CHAR_ATTR_NB = CHAR_ATTR_END - CHAR_ATTR_BEGIN,
+
+ CHAR_SKILL_BEGIN = CHAR_ATTR_END,
+
+ CHAR_SKILL_WEAPON_BEGIN = CHAR_SKILL_BEGIN,
+ CHAR_SKILL_WEAPON_NONE = CHAR_SKILL_WEAPON_BEGIN,
+ CHAR_SKILL_WEAPON_KNIFE,
+ CHAR_SKILL_WEAPON_SWORD,
+ CHAR_SKILL_WEAPON_POLEARM,
+ CHAR_SKILL_WEAPON_STAFF,
+ CHAR_SKILL_WEAPON_WHIP,
+ CHAR_SKILL_WEAPON_BOW,
+ CHAR_SKILL_WEAPON_SHOOTING,
+ CHAR_SKILL_WEAPON_MACE,
+ CHAR_SKILL_WEAPON_AXE,
+ CHAR_SKILL_WEAPON_THROWN,
+ CHAR_SKILL_WEAPON_END,
+ CHAR_SKILL_WEAPON_NB = CHAR_SKILL_WEAPON_END - CHAR_SKILL_WEAPON_BEGIN,
+
+ CHAR_SKILL_MAGIC_BEGIN = CHAR_SKILL_WEAPON_END,
+ CHAR_SKILL_MAGIC_IAMJUSTAPLACEHOLDER = CHAR_SKILL_MAGIC_BEGIN,
+ // add magic skills here
+ CHAR_SKILL_MAGIC_END,
+ CHAR_SKILL_MAGIC_NB = CHAR_SKILL_MAGIC_END - CHAR_SKILL_MAGIC_BEGIN,
+
+ CHAR_SKILL_CRAFT_BEGIN = CHAR_SKILL_MAGIC_END,
+ CHAR_SKILL_CRAFT_IAMJUSTAPLACEHOLDER = CHAR_SKILL_CRAFT_BEGIN,
+ // add crafting skills here
+ CHAR_SKILL_CRAFT_END,
+ CHAR_SKILL_CRAFT_NB = CHAR_SKILL_CRAFT_END - CHAR_SKILL_CRAFT_BEGIN,
+
+ CHAR_SKILL_END = CHAR_SKILL_CRAFT_END,
+ CHAR_SKILL_NB = CHAR_SKILL_END - CHAR_SKILL_BEGIN,
+
+ NB_CHARACTER_ATTRIBUTES = CHAR_SKILL_END
+};
+
+#endif
/**
* The local player character.
@@ -49,13 +142,21 @@ class LocalPlayer : public Player
public:
enum Attribute
{
+#ifdef TMWSERV_SUPPORT
+ STR = 0, AGI, DEX, VIT, INT, WIL, CHR
+#else
STR = 0, AGI, VIT, INT, DEX, LUK
+#endif
};
/**
* Constructor.
*/
+#ifdef TMWSERV_SUPPORT
+ LocalPlayer();
+#else
LocalPlayer(Uint32 id, Uint16 job, Map *map);
+#endif
/**
* Destructor.
@@ -63,8 +164,11 @@ class LocalPlayer : public Player
~LocalPlayer();
virtual void setName(const std::string &name);
+
+#ifdef EATHENA_SUPPORT
void setNetwork(Network *network) { mNetwork = network; }
Network *getNetwork() {return mNetwork; }
+#endif
virtual void logic();
/**
@@ -78,10 +182,37 @@ class LocalPlayer : public Player
*/
Inventory* getInventory() const { return mInventory; }
+#ifdef EATHENA_SUPPORT
/**
* Returns the player's storage
*/
Inventory* getStorage() const { return mStorage; }
+#endif
+
+#ifdef TMWSERV_SUPPORT
+ /**
+ * Check the player has permission to invite users to specific guild
+ */
+ bool checkInviteRights(const std::string &guildName);
+
+ /**
+ * Invite a player to join guild
+ */
+ void inviteToGuild(Being *being);
+
+ /**
+ * Invite a player to join their party
+ */
+ void inviteToParty(const std::string &name);
+
+ void clearInventory();
+ void setInvItem(int index, int id, int amount);
+#endif
+
+ /**
+ * Move the Inventory item from the old slot to the new slot.
+ */
+ void moveInvItem(Item *item, int newIndex);
/**
* Equips an item.
@@ -91,21 +222,37 @@ class LocalPlayer : public Player
/**
* Unequips an item.
*/
+#ifdef TMWSERV_SUPPORT
+ void unequipItem(int slot);
+#else
void unequipItem(Item *item);
+#endif
+#ifdef TMWSERV_SUPPORT
+ void useItem(int slot);
+#else
void useItem(Item *item);
+#endif
+
void dropItem(Item *item, int quantity);
+
+#ifdef TMWSERV_SUPPORT
+ void splitItem(Item *item, int quantity);
+#endif
+
void pickUp(FloorItem *item);
+#ifdef EATHENA_SUPPORT
/**
* Sets the attack range.
*/
void setAttackRange(int range) { mAttackRange = range; }
+#endif
/**
* Gets the attack range.
*/
- int getAttackRange() const { return mAttackRange; }
+ int getAttackRange();
/**
* Sents a trade request to the given being.
@@ -129,7 +276,12 @@ class LocalPlayer : public Player
*/
void setTrading(bool trading) { mTrading = trading; }
+#ifdef TMWSERV_SUPPORT
+ void attack();
+ void useSpecial(int id);
+#else
void attack(Being *target = NULL, bool keep = false);
+#endif
/**
* Triggers whether or not to show the name as a GM name.
@@ -139,7 +291,9 @@ class LocalPlayer : public Player
*/
virtual void setGM();
+#ifdef EATHENA_SUPPORT
void stopAttack();
+#endif
/**
* Overridden to do nothing. The attacks of the local player are
@@ -150,6 +304,7 @@ class LocalPlayer : public Player
* @param damage The amount of damage dealt (0 means miss).
*/
virtual void handleAttack(Being *victim, int damage) {}
+ virtual void handleAttack() {}
/**
* Returns the current target of the player. Returns 0 if no being is
@@ -157,6 +312,7 @@ class LocalPlayer : public Player
*/
Being* getTarget() const;
+
/**
* Sets the target being of the player.
*/
@@ -165,7 +321,11 @@ class LocalPlayer : public Player
/**
* Sets a new destination for this being to walk to.
*/
+#ifdef TMWSERV_SUPPORT
+ void setDestination(int x, int y);
+#else
virtual void setDestination(Uint16 x, Uint16 y);
+#endif
/**
* Sets a new direction to keep walking in.
@@ -173,6 +333,12 @@ class LocalPlayer : public Player
void setWalkingDir(int dir);
/**
+ * Gets the walking direction
+ */
+ int getWalkingDir() const
+ { return mWalkingDir; }
+
+ /**
* Sets going to being to attack
*/
void setGotoTarget(Being *target);
@@ -182,14 +348,33 @@ class LocalPlayer : public Player
*/
bool withinAttackRange(Being *target);
+#ifdef EATHENA_SUPPORT
void raiseAttribute(Attribute attr);
void raiseSkill(Uint16 skillId);
+#else
+
+ /**
+ * Stops the player dead in his tracks
+ */
+ void stopWalking(bool sendToServer = true);
+
+ /**
+ * Uses a character point to raise an attribute
+ */
+ void raiseAttribute(size_t attr);
+
+ /**
+ * Uses a correction point to lower an attribute
+ */
+ void lowerAttribute(size_t attr);
+#endif
void toggleSit();
void emote(Uint8 emotion);
void revive();
+#ifdef EATHENA_SUPPORT
/**
* Accessors for mInStorage
*/
@@ -210,16 +395,12 @@ class LocalPlayer : public Player
Uint32 mCharId; /**< Used only during character selection. */
Uint32 mJobXp;
- Uint16 mLevel;
Uint32 mJobLevel;
Uint32 mXpForNextLevel, mJobXpForNextLevel;
- Uint16 mHp, mMaxHp, mMp, mMaxMp;
- Uint32 mGp;
+ Uint16 mMp, mMaxMp;
Uint16 mAttackRange;
- Uint32 mTotalWeight, mMaxWeight;
-
Uint8 mAttr[6];
Uint8 mAttrUp[6];
@@ -228,6 +409,88 @@ class LocalPlayer : public Player
Uint16 mStatPoint, mSkillPoint;
Uint16 mStatsPointsToAttribute;
+#endif
+
+ int getHp() const
+ { return mHp; }
+
+ int getMaxHp() const
+ { return mMaxHp; }
+
+ void setHp(int value)
+ { mHp = value; }
+
+ void setMaxHp(int value)
+ { mMaxHp = value; }
+
+ int getLevel() const
+ { return mLevel; }
+
+ void setLevel(int value)
+ { mLevel = value; }
+
+#ifdef TMWSERV_SUPPORT
+ void setLevelProgress(int percent)
+ { mLevelProgress = percent; }
+
+ int getLevelProgress() const
+ { return mLevelProgress; }
+#endif
+
+ int getMoney() const
+ { return mMoney; }
+
+ void setMoney(int value)
+ { mMoney = value; }
+
+ int getTotalWeight() const
+ { return mTotalWeight; }
+
+ void setTotalWeight(int value)
+ { mTotalWeight = value; }
+
+ int getMaxWeight() const
+ { return mMaxWeight; }
+
+ void setMaxWeight(int value)
+ { mMaxWeight = value; }
+
+#ifdef TMWSERV_SUPPORT
+ int getAttributeBase(int num) const
+ { return mAttributeBase[num]; }
+
+ void setAttributeBase(int num, int value)
+ { mAttributeBase[num] = value; }
+
+ int getAttributeEffective(int num) const
+ { return mAttributeEffective[num]; }
+
+ void setAttributeEffective(int num, int value)
+ { mAttributeEffective[num] = value; }
+
+ int getCharacterPoints() const
+ { return mCharacterPoints; }
+
+ void setCharacterPoints(int n)
+ { mCharacterPoints = n; }
+
+ int getCorrectionPoints() const
+ { return mCorrectionPoints; }
+
+ void setCorrectionPoints(int n)
+ { mCorrectionPoints = n; }
+
+ void setExperience(int skill, int current, int next);
+
+ struct SkillInfo {
+ std::string name;
+ std::string icon;
+ };
+
+ static const SkillInfo& getSkillInfo(int skill);
+
+ std::pair<int, int> getExperience(int skill);
+#endif
bool mUpdateName; /** Whether or not the name settings have changed */
@@ -243,27 +506,52 @@ class LocalPlayer : public Player
void walk(unsigned char dir);
+#ifdef EATHENA_SUPPORT
+ Network *mNetwork;
int mXp; /**< Experience points. */
+ bool mInStorage; /**< Whether storage is currently accessible */
+ int mTargetTime; /** How long the being has been targeted **/
+ int mLastTarget; /** Time stamp of last targeting action, -1 if none. */
+#endif
+
+#ifdef TMWSERV_SUPPORT
+ // Character status:
+ std::vector<int> mAttributeBase;
+ std::vector<int> mAttributeEffective;
+ std::vector<int> mExpCurrent;
+ std::vector<int> mExpNext;
+ int mCharacterPoints;
+ int mCorrectionPoints;
+ int mLevelProgress;
+#endif
+ int mLevel;
+ int mMoney;
+ int mTotalWeight;
+ int mMaxWeight;
+ int mHp;
+ int mMaxHp;
- Network *mNetwork;
Being *mTarget;
FloorItem *mPickUpTarget;
bool mTrading;
- bool mInStorage; /**< Whether storage is currently accessible */
bool mGoingToTarget;
bool mKeepAttacking; /** Whether or not to continue to attack */
- int mTargetTime; /** How long the being has been targeted **/
int mLastAction; /**< Time stamp of the last action, -1 if none. */
- int mLastTarget; /** Time stamp of last targeting action, -1 if none. */
int mWalkingDir; /**< The direction the player is walking in. */
int mDestX; /**< X coordinate of destination. */
int mDestY; /**< Y coordinate of destination. */
+#ifdef TMWSERV_SUPPORT
+ int mLocalWalkTime; /**< Timestamp used to control keyboard walk
+ messages flooding */
+#endif
std::vector<int> mStatusEffectIcons;
Inventory *mInventory;
+#ifdef EATHENA_SUPPORT
Inventory *mStorage;
+#endif
// Load the target cursors into memory
void initTargetCursor();
@@ -279,6 +567,11 @@ class LocalPlayer : public Player
/** Animated target cursors. */
SimpleAnimation *mTargetCursor[2][NUM_TC];
+
+#ifdef TMWSERV_SUPPORT
+ std::list<std::string> mExpMessages; /**< Queued exp messages*/
+ int mExpMessageTime;
+#endif
};
extern LocalPlayer *player_node;
diff --git a/src/lockedarray.h b/src/lockedarray.h
index 2b4b099d..c4c83ea9 100644
--- a/src/lockedarray.h
+++ b/src/lockedarray.h
@@ -44,7 +44,7 @@ class LockedArray
bool isLocked() const { return mLocked; };
T getEntry() const { return mData[mCurEntry]; };
- void setEntry(T entry) { mData[mCurEntry] = entry; };
+ void setEntry(T entry) { mData[mCurEntry] = entry; mFilled = true; };
void next();
void prev();
@@ -53,6 +53,11 @@ class LockedArray
unsigned int getSize() const { return mSize; };
+ /**
+ * Clears the array without changing size or data type
+ */
+ void clear();
+
protected:
unsigned int mSize;
@@ -60,11 +65,14 @@ class LockedArray
unsigned int mCurEntry;
bool mLocked;
+
+ bool mFilled;
};
template<class T>
LockedArray<T>::LockedArray(unsigned int size):
- mSize(size), mData(new T[size]), mCurEntry(0), mLocked(false)
+ mSize(size), mData(new T[size]), mCurEntry(0), mLocked(false),
+ mFilled(false)
{
std::fill_n(mData, mSize, (T)0);
}
@@ -105,4 +113,19 @@ void LockedArray<T>::select(unsigned int pos)
mCurEntry = 0;
}
+template<class T>
+void LockedArray<T>::clear()
+{
+ if (!mFilled) return;
+
+ delete [] mData;
+
+ mData = new T[mSize];
+
+ std::fill_n(mData, mSize, (T)0);
+
+ mCurEntry = 0;
+
+ mLocked = false;
+}
#endif
diff --git a/src/logindata.h b/src/logindata.h
index 410d2e73..ae89eb5f 100644
--- a/src/logindata.h
+++ b/src/logindata.h
@@ -24,21 +24,51 @@
#include <string>
+#include <string>
+
struct LoginData
{
std::string username;
std::string password;
+ std::string newPassword;
std::string hostname;
std::string updateHost;
+#ifdef TMWSERV_SUPPORT
+ std::string email;
+ std::string newEmail;
+#endif
short port;
+#ifdef EATHENA_SUPPORT
int account_ID;
int session_ID1;
int session_ID2;
char sex;
+#endif
bool remember; /**< Whether to store the username and host. */
bool registerLogin; /**< Whether an account is being registered. */
-};
+ void clear()
+ {
+ username.clear();
+ password.clear();
+ newPassword.clear();
+ hostname.clear();
+ updateHost.clear();
+#ifdef TMWSERV_SUPPORT
+ email.clear();
+ newEmail.clear();
#endif
+ port = 0;
+
+#ifdef EATHENA_SUPPORT
+ account_ID = 0;
+ session_ID1 = 0;
+ session_ID2 = 0;
+ sex = 0;
+#endif
+ };
+};
+
+#endif // LOGINDATA_H
diff --git a/src/main.cpp b/src/main.cpp
index bdc3941c..7d623f69 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -22,12 +22,11 @@
#include <getopt.h>
#include <iostream>
#include <physfs.h>
-#include <SDL_image.h>
#include <unistd.h>
#include <vector>
+#include <SDL_image.h>
#include <guichan/actionlistener.hpp>
-
#include <guichan/widgets/label.hpp>
#include <libxml/parser.h>
@@ -54,7 +53,9 @@
#include "units.h"
#include "gui/button.h"
+#ifdef EATHENA_SUPPORT
#include "gui/char_server.h"
+#endif
#include "gui/char_select.h"
#include "gui/color.h"
#include "gui/gui.h"
@@ -64,13 +65,35 @@
#include "gui/register.h"
#include "gui/sdlinput.h"
#include "gui/setup.h"
+#ifdef TMWSERV_SUPPORT
+#include "gui/connection.h"
+#include "gui/quitdialog.h"
+#include "gui/serverdialog.h"
+#endif
#include "gui/updatewindow.h"
+#ifdef TMWSERV_SUPPORT
#include "net/charserverhandler.h"
+#include "net/connection.h"
#include "net/loginhandler.h"
-#include "net/maploginhandler.h"
-#include "net/messageout.h"
#include "net/network.h"
+#else
+#include "net/ea/charserverhandler.h"
+#include "net/ea/loginhandler.h"
+#include "net/ea/network.h"
+#include "net/ea/maploginhandler.h"
+#include "net/messageout.h"
+#endif
+#include "net/logouthandler.h"
+
+#ifdef TMWSERV_SUPPORT
+#include "net/accountserver/accountserver.h"
+#include "net/accountserver/account.h"
+
+#include "net/chatserver/chatserver.h"
+
+#include "net/gameserver/gameserver.h"
+#endif
#include "resources/colordb.h"
#include "resources/emotedb.h"
@@ -80,6 +103,9 @@
#include "resources/npcdb.h"
#include "resources/resourcemanager.h"
+#ifdef TMWSERV_SUPPORT
+#include "utils/dtor.h"
+#endif
#include "utils/gettext.h"
#include "utils/stringutils.h"
@@ -112,29 +138,43 @@ namespace
} listener;
}
+#ifdef TMWSERV_SUPPORT
+std::string token; //used to store magic_token
+#else
// Account infos
char n_server, n_character;
-Graphics *graphics;
-
// TODO Anyone knows a good location for this? Or a way to make it non-global?
class SERVER_INFO;
SERVER_INFO **server_info;
+#endif
+
+Graphics *graphics;
unsigned char state;
std::string errorMessage;
-unsigned char screen_mode;
Sound sound;
Music *bgm;
Configuration config; /**< XML file configuration reader */
+Configuration branding; /**< XML branding information reader */
Logger *logger; /**< Log object */
KeyboardConfig keyboard;
+#ifdef TMWSERV_SUPPORT
+Net::Connection *gameServerConnection = 0;
+Net::Connection *chatServerConnection = 0;
+Net::Connection *accountServerConnection = 0;
+#endif
+
CharServerHandler charServerHandler;
LoginData loginData;
-LockedArray<LocalPlayer*> charInfo(MAX_SLOT + 1);
+#ifdef TMWSERV_SUPPORT
+LoginHandler loginHandler;
+LogoutHandler logoutHandler;
+#endif
+LockedArray<LocalPlayer*> charInfo(maxSlot + 1);
Color *textColor;
@@ -145,8 +185,10 @@ std::string homeDir;
std::string updateHost;
std::string updatesDir;
+#ifdef EATHENA_SUPPORT
LoginHandler loginHandler;
MapLoginHandler mapLoginHandler;
+#endif
/**
* A structure holding the values of various options that can be passed from
@@ -161,7 +203,8 @@ struct Options
printHelp(false),
printVersion(false),
skipUpdate(false),
- chooseDefault(false)
+ chooseDefault(false),
+ serverPort(0)
{};
bool printHelp;
@@ -170,10 +213,13 @@ struct Options
bool chooseDefault;
std::string username;
std::string password;
- std::string playername;
+ std::string character;
std::string configPath;
std::string updateHost;
std::string dataPath;
+
+ std::string serverName;
+ short serverPort;
};
/**
@@ -210,7 +256,7 @@ void setUpdatesDir()
{
logger->log("Error: Invalid update host: %s", updateHost.c_str());
errorMessage = _("Invalid update host: ") + updateHost;
- state = ERROR_STATE;
+ state = STATE_ERROR;
}
}
else
@@ -243,36 +289,35 @@ void setUpdatesDir()
logger->log("Error: %s can't be made, but doesn't exist!",
newDir.c_str());
errorMessage = _("Error creating updates directory!");
- state = ERROR_STATE;
+ state = STATE_ERROR;
}
#else
logger->log("Error: %s/%s can't be made, but doesn't exist!",
homeDir.c_str(), updatesDir.c_str());
errorMessage = _("Error creating updates directory!");
- state = ERROR_STATE;
+ state = STATE_ERROR;
#endif
}
}
}
/**
- * Do all initialization stuff
+ * Initializes the home directory. On UNIX and FreeBSD, ~/.tmw is used. On
+ * Windows and other systems we use the current working directory.
*/
-void init_engine(const Options &options)
+void initHomeDir()
{
- if (homeDir.empty())
-#if defined __APPLE__
- // Use Application Directory instead of .tmw
- homeDir = std::string(PHYSFS_getUserDir()) +
- "/Library/Application Support/The Mana World";
-#else
- homeDir = std::string(PHYSFS_getUserDir()) + "/.tmw";
-#endif
-
+ homeDir = std::string(PHYSFS_getUserDir()) +
+ "/." +
+ branding.getValue("appShort", "tmw");
#if defined WIN32
if (!CreateDirectory(homeDir.c_str(), 0) &&
GetLastError() != ERROR_ALREADY_EXISTS)
#elif defined __APPLE__
+ // Use Application Directory instead of .tmw
+ homeDir = std::string(PHYSFS_getUserDir()) +
+ "/Library/Application Support/" +
+ branding.getValue("appName", "The Mana World");
if ((mkdir(homeDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) &&
(errno != EEXIST))
#else
@@ -286,20 +331,76 @@ void init_engine(const Options &options)
<< std::endl;
exit(1);
}
+}
- // Set log file
- logger->setLogFile(homeDir + std::string("/tmw.log"));
+/**
+ * Initialize configuration.
+ */
+void initConfiguration(const Options &options)
+{
+ // Fill configuration with defaults
+ logger->log("Initializing configuration...");
+ std::string defaultHost = branding.getValue("defaultServer",
+ "server.themanaworld.org");
+ config.setValue("host", defaultHost);
+#ifdef TWMSERV_SUPPORT
+ int defaultPort = (int)branding.getValue("defaultPort", 9601);
+#else
+ int defaultPort = (int)branding.getValue("defaultPort", 6901);
+#endif
+ config.setValue("port", defaultPort);
+ config.setValue("hwaccel", 0);
+#if (defined __APPLE__ || defined WIN32) && defined USE_OPENGL
+ config.setValue("opengl", 1);
+#else
+ config.setValue("opengl", 0);
+#endif
+ config.setValue("screen", 0);
+ config.setValue("sound", 1);
+ config.setValue("guialpha", 0.8f);
+ config.setValue("remember", 1);
+ config.setValue("sfxVolume", 100);
+ config.setValue("musicVolume", 60);
+ config.setValue("fpslimit", 0);
+ std::string defaultUpdateHost = branding.getValue("defaultUpdateHost",
+ "http://updates.themanaworld.org");
+ config.setValue("updatehost", defaultUpdateHost);
+ config.setValue("customcursor", 1);
+ config.setValue("ChatLogLength", 128);
+
+ // Checking if the configuration file exists... otherwise create it with
+ // default options.
+ FILE *configFile = 0;
+ std::string configPath = options.configPath;
+
+ if (configPath.empty())
+ configPath = homeDir + "/config.xml";
+
+ configFile = fopen(configPath.c_str(), "r");
- #ifdef PACKAGE_VERSION
- logger->log("Starting The Mana World Version %s", PACKAGE_VERSION);
- #else
- logger->log("Starting The Mana World - Version not defined");
- #endif
+ // If we can't read it, it doesn't exist !
+ if (configFile == NULL) {
+ // We reopen the file in write mode and we create it
+ configFile = fopen(configPath.c_str(), "wt");
+ }
+ if (configFile == NULL) {
+ std::cout << "Can't create " << configPath << ". "
+ << "Using Defaults." << std::endl;
+ } else {
+ fclose(configFile);
+ config.init(configPath);
+ }
+}
+/**
+ * Do all initialization stuff.
+ */
+void initEngine(const Options &options)
+{
// Initialize SDL
logger->log("Initializing SDL...");
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
- std::cerr << _("Could not initialize SDL: ") <<
+ std::cerr << "Could not initialize SDL: " <<
SDL_GetError() << std::endl;
exit(1);
}
@@ -308,11 +409,13 @@ void init_engine(const Options &options)
SDL_EnableUNICODE(1);
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
+ SDL_WM_SetCaption(branding.getValue("appName", "The Mana World").c_str(), NULL);
+
ResourceManager *resman = ResourceManager::getInstance();
if (!resman->setWriteDir(homeDir)) {
std::cout << homeDir
- << _(" couldn't be set as home directory! Exiting.")
+ << " couldn't be set as home directory! Exiting."
<< std::endl;
exit(1);
}
@@ -332,7 +435,7 @@ void init_engine(const Options &options)
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path,
PATH_MAX))
{
- fprintf(stderr, _("Can't find Resources directory\n"));
+ fprintf(stderr, "Can't find Resources directory\n");
}
CFRelease(resourcesURL);
strncat(path, "/data", PATH_MAX - 1);
@@ -341,51 +444,6 @@ void init_engine(const Options &options)
resman->addToSearchPath(PKG_DATADIR "data", true);
#endif
- // Fill configuration with defaults
- logger->log("Initializing configuration...");
- config.setValue("host", "www.themanaworld.org");
- config.setValue("port", 6901);
- config.setValue("hwaccel", 0);
-#if (defined __APPLE__ || defined WIN32) && defined USE_OPENGL
- config.setValue("opengl", 1);
-#else
- config.setValue("opengl", 0);
-#endif
- config.setValue("screen", 0);
- config.setValue("sound", 1);
- config.setValue("guialpha", 0.8f);
- config.setValue("remember", 1);
- config.setValue("sfxVolume", 100);
- config.setValue("musicVolume", 60);
- config.setValue("fpslimit", 0);
- config.setValue("updatehost", "http://updates.themanaworld.org");
- config.setValue("customcursor", 1);
- config.setValue("ChatLogLength", 128);
-
- // Checking if the configuration file exists... otherwise creates it with
- // default options !
- FILE *configFile = 0;
- std::string configPath = options.configPath;
-
- if (configPath.empty())
- configPath = homeDir + "/config.xml";
-
- configFile = fopen(configPath.c_str(), "r");
-
- // If we can't read it, it doesn't exist !
- if (configFile == NULL) {
- // We reopen the file in write mode and we create it
- configFile = fopen(configPath.c_str(), "wt");
- }
- if (configFile == NULL) {
- std::cout << "Can't create " << configPath << ". "
- "Using Defaults." << std::endl;
- } else {
- fclose(configFile);
- config.init(configPath);
- }
-
- SDL_WM_SetCaption("The Mana World", NULL);
#ifdef WIN32
static SDL_SysWMinfo pInfo;
SDL_GetWMInfo(&pInfo);
@@ -395,7 +453,7 @@ void init_engine(const Options &options)
SetClassLong(pInfo.window, GCL_HICON, (LONG) icon);
}
#else
- SDL_Surface *icon = IMG_Load(PKG_DATADIR "data/icons/tmw.png");
+ SDL_Surface *icon = IMG_Load(resman->getPath(branding.getValue("appIcon", "data/icons/tmw.png")).c_str());
if (icon)
{
SDL_SetAlpha(icon, SDL_SRCALPHA, SDL_ALPHA_OPAQUE);
@@ -441,7 +499,11 @@ void init_engine(const Options &options)
emoteShortcut = new EmoteShortcut;
gui = new Gui(graphics);
- state = LOGIN_STATE; /**< Initial game state */
+#ifdef TMWSERV_SUPPORT
+ state = STATE_CHOOSE_SERVER; /**< Initial game state */
+#else
+ state = STATE_LOGIN; /**< Initial game state */
+#endif
// Initialize sound engine
try {
@@ -454,7 +516,7 @@ void init_engine(const Options &options)
defaultMusicVolume));
}
catch (const char *err) {
- state = ERROR_STATE;
+ state = STATE_ERROR;
errorMessage = err;
logger->log("Warning: %s", err);
}
@@ -492,7 +554,6 @@ void exit_engine()
NPCDB::unload();
ResourceManager::deleteInstance();
- delete logger;
}
void printHelp()
@@ -507,8 +568,10 @@ void printHelp()
<< _(" -h --help : Display this help") << std::endl
<< _(" -S --homedir : Directory to use as home directory") << std::endl
<< _(" -H --updatehost : Use this update host") << std::endl
- << _(" -p --playername : Login with this player") << std::endl
<< _(" -P --password : Login with this password") << std::endl
+ << _(" -c --character : Login with this character") << std::endl
+ << _(" -o --port : Login Server Port") << std::endl
+ << _(" -s --server : Login Server name or IP") << std::endl
<< _(" -u --skipupdate : Skip the update downloads") << std::endl
<< _(" -U --username : Login with this username") << std::endl
<< _(" -v --version : Display the version") << std::endl;
@@ -526,17 +589,19 @@ void printVersion()
void parseOptions(int argc, char *argv[], Options &options)
{
- const char *optstring = "hvud:U:P:Dp:C:H:S:";
+ const char *optstring = "hvud:U:P:Dc:s:o:C:H:S:";
const struct option long_options[] = {
{ "configfile", required_argument, 0, 'C' },
{ "data", required_argument, 0, 'd' },
{ "default", no_argument, 0, 'D' },
- { "playername", required_argument, 0, 'p' },
{ "password", required_argument, 0, 'P' },
+ { "character", required_argument, 0, 'c' },
{ "help", no_argument, 0, 'h' },
{ "homedir", required_argument, 0, 'S' },
{ "updatehost", required_argument, 0, 'H' },
+ { "port", required_argument, 0, 'o' },
+ { "server", required_argument, 0, 's' },
{ "skipupdate", no_argument, 0, 'u' },
{ "username", required_argument, 0, 'U' },
{ "version", no_argument, 0, 'v' },
@@ -567,12 +632,18 @@ void parseOptions(int argc, char *argv[], Options &options)
case 'H':
options.updateHost = optarg;
break;
- case 'p':
- options.playername = optarg;
+ case 'c':
+ options.character = optarg;
break;
case 'P':
options.password = optarg;
break;
+ case 's':
+ options.serverName = optarg;
+ break;
+ case 'o':
+ options.serverPort = (short)atoi(optarg);
+ break;
case 'u':
options.skipUpdate = true;
break;
@@ -613,20 +684,62 @@ struct ErrorListener : public gcn::ActionListener
{
void action(const gcn::ActionEvent &event)
{
- state = loginData.registerLogin ? REGISTER_STATE : LOGIN_STATE;
+#ifdef TMWSERV_SUPPORT
+ state = STATE_CHOOSE_SERVER;
+#else
+ state = loginData.registerLogin ? STATE_REGISTER : STATE_LOGIN;
+#endif
}
} errorListener;
+#ifdef TMWSERV_SUPPORT
+struct AccountListener : public gcn::ActionListener
+{
+ void action(const gcn::ActionEvent &event)
+ {
+ state = STATE_CHAR_SELECT;
+ }
+} accountListener;
+
+struct LoginListener : public gcn::ActionListener
+{
+ void action(const gcn::ActionEvent &event)
+ {
+ state = STATE_LOGIN;
+ }
+} loginListener;
+#endif
+
// TODO Find some nice place for these functions
+#ifdef TMWSERV_SUPPORT
+void accountLogin(LoginData *loginData)
+#else
void accountLogin(Network *network, LoginData *loginData)
+#endif
{
+#ifdef EATHENA_SUPPORT
logger->log("Trying to connect to account server...");
+#endif
logger->log("Username is %s", loginData->username.c_str());
+#ifdef EATHENA_SUPPORT
network->connect(loginData->hostname, loginData->port);
network->registerHandler(&loginHandler);
+#endif
loginHandler.setLoginData(loginData);
+#ifdef TMWSERV_SUPPORT
+ Net::registerHandler(&loginHandler);
+
+ charServerHandler.setCharInfo(&charInfo);
+ Net::registerHandler(&charServerHandler);
+#endif
// Send login infos
+#ifdef TMWSERV_SUPPORT
+ Net::AccountServer::login(accountServerConnection,
+ 0, // client version
+ loginData->username,
+ loginData->password);
+#else
MessageOut outMsg(network);
outMsg.writeInt16(0x0064);
outMsg.writeInt32(0); // client version
@@ -640,16 +753,19 @@ void accountLogin(Network *network, LoginData *loginData)
* 0 here.
*/
outMsg.writeInt8(0x01);
+#endif
// Clear the password, avoids auto login when returning to login
loginData->password = "";
+#ifdef EATHENA_SUPPORT
// Remove _M or _F from username after a login for registration purpose
if (loginData->registerLogin)
{
loginData->username =
loginData->username.substr(0, loginData->username.length() - 2);
}
+#endif
// TODO This is not the best place to save the config, but at least better
// than the login gui window
@@ -661,6 +777,8 @@ void accountLogin(Network *network, LoginData *loginData)
config.setValue("remember", loginData->remember);
}
+#ifdef EATHENA_SUPPORT
+
static void positionDialog(Window *dialog, int screenWidth, int screenHeight)
{
dialog->setPosition(
@@ -717,6 +835,160 @@ void mapLogin(Network *network, LoginData *loginData)
network->skip(4);
}
+#else
+
+void accountRegister(LoginData *loginData)
+{
+ logger->log("Username is %s", loginData->username.c_str());
+
+ Net::registerHandler(&loginHandler);
+
+ charServerHandler.setCharInfo(&charInfo);
+ Net::registerHandler(&charServerHandler);
+
+ Net::AccountServer::registerAccount(accountServerConnection,
+ 0, // client version
+ loginData->username,
+ loginData->password,
+ loginData->email);
+}
+
+void accountUnRegister(LoginData *loginData)
+{
+ Net::registerHandler(&logoutHandler);
+
+ Net::AccountServer::Account::unregister(loginData->username,
+ loginData->password);
+
+}
+
+void accountChangePassword(LoginData *loginData)
+{
+ Net::registerHandler(&loginHandler);
+
+ Net::AccountServer::Account::changePassword(loginData->username,
+ loginData->password,
+ loginData->newPassword);
+}
+
+void accountChangeEmail(LoginData *loginData)
+{
+ Net::registerHandler(&loginHandler);
+
+ Net::AccountServer::Account::changeEmail(loginData->newEmail);
+}
+
+void switchCharacter(std::string* passToken)
+{
+ Net::registerHandler(&logoutHandler);
+
+ logoutHandler.reset();
+ logoutHandler.setScenario(LOGOUT_SWITCH_CHARACTER, passToken);
+
+ Net::GameServer::logout(true);
+ Net::ChatServer::logout();
+}
+
+void switchAccountServer()
+{
+ Net::registerHandler(&logoutHandler);
+
+ logoutHandler.reset();
+ logoutHandler.setScenario(LOGOUT_SWITCH_ACCOUNTSERVER);
+
+ //Can't logout if we were not logged in ...
+ if (accountServerConnection->isConnected())
+ {
+ Net::AccountServer::logout();
+ }
+ else
+ {
+ logoutHandler.setAccountLoggedOut();
+ }
+
+ if (gameServerConnection->isConnected())
+ {
+ Net::GameServer::logout(false);
+ }
+ else
+ {
+ logoutHandler.setGameLoggedOut();
+ }
+
+ if (chatServerConnection->isConnected())
+ {
+ Net::ChatServer::logout();
+ }
+ else
+ {
+ logoutHandler.setChatLoggedOut();
+ }
+}
+
+void logoutThenExit()
+{
+ Net::registerHandler(&logoutHandler);
+
+ logoutHandler.reset();
+ logoutHandler.setScenario(LOGOUT_EXIT);
+
+ // Can't logout if we were not logged in ...
+ if (accountServerConnection->isConnected())
+ {
+ Net::AccountServer::logout();
+ }
+ else
+ {
+ logoutHandler.setAccountLoggedOut();
+ }
+
+ if (gameServerConnection->isConnected())
+ {
+ Net::GameServer::logout(false);
+ }
+ else
+ {
+ logoutHandler.setGameLoggedOut();
+ }
+
+ if (chatServerConnection->isConnected())
+ {
+ Net::ChatServer::logout();
+ }
+ else
+ {
+ logoutHandler.setChatLoggedOut();
+ }
+}
+
+void reconnectAccount(const std::string& passToken)
+{
+ Net::registerHandler(&loginHandler);
+
+ charServerHandler.setCharInfo(&charInfo);
+ Net::registerHandler(&charServerHandler);
+
+ Net::AccountServer::reconnectAccount(accountServerConnection, passToken);
+}
+
+#endif
+
+void xmlNullLogger(void *ctx, const char *msg, ...)
+{
+ // Does nothing, that's the whole point of it
+}
+
+// Initialize libxml2 and check for potential ABI mismatches between
+// compiled version and the shared library actually used.
+void initXML()
+{
+ xmlInitParser();
+ LIBXML_TEST_VERSION;
+
+ // Suppress libxml2 error messages
+ xmlSetGenericErrorFunc(NULL, xmlNullLogger);
+}
+
} // namespace
extern "C" char const *_nl_locale_name_default(void);
@@ -724,12 +996,9 @@ extern "C" char const *_nl_locale_name_default(void);
/** Main */
int main(int argc, char *argv[])
{
- logger = new Logger;
-
+ // Parse command line options
Options options;
-
parseOptions(argc, argv, options);
-
if (options.printHelp)
{
printHelp();
@@ -743,47 +1012,57 @@ int main(int argc, char *argv[])
#if ENABLE_NLS
#ifdef WIN32
- putenv(("LANG=" + std::string(_nl_locale_name_default())).c_str());
- // mingw doesn't like LOCALEDIR to be defined for some reason
- bindtextdomain("tmw", "translations/");
+ putenv(("LANG=" + std::string(_nl_locale_name_default())).c_str());
+ // mingw doesn't like LOCALEDIR to be defined for some reason
+ bindtextdomain("tmw", "translations/");
#else
- bindtextdomain("tmw", LOCALEDIR);
+ bindtextdomain("tmw", LOCALEDIR);
#endif
- setlocale(LC_MESSAGES, "");
- bind_textdomain_codeset("tmw", "UTF-8");
- textdomain("tmw");
+ setlocale(LC_MESSAGES, "");
+ bind_textdomain_codeset("tmw", "UTF-8");
+ textdomain("tmw");
#endif
- // Initialize libxml2 and check for potential ABI mismatches between
- // compiled version and the shared library actually used.
- xmlInitParser();
- LIBXML_TEST_VERSION;
-
- // Redirect libxml errors to /dev/null
- FILE *nullFile = fopen("/dev/null", "w");
- xmlSetGenericErrorFunc(nullFile, NULL);
-
// Initialize PhysicsFS
PHYSFS_init(argv[0]);
- init_engine(options);
+ initXML();
- SDL_Event event;
+ // load branding information
+ branding.init("data/branding.xml");
- unsigned int oldstate = !state; // We start with a status change.
+ initHomeDir();
+ // Configure logger
+ logger = new Logger();
+ logger->setLogFile(homeDir + std::string("/tmw.log"));
+ logger->setLogToStandardOut(config.getValue("logToStandardOut", 0));
+
+ // Log the tmw version
+#ifdef PACKAGE_VERSION
+ logger->log("The Mana World v%s", PACKAGE_VERSION);
+#else
+ logger->log("The Mana World - version not defined");
+#endif
+
+ initConfiguration(options);
+
+ initEngine(options);
// Needs to be created in main, as the updater uses it
textColor = new Color;
Game *game = NULL;
Window *currentDialog = NULL;
+#ifdef TMWSERV_SUPPORT
+ QuitDialog* quitDialog = NULL;
+#endif
Image *login_wallpaper = NULL;
setupWindow = new Setup;
gcn::Container *top = static_cast<gcn::Container*>(gui->getTop());
#ifdef PACKAGE_VERSION
gcn::Label *versionLabel = new gcn::Label(PACKAGE_VERSION);
- top->add(versionLabel, 2, 2);
+ top->add(versionLabel, 25, 2);
#endif
ProgressBar *progressBar = new ProgressBar(0.0f, 100, 20, 168, 116, 31);
gcn::Label *progressLabel = new gcn::Label();
@@ -795,7 +1074,22 @@ int main(int argc, char *argv[])
setup->setPosition(top->getWidth() - setup->getWidth() - 3, 3);
top->add(setup);
- sound.playMusic("Magick - Real.ogg");
+ sound.playMusic(branding.getValue("loginMusic", ""));
+
+ // Server choice
+ if (options.serverName.empty()) {
+ loginData.hostname = config.getValue("MostUsedServerName0",
+ branding.getValue("defaultServer", "server.themanaworld.org").c_str());
+ }
+ else {
+ loginData.hostname = options.serverName;
+ }
+ if (options.serverPort == 0) {
+ loginData.port = (short)config.getValue("MostUsedServerPort0",
+ branding.getValue("defaultPort", 9601));
+ } else {
+ loginData.port = options.serverPort;
+ }
loginData.username = options.username;
if (loginData.username.empty()) {
@@ -806,18 +1100,30 @@ int main(int argc, char *argv[])
if (!options.password.empty()) {
loginData.password = options.password;
}
+
+#ifdef EATHENA_SUPPORT
loginData.hostname = config.getValue("host", "server.themanaworld.org");
loginData.port = (short)config.getValue("port", 6901);
+#endif
loginData.remember = config.getValue("remember", 0);
loginData.registerLogin = false;
+#ifdef TMWSERV_SUPPORT
+ Net::initialize();
+ accountServerConnection = Net::getConnection();
+ gameServerConnection = Net::getConnection();
+ chatServerConnection = Net::getConnection();
+#else
SDLNet_Init();
Network *network = new Network;
+#endif
// Set the most appropriate wallpaper, based on screen width
int screenWidth = (int) config.getValue("screenwidth", defaultScreenWidth);
+#ifdef EATHENA_SUPPORT
int screenHeight = static_cast<int>(config.getValue("screenheight",
defaultScreenHeight));
+#endif
std::string wallpaperName;
wallpaperName = "graphics/images/login_wallpaper.png";
@@ -838,19 +1144,43 @@ int main(int argc, char *argv[])
if (!login_wallpaper)
logger->log("Couldn't load %s as wallpaper", wallpaperName.c_str());
- while (state != EXIT_STATE)
+ unsigned int oldstate = !state; // We start with a status change.
+
+ SDL_Event event;
+#ifdef TMWSERV_SUPPORT
+ while (state != STATE_FORCE_QUIT)
+#else
+ while (state != STATE_EXIT)
+#endif
{
// Handle SDL events
- while (SDL_PollEvent(&event)) {
- switch (event.type) {
+ while (SDL_PollEvent(&event))
+ {
+ switch (event.type)
+ {
case SDL_QUIT:
- state = EXIT_STATE;
+#ifdef TMWSERV_SUPPORT
+ state = STATE_FORCE_QUIT;
+#else
+ state = STATE_EXIT;
+#endif
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_ESCAPE)
{
- state = EXIT_STATE;
+#ifdef TMWSERV_SUPPORT
+ if (!quitDialog)
+ {
+ quitDialog = new QuitDialog(NULL, &quitDialog);
+ }
+ else
+ {
+ quitDialog->requestMoveToTop();
+ }
+#else
+ state = STATE_EXIT;
+#endif
}
break;
}
@@ -858,13 +1188,18 @@ int main(int argc, char *argv[])
guiInput->pushInput(event);
}
+#ifdef TMWSERV_SUPPORT
+ Net::flush();
+#else
network->flush();
network->dispatchMessages();
+#endif
gui->logic();
+#ifdef EATHENA_SUPPORT
if (network->getState() == Network::NET_ERROR)
{
- state = ERROR_STATE;
+ state = STATE_ERROR;
if (!network->getError().empty()) {
errorMessage = network->getError();
@@ -872,6 +1207,7 @@ int main(int argc, char *argv[])
errorMessage = _("Got disconnected from server!");
}
}
+#endif
if (progressBar->isVisible())
{
@@ -893,10 +1229,320 @@ int main(int argc, char *argv[])
gui->draw();
graphics->updateScreen();
+#ifdef TMWSERV_SUPPORT
+ // TODO: Add connect timeouts
+ if (state == STATE_CONNECT_ACCOUNT &&
+ accountServerConnection->isConnected())
+ {
+ if (options.skipUpdate) {
+ state = STATE_LOADDATA;
+ } else {
+ state = STATE_UPDATE;
+ }
+ }
+ else if (state == STATE_CONNECT_GAME &&
+ gameServerConnection->isConnected() &&
+ chatServerConnection->isConnected())
+ {
+ accountServerConnection->disconnect();
+ Net::clearHandlers();
+
+ state = STATE_GAME;
+ }
+ else if (state == STATE_RECONNECT_ACCOUNT &&
+ accountServerConnection->isConnected())
+ {
+ reconnectAccount(token);
+ state = STATE_WAIT;
+ }
+#endif
+
+#ifdef TMWSERV_SUPPORT
+ if (state != oldstate) {
+ // Load updates after exiting the update state
+ if (oldstate == STATE_UPDATE)
+ {
+ loadUpdates();
+ // Reload the wallpaper in case that it was updated
+ login_wallpaper->decRef();
+ login_wallpaper = ResourceManager::getInstance()->getImage(
+ branding.getValue("loginWallpaper",
+ "graphics/images/login_wallpaper.png"));
+ }
+
+ oldstate = state;
+
+ // Get rid of the dialog of the previous state
+ if (currentDialog) {
+ delete currentDialog;
+ currentDialog = NULL;
+ }
+ // State has changed, while the quitDialog was active, it might
+ // not be correct anymore
+ if (quitDialog) {
+ quitDialog->scheduleDelete();
+ }
+
+ switch (state) {
+ case STATE_CHOOSE_SERVER:
+ logger->log("State: CHOOSE_SERVER");
+
+ // Allow changing this using a server choice dialog
+ // We show the dialog box only if the command-line
+ // options weren't set.
+ if (options.serverName.empty() && options.serverPort == 0) {
+ currentDialog = new ServerDialog(&loginData);
+ } else {
+ state = STATE_CONNECT_ACCOUNT;
+
+ // Reset options so that cancelling or connect
+ // timeout will show the server dialog.
+ options.serverName.clear();
+ options.serverPort = 0;
+ }
+ break;
+
+ case STATE_CONNECT_ACCOUNT:
+ logger->log("State: CONNECT_ACCOUNT");
+ logger->log("Trying to connect to account server...");
+ accountServerConnection->connect(loginData.hostname,
+ loginData.port);
+ currentDialog = new ConnectionDialog(
+ STATE_SWITCH_ACCOUNTSERVER_ATTEMPT);
+ break;
+
+ case STATE_UPDATE:
+ // Determine which source to use for the update host
+ if (!options.updateHost.empty())
+ updateHost = options.updateHost;
+ else
+ updateHost = loginData.updateHost;
+
+ setUpdatesDir();
+ logger->log("State: UPDATE");
+ currentDialog = new UpdaterWindow(updateHost,
+ homeDir + "/" + updatesDir);
+ break;
+
+ case STATE_LOGIN:
+ logger->log("State: LOGIN");
+ if (options.username.empty()
+ || options.password.empty()) {
+ currentDialog = new LoginDialog(&loginData);
+ } else {
+ state = STATE_LOGIN_ATTEMPT;
+ // Clear the password so that when login fails, the
+ // dialog will show up next time.
+ options.password.clear();
+ }
+ break;
+
+ case STATE_LOADDATA:
+ logger->log("State: LOADDATA");
+
+ // Add customdata directory
+ ResourceManager::getInstance()->searchAndAddArchives(
+ "customdata/",
+ "zip",
+ false);
+
+ // Load XML databases
+ ColorDB::load();
+ ItemDB::load();
+ MonsterDB::load();
+ NPCDB::load();
+ EmoteDB::load();
+ Units::loadUnits();
+
+ state = STATE_LOGIN;
+ break;
+
+ case STATE_LOGIN_ATTEMPT:
+ accountLogin(&loginData);
+ break;
+
+ case STATE_LOGIN_ERROR:
+ logger->log("State: LOGIN ERROR");
+ currentDialog = new OkDialog("Error ", errorMessage);
+ currentDialog->addActionListener(&loginListener);
+ currentDialog = NULL; // OkDialog deletes itself
+ break;
+
+ case STATE_SWITCH_ACCOUNTSERVER:
+ logger->log("State: SWITCH_ACCOUNTSERVER");
+
+ gameServerConnection->disconnect();
+ chatServerConnection->disconnect();
+ accountServerConnection->disconnect();
+
+ state = STATE_CHOOSE_SERVER;
+ break;
+
+ case STATE_SWITCH_ACCOUNTSERVER_ATTEMPT:
+ logger->log("State: SWITCH_ACCOUNTSERVER_ATTEMPT");
+ switchAccountServer();
+
+ state = STATE_SWITCH_ACCOUNTSERVER;
+ break;
+
+ case STATE_REGISTER:
+ logger->log("State: REGISTER");
+ currentDialog = new RegisterDialog(&loginData);
+ break;
+
+ case STATE_REGISTER_ATTEMPT:
+ accountRegister(&loginData);
+ break;
+
+ case STATE_CHAR_SELECT:
+ logger->log("State: CHAR_SELECT");
+ currentDialog =
+ new CharSelectDialog(&charInfo, &loginData);
+
+ if (((CharSelectDialog*) currentDialog)->
+ selectByName(options.character)) {
+ ((CharSelectDialog*) currentDialog)->action(
+ gcn::ActionEvent(NULL, "ok"));
+ } else {
+ ((CharSelectDialog*) currentDialog)->selectByName(
+ config.getValue("lastCharacter", ""));
+ }
+
+ break;
+
+ case STATE_CHANGEEMAIL_ATTEMPT:
+ logger->log("State: CHANGE EMAIL ATTEMPT");
+ accountChangeEmail(&loginData);
+ break;
+
+ case STATE_CHANGEEMAIL:
+ logger->log("State: CHANGE EMAIL");
+ currentDialog = new OkDialog("Email Address change",
+ "Email Address changed successfully!");
+ currentDialog->addActionListener(&accountListener);
+ currentDialog = NULL; // OkDialog deletes itself
+ loginData.email = loginData.newEmail;
+ loginData.newEmail = "";
+ break;
+
+ case STATE_CHANGEPASSWORD_ATTEMPT:
+ logger->log("State: CHANGE PASSWORD ATTEMPT");
+ accountChangePassword(&loginData);
+ break;
+
+ case STATE_CHANGEPASSWORD:
+ logger->log("State: CHANGE PASSWORD");
+ currentDialog = new OkDialog("Password change",
+ "Password changed successfully!");
+ currentDialog->addActionListener(&accountListener);
+ currentDialog = NULL; // OkDialog deletes itself
+ loginData.password = loginData.newPassword;
+ loginData.newPassword = "";
+ break;
+
+ case STATE_UNREGISTER_ATTEMPT:
+ logger->log("State: UNREGISTER ATTEMPT");
+ accountUnRegister(&loginData);
+ break;
+
+ case STATE_UNREGISTER:
+ logger->log("State: UNREGISTER");
+ accountServerConnection->disconnect();
+ currentDialog = new OkDialog("Unregister successful",
+ "Farewell, come back any time ....");
+ loginData.clear();
+ //The errorlistener sets the state to STATE_CHOOSE_SERVER
+ currentDialog->addActionListener(&errorListener);
+ currentDialog = NULL; // OkDialog deletes itself
+ break;
+
+ case STATE_ACCOUNTCHANGE_ERROR:
+ logger->log("State: ACCOUNT CHANGE ERROR");
+ currentDialog = new OkDialog("Error ", errorMessage);
+ currentDialog->addActionListener(&accountListener);
+ currentDialog = NULL; // OkDialog deletes itself
+ break;
+
+
+ case STATE_ERROR:
+ logger->log("State: ERROR");
+ currentDialog = new OkDialog("Error", errorMessage);
+ currentDialog->addActionListener(&errorListener);
+ currentDialog = NULL; // OkDialog deletes itself
+ gameServerConnection->disconnect();
+ chatServerConnection->disconnect();
+ Net::clearHandlers();
+ break;
+
+ case STATE_CONNECT_GAME:
+ logger->log("State: CONNECT_GAME");
+ currentDialog = new ConnectionDialog(STATE_SWITCH_ACCOUNTSERVER_ATTEMPT);
+ break;
+
+ case STATE_GAME:
+ logger->log("Memorizing selected character %s",
+ player_node->getName().c_str());
+ config.setValue("lastCharacter", player_node->getName());
+
+ Net::GameServer::connect(gameServerConnection, token);
+ Net::ChatServer::connect(chatServerConnection, token);
+ sound.fadeOutMusic(1000);
+
+#ifdef PACKAGE_VERSION
+ delete versionLabel;
+ versionLabel = NULL;
+#endif
+ currentDialog = NULL;
+
+ logger->log("State: GAME");
+ game = new Game;
+ game->logic();
+ delete game;
+
+ // If the quitdialog didn't set the next state
+ if (state == STATE_GAME)
+ {
+ state = STATE_EXIT;
+ }
+ break;
+
+ case STATE_SWITCH_CHARACTER:
+ logger->log("State: SWITCH_CHARACTER");
+ switchCharacter(&token);
+ break;
+
+ case STATE_RECONNECT_ACCOUNT:
+ logger->log("State: RECONNECT_ACCOUNT");
+
+ // Done with game & chat
+ gameServerConnection->disconnect();
+ chatServerConnection->disconnect();
+
+ accountServerConnection->connect(
+ loginData.hostname,
+ loginData.port);
+ break;
+
+ case STATE_WAIT:
+ break;
+
+ case STATE_EXIT:
+ logger->log("State: EXIT");
+ logoutThenExit();
+ break;
+
+ default:
+ state = STATE_FORCE_QUIT;
+ break;
+ }
+ }
+
+#else // no TMWSERV_SUPPORT
+
if (state != oldstate) {
switch (oldstate)
{
- case UPDATE_STATE:
+ case STATE_UPDATE:
loadUpdates();
// Reload the wallpaper in case that it was updated
login_wallpaper->decRef();
@@ -907,12 +1553,12 @@ int main(int argc, char *argv[])
break;
// Those states don't cause a network disconnect
- case LOADDATA_STATE:
+ case STATE_LOADDATA:
break;
- case ACCOUNT_STATE:
- case CHAR_CONNECT_STATE:
- case CONNECTING_STATE:
+ case STATE_ACCOUNT:
+ case STATE_CHAR_CONNECT:
+ case STATE_CONNECTING:
progressBar->setVisible(false);
progressLabel->setCaption("");
break;
@@ -925,14 +1571,14 @@ int main(int argc, char *argv[])
oldstate = state;
- if (currentDialog && state != ACCOUNT_STATE &&
- state != CHAR_CONNECT_STATE) {
+ if (currentDialog && state != STATE_ACCOUNT &&
+ state != STATE_CHAR_CONNECT) {
delete currentDialog;
currentDialog = NULL;
}
switch (state) {
- case LOADDATA_STATE:
+ case STATE_LOADDATA:
logger->log("State: LOADDATA");
// Add customdata directory
@@ -948,15 +1594,15 @@ int main(int argc, char *argv[])
NPCDB::load();
EmoteDB::load();
- state = CHAR_CONNECT_STATE;
+ state = STATE_CHAR_CONNECT;
break;
- case LOGIN_STATE:
+ case STATE_LOGIN:
logger->log("State: LOGIN");
if (!loginData.password.empty()) {
loginData.registerLogin = false;
- state = ACCOUNT_STATE;
+ state = STATE_ACCOUNT;
} else {
currentDialog = new LoginDialog(&loginData);
positionDialog(currentDialog, screenWidth,
@@ -964,13 +1610,13 @@ int main(int argc, char *argv[])
}
break;
- case REGISTER_STATE:
+ case STATE_REGISTER:
logger->log("State: REGISTER");
currentDialog = new RegisterDialog(&loginData);
positionDialog(currentDialog, screenWidth, screenHeight);
break;
- case CHAR_SERVER_STATE:
+ case STATE_CHAR_SERVER:
logger->log("State: CHAR_SERVER");
if (n_server == 1)
@@ -979,25 +1625,25 @@ int main(int argc, char *argv[])
loginData.hostname = ipToString(si->address);
loginData.port = si->port;
loginData.updateHost = si->updateHost;
- state = UPDATE_STATE;
+ state = STATE_UPDATE;
}
else
{
int nextState = (options.skipUpdate) ?
- LOADDATA_STATE : UPDATE_STATE;
+ STATE_LOADDATA : STATE_UPDATE;
currentDialog = new ServerSelectDialog(&loginData,
nextState);
positionDialog(currentDialog, screenWidth,
screenHeight);
if (options.chooseDefault
- || !options.playername.empty())
+ || !options.character.empty())
{
((ServerSelectDialog*) currentDialog)->action(
gcn::ActionEvent(NULL, "ok"));
}
}
break;
- case CHAR_SELECT_STATE:
+ case STATE_CHAR_SELECT:
logger->log("State: CHAR_SELECT");
currentDialog = new CharSelectDialog(network, &charInfo,
(loginData.sex == 0) ?
@@ -1005,7 +1651,7 @@ int main(int argc, char *argv[])
positionDialog(currentDialog, screenWidth, screenHeight);
if (((CharSelectDialog*) currentDialog)->
- selectByName(options.playername))
+ selectByName(options.character))
options.chooseDefault = true;
else
((CharSelectDialog*) currentDialog)->selectByName(
@@ -1017,7 +1663,7 @@ int main(int argc, char *argv[])
break;
- case GAME_STATE:
+ case STATE_GAME:
sound.fadeOutMusic(1000);
#ifdef PACKAGE_VERSION
@@ -1040,10 +1686,10 @@ int main(int argc, char *argv[])
game = new Game(network);
game->logic();
delete game;
- state = EXIT_STATE;
+ state = STATE_EXIT;
break;
- case UPDATE_STATE:
+ case STATE_UPDATE:
// Determine which source to use for the update host
if (!options.updateHost.empty())
updateHost = options.updateHost;
@@ -1054,7 +1700,7 @@ int main(int argc, char *argv[])
logger->log("State: UPDATE");
if (options.skipUpdate) {
- state = LOADDATA_STATE;
+ state = STATE_LOADDATA;
} else {
currentDialog = new UpdaterWindow(updateHost,
homeDir + "/" + updatesDir);
@@ -1063,7 +1709,7 @@ int main(int argc, char *argv[])
}
break;
- case ERROR_STATE:
+ case STATE_ERROR:
logger->log("State: ERROR");
currentDialog = new OkDialog(_("Error"), errorMessage);
positionDialog(currentDialog, screenWidth, screenHeight);
@@ -1073,7 +1719,7 @@ int main(int argc, char *argv[])
network->clearHandlers();
break;
- case CONNECTING_STATE:
+ case STATE_CONNECTING:
logger->log("State: CONNECTING");
progressBar->setVisible(true);
progressLabel->setCaption(
@@ -1082,7 +1728,7 @@ int main(int argc, char *argv[])
mapLogin(network, &loginData);
break;
- case CHAR_CONNECT_STATE:
+ case STATE_CHAR_CONNECT:
progressBar->setVisible(true);
progressLabel->setCaption(
_("Connecting to character server..."));
@@ -1090,7 +1736,7 @@ int main(int argc, char *argv[])
charLogin(network, &loginData);
break;
- case ACCOUNT_STATE:
+ case STATE_ACCOUNT:
progressBar->setVisible(true);
progressLabel->setCaption(
_("Connecting to account server..."));
@@ -1099,10 +1745,11 @@ int main(int argc, char *argv[])
break;
default:
- state = EXIT_STATE;
+ state = STATE_EXIT;
break;
}
}
+#endif
/*
* This loop can really stress the CPU, for no reason since it's
* just constantly redrawing the wallpaper. Added the following
@@ -1120,16 +1767,28 @@ int main(int argc, char *argv[])
delete setup;
delete setupWindow;
+#ifdef TMWSERV_SUPPORT
+ if (accountServerConnection)
+ accountServerConnection->disconnect();
+ if (gameServerConnection)
+ gameServerConnection->disconnect();
+ if (chatServerConnection)
+ chatServerConnection->disconnect();
+
+ delete accountServerConnection;
+ delete gameServerConnection;
+ delete chatServerConnection;
+ Net::finalize();
+#else
delete network;
SDLNet_Quit();
+#endif
- if (nullFile)
- {
- fclose(nullFile);
- }
- logger->log("State: EXIT");
+ logger->log("Quitting");
exit_engine();
PHYSFS_deinit();
+ delete logger;
+
return 0;
}
diff --git a/src/main.h b/src/main.h
index 1d984661..11ea1f70 100644
--- a/src/main.h
+++ b/src/main.h
@@ -22,6 +22,35 @@
#ifndef MAIN_H
#define MAIN_H
+/**
+ * \mainpage
+ *
+ * \section Introduction Introduction
+ *
+ * This is the documentation for the client of The Mana World
+ * (http://themanaworld.org). It is always a work in progress, with the intent
+ * to make it easier for new developers to grow familiar with the source code.
+ *
+ * \section General General information
+ *
+ * During the game, the current Map is displayed by the main Viewport, which
+ * is the bottom-most widget in the WindowContainer. Aside the viewport, the
+ * window container keeps track of all the \link Window Windows\endlink
+ * displayed during the game. It is the <i>top</i> widget for Guichan.
+ *
+ * A Map is composed of several layers of \link Image Images\endlink (tiles),
+ * a layer with collision information and \link Sprite Sprites\endlink. The
+ * sprites define the visible part of \link Being Beings\endlink and
+ * \link FloorItem FloorItems\endlink, they are drawn from top to bottom
+ * by the map, interleaved with the tiles in the fringe layer.
+ *
+ * The server is split up into an \link Net::AccountServer account
+ * server\endlink, a \link Net::ChatServer chat server\endlink and a \link
+ * Net::GameServer game server\endlink. There may be multiple game servers.
+ * Handling of incoming messages is spread over several \link MessageHandler
+ * MessageHanders\endlink.
+ */
+
#include <string>
#ifdef HAVE_CONFIG_H
@@ -29,7 +58,7 @@
#elif defined WIN32
#include "winver.h"
#elif defined __APPLE__
-#define PACKAGE_VERSION "0.0.29"
+#define PACKAGE_VERSION "0.1.0"
#endif
#ifndef PKG_DATADIR
@@ -40,20 +69,43 @@
* Client different States
*/
enum {
- EXIT_STATE,
- LOADDATA_STATE,
- LOGIN_STATE,
- ACCOUNT_STATE,
- REGISTER_STATE,
- CHAR_CONNECT_STATE,
- CHAR_SERVER_STATE,
- CHAR_SELECT_STATE,
- CHAR_NEW_STATE,
- CHAR_DEL_STATE,
- GAME_STATE,
- ERROR_STATE,
- UPDATE_STATE,
- CONNECTING_STATE
+ STATE_EXIT,
+ STATE_LOADDATA,
+ STATE_LOGIN,
+ STATE_REGISTER,
+ STATE_CHAR_SELECT,
+ STATE_GAME,
+ STATE_ERROR,
+ STATE_UPDATE,
+#ifdef TMWSERV_SUPPORT
+ STATE_CHOOSE_SERVER,
+ STATE_CONNECT_ACCOUNT,
+ STATE_LOGIN_ATTEMPT,
+ STATE_LOGIN_ERROR,
+ STATE_REGISTER_ATTEMPT,
+ STATE_ACCOUNTCHANGE_ERROR,
+ STATE_CHANGEEMAIL_ATTEMPT,
+ STATE_CHANGEEMAIL,
+ STATE_CHANGEPASSWORD_ATTEMPT,
+ STATE_CHANGEPASSWORD,
+ STATE_UNREGISTER_ATTEMPT,
+ STATE_UNREGISTER,
+ STATE_SWITCH_CHARACTER,
+ STATE_RECONNECT_ACCOUNT,
+ STATE_SWITCH_ACCOUNTSERVER_ATTEMPT,
+ STATE_SWITCH_ACCOUNTSERVER,
+ STATE_LOGOUT_ATTEMPT,
+ STATE_CONNECT_GAME,
+ STATE_WAIT,
+ STATE_FORCE_QUIT
+#else
+ STATE_ACCOUNT,
+ STATE_CHAR_CONNECT,
+ STATE_CHAR_SERVER,
+ STATE_CHAR_NEW,
+ STATE_CHAR_DEL,
+ STATE_CONNECTING
+#endif
};
/* length definitions for several char[]s in order
@@ -76,7 +128,15 @@ const short defaultScreenHeight = 600;
const short defaultSfxVolume = 100;
const short defaultMusicVolume = 60;
+// Defines the number of usable player slots
+const short maxSlot = 2;
+
+#ifdef TMWSERV_SUPPORT
+extern std::string token;
+#else
extern char n_server, n_character;
+#endif
+
extern unsigned char state;
extern std::string errorMessage;
diff --git a/src/map.cpp b/src/map.cpp
index 814b4225..e7646fd2 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -143,7 +143,11 @@ void MapLayer::draw(Graphics *graphics,
// tiles have been drawn
if (mIsFringeLayer)
{
+#ifdef TMWSERV_SUPPORT
+ while (si != sprites.end() && (*si)->getPixelY() <= y * 32)
+#else
while (si != sprites.end() && (*si)->getPixelY() <= y * 32 - 32)
+#endif
{
(*si)->draw(graphics, -scrollX, -scrollY);
si++;
@@ -181,12 +185,21 @@ Map::Map(int width, int height, int tileWidth, int tileHeight):
const int size = mWidth * mHeight;
mMetaTiles = new MetaTile[size];
+ for (int i = 0; i < NB_BLOCKTYPES; i++)
+ {
+ mOccupation[i] = new int[size];
+ memset(mOccupation[i], 0, size * sizeof(int));
+ }
}
Map::~Map()
{
// delete metadata, layers, tilesets and overlays
delete[] mMetaTiles;
+ for (int i = 0; i < NB_BLOCKTYPES; i++)
+ {
+ delete[] mOccupation[i];
+ }
delete_all(mLayers);
delete_all(mTilesets);
delete_all(mOverlays);
@@ -277,6 +290,59 @@ void Map::draw(Graphics *graphics, int scrollX, int scrollY)
(int) config.getValue("OverlayDetail", 2));
}
+void Map::drawCollision(Graphics *graphics, int scrollX, int scrollY)
+{
+ int endPixelY = graphics->getHeight() + scrollY + mTileHeight - 1;
+ int startX = scrollX / mTileWidth;
+ int startY = scrollY / mTileHeight;
+ int endX = (graphics->getWidth() + scrollX + mTileWidth - 1) / mTileWidth;
+ int endY = endPixelY / mTileHeight;
+
+ if (startX < 0) startX = 0;
+ if (startY < 0) startY = 0;
+ if (endX > mWidth) endX = mWidth;
+ if (endY > mHeight) endY = mHeight;
+
+ for (int y = startY; y < endY; y++)
+ {
+ for (int x = startX; x < endX; x++)
+ {
+ graphics->setColor(gcn::Color(0, 0, 0, 64));
+ graphics->drawRectangle(gcn::Rectangle(
+ x * mTileWidth - scrollX,
+ y * mTileWidth - scrollY,
+ 33, 33));
+
+ if (!getWalk(x, y, BLOCKMASK_WALL))
+ {
+ graphics->setColor(gcn::Color(0, 0, 200, 64));
+ graphics->fillRectangle(gcn::Rectangle(
+ x * mTileWidth - scrollX,
+ y * mTileWidth - scrollY,
+ 32, 32));
+ }
+
+ if (!getWalk(x, y, BLOCKMASK_MONSTER))
+ {
+ graphics->setColor(gcn::Color(200, 0, 0, 64));
+ graphics->fillRectangle(gcn::Rectangle(
+ x * mTileWidth - scrollX,
+ y * mTileWidth - scrollY,
+ 32, 32));
+ }
+
+ if (!getWalk(x, y, BLOCKMASK_CHARACTER))
+ {
+ graphics->setColor(gcn::Color(0, 200, 0, 64));
+ graphics->fillRectangle(gcn::Rectangle(
+ x * mTileWidth - scrollX,
+ y * mTileWidth - scrollY,
+ 32, 32));
+ }
+ }
+ }
+}
+
void Map::drawOverlay(Graphics *graphics,
float scrollX, float scrollY, int detail)
{
@@ -338,29 +404,41 @@ Tileset* Map::getTilesetWithGid(int gid) const
return (i == mTilesets.end()) ? NULL : *i;
}
-void Map::setWalk(int x, int y, bool walkable)
+void Map::blockTile(int x, int y, BlockType type)
{
- mMetaTiles[x + y * mWidth].walkable = walkable;
-}
+ if (type == BLOCKTYPE_NONE || !contains(x, y))
+ return;
-bool Map::occupied(int x, int y) const
-{
- Beings &beings = beingManager->getAll();
- for (BeingIterator i = beings.begin(); i != beings.end(); i++)
+ int tileNum = x + y * mWidth;
+
+ if ((++mOccupation[type][tileNum]) > 0)
{
- // job 45 is a portal, they don't collide
- if ((*i)->mX == x && (*i)->mY == y && (*i)->mJob != 45)
+ switch (type)
{
- return true;
+ case BLOCKTYPE_WALL:
+ mMetaTiles[tileNum].blockmask |= BLOCKMASK_WALL;
+ break;
+ case BLOCKTYPE_CHARACTER:
+ mMetaTiles[tileNum].blockmask |= BLOCKMASK_CHARACTER;
+ break;
+ case BLOCKTYPE_MONSTER:
+ mMetaTiles[tileNum].blockmask |= BLOCKMASK_MONSTER;
+ break;
+ default:
+ // shut up!
+ break;
}
}
-
- return false;
}
-bool Map::tileCollides(int x, int y) const
+bool Map::getWalk(int x, int y, char walkmask) const
{
- return !(contains(x, y) && mMetaTiles[x + y * mWidth].walkable);
+ // You can't walk outside of the map
+ if (!contains(x, y))
+ return false;
+
+ // Check if the tile is walkable
+ return !(mMetaTiles[x + y * mWidth].blockmask & walkmask);
}
bool Map::contains(int x, int y) const
@@ -368,7 +446,7 @@ bool Map::contains(int x, int y) const
return x >= 0 && y >= 0 && x < mWidth && y < mHeight;
}
-MetaTile* Map::getMetaTile(int x, int y)
+MetaTile* Map::getMetaTile(int x, int y) const
{
return &mMetaTiles[x + y * mWidth];
}
@@ -384,7 +462,9 @@ void Map::removeSprite(SpriteIterator iterator)
mSprites.erase(iterator);
}
-Path Map::findPath(int startX, int startY, int destX, int destY)
+static int const basicCost = 100;
+
+Path Map::findPath(int startX, int startY, int destX, int destY, unsigned char walkmask, int maxCost)
{
// Path to be built up (empty by default)
Path path;
@@ -392,6 +472,9 @@ Path Map::findPath(int startX, int startY, int destX, int destY)
// Declare open list, a list with open tiles sorted on F cost
std::priority_queue<Location> openList;
+ // Return when destination not walkable
+ if (!getWalk(destX, destY, walkmask)) return path;
+
// Reset starting tile's G cost to 0
MetaTile *startTile = getMetaTile(startX, startY);
startTile->Gcost = 0;
@@ -436,42 +519,55 @@ Path Map::findPath(int startX, int startY, int destX, int destY)
MetaTile *newTile = getMetaTile(x, y);
- // Skip if the tile is on the closed list or collides unless
- // its the destination tile
+ // Skip if the tile is on the closed list or is not walkable
+ // unless its the destination tile
if (newTile->whichList == mOnClosedList ||
- (tileCollides(x, y) && !(x == destX && y == destY)))
+ ((newTile->blockmask & walkmask) && !(x == destX && y == destY)))
{
continue;
}
// When taking a diagonal step, verify that we can skip the
- // corner. We allow skipping past beings but not past non-
- // walkable tiles.
+ // corner.
if (dx != 0 && dy != 0)
{
MetaTile *t1 = getMetaTile(curr.x, curr.y + dy);
MetaTile *t2 = getMetaTile(curr.x + dx, curr.y);
- if (!(t1->walkable && t2->walkable))
+ if (t1->blockmask & walkmask && !(t2->blockmask & walkmask)) // I hope I didn't fuck this line up
{
continue;
}
}
- // Calculate G cost for this route, 10 for moving straight and
- // 14 for moving diagonal (sqrt(200) = 14.1421...)
- int Gcost = curr.tile->Gcost + ((dx == 0 || dy == 0) ? 10 : 14);
+ // Calculate G cost for this route, ~sqrt(2) for moving diagonal
+ int Gcost = curr.tile->Gcost +
+ (dx == 0 || dy == 0 ? basicCost : basicCost * 362 / 256);
+
+ /* Demote an arbitrary direction to speed pathfinding by
+ adding a defect (TODO: change depending on the desired
+ visual effect, e.g. a cross-product defect toward
+ destination).
+ Important: as long as the total defect along any path is
+ less than the basicCost, the pathfinder will still find one
+ of the shortest paths! */
+ if (dx == 0 || dy == 0)
+ {
+ // Demote horizontal and vertical directions, so that two
+ // consecutive directions cannot have the same Fcost.
+ ++Gcost;
+ }
// It costs extra to walk through a being (needs to be enough
// to make it more attractive to walk around).
- if (occupied(x, y))
+ if (!getWalk(x, y, BLOCKMASK_CHARACTER | BLOCKMASK_MONSTER))
{
- Gcost += 30;
+ Gcost += 3 * basicCost;
}
// Skip if Gcost becomes too much
// Warning: probably not entirely accurate
- if (Gcost > 200)
+ if (Gcost > maxCost * basicCost)
{
continue;
}
@@ -479,8 +575,14 @@ Path Map::findPath(int startX, int startY, int destX, int destY)
if (newTile->whichList != mOnOpenList)
{
// Found a new tile (not on open nor on closed list)
- // Update Hcost of the new tile using Manhatten distance
- newTile->Hcost = 10 * (abs(x - destX) + abs(y - destY));
+
+ /* Update Hcost of the new tile. The pathfinder does not
+ work reliably if the heuristic cost is higher than the
+ real cost. In particular, using Manhattan distance is
+ forbidden here. */
+ int dx = std::abs(x - destX), dy = std::abs(y - destY);
+ newTile->Hcost = std::abs(dx - dy) * basicCost +
+ std::min(dx, dy) * (basicCost * 362 / 256);
// Set the current tile as the parent of the new tile
newTile->parentX = curr.x;
diff --git a/src/map.h b/src/map.h
index 9703c5b3..09bed293 100644
--- a/src/map.h
+++ b/src/map.h
@@ -53,7 +53,7 @@ struct MetaTile
/**
* Constructor.
*/
- MetaTile():whichList(0) {};
+ MetaTile():whichList(0), blockmask(0) {};
// Pathfinding members
int Fcost; /**< Estimation of total path cost */
@@ -62,7 +62,7 @@ struct MetaTile
int whichList; /**< No list, open list or closed list */
int parentX; /**< X coordinate of parent tile */
int parentY; /**< Y coordinate of parent tile */
- bool walkable; /**< Can beings walk on this tile */
+ unsigned char blockmask; /**< Blocking properties of this tile */
};
/**
@@ -143,6 +143,15 @@ class MapLayer
class Map : public Properties
{
public:
+ enum BlockType
+ {
+ BLOCKTYPE_NONE = -1,
+ BLOCKTYPE_WALL,
+ BLOCKTYPE_CHARACTER,
+ BLOCKTYPE_MONSTER,
+ NB_BLOCKTYPES
+ };
+
/**
* Constructor, taking map and tile size as parameters.
*/
@@ -175,6 +184,11 @@ class Map : public Properties
void draw(Graphics *graphics, int scrollX, int scrollY);
/**
+ * Visualizes collision layer for debugging
+ */
+ void drawCollision(Graphics *graphics, int scrollX, int scrollY);
+
+ /**
* Adds a layer to this map. The map takes ownership of the layer.
*/
void addLayer(MapLayer *layer);
@@ -192,17 +206,18 @@ class Map : public Properties
/**
* Get tile reference.
*/
- MetaTile *getMetaTile(int x, int y);
+ MetaTile *getMetaTile(int x, int y) const;
/**
- * Set walkability flag for a tile.
+ * Marks a tile as occupied
*/
- void setWalk(int x, int y, bool walkable);
+ void blockTile(int x, int y, BlockType type);
/**
- * Tell if a tile collides, not including a check on beings.
+ * Gets walkability for a tile with a blocking bitmask. When called
+ * without walkmask, only blocks against colliding tiles.
*/
- bool tileCollides(int x, int y) const;
+ bool getWalk(int x, int y, char walkmask = BLOCKMASK_WALL) const;
/**
* Returns the width of this map.
@@ -227,7 +242,8 @@ class Map : public Properties
/**
* Find a path from one location to the next.
*/
- Path findPath(int startX, int startY, int destX, int destY);
+ Path findPath(int startX, int startY, int destX, int destY,
+ unsigned char walkmask, int maxCost = 20);
/**
* Adds a sprite to the map.
@@ -268,14 +284,17 @@ class Map : public Properties
int detail);
/**
- * Tells whether a tile is occupied by a being.
+ * Tells whether the given coordinates fall within the map boundaries.
*/
- bool occupied(int x, int y) const;
+ bool contains(int x, int y) const;
/**
- * Tells whether the given coordinates fall within the map boundaries.
+ * Blockmasks for different entities
*/
- bool contains(int x, int y) const;
+ static const unsigned char BLOCKMASK_WALL = 0x80; // = bin 1000 0000
+ static const unsigned char BLOCKMASK_CHARACTER = 0x01;// = bin 0000 0001
+ static const unsigned char BLOCKMASK_MONSTER = 0x02; // = bin 0000 0010
+ int *mOccupation[NB_BLOCKTYPES];
int mWidth, mHeight;
int mTileWidth, mTileHeight;
diff --git a/src/monster.cpp b/src/monster.cpp
index 610da492..deabd7a8 100644
--- a/src/monster.cpp
+++ b/src/monster.cpp
@@ -37,7 +37,7 @@ Monster::Monster(Uint32 id, Uint16 job, Map *map):
Being(id, job, map),
mText(0)
{
- const MonsterInfo& info = MonsterDB::get(job - 1002);
+ const MonsterInfo& info = getInfo();
// Setup Monster sprites
int c = BASE_SPRITE;
@@ -79,11 +79,12 @@ Monster::~Monster()
delete mText;
}
+#ifdef EATHENA_SUPPORT
void Monster::logic()
{
if (mAction != STAND)
{
- mFrame = (get_elapsed_time(mWalkTime) * 4) / mWalkSpeed;
+ mFrame = (get_elapsed_time(mWalkTime) * 4) / getWalkSpeed();
if (mFrame >= 4 && mAction != DEAD)
{
@@ -93,13 +94,14 @@ void Monster::logic()
Being::logic();
}
+#endif
Being::Type Monster::getType() const
{
return MONSTER;
}
-void Monster::setAction(Action action)
+void Monster::setAction(Action action, int attackType)
{
SpriteAction currentAction = ACTION_INVALID;
int rotation = 0;
@@ -115,11 +117,11 @@ void Monster::setAction(Action action)
sound.playSfx(getInfo().getSound(MONSTER_EVENT_DIE));
break;
case ATTACK:
- currentAction = ACTION_ATTACK;
+ currentAction = getInfo().getAttackAction(attackType);
mSprites[BASE_SPRITE]->reset();
//attack particle effect
- particleEffect = getInfo().getAttackParticleEffect();
+ particleEffect = getInfo().getAttackParticleEffect(attackType);
if (!particleEffect.empty() && mParticleEffects)
{
switch (mDirection)
@@ -160,6 +162,22 @@ void Monster::setAction(Action action)
}
}
+#ifdef TMWSERV_SUPPORT
+
+void Monster::handleAttack()
+{
+ Being::handleAttack();
+
+ const MonsterInfo &mi = getInfo();
+
+ // TODO: It's not possible to determine hit or miss here, so this stuff
+ // probably needs to be moved somewhere else. We may lose synchronization
+ // between attack animation and the sound, unless we adapt the protocol...
+ sound.playSfx(mi.getSound(MONSTER_EVENT_HIT));
+}
+
+#else
+
void Monster::handleAttack(Being *victim, int damage)
{
Being::handleAttack(victim, damage);
@@ -169,6 +187,8 @@ void Monster::handleAttack(Being *victim, int damage)
MONSTER_EVENT_HIT : MONSTER_EVENT_MISS));
}
+#endif
+
void Monster::takeDamage(int amount)
{
if (amount > 0) sound.playSfx(getInfo().getSound(MONSTER_EVENT_HURT));
@@ -182,7 +202,11 @@ Being::TargetCursorSize Monster::getTargetCursorSize() const
const MonsterInfo &Monster::getInfo() const
{
+#ifdef TMWSERV_SUPPORT
+ return MonsterDB::get(mJob);
+#else
return MonsterDB::get(mJob - 1002);
+#endif
}
void Monster::showName(bool show)
diff --git a/src/monster.h b/src/monster.h
index 8d7f8ae7..5251d37e 100644
--- a/src/monster.h
+++ b/src/monster.h
@@ -34,9 +34,11 @@ class Monster : public Being
~Monster();
+#ifdef EATHENA_SUPPORT
virtual void logic();
+#endif
- virtual void setAction(Action action);
+ virtual void setAction(Action action, int attackType = 0);
virtual Type getType() const;
@@ -50,7 +52,11 @@ class Monster : public Being
* @param victim The attacked being.
* @param damage The amount of damage dealt (0 means miss).
*/
+#ifdef TMWSERV_SUPPORT
+ virtual void handleAttack();
+#else
virtual void handleAttack(Being *victim, int damage);
+#endif
/**
* Puts a damage bubble above this monster and plays the hurt sound
@@ -69,8 +75,20 @@ class Monster : public Being
*/
void showName(bool show);
+ /**
+ * Gets the way the monster is blocked by other objects
+ */
+ virtual unsigned char getWalkMask() const
+ { return 0x83; } // blocked by walls, other monsters and players ( bin 1000 0011)
+
protected:
/**
+ * Gets the way the monster blocks pathfinding for other objects
+ */
+ virtual Map::BlockType getBlockType() const
+ { return Map::BLOCKTYPE_MONSTER; }
+
+ /**
* Update the text when the monster moves
*/
void updateCoords();
diff --git a/src/net/accountserver/account.cpp b/src/net/accountserver/account.cpp
new file mode 100644
index 00000000..f734c4eb
--- /dev/null
+++ b/src/net/accountserver/account.cpp
@@ -0,0 +1,107 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "account.h"
+
+#include <string>
+
+#include "internal.h"
+
+#include "../connection.h"
+#include "../messageout.h"
+#include "../protocol.h"
+
+#include "../../utils/sha256.h"
+
+void Net::AccountServer::Account::createCharacter(
+ const std::string &name, char hairStyle, char hairColor, char gender,
+ short strength, short agility, short vitality,
+ short intelligence, short dexterity, short willpower)
+{
+ MessageOut msg(PAMSG_CHAR_CREATE);
+
+ msg.writeString(name);
+ msg.writeInt8(hairStyle);
+ msg.writeInt8(hairColor);
+ msg.writeInt8(gender);
+ msg.writeInt16(strength);
+ msg.writeInt16(agility);
+ msg.writeInt16(vitality);
+ msg.writeInt16(intelligence);
+ msg.writeInt16(dexterity);
+ msg.writeInt16(willpower);
+
+ Net::AccountServer::connection->send(msg);
+}
+
+void Net::AccountServer::Account::deleteCharacter(char slot)
+{
+ MessageOut msg(PAMSG_CHAR_DELETE);
+
+ msg.writeInt8(slot);
+
+ Net::AccountServer::connection->send(msg);
+}
+
+void Net::AccountServer::Account::selectCharacter(char slot)
+{
+ MessageOut msg(PAMSG_CHAR_SELECT);
+
+ msg.writeInt8(slot);
+
+ Net::AccountServer::connection->send(msg);
+}
+
+void Net::AccountServer::Account::unregister(const std::string &username,
+ const std::string &password)
+{
+ MessageOut msg(PAMSG_UNREGISTER);
+
+ msg.writeString(username);
+ msg.writeString(sha256(username + password));
+
+ Net::AccountServer::connection->send(msg);
+}
+
+void Net::AccountServer::Account::changeEmail(const std::string &email)
+{
+ MessageOut msg(PAMSG_EMAIL_CHANGE);
+
+ // Email is sent clearly so the server can validate the data.
+ // Encryption is assumed server-side.
+ msg.writeString(email);
+
+ Net::AccountServer::connection->send(msg);
+}
+
+void Net::AccountServer::Account::changePassword(
+ const std::string &username,
+ const std::string &oldPassword,
+ const std::string &newPassword)
+{
+ MessageOut msg(PAMSG_PASSWORD_CHANGE);
+
+ // Change password using SHA2 encryption
+ msg.writeString(sha256(username + oldPassword));
+ msg.writeString(sha256(username + newPassword));
+
+ Net::AccountServer::connection->send(msg);
+}
diff --git a/src/net/accountserver/account.h b/src/net/accountserver/account.h
new file mode 100644
index 00000000..581bcb42
--- /dev/null
+++ b/src/net/accountserver/account.h
@@ -0,0 +1,54 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_ACCOUNTSERVER_CHARACTER_H
+#define _TMW_NET_ACCOUNTSERVER_CHARACTER_H
+
+#include <iosfwd>
+
+namespace Net
+{
+ namespace AccountServer
+ {
+ namespace Account
+ {
+ void createCharacter(const std::string &name,
+ char hairStyle, char hairColor, char gender,
+ short strength, short agility, short vitality,
+ short intelligence, short dexterity, short willpower);
+
+ void deleteCharacter(char slot);
+
+ void selectCharacter(char slot);
+
+ void unregister(const std::string &username,
+ const std::string &password);
+
+ void changeEmail(const std::string &email);
+
+ void changePassword(const std::string &username,
+ const std::string &oldPassword,
+ const std::string &newPassword);
+ }
+ }
+}
+
+#endif
diff --git a/src/net/accountserver/accountserver.cpp b/src/net/accountserver/accountserver.cpp
new file mode 100644
index 00000000..b1ce590c
--- /dev/null
+++ b/src/net/accountserver/accountserver.cpp
@@ -0,0 +1,81 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "accountserver.h"
+
+#include <string>
+
+#include "internal.h"
+
+#include "../connection.h"
+#include "../messageout.h"
+#include "../protocol.h"
+
+#include "../../utils/sha256.h"
+
+void Net::AccountServer::login(Net::Connection *connection, int version,
+ const std::string &username, const std::string &password)
+{
+ Net::AccountServer::connection = connection;
+
+ MessageOut msg(PAMSG_LOGIN);
+
+ msg.writeInt32(version);
+ msg.writeString(username);
+ msg.writeString(sha256(username + password));
+
+ Net::AccountServer::connection->send(msg);
+}
+
+void Net::AccountServer::registerAccount(Net::Connection *connection,
+ int version, const std::string &username, const std::string &password,
+ const std::string &email)
+{
+ Net::AccountServer::connection = connection;
+
+ MessageOut msg(PAMSG_REGISTER);
+
+ msg.writeInt32(version); // client version
+ msg.writeString(username);
+ // When registering, the password and email hash is assumed by server.
+ // Hence, data can be validated safely server-side.
+ // This is the only time we send a clear password.
+ msg.writeString(password);
+ msg.writeString(email);
+
+ Net::AccountServer::connection->send(msg);
+}
+
+void Net::AccountServer::logout()
+{
+ MessageOut msg(PAMSG_LOGOUT);
+ Net::AccountServer::connection->send(msg);
+}
+
+void Net::AccountServer::reconnectAccount(Net::Connection *connection,
+ const std::string &passToken)
+{
+ Net::AccountServer::connection = connection;
+
+ MessageOut msg(PAMSG_RECONNECT);
+ msg.writeString(passToken, 32);
+ Net::AccountServer::connection->send(msg);
+}
diff --git a/src/net/accountserver/accountserver.h b/src/net/accountserver/accountserver.h
new file mode 100644
index 00000000..8e0573fc
--- /dev/null
+++ b/src/net/accountserver/accountserver.h
@@ -0,0 +1,47 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_ACCOUNTSERVER_ACCOUNTSERVER_H
+#define _TMW_NET_ACCOUNTSERVER_ACCOUNTSERVER_H
+
+#include <iosfwd>
+
+namespace Net
+{
+ class Connection;
+
+ namespace AccountServer
+ {
+ void login(Net::Connection *connection, int version,
+ const std::string &username, const std::string &password);
+
+ void registerAccount(Net::Connection *connection, int version,
+ const std::string &username, const std::string &password,
+ const std::string &email);
+
+ void logout();
+
+ void reconnectAccount(Net::Connection *connection,
+ const std::string &passToken);
+ }
+}
+
+#endif
diff --git a/src/net/accountserver/internal.cpp b/src/net/accountserver/internal.cpp
new file mode 100644
index 00000000..a3be76a1
--- /dev/null
+++ b/src/net/accountserver/internal.cpp
@@ -0,0 +1,32 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "internal.h"
+
+namespace Net
+{
+ class Connection;
+
+ namespace AccountServer
+ {
+ Connection *connection = 0;
+ }
+}
diff --git a/src/net/accountserver/internal.h b/src/net/accountserver/internal.h
new file mode 100644
index 00000000..b3d64582
--- /dev/null
+++ b/src/net/accountserver/internal.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_ACCOUNTSERVER_INTERNAL_H
+#define _TMW_NET_ACCOUNTSERVER_INTERNAL_H
+
+namespace Net
+{
+ class Connection;
+
+ namespace AccountServer
+ {
+ extern Connection *connection;
+ }
+}
+
+#endif
diff --git a/src/net/beinghandler.cpp b/src/net/beinghandler.cpp
index 3e746eb5..8f1fb8fd 100644
--- a/src/net/beinghandler.cpp
+++ b/src/net/beinghandler.cpp
@@ -1,542 +1,359 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include <iostream>
+#include "beinghandler.h"
+
#include <SDL_types.h>
-#include "beinghandler.h"
#include "messagein.h"
#include "protocol.h"
#include "../being.h"
#include "../beingmanager.h"
-#include "../effectmanager.h"
#include "../game.h"
#include "../localplayer.h"
#include "../log.h"
+#include "../main.h"
#include "../npc.h"
-#include "../player_relations.h"
+#include "../particle.h"
+#include "../sound.h"
+
+#include "../gui/ok_dialog.h"
+
+#include "../utils/gettext.h"
+
+#include "gameserver/player.h"
const int EMOTION_TIME = 150; /**< Duration of emotion icon */
-BeingHandler::BeingHandler(bool enableSync):
- mSync(enableSync)
+BeingHandler::BeingHandler()
{
static const Uint16 _messages[] = {
- SMSG_BEING_VISIBLE,
- SMSG_BEING_MOVE,
- SMSG_BEING_MOVE2,
- SMSG_BEING_REMOVE,
- SMSG_BEING_ACTION,
- SMSG_BEING_SELFEFFECT,
- SMSG_BEING_EMOTION,
- SMSG_BEING_CHANGE_LOOKS,
- SMSG_BEING_CHANGE_LOOKS2,
- SMSG_BEING_NAME_RESPONSE,
- SMSG_PLAYER_UPDATE_1,
- SMSG_PLAYER_UPDATE_2,
- SMSG_PLAYER_MOVE,
- SMSG_PLAYER_STOP,
- SMSG_PLAYER_MOVE_TO_ATTACK,
- 0x0119,
- 0x0196,
+ GPMSG_BEING_ATTACK,
+ GPMSG_BEING_ENTER,
+ GPMSG_BEING_LEAVE,
+ GPMSG_BEINGS_MOVE,
+ GPMSG_BEINGS_DAMAGE,
+ GPMSG_BEING_ACTION_CHANGE,
+ GPMSG_BEING_LOOKS_CHANGE,
+ GPMSG_BEING_DIR_CHANGE,
0
};
handledMessages = _messages;
}
-void BeingHandler::handleMessage(MessageIn *msg)
+void BeingHandler::handleMessage(MessageIn &msg)
{
- Uint32 id;
- Uint16 job, speed;
- Uint16 headTop, headMid, headBottom;
- Uint16 shoes, gloves;
- Uint16 weapon, shield;
- Uint16 gmstatus;
- Sint16 param1;
- int stunMode;
- Uint32 statusEffects;
- Sint8 type;
- Uint16 status;
- Being *srcBeing, *dstBeing;
- int hairStyle, hairColor, flag;
-
- switch (msg->getId())
+ switch (msg.getId())
{
- case SMSG_BEING_VISIBLE:
- case SMSG_BEING_MOVE:
- // Information about a being in range
- id = msg->readInt32();
- speed = msg->readInt16();
- stunMode = msg->readInt16(); // opt1
- statusEffects = msg->readInt16(); // opt2
- statusEffects |= ((Uint32)msg->readInt16()) << 16; // option
- job = msg->readInt16(); // class
-
- dstBeing = beingManager->findBeing(id);
-
- if (!dstBeing)
- {
- // Being with id >= 110000000 and job 0 are better
- // known as ghosts, so don't create those.
- if (job == 0 && id >= 110000000)
- {
- break;
- }
-
- dstBeing = beingManager->createBeing(id, job);
- }
- else if (msg->getId() == 0x0078)
- {
- dstBeing->clearPath();
- dstBeing->mFrame = 0;
- dstBeing->mWalkTime = tick_time;
- dstBeing->setAction(Being::STAND);
- }
-
-
- // Prevent division by 0 when calculating frame
- if (speed == 0) { speed = 150; }
-
- dstBeing->setWalkSpeed(speed);
- dstBeing->mJob = job;
- hairStyle = msg->readInt16();
- dstBeing->setSprite(Being::WEAPON_SPRITE, msg->readInt16());
- headBottom = msg->readInt16();
-
- if (msg->getId() == SMSG_BEING_MOVE)
- {
- msg->readInt32(); // server tick
- }
-
- dstBeing->setSprite(Being::SHIELD_SPRITE, msg->readInt16());
- headTop = msg->readInt16();
- headMid = msg->readInt16();
- hairColor = msg->readInt16();
- shoes = msg->readInt16(); // clothes color - "abused" as shoes
- gloves = msg->readInt16(); // head dir - "abused" as gloves
- msg->readInt16(); // guild
- msg->readInt16(); // unknown
- msg->readInt16(); // unknown
- msg->readInt16(); // manner
- dstBeing->setStatusEffectBlock(32, msg->readInt16()); // opt3
- msg->readInt8(); // karma
- dstBeing->setGender(
- (msg->readInt8() == 0) ? GENDER_FEMALE : GENDER_MALE);
-
- // Set these after the gender, as the sprites may be gender-specific
- dstBeing->setSprite(Being::BOTTOMCLOTHES_SPRITE, headBottom);
- dstBeing->setSprite(Being::TOPCLOTHES_SPRITE, headMid);
- dstBeing->setSprite(Being::HAT_SPRITE, headTop);
- dstBeing->setSprite(Being::SHOE_SPRITE, shoes);
- dstBeing->setSprite(Being::GLOVES_SPRITE, gloves);
- dstBeing->setHairStyle(hairStyle, hairColor);
-
- if (msg->getId() == SMSG_BEING_MOVE)
- {
- Uint16 srcX, srcY, dstX, dstY;
- msg->readCoordinatePair(srcX, srcY, dstX, dstY);
- dstBeing->setAction(Being::STAND);
- dstBeing->mX = srcX;
- dstBeing->mY = srcY;
- dstBeing->setDestination(dstX, dstY);
- }
- else
- {
- Uint8 dir;
- msg->readCoordinates(dstBeing->mX, dstBeing->mY, dir);
- dstBeing->setDirection(dir);
- }
-
- msg->readInt8(); // unknown
- msg->readInt8(); // unknown
- msg->readInt8(); // unknown / sit
-
- dstBeing->setStunMode(stunMode);
- dstBeing->setStatusEffectBlock(0, (statusEffects >> 16) & 0xffff);
- dstBeing->setStatusEffectBlock(16, statusEffects & 0xffff);
+ case GPMSG_BEING_ENTER:
+ handleBeingEnterMessage(msg);
break;
-
- case SMSG_BEING_MOVE2:
- /*
- * A simplified movement packet, used by the
- * later versions of eAthena for both mobs and
- * players
- */
- dstBeing = beingManager->findBeing(msg->readInt32());
-
- Uint16 srcX, srcY, dstX, dstY;
- msg->readCoordinatePair(srcX, srcY, dstX, dstY);
- msg->readInt32(); // Server tick
-
- /*
- * This packet doesn't have enough info to actually
- * create a new being, so if the being isn't found,
- * we'll just pretend the packet didn't happen
- */
-
- if (dstBeing) {
- dstBeing->setAction(Being::STAND);
- dstBeing->mX = srcX;
- dstBeing->mY = srcY;
- dstBeing->setDestination(dstX, dstY);
- }
-
+ case GPMSG_BEING_LEAVE:
+ handleBeingLeaveMessage(msg);
break;
-
- case SMSG_BEING_REMOVE:
- // A being should be removed or has died
- dstBeing = beingManager->findBeing(msg->readInt32());
-
- if (!dstBeing)
- break;
-
- // If this is player's current target, clear it.
- if (dstBeing == player_node->getTarget())
- player_node->stopAttack();
-
- if (dstBeing == current_npc)
- current_npc->handleDeath();
-
- if (msg->readInt8() == 1)
- dstBeing->setAction(Being::DEAD);
- else
- beingManager->destroyBeing(dstBeing);
-
+ case GPMSG_BEINGS_MOVE:
+ handleBeingsMoveMessage(msg);
break;
-
- case SMSG_BEING_ACTION:
- srcBeing = beingManager->findBeing(msg->readInt32());
- dstBeing = beingManager->findBeing(msg->readInt32());
- msg->readInt32(); // server tick
- msg->readInt32(); // src speed
- msg->readInt32(); // dst speed
- param1 = msg->readInt16();
- msg->readInt16(); // param 2
- type = msg->readInt8();
- msg->readInt16(); // param 3
-
- switch (type)
- {
- case 0x0a: // Critical Damage
- if (dstBeing)
- dstBeing->showCrit();
- case 0x00: // Damage
- if (dstBeing)
- dstBeing->takeDamage(param1);
- if (srcBeing)
- srcBeing->handleAttack(dstBeing, param1);
- break;
-
- case 0x02: // Sit
- if (srcBeing)
- {
- srcBeing->mFrame = 0;
- srcBeing->setAction(Being::SIT);
- }
- break;
-
- case 0x03: // Stand up
- if (srcBeing)
- {
- srcBeing->mFrame = 0;
- srcBeing->setAction(Being::STAND);
- }
- break;
- }
+ case GPMSG_BEING_ATTACK:
+ handleBeingAttackMessage(msg);
break;
+ case GPMSG_BEINGS_DAMAGE:
+ handleBeingsDamageMessage(msg);
+ break;
+ case GPMSG_BEING_ACTION_CHANGE:
+ handleBeingActionChangeMessage(msg);
+ break;
+ case GPMSG_BEING_LOOKS_CHANGE:
+ handleBeingLooksChangeMessage(msg);
+ break;
+ case GPMSG_BEING_DIR_CHANGE:
+ handleBeingDirChangeMessage(msg);
+ break;
+ }
+}
- case SMSG_BEING_SELFEFFECT: {
- id = (Uint32)msg->readInt32();
- if (!beingManager->findBeing(id))
- break;
-
- int effectType = msg->readInt32();
- Being* being = beingManager->findBeing(id);
+static void handleLooks(Player *being, MessageIn &msg)
+{
+ // Order of sent slots. Has to be in sync with the server code.
+ static int const nb_slots = 4;
+ static int const slots[nb_slots] =
+ { Being::WEAPON_SPRITE, Being::HAT_SPRITE, Being::TOPCLOTHES_SPRITE,
+ Being::BOTTOMCLOTHES_SPRITE };
- effectManager->trigger(effectType, being);
+ int mask = msg.readInt8();
- break;
+ if (mask & (1 << 7))
+ {
+ // The equipment has to be cleared first.
+ for (int i = 0; i < nb_slots; ++i)
+ {
+ being->setSprite(slots[i], 0);
}
+ }
- case SMSG_BEING_EMOTION:
- if (!(dstBeing = beingManager->findBeing(msg->readInt32())))
- {
- break;
- }
-
- if (player_relations.hasPermission(dstBeing, PlayerRelation::EMOTE))
- dstBeing->setEmote(msg->readInt8(), EMOTION_TIME);
-
- break;
+ // Fill slots enumerated by the bitmask.
+ for (int i = 0; i < nb_slots; ++i)
+ {
+ if (!(mask & (1 << i))) continue;
+ int id = msg.readInt16();
+ being->setSprite(slots[i], id);
+ }
+}
- case SMSG_BEING_CHANGE_LOOKS:
- case SMSG_BEING_CHANGE_LOOKS2:
+void BeingHandler::handleBeingEnterMessage(MessageIn &msg)
+{
+ int type = msg.readInt8();
+ int id = msg.readInt16();
+ Being::Action action = (Being::Action)msg.readInt8();
+ int px = msg.readInt16();
+ int py = msg.readInt16();
+ Being *being;
+
+ switch (type)
+ {
+ case OBJECT_PLAYER:
{
- /*
- * SMSG_BEING_CHANGE_LOOKS (0x00c3) and
- * SMSG_BEING_CHANGE_LOOKS2 (0x01d7) do basically the same
- * thing. The difference is that ...LOOKS carries a single
- * 8 bit value, where ...LOOKS2 carries two 16 bit values.
- *
- * If type = 2, then the first 16 bit value is the weapon ID,
- * and the second 16 bit value is the shield ID. If no
- * shield is equipped, or type is not 2, then the second
- * 16 bit value will be 0.
- */
-
- if (!(dstBeing = beingManager->findBeing(msg->readInt32())))
+ std::string name = msg.readString();
+ if (player_node->getName() == name)
{
- break;
+ being = player_node;
+ being->setId(id);
}
-
- int type = msg->readInt8();
- int id = 0;
- int id2 = 0;
-
- if (msg->getId() == SMSG_BEING_CHANGE_LOOKS) {
- id = msg->readInt8();
- } else { // SMSG_BEING_CHANGE_LOOKS2
- id = msg->readInt16();
- id2 = msg->readInt16();
- }
-
- switch (type) {
- case 1: // eAthena LOOK_HAIR
- dstBeing->setHairStyle(id, -1);
- break;
- case 2: // Weapon ID in id, Shield ID in id2
- dstBeing->setSprite(Being::WEAPON_SPRITE, id);
- dstBeing->setSprite(Being::SHIELD_SPRITE, id2);
- break;
- case 3: // Change lower headgear for eAthena, pants for us
- dstBeing->setSprite(Being::BOTTOMCLOTHES_SPRITE, id);
- break;
- case 4: // Change upper headgear for eAthena, hat for us
- dstBeing->setSprite(Being::HAT_SPRITE, id);
- break;
- case 5: // Change middle headgear for eathena, armor for us
- dstBeing->setSprite(Being::TOPCLOTHES_SPRITE, id);
- break;
- case 6: // eAthena LOOK_HAIR_COLOR
- dstBeing->setHairStyle(-1, id);
- break;
- case 8: // eAthena LOOK_SHIELD
- dstBeing->setSprite(Being::SHIELD_SPRITE, id);
- break;
- case 9: // eAthena LOOK_SHOES
- dstBeing->setSprite(Being::SHOE_SPRITE, id);
- break;
- case 10: // LOOK_GLOVES
- dstBeing->setSprite(Being::GLOVES_SPRITE, id);
- break;
- case 11: // LOOK_CAPE
- dstBeing->setSprite(Being::CAPE_SPRITE, id);
- break;
- case 12:
- dstBeing->setSprite(Being::MISC1_SPRITE, id);
- break;
- case 13:
- dstBeing->setSprite(Being::MISC2_SPRITE, id);
- break;
- default:
- logger->log("SMSG_BEING_CHANGE_LOOKS: unsupported type: "
- "%d, id: %d", type, id);
- break;
- }
- }
- break;
-
- case SMSG_BEING_NAME_RESPONSE:
- if ((dstBeing = beingManager->findBeing(msg->readInt32())))
+ else
{
- dstBeing->setName(msg->readString(24));
+ being = beingManager->createBeing(id, type, 0);
+ being->setName(name);
}
- break;
+ Player *p = static_cast< Player * >(being);
+ int hs = msg.readInt8(), hc = msg.readInt8();
+ p->setHairStyle(hs, hc);
+ p->setGender(msg.readInt8() == GENDER_MALE ?
+ GENDER_MALE : GENDER_FEMALE);
+ handleLooks(p, msg);
+ } break;
+
+ case OBJECT_MONSTER:
+ case OBJECT_NPC:
+ {
+ int subtype = msg.readInt16();
+ being = beingManager->createBeing(id, type, subtype);
+ std::string name = msg.readString();
+ if (name.length() > 0) being->setName(name);
+ } break;
+
+ default:
+ return;
+ }
- case SMSG_PLAYER_UPDATE_1:
- case SMSG_PLAYER_UPDATE_2:
- case SMSG_PLAYER_MOVE:
- // An update about a player, potentially including movement.
- id = msg->readInt32();
- speed = msg->readInt16();
- stunMode = msg->readInt16(); // opt1; Aethyra use this as cape
- statusEffects = msg->readInt16(); // opt2; Aethyra use this as misc1
- statusEffects |= ((Uint32) msg->readInt16())
- << 16; // status.options; Aethyra uses this as misc2
- job = msg->readInt16();
-
- dstBeing = beingManager->findBeing(id);
-
- if (!dstBeing)
- {
- dstBeing = beingManager->createBeing(id, job);
- }
+ being->setPosition(px, py);
+ being->setDestination(px, py);
+ being->setAction(action);
+}
- dstBeing->setWalkSpeed(speed);
- dstBeing->mJob = job;
- hairStyle = msg->readInt16();
- weapon = msg->readInt16();
- shield = msg->readInt16();
- headBottom = msg->readInt16();
+void BeingHandler::handleBeingLeaveMessage(MessageIn &msg)
+{
+ Being *being = beingManager->findBeing(msg.readInt16());
+ if (!being) return;
- if (msg->getId() == SMSG_PLAYER_MOVE)
- {
- msg->readInt32(); // server tick
- }
+ beingManager->destroyBeing(being);
+}
- headTop = msg->readInt16();
- headMid = msg->readInt16();
- hairColor = msg->readInt16();
- msg->readInt16(); // clothes color - Aethyra-"abused" as shoes, we ignore it
- msg->readInt16(); // head dir - Aethyra-"abused" as gloves, we ignore it
- msg->readInt32(); // guild
- msg->readInt16(); // emblem
- msg->readInt16(); // manner
- dstBeing->setStatusEffectBlock(32, msg->readInt16()); // opt3
- msg->readInt8(); // karma
- dstBeing->setGender(
- (msg->readInt8() == 0) ? GENDER_FEMALE : GENDER_MALE);
-
- // Set these after the gender, as the sprites may be gender-specific
- dstBeing->setSprite(Being::WEAPON_SPRITE, weapon);
- dstBeing->setSprite(Being::SHIELD_SPRITE, shield);
- dstBeing->setSprite(Being::BOTTOMCLOTHES_SPRITE, headBottom);
- dstBeing->setSprite(Being::TOPCLOTHES_SPRITE, headMid);
- dstBeing->setSprite(Being::HAT_SPRITE, headTop);
- //dstBeing->setSprite(Being::CAPE_SPRITE, cape);
- //dstBeing->setSprite(Being::MISC1_SPRITE, misc1);
- //dstBeing->setSprite(Being::MISC2_SPRITE, misc2);
- dstBeing->setHairStyle(hairStyle, hairColor);
-
- if (msg->getId() == SMSG_PLAYER_MOVE)
- {
- Uint16 srcX, srcY, dstX, dstY;
- msg->readCoordinatePair(srcX, srcY, dstX, dstY);
- dstBeing->mX = srcX;
- dstBeing->mY = srcY;
- dstBeing->setDestination(dstX, dstY);
- }
- else
+void BeingHandler::handleBeingsMoveMessage(MessageIn &msg)
+{
+ while (msg.getUnreadLength())
+ {
+ int id = msg.readInt16();
+ int flags = msg.readInt8();
+ Being *being = beingManager->findBeing(id);
+ int sx = 0;
+ int sy = 0;
+ int dx = 0;
+ int dy = 0;
+ int speed = 0;
+
+ printf("handleBeingsMoveMessage for %p (%s | %s)\n",
+ (void*) being,
+ (flags & MOVING_POSITION) ? "pos" : "",
+ (flags & MOVING_DESTINATION) ? "dest" : "");
+
+ if (flags & MOVING_POSITION)
+ {
+ Uint16 sx2, sy2;
+ msg.readCoordinates(sx2, sy2);
+ sx = sx2 * 32 + 16;
+ sy = sy2 * 32 + 16;
+ speed = msg.readInt8();
+ }
+ if (flags & MOVING_DESTINATION)
+ {
+ dx = msg.readInt16();
+ dy = msg.readInt16();
+ if (!(flags & MOVING_POSITION))
{
- Uint8 dir;
- msg->readCoordinates(dstBeing->mX, dstBeing->mY, dir);
- dstBeing->setDirection(dir);
+ sx = dx;
+ sy = dy;
}
+ }
+ if (!being || !(flags & (MOVING_POSITION | MOVING_DESTINATION)))
+ {
+ continue;
+ }
+ if (speed)
+ {
+ /* The speed on the server is the cost of moving from one tile to
+ * the next. Beings get 1000 cost units per second. The speed is
+ * transferred as devided by 10, so that slower speeds fit in a
+ * byte. Here we convert the speed to pixels per second.
+ */
+ const float tilesPerSecond = 100.0f / speed;
+ being->setWalkSpeed((int) (tilesPerSecond * 32));
+ }
- gmstatus = msg->readInt16();
- if (gmstatus & 0x80)
- dstBeing->setGM();
+ // Ignore messages from the server for the local player
+ if (being == player_node)
+ continue;
- if (msg->getId() == SMSG_PLAYER_UPDATE_1)
- {
- switch (msg->readInt8())
- {
- case 1:
- if (dstBeing->getType() != Being::NPC)
- dstBeing->setAction(Being::DEAD);
- break;
-
- case 2:
- dstBeing->setAction(Being::SIT);
- break;
- }
- }
- else if (msg->getId() == SMSG_PLAYER_MOVE)
- {
- msg->readInt8(); // unknown
- }
+ // If being is a player, and he only moves a little, its ok to be a little out of sync
+ if (being->getType() == Being::PLAYER && abs(being->getPixelX() - dx) +
+ abs(being->getPixelY() - dy) < 2 * 32 &&
+ (dx != being->getDestination().x && dy != being->getDestination().y))
+ {
+ being->setDestination(being->getPixelX(),being->getPixelY());
+ continue;
+ }
+ if (abs(being->getPixelX() - sx) +
+ abs(being->getPixelY() - sy) > 10 * 32)
+ {
+ // Too large a desynchronization.
+ being->setPosition(sx, sy);
+ being->setDestination(dx, dy);
+ }
+ else if (!(flags & MOVING_POSITION))
+ {
+ being->setDestination(dx, dy);
+ }
+ else if (!(flags & MOVING_DESTINATION))
+ {
+ being->adjustCourse(sx, sy);
+ }
+ else
+ {
+ being->adjustCourse(sx, sy, dx, dy);
+ }
+ }
+}
- msg->readInt8(); // Lv
- msg->readInt8(); // unknown
+void BeingHandler::handleBeingAttackMessage(MessageIn &msg)
+{
+ Being *being = beingManager->findBeing(msg.readInt16());
+ int direction = msg.readInt8();
+ int attackType = msg.readInt8();
- dstBeing->mWalkTime = tick_time;
- dstBeing->mFrame = 0;
+ if (!being) return;
- dstBeing->setStunMode(stunMode);
- dstBeing->setStatusEffectBlock(0, (statusEffects >> 16) & 0xffff);
- dstBeing->setStatusEffectBlock(16, statusEffects & 0xffff);
- break;
+ switch (direction)
+ {
+ case DIRECTION_UP: being->setDirection(Being::UP); break;
+ case DIRECTION_DOWN: being->setDirection(Being::DOWN); break;
+ case DIRECTION_LEFT: being->setDirection(Being::LEFT); break;
+ case DIRECTION_RIGHT: being->setDirection(Being::RIGHT); break;
+ }
- case SMSG_PLAYER_STOP:
- /*
- * Instruction from server to stop walking at x, y.
- *
- * Some people like having this enabled. Others absolutely
- * despise it. So I'm setting to so that it only affects the
- * local player if the person has set a key "EnableSync" to "1"
- * in their config.xml file.
- *
- * This packet will be honored for all other beings, regardless
- * of the config setting.
- */
+ being->setAction(Being::ATTACK, attackType);
+}
- id = msg->readInt32();
- if (mSync || id != player_node->getId()) {
- dstBeing = beingManager->findBeing(id);
- if (dstBeing) {
- dstBeing->mX = msg->readInt16();
- dstBeing->mY = msg->readInt16();
- if (dstBeing->mAction == Being::WALK) {
- dstBeing->mFrame = 0;
- dstBeing->setAction(Being::STAND);
- }
- }
- }
- break;
+void BeingHandler::handleBeingsDamageMessage(MessageIn &msg)
+{
+ while (msg.getUnreadLength())
+ {
+ Being *being = beingManager->findBeing(msg.readInt16());
+ int damage = msg.readInt16();
+ if (being)
+ {
+ being->takeDamage(damage);
+ }
+ }
+}
- case SMSG_PLAYER_MOVE_TO_ATTACK:
- /*
- * This is an *advisory* message, telling the client that
- * it needs to move the character before attacking
- * a target (out of range, obstruction in line of fire).
- * We can safely ignore this...
- */
- break;
+void BeingHandler::handleBeingActionChangeMessage(MessageIn &msg)
+{
+ Being* being = beingManager->findBeing(msg.readInt16());
+ Being::Action action = (Being::Action) msg.readInt8();
+ if (!being) return;
- case 0x0119:
- // Change in players' flags
- id = msg->readInt32();
- dstBeing = beingManager->findBeing(id);
- stunMode = msg->readInt16();
- statusEffects = msg->readInt16();
- statusEffects |= ((Uint32) msg->readInt16()) << 16;
- msg->readInt8();
-
- if (dstBeing) {
- dstBeing->setStunMode(stunMode);
- dstBeing->setStatusEffectBlock(0, (statusEffects >> 16) & 0xffff);
- dstBeing->setStatusEffectBlock(16, statusEffects & 0xffff);
- }
- break;
+ being->setAction(action);
+
+ if (action == Being::DEAD && being==player_node)
+ {
+ static char const *const deadMsg[] =
+ {
+ _("You are dead."),
+ _("We regret to inform you that your character was killed in battle."),
+ _("You are not that alive anymore."),
+ _("The cold hands of the grim reaper are grabbing for your soul."),
+ _("Game Over!"),
+ _("No, kids. Your character did not really die. It... err... went to a better place."),
+ _("Your plan of breaking your enemies weapon by bashing it with your throat failed."),
+ _("I guess this did not run too well."),
+ _("Do you want your possessions identified?"), // Nethack reference
+ _("Sadly, no trace of you was ever found..."), // Secret of Mana reference
+ _("Annihilated."), // Final Fantasy VI reference
+ _("Looks like you got your head handed to you."), //Earthbound reference
+ _("You screwed up again, dump your body down the tubes and get you another one.") // Leisure Suit Larry 1 Reference
+
+ };
+ std::string message(deadMsg[rand()%13]);
+ message.append(_(" Press OK to respawn"));
+ OkDialog *dlg = new OkDialog(_("You died"), message);
+ dlg->addActionListener(&(Net::GameServer::Player::respawnListener));
+ }
+}
- case 0x0196:
- // Status change
- status = msg->readInt16();
- id = msg->readInt32();
- flag = msg->readInt8(); // 0: stop, 1: start
+void BeingHandler::handleBeingLooksChangeMessage(MessageIn &msg)
+{
+ Being *being = beingManager->findBeing(msg.readInt16());
+ if (!being || being->getType() != Being::PLAYER) return;
+ Player * player = static_cast< Player * >(being);
+ handleLooks(player, msg);
+ if (msg.getUnreadLength())
+ {
+ int style = msg.readInt16();
+ int color = msg.readInt16();
+ player->setHairStyle(style, color);
+ player->setGender((Gender)msg.readInt16());
+ }
+}
- dstBeing = beingManager->findBeing(id);
- if (dstBeing)
- dstBeing->setStatusEffect(status, flag);
- break;
+void BeingHandler::handleBeingDirChangeMessage(MessageIn &msg)
+{
+ Being *being = beingManager->findBeing(msg.readInt16());
+ if (!being) return;
+ int data = msg.readInt8();
+ switch (data)
+ {
+ case DIRECTION_UP: being->setDirection(Being::UP); break;
+ case DIRECTION_DOWN: being->setDirection(Being::DOWN); break;
+ case DIRECTION_LEFT: being->setDirection(Being::LEFT); break;
+ case DIRECTION_RIGHT: being->setDirection(Being::RIGHT); break;
}
}
+
diff --git a/src/net/beinghandler.h b/src/net/beinghandler.h
index 54b82075..b02728b4 100644
--- a/src/net/beinghandler.h
+++ b/src/net/beinghandler.h
@@ -1,39 +1,45 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#ifndef NET_BEINGHANDLER_H
-#define NET_BEINGHANDLER_H
+#ifndef _TMW_NET_BEINGHANDLER_H
+#define _TMW_NET_BEINGHANDLER_H
#include "messagehandler.h"
class BeingHandler : public MessageHandler
{
public:
- BeingHandler(bool enableSync);
+ BeingHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
private:
- // Should we honor server "Stop Walking" packets
- bool mSync;
+ void handleBeingAttackMessage(MessageIn &msg);
+ void handleBeingEnterMessage(MessageIn &msg);
+ void handleBeingLeaveMessage(MessageIn &msg);
+ void handleBeingsMoveMessage(MessageIn &msg);
+ void handleBeingsDamageMessage(MessageIn &msg);
+ void handleBeingActionChangeMessage(MessageIn &msg);
+ void handleBeingLooksChangeMessage(MessageIn &msg);
+ void handleBeingDirChangeMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/buysellhandler.cpp b/src/net/buysellhandler.cpp
index a2442d70..a551f213 100644
--- a/src/net/buysellhandler.cpp
+++ b/src/net/buysellhandler.cpp
@@ -1,32 +1,32 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
+#include "buysellhandler.h"
+
#include <SDL_types.h>
-#include "buysellhandler.h"
#include "messagein.h"
#include "protocol.h"
#include "../beingmanager.h"
-#include "../inventory.h"
#include "../item.h"
#include "../localplayer.h"
#include "../npc.h"
@@ -35,98 +35,57 @@
#include "../gui/chat.h"
#include "../gui/sell.h"
-#include "../utils/gettext.h"
-
extern BuyDialog *buyDialog;
-extern Window *buySellDialog;
extern SellDialog *sellDialog;
+extern Window *buySellDialog;
BuySellHandler::BuySellHandler()
{
static const Uint16 _messages[] = {
- SMSG_NPC_BUY_SELL_CHOICE,
- SMSG_NPC_BUY,
- SMSG_NPC_SELL,
- SMSG_NPC_BUY_RESPONSE,
- SMSG_NPC_SELL_RESPONSE,
+ GPMSG_NPC_BUY,
+ GPMSG_NPC_SELL,
0
};
handledMessages = _messages;
}
-void BuySellHandler::handleMessage(MessageIn *msg)
+void BuySellHandler::handleMessage(MessageIn &msg)
{
- int n_items;
- switch (msg->getId())
+ Being *being = beingManager->findBeing(msg.readInt16());
+ if (!being || being->getType() != Being::NPC)
{
- case SMSG_NPC_BUY_SELL_CHOICE:
- buyDialog->setVisible(false);
- buyDialog->reset();
- sellDialog->setVisible(false);
- sellDialog->reset();
- buySellDialog->setVisible(true);
- current_npc = dynamic_cast<NPC*>(beingManager->findBeing(msg->readInt32()));
- break;
+ return;
+ }
+
+ current_npc = static_cast< NPC * >(being);
- case SMSG_NPC_BUY:
- msg->readInt16(); // length
- n_items = (msg->getLength() - 4) / 11;
+ switch (msg.getId())
+ {
+ case GPMSG_NPC_BUY:
buyDialog->reset();
- buyDialog->setMoney(player_node->mGp);
+ buyDialog->setMoney(player_node->getMoney());
buyDialog->setVisible(true);
- for (int k = 0; k < n_items; k++)
+ while (msg.getUnreadLength())
{
- Sint32 value = msg->readInt32();
- msg->readInt32(); // DCvalue
- msg->readInt8(); // type
- Sint16 itemId = msg->readInt16();
- buyDialog->addItem(itemId, value);
+ int itemId = msg.readInt16();
+ int amount = msg.readInt16();
+ int value = msg.readInt16();
+ buyDialog->addItem(itemId, amount, value);
}
break;
- case SMSG_NPC_SELL:
- msg->readInt16(); // length
- n_items = (msg->getLength() - 4) / 10;
- if (n_items > 0) {
- sellDialog->setMoney(player_node->mGp);
- sellDialog->reset();
- sellDialog->setVisible(true);
-
- for (int k = 0; k < n_items; k++)
- {
- Sint16 index = msg->readInt16();
- Sint32 value = msg->readInt32();
- msg->readInt32(); // OCvalue
-
- Item *item = player_node->getInventory()->getItem(index);
- if (item && !(item->isEquipped())) {
- sellDialog->addItem(item, value);
- }
- }
- }
- else {
- chatWindow->chatLog(_("Nothing to sell"), BY_SERVER);
- if (current_npc) current_npc->handleDeath();
- }
- break;
-
- case SMSG_NPC_BUY_RESPONSE:
- if (msg->readInt8() == 0) {
- chatWindow->chatLog(_("Thanks for buying"), BY_SERVER);
- } else {
- // Reset player money since buy dialog already assumed purchase
- // would go fine
- buyDialog->setMoney(player_node->mGp);
- chatWindow->chatLog(_("Unable to buy"), BY_SERVER);
- }
- break;
+ case GPMSG_NPC_SELL:
+ sellDialog->setMoney(player_node->getMoney());
+ sellDialog->reset();
+ sellDialog->setVisible(true);
- case SMSG_NPC_SELL_RESPONSE:
- if (msg->readInt8() == 0) {
- chatWindow->chatLog(_("Thanks for selling"), BY_SERVER);
- } else {
- chatWindow->chatLog(_("Unable to sell"), BY_SERVER);
+ while (msg.getUnreadLength())
+ {
+ int itemId = msg.readInt16();
+ int amount = msg.readInt16();
+ int value = msg.readInt16();
+ sellDialog->addItem(itemId, amount, value);
}
break;
}
diff --git a/src/net/buysellhandler.h b/src/net/buysellhandler.h
index 0ede7b48..719b76d9 100644
--- a/src/net/buysellhandler.h
+++ b/src/net/buysellhandler.h
@@ -29,7 +29,7 @@ class BuySellHandler : public MessageHandler
public:
BuySellHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/charserverhandler.cpp b/src/net/charserverhandler.cpp
index 8e743bf0..5905dba0 100644
--- a/src/net/charserverhandler.cpp
+++ b/src/net/charserverhandler.cpp
@@ -1,25 +1,27 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "charserverhandler.h"
+
+#include "connection.h"
#include "messagein.h"
#include "protocol.h"
@@ -29,107 +31,73 @@
#include "../logindata.h"
#include "../main.h"
-#include "../gui/char_select.h"
#include "../gui/ok_dialog.h"
+#include "../gui/char_select.h"
-#include "../utils/gettext.h"
-#include "../utils/stringutils.h"
+extern Net::Connection *gameServerConnection;
+extern Net::Connection *chatServerConnection;
CharServerHandler::CharServerHandler():
mCharCreateDialog(0)
{
static const Uint16 _messages[] = {
- SMSG_CONNECTION_PROBLEM,
- 0x006b,
- 0x006c,
- 0x006d,
- 0x006e,
- 0x006f,
- 0x0070,
- 0x0071,
+ APMSG_CHAR_CREATE_RESPONSE,
+ APMSG_CHAR_DELETE_RESPONSE,
+ APMSG_CHAR_INFO,
+ APMSG_CHAR_SELECT_RESPONSE,
0
};
handledMessages = _messages;
}
-void CharServerHandler::handleMessage(MessageIn *msg)
+void CharServerHandler::handleMessage(MessageIn &msg)
{
- int slot, flags, code;
+ int slot;
LocalPlayer *tempPlayer;
- logger->log("CharServerHandler: Packet ID: %x, Length: %d",
- msg->getId(), msg->getLength());
- switch (msg->getId())
+ switch (msg.getId())
{
- case SMSG_CONNECTION_PROBLEM:
- code = msg->readInt8();
- logger->log("Connection problem: %i", code);
-
- switch (code) {
- case 0:
- errorMessage = _("Authentication failed");
- break;
- case 1:
- errorMessage = _("Map server(s) offline");
- break;
- case 2:
- errorMessage = _("This account is already logged in");
- break;
- case 3:
- errorMessage = _("Speed hack detected");
- break;
- case 8:
- errorMessage = _("Duplicated login");
- break;
- default:
- errorMessage = _("Unknown connection error");
- break;
- }
- state = ERROR_STATE;
+ case APMSG_CHAR_CREATE_RESPONSE:
+ handleCharCreateResponse(msg);
break;
- case 0x006b:
- msg->skip(2); // Length word
- flags = msg->readInt32(); // Aethyra extensions flags
- logger->log("Server flags are: %x", flags);
- msg->skip(16); // Unused
-
- // Derive number of characters from message length
- n_character = (msg->getLength() - 24) / 106;
-
- for (int i = 0; i < n_character; i++)
+ case APMSG_CHAR_DELETE_RESPONSE:
+ {
+ int errMsg = msg.readInt8();
+ // Character deletion successful
+ if (errMsg == ERRMSG_OK)
{
- tempPlayer = readPlayerData(*msg, slot);
- mCharInfo->select(slot);
- mCharInfo->setEntry(tempPlayer);
- logger->log("CharServer: Player: %s (%d)",
- tempPlayer->getName().c_str(), slot);
+ delete mCharInfo->getEntry();
+ mCharInfo->setEntry(0);
+ mCharInfo->unlock();
+ new OkDialog("Info", "Player deleted");
}
-
- state = CHAR_SELECT_STATE;
- break;
-
- case 0x006c:
- switch (msg->readInt8()) {
- case 0:
- errorMessage = _("Access denied");
- break;
- case 1:
- errorMessage = _("Cannot use this ID");
- break;
- default:
- errorMessage = _("Unknown failure to select character");
- break;
+ // Character deletion failed
+ else
+ {
+ std::string message = "";
+ switch (errMsg)
+ {
+ case ERRMSG_NO_LOGIN:
+ message = "Not logged in";
+ break;
+ case ERRMSG_INVALID_ARGUMENT:
+ message = "Selection out of range";
+ break;
+ default:
+ message = "Unknown error";
+ }
+ mCharInfo->unlock();
+ new OkDialog("Error", message);
}
- mCharInfo->unlock();
+ }
break;
- case 0x006d:
- tempPlayer = readPlayerData(*msg, slot);
+ case APMSG_CHAR_INFO:
+ tempPlayer = readPlayerData(msg, slot);
mCharInfo->unlock();
mCharInfo->select(slot);
mCharInfo->setEntry(tempPlayer);
- n_character++;
// Close the character create dialog
if (mCharCreateDialog)
@@ -139,97 +107,121 @@ void CharServerHandler::handleMessage(MessageIn *msg)
}
break;
- case 0x006e:
- new OkDialog(_("Error"), _("Failed to create character. Most likely"
- " the name is already taken."));
-
- if (mCharCreateDialog)
- mCharCreateDialog->unlock();
+ case APMSG_CHAR_SELECT_RESPONSE:
+ handleCharSelectResponse(msg);
break;
+ }
+}
- case 0x006f:
- delete mCharInfo->getEntry();
- mCharInfo->setEntry(0);
- mCharInfo->unlock();
- n_character--;
- new OkDialog(_("Info"), _("Player deleted"));
- break;
+void CharServerHandler::handleCharCreateResponse(MessageIn &msg)
+{
+ int errMsg = msg.readInt8();
- case 0x0070:
- mCharInfo->unlock();
- new OkDialog(_("Error"), _("Failed to delete character."));
- break;
+ // Character creation failed
+ if (errMsg != ERRMSG_OK)
+ {
+ std::string message = "";
+ switch (errMsg)
+ {
+ case ERRMSG_NO_LOGIN:
+ message = "Not logged in";
+ break;
+ case CREATE_TOO_MUCH_CHARACTERS:
+ message = "No empty slot";
+ break;
+ case ERRMSG_INVALID_ARGUMENT:
+ message = "Invalid name";
+ break;
+ case CREATE_EXISTS_NAME:
+ message = "Character's name already exists";
+ break;
+ case CREATE_INVALID_HAIRSTYLE:
+ message = "Invalid hairstyle";
+ break;
+ case CREATE_INVALID_HAIRCOLOR:
+ message = "Invalid hair color";
+ break;
+ case CREATE_INVALID_GENDER:
+ message = "Invalid gender";
+ break;
+ case CREATE_RAW_STATS_TOO_HIGH:
+ message = "Character's stats are too high";
+ break;
+ case CREATE_RAW_STATS_TOO_LOW:
+ message = "Character's stats are too low";
+ break;
+ case CREATE_RAW_STATS_EQUAL_TO_ZERO:
+ message = "One stat is zero";
+ break;
+ default:
+ message = "Unknown error";
+ break;
+ }
+ new OkDialog("Error", message);
+ }
- case 0x0071:
- player_node = mCharInfo->getEntry();
- slot = mCharInfo->getPos();
- msg->skip(4); // CharID, must be the same as player_node->charID
- map_path = msg->readString(16);
- mLoginData->hostname = ipToString(msg->readInt32());
- mLoginData->port = msg->readInt16();
- mCharInfo->unlock();
- mCharInfo->select(0);
- // Clear unselected players infos
- do
+ if (mCharCreateDialog)
+ mCharCreateDialog->unlock();
+}
+
+void CharServerHandler::handleCharSelectResponse(MessageIn &msg)
+{
+ int errMsg = msg.readInt8();
+
+ if (errMsg == ERRMSG_OK)
+ {
+ token = msg.readString(32);
+ std::string gameServer = msg.readString();
+ unsigned short gameServerPort = msg.readInt16();
+ std::string chatServer = msg.readString();
+ unsigned short chatServerPort = msg.readInt16();
+
+ logger->log("Game server: %s:%d", gameServer.c_str(), gameServerPort);
+ logger->log("Chat server: %s:%d", chatServer.c_str(), chatServerPort);
+
+ gameServerConnection->connect(gameServer, gameServerPort);
+ chatServerConnection->connect(chatServer, chatServerPort);
+
+ // Keep the selected character and delete the others
+ player_node = mCharInfo->getEntry();
+ int slot = mCharInfo->getPos();
+ mCharInfo->unlock();
+ mCharInfo->select(0);
+
+ do {
+ LocalPlayer *tmp = mCharInfo->getEntry();
+ if (tmp != player_node)
{
- LocalPlayer *tmp = mCharInfo->getEntry();
- if (tmp != player_node)
- {
- delete tmp;
- mCharInfo->setEntry(0);
- }
- mCharInfo->next();
- } while (mCharInfo->getPos());
+ delete tmp;
+ mCharInfo->setEntry(0);
+ }
+ mCharInfo->next();
+ } while (mCharInfo->getPos());
+ mCharInfo->select(slot);
- mCharInfo->select(slot);
- state = CONNECTING_STATE;
- break;
+ mCharInfo->clear(); //player_node will be deleted by ~Game
+
+ state = STATE_CONNECT_GAME;
}
}
-LocalPlayer *CharServerHandler::readPlayerData(MessageIn &msg, int &slot)
+LocalPlayer* CharServerHandler::readPlayerData(MessageIn &msg, int &slot)
{
- LocalPlayer *tempPlayer = new LocalPlayer(mLoginData->account_ID, 0, NULL);
- tempPlayer->setGender(
- (mLoginData->sex == 0) ? GENDER_FEMALE : GENDER_MALE);
-
- tempPlayer->mCharId = msg.readInt32();
- tempPlayer->setXp(msg.readInt32());
- tempPlayer->mGp = msg.readInt32();
- tempPlayer->mJobXp = msg.readInt32();
- tempPlayer->mJobLevel = msg.readInt32();
- tempPlayer->setSprite(Being::SHOE_SPRITE, msg.readInt16());
- tempPlayer->setSprite(Being::GLOVES_SPRITE, msg.readInt16());
- tempPlayer->setSprite(Being::CAPE_SPRITE, msg.readInt16());
- tempPlayer->setSprite(Being::MISC1_SPRITE, msg.readInt16());
- msg.readInt32(); // option
- msg.readInt32(); // karma
- msg.readInt32(); // manner
- msg.skip(2); // unknown
- tempPlayer->mHp = msg.readInt16();
- tempPlayer->mMaxHp = msg.readInt16();
- tempPlayer->mMp = msg.readInt16();
- tempPlayer->mMaxMp = msg.readInt16();
- msg.readInt16(); // speed
- msg.readInt16(); // class
- int hairStyle = msg.readInt16();
- Uint16 weapon = msg.readInt16();
- tempPlayer->setSprite(Being::WEAPON_SPRITE, weapon);
- tempPlayer->mLevel = msg.readInt16();
- msg.readInt16(); // skill point
- tempPlayer->setSprite(Being::BOTTOMCLOTHES_SPRITE, msg.readInt16()); // head bottom
- tempPlayer->setSprite(Being::SHIELD_SPRITE, msg.readInt16());
- tempPlayer->setSprite(Being::HAT_SPRITE, msg.readInt16()); // head option top
- tempPlayer->setSprite(Being::TOPCLOTHES_SPRITE, msg.readInt16()); // head option mid
- int hairColor = msg.readInt16();
- tempPlayer->setHairStyle(hairStyle, hairColor);
- tempPlayer->setSprite(Being::MISC2_SPRITE, msg.readInt16());
- tempPlayer->setName(msg.readString(24));
- for (int i = 0; i < 6; i++) {
- tempPlayer->mAttr[i] = msg.readInt8();
- }
+ LocalPlayer *tempPlayer = new LocalPlayer;
slot = msg.readInt8(); // character slot
- msg.readInt8(); // unknown
+ tempPlayer->setName(msg.readString());
+ tempPlayer->setGender(msg.readInt8() == GENDER_MALE ? GENDER_MALE : GENDER_FEMALE);
+ int hs = msg.readInt8(), hc = msg.readInt8();
+ tempPlayer->setHairStyle(hs, hc);
+ tempPlayer->setLevel(msg.readInt16());
+ tempPlayer->setCharacterPoints(msg.readInt16());
+ tempPlayer->setCorrectionPoints(msg.readInt16());
+ tempPlayer->setMoney(msg.readInt32());
+
+ for (int i = 0; i < 7; i++)
+ {
+ tempPlayer->setAttributeBase(i, msg.readInt8());
+ }
return tempPlayer;
}
diff --git a/src/net/charserverhandler.h b/src/net/charserverhandler.h
index 37b378f2..08ba5102 100644
--- a/src/net/charserverhandler.h
+++ b/src/net/charserverhandler.h
@@ -1,26 +1,26 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#ifndef NET_CHARSERVERHANDLER_H
-#define NET_CHARSERVERHANDLER_H
+#ifndef _TMW_NET_CHARSERVERHANDLER_H
+#define _TMW_NET_CHARSERVERHANDLER_H
#include "messagehandler.h"
@@ -31,20 +31,21 @@ class LocalPlayer;
class LoginData;
/**
- * Deals with incoming messages from the character server.
+ * Deals with incoming messages related to character selection.
*/
class CharServerHandler : public MessageHandler
{
public:
CharServerHandler();
- void handleMessage(MessageIn *msg);
+ void
+ handleMessage(MessageIn &msg);
- void setCharInfo(LockedArray<LocalPlayer*> *charInfo)
- { mCharInfo = charInfo; }
-
- void setLoginData(LoginData *loginData)
- { mLoginData = loginData; }
+ void
+ setCharInfo(LockedArray<LocalPlayer*> *charInfo)
+ {
+ mCharInfo = charInfo;
+ }
/**
* Sets the character create dialog. The handler will clean up this
@@ -55,11 +56,17 @@ class CharServerHandler : public MessageHandler
{ mCharCreateDialog = window; }
protected:
- LoginData *mLoginData;
+ void
+ handleCharCreateResponse(MessageIn &msg);
+
+ void
+ handleCharSelectResponse(MessageIn &msg);
+
LockedArray<LocalPlayer*> *mCharInfo;
CharCreateDialog *mCharCreateDialog;
- LocalPlayer* readPlayerData(MessageIn &msg, int &slot);
+ LocalPlayer*
+ readPlayerData(MessageIn &msg, int &slot);
};
#endif
diff --git a/src/net/chathandler.cpp b/src/net/chathandler.cpp
index a3ccc4fb..90af899a 100644
--- a/src/net/chathandler.cpp
+++ b/src/net/chathandler.cpp
@@ -1,175 +1,285 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
+#include "chathandler.h"
+
#include <SDL_types.h>
#include <string>
+#include <iostream>
-#include "chathandler.h"
#include "messagein.h"
#include "protocol.h"
#include "../being.h"
#include "../beingmanager.h"
#include "../game.h"
-#include "../player_relations.h"
+#include "../channel.h"
+#include "../channelmanager.h"
#include "../gui/chat.h"
-
-#include "../utils/gettext.h"
-#include "../utils/stringutils.h"
+#include "../gui/guildwindow.h"
extern Being *player_node;
-#define SERVER_NAME "Server"
-
ChatHandler::ChatHandler()
{
static const Uint16 _messages[] = {
- SMSG_BEING_CHAT,
- SMSG_PLAYER_CHAT,
- SMSG_WHISPER,
- SMSG_WHISPER_RESPONSE,
- SMSG_GM_CHAT,
- SMSG_WHO_ANSWER,
- 0x10c, // MVP
+ GPMSG_SAY,
+ CPMSG_ENTER_CHANNEL_RESPONSE,
+ CPMSG_LIST_CHANNELS_RESPONSE,
+ CPMSG_PUBMSG,
+ CPMSG_ANNOUNCEMENT,
+ CPMSG_PRIVMSG,
+ CPMSG_QUIT_CHANNEL_RESPONSE,
+ CPMSG_LIST_CHANNELUSERS_RESPONSE,
+ CPMSG_CHANNEL_EVENT,
0
};
handledMessages = _messages;
}
-void ChatHandler::handleMessage(MessageIn *msg)
+void ChatHandler::handleMessage(MessageIn &msg)
{
- Being *being;
- std::string chatMsg;
- std::string nick;
- Sint16 chatMsgLength;
-
- switch (msg->getId())
+ switch (msg.getId())
{
- case SMSG_WHISPER_RESPONSE:
- switch (msg->readInt8())
- {
- case 0x00:
- // comment out since we'll local echo in chat.cpp instead, then only report failures
- //chatWindow->chatLog("Whisper sent", BY_SERVER);
- break;
- case 0x01:
- chatWindow->chatLog(_("Whisper could not be sent, user is offline"), BY_SERVER);
- break;
- case 0x02:
- chatWindow->chatLog(_("Whisper could not be sent, ignored by user"), BY_SERVER);
- break;
- }
+ case GPMSG_SAY:
+ handleGameChatMessage(msg);
break;
- // Received whisper
- case SMSG_WHISPER:
- chatMsgLength = msg->readInt16() - 28;
- nick = msg->readString(24);
+ case CPMSG_ENTER_CHANNEL_RESPONSE:
+ handleEnterChannelResponse(msg);
+ break;
- if (chatMsgLength <= 0)
- break;
+ case CPMSG_LIST_CHANNELS_RESPONSE:
+ handleListChannelsResponse(msg);
+ break;
- chatMsg = msg->readString(chatMsgLength);
- if (nick != SERVER_NAME)
- chatMsg = nick + " : " + chatMsg;
+ case CPMSG_PRIVMSG:
+ handlePrivateMessage(msg);
+ break;
- if (nick == SERVER_NAME)
- chatWindow->chatLog(chatMsg, BY_SERVER);
- else {
- if (player_relations.hasPermission(nick, PlayerRelation::WHISPER))
- chatWindow->chatLog(chatMsg, ACT_WHISPER);
- }
+ case CPMSG_ANNOUNCEMENT:
+ handleAnnouncement(msg);
+ break;
+
+ case CPMSG_PUBMSG:
+ handleChatMessage(msg);
+ break;
+ case CPMSG_QUIT_CHANNEL_RESPONSE:
+ handleQuitChannelResponse(msg);
break;
- // Received speech from being
- case SMSG_BEING_CHAT: {
- chatMsgLength = msg->readInt16() - 8;
- being = beingManager->findBeing(msg->readInt32());
+ case CPMSG_LIST_CHANNELUSERS_RESPONSE:
+ handleListChannelUsersResponse(msg);
+ break;
+
+ case CPMSG_CHANNEL_EVENT:
+ handleChannelEvent(msg);
+ }
+}
+
+void ChatHandler::handleGameChatMessage(MessageIn &msg)
+{
+ short id = msg.readInt16();
+ std::string chatMsg = msg.readString();
+
+ if (id == 0)
+ {
+ chatWindow->chatLog(chatMsg, BY_SERVER);
+ return;
+ }
+
+ Being *being = beingManager->findBeing(id);
+
+ if (being)
+ {
+ chatWindow->chatLog(being->getName() + " : " + chatMsg,
+ being == player_node ? BY_PLAYER : BY_OTHER, "General");
+ being->setSpeech(chatMsg, SPEECH_TIME);
+ }
+ else
+ {
+ chatWindow->chatLog("Unknown : " + chatMsg, BY_OTHER, "General");
+ }
+}
- if (!being || chatMsgLength <= 0)
+void ChatHandler::handleEnterChannelResponse(MessageIn &msg)
+{
+ if(msg.readInt8() == ERRMSG_OK)
+ {
+ short channelId = msg.readInt16();
+ std::string channelName = msg.readString();
+ std::string announcement = msg.readString();
+ Channel *channel = new Channel(channelId, channelName, announcement);
+ channelManager->addChannel(channel);
+ chatWindow->createNewChannelTab(channelName);
+ chatWindow->chatLog("Topic: " + announcement, BY_CHANNEL, channelName);
+
+ std::string user;
+ std::string userModes;
+ chatWindow->chatLog("Players in this channel:", BY_CHANNEL, channelName);
+ while(msg.getUnreadLength())
+ {
+ user = msg.readString();
+ if (user == "")
+ return;
+ userModes = msg.readString();
+ if (userModes.find('o') != std::string::npos)
{
- break;
+ user = "@" + user;
}
+ chatWindow->chatLog(user, BY_CHANNEL, channelName);
+ }
+
+ }
+ else
+ {
+ chatWindow->chatLog("Error joining channel", BY_SERVER);
+ }
+}
- chatMsg = msg->readString(chatMsgLength);
+void ChatHandler::handleListChannelsResponse(MessageIn &msg)
+{
+ chatWindow->chatLog("Listing Channels", BY_SERVER);
+ while(msg.getUnreadLength())
+ {
+ std::string channelName = msg.readString();
+ if (channelName == "")
+ return;
+ std::ostringstream numUsers;
+ numUsers << msg.readInt16();
+ channelName += " - ";
+ channelName += numUsers.str();
+ chatWindow->chatLog(channelName, BY_SERVER);
+ }
+ chatWindow->chatLog("End of channel list", BY_SERVER);
+}
- std::string::size_type pos = chatMsg.find(" : ", 0);
- std::string sender_name = ((pos == std::string::npos)
- ? ""
- : chatMsg.substr(0, pos));
+void ChatHandler::handlePrivateMessage(MessageIn &msg)
+{
+ std::string userNick = msg.readString();
+ std::string chatMsg = msg.readString();
- // We use getIgnorePlayer instead of ignoringPlayer here because ignorePlayer' side
- // effects are triggered right below for Being::IGNORE_SPEECH_FLOAT.
- if (player_relations.checkPermissionSilently(sender_name, PlayerRelation::SPEECH_LOG))
- chatWindow->chatLog(chatMsg, BY_OTHER);
+ if (!chatWindow->tabExists(userNick))
+ {
+ chatWindow->createNewChannelTab(userNick);
- chatMsg.erase(0, pos + 3);
- trim(chatMsg);
+ }
+ chatWindow->chatLog(userNick + ": " + chatMsg, BY_OTHER, userNick);
+}
+
+void ChatHandler::handleAnnouncement(MessageIn &msg)
+{
+ std::string chatMsg = msg.readString();
+ chatWindow->chatLog(chatMsg, BY_GM);
+}
- if (player_relations.hasPermission(sender_name, PlayerRelation::SPEECH_FLOAT))
- being->setSpeech(chatMsg, SPEECH_TIME);
+void ChatHandler::handleChatMessage(MessageIn &msg)
+{
+ short channelId = msg.readInt16();
+ std::string userNick = msg.readString();
+ std::string chatMsg = msg.readString();
+
+ chatWindow->sendToChannel(channelId, userNick, chatMsg);
+}
+
+void ChatHandler::handleQuitChannelResponse(MessageIn &msg)
+{
+ if(msg.readInt8() == ERRMSG_OK)
+ {
+ short channelId = msg.readInt16();
+ // remove the chat tab
+ chatWindow->removeChannel(channelId);
+ }
+}
+
+void ChatHandler::handleListChannelUsersResponse(MessageIn &msg)
+{
+ std::string channel = msg.readString();
+ std::string userNick;
+ std::string userModes;
+ chatWindow->chatLog("Players in this channel:", BY_CHANNEL, channel);
+ while(msg.getUnreadLength())
+ {
+ userNick = msg.readString();
+ if (userNick == "")
+ {
break;
}
+ userModes = msg.readString();
+ if (userModes.find('o') != std::string::npos)
+ {
+ userNick = "@" + userNick;
+ }
+ chatWindow->chatLog(userNick, BY_CHANNEL, channel);
+ }
+}
- case SMSG_PLAYER_CHAT:
- case SMSG_GM_CHAT: {
- chatMsgLength = msg->readInt16() - 4;
+void ChatHandler::handleChannelEvent(MessageIn &msg)
+{
+ short channelId = msg.readInt16();
+ char eventId = msg.readInt8();
+ std::string line = msg.readString();
+ Channel *channel = channelManager->findById(channelId);
- if (chatMsgLength <= 0)
- {
+ if(channel)
+ {
+ switch(eventId)
+ {
+ case CHAT_EVENT_NEW_PLAYER:
+ line += " entered the channel.";
break;
- }
-
- chatMsg = msg->readString(chatMsgLength);
- std::string::size_type pos = chatMsg.find(" : ", 0);
- if (msg->getId() == SMSG_PLAYER_CHAT)
- {
- chatWindow->chatLog(chatMsg, BY_PLAYER);
+ case CHAT_EVENT_LEAVING_PLAYER:
+ line += " left the channel.";
+ break;
- if (pos != std::string::npos)
- chatMsg.erase(0, pos + 3);
+ case CHAT_EVENT_TOPIC_CHANGE:
+ line = "Topic: " + line;
+ break;
- trim(chatMsg);
+ case CHAT_EVENT_MODE_CHANGE:
+ {
+ int first = line.find(":");
+ int second = line.find(":", first+1);
+ std::string user1 = line.substr(0, first);
+ std::string user2 = line.substr(first+1, second);
+ std::string mode = line.substr(second+1, line.length());
+ line = user1 + " has set mode " + mode + " on user " + user2;
+ } break;
- player_node->setSpeech(chatMsg, SPEECH_TIME);
- }
- else
+ case CHAT_EVENT_KICKED_PLAYER:
{
- chatWindow->chatLog(chatMsg, BY_GM);
- }
- break;
- }
+ int first = line.find(":");
+ std::string user1 = line.substr(0, first);
+ std::string user2 = line.substr(first+1, line.length());
+ line = user1 + " has kicked " + user2;
+ } break;
- case SMSG_WHO_ANSWER:
- chatWindow->chatLog("Online users: " + toString(msg->readInt32()),
- BY_SERVER);
- break;
+ default:
+ line = "Unknown channel event.";
+ }
- case 0x010c:
- // Display MVP player
- msg->readInt32(); // id
- chatWindow->chatLog("MVP player", BY_SERVER);
- break;
+ chatWindow->chatLog(line, BY_CHANNEL, channel->getName());
}
}
+
diff --git a/src/net/chathandler.h b/src/net/chathandler.h
index ff649205..a9e9bd99 100644
--- a/src/net/chathandler.h
+++ b/src/net/chathandler.h
@@ -28,8 +28,57 @@ class ChatHandler : public MessageHandler
{
public:
ChatHandler();
-
- void handleMessage(MessageIn *msg);
+
+ /**
+ * Handle the given message appropriately.
+ */
+ void handleMessage(MessageIn &msg);
+
+ private:
+ /**
+ * Handle chat messages sent from the game server.
+ */
+ void handleGameChatMessage(MessageIn &msg);
+
+ /**
+ * Handle channel entry responses.
+ */
+ void handleEnterChannelResponse(MessageIn &msg);
+
+ /**
+ * Handle list channels responses.
+ */
+ void handleListChannelsResponse(MessageIn &msg);
+
+ /**
+ * Handle private messages.
+ */
+ void handlePrivateMessage(MessageIn &msg);
+
+ /**
+ * Handle announcements.
+ */
+ void handleAnnouncement(MessageIn &msg);
+
+ /**
+ * Handle chat messages.
+ */
+ void handleChatMessage(MessageIn &msg);
+
+ /**
+ * Handle quit channel responses.
+ */
+ void handleQuitChannelResponse(MessageIn &msg);
+
+ /**
+ * Handle list channel users responses.
+ */
+ void handleListChannelUsersResponse(MessageIn &msg);
+
+ /**
+ * Handle channel events.
+ */
+ void handleChannelEvent(MessageIn &msg);
};
#endif
diff --git a/src/net/chatserver/chatserver.cpp b/src/net/chatserver/chatserver.cpp
new file mode 100644
index 00000000..94e36b94
--- /dev/null
+++ b/src/net/chatserver/chatserver.cpp
@@ -0,0 +1,146 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "chatserver.h"
+
+#include "internal.h"
+
+#include "../connection.h"
+#include "../messageout.h"
+#include "../protocol.h"
+
+using Net::ChatServer::connection;
+
+void Net::ChatServer::connect(Net::Connection *connection,
+ const std::string &token)
+{
+ Net::ChatServer::connection = connection;
+
+ MessageOut msg(PCMSG_CONNECT);
+
+ msg.writeString(token, 32);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::logout()
+{
+ MessageOut msg(PCMSG_DISCONNECT);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::chat(short channel, const std::string &text)
+{
+ MessageOut msg(PCMSG_CHAT);
+
+ msg.writeString(text);
+ msg.writeInt16(channel);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::announce(const std::string &text)
+{
+ MessageOut msg(PCMSG_ANNOUNCE);
+
+ msg.writeString(text);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::privMsg(const std::string &recipient,
+ const std::string &text)
+{
+ MessageOut msg(PCMSG_PRIVMSG);
+
+ msg.writeString(recipient);
+ msg.writeString(text);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::enterChannel(const std::string &channel, const std::string &password)
+{
+ MessageOut msg(PCMSG_ENTER_CHANNEL);
+
+ msg.writeString(channel);
+ msg.writeString(password);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::quitChannel(short channel)
+{
+ MessageOut msg(PCMSG_QUIT_CHANNEL);
+
+ msg.writeInt16(channel);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::getChannelList()
+{
+ MessageOut msg(PCMSG_LIST_CHANNELS);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::getUserList(const std::string &channel)
+{
+ MessageOut msg(PCMSG_LIST_CHANNELUSERS);
+
+ msg.writeString(channel);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::setChannelTopic(short channel, const std::string &topic)
+{
+ MessageOut msg(PCMSG_TOPIC_CHANGE);
+
+ msg.writeInt16(channel);
+ msg.writeString(topic);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::setUserMode(short channel, const std::string &user,
+ unsigned char mode)
+{
+ MessageOut msg(PCMSG_USER_MODE);
+
+ msg.writeInt16(channel);
+ msg.writeString(user);
+ msg.writeInt8(mode);
+
+ connection->send(msg);
+}
+
+void Net::ChatServer::kickUser(short channel, const std::string &user)
+{
+ MessageOut msg(PCMSG_KICK_USER);
+
+ msg.writeInt16(channel);
+ msg.writeString(user);
+
+ connection->send(msg);
+}
diff --git a/src/net/chatserver/chatserver.h b/src/net/chatserver/chatserver.h
new file mode 100644
index 00000000..1129239a
--- /dev/null
+++ b/src/net/chatserver/chatserver.h
@@ -0,0 +1,60 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_CHATSERVER_CHATSERVER_H
+#define _TMW_NET_CHATSERVER_CHATSERVER_H
+
+#include <iosfwd>
+
+namespace Net
+{
+ class Connection;
+
+ namespace ChatServer
+ {
+ void connect(Net::Connection *connection, const std::string &token);
+
+ void logout();
+
+ void chat(short channel, const std::string &text);
+
+ void announce(const std::string &text);
+
+ void privMsg(const std::string &recipient, const std::string &text);
+
+ void enterChannel(const std::string &channel, const std::string &password);
+
+ void quitChannel(short channel);
+
+ void getChannelList();
+
+ void getUserList(const std::string &channel);
+
+ void setChannelTopic(short channel, const std::string &topic);
+
+ void setUserMode(short channel, const std::string &user, unsigned char mode);
+
+ void kickUser(short channel, const std::string &user);
+
+ }
+}
+
+#endif
diff --git a/src/net/chatserver/guild.cpp b/src/net/chatserver/guild.cpp
new file mode 100644
index 00000000..042ff013
--- /dev/null
+++ b/src/net/chatserver/guild.cpp
@@ -0,0 +1,95 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+#include "guild.h"
+
+#include "internal.h"
+
+#include "../connection.h"
+#include "../messageout.h"
+#include "../protocol.h"
+
+#include "../../log.h"
+
+void Net::ChatServer::Guild::createGuild(const std::string &name)
+{
+ logger->log("Sending PCMSG_GUILD_CREATE");
+ MessageOut msg(PCMSG_GUILD_CREATE);
+
+ msg.writeString(name);
+
+ Net::ChatServer::connection->send(msg);
+}
+
+void Net::ChatServer::Guild::invitePlayer(const std::string &name, short guildId)
+{
+ logger->log("Sending PCMSG_GUILD_INVITE");
+ MessageOut msg(PCMSG_GUILD_INVITE);
+
+ msg.writeInt16(guildId);
+ msg.writeString(name);
+
+ Net::ChatServer::connection->send(msg);
+}
+
+void Net::ChatServer::Guild::acceptInvite(const std::string &name)
+{
+ logger->log("Sending PCMSG_GUILD_ACCEPT");
+ MessageOut msg(PCMSG_GUILD_ACCEPT);
+
+ msg.writeString(name);
+
+ Net::ChatServer::connection->send(msg);
+}
+
+void Net::ChatServer::Guild::getGuildMembers(short guildId)
+{
+ logger->log("Sending PCMSG_GUILD_GET_MEMBERS");
+ MessageOut msg(PCMSG_GUILD_GET_MEMBERS);
+
+ msg.writeInt16(guildId);
+
+ Net::ChatServer::connection->send(msg);
+}
+
+void Net::ChatServer::Guild::promoteMember(const std::string &name,
+ short guildId, short level)
+{
+ logger->log("Sending PCMSG_GUILD_PROMOTE_MEMBER");
+ MessageOut msg(PCMSG_GUILD_PROMOTE_MEMBER);
+
+ msg.writeInt16(guildId);
+ msg.writeString(name);
+ msg.writeInt8(level);
+
+ Net::ChatServer::connection->send(msg);
+}
+
+void Net::ChatServer::Guild::quitGuild(short guildId)
+{
+ logger->log("Sending PCMSG_GUILD_QUIT");
+ MessageOut msg(PCMSG_GUILD_QUIT);
+
+ msg.writeInt16(guildId);
+
+ Net::ChatServer::connection->send(msg);
+}
diff --git a/src/net/chatserver/guild.h b/src/net/chatserver/guild.h
new file mode 100644
index 00000000..6c35be9f
--- /dev/null
+++ b/src/net/chatserver/guild.h
@@ -0,0 +1,69 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+#ifndef _TMW_NET_CHATSERVER_GUILD_H
+#define _TMW_NET_CHATSERVER_GUILD_H
+
+#include <iosfwd>
+
+namespace Net
+{
+ namespace ChatServer
+ {
+ namespace Guild
+ {
+ /**
+ * Create guild.
+ */
+ void createGuild(const std::string &name);
+
+ /**
+ * Invite a player to your guild.
+ */
+ void invitePlayer(const std::string &name, short guildId);
+
+ /**
+ * Accept an invite another player has sent to join their guild.
+ */
+ void acceptInvite(const std::string &name);
+
+ /**
+ * Get a list of members in a guild.
+ */
+ void getGuildMembers(short guildId);
+
+ /**
+ * Promote guild member
+ */
+ void promoteMember(const std::string &name, short guildId,
+ short level);
+
+ /**
+ * Quit guild.
+ */
+ void quitGuild(short guildId);
+ }
+ }
+}
+
+#endif
+
diff --git a/src/net/chatserver/internal.cpp b/src/net/chatserver/internal.cpp
new file mode 100644
index 00000000..0822d93d
--- /dev/null
+++ b/src/net/chatserver/internal.cpp
@@ -0,0 +1,32 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "internal.h"
+
+namespace Net
+{
+ class Connection;
+
+ namespace ChatServer
+ {
+ Connection *connection = 0;
+ }
+}
diff --git a/src/net/chatserver/internal.h b/src/net/chatserver/internal.h
new file mode 100644
index 00000000..b0f137c5
--- /dev/null
+++ b/src/net/chatserver/internal.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_CHATSERVER_INTERNAL_H
+#define _TMW_NET_CHATSERVER_INTERNAL_H
+
+namespace Net
+{
+ class Connection;
+
+ namespace ChatServer
+ {
+ extern Connection *connection;
+ }
+}
+
+#endif
diff --git a/src/net/chatserver/party.cpp b/src/net/chatserver/party.cpp
new file mode 100644
index 00000000..56eb57d2
--- /dev/null
+++ b/src/net/chatserver/party.cpp
@@ -0,0 +1,70 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+#include "party.h"
+
+#include "internal.h"
+
+#include "../connection.h"
+#include "../messageout.h"
+#include "../protocol.h"
+
+#include "../../log.h"
+
+void Net::ChatServer::Party::invitePlayer(const std::string &name)
+{
+ logger->log("Sending PCMSG_PARTY_INVITE");
+ MessageOut msg(PCMSG_PARTY_INVITE);
+
+ msg.writeString(name);
+
+ Net::ChatServer::connection->send(msg);
+}
+
+void Net::ChatServer::Party::acceptInvite(const std::string &name)
+{
+ logger->log("Sending PCMSG_PARTY_ACCEPT_INVITE");
+ MessageOut msg(PCMSG_PARTY_ACCEPT_INVITE);
+
+ msg.writeString(name);
+
+ Net::ChatServer::connection->send(msg);
+}
+
+void Net::ChatServer::Party::getPartyMembers()
+{
+ logger->log("Sending PCMSG_PARTY_GET_MEMBERS");
+// MessageOut msg(PCMSG_GUILD_GET_MEMBERS);
+
+// msg.writeInt16(guildId);
+
+// Net::ChatServer::connection->send(msg);
+}
+
+void Net::ChatServer::Party::quitParty()
+{
+ logger->log("Sending PCMSG_PARTY_QUIT");
+ MessageOut msg(PCMSG_PARTY_QUIT);
+
+ Net::ChatServer::connection->send(msg);
+}
+
diff --git a/src/net/chatserver/party.h b/src/net/chatserver/party.h
new file mode 100644
index 00000000..c1febd66
--- /dev/null
+++ b/src/net/chatserver/party.h
@@ -0,0 +1,57 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+#ifndef _TMW_NET_CHATSERVER_PARTY_H
+#define _TMW_NET_CHATSERVER_PARTY_H
+
+#include <iosfwd>
+
+namespace Net
+{
+ namespace ChatServer
+ {
+ namespace Party
+ {
+ /**
+ * Invite a player to the party.
+ */
+ void invitePlayer(const std::string &name);
+
+ /**
+ * Accept an invite another player has sent to join their party
+ */
+ void acceptInvite(const std::string &name);
+
+ /**
+ * Get a list of party members
+ */
+ void getPartyMembers();
+
+ /**
+ * Leave party
+ */
+ void quitParty();
+ }
+ }
+}
+
+#endif
diff --git a/src/net/connection.cpp b/src/net/connection.cpp
new file mode 100644
index 00000000..7d3c2328
--- /dev/null
+++ b/src/net/connection.cpp
@@ -0,0 +1,103 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "connection.h"
+
+#include <string>
+
+#include "internal.h"
+#include "messageout.h"
+
+#include "../log.h"
+
+Net::Connection::Connection(ENetHost *client):
+ mConnection(0), mClient(client)
+{
+ Net::connections++;
+}
+
+Net::Connection::~Connection()
+{
+ Net::connections--;
+}
+
+bool Net::Connection::connect(const std::string &address, short port)
+{
+ logger->log("Net::Connection::connect(%s, %i)", address.c_str(), port);
+
+ if (address.empty())
+ {
+ logger->log("Net::Connection::connect() got empty address!");
+ mState = NET_ERROR;
+ return false;
+ }
+
+ ENetAddress enetAddress;
+
+ enet_address_set_host(&enetAddress, address.c_str());
+ enetAddress.port = port;
+
+ // Initiate the connection, allocating channel 0.
+ mConnection = enet_host_connect(mClient, &enetAddress, 1);
+
+ if (!mConnection)
+ {
+ logger->log("Unable to initiate connection to the server.");
+ mState = NET_ERROR;
+ return false;
+ }
+
+ return true;
+}
+
+void Net::Connection::disconnect()
+{
+ if (!mConnection)
+ return;
+
+ enet_peer_disconnect(mConnection, 0);
+ enet_host_flush(mClient);
+ enet_peer_reset(mConnection);
+
+ mConnection = 0;
+}
+
+bool Net::Connection::isConnected()
+{
+ return bool (mConnection) ?
+ (mConnection->state == ENET_PEER_STATE_CONNECTED) : false;
+}
+
+void Net::Connection::send(const MessageOut &msg)
+{
+ if (!isConnected())
+ {
+ logger->log("Warning: cannot send message to not connected server!");
+ return;
+ }
+
+ //logger->log("Sending message of size %d...", msg.getDataSize());
+
+ ENetPacket *packet = enet_packet_create(msg.getData(),
+ msg.getDataSize(),
+ ENET_PACKET_FLAG_RELIABLE);
+ enet_peer_send(mConnection, 0, packet);
+}
diff --git a/src/net/connection.h b/src/net/connection.h
new file mode 100644
index 00000000..4ab3d24d
--- /dev/null
+++ b/src/net/connection.h
@@ -0,0 +1,80 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_CONNECTION_H
+#define _TMW_NET_CONNECTION_H
+
+#include <iosfwd>
+
+#include <enet/enet.h>
+
+class MessageOut;
+
+namespace Net
+{
+ /**
+ * \ingroup Network
+ */
+ class Connection
+ {
+ public:
+ enum State {
+ OK,
+ NET_ERROR
+ };
+
+ ~Connection();
+
+ /**
+ * Connects to the given server with the specified address and port.
+ * This method is non-blocking, use isConnected to check whether the
+ * server is connected.
+ */
+ bool connect(const std::string &address, short port);
+
+ /**
+ * Disconnects from the given server.
+ */
+ void disconnect();
+
+ State getState() { return mState; }
+
+ /**
+ * Returns whether the server is connected.
+ */
+ bool isConnected();
+
+ /**
+ * Sends a message.
+ */
+ void send(const MessageOut &msg);
+
+ private:
+ friend Connection *Net::getConnection();
+ Connection(ENetHost *client);
+
+ ENetPeer *mConnection;
+ ENetHost *mClient;
+ State mState;
+ };
+}
+
+#endif
diff --git a/src/net/ea/beinghandler.cpp b/src/net/ea/beinghandler.cpp
new file mode 100644
index 00000000..1edc6079
--- /dev/null
+++ b/src/net/ea/beinghandler.cpp
@@ -0,0 +1,542 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <iostream>
+#include <SDL_types.h>
+
+#include "beinghandler.h"
+#include "../messagein.h"
+#include "protocol.h"
+
+#include "../../being.h"
+#include "../../beingmanager.h"
+#include "../../effectmanager.h"
+#include "../../game.h"
+#include "../../localplayer.h"
+#include "../../log.h"
+#include "../../npc.h"
+#include "../../player_relations.h"
+
+const int EMOTION_TIME = 150; /**< Duration of emotion icon */
+
+BeingHandler::BeingHandler(bool enableSync):
+ mSync(enableSync)
+{
+ static const Uint16 _messages[] = {
+ SMSG_BEING_VISIBLE,
+ SMSG_BEING_MOVE,
+ SMSG_BEING_MOVE2,
+ SMSG_BEING_REMOVE,
+ SMSG_BEING_ACTION,
+ SMSG_BEING_SELFEFFECT,
+ SMSG_BEING_EMOTION,
+ SMSG_BEING_CHANGE_LOOKS,
+ SMSG_BEING_CHANGE_LOOKS2,
+ SMSG_BEING_NAME_RESPONSE,
+ SMSG_PLAYER_UPDATE_1,
+ SMSG_PLAYER_UPDATE_2,
+ SMSG_PLAYER_MOVE,
+ SMSG_PLAYER_STOP,
+ SMSG_PLAYER_MOVE_TO_ATTACK,
+ 0x0119,
+ 0x0196,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void BeingHandler::handleMessage(MessageIn &msg)
+{
+ Uint32 id;
+ Uint16 job, speed;
+ Uint16 headTop, headMid, headBottom;
+ Uint16 shoes, gloves;
+ Uint16 weapon, shield;
+ Uint16 gmstatus;
+ Sint16 param1;
+ int stunMode;
+ Uint32 statusEffects;
+ Sint8 type;
+ Uint16 status;
+ Being *srcBeing, *dstBeing;
+ int hairStyle, hairColor, flag;
+
+ switch (msg.getId())
+ {
+ case SMSG_BEING_VISIBLE:
+ case SMSG_BEING_MOVE:
+ // Information about a being in range
+ id = msg.readInt32();
+ speed = msg.readInt16();
+ stunMode = msg.readInt16(); // opt1
+ statusEffects = msg.readInt16(); // opt2
+ statusEffects |= ((Uint32)msg.readInt16()) << 16; // option
+ job = msg.readInt16(); // class
+
+ dstBeing = beingManager->findBeing(id);
+
+ if (!dstBeing)
+ {
+ // Being with id >= 110000000 and job 0 are better
+ // known as ghosts, so don't create those.
+ if (job == 0 && id >= 110000000)
+ {
+ break;
+ }
+
+ dstBeing = beingManager->createBeing(id, job);
+ }
+ else if (msg.getId() == 0x0078)
+ {
+ dstBeing->clearPath();
+ dstBeing->mFrame = 0;
+ dstBeing->mWalkTime = tick_time;
+ dstBeing->setAction(Being::STAND);
+ }
+
+
+ // Prevent division by 0 when calculating frame
+ if (speed == 0) { speed = 150; }
+
+ dstBeing->setWalkSpeed(speed);
+ dstBeing->mJob = job;
+ hairStyle = msg.readInt16();
+ dstBeing->setSprite(Being::WEAPON_SPRITE, msg.readInt16());
+ headBottom = msg.readInt16();
+
+ if (msg.getId() == SMSG_BEING_MOVE)
+ {
+ msg.readInt32(); // server tick
+ }
+
+ dstBeing->setSprite(Being::SHIELD_SPRITE, msg.readInt16());
+ headTop = msg.readInt16();
+ headMid = msg.readInt16();
+ hairColor = msg.readInt16();
+ shoes = msg.readInt16(); // clothes color - "abused" as shoes
+ gloves = msg.readInt16(); // head dir - "abused" as gloves
+ msg.readInt16(); // guild
+ msg.readInt16(); // unknown
+ msg.readInt16(); // unknown
+ msg.readInt16(); // manner
+ dstBeing->setStatusEffectBlock(32, msg.readInt16()); // opt3
+ msg.readInt8(); // karma
+ dstBeing->setGender(
+ (msg.readInt8() == 0) ? GENDER_FEMALE : GENDER_MALE);
+
+ // Set these after the gender, as the sprites may be gender-specific
+ dstBeing->setSprite(Being::BOTTOMCLOTHES_SPRITE, headBottom);
+ dstBeing->setSprite(Being::TOPCLOTHES_SPRITE, headMid);
+ dstBeing->setSprite(Being::HAT_SPRITE, headTop);
+ dstBeing->setSprite(Being::SHOE_SPRITE, shoes);
+ dstBeing->setSprite(Being::GLOVES_SPRITE, gloves);
+ dstBeing->setHairStyle(hairStyle, hairColor);
+
+ if (msg.getId() == SMSG_BEING_MOVE)
+ {
+ Uint16 srcX, srcY, dstX, dstY;
+ msg.readCoordinatePair(srcX, srcY, dstX, dstY);
+ dstBeing->setAction(Being::STAND);
+ dstBeing->mX = srcX;
+ dstBeing->mY = srcY;
+ dstBeing->setDestination(dstX, dstY);
+ }
+ else
+ {
+ Uint8 dir;
+ msg.readCoordinates(dstBeing->mX, dstBeing->mY, dir);
+ dstBeing->setDirection(dir);
+ }
+
+ msg.readInt8(); // unknown
+ msg.readInt8(); // unknown
+ msg.readInt8(); // unknown / sit
+
+ dstBeing->setStunMode(stunMode);
+ dstBeing->setStatusEffectBlock(0, (statusEffects >> 16) & 0xffff);
+ dstBeing->setStatusEffectBlock(16, statusEffects & 0xffff);
+ break;
+
+ case SMSG_BEING_MOVE2:
+ /*
+ * A simplified movement packet, used by the
+ * later versions of eAthena for both mobs and
+ * players
+ */
+ dstBeing = beingManager->findBeing(msg.readInt32());
+
+ Uint16 srcX, srcY, dstX, dstY;
+ msg.readCoordinatePair(srcX, srcY, dstX, dstY);
+ msg.readInt32(); // Server tick
+
+ /*
+ * This packet doesn't have enough info to actually
+ * create a new being, so if the being isn't found,
+ * we'll just pretend the packet didn't happen
+ */
+
+ if (dstBeing) {
+ dstBeing->setAction(Being::STAND);
+ dstBeing->mX = srcX;
+ dstBeing->mY = srcY;
+ dstBeing->setDestination(dstX, dstY);
+ }
+
+ break;
+
+ case SMSG_BEING_REMOVE:
+ // A being should be removed or has died
+ dstBeing = beingManager->findBeing(msg.readInt32());
+
+ if (!dstBeing)
+ break;
+
+ // If this is player's current target, clear it.
+ if (dstBeing == player_node->getTarget())
+ player_node->stopAttack();
+
+ if (dstBeing == current_npc)
+ current_npc->handleDeath();
+
+ if (msg.readInt8() == 1)
+ dstBeing->setAction(Being::DEAD);
+ else
+ beingManager->destroyBeing(dstBeing);
+
+ break;
+
+ case SMSG_BEING_ACTION:
+ srcBeing = beingManager->findBeing(msg.readInt32());
+ dstBeing = beingManager->findBeing(msg.readInt32());
+ msg.readInt32(); // server tick
+ msg.readInt32(); // src speed
+ msg.readInt32(); // dst speed
+ param1 = msg.readInt16();
+ msg.readInt16(); // param 2
+ type = msg.readInt8();
+ msg.readInt16(); // param 3
+
+ switch (type)
+ {
+ case 0x0a: // Critical Damage
+ if (dstBeing)
+ dstBeing->showCrit();
+ case 0x00: // Damage
+ if (dstBeing)
+ dstBeing->takeDamage(param1);
+ if (srcBeing)
+ srcBeing->handleAttack(dstBeing, param1);
+ break;
+
+ case 0x02: // Sit
+ if (srcBeing)
+ {
+ srcBeing->mFrame = 0;
+ srcBeing->setAction(Being::SIT);
+ }
+ break;
+
+ case 0x03: // Stand up
+ if (srcBeing)
+ {
+ srcBeing->mFrame = 0;
+ srcBeing->setAction(Being::STAND);
+ }
+ break;
+ }
+ break;
+
+ case SMSG_BEING_SELFEFFECT: {
+ id = (Uint32)msg.readInt32();
+ if (!beingManager->findBeing(id))
+ break;
+
+ int effectType = msg.readInt32();
+ Being* being = beingManager->findBeing(id);
+
+ effectManager->trigger(effectType, being);
+
+ break;
+ }
+
+ case SMSG_BEING_EMOTION:
+ if (!(dstBeing = beingManager->findBeing(msg.readInt32())))
+ {
+ break;
+ }
+
+ if (player_relations.hasPermission(dstBeing, PlayerRelation::EMOTE))
+ dstBeing->setEmote(msg.readInt8(), EMOTION_TIME);
+
+ break;
+
+ case SMSG_BEING_CHANGE_LOOKS:
+ case SMSG_BEING_CHANGE_LOOKS2:
+ {
+ /*
+ * SMSG_BEING_CHANGE_LOOKS (0x00c3) and
+ * SMSG_BEING_CHANGE_LOOKS2 (0x01d7) do basically the same
+ * thing. The difference is that ...LOOKS carries a single
+ * 8 bit value, where ...LOOKS2 carries two 16 bit values.
+ *
+ * If type = 2, then the first 16 bit value is the weapon ID,
+ * and the second 16 bit value is the shield ID. If no
+ * shield is equipped, or type is not 2, then the second
+ * 16 bit value will be 0.
+ */
+
+ if (!(dstBeing = beingManager->findBeing(msg.readInt32())))
+ {
+ break;
+ }
+
+ int type = msg.readInt8();
+ int id = 0;
+ int id2 = 0;
+
+ if (msg.getId() == SMSG_BEING_CHANGE_LOOKS) {
+ id = msg.readInt8();
+ } else { // SMSG_BEING_CHANGE_LOOKS2
+ id = msg.readInt16();
+ id2 = msg.readInt16();
+ }
+
+ switch (type) {
+ case 1: // eAthena LOOK_HAIR
+ dstBeing->setHairStyle(id, -1);
+ break;
+ case 2: // Weapon ID in id, Shield ID in id2
+ dstBeing->setSprite(Being::WEAPON_SPRITE, id);
+ dstBeing->setSprite(Being::SHIELD_SPRITE, id2);
+ break;
+ case 3: // Change lower headgear for eAthena, pants for us
+ dstBeing->setSprite(Being::BOTTOMCLOTHES_SPRITE, id);
+ break;
+ case 4: // Change upper headgear for eAthena, hat for us
+ dstBeing->setSprite(Being::HAT_SPRITE, id);
+ break;
+ case 5: // Change middle headgear for eathena, armor for us
+ dstBeing->setSprite(Being::TOPCLOTHES_SPRITE, id);
+ break;
+ case 6: // eAthena LOOK_HAIR_COLOR
+ dstBeing->setHairStyle(-1, id);
+ break;
+ case 8: // eAthena LOOK_SHIELD
+ dstBeing->setSprite(Being::SHIELD_SPRITE, id);
+ break;
+ case 9: // eAthena LOOK_SHOES
+ dstBeing->setSprite(Being::SHOE_SPRITE, id);
+ break;
+ case 10: // LOOK_GLOVES
+ dstBeing->setSprite(Being::GLOVES_SPRITE, id);
+ break;
+ case 11: // LOOK_CAPE
+ dstBeing->setSprite(Being::CAPE_SPRITE, id);
+ break;
+ case 12:
+ dstBeing->setSprite(Being::MISC1_SPRITE, id);
+ break;
+ case 13:
+ dstBeing->setSprite(Being::MISC2_SPRITE, id);
+ break;
+ default:
+ logger->log("SMSG_BEING_CHANGE_LOOKS: unsupported type: "
+ "%d, id: %d", type, id);
+ break;
+ }
+ }
+ break;
+
+ case SMSG_BEING_NAME_RESPONSE:
+ if ((dstBeing = beingManager->findBeing(msg.readInt32())))
+ {
+ dstBeing->setName(msg.readString(24));
+ }
+ break;
+
+ case SMSG_PLAYER_UPDATE_1:
+ case SMSG_PLAYER_UPDATE_2:
+ case SMSG_PLAYER_MOVE:
+ // An update about a player, potentially including movement.
+ id = msg.readInt32();
+ speed = msg.readInt16();
+ stunMode = msg.readInt16(); // opt1; Aethyra use this as cape
+ statusEffects = msg.readInt16(); // opt2; Aethyra use this as misc1
+ statusEffects |= ((Uint32) msg.readInt16())
+ << 16; // status.options; Aethyra uses this as misc2
+ job = msg.readInt16();
+
+ dstBeing = beingManager->findBeing(id);
+
+ if (!dstBeing)
+ {
+ dstBeing = beingManager->createBeing(id, job);
+ }
+
+ dstBeing->setWalkSpeed(speed);
+ dstBeing->mJob = job;
+ hairStyle = msg.readInt16();
+ weapon = msg.readInt16();
+ shield = msg.readInt16();
+ headBottom = msg.readInt16();
+
+ if (msg.getId() == SMSG_PLAYER_MOVE)
+ {
+ msg.readInt32(); // server tick
+ }
+
+ headTop = msg.readInt16();
+ headMid = msg.readInt16();
+ hairColor = msg.readInt16();
+ msg.readInt16(); // clothes color - Aethyra-"abused" as shoes, we ignore it
+ msg.readInt16(); // head dir - Aethyra-"abused" as gloves, we ignore it
+ msg.readInt32(); // guild
+ msg.readInt16(); // emblem
+ msg.readInt16(); // manner
+ dstBeing->setStatusEffectBlock(32, msg.readInt16()); // opt3
+ msg.readInt8(); // karma
+ dstBeing->setGender(
+ (msg.readInt8() == 0) ? GENDER_FEMALE : GENDER_MALE);
+
+ // Set these after the gender, as the sprites may be gender-specific
+ dstBeing->setSprite(Being::WEAPON_SPRITE, weapon);
+ dstBeing->setSprite(Being::SHIELD_SPRITE, shield);
+ dstBeing->setSprite(Being::BOTTOMCLOTHES_SPRITE, headBottom);
+ dstBeing->setSprite(Being::TOPCLOTHES_SPRITE, headMid);
+ dstBeing->setSprite(Being::HAT_SPRITE, headTop);
+ //dstBeing->setSprite(Being::CAPE_SPRITE, cape);
+ //dstBeing->setSprite(Being::MISC1_SPRITE, misc1);
+ //dstBeing->setSprite(Being::MISC2_SPRITE, misc2);
+ dstBeing->setHairStyle(hairStyle, hairColor);
+
+ if (msg.getId() == SMSG_PLAYER_MOVE)
+ {
+ Uint16 srcX, srcY, dstX, dstY;
+ msg.readCoordinatePair(srcX, srcY, dstX, dstY);
+ dstBeing->mX = srcX;
+ dstBeing->mY = srcY;
+ dstBeing->setDestination(dstX, dstY);
+ }
+ else
+ {
+ Uint8 dir;
+ msg.readCoordinates(dstBeing->mX, dstBeing->mY, dir);
+ dstBeing->setDirection(dir);
+ }
+
+ gmstatus = msg.readInt16();
+ if (gmstatus & 0x80)
+ dstBeing->setGM();
+
+ if (msg.getId() == SMSG_PLAYER_UPDATE_1)
+ {
+ switch (msg.readInt8())
+ {
+ case 1:
+ if (dstBeing->getType() != Being::NPC)
+ dstBeing->setAction(Being::DEAD);
+ break;
+
+ case 2:
+ dstBeing->setAction(Being::SIT);
+ break;
+ }
+ }
+ else if (msg.getId() == SMSG_PLAYER_MOVE)
+ {
+ msg.readInt8(); // unknown
+ }
+
+ msg.readInt8(); // Lv
+ msg.readInt8(); // unknown
+
+ dstBeing->mWalkTime = tick_time;
+ dstBeing->mFrame = 0;
+
+ dstBeing->setStunMode(stunMode);
+ dstBeing->setStatusEffectBlock(0, (statusEffects >> 16) & 0xffff);
+ dstBeing->setStatusEffectBlock(16, statusEffects & 0xffff);
+ break;
+
+ case SMSG_PLAYER_STOP:
+ /*
+ * Instruction from server to stop walking at x, y.
+ *
+ * Some people like having this enabled. Others absolutely
+ * despise it. So I'm setting to so that it only affects the
+ * local player if the person has set a key "EnableSync" to "1"
+ * in their config.xml file.
+ *
+ * This packet will be honored for all other beings, regardless
+ * of the config setting.
+ */
+
+ id = msg.readInt32();
+ if (mSync || id != player_node->getId()) {
+ dstBeing = beingManager->findBeing(id);
+ if (dstBeing) {
+ dstBeing->mX = msg.readInt16();
+ dstBeing->mY = msg.readInt16();
+ if (dstBeing->mAction == Being::WALK) {
+ dstBeing->mFrame = 0;
+ dstBeing->setAction(Being::STAND);
+ }
+ }
+ }
+ break;
+
+ case SMSG_PLAYER_MOVE_TO_ATTACK:
+ /*
+ * This is an *advisory* message, telling the client that
+ * it needs to move the character before attacking
+ * a target (out of range, obstruction in line of fire).
+ * We can safely ignore this...
+ */
+ break;
+
+ case 0x0119:
+ // Change in players' flags
+ id = msg.readInt32();
+ dstBeing = beingManager->findBeing(id);
+ stunMode = msg.readInt16();
+ statusEffects = msg.readInt16();
+ statusEffects |= ((Uint32) msg.readInt16()) << 16;
+ msg.readInt8();
+
+ if (dstBeing) {
+ dstBeing->setStunMode(stunMode);
+ dstBeing->setStatusEffectBlock(0, (statusEffects >> 16) & 0xffff);
+ dstBeing->setStatusEffectBlock(16, statusEffects & 0xffff);
+ }
+ break;
+
+ case 0x0196:
+ // Status change
+ status = msg.readInt16();
+ id = msg.readInt32();
+ flag = msg.readInt8(); // 0: stop, 1: start
+
+ dstBeing = beingManager->findBeing(id);
+ if (dstBeing)
+ dstBeing->setStatusEffect(status, flag);
+ break;
+ }
+}
diff --git a/src/net/ea/beinghandler.h b/src/net/ea/beinghandler.h
new file mode 100644
index 00000000..16a7c8d6
--- /dev/null
+++ b/src/net/ea/beinghandler.h
@@ -0,0 +1,39 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_BEINGHANDLER_H
+#define NET_BEINGHANDLER_H
+
+#include "../messagehandler.h"
+
+class BeingHandler : public MessageHandler
+{
+ public:
+ BeingHandler(bool enableSync);
+
+ void handleMessage(MessageIn &msg);
+
+ private:
+ // Should we honor server "Stop Walking" packets
+ bool mSync;
+};
+
+#endif
diff --git a/src/net/ea/buysellhandler.cpp b/src/net/ea/buysellhandler.cpp
new file mode 100644
index 00000000..480c71b8
--- /dev/null
+++ b/src/net/ea/buysellhandler.cpp
@@ -0,0 +1,133 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <SDL_types.h>
+
+#include "buysellhandler.h"
+#include "../messagein.h"
+#include "protocol.h"
+
+#include "../../beingmanager.h"
+#include "../../inventory.h"
+#include "../../item.h"
+#include "../../localplayer.h"
+#include "../../npc.h"
+
+#include "../../gui/buy.h"
+#include "../../gui/chat.h"
+#include "../../gui/sell.h"
+
+#include "../../utils/gettext.h"
+
+extern BuyDialog *buyDialog;
+extern Window *buySellDialog;
+extern SellDialog *sellDialog;
+
+BuySellHandler::BuySellHandler()
+{
+ static const Uint16 _messages[] = {
+ SMSG_NPC_BUY_SELL_CHOICE,
+ SMSG_NPC_BUY,
+ SMSG_NPC_SELL,
+ SMSG_NPC_BUY_RESPONSE,
+ SMSG_NPC_SELL_RESPONSE,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void BuySellHandler::handleMessage(MessageIn &msg)
+{
+ int n_items;
+ switch (msg.getId())
+ {
+ case SMSG_NPC_BUY_SELL_CHOICE:
+ buyDialog->setVisible(false);
+ buyDialog->reset();
+ sellDialog->setVisible(false);
+ sellDialog->reset();
+ buySellDialog->setVisible(true);
+ current_npc = dynamic_cast<NPC*>(beingManager->findBeing(msg.readInt32()));
+ break;
+
+ case SMSG_NPC_BUY:
+ msg.readInt16(); // length
+ n_items = (msg.getLength() - 4) / 11;
+ buyDialog->reset();
+ buyDialog->setMoney(player_node->getMoney());
+ buyDialog->setVisible(true);
+
+ for (int k = 0; k < n_items; k++)
+ {
+ Sint32 value = msg.readInt32();
+ msg.readInt32(); // DCvalue
+ msg.readInt8(); // type
+ Sint16 itemId = msg.readInt16();
+ buyDialog->addItem(itemId, 0, value);
+ }
+ break;
+
+ case SMSG_NPC_SELL:
+ msg.readInt16(); // length
+ n_items = (msg.getLength() - 4) / 10;
+ if (n_items > 0) {
+ sellDialog->setMoney(player_node->getMoney());
+ sellDialog->reset();
+ sellDialog->setVisible(true);
+
+ for (int k = 0; k < n_items; k++)
+ {
+ Sint16 index = msg.readInt16();
+ Sint32 value = msg.readInt32();
+ msg.readInt32(); // OCvalue
+
+ Item *item = player_node->getInventory()->getItem(index);
+ if (item && !(item->isEquipped())) {
+ sellDialog->addItem(item, value);
+ }
+ }
+ }
+ else {
+ chatWindow->chatLog(_("Nothing to sell"), BY_SERVER);
+ if (current_npc) current_npc->handleDeath();
+ }
+ break;
+
+ case SMSG_NPC_BUY_RESPONSE:
+ if (msg.readInt8() == 0) {
+ chatWindow->chatLog(_("Thanks for buying"), BY_SERVER);
+ } else {
+ // Reset player money since buy dialog already assumed purchase
+ // would go fine
+ buyDialog->setMoney(player_node->getMoney());
+ chatWindow->chatLog(_("Unable to buy"), BY_SERVER);
+ }
+ break;
+
+ case SMSG_NPC_SELL_RESPONSE:
+ if (msg.readInt8() == 0) {
+ chatWindow->chatLog(_("Thanks for selling"), BY_SERVER);
+ } else {
+ chatWindow->chatLog(_("Unable to sell"), BY_SERVER);
+ }
+ break;
+ }
+}
diff --git a/src/net/ea/buysellhandler.h b/src/net/ea/buysellhandler.h
new file mode 100644
index 00000000..5bf58d8e
--- /dev/null
+++ b/src/net/ea/buysellhandler.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_BUYSELLHANDLER_H
+#define NET_BUYSELLHANDLER_H
+
+#include "../messagehandler.h"
+
+class BuySellHandler : public MessageHandler
+{
+ public:
+ BuySellHandler();
+
+ void handleMessage(MessageIn &msg);
+};
+
+#endif
diff --git a/src/net/ea/charserverhandler.cpp b/src/net/ea/charserverhandler.cpp
new file mode 100644
index 00000000..0fef3de7
--- /dev/null
+++ b/src/net/ea/charserverhandler.cpp
@@ -0,0 +1,235 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "charserverhandler.h"
+#include "../messagein.h"
+#include "protocol.h"
+
+#include "../../game.h"
+#include "../../localplayer.h"
+#include "../../log.h"
+#include "../../logindata.h"
+#include "../../main.h"
+
+#include "../../gui/char_select.h"
+#include "../../gui/ok_dialog.h"
+
+#include "../../utils/gettext.h"
+#include "../../utils/stringutils.h"
+
+CharServerHandler::CharServerHandler():
+ mCharCreateDialog(0)
+{
+ static const Uint16 _messages[] = {
+ SMSG_CONNECTION_PROBLEM,
+ 0x006b,
+ 0x006c,
+ 0x006d,
+ 0x006e,
+ 0x006f,
+ 0x0070,
+ 0x0071,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void CharServerHandler::handleMessage(MessageIn &msg)
+{
+ int slot, flags, code;
+ LocalPlayer *tempPlayer;
+
+ logger->log("CharServerHandler: Packet ID: %x, Length: %d",
+ msg.getId(), msg.getLength());
+ switch (msg.getId())
+ {
+ case SMSG_CONNECTION_PROBLEM:
+ code = msg.readInt8();
+ logger->log("Connection problem: %i", code);
+
+ switch (code) {
+ case 0:
+ errorMessage = _("Authentication failed");
+ break;
+ case 1:
+ errorMessage = _("Map server(s) offline");
+ break;
+ case 2:
+ errorMessage = _("This account is already logged in");
+ break;
+ case 3:
+ errorMessage = _("Speed hack detected");
+ break;
+ case 8:
+ errorMessage = _("Duplicated login");
+ break;
+ default:
+ errorMessage = _("Unknown connection error");
+ break;
+ }
+ state = STATE_ERROR;
+ break;
+
+ case 0x006b:
+ msg.skip(2); // Length word
+ flags = msg.readInt32(); // Aethyra extensions flags
+ logger->log("Server flags are: %x", flags);
+ msg.skip(16); // Unused
+
+ // Derive number of characters from message length
+ n_character = (msg.getLength() - 24) / 106;
+
+ for (int i = 0; i < n_character; i++)
+ {
+ tempPlayer = readPlayerData(msg, slot);
+ mCharInfo->select(slot);
+ mCharInfo->setEntry(tempPlayer);
+ logger->log("CharServer: Player: %s (%d)",
+ tempPlayer->getName().c_str(), slot);
+ }
+
+ state = STATE_CHAR_SELECT;
+ break;
+
+ case 0x006c:
+ switch (msg.readInt8()) {
+ case 0:
+ errorMessage = _("Access denied");
+ break;
+ case 1:
+ errorMessage = _("Cannot use this ID");
+ break;
+ default:
+ errorMessage = _("Unknown failure to select character");
+ break;
+ }
+ mCharInfo->unlock();
+ break;
+
+ case 0x006d:
+ tempPlayer = readPlayerData(msg, slot);
+ mCharInfo->unlock();
+ mCharInfo->select(slot);
+ mCharInfo->setEntry(tempPlayer);
+ n_character++;
+
+ // Close the character create dialog
+ if (mCharCreateDialog)
+ {
+ mCharCreateDialog->scheduleDelete();
+ mCharCreateDialog = 0;
+ }
+ break;
+
+ case 0x006e:
+ new OkDialog(_("Error"), _("Failed to create character. Most likely"
+ " the name is already taken."));
+
+ if (mCharCreateDialog)
+ mCharCreateDialog->unlock();
+ break;
+
+ case 0x006f:
+ delete mCharInfo->getEntry();
+ mCharInfo->setEntry(0);
+ mCharInfo->unlock();
+ n_character--;
+ new OkDialog(_("Info"), _("Player deleted"));
+ break;
+
+ case 0x0070:
+ mCharInfo->unlock();
+ new OkDialog(_("Error"), _("Failed to delete character."));
+ break;
+
+ case 0x0071:
+ player_node = mCharInfo->getEntry();
+ slot = mCharInfo->getPos();
+ msg.skip(4); // CharID, must be the same as player_node->charID
+ map_path = msg.readString(16);
+ mLoginData->hostname = ipToString(msg.readInt32());
+ mLoginData->port = msg.readInt16();
+ mCharInfo->unlock();
+ mCharInfo->select(0);
+ // Clear unselected players infos
+ do
+ {
+ LocalPlayer *tmp = mCharInfo->getEntry();
+ if (tmp != player_node)
+ {
+ delete tmp;
+ mCharInfo->setEntry(0);
+ }
+ mCharInfo->next();
+ } while (mCharInfo->getPos());
+
+ mCharInfo->select(slot);
+ state = STATE_CONNECTING;
+ break;
+ }
+}
+
+LocalPlayer *CharServerHandler::readPlayerData(MessageIn &msg, int &slot)
+{
+ LocalPlayer *tempPlayer = new LocalPlayer(mLoginData->account_ID, 0, NULL);
+ tempPlayer->setGender(
+ (mLoginData->sex == 0) ? GENDER_FEMALE : GENDER_MALE);
+
+ tempPlayer->mCharId = msg.readInt32();
+ tempPlayer->setXp(msg.readInt32());
+ tempPlayer->setMoney(msg.readInt32());
+ tempPlayer->mJobXp = msg.readInt32();
+ tempPlayer->mJobLevel = msg.readInt32();
+ tempPlayer->setSprite(Being::SHOE_SPRITE, msg.readInt16());
+ tempPlayer->setSprite(Being::GLOVES_SPRITE, msg.readInt16());
+ tempPlayer->setSprite(Being::CAPE_SPRITE, msg.readInt16());
+ tempPlayer->setSprite(Being::MISC1_SPRITE, msg.readInt16());
+ msg.readInt32(); // option
+ msg.readInt32(); // karma
+ msg.readInt32(); // manner
+ msg.skip(2); // unknown
+ tempPlayer->setHp(msg.readInt16());
+ tempPlayer->setMaxHp(msg.readInt16());
+ tempPlayer->mMp = msg.readInt16();
+ tempPlayer->mMaxMp = msg.readInt16();
+ msg.readInt16(); // speed
+ msg.readInt16(); // class
+ int hairStyle = msg.readInt16();
+ Uint16 weapon = msg.readInt16();
+ tempPlayer->setSprite(Being::WEAPON_SPRITE, weapon);
+ tempPlayer->setLevel(msg.readInt16());
+ msg.readInt16(); // skill point
+ tempPlayer->setSprite(Being::BOTTOMCLOTHES_SPRITE, msg.readInt16()); // head bottom
+ tempPlayer->setSprite(Being::SHIELD_SPRITE, msg.readInt16());
+ tempPlayer->setSprite(Being::HAT_SPRITE, msg.readInt16()); // head option top
+ tempPlayer->setSprite(Being::TOPCLOTHES_SPRITE, msg.readInt16()); // head option mid
+ int hairColor = msg.readInt16();
+ tempPlayer->setHairStyle(hairStyle, hairColor);
+ tempPlayer->setSprite(Being::MISC2_SPRITE, msg.readInt16());
+ tempPlayer->setName(msg.readString(24));
+ for (int i = 0; i < 6; i++) {
+ tempPlayer->mAttr[i] = msg.readInt8();
+ }
+ slot = msg.readInt8(); // character slot
+ msg.readInt8(); // unknown
+
+ return tempPlayer;
+}
diff --git a/src/net/ea/charserverhandler.h b/src/net/ea/charserverhandler.h
new file mode 100644
index 00000000..237f5e49
--- /dev/null
+++ b/src/net/ea/charserverhandler.h
@@ -0,0 +1,65 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_CHARSERVERHANDLER_H
+#define NET_CHARSERVERHANDLER_H
+
+#include "../messagehandler.h"
+
+#include "../../lockedarray.h"
+
+class CharCreateDialog;
+class LocalPlayer;
+class LoginData;
+
+/**
+ * Deals with incoming messages from the character server.
+ */
+class CharServerHandler : public MessageHandler
+{
+ public:
+ CharServerHandler();
+
+ void handleMessage(MessageIn &msg);
+
+ void setCharInfo(LockedArray<LocalPlayer*> *charInfo)
+ { mCharInfo = charInfo; }
+
+ void setLoginData(LoginData *loginData)
+ { mLoginData = loginData; }
+
+ /**
+ * Sets the character create dialog. The handler will clean up this
+ * dialog when a new character is succesfully created, and will unlock
+ * the dialog when a new character failed to be created.
+ */
+ void setCharCreateDialog(CharCreateDialog *window)
+ { mCharCreateDialog = window; }
+
+ protected:
+ LoginData *mLoginData;
+ LockedArray<LocalPlayer*> *mCharInfo;
+ CharCreateDialog *mCharCreateDialog;
+
+ LocalPlayer* readPlayerData(MessageIn &msg, int &slot);
+};
+
+#endif
diff --git a/src/net/ea/chathandler.cpp b/src/net/ea/chathandler.cpp
new file mode 100644
index 00000000..0293f987
--- /dev/null
+++ b/src/net/ea/chathandler.cpp
@@ -0,0 +1,175 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <SDL_types.h>
+#include <string>
+
+#include "chathandler.h"
+#include "../messagein.h"
+#include "protocol.h"
+
+#include "../../being.h"
+#include "../../beingmanager.h"
+#include "../../game.h"
+#include "../../player_relations.h"
+
+#include "../../gui/chat.h"
+
+#include "../../utils/gettext.h"
+#include "../../utils/stringutils.h"
+
+extern Being *player_node;
+
+#define SERVER_NAME "Server"
+
+ChatHandler::ChatHandler()
+{
+ static const Uint16 _messages[] = {
+ SMSG_BEING_CHAT,
+ SMSG_PLAYER_CHAT,
+ SMSG_WHISPER,
+ SMSG_WHISPER_RESPONSE,
+ SMSG_GM_CHAT,
+ SMSG_WHO_ANSWER,
+ 0x10c, // MVP
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void ChatHandler::handleMessage(MessageIn &msg)
+{
+ Being *being;
+ std::string chatMsg;
+ std::string nick;
+ Sint16 chatMsgLength;
+
+ switch (msg.getId())
+ {
+ case SMSG_WHISPER_RESPONSE:
+ switch (msg.readInt8())
+ {
+ case 0x00:
+ // comment out since we'll local echo in chat.cpp instead, then only report failures
+ //chatWindow->chatLog("Whisper sent", BY_SERVER);
+ break;
+ case 0x01:
+ chatWindow->chatLog(_("Whisper could not be sent, user is offline"), BY_SERVER);
+ break;
+ case 0x02:
+ chatWindow->chatLog(_("Whisper could not be sent, ignored by user"), BY_SERVER);
+ break;
+ }
+ break;
+
+ // Received whisper
+ case SMSG_WHISPER:
+ chatMsgLength = msg.readInt16() - 28;
+ nick = msg.readString(24);
+
+ if (chatMsgLength <= 0)
+ break;
+
+ chatMsg = msg.readString(chatMsgLength);
+ if (nick != SERVER_NAME)
+ chatMsg = nick + " : " + chatMsg;
+
+ if (nick == SERVER_NAME)
+ chatWindow->chatLog(chatMsg, BY_SERVER);
+ else {
+ if (player_relations.hasPermission(nick, PlayerRelation::WHISPER))
+ chatWindow->chatLog(chatMsg, ACT_WHISPER);
+ }
+
+ break;
+
+ // Received speech from being
+ case SMSG_BEING_CHAT: {
+ chatMsgLength = msg.readInt16() - 8;
+ being = beingManager->findBeing(msg.readInt32());
+
+ if (!being || chatMsgLength <= 0)
+ {
+ break;
+ }
+
+ chatMsg = msg.readString(chatMsgLength);
+
+ std::string::size_type pos = chatMsg.find(" : ", 0);
+ std::string sender_name = ((pos == std::string::npos)
+ ? ""
+ : chatMsg.substr(0, pos));
+
+ // We use getIgnorePlayer instead of ignoringPlayer here because ignorePlayer' side
+ // effects are triggered right below for Being::IGNORE_SPEECH_FLOAT.
+ if (player_relations.checkPermissionSilently(sender_name, PlayerRelation::SPEECH_LOG))
+ chatWindow->chatLog(chatMsg, BY_OTHER);
+
+ chatMsg.erase(0, pos + 3);
+ trim(chatMsg);
+
+ if (player_relations.hasPermission(sender_name, PlayerRelation::SPEECH_FLOAT))
+ being->setSpeech(chatMsg, SPEECH_TIME);
+ break;
+ }
+
+ case SMSG_PLAYER_CHAT:
+ case SMSG_GM_CHAT: {
+ chatMsgLength = msg.readInt16() - 4;
+
+ if (chatMsgLength <= 0)
+ {
+ break;
+ }
+
+ chatMsg = msg.readString(chatMsgLength);
+ std::string::size_type pos = chatMsg.find(" : ", 0);
+
+ if (msg.getId() == SMSG_PLAYER_CHAT)
+ {
+ chatWindow->chatLog(chatMsg, BY_PLAYER);
+
+ if (pos != std::string::npos)
+ chatMsg.erase(0, pos + 3);
+
+ trim(chatMsg);
+
+ player_node->setSpeech(chatMsg, SPEECH_TIME);
+ }
+ else
+ {
+ chatWindow->chatLog(chatMsg, BY_GM);
+ }
+ break;
+ }
+
+ case SMSG_WHO_ANSWER:
+ chatWindow->chatLog("Online users: " + toString(msg.readInt32()),
+ BY_SERVER);
+ break;
+
+ case 0x010c:
+ // Display MVP player
+ msg.readInt32(); // id
+ chatWindow->chatLog("MVP player", BY_SERVER);
+ break;
+ }
+}
diff --git a/src/net/ea/chathandler.h b/src/net/ea/chathandler.h
new file mode 100644
index 00000000..8207b1d5
--- /dev/null
+++ b/src/net/ea/chathandler.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_CHATHANDLER_H
+#define NET_CHATHANDLER_H
+
+#include "../messagehandler.h"
+
+class ChatHandler : public MessageHandler
+{
+ public:
+ ChatHandler();
+
+ void handleMessage(MessageIn &msg);
+};
+
+#endif
diff --git a/src/net/equipmenthandler.cpp b/src/net/ea/equipmenthandler.cpp
index 9a3c396a..19063daf 100644
--- a/src/net/equipmenthandler.cpp
+++ b/src/net/ea/equipmenthandler.cpp
@@ -20,18 +20,18 @@
*/
#include "equipmenthandler.h"
-#include "messagein.h"
+#include "../messagein.h"
#include "protocol.h"
-#include "../equipment.h"
-#include "../inventory.h"
-#include "../item.h"
-#include "../localplayer.h"
-#include "../log.h"
+#include "../../equipment.h"
+#include "../../inventory.h"
+#include "../../item.h"
+#include "../../localplayer.h"
+#include "../../log.h"
-#include "../gui/chat.h"
+#include "../../gui/chat.h"
-#include "../utils/gettext.h"
+#include "../../utils/gettext.h"
EquipmentHandler::EquipmentHandler()
{
@@ -46,7 +46,7 @@ EquipmentHandler::EquipmentHandler()
handledMessages = _messages;
}
-void EquipmentHandler::handleMessage(MessageIn *msg)
+void EquipmentHandler::handleMessage(MessageIn &msg)
{
Sint32 itemCount;
Sint16 index, equipPoint, itemId;
@@ -55,23 +55,23 @@ void EquipmentHandler::handleMessage(MessageIn *msg)
Item *item;
Inventory *inventory = player_node->getInventory();
- switch (msg->getId())
+ switch (msg.getId())
{
case SMSG_PLAYER_EQUIPMENT:
- msg->readInt16(); // length
- itemCount = (msg->getLength() - 4) / 20;
+ msg.readInt16(); // length
+ itemCount = (msg.getLength() - 4) / 20;
for (int loop = 0; loop < itemCount; loop++)
{
- index = msg->readInt16();
- itemId = msg->readInt16();
- msg->readInt8(); // type
- msg->readInt8(); // identify flag
- msg->readInt16(); // equip type
- equipPoint = msg->readInt16();
- msg->readInt8(); // attribute
- msg->readInt8(); // refine
- msg->skip(8); // card
+ index = msg.readInt16();
+ itemId = msg.readInt16();
+ msg.readInt8(); // type
+ msg.readInt8(); // identify flag
+ msg.readInt16(); // equip type
+ equipPoint = msg.readInt16();
+ msg.readInt8(); // attribute
+ msg.readInt8(); // refine
+ msg.skip(8); // card
inventory->setItem(index, itemId, 1, true);
@@ -91,9 +91,9 @@ void EquipmentHandler::handleMessage(MessageIn *msg)
break;
case SMSG_PLAYER_EQUIP:
- index = msg->readInt16();
- equipPoint = msg->readInt16();
- type = msg->readInt8();
+ index = msg.readInt16();
+ equipPoint = msg.readInt16();
+ type = msg.readInt8();
logger->log("Equipping: %i %i %i", index, equipPoint, type);
@@ -131,9 +131,9 @@ void EquipmentHandler::handleMessage(MessageIn *msg)
break;
case SMSG_PLAYER_UNEQUIP:
- index = msg->readInt16();
- equipPoint = msg->readInt16();
- type = msg->readInt8();
+ index = msg.readInt16();
+ equipPoint = msg.readInt16();
+ type = msg.readInt8();
if (!type) {
chatWindow->chatLog(_("Unable to unequip."), BY_SERVER);
@@ -169,11 +169,11 @@ void EquipmentHandler::handleMessage(MessageIn *msg)
break;
case SMSG_PLAYER_ATTACK_RANGE:
- player_node->setAttackRange(msg->readInt16());
+ player_node->setAttackRange(msg.readInt16());
break;
case SMSG_PLAYER_ARROW_EQUIP:
- index = msg->readInt16();
+ index = msg.readInt16();
if (index <= 1)
break;
diff --git a/src/net/equipmenthandler.h b/src/net/ea/equipmenthandler.h
index c66d7932..fe4a7ecc 100644
--- a/src/net/equipmenthandler.h
+++ b/src/net/ea/equipmenthandler.h
@@ -22,14 +22,14 @@
#ifndef NET_EQUIPMENTHANDLER_H
#define NET_EQUIPMENTHANDLER_H
-#include "messagehandler.h"
+#include "../messagehandler.h"
class EquipmentHandler : public MessageHandler
{
public:
EquipmentHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/ea/inventoryhandler.cpp b/src/net/ea/inventoryhandler.cpp
new file mode 100644
index 00000000..71eee291
--- /dev/null
+++ b/src/net/ea/inventoryhandler.cpp
@@ -0,0 +1,227 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <SDL_types.h>
+
+#include "inventoryhandler.h"
+#include "../messagein.h"
+#include "protocol.h"
+
+#include "../../inventory.h"
+#include "../../item.h"
+#include "../../itemshortcut.h"
+#include "../../localplayer.h"
+#include "../../log.h"
+
+#include "../../gui/chat.h"
+
+#include "../../resources/iteminfo.h"
+
+#include "../../utils/gettext.h"
+#include "../../utils/strprintf.h"
+#include "../../utils/stringutils.h"
+
+InventoryHandler::InventoryHandler()
+{
+ static const Uint16 _messages[] = {
+ SMSG_PLAYER_INVENTORY,
+ SMSG_PLAYER_INVENTORY_ADD,
+ SMSG_PLAYER_INVENTORY_REMOVE,
+ SMSG_PLAYER_INVENTORY_USE,
+ SMSG_ITEM_USE_RESPONSE,
+ SMSG_PLAYER_STORAGE_ITEMS,
+ SMSG_PLAYER_STORAGE_EQUIP,
+ SMSG_PLAYER_STORAGE_STATUS,
+ SMSG_PLAYER_STORAGE_ADD,
+ SMSG_PLAYER_STORAGE_REMOVE,
+ SMSG_PLAYER_STORAGE_CLOSE,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void InventoryHandler::handleMessage(MessageIn &msg)
+{
+ Sint32 number;
+ Sint16 index, amount, itemId, equipType, arrow;
+ Sint16 identified, cards[4], itemType;
+ Inventory *inventory = player_node->getInventory();
+ Inventory *storage = player_node->getStorage();
+
+ switch (msg.getId())
+ {
+ case SMSG_PLAYER_INVENTORY:
+ case SMSG_PLAYER_STORAGE_ITEMS:
+ case SMSG_PLAYER_STORAGE_EQUIP:
+ switch (msg.getId()) {
+ case SMSG_PLAYER_INVENTORY:
+ // Clear inventory - this will be a complete refresh
+ inventory->clear();
+ break;
+ case SMSG_PLAYER_STORAGE_ITEMS:
+ /*
+ * This packet will always be followed by a
+ * SMSG_PLAYER_STORAGE_EQUIP packet. The two packets
+ * together comprise a complete refresh of storage, so
+ * clear storage here
+ */
+ storage->clear();
+ logger->log("Received SMSG_PLAYER_STORAGE_ITEMS");
+ break;
+ default:
+ logger->log("Received SMSG_PLAYER_STORAGE_EQUIP");
+ break;
+ }
+ msg.readInt16(); // length
+ number = (msg.getLength() - 4) / 18;
+
+ for (int loop = 0; loop < number; loop++) {
+ index = msg.readInt16();
+ itemId = msg.readInt16();
+ itemType = msg.readInt8();
+ identified = msg.readInt8();
+ if (msg.getId() == SMSG_PLAYER_STORAGE_EQUIP) {
+ amount = 1;
+ msg.readInt16(); // Equip Point?
+ } else {
+ amount = msg.readInt16();
+ }
+ arrow = msg.readInt16();
+ if (msg.getId() == SMSG_PLAYER_STORAGE_EQUIP) {
+ msg.readInt8(); // Attribute (broken)
+ msg.readInt8(); // Refine level
+ }
+ for (int i = 0; i < 4; i++)
+ cards[i] = msg.readInt16();
+
+ if (msg.getId() == SMSG_PLAYER_INVENTORY) {
+ inventory->setItem(index, itemId, amount, false);
+
+ // Trick because arrows are not considered equipment
+ if (arrow & 0x8000) {
+ if (Item *item = inventory->getItem(index))
+ item->setEquipment(true);
+ }
+ } else {
+ logger->log("Index:%d, ID:%d, Type:%d, Identified:%d, Qty:%d, Cards:%d, %d, %d, %d",
+ index, itemId, itemType, identified, amount, cards[0], cards[1], cards[2], cards[3]);
+ storage->setItem(index, itemId, amount, false);
+ }
+ }
+ break;
+
+ case SMSG_PLAYER_INVENTORY_ADD:
+ index = msg.readInt16();
+ amount = msg.readInt16();
+ itemId = msg.readInt16();
+ identified = msg.readInt8();
+ msg.readInt8(); // attribute
+ msg.readInt8(); // refine
+ for (int i = 0; i < 4; i++)
+ cards[i] = msg.readInt16();
+ equipType = msg.readInt16();
+ itemType = msg.readInt8();
+
+ if (msg.readInt8() > 0) {
+ chatWindow->chatLog(_("Unable to pick up item"), BY_SERVER);
+ } else {
+ const ItemInfo &itemInfo = ItemDB::get(itemId);
+ const std::string amountStr =
+ (amount > 1) ? toString(amount) : "a";
+ chatWindow->chatLog(strprintf(_("You picked up %s %s"),
+ amountStr.c_str(), itemInfo.getName().c_str()), BY_SERVER);
+
+ if (Item *item = inventory->getItem(index)) {
+ item->setId(itemId);
+ item->increaseQuantity(amount);
+ } else {
+ inventory->setItem(index, itemId, amount, equipType != 0);
+ }
+ }
+ break;
+
+ case SMSG_PLAYER_INVENTORY_REMOVE:
+ index = msg.readInt16();
+ amount = msg.readInt16();
+ if (Item *item = inventory->getItem(index)) {
+ item->increaseQuantity(-amount);
+ if (item->getQuantity() == 0)
+ inventory->removeItemAt(index);
+ }
+ break;
+
+ case SMSG_PLAYER_INVENTORY_USE:
+ index = msg.readInt16();
+ msg.readInt16(); // item id
+ msg.readInt32(); // id
+ amount = msg.readInt16();
+ msg.readInt8(); // type
+
+ if (Item *item = inventory->getItem(index))
+ item->setQuantity(amount);
+ break;
+
+ case SMSG_ITEM_USE_RESPONSE:
+ index = msg.readInt16();
+ amount = msg.readInt16();
+
+ if (msg.readInt8() == 0) {
+ chatWindow->chatLog(_("Failed to use item"), BY_SERVER);
+ } else {
+ if (Item *item = inventory->getItem(index))
+ item->setQuantity(amount);
+ }
+ break;
+
+ case SMSG_PLAYER_STORAGE_STATUS:
+ /*
+ * Basic slots used vs total slots info
+ * We don't really need this information, but this is
+ * the closest we get to an "Open Storage" packet
+ * from the server. It always comes after the two
+ * SMSG_PLAYER_STORAGE_... packets that update
+ * storage contents.
+ */
+ logger->log("Received SMSG_PLAYER_STORAGE_STATUS");
+ player_node->setInStorage(true);
+ break;
+
+ case SMSG_PLAYER_STORAGE_ADD:
+ /*
+ * Move an item into storage
+ */
+ break;
+
+ case SMSG_PLAYER_STORAGE_REMOVE:
+ /*
+ * Move an item out of storage
+ */
+ break;
+
+ case SMSG_PLAYER_STORAGE_CLOSE:
+ /*
+ * Storage access has been closed
+ */
+ player_node->setInStorage(false);
+ logger->log("Received SMSG_PLAYER_STORAGE_CLOSE");
+ break;
+ }
+}
diff --git a/src/net/ea/inventoryhandler.h b/src/net/ea/inventoryhandler.h
new file mode 100644
index 00000000..b2e469fa
--- /dev/null
+++ b/src/net/ea/inventoryhandler.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_INVENTORYHANDLER_H
+#define NET_INVENTORYHANDLER_H
+
+#include "../messagehandler.h"
+
+class InventoryHandler : public MessageHandler
+{
+ public:
+ InventoryHandler();
+
+ void handleMessage(MessageIn &msg);
+};
+
+#endif
diff --git a/src/net/ea/loginhandler.cpp b/src/net/ea/loginhandler.cpp
new file mode 100644
index 00000000..3f58f2c0
--- /dev/null
+++ b/src/net/ea/loginhandler.cpp
@@ -0,0 +1,158 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "loginhandler.h"
+#include "../messagein.h"
+#include "protocol.h"
+
+#include "../../log.h"
+#include "../../logindata.h"
+#include "../../main.h"
+#include "../../serverinfo.h"
+
+#include "../../utils/gettext.h"
+#include "../../utils/strprintf.h"
+#include "../../utils/stringutils.h"
+
+extern SERVER_INFO **server_info;
+
+LoginHandler::LoginHandler()
+{
+ static const Uint16 _messages[] = {
+ SMSG_CONNECTION_PROBLEM,
+ SMSG_UPDATE_HOST,
+ 0x0069,
+ 0x006a,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void LoginHandler::handleMessage(MessageIn &msg)
+{
+ int code;
+
+ switch (msg.getId())
+ {
+ case SMSG_CONNECTION_PROBLEM:
+ code = msg.readInt8();
+ logger->log("Connection problem: %i", code);
+
+ switch (code) {
+ case 0:
+ errorMessage = _("Authentication failed");
+ break;
+ case 1:
+ errorMessage = _("No servers available");
+ break;
+ case 2:
+ errorMessage = _("This account is already logged in");
+ break;
+ default:
+ errorMessage = _("Unknown connection error");
+ break;
+ }
+ state = STATE_ERROR;
+ break;
+
+ case SMSG_UPDATE_HOST:
+ int len;
+
+ len = msg.readInt16() - 4;
+ mUpdateHost = msg.readString(len);
+
+ logger->log("Received update host \"%s\" from login server",
+ mUpdateHost.c_str());
+ break;
+
+ case 0x0069:
+ // Skip the length word
+ msg.skip(2);
+
+ n_server = (msg.getLength() - 47) / 32;
+ server_info =
+ (SERVER_INFO**) malloc(sizeof(SERVER_INFO*) * n_server);
+
+ mLoginData->session_ID1 = msg.readInt32();
+ mLoginData->account_ID = msg.readInt32();
+ mLoginData->session_ID2 = msg.readInt32();
+ msg.skip(30); // unknown
+ mLoginData->sex = msg.readInt8();
+
+ for (int i = 0; i < n_server; i++)
+ {
+ server_info[i] = new SERVER_INFO;
+
+ server_info[i]->address = msg.readInt32();
+ server_info[i]->port = msg.readInt16();
+ server_info[i]->name = msg.readString(20);
+ server_info[i]->online_users = msg.readInt32();
+ server_info[i]->updateHost = mUpdateHost;
+ msg.skip(2); // unknown
+
+ logger->log("Network: Server: %s (%s:%d)",
+ server_info[i]->name.c_str(),
+ ipToString(server_info[i]->address),
+ server_info[i]->port);
+ }
+ state = STATE_CHAR_SERVER;
+ break;
+
+ case 0x006a:
+ code = msg.readInt8();
+ logger->log("Login::error code: %i", code);
+
+ switch (code) {
+ case 0:
+ errorMessage = _("Unregistered ID");
+ break;
+ case 1:
+ errorMessage = _("Wrong password");
+ break;
+ case 2:
+ errorMessage = _("Account expired");
+ break;
+ case 3:
+ errorMessage = _("Rejected from server");
+ break;
+ case 4:
+
+ errorMessage = _("You have been permanently banned from "
+ "the game. Please contact the GM Team.");
+ break;
+ case 6:
+ errorMessage = strprintf(_("You have been temporarily "
+ "banned from the game until "
+ "%s.\n Please contact the GM "
+ "team via the forums."),
+ msg.readString(20).c_str());
+ break;
+ case 9:
+ errorMessage = _("This user name is already taken");
+ break;
+ default:
+ errorMessage = _("Unknown error");
+ break;
+ }
+ state = STATE_ERROR;
+ break;
+ }
+}
diff --git a/src/net/ea/loginhandler.h b/src/net/ea/loginhandler.h
new file mode 100644
index 00000000..c2ba5083
--- /dev/null
+++ b/src/net/ea/loginhandler.h
@@ -0,0 +1,45 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_LOGINHANDLER_H
+#define NET_LOGINHANDLER_H
+
+#include <string>
+
+#include "../messagehandler.h"
+
+struct LoginData;
+
+class LoginHandler : public MessageHandler
+{
+ public:
+ LoginHandler();
+
+ void handleMessage(MessageIn &msg);
+
+ void setLoginData(LoginData *loginData) { mLoginData = loginData; };
+
+ private:
+ LoginData *mLoginData;
+ std::string mUpdateHost;
+};
+
+#endif
diff --git a/src/net/maploginhandler.cpp b/src/net/ea/maploginhandler.cpp
index b5192bd7..6931024e 100644
--- a/src/net/maploginhandler.cpp
+++ b/src/net/ea/maploginhandler.cpp
@@ -20,14 +20,14 @@
*/
#include "maploginhandler.h"
-#include "messagein.h"
+#include "../messagein.h"
#include "protocol.h"
-#include "../localplayer.h"
-#include "../log.h"
-#include "../main.h"
+#include "../../localplayer.h"
+#include "../../log.h"
+#include "../../main.h"
-#include "../utils/gettext.h"
+#include "../../utils/gettext.h"
MapLoginHandler::MapLoginHandler()
{
@@ -39,15 +39,15 @@ MapLoginHandler::MapLoginHandler()
handledMessages = _messages;
}
-void MapLoginHandler::handleMessage(MessageIn *msg)
+void MapLoginHandler::handleMessage(MessageIn &msg)
{
int code;
unsigned char direction;
- switch (msg->getId())
+ switch (msg.getId())
{
case SMSG_CONNECTION_PROBLEM:
- code = msg->readInt8();
+ code = msg.readInt8();
logger->log("Connection problem: %i", code);
switch (code) {
@@ -61,16 +61,16 @@ void MapLoginHandler::handleMessage(MessageIn *msg)
errorMessage = _("Unknown connection error");
break;
}
- state = ERROR_STATE;
+ state = STATE_ERROR;
break;
case SMSG_LOGIN_SUCCESS:
- msg->readInt32(); // server tick
- msg->readCoordinates(player_node->mX, player_node->mY, direction);
- msg->skip(2); // unknown
+ msg.readInt32(); // server tick
+ msg.readCoordinates(player_node->mX, player_node->mY, direction);
+ msg.skip(2); // unknown
logger->log("Protocol: Player start position: (%d, %d), Direction: %d",
player_node->mX, player_node->mY, direction);
- state = GAME_STATE;
+ state = STATE_GAME;
break;
}
}
diff --git a/src/net/maploginhandler.h b/src/net/ea/maploginhandler.h
index c7fee70c..1ce5ee79 100644
--- a/src/net/maploginhandler.h
+++ b/src/net/ea/maploginhandler.h
@@ -22,14 +22,14 @@
#ifndef NET_MAPLOGINHANDLER_H
#define NET_MAPLOGINHANDLER_H
-#include "messagehandler.h"
+#include "../messagehandler.h"
class MapLoginHandler : public MessageHandler
{
public:
MapLoginHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/ea/network.cpp b/src/net/ea/network.cpp
new file mode 100644
index 00000000..199e94da
--- /dev/null
+++ b/src/net/ea/network.cpp
@@ -0,0 +1,436 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <sstream>
+
+#include "../messagehandler.h"
+#include "../messagein.h"
+#include "network.h"
+
+#include "../../log.h"
+#include "../../utils/stringutils.h"
+
+/** Warning: buffers and other variables are shared,
+ so there can be only one connection active at a time */
+
+short packet_lengths[] = {
+ 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+// #0x0040
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, -1, 55, 17, 3, 37, 46, -1, 23, -1, 3,108, 3, 2,
+ 3, 28, 19, 11, 3, -1, 9, 5, 54, 53, 58, 60, 41, 2, 6, 6,
+// #0x0080
+ 7, 3, 2, 2, 2, 5, 16, 12, 10, 7, 29, 23, -1, -1, -1, 0,
+ 7, 22, 28, 2, 6, 30, -1, -1, 3, -1, -1, 5, 9, 17, 17, 6,
+ 23, 6, 6, -1, -1, -1, -1, 8, 7, 6, 7, 4, 7, 0, -1, 6,
+ 8, 8, 3, 3, -1, 6, 6, -1, 7, 6, 2, 5, 6, 44, 5, 3,
+// #0x00C0
+ 7, 2, 6, 8, 6, 7, -1, -1, -1, -1, 3, 3, 6, 6, 2, 27,
+ 3, 4, 4, 2, -1, -1, 3, -1, 6, 14, 3, -1, 28, 29, -1, -1,
+ 30, 30, 26, 2, 6, 26, 3, 3, 8, 19, 5, 2, 3, 2, 2, 2,
+ 3, 2, 6, 8, 21, 8, 8, 2, 2, 26, 3, -1, 6, 27, 30, 10,
+// #0x0100
+ 2, 6, 6, 30, 79, 31, 10, 10, -1, -1, 4, 6, 6, 2, 11, -1,
+ 10, 39, 4, 10, 31, 35, 10, 18, 2, 13, 15, 20, 68, 2, 3, 16,
+ 6, 14, -1, -1, 21, 8, 8, 8, 8, 8, 2, 2, 3, 4, 2, -1,
+ 6, 86, 6, -1, -1, 7, -1, 6, 3, 16, 4, 4, 4, 6, 24, 26,
+// #0x0140
+ 22, 14, 6, 10, 23, 19, 6, 39, 8, 9, 6, 27, -1, 2, 6, 6,
+ 110, 6, -1, -1, -1, -1, -1, 6, -1, 54, 66, 54, 90, 42, 6, 42,
+ -1, -1, -1, -1, -1, 30, -1, 3, 14, 3, 30, 10, 43, 14,186,182,
+ 14, 30, 10, 3, -1, 6,106, -1, 4, 5, 4, -1, 6, 7, -1, -1,
+// #0x0180
+ 6, 3,106, 10, 10, 34, 0, 6, 8, 4, 4, 4, 29, -1, 10, 6,
+ 90, 86, 24, 6, 30,102, 9, 4, 8, 4, 14, 10, 4, 6, 2, 6,
+ 3, 3, 35, 5, 11, 26, -1, 4, 4, 6, 10, 12, 6, -1, 4, 4,
+ 11, 7, -1, 67, 12, 18,114, 6, 3, 6, 26, 26, 26, 26, 2, 3,
+// #0x01C0
+ 2, 14, 10, -1, 22, 22, 4, 2, 13, 97, 0, 9, 9, 29, 6, 28,
+ 8, 14, 10, 35, 6, 8, 4, 11, 54, 53, 60, 2, -1, 47, 33, 6,
+ 30, 8, 34, 14, 2, 6, 26, 2, 28, 81, 6, 10, 26, 2, -1, -1,
+ -1, -1, 20, 10, 32, 9, 34, 14, 2, 6, 48, 56, -1, 4, 5, 10,
+// #0x200
+ 26, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+};
+
+const unsigned int BUFFER_SIZE = 65536;
+
+int networkThread(void *data)
+{
+ Network *network = static_cast<Network*>(data);
+
+ if (!network->realConnect())
+ return -1;
+
+ network->receive();
+
+ return 0;
+}
+
+Network::Network():
+ mSocket(0),
+ mAddress(), mPort(0),
+ mInBuffer(new char[BUFFER_SIZE]),
+ mOutBuffer(new char[BUFFER_SIZE]),
+ mInSize(0), mOutSize(0),
+ mToSkip(0),
+ mState(IDLE),
+ mWorkerThread(0)
+{
+ mMutex = SDL_CreateMutex();
+}
+
+Network::~Network()
+{
+ clearHandlers();
+
+ if (mState != IDLE && mState != NET_ERROR)
+ disconnect();
+
+ SDL_DestroyMutex(mMutex);
+
+ delete[] mInBuffer;
+ delete[] mOutBuffer;
+}
+
+bool Network::connect(const std::string &address, short port)
+{
+ if (mState != IDLE && mState != NET_ERROR)
+ {
+ logger->log("Tried to connect an already connected socket!");
+ return false;
+ }
+
+ if (address.empty())
+ {
+ setError("Empty address given to Network::connect()!");
+ return false;
+ }
+
+ logger->log("Network::Connecting to %s:%i", address.c_str(), port);
+
+ mAddress = address;
+ mPort = port;
+
+ // Reset to sane values
+ mOutSize = 0;
+ mInSize = 0;
+ mToSkip = 0;
+
+ mState = CONNECTING;
+ mWorkerThread = SDL_CreateThread(networkThread, this);
+ if (!mWorkerThread)
+ {
+ setError("Unable to create network worker thread");
+ return false;
+ }
+
+ return true;
+}
+
+void Network::disconnect()
+{
+ mState = IDLE;
+
+ if (mWorkerThread)
+ {
+ SDL_WaitThread(mWorkerThread, NULL);
+ mWorkerThread = NULL;
+ }
+
+ if (mSocket)
+ {
+ SDLNet_TCP_Close(mSocket);
+ mSocket = 0;
+ }
+}
+
+void Network::registerHandler(MessageHandler *handler)
+{
+ for (const Uint16 *i = handler->handledMessages; *i; i++)
+ {
+ mMessageHandlers[*i] = handler;
+ }
+
+ handler->setNetwork(this);
+}
+
+void Network::unregisterHandler(MessageHandler *handler)
+{
+ for (const Uint16 *i = handler->handledMessages; *i; i++)
+ {
+ mMessageHandlers.erase(*i);
+ }
+
+ handler->setNetwork(0);
+}
+
+void Network::clearHandlers()
+{
+ MessageHandlerIterator i;
+ for (i = mMessageHandlers.begin(); i != mMessageHandlers.end(); i++)
+ {
+ i->second->setNetwork(0);
+ }
+ mMessageHandlers.clear();
+}
+
+void Network::dispatchMessages()
+{
+ while (messageReady())
+ {
+ MessageIn msg = getNextMessage();
+
+ MessageHandlerIterator iter = mMessageHandlers.find(msg.getId());
+
+ if (iter != mMessageHandlers.end())
+ iter->second->handleMessage(msg);
+ else
+ logger->log("Unhandled packet: %x", msg.getId());
+
+ skip(msg.getLength());
+ }
+}
+
+void Network::flush()
+{
+ if (!mOutSize || mState != CONNECTED)
+ return;
+
+ int ret;
+
+
+ SDL_mutexP(mMutex);
+ ret = SDLNet_TCP_Send(mSocket, mOutBuffer, mOutSize);
+ if (ret < (int)mOutSize)
+ {
+ setError("Error in SDLNet_TCP_Send(): " +
+ std::string(SDLNet_GetError()));
+ }
+ mOutSize = 0;
+ SDL_mutexV(mMutex);
+}
+
+void Network::skip(int len)
+{
+ SDL_mutexP(mMutex);
+ mToSkip += len;
+ if (!mInSize)
+ {
+ SDL_mutexV(mMutex);
+ return;
+ }
+
+ if (mInSize >= mToSkip)
+ {
+ mInSize -= mToSkip;
+ memmove(mInBuffer, mInBuffer + mToSkip, mInSize);
+ mToSkip = 0;
+ }
+ else
+ {
+ mToSkip -= mInSize;
+ mInSize = 0;
+ }
+ SDL_mutexV(mMutex);
+}
+
+bool Network::messageReady()
+{
+ int len = -1;
+
+ SDL_mutexP(mMutex);
+ if (mInSize >= 2)
+ {
+ len = packet_lengths[readWord(0)];
+
+ if (len == -1 && mInSize > 4)
+ len = readWord(2);
+
+ }
+
+ bool ret = (mInSize >= static_cast<unsigned int>(len));
+ SDL_mutexV(mMutex);
+
+ return ret;
+}
+
+MessageIn Network::getNextMessage()
+{
+ while (!messageReady())
+ {
+ if (mState == NET_ERROR)
+ break;
+ }
+
+ SDL_mutexP(mMutex);
+ int msgId = readWord(0);
+ int len = packet_lengths[msgId];
+
+ if (len == -1)
+ len = readWord(2);
+
+#ifdef DEBUG
+ logger->log("Received packet 0x%x of length %d", msgId, len);
+#endif
+
+ MessageIn msg(mInBuffer, len);
+ SDL_mutexV(mMutex);
+
+ return msg;
+}
+
+bool Network::realConnect()
+{
+ IPaddress ipAddress;
+
+ if (SDLNet_ResolveHost(&ipAddress, mAddress.c_str(), mPort) == -1)
+ {
+ std::string error = "Unable to resolve host \"" + mAddress + "\"";
+ setError(error);
+ logger->log("SDLNet_ResolveHost: %s", error.c_str());
+ return false;
+ }
+
+ mState = CONNECTING;
+
+ mSocket = SDLNet_TCP_Open(&ipAddress);
+ if (!mSocket)
+ {
+ logger->log("Error in SDLNet_TCP_Open(): %s", SDLNet_GetError());
+ setError(SDLNet_GetError());
+ return false;
+ }
+
+ logger->log("Network::Started session with %s:%i",
+ ipToString(ipAddress.host), ipAddress.port);
+
+ mState = CONNECTED;
+
+ return true;
+}
+
+void Network::receive()
+{
+ SDLNet_SocketSet set;
+
+ if (!(set = SDLNet_AllocSocketSet(1)))
+ {
+ setError("Error in SDLNet_AllocSocketSet(): " +
+ std::string(SDLNet_GetError()));
+ return;
+ }
+
+ if (SDLNet_TCP_AddSocket(set, mSocket) == -1)
+ {
+ setError("Error in SDLNet_AddSocket(): " +
+ std::string(SDLNet_GetError()));
+ }
+
+ while (mState == CONNECTED)
+ {
+ // TODO Try to get this to block all the time while still being able
+ // to escape the loop
+ int numReady = SDLNet_CheckSockets(set, ((Uint32)500));
+ int ret;
+ switch (numReady)
+ {
+ case -1:
+ logger->log("Error: SDLNet_CheckSockets");
+ // FALLTHROUGH
+ case 0:
+ break;
+
+ case 1:
+ // Receive data from the socket
+ SDL_mutexP(mMutex);
+ ret = SDLNet_TCP_Recv(mSocket, mInBuffer + mInSize, BUFFER_SIZE - mInSize);
+
+ if (!ret)
+ {
+ // We got disconnected
+ mState = IDLE;
+ logger->log("Disconnected.");
+ }
+ else if (ret < 0)
+ {
+ setError("Error in SDLNet_TCP_Recv(): " +
+ std::string(SDLNet_GetError()));
+ }
+ else {
+ mInSize += ret;
+ if (mToSkip)
+ {
+ if (mInSize >= mToSkip)
+ {
+ mInSize -= mToSkip;
+ memmove(mInBuffer, mInBuffer + mToSkip, mInSize);
+ mToSkip = 0;
+ }
+ else
+ {
+ mToSkip -= mInSize;
+ mInSize = 0;
+ }
+ }
+ }
+ SDL_mutexV(mMutex);
+ break;
+
+ default:
+ // more than one socket is ready..
+ // this should not happen since we only listen once socket.
+ std::stringstream errorStream;
+ errorStream << "Error in SDLNet_TCP_Recv(), " << numReady
+ << " sockets are ready: " << SDLNet_GetError();
+ setError(errorStream.str());
+ break;
+ }
+ }
+
+ if (SDLNet_TCP_DelSocket(set, mSocket) == -1)
+ {
+ logger->log("Error in SDLNet_DelSocket(): %s", SDLNet_GetError());
+ }
+
+ SDLNet_FreeSocketSet(set);
+}
+
+void Network::setError(const std::string& error)
+{
+ logger->log("Network error: %s", error.c_str());
+ mError = error;
+ mState = NET_ERROR;
+}
+
+Uint16 Network::readWord(int pos)
+{
+#if SDL_BYTEORDER == SDL_BIG_ENDIAN
+ return SDL_Swap16((*(Uint16*)(mInBuffer+(pos))));
+#else
+ return (*(Uint16*)(mInBuffer+(pos)));
+#endif
+}
diff --git a/src/net/ea/network.h b/src/net/ea/network.h
new file mode 100644
index 00000000..02fe7538
--- /dev/null
+++ b/src/net/ea/network.h
@@ -0,0 +1,118 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NETWORK_
+#define NETWORK_
+
+#include <map>
+#include <SDL_net.h>
+#include <SDL_thread.h>
+#include <string>
+
+/**
+ * Protocol version, reported to the eAthena char and mapserver who can adjust
+ * the protocol accordingly.
+ */
+#define CLIENT_PROTOCOL_VERSION 1
+
+class MessageHandler;
+class MessageIn;
+
+class Network;
+
+class Network
+{
+ public:
+ friend int networkThread(void *data);
+ friend class MessageOut;
+
+ Network();
+
+ ~Network();
+
+ bool connect(const std::string &address, short port);
+
+ void disconnect();
+
+ void registerHandler(MessageHandler *handler);
+
+ void unregisterHandler(MessageHandler *handler);
+
+ void clearHandlers();
+
+ int getState() const { return mState; }
+
+ const std::string& getError() const { return mError; }
+
+ bool isConnected() const { return mState == CONNECTED; }
+
+ int getInSize() const { return mInSize; }
+
+ void skip(int len);
+
+ bool messageReady();
+
+ MessageIn getNextMessage();
+
+ void dispatchMessages();
+
+ void flush();
+
+ // ERROR replaced by NET_ERROR because already defined in Windows
+ enum {
+ IDLE,
+ CONNECTED,
+ CONNECTING,
+ DATA,
+ NET_ERROR
+ };
+
+ protected:
+ void setError(const std::string& error);
+
+ Uint16 readWord(int pos);
+
+ bool realConnect();
+
+ void receive();
+
+ TCPsocket mSocket;
+
+ std::string mAddress;
+ short mPort;
+
+ char *mInBuffer, *mOutBuffer;
+ unsigned int mInSize, mOutSize;
+
+ unsigned int mToSkip;
+
+ int mState;
+ std::string mError;
+
+ SDL_Thread *mWorkerThread;
+ SDL_mutex *mMutex;
+
+ typedef std::map<Uint16, MessageHandler*> MessageHandlers;
+ typedef MessageHandlers::iterator MessageHandlerIterator;
+ MessageHandlers mMessageHandlers;
+};
+
+#endif
diff --git a/src/net/ea/npchandler.cpp b/src/net/ea/npchandler.cpp
new file mode 100644
index 00000000..068a3be6
--- /dev/null
+++ b/src/net/ea/npchandler.cpp
@@ -0,0 +1,111 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "../messagein.h"
+#include "npchandler.h"
+#include "protocol.h"
+
+#include "../../beingmanager.h"
+#include "../../localplayer.h"
+#include "../../npc.h"
+
+#include "../../gui/npc_text.h"
+#include "../../gui/npcintegerdialog.h"
+#include "../../gui/npclistdialog.h"
+#include "../../gui/npcstringdialog.h"
+
+extern NpcIntegerDialog *npcIntegerDialog;
+extern NpcListDialog *npcListDialog;
+extern NpcTextDialog *npcTextDialog;
+extern NpcStringDialog *npcStringDialog;
+
+NPCHandler::NPCHandler()
+{
+ static const Uint16 _messages[] = {
+ SMSG_NPC_CHOICE,
+ SMSG_NPC_MESSAGE,
+ SMSG_NPC_NEXT,
+ SMSG_NPC_CLOSE,
+ SMSG_NPC_INT_INPUT,
+ SMSG_NPC_STR_INPUT,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void NPCHandler::handleMessage(MessageIn &msg)
+{
+ int id;
+
+ switch (msg.getId())
+ {
+ case SMSG_NPC_CHOICE:
+ msg.readInt16(); // length
+ id = msg.readInt32();
+ player_node->setAction(LocalPlayer::STAND);
+ current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
+ npcListDialog->parseItems(msg.readString(msg.getLength() - 8));
+ npcListDialog->setVisible(true);
+ break;
+
+ case SMSG_NPC_MESSAGE:
+ msg.readInt16(); // length
+ id = msg.readInt32();
+ player_node->setAction(LocalPlayer::STAND);
+ current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
+ npcTextDialog->addText(msg.readString(msg.getLength() - 8));
+ npcListDialog->setVisible(false);
+ npcTextDialog->setVisible(true);
+ break;
+
+ case SMSG_NPC_CLOSE:
+ id = msg.readInt32();
+ current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
+ npcTextDialog->showCloseButton();
+ break;
+
+ case SMSG_NPC_NEXT:
+ // Next button in NPC dialog, currently unused
+ id = msg.readInt32();
+ current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
+ npcTextDialog->showNextButton();
+ break;
+
+ case SMSG_NPC_INT_INPUT:
+ // Request for an integer
+ id = msg.readInt32();
+ current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
+ npcIntegerDialog->setRange(0, 2147483647);
+ npcIntegerDialog->setDefaultValue(0);
+ npcIntegerDialog->setVisible(true);
+ npcIntegerDialog->requestFocus();
+ break;
+
+ case SMSG_NPC_STR_INPUT:
+ // Request for a string
+ id = msg.readInt32();
+ current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
+ npcStringDialog->setValue("");
+ npcStringDialog->setVisible(true);
+ npcStringDialog->requestFocus();
+ break;
+ }
+}
diff --git a/src/net/ea/npchandler.h b/src/net/ea/npchandler.h
new file mode 100644
index 00000000..49df20c3
--- /dev/null
+++ b/src/net/ea/npchandler.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_NPCHANDLER_H
+#define NET_NPCHANDLER_H
+
+#include "../messagehandler.h"
+
+class NPCHandler : public MessageHandler
+{
+ public:
+ NPCHandler();
+
+ void handleMessage(MessageIn &msg);
+};
+
+#endif
diff --git a/src/net/ea/partyhandler.cpp b/src/net/ea/partyhandler.cpp
new file mode 100644
index 00000000..d1d3b55e
--- /dev/null
+++ b/src/net/ea/partyhandler.cpp
@@ -0,0 +1,122 @@
+/*
+ * The Mana World
+ * Copyright (C) 2008 Lloyd Bryant <lloyd_bryant@netzero.net>
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <guichan/actionlistener.hpp>
+
+#include "partyhandler.h"
+#include "protocol.h"
+#include "../messagein.h"
+
+#include "../../gui/chat.h"
+#include "../../gui/confirm_dialog.h"
+
+#include "../../beingmanager.h"
+#include "../../party.h"
+
+PartyHandler::PartyHandler(Party *party) : mParty(party)
+{
+ static const Uint16 _messages[] = {
+ SMSG_PARTY_CREATE,
+ SMSG_PARTY_INFO,
+ SMSG_PARTY_INVITE,
+ SMSG_PARTY_INVITED,
+ SMSG_PARTY_SETTINGS,
+ SMSG_PARTY_MEMBER_INFO,
+ SMSG_PARTY_LEAVE,
+ SMSG_PARTY_UPDATE_HP,
+ SMSG_PARTY_UPDATE_COORDS,
+ SMSG_PARTY_MESSAGE,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void PartyHandler::handleMessage(MessageIn &msg)
+{
+ switch (msg.getId())
+ {
+ case SMSG_PARTY_CREATE:
+ mParty->createResponse(msg.readInt8());
+ break;
+ case SMSG_PARTY_INFO:
+ break;
+ case SMSG_PARTY_INVITE:
+ {
+ std::string nick = msg.readString(24);
+ int status = msg.readInt8();
+ mParty->inviteResponse(nick, status);
+ break;
+ }
+ case SMSG_PARTY_INVITED:
+ {
+ int id = msg.readInt32();
+ Being *being = beingManager->findBeing(id);
+ if (!being)
+ {
+ break;
+ }
+ std::string nick;
+ int gender = 0;
+ std::string partyName = "";
+ if (being->getType() != Being::PLAYER)
+ {
+ nick = "";
+ }
+ else
+ {
+ nick = being->getName();
+ gender = being->getGender();
+ partyName = msg.readString(24);
+ }
+ mParty->invitedAsk(nick, gender, partyName);
+ break;
+ }
+ case SMSG_PARTY_SETTINGS:
+ break;
+ case SMSG_PARTY_MEMBER_INFO:
+ break;
+ case SMSG_PARTY_LEAVE:
+ {
+ /*int id = */msg.readInt32();
+ std::string nick = msg.readString(24);
+ /*int fail = */msg.readInt8();
+ mParty->leftResponse(nick);
+ break;
+ }
+ case SMSG_PARTY_UPDATE_HP:
+ break;
+ case SMSG_PARTY_UPDATE_COORDS:
+ break;
+ case SMSG_PARTY_MESSAGE:
+ { // new block to enable local variables
+ int msgLength = msg.readInt16() - 8;
+ if (msgLength <= 0)
+ {
+ return;
+ }
+ int id = msg.readInt32();
+ Being *being = beingManager->findBeing(id);
+ std::string chatMsg = msg.readString(msgLength);
+ mParty->receiveChat(being, chatMsg);
+ }
+ break;
+ }
+}
diff --git a/src/net/ea/partyhandler.h b/src/net/ea/partyhandler.h
new file mode 100644
index 00000000..5c10eb21
--- /dev/null
+++ b/src/net/ea/partyhandler.h
@@ -0,0 +1,39 @@
+/*
+ * The Mana World
+ * Copyright (C) 2008 Lloyd Bryant <lloyd_bryant@netzero.net>
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef PARTYHANDLER_H
+#define PARTYHANDLER_H
+
+#include "../messagehandler.h"
+
+class Party;
+
+class PartyHandler : public MessageHandler
+{
+ public:
+ PartyHandler(Party *party);
+
+ void handleMessage(MessageIn &msg);
+ private:
+ Party *mParty;
+};
+
+#endif
diff --git a/src/net/ea/playerhandler.cpp b/src/net/ea/playerhandler.cpp
new file mode 100644
index 00000000..9f0acbb3
--- /dev/null
+++ b/src/net/ea/playerhandler.cpp
@@ -0,0 +1,417 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "../messagein.h"
+#include "playerhandler.h"
+#include "protocol.h"
+
+#include "../../engine.h"
+#include "../../localplayer.h"
+#include "../../log.h"
+#include "../../npc.h"
+#include "../../units.h"
+
+#include "../../gui/buy.h"
+#include "../../gui/chat.h"
+#include "../../gui/gui.h"
+#include "../../gui/npclistdialog.h"
+#include "../../gui/npc_text.h"
+#include "../../gui/ok_dialog.h"
+#include "../../gui/sell.h"
+#include "../../gui/skill.h"
+#include "../../gui/viewport.h"
+
+#include "../../utils/stringutils.h"
+#include "../../utils/gettext.h"
+
+// TODO Move somewhere else
+OkDialog *weightNotice = NULL;
+OkDialog *deathNotice = NULL;
+
+extern NpcListDialog *npcListDialog;
+extern NpcTextDialog *npcTextDialog;
+extern BuyDialog *buyDialog;
+extern SellDialog *sellDialog;
+extern Window *buySellDialog;
+
+// Max. distance we are willing to scroll after a teleport;
+// everything beyond will reset the port hard.
+static const int MAP_TELEPORT_SCROLL_DISTANCE = 8;
+
+/**
+ * Listener used for handling the overweigth message.
+ */
+// TODO Move somewhere else
+namespace {
+ struct WeightListener : public gcn::ActionListener
+ {
+ void action(const gcn::ActionEvent &event)
+ {
+ weightNotice = NULL;
+ }
+ } weightListener;
+}
+
+/**
+ * Listener used for handling death message.
+ */
+// TODO Move somewhere else
+namespace {
+ struct DeathListener : public gcn::ActionListener
+ {
+ void action(const gcn::ActionEvent &event)
+ {
+ player_node->revive();
+ deathNotice = NULL;
+ npcListDialog->setVisible(false);
+ npcTextDialog->setVisible(false);
+ buyDialog->setVisible(false);
+ sellDialog->setVisible(false);
+ buySellDialog->setVisible(false);
+ if (current_npc) current_npc->handleDeath();
+ }
+ } deathListener;
+}
+
+PlayerHandler::PlayerHandler()
+{
+ static const Uint16 _messages[] = {
+ SMSG_WALK_RESPONSE,
+ SMSG_PLAYER_WARP,
+ SMSG_PLAYER_STAT_UPDATE_1,
+ SMSG_PLAYER_STAT_UPDATE_2,
+ SMSG_PLAYER_STAT_UPDATE_3,
+ SMSG_PLAYER_STAT_UPDATE_4,
+ SMSG_PLAYER_STAT_UPDATE_5,
+ SMSG_PLAYER_STAT_UPDATE_6,
+ SMSG_PLAYER_ARROW_MESSAGE,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void PlayerHandler::handleMessage(MessageIn &msg)
+{
+ switch (msg.getId())
+ {
+ case SMSG_WALK_RESPONSE:
+ /*
+ * This client assumes that all walk messages succeed,
+ * and that the server will send a correction notice
+ * otherwise.
+ */
+ break;
+
+ case SMSG_PLAYER_WARP:
+ {
+ std::string mapPath = msg.readString(16);
+ bool nearby;
+ Uint16 x = msg.readInt16();
+ Uint16 y = msg.readInt16();
+
+ logger->log("Warping to %s (%d, %d)", mapPath.c_str(), x, y);
+
+ /*
+ * We must clear the local player's target *before* the call
+ * to changeMap, as it deletes all beings.
+ */
+ player_node->stopAttack();
+
+ nearby = (engine->getCurrentMapName() == mapPath);
+
+ // Switch the actual map, deleting the previous one if necessary
+ engine->changeMap(mapPath);
+
+ if (current_npc) current_npc->handleDeath();
+
+ float scrollOffsetX = 0.0f;
+ float scrollOffsetY = 0.0f;
+
+ /* Scroll if neccessary */
+ if (!nearby
+ || (abs(x - player_node->mX) > MAP_TELEPORT_SCROLL_DISTANCE)
+ || (abs(y - player_node->mY) > MAP_TELEPORT_SCROLL_DISTANCE))
+ {
+ scrollOffsetX = (x - player_node->mX) * 32;
+ scrollOffsetY = (y - player_node->mY) * 32;
+ }
+
+ player_node->setAction(Being::STAND);
+ player_node->mFrame = 0;
+ player_node->mX = x;
+ player_node->mY = y;
+
+ logger->log("Adjust scrolling by %d:%d",
+ (int)scrollOffsetX,
+ (int)scrollOffsetY);
+
+ viewport->scrollBy(scrollOffsetX, scrollOffsetY);
+ }
+ break;
+
+ case SMSG_PLAYER_STAT_UPDATE_1:
+ {
+ Sint16 type = msg.readInt16();
+ Uint32 value = msg.readInt32();
+
+ switch (type)
+ {
+ //case 0x0000:
+ // player_node->setWalkSpeed(msg.readInt32());
+ // break;
+ case 0x0005: player_node->setHp(value); break;
+ case 0x0006: player_node->setMaxHp(value); break;
+ case 0x0007: player_node->mMp = value; break;
+ case 0x0008: player_node->mMaxMp = value; break;
+ case 0x0009:
+ player_node->mStatsPointsToAttribute = value;
+ break;
+ case 0x000b: player_node->setLevel(value); break;
+ case 0x000c:
+ player_node->mSkillPoint = value;
+ skillDialog->update();
+ break;
+ case 0x0018:
+ if ((int) value >= player_node->getMaxWeight() / 2 &&
+ player_node->getTotalWeight() <
+ player_node->getMaxWeight() / 2)
+ {
+ weightNotice = new OkDialog(_("Message"),
+ _("You are carrying more than "
+ "half your weight. You are "
+ "unable to regain health."));
+ weightNotice->addActionListener(
+ &weightListener);
+ }
+ player_node->setTotalWeight(value);
+ break;
+ case 0x0019: player_node->setMaxWeight(value); break;
+ case 0x0029: player_node->ATK = value; break;
+ case 0x002b: player_node->MATK = value; break;
+ case 0x002d: player_node->DEF = value; break;
+ case 0x002e: player_node->DEF_BONUS = value; break;
+ case 0x002f: player_node->MDEF = value; break;
+ case 0x0031: player_node->HIT = value; break;
+ case 0x0032: player_node->FLEE = value; break;
+ case 0x0035: player_node->mAttackSpeed = value; break;
+ case 0x0037: player_node->mJobLevel = value; break;
+ }
+
+ if (player_node->getHp() == 0 && !deathNotice)
+ {
+ static char const *const deadMsg[] =
+ {
+ _("You are dead."),
+ _("We regret to inform you that your character was "
+ "killed in battle."),
+ _("You are not that alive anymore."),
+ _("The cold hands of the grim reaper are grabbing for "
+ "your soul."),
+ _("Game Over!"),
+ _("Insert coin to continue"),
+ _("No, kids. Your character did not really die. It... "
+ "err... went to a better place."),
+ _("Your plan of breaking your enemies weapon by "
+ "bashing it with your throat failed."),
+ _("I guess this did not run too well."),
+ // NetHack reference:
+ _("Do you want your possessions identified?"),
+ // Secret of Mana reference:
+ _("Sadly, no trace of you was ever found..."),
+ // Final Fantasy VI reference:
+ _("Annihilated."),
+ // Earthbound reference:
+ _("Looks like you got your head handed to you."),
+ // Leisure Suit Larry 1 reference:
+ _("You screwed up again, dump your body down the tubes "
+ "and get you another one."),
+ // Monty Python references (Dead Parrot sketch mostly):
+ _("You're not dead yet. You're just resting."),
+ _("You are no more."),
+ _("You have ceased to be."),
+ _("You've expired and gone to meet your maker."),
+ _("You're a stiff."),
+ _("Bereft of life, you rest in peace."),
+ _("If you weren't so animated, you'd be pushing up the "
+ "daisies."),
+ _("Your metabolic processes are now history."),
+ _("You're off the twig."),
+ _("You've kicked the bucket."),
+ _("You've shuffled off your mortal coil, run down the "
+ "curtain and joined the bleedin' choir invisibile."),
+ _("You are an ex-player."),
+ _("You're pining for the fjords.")
+ };
+ std::string message(deadMsg[rand()%27]);
+
+ deathNotice = new OkDialog(_("Message"), message);
+ deathNotice->addActionListener(&deathListener);
+ player_node->setAction(Being::DEAD);
+ }
+ }
+ break;
+
+ case SMSG_PLAYER_STAT_UPDATE_2:
+ switch (msg.readInt16()) {
+ case 0x0001:
+ player_node->setXp(msg.readInt32());
+ break;
+ case 0x0002:
+ player_node->mJobXp = msg.readInt32();
+ break;
+ case 0x0014: {
+ int curGp = player_node->getMoney();
+ player_node->setMoney(msg.readInt32());
+ if (player_node->getMoney() > curGp)
+ chatWindow->chatLog(_("You picked up ") +
+ Units::formatCurrency(player_node->getMoney()
+ - curGp), BY_SERVER);
+ }
+ break;
+ case 0x0016:
+ player_node->mXpForNextLevel = msg.readInt32();
+ break;
+ case 0x0017:
+ player_node->mJobXpForNextLevel = msg.readInt32();
+ break;
+ }
+ break;
+
+ case SMSG_PLAYER_STAT_UPDATE_3:
+ {
+ Sint32 type = msg.readInt32();
+ Sint32 base = msg.readInt32();
+ Sint32 bonus = msg.readInt32();
+ Sint32 total = base + bonus;
+
+ switch (type) {
+ case 0x000d: player_node->mAttr[LocalPlayer::STR] = total;
+ break;
+ case 0x000e: player_node->mAttr[LocalPlayer::AGI] = total;
+ break;
+ case 0x000f: player_node->mAttr[LocalPlayer::VIT] = total;
+ break;
+ case 0x0010: player_node->mAttr[LocalPlayer::INT] = total;
+ break;
+ case 0x0011: player_node->mAttr[LocalPlayer::DEX] = total;
+ break;
+ case 0x0012: player_node->mAttr[LocalPlayer::LUK] = total;
+ break;
+ }
+ }
+ break;
+
+ case SMSG_PLAYER_STAT_UPDATE_4:
+ {
+ Sint16 type = msg.readInt16();
+ Sint8 fail = msg.readInt8();
+ Sint8 value = msg.readInt8();
+
+ if (fail != 1)
+ break;
+
+ switch (type) {
+ case 0x000d: player_node->mAttr[LocalPlayer::STR] = value;
+ break;
+ case 0x000e: player_node->mAttr[LocalPlayer::AGI] = value;
+ break;
+ case 0x000f: player_node->mAttr[LocalPlayer::VIT] = value;
+ break;
+ case 0x0010: player_node->mAttr[LocalPlayer::INT] = value;
+ break;
+ case 0x0011: player_node->mAttr[LocalPlayer::DEX] = value;
+ break;
+ case 0x0012: player_node->mAttr[LocalPlayer::LUK] = value;
+ break;
+ }
+ }
+ break;
+
+ // Updates stats and status points
+ case SMSG_PLAYER_STAT_UPDATE_5:
+ player_node->mStatsPointsToAttribute = msg.readInt16();
+ player_node->mAttr[LocalPlayer::STR] = msg.readInt8();
+ player_node->mAttrUp[LocalPlayer::STR] = msg.readInt8();
+ player_node->mAttr[LocalPlayer::AGI] = msg.readInt8();
+ player_node->mAttrUp[LocalPlayer::AGI] = msg.readInt8();
+ player_node->mAttr[LocalPlayer::VIT] = msg.readInt8();
+ player_node->mAttrUp[LocalPlayer::VIT] = msg.readInt8();
+ player_node->mAttr[LocalPlayer::INT] = msg.readInt8();
+ player_node->mAttrUp[LocalPlayer::INT] = msg.readInt8();
+ player_node->mAttr[LocalPlayer::DEX] = msg.readInt8();
+ player_node->mAttrUp[LocalPlayer::DEX] = msg.readInt8();
+ player_node->mAttr[LocalPlayer::LUK] = msg.readInt8();
+ player_node->mAttrUp[LocalPlayer::LUK] = msg.readInt8();
+ player_node->ATK = msg.readInt16(); // ATK
+ player_node->ATK_BONUS = msg.readInt16(); // ATK bonus
+ player_node->MATK = msg.readInt16(); // MATK max
+ player_node->MATK_BONUS = msg.readInt16(); // MATK min
+ player_node->DEF = msg.readInt16(); // DEF
+ player_node->DEF_BONUS = msg.readInt16(); // DEF bonus
+ player_node->MDEF = msg.readInt16(); // MDEF
+ player_node->MDEF_BONUS = msg.readInt16(); // MDEF bonus
+ player_node->HIT = msg.readInt16(); // HIT
+ player_node->FLEE = msg.readInt16(); // FLEE
+ player_node->FLEE_BONUS = msg.readInt16(); // FLEE bonus
+ msg.readInt16(); // critical
+ msg.readInt16(); // unknown
+ break;
+
+ case SMSG_PLAYER_STAT_UPDATE_6:
+ switch (msg.readInt16()) {
+ case 0x0020:
+ player_node->mAttrUp[LocalPlayer::STR] = msg.readInt8();
+ break;
+ case 0x0021:
+ player_node->mAttrUp[LocalPlayer::AGI] = msg.readInt8();
+ break;
+ case 0x0022:
+ player_node->mAttrUp[LocalPlayer::VIT] = msg.readInt8();
+ break;
+ case 0x0023:
+ player_node->mAttrUp[LocalPlayer::INT] = msg.readInt8();
+ break;
+ case 0x0024:
+ player_node->mAttrUp[LocalPlayer::DEX] = msg.readInt8();
+ break;
+ case 0x0025:
+ player_node->mAttrUp[LocalPlayer::LUK] = msg.readInt8();
+ break;
+ }
+ break;
+
+ case SMSG_PLAYER_ARROW_MESSAGE:
+ {
+ Sint16 type = msg.readInt16();
+
+ switch (type) {
+ case 0:
+ chatWindow->chatLog(_("Equip arrows first"),
+ BY_SERVER);
+ break;
+ default:
+ logger->log("0x013b: Unhandled message %i", type);
+ break;
+ }
+ }
+ break;
+ }
+}
diff --git a/src/net/ea/playerhandler.h b/src/net/ea/playerhandler.h
new file mode 100644
index 00000000..f3352289
--- /dev/null
+++ b/src/net/ea/playerhandler.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_PLAYERHANDLER_H
+#define NET_PLAYERHANDLER_H
+
+#include "../messagehandler.h"
+
+class PlayerHandler : public MessageHandler
+{
+ public:
+ PlayerHandler();
+
+ void handleMessage(MessageIn &msg);
+};
+
+#endif
diff --git a/src/net/protocol.cpp b/src/net/ea/protocol.cpp
index 69d69901..69d69901 100644
--- a/src/net/protocol.cpp
+++ b/src/net/ea/protocol.cpp
diff --git a/src/net/ea/protocol.h b/src/net/ea/protocol.h
new file mode 100644
index 00000000..55c0d8b6
--- /dev/null
+++ b/src/net/ea/protocol.h
@@ -0,0 +1,162 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef PROTOCOL_H
+#define PROTOCOL_H
+
+/*********************************
+ * Packets from server to client *
+ *********************************/
+#define SMSG_LOGIN_SUCCESS 0x0073 /**< Contains starting location */
+#define SMSG_SERVER_PING 0x007f /**< Contains server tick */
+#define SMSG_CONNECTION_PROBLEM 0x0081
+#define SMSG_UPDATE_HOST 0x0063 /**< Custom update host packet */
+#define SMSG_PLAYER_UPDATE_1 0x01d8
+#define SMSG_PLAYER_UPDATE_2 0x01d9
+#define SMSG_PLAYER_MOVE 0x01da /**< A nearby player moves */
+#define SMSG_PLAYER_STOP 0x0088 /**< Stop walking, set position */
+#define SMSG_PLAYER_MOVE_TO_ATTACK 0x0139 /**< Move to within attack range */
+#define SMSG_PLAYER_STAT_UPDATE_1 0x00b0
+#define SMSG_PLAYER_STAT_UPDATE_2 0x00b1
+#define SMSG_PLAYER_STAT_UPDATE_3 0x0141
+#define SMSG_PLAYER_STAT_UPDATE_4 0x00bc
+#define SMSG_PLAYER_STAT_UPDATE_5 0x00bd
+#define SMSG_PLAYER_STAT_UPDATE_6 0x00be
+#define SMSG_WHO_ANSWER 0x00c2
+#define SMSG_PLAYER_WARP 0x0091 /**< Warp player to map/location */
+#define SMSG_PLAYER_INVENTORY 0x01ee
+#define SMSG_PLAYER_INVENTORY_ADD 0x00a0
+#define SMSG_PLAYER_INVENTORY_REMOVE 0x00af
+#define SMSG_PLAYER_INVENTORY_USE 0x01c8
+#define SMSG_PLAYER_EQUIPMENT 0x00a4
+#define SMSG_PLAYER_EQUIP 0x00aa
+#define SMSG_PLAYER_UNEQUIP 0x00ac
+#define SMSG_PLAYER_ATTACK_RANGE 0x013a
+#define SMSG_PLAYER_ARROW_EQUIP 0x013c
+#define SMSG_PLAYER_ARROW_MESSAGE 0x013b
+#define SMSG_PLAYER_SKILLS 0x010f
+#define SMSG_SKILL_FAILED 0x0110
+#define SMSG_ITEM_USE_RESPONSE 0x00a8
+#define SMSG_ITEM_VISIBLE 0x009d /**< An item is on the floor */
+#define SMSG_ITEM_DROPPED 0x009e /**< An item is dropped */
+#define SMSG_ITEM_REMOVE 0x00a1 /**< An item disappers */
+#define SMSG_BEING_VISIBLE 0x0078
+#define SMSG_BEING_MOVE 0x007b /**< A nearby monster moves */
+#define SMSG_BEING_SPAWN 0x007c /**< A being spawns nearby */
+#define SMSG_BEING_MOVE2 0x0086 /**< New eAthena being moves */
+#define SMSG_BEING_REMOVE 0x0080
+#define SMSG_BEING_CHANGE_LOOKS 0x00c3
+#define SMSG_BEING_CHANGE_LOOKS2 0x01d7 /**< Same as 0x00c3, but 16 bit ID */
+#define SMSG_BEING_SELFEFFECT 0x019b
+#define SMSG_BEING_EMOTION 0x00c0
+#define SMSG_BEING_ACTION 0x008a /**< Attack, sit, stand up, ... */
+#define SMSG_BEING_CHAT 0x008d /**< A being talks */
+#define SMSG_BEING_NAME_RESPONSE 0x0095 /**< Has to be requested */
+
+#define SMSG_NPC_MESSAGE 0x00b4
+#define SMSG_NPC_NEXT 0x00b5
+#define SMSG_NPC_CLOSE 0x00b6
+#define SMSG_NPC_CHOICE 0x00b7 /**< Display a choice */
+#define SMSG_NPC_BUY_SELL_CHOICE 0x00c4
+#define SMSG_NPC_BUY 0x00c6
+#define SMSG_NPC_SELL 0x00c7
+#define SMSG_NPC_BUY_RESPONSE 0x00ca
+#define SMSG_NPC_SELL_RESPONSE 0x00cb
+#define SMSG_NPC_INT_INPUT 0x0142 /**< Integer input */
+#define SMSG_NPC_STR_INPUT 0x01d4 /**< String input */
+#define SMSG_PLAYER_CHAT 0x008e /**< Player talks */
+#define SMSG_WHISPER 0x0097 /**< Whisper Recieved */
+#define SMSG_WHISPER_RESPONSE 0x0098
+#define SMSG_GM_CHAT 0x009a /**< GM announce */
+#define SMSG_WALK_RESPONSE 0x0087
+
+#define SMSG_TRADE_REQUEST 0x00e5 /**< Receiving a request to trade */
+#define SMSG_TRADE_RESPONSE 0x00e7
+#define SMSG_TRADE_ITEM_ADD 0x00e9
+#define SMSG_TRADE_ITEM_ADD_RESPONSE 0x01b1 /**< Not standard eAthena! */
+#define SMSG_TRADE_OK 0x00ec
+#define SMSG_TRADE_CANCEL 0x00ee
+#define SMSG_TRADE_COMPLETE 0x00f0
+
+#define SMSG_PARTY_CREATE 0x00fa
+#define SMSG_PARTY_INFO 0x00fb
+#define SMSG_PARTY_INVITE 0x00fd
+#define SMSG_PARTY_INVITED 0x00fe
+#define SMSG_PARTY_SETTINGS 0x0102
+#define SMSG_PARTY_MEMBER_INFO 0x0104
+#define SMSG_PARTY_LEAVE 0x0105
+#define SMSG_PARTY_UPDATE_HP 0x0106
+#define SMSG_PARTY_UPDATE_COORDS 0x0107
+#define SMSG_PARTY_MESSAGE 0x0109
+
+#define SMSG_PLAYER_STORAGE_ITEMS 0x01f0 /**< Item list for storage */
+#define SMSG_PLAYER_STORAGE_EQUIP 0x00a6 /**< Equipment list for storage */
+#define SMSG_PLAYER_STORAGE_STATUS 0x00f2 /**< Slots used and total slots */
+#define SMSG_PLAYER_STORAGE_ADD 0x00f4 /**< Add item/equip to storage */
+#define SMSG_PLAYER_STORAGE_REMOVE 0x00f6 /**< Remove item/equip from storage */
+#define SMSG_PLAYER_STORAGE_CLOSE 0x00f8 /**< Storage access closed */
+
+/**********************************
+ * Packets from client to server *
+ **********************************/
+#define CMSG_CLIENT_PING 0x007e /**< Send to server with tick */
+#define CMSG_TRADE_RESPONSE 0x00e6
+#define CMSG_ITEM_PICKUP 0x009f
+#define CMSG_MAP_LOADED 0x007d
+#define CMSG_NPC_BUY_REQUEST 0x00c8
+#define CMSG_NPC_BUY_SELL_REQUEST 0x00c5
+#define CMSG_CHAT_MESSAGE 0x008c
+#define CMSG_CHAT_WHISPER 0x0096
+#define CMSG_CHAT_ANNOUNCE 0x0099
+#define CMSG_CHAT_WHO 0x00c1
+#define CMSG_NPC_LIST_CHOICE 0x00b8
+#define CMSG_NPC_NEXT_REQUEST 0x00b9
+#define CMSG_NPC_SELL_REQUEST 0x00c9
+#define CMSG_NPC_INT_RESPONSE 0x0143
+#define CMSG_NPC_STR_RESPONSE 0x01d5
+#define CMSG_SKILL_LEVELUP_REQUEST 0x0112
+#define CMSG_STAT_UPDATE_REQUEST 0x00bb
+#define CMSG_TRADE_ITEM_ADD_REQUEST 0x00e8
+#define CMSG_TRADE_CANCEL_REQUEST 0x00ed
+#define CMSG_TRADE_ADD_COMPLETE 0x00eb
+#define CMSG_TRADE_OK 0x00ef
+#define CMSG_NPC_TALK 0x0090
+#define CMSG_TRADE_REQUEST 0x00e4
+#define CMSG_PLAYER_INVENTORY_USE 0x00a7
+#define CMSG_PLAYER_INVENTORY_DROP 0x00a2
+#define CMSG_PLAYER_EQUIP 0x00a9
+#define CMSG_PLAYER_UNEQUIP 0x00ab
+
+#define CMSG_PARTY_CREATE 0x00f9
+#define CMSG_PARTY_INVITE 0x00fc
+#define CMSG_PARTY_INVITED 0x00ff
+#define CMSG_PARTY_LEAVE 0x0100 /** Undocumented */
+#define CMSG_PARTY_SETTINGS 0x0101
+#define CMSG_PARTY_MESSAGE 0x0108
+
+#define CMSG_MOVE_TO_STORAGE 0x00f3 /** Move item to storage */
+#define CSMG_MOVE_FROM_STORAGE 0x00f5 /** Remove item from storage */
+#define CMSG_CLOSE_STORAGE 0x00f7 /** Request storage close */
+
+/** Encodes coords and direction in 3 bytes data */
+void set_coordinates(char *data, unsigned short x, unsigned short y, unsigned char direction);
+
+#endif
diff --git a/src/net/skillhandler.cpp b/src/net/ea/skillhandler.cpp
index e2185524..6e766008 100644
--- a/src/net/skillhandler.cpp
+++ b/src/net/ea/skillhandler.cpp
@@ -19,14 +19,14 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include "messagein.h"
+#include "../messagein.h"
#include "protocol.h"
#include "skillhandler.h"
-#include "../log.h"
+#include "../../log.h"
-#include "../gui/chat.h"
-#include "../gui/skill.h"
+#include "../../gui/chat.h"
+#include "../../gui/skill.h"
SkillHandler::SkillHandler()
{
@@ -38,27 +38,27 @@ SkillHandler::SkillHandler()
handledMessages = _messages;
}
-void SkillHandler::handleMessage(MessageIn *msg)
+void SkillHandler::handleMessage(MessageIn &msg)
{
int skillCount;
- switch (msg->getId())
+ switch (msg.getId())
{
case SMSG_PLAYER_SKILLS:
- msg->readInt16(); // length
- skillCount = (msg->getLength() - 4) / 37;
+ msg.readInt16(); // length
+ skillCount = (msg.getLength() - 4) / 37;
skillDialog->cleanList();
for (int k = 0; k < skillCount; k++)
{
- Sint16 skillId = msg->readInt16();
- msg->readInt16(); // target type
- msg->readInt16(); // unknown
- Sint16 level = msg->readInt16();
- Sint16 sp = msg->readInt16();
- msg->readInt16(); // range
- std::string skillName = msg->readString(24);
- Sint8 up = msg->readInt8();
+ Sint16 skillId = msg.readInt16();
+ msg.readInt16(); // target type
+ msg.readInt16(); // unknown
+ Sint16 level = msg.readInt16();
+ Sint16 sp = msg.readInt16();
+ msg.readInt16(); // range
+ std::string skillName = msg.readString(24);
+ Sint8 up = msg.readInt8();
if (level != 0 || up != 0)
{
@@ -77,11 +77,11 @@ void SkillHandler::handleMessage(MessageIn *msg)
// Action failed (ex. sit because you have not reached the
// right level)
CHATSKILL action;
- action.skill = msg->readInt16();
- action.bskill = msg->readInt16();
- action.unused = msg->readInt16(); // unknown
- action.success = msg->readInt8();
- action.reason = msg->readInt8();
+ action.skill = msg.readInt16();
+ action.bskill = msg.readInt16();
+ action.unused = msg.readInt16(); // unknown
+ action.success = msg.readInt8();
+ action.reason = msg.readInt8();
if (action.success != SKILL_FAILED &&
action.bskill == BSKILL_EMOTE)
{
diff --git a/src/net/skillhandler.h b/src/net/ea/skillhandler.h
index 2b55605d..57d68f47 100644
--- a/src/net/skillhandler.h
+++ b/src/net/ea/skillhandler.h
@@ -22,14 +22,14 @@
#ifndef NET_SKILLHANDLER_H
#define NET_SKILLHANDLER_H
-#include "messagehandler.h"
+#include "../messagehandler.h"
class SkillHandler : public MessageHandler
{
public:
SkillHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/ea/tradehandler.cpp b/src/net/ea/tradehandler.cpp
new file mode 100644
index 00000000..6c953a11
--- /dev/null
+++ b/src/net/ea/tradehandler.cpp
@@ -0,0 +1,220 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "../messagein.h"
+#include "protocol.h"
+#include "tradehandler.h"
+
+#include "../../inventory.h"
+#include "../../item.h"
+#include "../../localplayer.h"
+#include "../../player_relations.h"
+
+#include "../../gui/chat.h"
+#include "../../gui/confirm_dialog.h"
+#include "../../gui/trade.h"
+
+#include "../../utils/gettext.h"
+
+std::string tradePartnerName;
+
+/**
+ * Listener for request trade dialogs
+ */
+namespace {
+ struct RequestTradeListener : public gcn::ActionListener
+ {
+ void action(const gcn::ActionEvent &event)
+ {
+ player_node->tradeReply(event.getId() == "yes");
+ };
+ } listener;
+}
+
+TradeHandler::TradeHandler()
+{
+ static const Uint16 _messages[] = {
+ SMSG_TRADE_REQUEST,
+ SMSG_TRADE_RESPONSE,
+ SMSG_TRADE_ITEM_ADD,
+ SMSG_TRADE_ITEM_ADD_RESPONSE,
+ SMSG_TRADE_OK,
+ SMSG_TRADE_CANCEL,
+ SMSG_TRADE_COMPLETE,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+
+void TradeHandler::handleMessage(MessageIn &msg)
+{
+ switch (msg.getId())
+ {
+ case SMSG_TRADE_REQUEST:
+ // If a trade window or request window is already open, send a
+ // trade cancel to any other trade request.
+ //
+ // Note that it would be nice if the server would prevent this
+ // situation, and that the requesting player would get a
+ // special message about the player being occupied.
+ tradePartnerName = msg.readString(24);
+
+ if (player_relations.hasPermission(tradePartnerName, PlayerRelation::TRADE))
+ {
+ if (!player_node->tradeRequestOk())
+ {
+ player_node->tradeReply(false);
+ break;
+ }
+
+ player_node->setTrading(true);
+ ConfirmDialog *dlg;
+ dlg = new ConfirmDialog(_("Request for trade"),
+ tradePartnerName +
+ _(" wants to trade with you, do you accept?"));
+ dlg->addActionListener(&listener);
+ }
+ else
+ {
+ player_node->tradeReply(false);
+ break;
+ }
+ break;
+
+ case SMSG_TRADE_RESPONSE:
+ switch (msg.readInt8())
+ {
+ case 0: // Too far away
+ chatWindow->chatLog(_("Trading isn't possible. Trade partner is too far away."),
+ BY_SERVER);
+ break;
+ case 1: // Character doesn't exist
+ chatWindow->chatLog(_("Trading isn't possible. Character doesn't exist."),
+ BY_SERVER);
+ break;
+ case 2: // Invite request check failed...
+ chatWindow->chatLog(_("Trade cancelled due to an unknown reason."),
+ BY_SERVER);
+ break;
+ case 3: // Trade accepted
+ tradeWindow->reset();
+ tradeWindow->setCaption(
+ _("Trade: You and ") + tradePartnerName);
+ tradeWindow->setVisible(true);
+ break;
+ case 4: // Trade cancelled
+ if (player_relations.hasPermission(tradePartnerName,
+ PlayerRelation::SPEECH_LOG))
+ chatWindow->chatLog(_("Trade with ") + tradePartnerName +
+ _(" cancelled"), BY_SERVER);
+ // otherwise ignore silently
+
+ tradeWindow->setVisible(false);
+ player_node->setTrading(false);
+ break;
+ default: // Shouldn't happen as well, but to be sure
+ chatWindow->chatLog(_("Unhandled trade cancel packet"),
+ BY_SERVER);
+ break;
+ }
+ break;
+
+ case SMSG_TRADE_ITEM_ADD:
+ {
+ Sint32 amount = msg.readInt32();
+ Sint16 type = msg.readInt16();
+ msg.readInt8(); // identified flag
+ msg.readInt8(); // attribute
+ msg.readInt8(); // refine
+ msg.skip(8); // card (4 shorts)
+
+ // TODO: handle also identified, etc
+ if (type == 0) {
+ tradeWindow->setMoney(amount);
+ } else {
+ tradeWindow->addItem(type, false, amount, false);
+ }
+ }
+ break;
+
+ case SMSG_TRADE_ITEM_ADD_RESPONSE:
+ // Trade: New Item add response (was 0x00ea, now 01b1)
+ {
+ const int index = msg.readInt16();
+ Item *item = player_node->getInventory()->getItem(index);
+ if (!item)
+ {
+ tradeWindow->receivedOk(true);
+ return;
+ }
+ Sint16 quantity = msg.readInt16();
+
+ switch (msg.readInt8())
+ {
+ case 0:
+ // Successfully added item
+ if (item->isEquipment() && item->isEquipped())
+ {
+ player_node->unequipItem(item);
+ }
+ tradeWindow->addItem(item->getId(), true, quantity,
+ item->isEquipment());
+ item->increaseQuantity(-quantity);
+ break;
+ case 1:
+ // Add item failed - player overweighted
+ chatWindow->chatLog(_("Failed adding item. Trade partner is over weighted."),
+ BY_SERVER);
+ break;
+ case 2:
+ // Add item failed - player has no free slot
+ chatWindow->chatLog(_("Failed adding item. Trade partner has no free slot."),
+ BY_SERVER);
+ break;
+ default:
+ chatWindow->chatLog(_("Failed adding item for unknown reason."),
+ BY_SERVER);
+ break;
+ }
+ }
+ break;
+
+ case SMSG_TRADE_OK:
+ // 0 means ok from myself, 1 means ok from other;
+ tradeWindow->receivedOk(msg.readInt8() == 0);
+ break;
+
+ case SMSG_TRADE_CANCEL:
+ chatWindow->chatLog(_("Trade canceled."), BY_SERVER);
+ tradeWindow->setVisible(false);
+ tradeWindow->reset();
+ player_node->setTrading(false);
+ break;
+
+ case SMSG_TRADE_COMPLETE:
+ chatWindow->chatLog(_("Trade completed."), BY_SERVER);
+ tradeWindow->setVisible(false);
+ tradeWindow->reset();
+ player_node->setTrading(false);
+ break;
+ }
+}
diff --git a/src/net/ea/tradehandler.h b/src/net/ea/tradehandler.h
new file mode 100644
index 00000000..04335069
--- /dev/null
+++ b/src/net/ea/tradehandler.h
@@ -0,0 +1,37 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef NET_TRADEHANDLER_H
+#define NET_TRADEHANDLER_H
+
+#include "../messagehandler.h"
+
+class Network;
+
+class TradeHandler : public MessageHandler
+{
+ public:
+ TradeHandler();
+
+ void handleMessage(MessageIn &msg);
+};
+
+#endif
diff --git a/src/net/effecthandler.cpp b/src/net/effecthandler.cpp
new file mode 100644
index 00000000..8411b9e7
--- /dev/null
+++ b/src/net/effecthandler.cpp
@@ -0,0 +1,58 @@
+/*
+ * The Mana World
+ * Copyright (C) 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "effecthandler.h"
+
+#include "messagein.h"
+#include "protocol.h"
+
+#include "../effectmanager.h"
+
+
+EffectHandler::EffectHandler()
+{
+ static const Uint16 _messages[] = {
+ GPMSG_CREATE_EFFECT,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void EffectHandler::handleMessage(MessageIn &msg)
+{
+ switch (msg.getId())
+ {
+ case GPMSG_CREATE_EFFECT:
+ handleCreateEffects(msg);
+ break;
+ default:
+ break;
+ }
+}
+
+void EffectHandler::handleCreateEffects(MessageIn &msg)
+{
+ int id = msg.readInt16();
+ Uint16 x = msg.readInt16();
+ Uint16 y = msg.readInt16();
+ effectManager->trigger(id, x, y);
+}
+
diff --git a/src/net/effecthandler.h b/src/net/effecthandler.h
new file mode 100644
index 00000000..283c7c10
--- /dev/null
+++ b/src/net/effecthandler.h
@@ -0,0 +1,38 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_EFFECTSHANDLER_H
+#define _TMW_NET_EFFECTSHANDLER_H
+
+#include "messagehandler.h"
+
+class EffectHandler : public MessageHandler
+{
+ public:
+ EffectHandler();
+
+ void handleMessage(MessageIn &msg);
+
+ private:
+ void handleCreateEffects(MessageIn &msg);
+};
+
+#endif
diff --git a/src/net/gameserver/gameserver.cpp b/src/net/gameserver/gameserver.cpp
new file mode 100644
index 00000000..1bdaef26
--- /dev/null
+++ b/src/net/gameserver/gameserver.cpp
@@ -0,0 +1,49 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "gameserver.h"
+
+#include "internal.h"
+
+#include "../connection.h"
+#include "../messageout.h"
+#include "../protocol.h"
+
+void Net::GameServer::connect(Net::Connection *connection,
+ const std::string &token)
+{
+ Net::GameServer::connection = connection;
+
+ MessageOut msg(PGMSG_CONNECT);
+
+ msg.writeString(token, 32);
+
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::logout(bool reconnectAccount)
+{
+ MessageOut msg(PGMSG_DISCONNECT);
+
+ msg.writeInt8((unsigned char) reconnectAccount);
+
+ Net::GameServer::connection->send(msg);
+}
diff --git a/src/net/gameserver/gameserver.h b/src/net/gameserver/gameserver.h
new file mode 100644
index 00000000..5ea2c718
--- /dev/null
+++ b/src/net/gameserver/gameserver.h
@@ -0,0 +1,39 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_GAMESERVER_GAMESERVER_H
+#define _TMW_NET_GAMESERVER_GAMESERVER_H
+
+#include <iosfwd>
+
+namespace Net
+{
+ class Connection;
+
+ namespace GameServer
+ {
+ void connect(Net::Connection *connection, const std::string &token);
+
+ void logout(bool reconnectAccount);
+ }
+}
+
+#endif
diff --git a/src/net/gameserver/internal.cpp b/src/net/gameserver/internal.cpp
new file mode 100644
index 00000000..6b6ba081
--- /dev/null
+++ b/src/net/gameserver/internal.cpp
@@ -0,0 +1,32 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "internal.h"
+
+namespace Net
+{
+ class Connection;
+
+ namespace GameServer
+ {
+ Connection *connection = 0;
+ }
+}
diff --git a/src/net/gameserver/internal.h b/src/net/gameserver/internal.h
new file mode 100644
index 00000000..df9787fe
--- /dev/null
+++ b/src/net/gameserver/internal.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_GAMESERVER_INTERNAL_H
+#define _TMW_NET_GAMESERVER_INTERNAL_H
+
+namespace Net
+{
+ class Connection;
+
+ namespace GameServer
+ {
+ extern Connection *connection;
+ }
+}
+
+#endif
diff --git a/src/net/gameserver/player.cpp b/src/net/gameserver/player.cpp
new file mode 100644
index 00000000..95c13ec2
--- /dev/null
+++ b/src/net/gameserver/player.cpp
@@ -0,0 +1,202 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "player.h"
+
+#include "internal.h"
+
+#include "../connection.h"
+#include "../messageout.h"
+#include "../protocol.h"
+
+void RespawnRequestListener::action(const gcn::ActionEvent &event)
+{
+ Net::GameServer::Player::respawn();
+}
+
+void Net::GameServer::Player::say(const std::string &text)
+{
+ MessageOut msg(PGMSG_SAY);
+ msg.writeString(text);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::walk(int x, int y)
+{
+ MessageOut msg(PGMSG_WALK);
+ msg.writeInt16(x);
+ msg.writeInt16(y);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::pickUp(int x, int y)
+{
+ MessageOut msg(PGMSG_PICKUP);
+ msg.writeInt16(x);
+ msg.writeInt16(y);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::moveItem(int oldSlot, int newSlot, int amount)
+{
+ MessageOut msg(PGMSG_MOVE_ITEM);
+ msg.writeInt8(oldSlot);
+ msg.writeInt8(newSlot);
+ msg.writeInt8(amount);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::drop(int slot, int amount)
+{
+ MessageOut msg(PGMSG_DROP);
+ msg.writeInt8(slot);
+ msg.writeInt8(amount);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::equip(int slot)
+{
+ MessageOut msg(PGMSG_EQUIP);
+ msg.writeInt8(slot);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::unequip(int slot)
+{
+ MessageOut msg(PGMSG_UNEQUIP);
+ msg.writeInt8(slot);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::useItem(int slot)
+{
+ MessageOut msg(PGMSG_USE_ITEM);
+ msg.writeInt8(slot);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::attack(int direction)
+{
+ MessageOut msg(PGMSG_ATTACK);
+ msg.writeInt8(direction);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::useSpecial(int special)
+{
+ MessageOut msg(PGMSG_USE_SPECIAL);
+ msg.writeInt8(special);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::changeAction(Being::Action action)
+{
+ MessageOut msg(PGMSG_ACTION_CHANGE);
+ msg.writeInt8(action);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::talkToNPC(int id, bool restart)
+{
+ MessageOut msg(restart ? PGMSG_NPC_TALK : PGMSG_NPC_TALK_NEXT);
+ msg.writeInt16(id);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::selectFromNPC(int id, int choice)
+{
+ MessageOut msg(PGMSG_NPC_SELECT);
+ msg.writeInt16(id);
+ msg.writeInt8(choice);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::requestTrade(int id)
+{
+ MessageOut msg(PGMSG_TRADE_REQUEST);
+ msg.writeInt16(id);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::acceptTrade(bool accept)
+{
+ MessageOut msg(accept ? PGMSG_TRADE_ACCEPT : PGMSG_TRADE_CANCEL);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::tradeItem(int slot, int amount)
+{
+ MessageOut msg(PGMSG_TRADE_ADD_ITEM);
+ msg.writeInt8(slot);
+ msg.writeInt8(amount);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::tradeMoney(int amount)
+{
+ MessageOut msg(PGMSG_TRADE_SET_MONEY);
+ msg.writeInt32(amount);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::tradeWithNPC(int item, int amount)
+{
+ MessageOut msg(PGMSG_NPC_BUYSELL);
+ msg.writeInt16(item);
+ msg.writeInt16(amount);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::sendLetter(const std::string &player,
+ const std::string &text)
+{
+ MessageOut msg(PGMSG_NPC_POST_SEND);
+ msg.writeString(player);
+ msg.writeString(text);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::raiseAttribute(int attribute)
+{
+ MessageOut msg(PGMSG_RAISE_ATTRIBUTE);
+ msg.writeInt8(attribute);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::lowerAttribute(int attribute)
+{
+ MessageOut msg(PGMSG_LOWER_ATTRIBUTE);
+ msg.writeInt8(attribute);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::respawn()
+{
+ MessageOut msg(PGMSG_RESPAWN);
+ Net::GameServer::connection->send(msg);
+}
+
+void Net::GameServer::Player::changeDir(unsigned char dir)
+{
+ MessageOut msg(PGMSG_DIRECTION_CHANGE);
+ msg.writeInt8(dir);
+ Net::GameServer::connection->send(msg);
+}
diff --git a/src/net/gameserver/player.h b/src/net/gameserver/player.h
new file mode 100644
index 00000000..9e68ced9
--- /dev/null
+++ b/src/net/gameserver/player.h
@@ -0,0 +1,71 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_GAMESERVER_PLAYER_H
+#define _TMW_NET_GAMESERVER_PLAYER_H
+
+#include "../../being.h"
+
+#include <guichan/actionlistener.hpp>
+
+#include <iosfwd>
+
+
+struct RespawnRequestListener : public gcn::ActionListener
+{
+ void action(const gcn::ActionEvent &event);
+};
+
+namespace Net
+{
+ namespace GameServer
+ {
+ namespace Player
+ {
+ void say(const std::string &text);
+ void walk(int x, int y);
+ void pickUp(int x, int y);
+ void moveItem(int oldSlot, int newSlot, int amount);
+ void drop(int slot, int amount);
+ void equip(int slot);
+ void unequip(int slot);
+ void useItem(int slot);
+ void attack(int direction);
+ void useSpecial(int special);
+ void changeAction(Being::Action action);
+ void talkToNPC(int id, bool restart);
+ void selectFromNPC(int id, int choice);
+ void requestTrade(int id);
+ void acceptTrade(bool accept);
+ void tradeItem(int slot, int amount);
+ void tradeMoney(int amount);
+ void tradeWithNPC(int item, int amount);
+ void sendLetter(const std::string &player, const std::string &text);
+ void raiseAttribute(int attribute);
+ void lowerAttribute(int attribute);
+ void respawn();
+ static RespawnRequestListener respawnListener;
+ void changeDir(unsigned char dir);
+ }
+ }
+}
+
+#endif
diff --git a/src/net/guildhandler.cpp b/src/net/guildhandler.cpp
new file mode 100644
index 00000000..cf886ab3
--- /dev/null
+++ b/src/net/guildhandler.cpp
@@ -0,0 +1,240 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <iostream>
+#include "guildhandler.h"
+
+#include "protocol.h"
+#include "messagein.h"
+
+#include "chatserver/chatserver.h"
+#include "chatserver/guild.h"
+
+#include "../gui/guildwindow.h"
+#include "../gui/chat.h"
+#include "../guild.h"
+#include "../log.h"
+#include "../localplayer.h"
+#include "../channel.h"
+#include "../channelmanager.h"
+
+GuildHandler::GuildHandler()
+{
+ static const Uint16 _messages[] = {
+ CPMSG_GUILD_CREATE_RESPONSE,
+ CPMSG_GUILD_INVITE_RESPONSE,
+ CPMSG_GUILD_ACCEPT_RESPONSE,
+ CPMSG_GUILD_GET_MEMBERS_RESPONSE,
+ CPMSG_GUILD_UPDATE_LIST,
+ CPMSG_GUILD_INVITED,
+ CPMSG_GUILD_REJOIN,
+ CPMSG_GUILD_QUIT_RESPONSE,
+ 0
+ };
+ handledMessages = _messages;
+
+}
+
+void GuildHandler::handleMessage(MessageIn &msg)
+{
+ switch (msg.getId())
+ {
+ case CPMSG_GUILD_CREATE_RESPONSE:
+ {
+ logger->log("Received CPMSG_GUILD_CREATE_RESPONSE");
+ if(msg.readInt8() == ERRMSG_OK)
+ {
+ // TODO - Acknowledge guild was created
+ chatWindow->chatLog("Guild created.");
+ joinedGuild(msg);
+ }
+ else
+ {
+ chatWindow->chatLog("Error creating guild.");
+ }
+ } break;
+
+ case CPMSG_GUILD_INVITE_RESPONSE:
+ {
+ logger->log("Received CPMSG_GUILD_INVITE_RESPONSE");
+ if(msg.readInt8() == ERRMSG_OK)
+ {
+ // TODO - Acknowledge invite was sent
+ chatWindow->chatLog("Invite sent.");
+ }
+ } break;
+
+ case CPMSG_GUILD_ACCEPT_RESPONSE:
+ {
+ logger->log("Received CPMSG_GUILD_ACCEPT_RESPONSE");
+ if(msg.readInt8() == ERRMSG_OK)
+ {
+ // TODO - Acknowledge accepted into guild
+ joinedGuild(msg);
+ }
+ } break;
+
+ case CPMSG_GUILD_GET_MEMBERS_RESPONSE:
+ {
+ logger->log("Received CPMSG_GUILD_GET_MEMBERS_RESPONSE");
+ if(msg.readInt8() == ERRMSG_OK)
+ {
+ std::string guildMember;
+ bool online;
+ std::string guildName;
+ Guild *guild;
+
+ short guildId = msg.readInt16();
+ guild = player_node->getGuild(guildId);
+
+ if (!guild)
+ return;
+
+ guildName = guild->getName();
+
+ while(msg.getUnreadLength())
+ {
+ guildMember = msg.readString();
+ online = msg.readInt8();
+ if(guildMember != "")
+ {
+ guild->addMember(guildMember);
+ guildWindow->setOnline(guildName, guildMember, online);
+ }
+ }
+
+ guildWindow->updateTab();
+ }
+ } break;
+
+ case CPMSG_GUILD_UPDATE_LIST:
+ {
+ logger->log("Received CPMSG_GUILD_UPDATE_LIST");
+ short guildId = msg.readInt16();
+ std::string guildMember = msg.readString();
+ char eventId = msg.readInt8();
+
+ Guild *guild = player_node->getGuild(guildId);
+ if (guild)
+ {
+ switch(eventId)
+ {
+ case GUILD_EVENT_NEW_PLAYER:
+ guild->addMember(guildMember);
+ guildWindow->setOnline(guild->getName(), guildMember, true);
+ break;
+
+ case GUILD_EVENT_LEAVING_PLAYER:
+ guild->removeMember(guildMember);
+ break;
+
+ case GUILD_EVENT_ONLINE_PLAYER:
+ guildWindow->setOnline(guild->getName(), guildMember, true);
+ break;
+
+ case GUILD_EVENT_OFFLINE_PLAYER:
+ guildWindow->setOnline(guild->getName(), guildMember, false);
+ break;
+
+ default:
+ logger->log("Invalid guild event");
+ }
+ }
+ guildWindow->updateTab();
+
+
+ } break;
+
+ case CPMSG_GUILD_INVITED:
+ {
+ logger->log("Received CPMSG_GUILD_INVITED");
+ std::string inviterName = msg.readString();
+ std::string guildName = msg.readString();
+
+ // Open a dialog asking if the player accepts joining the guild.
+ guildWindow->openAcceptDialog(inviterName, guildName);
+ } break;
+
+ case CPMSG_GUILD_PROMOTE_MEMBER_RESPONSE:
+ {
+ logger->log("Received CPMSG_GUILD_PROMOTE_MEMBER_RESPONSE");
+
+ if (msg.readInt8() == ERRMSG_OK)
+ {
+ // promotion succeeded
+ chatWindow->chatLog("Member was promoted successfully");
+ }
+ else
+ {
+ // promotion failed
+ chatWindow->chatLog("Failed to promote member");
+ }
+ }
+
+ case CPMSG_GUILD_REJOIN:
+ {
+ logger->log("Received CPMSG_GUILD_REJOIN");
+
+ joinedGuild(msg);
+ } break;
+
+ case CPMSG_GUILD_QUIT_RESPONSE:
+ {
+ logger->log("Received CPMSG_GUILD_QUIT_RESPONSE");
+
+ if (msg.readInt8() == ERRMSG_OK)
+ {
+ // Must remove tab first, as it wont find the guild
+ // name after its removed from the player
+ int guildId = msg.readInt16();
+ Guild *guild = player_node->getGuild(guildId);
+ if (guild)
+ {
+ chatWindow->removeChannel(guild->getName());
+ guildWindow->removeTab(guildId);
+ player_node->removeGuild(guildId);
+ }
+ }
+ } break;
+ }
+}
+
+void GuildHandler::joinedGuild(MessageIn &msg)
+{
+ std::string guildName = msg.readString();
+ short guildId = msg.readInt16();
+ short permissions = msg.readInt16();
+ short channelId = msg.readInt16();
+ std::string announcement = msg.readString();
+
+ // Add guild to player and create new guild tab
+ Guild *guild = player_node->addGuild(guildId, permissions);
+ guild->setName(guildName);
+ guildWindow->newGuildTab(guildName);
+ guildWindow->requestMemberList(guildId);
+
+ // Automatically create the guild channel
+ // COMMENT: Should this go here??
+ Channel *channel = new Channel(channelId, guildName, announcement);
+ channelManager->addChannel(channel);
+ chatWindow->createNewChannelTab(guildName);
+ chatWindow->chatLog("Topic: " + announcement, BY_CHANNEL, guildName);
+}
diff --git a/src/net/guildhandler.h b/src/net/guildhandler.h
new file mode 100644
index 00000000..4eb2da0b
--- /dev/null
+++ b/src/net/guildhandler.h
@@ -0,0 +1,40 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_GUILDHANDLER_H
+#define _TMW_NET_GUILDHANDLER_H
+
+#include "messagehandler.h"
+
+#include <string>
+
+class GuildHandler : public MessageHandler
+{
+public:
+ GuildHandler();
+
+ void handleMessage(MessageIn &msg);
+
+protected:
+ void joinedGuild(MessageIn &msg);
+};
+
+#endif
diff --git a/src/net/internal.cpp b/src/net/internal.cpp
new file mode 100644
index 00000000..4cb88a4e
--- /dev/null
+++ b/src/net/internal.cpp
@@ -0,0 +1,27 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "internal.h"
+
+namespace Net
+{
+ int connections = 0;
+}
diff --git a/src/net/internal.h b/src/net/internal.h
new file mode 100644
index 00000000..1e411605
--- /dev/null
+++ b/src/net/internal.h
@@ -0,0 +1,30 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_INTERNAL_H
+#define _TMW_NET_INTERNAL_H
+
+namespace Net
+{
+ extern int connections;
+}
+
+#endif
diff --git a/src/net/inventoryhandler.cpp b/src/net/inventoryhandler.cpp
index d5ac0c29..41032f13 100644
--- a/src/net/inventoryhandler.cpp
+++ b/src/net/inventoryhandler.cpp
@@ -1,227 +1,79 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
+#include "inventoryhandler.h"
+
#include <SDL_types.h>
-#include "inventoryhandler.h"
#include "messagein.h"
#include "protocol.h"
+#include "../equipment.h"
#include "../inventory.h"
#include "../item.h"
#include "../itemshortcut.h"
#include "../localplayer.h"
-#include "../log.h"
#include "../gui/chat.h"
-
#include "../resources/iteminfo.h"
-#include "../utils/gettext.h"
-#include "../utils/strprintf.h"
-#include "../utils/stringutils.h"
-
InventoryHandler::InventoryHandler()
{
static const Uint16 _messages[] = {
- SMSG_PLAYER_INVENTORY,
- SMSG_PLAYER_INVENTORY_ADD,
- SMSG_PLAYER_INVENTORY_REMOVE,
- SMSG_PLAYER_INVENTORY_USE,
- SMSG_ITEM_USE_RESPONSE,
- SMSG_PLAYER_STORAGE_ITEMS,
- SMSG_PLAYER_STORAGE_EQUIP,
- SMSG_PLAYER_STORAGE_STATUS,
- SMSG_PLAYER_STORAGE_ADD,
- SMSG_PLAYER_STORAGE_REMOVE,
- SMSG_PLAYER_STORAGE_CLOSE,
+ GPMSG_INVENTORY_FULL,
+ GPMSG_INVENTORY,
0
};
handledMessages = _messages;
}
-void InventoryHandler::handleMessage(MessageIn *msg)
+void InventoryHandler::handleMessage(MessageIn &msg)
{
- Sint32 number;
- Sint16 index, amount, itemId, equipType, arrow;
- Sint16 identified, cards[4], itemType;
- Inventory *inventory = player_node->getInventory();
- Inventory *storage = player_node->getStorage();
-
- switch (msg->getId())
+ switch (msg.getId())
{
- case SMSG_PLAYER_INVENTORY:
- case SMSG_PLAYER_STORAGE_ITEMS:
- case SMSG_PLAYER_STORAGE_EQUIP:
- switch (msg->getId()) {
- case SMSG_PLAYER_INVENTORY:
- // Clear inventory - this will be a complete refresh
- inventory->clear();
- break;
- case SMSG_PLAYER_STORAGE_ITEMS:
- /*
- * This packet will always be followed by a
- * SMSG_PLAYER_STORAGE_EQUIP packet. The two packets
- * together comprise a complete refresh of storage, so
- * clear storage here
- */
- storage->clear();
- logger->log("Received SMSG_PLAYER_STORAGE_ITEMS");
- break;
- default:
- logger->log("Received SMSG_PLAYER_STORAGE_EQUIP");
- break;
- }
- msg->readInt16(); // length
- number = (msg->getLength() - 4) / 18;
-
- for (int loop = 0; loop < number; loop++) {
- index = msg->readInt16();
- itemId = msg->readInt16();
- itemType = msg->readInt8();
- identified = msg->readInt8();
- if (msg->getId() == SMSG_PLAYER_STORAGE_EQUIP) {
- amount = 1;
- msg->readInt16(); // Equip Point?
- } else {
- amount = msg->readInt16();
- }
- arrow = msg->readInt16();
- if (msg->getId() == SMSG_PLAYER_STORAGE_EQUIP) {
- msg->readInt8(); // Attribute (broken)
- msg->readInt8(); // Refine level
+ case GPMSG_INVENTORY_FULL:
+ player_node->clearInventory();
+ // no break!
+
+ case GPMSG_INVENTORY:
+ while (msg.getUnreadLength())
+ {
+ int slot = msg.readInt8();
+ if (slot == 255)
+ {
+ player_node->setMoney(msg.readInt32());
+ continue;
}
- for (int i = 0; i < 4; i++)
- cards[i] = msg->readInt16();
- if (msg->getId() == SMSG_PLAYER_INVENTORY) {
- inventory->setItem(index, itemId, amount, false);
-
- // Trick because arrows are not considered equipment
- if (arrow & 0x8000) {
- if (Item *item = inventory->getItem(index))
- item->setEquipment(true);
- }
- } else {
- logger->log("Index:%d, ID:%d, Type:%d, Identified:%d, Qty:%d, Cards:%d, %d, %d, %d",
- index, itemId, itemType, identified, amount, cards[0], cards[1], cards[2], cards[3]);
- storage->setItem(index, itemId, amount, false);
+ int id = msg.readInt16();
+ if (slot < EQUIPMENT_SIZE)
+ {
+ player_node->mEquipment->setEquipment(slot, id);
}
- }
- break;
-
- case SMSG_PLAYER_INVENTORY_ADD:
- index = msg->readInt16();
- amount = msg->readInt16();
- itemId = msg->readInt16();
- identified = msg->readInt8();
- msg->readInt8(); // attribute
- msg->readInt8(); // refine
- for (int i = 0; i < 4; i++)
- cards[i] = msg->readInt16();
- equipType = msg->readInt16();
- itemType = msg->readInt8();
-
- if (msg->readInt8() > 0) {
- chatWindow->chatLog(_("Unable to pick up item"), BY_SERVER);
- } else {
- const ItemInfo &itemInfo = ItemDB::get(itemId);
- const std::string amountStr =
- (amount > 1) ? toString(amount) : "a";
- chatWindow->chatLog(strprintf(_("You picked up %s %s"),
- amountStr.c_str(), itemInfo.getName().c_str()), BY_SERVER);
-
- if (Item *item = inventory->getItem(index)) {
- item->setId(itemId);
- item->increaseQuantity(amount);
- } else {
- inventory->setItem(index, itemId, amount, equipType != 0);
+ else if (slot >= 32 && slot < 32 + INVENTORY_SIZE)
+ {
+ int amount = id ? msg.readInt8() : 0;
+ player_node->setInvItem(slot - 32, id, amount);
}
- }
- break;
-
- case SMSG_PLAYER_INVENTORY_REMOVE:
- index = msg->readInt16();
- amount = msg->readInt16();
- if (Item *item = inventory->getItem(index)) {
- item->increaseQuantity(-amount);
- if (item->getQuantity() == 0)
- inventory->removeItemAt(index);
- }
- break;
-
- case SMSG_PLAYER_INVENTORY_USE:
- index = msg->readInt16();
- msg->readInt16(); // item id
- msg->readInt32(); // id
- amount = msg->readInt16();
- msg->readInt8(); // type
-
- if (Item *item = inventory->getItem(index))
- item->setQuantity(amount);
- break;
-
- case SMSG_ITEM_USE_RESPONSE:
- index = msg->readInt16();
- amount = msg->readInt16();
-
- if (msg->readInt8() == 0) {
- chatWindow->chatLog(_("Failed to use item"), BY_SERVER);
- } else {
- if (Item *item = inventory->getItem(index))
- item->setQuantity(amount);
- }
- break;
-
- case SMSG_PLAYER_STORAGE_STATUS:
- /*
- * Basic slots used vs total slots info
- * We don't really need this information, but this is
- * the closest we get to an "Open Storage" packet
- * from the server. It always comes after the two
- * SMSG_PLAYER_STORAGE_... packets that update
- * storage contents.
- */
- logger->log("Received SMSG_PLAYER_STORAGE_STATUS");
- player_node->setInStorage(true);
- break;
-
- case SMSG_PLAYER_STORAGE_ADD:
- /*
- * Move an item into storage
- */
- break;
-
- case SMSG_PLAYER_STORAGE_REMOVE:
- /*
- * Move an item out of storage
- */
- break;
-
- case SMSG_PLAYER_STORAGE_CLOSE:
- /*
- * Storage access has been closed
- */
- player_node->setInStorage(false);
- logger->log("Received SMSG_PLAYER_STORAGE_CLOSE");
+ };
break;
}
}
diff --git a/src/net/inventoryhandler.h b/src/net/inventoryhandler.h
index 336b2e98..9b457abe 100644
--- a/src/net/inventoryhandler.h
+++ b/src/net/inventoryhandler.h
@@ -29,7 +29,7 @@ class InventoryHandler : public MessageHandler
public:
InventoryHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/itemhandler.cpp b/src/net/itemhandler.cpp
index 8c4af4e4..189c6eb9 100644
--- a/src/net/itemhandler.cpp
+++ b/src/net/itemhandler.cpp
@@ -29,39 +29,36 @@
ItemHandler::ItemHandler()
{
static const Uint16 _messages[] = {
- SMSG_ITEM_VISIBLE,
- SMSG_ITEM_DROPPED,
- SMSG_ITEM_REMOVE,
+ GPMSG_ITEMS,
+ GPMSG_ITEM_APPEAR,
0
};
handledMessages = _messages;
}
-void ItemHandler::handleMessage(MessageIn *msg)
+void ItemHandler::handleMessage(MessageIn &msg)
{
- Uint32 id;
- Uint16 x, y;
- Sint16 itemId;
-
- switch (msg->getId())
+ switch (msg.getId())
{
- case SMSG_ITEM_VISIBLE:
- case SMSG_ITEM_DROPPED:
- id = msg->readInt32();
- itemId = msg->readInt16();
- msg->readInt8(); // identify flag
- x = msg->readInt16();
- y = msg->readInt16();
- msg->skip(4); // amount,subX,subY / subX,subY,amount
-
- floorItemManager->create(id, itemId, x, y, engine->getCurrentMap());
- break;
+ case GPMSG_ITEM_APPEAR:
+ case GPMSG_ITEMS:
+ {
+ while (msg.getUnreadLength())
+ {
+ int itemId = msg.readInt16();
+ int x = msg.readInt16();
+ int y = msg.readInt16();
+ int id = (x << 16) | y; // dummy id
- case SMSG_ITEM_REMOVE:
- FloorItem *item;
- item = floorItemManager->findById(msg->readInt32());
- if (item)
- floorItemManager->destroy(item);
- break;
+ if (itemId)
+ {
+ floorItemManager->create(id, itemId, x / 32, y / 32, engine->getCurrentMap());
+ }
+ else if (FloorItem *item = floorItemManager->findById(id))
+ {
+ floorItemManager->destroy(item);
+ }
+ }
+ } break;
}
}
diff --git a/src/net/itemhandler.h b/src/net/itemhandler.h
index 0cb3b42a..12057bb1 100644
--- a/src/net/itemhandler.h
+++ b/src/net/itemhandler.h
@@ -29,7 +29,7 @@ class ItemHandler : public MessageHandler
public:
ItemHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/loginhandler.cpp b/src/net/loginhandler.cpp
index 2695fc7b..37c3608a 100644
--- a/src/net/loginhandler.cpp
+++ b/src/net/loginhandler.cpp
@@ -1,158 +1,225 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "loginhandler.h"
+
#include "messagein.h"
#include "protocol.h"
-#include "../log.h"
#include "../logindata.h"
#include "../main.h"
-#include "../serverinfo.h"
-
-#include "../utils/gettext.h"
-#include "../utils/strprintf.h"
-#include "../utils/stringutils.h"
-
-extern SERVER_INFO **server_info;
LoginHandler::LoginHandler()
{
static const Uint16 _messages[] = {
- SMSG_CONNECTION_PROBLEM,
- SMSG_UPDATE_HOST,
- 0x0069,
- 0x006a,
+ APMSG_LOGIN_RESPONSE,
+ APMSG_REGISTER_RESPONSE,
+ APMSG_RECONNECT_RESPONSE,
+ APMSG_PASSWORD_CHANGE_RESPONSE,
+ APMSG_EMAIL_CHANGE_RESPONSE,
0
};
handledMessages = _messages;
}
-void LoginHandler::handleMessage(MessageIn *msg)
+void LoginHandler::setLoginData(LoginData *loginData)
{
- int code;
+ mLoginData = loginData;
+}
- switch (msg->getId())
+void LoginHandler::handleMessage(MessageIn &msg)
+{
+ switch (msg.getId())
{
- case SMSG_CONNECTION_PROBLEM:
- code = msg->readInt8();
- logger->log("Connection problem: %i", code);
-
- switch (code) {
- case 0:
- errorMessage = _("Authentication failed");
- break;
- case 1:
- errorMessage = _("No servers available");
- break;
- case 2:
- errorMessage = _("This account is already logged in");
- break;
- default:
- errorMessage = _("Unknown connection error");
- break;
+ case APMSG_LOGIN_RESPONSE:
+ handleLoginResponse(msg);
+ break;
+ case APMSG_REGISTER_RESPONSE:
+ handleRegisterResponse(msg);
+ break;
+ case APMSG_RECONNECT_RESPONSE:
+ {
+ int errMsg = msg.readInt8();
+ // Successful login
+ if (errMsg == ERRMSG_OK)
+ {
+ state = STATE_CHAR_SELECT;
}
- state = ERROR_STATE;
+ // Login failed
+ else
+ {
+ switch (errMsg) {
+ case ERRMSG_INVALID_ARGUMENT:
+ errorMessage = "Wrong magic_token";
+ break;
+ case ERRMSG_FAILURE:
+ errorMessage = "Already logged in";
+ break;
+ case LOGIN_SERVER_FULL:
+ errorMessage = "Server is full";
+ break;
+ default:
+ errorMessage = "Unknown error";
+ break;
+ }
+ state = STATE_ERROR;
+ }
+ }
break;
- case SMSG_UPDATE_HOST:
- int len;
-
- len = msg->readInt16() - 4;
- mUpdateHost = msg->readString(len);
-
- logger->log("Received update host \"%s\" from login server",
- mUpdateHost.c_str());
- break;
-
- case 0x0069:
- // Skip the length word
- msg->skip(2);
-
- n_server = (msg->getLength() - 47) / 32;
- server_info =
- (SERVER_INFO**) malloc(sizeof(SERVER_INFO*) * n_server);
-
- mLoginData->session_ID1 = msg->readInt32();
- mLoginData->account_ID = msg->readInt32();
- mLoginData->session_ID2 = msg->readInt32();
- msg->skip(30); // unknown
- mLoginData->sex = msg->readInt8();
-
- for (int i = 0; i < n_server; i++)
+ case APMSG_PASSWORD_CHANGE_RESPONSE:
+ {
+ int errMsg = msg.readInt8();
+ // Successful pass change
+ if (errMsg == ERRMSG_OK)
{
- server_info[i] = new SERVER_INFO;
-
- server_info[i]->address = msg->readInt32();
- server_info[i]->port = msg->readInt16();
- server_info[i]->name = msg->readString(20);
- server_info[i]->online_users = msg->readInt32();
- server_info[i]->updateHost = mUpdateHost;
- msg->skip(2); // unknown
+ state = STATE_CHANGEPASSWORD;
+ }
+ // pass change failed
+ else
+ {
+ switch (errMsg) {
+ case ERRMSG_INVALID_ARGUMENT:
+ errorMessage = "New password incorrect";
+ break;
+ case ERRMSG_FAILURE:
+ errorMessage = "Old password incorrect";
+ break;
+ case ERRMSG_NO_LOGIN:
+ errorMessage = "Account not connected. Please login first.";
+ break;
+ default:
+ errorMessage = "Unknown error";
+ break;
+ }
+ state = STATE_ACCOUNTCHANGE_ERROR;
+ }
+ }
+ break;
- logger->log("Network: Server: %s (%s:%d)",
- server_info[i]->name.c_str(),
- ipToString(server_info[i]->address),
- server_info[i]->port);
+ case APMSG_EMAIL_CHANGE_RESPONSE:
+ {
+ int errMsg = msg.readInt8();
+ // Successful pass change
+ if (errMsg == ERRMSG_OK)
+ {
+ state = STATE_CHANGEEMAIL;
}
- state = CHAR_SERVER_STATE;
+ // pass change failed
+ else
+ {
+ switch (errMsg) {
+ case ERRMSG_INVALID_ARGUMENT:
+ errorMessage = "New email address incorrect";
+ break;
+ case ERRMSG_FAILURE:
+ errorMessage = "Old email address incorrect";
+ break;
+ case ERRMSG_NO_LOGIN:
+ errorMessage = "Account not connected. Please login first.";
+ break;
+ case ERRMSG_EMAIL_ALREADY_EXISTS:
+ errorMessage = "The new Email Address already exists.";
+ break;
+ default:
+ errorMessage = "Unknown error";
+ break;
+ }
+ state = STATE_ACCOUNTCHANGE_ERROR;
+ }
+ }
break;
- case 0x006a:
- code = msg->readInt8();
- logger->log("Login::error code: %i", code);
+ }
+}
- switch (code) {
- case 0:
- errorMessage = _("Unregistered ID");
- break;
- case 1:
- errorMessage = _("Wrong password");
- break;
- case 2:
- errorMessage = _("Account expired");
- break;
- case 3:
- errorMessage = _("Rejected from server");
- break;
- case 4:
+void LoginHandler::handleLoginResponse(MessageIn &msg)
+{
+ const int errMsg = msg.readInt8();
- errorMessage = _("You have been permanently banned from "
- "the game. Please contact the GM Team.");
- break;
- case 6:
- errorMessage = strprintf(_("You have been temporarily "
- "banned from the game until "
- "%s.\n Please contact the GM "
- "team via the forums."),
- msg->readString(20).c_str());
- break;
- case 9:
- errorMessage = _("This user name is already taken");
- break;
- default:
- errorMessage = _("Unknown error");
- break;
- }
- state = ERROR_STATE;
- break;
+ if (errMsg == ERRMSG_OK)
+ {
+ readUpdateHost(msg);
+ state = STATE_CHAR_SELECT;
+ }
+ else
+ {
+ switch (errMsg) {
+ case LOGIN_INVALID_VERSION:
+ errorMessage = "Client version is too old";
+ break;
+ case ERRMSG_INVALID_ARGUMENT:
+ errorMessage = "Wrong username or password";
+ break;
+ case ERRMSG_FAILURE:
+ errorMessage = "Already logged in";
+ break;
+ case LOGIN_SERVER_FULL:
+ errorMessage = "Server is full";
+ break;
+ default:
+ errorMessage = "Unknown error";
+ break;
+ }
+ state = STATE_LOGIN_ERROR;
+ }
+}
+
+void LoginHandler::handleRegisterResponse(MessageIn &msg)
+{
+ const int errMsg = msg.readInt8();
+
+ if (errMsg == ERRMSG_OK)
+ {
+ readUpdateHost(msg);
+ state = STATE_CHAR_SELECT;
+ }
+ else
+ {
+ switch (errMsg) {
+ case REGISTER_INVALID_VERSION:
+ errorMessage = "Client version is too old";
+ break;
+ case ERRMSG_INVALID_ARGUMENT:
+ errorMessage = "Wrong username, password or email address";
+ break;
+ case REGISTER_EXISTS_USERNAME:
+ errorMessage = "Username already exists";
+ break;
+ case REGISTER_EXISTS_EMAIL:
+ errorMessage = "Email address already exists";
+ break;
+ default:
+ errorMessage = "Unknown error";
+ break;
+ }
+ state = STATE_LOGIN_ERROR;
+ }
+}
+
+void LoginHandler::readUpdateHost(MessageIn &msg)
+{
+ // Set the update host when included in the message
+ if (msg.getUnreadLength() > 0)
+ {
+ mLoginData->updateHost = msg.readString();
}
}
diff --git a/src/net/loginhandler.h b/src/net/loginhandler.h
index df86b634..015d6383 100644
--- a/src/net/loginhandler.h
+++ b/src/net/loginhandler.h
@@ -1,45 +1,47 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#ifndef NET_LOGINHANDLER_H
-#define NET_LOGINHANDLER_H
-
-#include <string>
+#ifndef _TMW_NET_LOGINHANDLER_H
+#define _TMW_NET_LOGINHANDLER_H
#include "messagehandler.h"
-struct LoginData;
+class LoginData;
class LoginHandler : public MessageHandler
{
public:
LoginHandler();
- void handleMessage(MessageIn *msg);
+ void setLoginData(LoginData *loginData);
- void setLoginData(LoginData *loginData) { mLoginData = loginData; };
+ void handleMessage(MessageIn &msg);
private:
+ void handleLoginResponse(MessageIn &msg);
+ void handleRegisterResponse(MessageIn &msg);
+
+ void readUpdateHost(MessageIn &msg);
+
LoginData *mLoginData;
- std::string mUpdateHost;
};
-#endif
+#endif // _TMW_NET_LOGINHANDLER_H
diff --git a/src/net/logouthandler.cpp b/src/net/logouthandler.cpp
new file mode 100644
index 00000000..6dea4c83
--- /dev/null
+++ b/src/net/logouthandler.cpp
@@ -0,0 +1,215 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "logouthandler.h"
+
+#include "messagein.h"
+#include "protocol.h"
+
+#include "../main.h"
+
+LogoutHandler::LogoutHandler():
+mPassToken(NULL), mScenario(LOGOUT_EXIT),
+mLoggedOutAccount(false), mLoggedOutGame(false), mLoggedOutChat(false)
+{
+ static const Uint16 _messages[] = {
+ APMSG_LOGOUT_RESPONSE,
+ APMSG_UNREGISTER_RESPONSE,
+ GPMSG_DISCONNECT_RESPONSE,
+ CPMSG_DISCONNECT_RESPONSE,
+ 0
+ };
+ handledMessages = _messages;
+}
+
+void LogoutHandler::handleMessage(MessageIn &msg)
+{
+ switch (msg.getId())
+ {
+ case APMSG_LOGOUT_RESPONSE:
+ {
+ int errMsg = msg.readInt8();
+
+ // Successful logout
+ if (errMsg == ERRMSG_OK)
+ {
+ mLoggedOutAccount = true;
+
+ switch (mScenario)
+ {
+ case LOGOUT_SWITCH_ACCOUNTSERVER:
+ if (mLoggedOutGame && mLoggedOutChat)
+ state = STATE_SWITCH_ACCOUNTSERVER;
+ break;
+
+ case LOGOUT_EXIT:
+ default:
+ if (mLoggedOutGame && mLoggedOutChat)
+ state = STATE_FORCE_QUIT;
+ break;
+ }
+ }
+ // Logout failed
+ else
+ {
+ switch (errMsg) {
+ case ERRMSG_NO_LOGIN:
+ errorMessage = "Accountserver: Not logged in";
+ break;
+ default:
+ errorMessage = "Accountserver: Unknown error";
+ break;
+ }
+ state = STATE_ERROR;
+ }
+ }
+ break;
+ case APMSG_UNREGISTER_RESPONSE:
+ {
+ int errMsg = msg.readInt8();
+ // Successful unregistration
+ if (errMsg == ERRMSG_OK)
+ {
+ state = STATE_UNREGISTER;
+ }
+ // Unregistration failed
+ else
+ {
+ switch (errMsg) {
+ case ERRMSG_INVALID_ARGUMENT:
+ errorMessage =
+ "Accountserver: Wrong username or password";
+ break;
+ default:
+ errorMessage = "Accountserver: Unknown error";
+ break;
+ }
+ state = STATE_ACCOUNTCHANGE_ERROR;
+ }
+ }
+ break;
+ case GPMSG_DISCONNECT_RESPONSE:
+ {
+ int errMsg = msg.readInt8();
+ // Successful logout
+ if (errMsg == ERRMSG_OK)
+ {
+ mLoggedOutGame = true;
+
+ switch (mScenario)
+ {
+ case LOGOUT_SWITCH_CHARACTER:
+ if (mPassToken)
+ {
+ *mPassToken = msg.readString(32);
+ mPassToken = NULL;
+ }
+ if (mLoggedOutChat) state = STATE_RECONNECT_ACCOUNT;
+ break;
+
+ case LOGOUT_SWITCH_ACCOUNTSERVER:
+ if (mLoggedOutAccount && mLoggedOutChat)
+ state = STATE_SWITCH_ACCOUNTSERVER;
+ break;
+
+ case LOGOUT_EXIT:
+ default:
+ if (mLoggedOutAccount && mLoggedOutChat)
+ state = STATE_FORCE_QUIT;
+ break;
+ }
+ }
+ // Logout failed
+ else
+ {
+ switch (errMsg) {
+ case ERRMSG_NO_LOGIN:
+ errorMessage = "Gameserver: Not logged in";
+ break;
+ default:
+ errorMessage = "Gameserver: Unknown error";
+ break;
+ }
+ state = STATE_ERROR;
+ }
+ }
+ break;
+ case CPMSG_DISCONNECT_RESPONSE:
+ {
+ int errMsg = msg.readInt8();
+ // Successful logout
+ if (errMsg == ERRMSG_OK)
+ {
+ mLoggedOutChat = true;
+
+ switch (mScenario)
+ {
+ case LOGOUT_SWITCH_CHARACTER:
+ if (mLoggedOutGame) state = STATE_RECONNECT_ACCOUNT;
+ break;
+
+ case LOGOUT_SWITCH_ACCOUNTSERVER:
+ if (mLoggedOutAccount && mLoggedOutGame)
+ state = STATE_SWITCH_ACCOUNTSERVER;
+ break;
+
+ case LOGOUT_EXIT:
+ default:
+ if (mLoggedOutAccount && mLoggedOutGame)
+ {
+ state = STATE_FORCE_QUIT;
+ }
+ break;
+ }
+ }
+ else
+ {
+ switch (errMsg) {
+ case ERRMSG_NO_LOGIN:
+ errorMessage = "Chatserver: Not logged in";
+ break;
+ default:
+ errorMessage = "Chatserver: Unknown error";
+ break;
+ }
+ state = STATE_ERROR;
+ }
+ }
+ break;
+ }
+}
+
+void
+LogoutHandler::setScenario(unsigned short scenario, std::string* passToken)
+{
+ mScenario = scenario;
+ mPassToken = passToken;
+}
+
+void
+LogoutHandler::reset()
+{
+ mPassToken = NULL;
+ mScenario = LOGOUT_EXIT;
+ mLoggedOutAccount = false;
+ mLoggedOutGame = false;
+ mLoggedOutChat = false;
+}
diff --git a/src/net/logouthandler.h b/src/net/logouthandler.h
new file mode 100644
index 00000000..369eaa80
--- /dev/null
+++ b/src/net/logouthandler.h
@@ -0,0 +1,62 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_NET_LOGOUTHANDLER_H
+#define _TMW_NET_LOGOUTHANDLER_H
+
+#include <string>
+
+#include "messagehandler.h"
+
+/**
+ * The different scenarios for which LogoutHandler can be used
+ */
+enum {
+ LOGOUT_EXIT,
+ LOGOUT_SWITCH_ACCOUNTSERVER,
+ LOGOUT_SWITCH_CHARACTER
+};
+
+class LogoutHandler : public MessageHandler
+{
+ public:
+ LogoutHandler();
+
+ void handleMessage(MessageIn &msg);
+
+ void setScenario(unsigned short scenario,
+ std::string* passToken = NULL);
+
+ void reset();
+
+ void setAccountLoggedOut(){ mLoggedOutAccount = true; }
+ void setGameLoggedOut(){ mLoggedOutGame = true; }
+ void setChatLoggedOut(){ mLoggedOutChat = true; }
+
+ private:
+ std::string* mPassToken;
+ unsigned short mScenario;
+ bool mLoggedOutAccount;
+ bool mLoggedOutGame;
+ bool mLoggedOutChat;
+};
+
+#endif
diff --git a/src/net/messagehandler.cpp b/src/net/messagehandler.cpp
index f1561a31..a765d0e8 100644
--- a/src/net/messagehandler.cpp
+++ b/src/net/messagehandler.cpp
@@ -22,21 +22,33 @@
#include <cassert>
#include "messagehandler.h"
+#ifdef TMWSERV_SUPPORT
#include "network.h"
+#else
+#include "ea/network.h"
+#endif
-MessageHandler::MessageHandler():
- mNetwork(0)
+MessageHandler::MessageHandler()
+#ifdef EATHENA_SUPPORT
+ : mNetwork(0)
+#endif
{
}
MessageHandler::~MessageHandler()
{
+#ifdef TMWSERV_SUPPORT
+ Net::unregisterHandler(this);
+#else
if (mNetwork)
mNetwork->unregisterHandler(this);
+#endif
}
+#ifdef EATHENA_SUPPORT
void MessageHandler::setNetwork(Network *network)
{
assert(!(network && mNetwork));
mNetwork = network;
}
+#endif
diff --git a/src/net/messagehandler.h b/src/net/messagehandler.h
index 45cdf8cd..261a8351 100644
--- a/src/net/messagehandler.h
+++ b/src/net/messagehandler.h
@@ -25,8 +25,13 @@
#include <SDL_types.h>
class MessageIn;
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
+/**
+ * \ingroup Network
+ */
class MessageHandler
{
public:
@@ -35,12 +40,14 @@ class MessageHandler
MessageHandler();
virtual ~MessageHandler();
- virtual void handleMessage(MessageIn *msg) =0;
+ virtual void handleMessage(MessageIn &msg) = 0;
+#ifdef EATHENA_SUPPORT
void setNetwork(Network *network);
protected:
Network *mNetwork;
+#endif
};
#endif
diff --git a/src/net/messagein.cpp b/src/net/messagein.cpp
index a288d936..813b440f 100644
--- a/src/net/messagein.cpp
+++ b/src/net/messagein.cpp
@@ -19,11 +19,16 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include <cassert>
+#include "messagein.h"
+
+#ifdef TMWSERV_SUPPORT
+#include <enet/enet.h>
+#else
#include <SDL.h>
#include <SDL_endian.h>
+#endif
-#include "messagein.h"
+#include <cassert>
#define MAKEWORD(low,high) \
((unsigned short)(((unsigned char)(low)) | \
@@ -38,32 +43,68 @@ MessageIn::MessageIn(const char *data, unsigned int length):
mId = readInt16();
}
-Sint8 MessageIn::readInt8()
+int MessageIn::readInt8()
{
- assert(mPos < mLength);
- return mData[mPos++];
+ int value = -1;
+ if (mPos < mLength)
+ {
+ value = (unsigned char) mData[mPos];
+ }
+ mPos += 1;
+ return value;
}
-Sint16 MessageIn::readInt16()
+int MessageIn::readInt16()
{
- assert(mPos + 2 <= mLength);
- mPos += 2;
+ int value = -1;
+ if (mPos + 2 <= mLength)
+ {
+#ifdef TMWSERV_SUPPORT
+ uint16_t t;
+ memcpy(&t, mData + mPos, 2);
+ value = (unsigned short) ENET_NET_TO_HOST_16(t);
+#else
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
- return SDL_Swap16(*(Sint16*)(mData + (mPos - 2)));
+ value = SDL_Swap16(*(Sint16*)(mData + mPos));
#else
- return (*(Sint16*)(mData + (mPos - 2)));
+ value = (*(Sint16*)(mData + mPos));
#endif
+#endif // TMWSERV_SUPPORT
+ }
+ mPos += 2;
+ return value;
}
-Sint32 MessageIn::readInt32()
+int MessageIn::readInt32()
{
- assert(mPos + 4 <= mLength);
- mPos += 4;
+ int value = -1;
+ if (mPos + 4 <= mLength)
+ {
+#ifdef TMWSERV_SUPPORT
+ uint32_t t;
+ memcpy(&t, mData + mPos, 4);
+ value = ENET_NET_TO_HOST_32(t);
+#else
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
- return SDL_Swap32(*(Sint32*)(mData + (mPos - 4)));
+ value = SDL_Swap32(*(Sint32*)(mData + mPos));
#else
- return (*(Sint32*)(mData + (mPos - 4)));
+ value = (*(Sint32*)(mData + mPos));
#endif
+#endif // TMWSERV_SUPPORT
+ }
+ mPos += 4;
+ return value;
+}
+
+void MessageIn::readCoordinates(Uint16 &x, Uint16 &y)
+{
+ if (mPos + 3 <= mLength)
+ {
+ unsigned char const *p = reinterpret_cast< unsigned char const * >(mData + mPos);
+ x = p[0] | ((p[1] & 0x07) << 8);
+ y = (p[1] >> 3) | ((p[2] & 0x3F) << 5);
+ }
+ mPos += 3;
}
void MessageIn::readCoordinates(Uint16 &x, Uint16 &y, Uint8 &direction)
@@ -164,21 +205,3 @@ std::string MessageIn::readString(int length)
mPos += length;
return readString;
}
-
-Sint8& operator<<(Sint8 &lhs, MessageIn &msg)
-{
- lhs = msg.readInt8();
- return lhs;
-}
-
-Sint16& operator<<(Sint16 &lhs, MessageIn &msg)
-{
- lhs = msg.readInt16();
- return lhs;
-}
-
-Sint32& operator<<(Sint32 &lhs, MessageIn &msg)
-{
- lhs = msg.readInt32();
- return lhs;
-}
diff --git a/src/net/messagein.h b/src/net/messagein.h
index 0ff6e78a..0d0e9981 100644
--- a/src/net/messagein.h
+++ b/src/net/messagein.h
@@ -27,13 +27,11 @@
/**
* Used for parsing an incoming message.
+ *
+ * \ingroup Network
*/
class MessageIn
{
- friend Sint8& operator<<(Sint8 &lhs, MessageIn &msg);
- friend Sint16& operator<<(Sint16 &lhs, MessageIn &msg);
- friend Sint32& operator<<(Sint32 &lhs, MessageIn &msg);
-
public:
/**
* Constructor.
@@ -43,16 +41,27 @@ class MessageIn
/**
* Returns the message ID.
*/
- short getId() { return mId; }
+ int getId() const { return mId; }
/**
* Returns the message length.
*/
- unsigned int getLength() { return mLength; }
+ unsigned int getLength() const { return mLength; }
+
+ /**
+ * Returns the length of unread data.
+ */
+ unsigned int getUnreadLength() const { return mLength - mPos; }
- Sint8 readInt8(); /**< Reads a byte. */
- Sint16 readInt16(); /**< Reads a short. */
- Sint32 readInt32(); /**< Reads a long. */
+ int readInt8(); /**< Reads a byte. */
+ int readInt16(); /**< Reads a short. */
+ int readInt32(); /**< Reads a long. */
+
+ /**
+ * Reads a 3-byte block containing tile-based coordinates. Used by
+ * tmwserv.
+ */
+ void readCoordinates(Uint16 &x, Uint16 &y);
/**
* Reads a special 3 byte block used by eAthena, containing x and y
@@ -82,8 +91,14 @@ class MessageIn
private:
const char* mData; /**< The message data. */
unsigned int mLength; /**< The length of the data. */
- unsigned int mPos; /**< The position in the data. */
- short mId; /**< The message ID. */
+ unsigned short mId; /**< The message ID. */
+
+ /**
+ * Actual position in the packet. From 0 to packet->length.
+ * A value bigger than packet->length means EOP was reached when
+ * reading it.
+ */
+ unsigned int mPos;
};
#endif
diff --git a/src/net/messageout.cpp b/src/net/messageout.cpp
index bf4957be..f7ab6b41 100644
--- a/src/net/messageout.cpp
+++ b/src/net/messageout.cpp
@@ -19,95 +19,131 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include <cstring>
+#include "messageout.h"
+
+#ifdef TMWSERV_SUPPORT
+#include <enet/enet.h>
+#else
+#include "ea/network.h"
#include <SDL.h>
#include <SDL_endian.h>
-#include <string>
+#endif
-#include "messageout.h"
-#include "network.h"
+#include <cstring>
+#include <string>
+#ifdef TMWSERV_SUPPORT
+MessageOut::MessageOut(short id):
+ mData(0),
+#else
MessageOut::MessageOut(Network *network):
mNetwork(network),
- mData(0),
+#endif
mDataSize(0),
mPos(0)
{
+#ifdef TMWSERV_SUPPORT
+ writeInt16(id);
+#else
mData = mNetwork->mOutBuffer + mNetwork->mOutSize;
+#endif
+}
+
+#ifdef TMWSERV_SUPPORT
+MessageOut::~MessageOut()
+{
+ free(mData);
+}
+
+void MessageOut::expand(size_t bytes)
+{
+ mData = (char*)realloc(mData, bytes);
+ mDataSize = bytes;
}
+#endif
void MessageOut::writeInt8(Sint8 value)
{
+#ifdef TMWSERV_SUPPORT
+ expand(mPos + 1);
+#else
+ mNetwork->mOutSize += 1;
+#endif
mData[mPos] = value;
- mPos += sizeof(Sint8);
- mNetwork->mOutSize+= sizeof(Sint8);
+ mPos += 1;
}
void MessageOut::writeInt16(Sint16 value)
{
+#ifdef TMWSERV_SUPPORT
+ expand(mPos + 2);
+ uint16_t t = ENET_HOST_TO_NET_16(value);
+ memcpy(mData + mPos, &t, 2);
+#else
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
(*(Sint16 *)(mData + mPos)) = SDL_Swap16(value);
#else
(*(Sint16 *)(mData + mPos)) = value;
#endif
- mPos += sizeof(Sint16);
- mNetwork->mOutSize += sizeof(Sint16);
+ mNetwork->mOutSize += 2;
+#endif // TMWSERV_SUPPORT
+ mPos += 2;
}
void MessageOut::writeInt32(Sint32 value)
{
+#ifdef TMWSERV_SUPPORT
+ expand(mPos + 4);
+ uint32_t t = ENET_HOST_TO_NET_32(value);
+ memcpy(mData + mPos, &t, 4);
+#else
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
(*(Sint32 *)(mData + mPos)) = SDL_Swap32(value);
#else
(*(Sint32 *)(mData + mPos)) = value;
#endif
- mPos += sizeof(Sint32);
- mNetwork->mOutSize += sizeof(Sint32);
+ mNetwork->mOutSize += 4;
+#endif // TMWSERV_SUPPORT
+ mPos += 4;
}
void MessageOut::writeString(const std::string &string, int length)
{
- std::string toWrite = string;
-
+ int stringLength = string.length();
if (length < 0)
{
// Write the length at the start if not fixed
- writeInt16(string.length());
+ writeInt16(stringLength);
+ length = stringLength;
}
- else
+ else if (length < stringLength)
{
// Make sure the length of the string is no longer than specified
- toWrite = string.substr(0, length);
+ stringLength = length;
}
+#ifdef TMWSERV_SUPPORT
+ expand(mPos + length);
+#else
+ mNetwork->mOutSize += length;
+#endif
// Write the actual string
- memcpy(&mData[mPos], (void*)toWrite.c_str(), toWrite.length());
- mPos += toWrite.length();
- mNetwork->mOutSize += toWrite.length();
+ memcpy(mData + mPos, string.c_str(), stringLength);
// Pad remaining space with zeros
- if (length > (int)toWrite.length())
+ if (length > stringLength)
{
- memset(&mData[mPos], '\0', length - toWrite.length());
- mPos += length - toWrite.length();
- mNetwork->mOutSize += length - toWrite.length();
+ memset(mData + mPos + stringLength, '\0', length - stringLength);
}
+ mPos += length;
}
-MessageOut& operator<<(MessageOut &msg, const Sint8 &rhs)
-{
- msg.writeInt8(rhs);
- return msg;
-}
-
-MessageOut& operator<<(MessageOut &msg, const Sint16 &rhs)
+char *MessageOut::getData() const
{
- msg.writeInt16(rhs);
- return msg;
+ return mData;
}
-MessageOut& operator<<(MessageOut &msg, const Sint32 &rhs)
+unsigned int MessageOut::getDataSize() const
{
- msg.writeInt32(rhs);
- return msg;
+ return mDataSize;
}
diff --git a/src/net/messageout.h b/src/net/messageout.h
index b3a4ef68..bc701b92 100644
--- a/src/net/messageout.h
+++ b/src/net/messageout.h
@@ -25,26 +25,38 @@
#include <iosfwd>
#include <SDL_types.h>
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
/**
* Used for building an outgoing message.
+ *
+ * With tmwserv, the message is sent using Net::Connection::send() when
+ * finished.
+ *
+ * \ingroup Network
*/
class MessageOut
{
- friend MessageOut& operator<<(MessageOut &msg, const Sint8 &rhs);
- friend MessageOut& operator<<(MessageOut &msg, const Sint16 &rhs);
- friend MessageOut& operator<<(MessageOut &msg, const Sint32 &rhs);
-
public:
/**
* Constructor.
*/
+#ifdef TMWSERV_SUPPORT
+ MessageOut(short id);
+
+ /**
+ * Destructor.
+ */
+ ~MessageOut();
+#else
MessageOut(Network *network);
+#endif
void writeInt8(Sint8 value); /**< Writes a byte. */
void writeInt16(Sint16 value); /**< Writes a short. */
- void writeInt32(Sint32 value); /**< Writes a long. */
+ void writeInt32(Sint32 value); /**< Writes a long. */
/**
* Writes a string. If a fixed length is not given (-1), it is stored
@@ -52,8 +64,29 @@ class MessageOut
*/
void writeString(const std::string &string, int length = -1);
+ /**
+ * Returns the content of the message.
+ */
+ char *getData() const;
+
+ /**
+ * Returns the length of the data.
+ */
+ unsigned int getDataSize() const;
+
private:
+#ifdef TMWSERV_SUPPORT
+ /**
+ * Expand the packet data to be able to hold more data.
+ *
+ * NOTE: For performance enhancements this method could allocate extra
+ * memory in advance instead of expanding size every time more data is
+ * added.
+ */
+ void expand(size_t size);
+#else
Network *mNetwork;
+#endif
char *mData; /**< Data building up. */
unsigned int mDataSize; /**< Size of data. */
diff --git a/src/net/network.cpp b/src/net/network.cpp
index 3fa046c4..57e368e2 100644
--- a/src/net/network.cpp
+++ b/src/net/network.cpp
@@ -1,436 +1,169 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include <sstream>
-
-#include "messagehandler.h"
-#include "messagein.h"
#include "network.h"
-#include "../log.h"
-#include "../utils/stringutils.h"
-
-/** Warning: buffers and other variables are shared,
- so there can be only one connection active at a time */
-
-short packet_lengths[] = {
- 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-// #0x0040
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, -1, 55, 17, 3, 37, 46, -1, 23, -1, 3,108, 3, 2,
- 3, 28, 19, 11, 3, -1, 9, 5, 54, 53, 58, 60, 41, 2, 6, 6,
-// #0x0080
- 7, 3, 2, 2, 2, 5, 16, 12, 10, 7, 29, 23, -1, -1, -1, 0,
- 7, 22, 28, 2, 6, 30, -1, -1, 3, -1, -1, 5, 9, 17, 17, 6,
- 23, 6, 6, -1, -1, -1, -1, 8, 7, 6, 7, 4, 7, 0, -1, 6,
- 8, 8, 3, 3, -1, 6, 6, -1, 7, 6, 2, 5, 6, 44, 5, 3,
-// #0x00C0
- 7, 2, 6, 8, 6, 7, -1, -1, -1, -1, 3, 3, 6, 6, 2, 27,
- 3, 4, 4, 2, -1, -1, 3, -1, 6, 14, 3, -1, 28, 29, -1, -1,
- 30, 30, 26, 2, 6, 26, 3, 3, 8, 19, 5, 2, 3, 2, 2, 2,
- 3, 2, 6, 8, 21, 8, 8, 2, 2, 26, 3, -1, 6, 27, 30, 10,
-// #0x0100
- 2, 6, 6, 30, 79, 31, 10, 10, -1, -1, 4, 6, 6, 2, 11, -1,
- 10, 39, 4, 10, 31, 35, 10, 18, 2, 13, 15, 20, 68, 2, 3, 16,
- 6, 14, -1, -1, 21, 8, 8, 8, 8, 8, 2, 2, 3, 4, 2, -1,
- 6, 86, 6, -1, -1, 7, -1, 6, 3, 16, 4, 4, 4, 6, 24, 26,
-// #0x0140
- 22, 14, 6, 10, 23, 19, 6, 39, 8, 9, 6, 27, -1, 2, 6, 6,
- 110, 6, -1, -1, -1, -1, -1, 6, -1, 54, 66, 54, 90, 42, 6, 42,
- -1, -1, -1, -1, -1, 30, -1, 3, 14, 3, 30, 10, 43, 14,186,182,
- 14, 30, 10, 3, -1, 6,106, -1, 4, 5, 4, -1, 6, 7, -1, -1,
-// #0x0180
- 6, 3,106, 10, 10, 34, 0, 6, 8, 4, 4, 4, 29, -1, 10, 6,
- 90, 86, 24, 6, 30,102, 9, 4, 8, 4, 14, 10, 4, 6, 2, 6,
- 3, 3, 35, 5, 11, 26, -1, 4, 4, 6, 10, 12, 6, -1, 4, 4,
- 11, 7, -1, 67, 12, 18,114, 6, 3, 6, 26, 26, 26, 26, 2, 3,
-// #0x01C0
- 2, 14, 10, -1, 22, 22, 4, 2, 13, 97, 0, 9, 9, 29, 6, 28,
- 8, 14, 10, 35, 6, 8, 4, 11, 54, 53, 60, 2, -1, 47, 33, 6,
- 30, 8, 34, 14, 2, 6, 26, 2, 28, 81, 6, 10, 26, 2, -1, -1,
- -1, -1, 20, 10, 32, 9, 34, 14, 2, 6, 48, 56, -1, 4, 5, 10,
-// #0x200
- 26, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-};
-
-const unsigned int BUFFER_SIZE = 65536;
+#include <enet/enet.h>
-int networkThread(void *data)
-{
- Network *network = static_cast<Network*>(data);
-
- if (!network->realConnect())
- return -1;
+#include <map>
- network->receive();
+#include "connection.h"
+#include "internal.h"
+#include "messagehandler.h"
+#include "messagein.h"
- return 0;
-}
+#include "../log.h"
-Network::Network():
- mSocket(0),
- mAddress(), mPort(0),
- mInBuffer(new char[BUFFER_SIZE]),
- mOutBuffer(new char[BUFFER_SIZE]),
- mInSize(0), mOutSize(0),
- mToSkip(0),
- mState(IDLE),
- mWorkerThread(0)
-{
- mMutex = SDL_CreateMutex();
+/**
+ * The local host which is shared for all outgoing connections.
+ */
+namespace {
+ ENetHost *client;
}
-Network::~Network()
-{
- clearHandlers();
-
- if (mState != IDLE && mState != NET_ERROR)
- disconnect();
-
- SDL_DestroyMutex(mMutex);
-
- delete[] mInBuffer;
- delete[] mOutBuffer;
-}
+typedef std::map<unsigned short, MessageHandler*> MessageHandlers;
+typedef MessageHandlers::iterator MessageHandlerIterator;
+static MessageHandlers mMessageHandlers;
-bool Network::connect(const std::string &address, short port)
+void Net::initialize()
{
- if (mState != IDLE && mState != NET_ERROR)
+ if (enet_initialize())
{
- logger->log("Tried to connect an already connected socket!");
- return false;
+ logger->error("Failed to initialize ENet.");
}
- if (address.empty())
+ client = enet_host_create(NULL, 3, 0, 0);
+
+ if (!client)
{
- setError("Empty address given to Network::connect()!");
- return false;
+ logger->error("Failed to create the local host.");
}
+}
- logger->log("Network::Connecting to %s:%i", address.c_str(), port);
-
- mAddress = address;
- mPort = port;
-
- // Reset to sane values
- mOutSize = 0;
- mInSize = 0;
- mToSkip = 0;
+void Net::finalize()
+{
+ if (!client)
+ return; // Wasn't initialized at all
- mState = CONNECTING;
- mWorkerThread = SDL_CreateThread(networkThread, this);
- if (!mWorkerThread)
- {
- setError("Unable to create network worker thread");
- return false;
+ if (Net::connections) {
+ logger->error("Tried to shutdown the network subsystem while there "
+ "are network connections left!");
}
- return true;
+ clearHandlers();
+ enet_deinitialize();
}
-void Network::disconnect()
+Net::Connection *Net::getConnection()
{
- mState = IDLE;
-
- if (mWorkerThread)
+ if (!client)
{
- SDL_WaitThread(mWorkerThread, NULL);
- mWorkerThread = NULL;
+ logger->error("Tried to instantiate a network object before "
+ "initializing the network subsystem!");
}
- if (mSocket)
- {
- SDLNet_TCP_Close(mSocket);
- mSocket = 0;
- }
+ return new Net::Connection(client);
}
-void Network::registerHandler(MessageHandler *handler)
+void Net::registerHandler(MessageHandler *handler)
{
for (const Uint16 *i = handler->handledMessages; *i; i++)
{
mMessageHandlers[*i] = handler;
}
-
- handler->setNetwork(this);
}
-void Network::unregisterHandler(MessageHandler *handler)
+void Net::unregisterHandler(MessageHandler *handler)
{
for (const Uint16 *i = handler->handledMessages; *i; i++)
{
mMessageHandlers.erase(*i);
}
-
- handler->setNetwork(0);
}
-void Network::clearHandlers()
+void Net::clearHandlers()
{
- MessageHandlerIterator i;
- for (i = mMessageHandlers.begin(); i != mMessageHandlers.end(); i++)
- {
- i->second->setNetwork(0);
- }
mMessageHandlers.clear();
}
-void Network::dispatchMessages()
-{
- while (messageReady())
- {
- MessageIn msg = getNextMessage();
-
- MessageHandlerIterator iter = mMessageHandlers.find(msg.getId());
-
- if (iter != mMessageHandlers.end())
- iter->second->handleMessage(&msg);
- else
- logger->log("Unhandled packet: %x", msg.getId());
-
- skip(msg.getLength());
- }
-}
-
-void Network::flush()
-{
- if (!mOutSize || mState != CONNECTED)
- return;
-
- int ret;
-
-
- SDL_mutexP(mMutex);
- ret = SDLNet_TCP_Send(mSocket, mOutBuffer, mOutSize);
- if (ret < (int)mOutSize)
- {
- setError("Error in SDLNet_TCP_Send(): " +
- std::string(SDLNet_GetError()));
- }
- mOutSize = 0;
- SDL_mutexV(mMutex);
-}
-
-void Network::skip(int len)
-{
- SDL_mutexP(mMutex);
- mToSkip += len;
- if (!mInSize)
- {
- SDL_mutexV(mMutex);
- return;
- }
- if (mInSize >= mToSkip)
- {
- mInSize -= mToSkip;
- memmove(mInBuffer, mInBuffer + mToSkip, mInSize);
- mToSkip = 0;
- }
- else
- {
- mToSkip -= mInSize;
- mInSize = 0;
- }
- SDL_mutexV(mMutex);
-}
-
-bool Network::messageReady()
-{
- int len = -1;
-
- SDL_mutexP(mMutex);
- if (mInSize >= 2)
- {
- len = packet_lengths[readWord(0)];
-
- if (len == -1 && mInSize > 4)
- len = readWord(2);
-
- }
-
- bool ret = (mInSize >= static_cast<unsigned int>(len));
- SDL_mutexV(mMutex);
-
- return ret;
-}
-
-MessageIn Network::getNextMessage()
+/**
+ * Dispatches a message to the appropriate message handler and
+ * destroys it afterwards.
+ */
+namespace
{
- while (!messageReady())
+ void dispatchMessage(ENetPacket *packet)
{
- if (mState == NET_ERROR)
- break;
- }
-
- SDL_mutexP(mMutex);
- int msgId = readWord(0);
- int len = packet_lengths[msgId];
-
- if (len == -1)
- len = readWord(2);
-
-#ifdef DEBUG
- logger->log("Received packet 0x%x of length %d", msgId, len);
-#endif
+ MessageIn msg((const char *)packet->data, packet->dataLength);
- MessageIn msg(mInBuffer, len);
- SDL_mutexV(mMutex);
-
- return msg;
-}
-
-bool Network::realConnect()
-{
- IPaddress ipAddress;
-
- if (SDLNet_ResolveHost(&ipAddress, mAddress.c_str(), mPort) == -1)
- {
- std::string error = "Unable to resolve host \"" + mAddress + "\"";
- setError(error);
- logger->log("SDLNet_ResolveHost: %s", error.c_str());
- return false;
- }
+ MessageHandlerIterator iter = mMessageHandlers.find(msg.getId());
- mState = CONNECTING;
+ if (iter != mMessageHandlers.end()) {
+ //logger->log("Received packet %x (%i B)",
+ // msg.getId(), msg.getLength());
+ iter->second->handleMessage(msg);
+ }
+ else {
+ logger->log("Unhandled packet %x (%i B)",
+ msg.getId(), msg.getLength());
+ }
- mSocket = SDLNet_TCP_Open(&ipAddress);
- if (!mSocket)
- {
- logger->log("Error in SDLNet_TCP_Open(): %s", SDLNet_GetError());
- setError(SDLNet_GetError());
- return false;
+ // Clean up the packet now that we're done using it.
+ enet_packet_destroy(packet);
}
-
- logger->log("Network::Started session with %s:%i",
- ipToString(ipAddress.host), ipAddress.port);
-
- mState = CONNECTED;
-
- return true;
}
-void Network::receive()
+void Net::flush()
{
- SDLNet_SocketSet set;
-
- if (!(set = SDLNet_AllocSocketSet(1)))
- {
- setError("Error in SDLNet_AllocSocketSet(): " +
- std::string(SDLNet_GetError()));
- return;
- }
-
- if (SDLNet_TCP_AddSocket(set, mSocket) == -1)
- {
- setError("Error in SDLNet_AddSocket(): " +
- std::string(SDLNet_GetError()));
- }
+ ENetEvent event;
- while (mState == CONNECTED)
+ // Wait up to 10 milliseconds for an event.
+ while (enet_host_service(client, &event, 10) > 0)
{
- // TODO Try to get this to block all the time while still being able
- // to escape the loop
- int numReady = SDLNet_CheckSockets(set, ((Uint32)500));
- int ret;
- switch (numReady)
+ switch (event.type)
{
- case -1:
- logger->log("Error: SDLNet_CheckSockets");
- // FALLTHROUGH
- case 0:
+ case ENET_EVENT_TYPE_CONNECT:
+ logger->log("Connected to port %d.", event.peer->address.port);
+ // Store any relevant server information here.
+ event.peer->data = 0;
break;
- case 1:
- // Receive data from the socket
- SDL_mutexP(mMutex);
- ret = SDLNet_TCP_Recv(mSocket, mInBuffer + mInSize, BUFFER_SIZE - mInSize);
+ case ENET_EVENT_TYPE_RECEIVE:
+ dispatchMessage(event.packet);
+ break;
+
+ case ENET_EVENT_TYPE_DISCONNECT:
+ logger->log("Disconnected.");
+ // Reset the server information.
+ event.peer->data = 0;
+ break;
- if (!ret)
- {
- // We got disconnected
- mState = IDLE;
- logger->log("Disconnected.");
- }
- else if (ret < 0)
- {
- setError("Error in SDLNet_TCP_Recv(): " +
- std::string(SDLNet_GetError()));
- }
- else {
- mInSize += ret;
- if (mToSkip)
- {
- if (mInSize >= mToSkip)
- {
- mInSize -= mToSkip;
- memmove(mInBuffer, mInBuffer + mToSkip, mInSize);
- mToSkip = 0;
- }
- else
- {
- mToSkip -= mInSize;
- mInSize = 0;
- }
- }
- }
- SDL_mutexV(mMutex);
+ case ENET_EVENT_TYPE_NONE:
+ logger->log("No event during 10 milliseconds.");
break;
default:
- // more than one socket is ready..
- // this should not happen since we only listen once socket.
- std::stringstream errorStream;
- errorStream << "Error in SDLNet_TCP_Recv(), " << numReady
- << " sockets are ready: " << SDLNet_GetError();
- setError(errorStream.str());
+ logger->log("Unhandled enet event.");
break;
}
}
-
- if (SDLNet_TCP_DelSocket(set, mSocket) == -1)
- {
- logger->log("Error in SDLNet_DelSocket(): %s", SDLNet_GetError());
- }
-
- SDLNet_FreeSocketSet(set);
-}
-
-void Network::setError(const std::string& error)
-{
- logger->log("Network error: %s", error.c_str());
- mError = error;
- mState = NET_ERROR;
-}
-
-Uint16 Network::readWord(int pos)
-{
-#if SDL_BYTEORDER == SDL_BIG_ENDIAN
- return SDL_Swap16((*(Uint16*)(mInBuffer+(pos))));
-#else
- return (*(Uint16*)(mInBuffer+(pos)));
-#endif
}
diff --git a/src/net/network.h b/src/net/network.h
index 02fe7538..13576e79 100644
--- a/src/net/network.h
+++ b/src/net/network.h
@@ -1,118 +1,79 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#ifndef NETWORK_
-#define NETWORK_
+#ifndef _TMW_NET_NETWORK_H
+#define _TMW_NET_NETWORK_H
-#include <map>
-#include <SDL_net.h>
-#include <SDL_thread.h>
-#include <string>
+#include <iosfwd>
/**
- * Protocol version, reported to the eAthena char and mapserver who can adjust
- * the protocol accordingly.
+ * \defgroup Network Core network layer
*/
-#define CLIENT_PROTOCOL_VERSION 1
class MessageHandler;
-class MessageIn;
+class MessageOut;
-class Network;
-
-class Network
+/**
+ * \ingroup Network
+ */
+namespace Net
{
- public:
- friend int networkThread(void *data);
- friend class MessageOut;
-
- Network();
-
- ~Network();
-
- bool connect(const std::string &address, short port);
-
- void disconnect();
-
- void registerHandler(MessageHandler *handler);
-
- void unregisterHandler(MessageHandler *handler);
-
- void clearHandlers();
-
- int getState() const { return mState; }
-
- const std::string& getError() const { return mError; }
-
- bool isConnected() const { return mState == CONNECTED; }
-
- int getInSize() const { return mInSize; }
-
- void skip(int len);
-
- bool messageReady();
-
- MessageIn getNextMessage();
-
- void dispatchMessages();
-
- void flush();
-
- // ERROR replaced by NET_ERROR because already defined in Windows
- enum {
- IDLE,
- CONNECTED,
- CONNECTING,
- DATA,
- NET_ERROR
- };
-
- protected:
- void setError(const std::string& error);
-
- Uint16 readWord(int pos);
-
- bool realConnect();
-
- void receive();
-
- TCPsocket mSocket;
-
- std::string mAddress;
- short mPort;
-
- char *mInBuffer, *mOutBuffer;
- unsigned int mInSize, mOutSize;
-
- unsigned int mToSkip;
-
- int mState;
- std::string mError;
-
- SDL_Thread *mWorkerThread;
- SDL_mutex *mMutex;
-
- typedef std::map<Uint16, MessageHandler*> MessageHandlers;
- typedef MessageHandlers::iterator MessageHandlerIterator;
- MessageHandlers mMessageHandlers;
-};
+ class Connection;
+
+ /**
+ * Initializes the network subsystem.
+ */
+ void initialize();
+
+ /**
+ * Finalizes the network subsystem.
+ */
+ void finalize();
+
+ /**
+ * Returns a new Connection object. Should be deleted by the caller.
+ */
+ Connection *getConnection();
+
+ /**
+ * Registers a message handler. A message handler handles a certain
+ * subset of incoming messages.
+ */
+ void registerHandler(MessageHandler *handler);
+
+ /**
+ * Unregisters a message handler.
+ */
+ void unregisterHandler(MessageHandler *handler);
+
+ /**
+ * Clears all registered message handlers.
+ */
+ void clearHandlers();
+
+ /*
+ * Handles all events and dispatches incoming messages to the
+ * registered handlers
+ */
+ void flush();
+}
#endif
diff --git a/src/net/npchandler.cpp b/src/net/npchandler.cpp
index a6dc216b..30507537 100644
--- a/src/net/npchandler.cpp
+++ b/src/net/npchandler.cpp
@@ -1,111 +1,86 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include "messagein.h"
#include "npchandler.h"
+
+#include "messagein.h"
#include "protocol.h"
#include "../beingmanager.h"
-#include "../localplayer.h"
#include "../npc.h"
-#include "../gui/npc_text.h"
-#include "../gui/npcintegerdialog.h"
#include "../gui/npclistdialog.h"
-#include "../gui/npcstringdialog.h"
+#include "../gui/npcpostdialog.h"
+#include "../gui/npc_text.h"
-extern NpcIntegerDialog *npcIntegerDialog;
extern NpcListDialog *npcListDialog;
extern NpcTextDialog *npcTextDialog;
-extern NpcStringDialog *npcStringDialog;
+extern NpcPostDialog *npcPostDialog;
NPCHandler::NPCHandler()
{
static const Uint16 _messages[] = {
- SMSG_NPC_CHOICE,
- SMSG_NPC_MESSAGE,
- SMSG_NPC_NEXT,
- SMSG_NPC_CLOSE,
- SMSG_NPC_INT_INPUT,
- SMSG_NPC_STR_INPUT,
+ GPMSG_NPC_CHOICE,
+ GPMSG_NPC_POST,
+ GPMSG_NPC_MESSAGE,
+ GPMSG_NPC_ERROR,
0
};
handledMessages = _messages;
}
-void NPCHandler::handleMessage(MessageIn *msg)
+void NPCHandler::handleMessage(MessageIn &msg)
{
- int id;
-
- switch (msg->getId())
+ Being *being = beingManager->findBeing(msg.readInt16());
+ if (!being || being->getType() != Being::NPC)
{
- case SMSG_NPC_CHOICE:
- msg->readInt16(); // length
- id = msg->readInt32();
- player_node->setAction(LocalPlayer::STAND);
- current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
- npcListDialog->parseItems(msg->readString(msg->getLength() - 8));
- npcListDialog->setVisible(true);
- break;
-
- case SMSG_NPC_MESSAGE:
- msg->readInt16(); // length
- id = msg->readInt32();
- player_node->setAction(LocalPlayer::STAND);
- current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
- npcTextDialog->addText(msg->readString(msg->getLength() - 8));
- npcListDialog->setVisible(false);
- npcTextDialog->setVisible(true);
- break;
+ return;
+ }
- case SMSG_NPC_CLOSE:
- id = msg->readInt32();
- current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
- npcTextDialog->showCloseButton();
- break;
+ current_npc = static_cast< NPC * >(being);
- case SMSG_NPC_NEXT:
- // Next button in NPC dialog, currently unused
- id = msg->readInt32();
- current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
- npcTextDialog->showNextButton();
+ switch (msg.getId())
+ {
+ case GPMSG_NPC_CHOICE:
+ npcListDialog->reset();
+ while (msg.getUnreadLength())
+ {
+ npcListDialog->addItem(msg.readString());
+ }
+ npcListDialog->setVisible(true);
break;
- case SMSG_NPC_INT_INPUT:
- // Request for an integer
- id = msg->readInt32();
- current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
- npcIntegerDialog->setRange(0, 2147483647);
- npcIntegerDialog->setDefaultValue(0);
- npcIntegerDialog->setVisible(true);
- npcIntegerDialog->requestFocus();
+ case GPMSG_NPC_POST:
+ npcTextDialog->setVisible(false);
+ npcPostDialog->clear();
+ npcPostDialog->setVisible(true);
break;
- case SMSG_NPC_STR_INPUT:
- // Request for a string
- id = msg->readInt32();
- current_npc = dynamic_cast<NPC*>(beingManager->findBeing(id));
- npcStringDialog->setValue("");
- npcStringDialog->setVisible(true);
- npcStringDialog->requestFocus();
+ case GPMSG_NPC_ERROR:
+ current_npc = NULL;
+ case GPMSG_NPC_MESSAGE:
+ npcTextDialog->addText(msg.readString(msg.getUnreadLength()));
+ npcListDialog->setVisible(false);
+ npcTextDialog->setVisible(true);
+ npcPostDialog->setVisible(false);
break;
}
}
diff --git a/src/net/npchandler.h b/src/net/npchandler.h
index 7ac962eb..18ab0a05 100644
--- a/src/net/npchandler.h
+++ b/src/net/npchandler.h
@@ -29,7 +29,7 @@ class NPCHandler : public MessageHandler
public:
NPCHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/partyhandler.cpp b/src/net/partyhandler.cpp
index 96200add..60c51821 100644
--- a/src/net/partyhandler.cpp
+++ b/src/net/partyhandler.cpp
@@ -1,122 +1,103 @@
/*
* The Mana World
- * Copyright (C) 2008 Lloyd Bryant <lloyd_bryant@netzero.net>
+ * Copyright 2008 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include <guichan/actionlistener.hpp>
-
+#include <iostream>
#include "partyhandler.h"
+
#include "protocol.h"
#include "messagein.h"
-#include "../gui/chat.h"
-#include "../gui/confirm_dialog.h"
+#include "chatserver/chatserver.h"
-#include "../beingmanager.h"
-#include "../party.h"
+#include "../gui/chat.h"
+#include "../gui/partywindow.h"
+#include "../log.h"
+#include "../localplayer.h"
-PartyHandler::PartyHandler(Party *party) : mParty(party)
+PartyHandler::PartyHandler()
{
static const Uint16 _messages[] = {
- SMSG_PARTY_CREATE,
- SMSG_PARTY_INFO,
- SMSG_PARTY_INVITE,
- SMSG_PARTY_INVITED,
- SMSG_PARTY_SETTINGS,
- SMSG_PARTY_MEMBER_INFO,
- SMSG_PARTY_LEAVE,
- SMSG_PARTY_UPDATE_HP,
- SMSG_PARTY_UPDATE_COORDS,
- SMSG_PARTY_MESSAGE,
+ CPMSG_PARTY_INVITE_RESPONSE,
+ CPMSG_PARTY_INVITED,
+ CPMSG_PARTY_ACCEPT_INVITE_RESPONSE,
+ CPMSG_PARTY_QUIT_RESPONSE,
+ CPMSG_PARTY_NEW_MEMBER,
+ CPMSG_PARTY_MEMBER_LEFT,
0
};
handledMessages = _messages;
+
}
-void PartyHandler::handleMessage(MessageIn *msg)
+void PartyHandler::handleMessage(MessageIn &msg)
{
- switch (msg->getId())
+ switch (msg.getId())
{
- case SMSG_PARTY_CREATE:
- mParty->createResponse(msg->readInt8());
- break;
- case SMSG_PARTY_INFO:
- break;
- case SMSG_PARTY_INVITE:
+ case CPMSG_PARTY_INVITE_RESPONSE:
+ {
+ if (msg.readInt8() == ERRMSG_OK)
{
- std::string nick = msg->readString(24);
- int status = msg->readInt8();
- mParty->inviteResponse(nick, status);
- break;
+
}
- case SMSG_PARTY_INVITED:
+ } break;
+
+ case CPMSG_PARTY_INVITED:
+ {
+ std::string inviter = msg.readString();
+ partyWindow->showPartyInvite(inviter);
+ } break;
+
+ case CPMSG_PARTY_ACCEPT_INVITE_RESPONSE:
+ {
+ if (msg.readInt8() == ERRMSG_OK)
{
- int id = msg->readInt32();
- Being *being = beingManager->findBeing(id);
- if (!being)
- {
- break;
- }
- std::string nick;
- int gender = 0;
- std::string partyName = "";
- if (being->getType() != Being::PLAYER)
- {
- nick = "";
- }
- else
- {
- nick = being->getName();
- gender = being->getGender();
- partyName = msg->readString(24);
- }
- mParty->invitedAsk(nick, gender, partyName);
- break;
+ player_node->setInParty(true);
+ chatWindow->chatLog("Joined party");
}
- case SMSG_PARTY_SETTINGS:
- break;
- case SMSG_PARTY_MEMBER_INFO:
- break;
- case SMSG_PARTY_LEAVE:
+ }
+
+ case CPMSG_PARTY_QUIT_RESPONSE:
+ {
+ if (msg.readInt8() == ERRMSG_OK)
{
- /*int id = */msg->readInt32();
- std::string nick = msg->readString(24);
- /*int fail = */msg->readInt8();
- mParty->leftResponse(nick);
- break;
- }
- case SMSG_PARTY_UPDATE_HP:
- break;
- case SMSG_PARTY_UPDATE_COORDS:
- break;
- case SMSG_PARTY_MESSAGE:
- { // new block to enable local variables
- int msgLength = msg->readInt16() - 8;
- if (msgLength <= 0)
- {
- return;
- }
- int id = msg->readInt32();
- Being *being = beingManager->findBeing(id);
- std::string chatMsg = msg->readString(msgLength);
- mParty->receiveChat(being, chatMsg);
+ player_node->setInParty(false);
}
- break;
+ } break;
+
+ case CPMSG_PARTY_NEW_MEMBER:
+ {
+ msg.readInt16(); // being id
+ std::string name = msg.readString();
+
+ chatWindow->chatLog(name + " joined the party");
+
+ if (!player_node->getInParty())
+ player_node->setInParty(true);
+
+ partyWindow->addPartyMember(name);
+ } break;
+
+ case CPMSG_PARTY_MEMBER_LEFT:
+ {
+ partyWindow->removePartyMember(msg.readString());
+ } break;
}
}
diff --git a/src/net/partyhandler.h b/src/net/partyhandler.h
index fc02bf0a..b4257c34 100644
--- a/src/net/partyhandler.h
+++ b/src/net/partyhandler.h
@@ -1,39 +1,41 @@
/*
* The Mana World
- * Copyright (C) 2008 Lloyd Bryant <lloyd_bryant@netzero.net>
+ * Copyright 2008 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#ifndef PARTYHANDLER_H
-#define PARTYHANDLER_H
+#ifndef _TMW_NET_PARTYHANDLER_H
+#define _TMW_NET_PARTYHANDLER_H
#include "messagehandler.h"
-class Party;
+#include <string>
class PartyHandler : public MessageHandler
{
- public:
- PartyHandler(Party *party);
+public:
+ PartyHandler();
+
+ void handleMessage(MessageIn &msg);
+
+protected:
- void handleMessage(MessageIn *msg);
- private:
- Party *mParty;
};
#endif
+
diff --git a/src/net/playerhandler.cpp b/src/net/playerhandler.cpp
index fc3506fb..b4e2f328 100644
--- a/src/net/playerhandler.cpp
+++ b/src/net/playerhandler.cpp
@@ -1,33 +1,34 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#include "messagein.h"
#include "playerhandler.h"
+
+#include "messagein.h"
#include "protocol.h"
#include "../engine.h"
#include "../localplayer.h"
#include "../log.h"
+#include "../particle.h"
#include "../npc.h"
-#include "../units.h"
#include "../gui/buy.h"
#include "../gui/chat.h"
@@ -39,9 +40,6 @@
#include "../gui/skill.h"
#include "../gui/viewport.h"
-#include "../utils/stringutils.h"
-#include "../utils/gettext.h"
-
// TODO Move somewhere else
OkDialog *weightNotice = NULL;
OkDialog *deathNotice = NULL;
@@ -52,9 +50,10 @@ extern BuyDialog *buyDialog;
extern SellDialog *sellDialog;
extern Window *buySellDialog;
-// Max. distance we are willing to scroll after a teleport;
-// everything beyond will reset the port hard.
-static const int MAP_TELEPORT_SCROLL_DISTANCE = 8;
+/* Max. distance we are willing to scroll after a teleport;
+ * everything beyond will reset the port hard.
+ */
+static const int MAP_TELEPORT_SCROLL_DISTANCE = 8 * 32;
/**
* Listener used for handling the overweigth message.
@@ -86,7 +85,7 @@ namespace {
buyDialog->setVisible(false);
sellDialog->setVisible(false);
buySellDialog->setVisible(false);
- if (current_npc) current_npc->handleDeath();
+ current_npc = 0;
}
} deathListener;
}
@@ -94,317 +93,192 @@ namespace {
PlayerHandler::PlayerHandler()
{
static const Uint16 _messages[] = {
- SMSG_WALK_RESPONSE,
- SMSG_PLAYER_WARP,
- SMSG_PLAYER_STAT_UPDATE_1,
- SMSG_PLAYER_STAT_UPDATE_2,
- SMSG_PLAYER_STAT_UPDATE_3,
- SMSG_PLAYER_STAT_UPDATE_4,
- SMSG_PLAYER_STAT_UPDATE_5,
- SMSG_PLAYER_STAT_UPDATE_6,
- SMSG_PLAYER_ARROW_MESSAGE,
+ GPMSG_PLAYER_MAP_CHANGE,
+ GPMSG_PLAYER_SERVER_CHANGE,
+ GPMSG_PLAYER_ATTRIBUTE_CHANGE,
+ GPMSG_PLAYER_EXP_CHANGE,
+ GPMSG_LEVELUP,
+ GPMSG_LEVEL_PROGRESS,
+ GPMSG_RAISE_ATTRIBUTE_RESPONSE,
+ GPMSG_LOWER_ATTRIBUTE_RESPONSE,
0
};
handledMessages = _messages;
}
-void PlayerHandler::handleMessage(MessageIn *msg)
+void PlayerHandler::handleMessage(MessageIn &msg)
{
- switch (msg->getId())
+ switch (msg.getId())
{
- case SMSG_WALK_RESPONSE:
- /*
- * This client assumes that all walk messages succeed,
- * and that the server will send a correction notice
- * otherwise.
- */
+ case GPMSG_PLAYER_MAP_CHANGE:
+ handleMapChangeMessage(msg);
break;
- case SMSG_PLAYER_WARP:
- {
- std::string mapPath = msg->readString(16);
- bool nearby;
- Uint16 x = msg->readInt16();
- Uint16 y = msg->readInt16();
-
- logger->log("Warping to %s (%d, %d)", mapPath.c_str(), x, y);
-
- /*
- * We must clear the local player's target *before* the call
- * to changeMap, as it deletes all beings.
- */
- player_node->stopAttack();
-
- nearby = (engine->getCurrentMapName() == mapPath);
-
- // Switch the actual map, deleting the previous one if necessary
- engine->changeMap(mapPath);
+ case GPMSG_PLAYER_SERVER_CHANGE:
+ { // TODO: Implement reconnecting to another game server
+ std::string token = msg.readString(32);
+ std::string address = msg.readString();
+ int port = msg.readInt16();
+ logger->log("Changing server to %s:%d", address.c_str(), port);
+ } break;
- if (current_npc) current_npc->handleDeath();
-
- float scrollOffsetX = 0.0f;
- float scrollOffsetY = 0.0f;
+ case GPMSG_PLAYER_ATTRIBUTE_CHANGE:
+ {
+ logger->log("ATTRIBUTE UPDATE:");
+ while (msg.getUnreadLength())
+ {
+ int stat = msg.readInt8();
+ int base = msg.readInt16();
+ int value = msg.readInt16();
+ logger->log("%d set to %d %d", stat, base, value);
- /* Scroll if neccessary */
- if (!nearby
- || (abs(x - player_node->mX) > MAP_TELEPORT_SCROLL_DISTANCE)
- || (abs(y - player_node->mY) > MAP_TELEPORT_SCROLL_DISTANCE))
+ if (stat == BASE_ATTR_HP)
{
- scrollOffsetX = (x - player_node->mX) * 32;
- scrollOffsetY = (y - player_node->mY) * 32;
+ player_node->setMaxHp(base);
+ player_node->setHp(value);
}
+ else if (stat < NB_CHARACTER_ATTRIBUTES)
+ {
+ if (stat >= CHAR_SKILL_BEGIN && stat < CHAR_SKILL_END
+ && player_node->getAttributeBase(stat) < base
+ && player_node->getAttributeBase(stat) > -1)
+ {
+ Particle* effect = particleEngine->addEffect("graphics/particles/skillup.particle.xml", 0, 0);
+ player_node->controlParticle(effect);
+ }
- player_node->setAction(Being::STAND);
- player_node->mFrame = 0;
- player_node->mX = x;
- player_node->mY = y;
-
- logger->log("Adjust scrolling by %d:%d",
- (int)scrollOffsetX,
- (int)scrollOffsetY);
-
- viewport->scrollBy(scrollOffsetX, scrollOffsetY);
+ player_node->setAttributeBase(stat, base);
+ player_node->setAttributeEffective(stat, value);
+ }
+ else
+ {
+ logger->log("Warning: server wants to update unknown "
+ "attribute %d to %d", stat, value);
+ }
}
- break;
+ } break;
- case SMSG_PLAYER_STAT_UPDATE_1:
+ case GPMSG_PLAYER_EXP_CHANGE:
+ {
+ logger->log("EXP Update");
+ while (msg.getUnreadLength())
{
- Sint16 type = msg->readInt16();
- Uint32 value = msg->readInt32();
+ int skill = msg.readInt8();
+ int current = msg.readInt32();
+ int next = msg.readInt32();
- switch (type)
+ if (skill < CHAR_SKILL_NB)
{
- //case 0x0000:
- // player_node->setWalkSpeed(msg->readInt32());
- // break;
- case 0x0005: player_node->mHp = value; break;
- case 0x0006: player_node->mMaxHp = value; break;
- case 0x0007: player_node->mMp = value; break;
- case 0x0008: player_node->mMaxMp = value; break;
- case 0x0009:
- player_node->mStatsPointsToAttribute = value;
- break;
- case 0x000b: player_node->mLevel = value; break;
- case 0x000c:
- player_node->mSkillPoint = value;
- skillDialog->update();
- break;
- case 0x0018:
- if (value >= player_node->mMaxWeight / 2 &&
- player_node->mTotalWeight <
- player_node->mMaxWeight / 2)
- {
- weightNotice = new OkDialog(_("Message"),
- _("You are carrying more than "
- "half your weight. You are "
- "unable to regain health."));
- weightNotice->addActionListener(
- &weightListener);
- }
- player_node->mTotalWeight = value;
- break;
- case 0x0019: player_node->mMaxWeight = value; break;
- case 0x0029: player_node->ATK = value; break;
- case 0x002b: player_node->MATK = value; break;
- case 0x002d: player_node->DEF = value; break;
- case 0x002e: player_node->DEF_BONUS = value; break;
- case 0x002f: player_node->MDEF = value; break;
- case 0x0031: player_node->HIT = value; break;
- case 0x0032: player_node->FLEE = value; break;
- case 0x0035: player_node->mAttackSpeed = value; break;
- case 0x0037: player_node->mJobLevel = value; break;
+ player_node->setExperience(skill, current, next);
}
-
- if (player_node->mHp == 0 && !deathNotice)
+ else
{
- static char const *const deadMsg[] =
- {
- _("You are dead."),
- _("We regret to inform you that your character was "
- "killed in battle."),
- _("You are not that alive anymore."),
- _("The cold hands of the grim reaper are grabbing for "
- "your soul."),
- _("Game Over!"),
- _("Insert coin to continue"),
- _("No, kids. Your character did not really die. It... "
- "err... went to a better place."),
- _("Your plan of breaking your enemies weapon by "
- "bashing it with your throat failed."),
- _("I guess this did not run too well."),
- // NetHack reference:
- _("Do you want your possessions identified?"),
- // Secret of Mana reference:
- _("Sadly, no trace of you was ever found..."),
- // Final Fantasy VI reference:
- _("Annihilated."),
- // Earthbound reference:
- _("Looks like you got your head handed to you."),
- // Leisure Suit Larry 1 reference:
- _("You screwed up again, dump your body down the tubes "
- "and get you another one."),
- // Monty Python references (Dead Parrot sketch mostly):
- _("You're not dead yet. You're just resting."),
- _("You are no more."),
- _("You have ceased to be."),
- _("You've expired and gone to meet your maker."),
- _("You're a stiff."),
- _("Bereft of life, you rest in peace."),
- _("If you weren't so animated, you'd be pushing up the "
- "daisies."),
- _("Your metabolic processes are now history."),
- _("You're off the twig."),
- _("You've kicked the bucket."),
- _("You've shuffled off your mortal coil, run down the "
- "curtain and joined the bleedin' choir invisibile."),
- _("You are an ex-player."),
- _("You're pining for the fjords.")
- };
- std::string message(deadMsg[rand()%27]);
-
- deathNotice = new OkDialog(_("Message"), message);
- deathNotice->addActionListener(&deathListener);
- player_node->setAction(Being::DEAD);
+ logger->log("Warning: server wants to update experience of unknown "
+ "skill %d to %d / %d", skill, current, next);
}
}
- break;
+ } break;
- case SMSG_PLAYER_STAT_UPDATE_2:
- switch (msg->readInt16()) {
- case 0x0001:
- player_node->setXp(msg->readInt32());
- break;
- case 0x0002:
- player_node->mJobXp = msg->readInt32();
- break;
- case 0x0014: {
- Uint32 curGp = player_node->mGp;
- player_node->mGp = msg->readInt32();
- if (player_node->mGp > curGp)
- chatWindow->chatLog(_("You picked up ") +
- Units::formatCurrency(player_node->mGp
- - curGp), BY_SERVER);
- }
- break;
- case 0x0016:
- player_node->mXpForNextLevel = msg->readInt32();
- break;
- case 0x0017:
- player_node->mJobXpForNextLevel = msg->readInt32();
- break;
- }
- break;
-
- case SMSG_PLAYER_STAT_UPDATE_3:
- {
- Sint32 type = msg->readInt32();
- Sint32 base = msg->readInt32();
- Sint32 bonus = msg->readInt32();
- Sint32 total = base + bonus;
+ case GPMSG_LEVELUP:
+ {
+ player_node->setLevel(msg.readInt16());
+ player_node->setCharacterPoints(msg.readInt16());
+ player_node->setCorrectionPoints(msg.readInt16());
+ Particle* effect = particleEngine->addEffect("graphics/particles/levelup.particle.xml", 0, 0);
+ player_node->controlParticle(effect);
+ } break;
- switch (type) {
- case 0x000d: player_node->mAttr[LocalPlayer::STR] = total;
- break;
- case 0x000e: player_node->mAttr[LocalPlayer::AGI] = total;
- break;
- case 0x000f: player_node->mAttr[LocalPlayer::VIT] = total;
- break;
- case 0x0010: player_node->mAttr[LocalPlayer::INT] = total;
- break;
- case 0x0011: player_node->mAttr[LocalPlayer::DEX] = total;
- break;
- case 0x0012: player_node->mAttr[LocalPlayer::LUK] = total;
- break;
- }
- }
- break;
- case SMSG_PLAYER_STAT_UPDATE_4:
- {
- Sint16 type = msg->readInt16();
- Sint8 fail = msg->readInt8();
- Sint8 value = msg->readInt8();
+ case GPMSG_LEVEL_PROGRESS:
+ {
+ logger->log("Level Progress Update");
+ player_node->setLevelProgress(msg.readInt8());
+ } break;
- if (fail != 1)
- break;
- switch (type) {
- case 0x000d: player_node->mAttr[LocalPlayer::STR] = value;
- break;
- case 0x000e: player_node->mAttr[LocalPlayer::AGI] = value;
- break;
- case 0x000f: player_node->mAttr[LocalPlayer::VIT] = value;
- break;
- case 0x0010: player_node->mAttr[LocalPlayer::INT] = value;
- break;
- case 0x0011: player_node->mAttr[LocalPlayer::DEX] = value;
- break;
- case 0x0012: player_node->mAttr[LocalPlayer::LUK] = value;
- break;
- }
+ case GPMSG_RAISE_ATTRIBUTE_RESPONSE:
+ {
+ int errCode = msg.readInt8();
+ int attrNum = msg.readInt8() - CHAR_ATTR_BEGIN;
+ switch (errCode)
+ {
+ case ATTRIBMOD_OK:
+ {
+ // feel(acknowledgment);
+ } break;
+ case ATTRIBMOD_INVALID_ATTRIBUTE:
+ {
+ logger->log("Warning: Server denied increase of attribute %d (unknown attribute) ", attrNum);
+ } break;
+ case ATTRIBMOD_NO_POINTS_LEFT:
+ {
+ // when the server says "you got no points" it
+ // has to be correct. The server is always right!
+ // undo attribute change and set points to 0
+ logger->log("Warning: Server denied increase of attribute %d (no points left) ", attrNum);
+ int attrValue = player_node->getAttributeBase(attrNum) - 1;
+ player_node->setCharacterPoints(0);
+ player_node->setAttributeBase(attrNum, attrValue);
+ } break;
+ case ATTRIBMOD_DENIED:
+ {
+ // undo attribute change
+ logger->log("Warning: Server denied increase of attribute %d (reason unknown) ", attrNum);
+ int points = player_node->getCharacterPoints() - 1;
+ player_node->setCharacterPoints(points);
+ int attrValue = player_node->getAttributeBase(attrNum) - 1;
+ player_node->setAttributeBase(attrNum, attrValue);
+ } break;
}
- break;
-
- // Updates stats and status points
- case SMSG_PLAYER_STAT_UPDATE_5:
- player_node->mStatsPointsToAttribute = msg->readInt16();
- player_node->mAttr[LocalPlayer::STR] = msg->readInt8();
- player_node->mAttrUp[LocalPlayer::STR] = msg->readInt8();
- player_node->mAttr[LocalPlayer::AGI] = msg->readInt8();
- player_node->mAttrUp[LocalPlayer::AGI] = msg->readInt8();
- player_node->mAttr[LocalPlayer::VIT] = msg->readInt8();
- player_node->mAttrUp[LocalPlayer::VIT] = msg->readInt8();
- player_node->mAttr[LocalPlayer::INT] = msg->readInt8();
- player_node->mAttrUp[LocalPlayer::INT] = msg->readInt8();
- player_node->mAttr[LocalPlayer::DEX] = msg->readInt8();
- player_node->mAttrUp[LocalPlayer::DEX] = msg->readInt8();
- player_node->mAttr[LocalPlayer::LUK] = msg->readInt8();
- player_node->mAttrUp[LocalPlayer::LUK] = msg->readInt8();
- player_node->ATK = msg->readInt16(); // ATK
- player_node->ATK_BONUS = msg->readInt16(); // ATK bonus
- player_node->MATK = msg->readInt16(); // MATK max
- player_node->MATK_BONUS = msg->readInt16(); // MATK min
- player_node->DEF = msg->readInt16(); // DEF
- player_node->DEF_BONUS = msg->readInt16(); // DEF bonus
- player_node->MDEF = msg->readInt16(); // MDEF
- player_node->MDEF_BONUS = msg->readInt16(); // MDEF bonus
- player_node->HIT = msg->readInt16(); // HIT
- player_node->FLEE = msg->readInt16(); // FLEE
- player_node->FLEE_BONUS = msg->readInt16(); // FLEE bonus
- msg->readInt16(); // critical
- msg->readInt16(); // unknown
- break;
+ } break;
- case SMSG_PLAYER_STAT_UPDATE_6:
- switch (msg->readInt16()) {
- case 0x0020:
- player_node->mAttrUp[LocalPlayer::STR] = msg->readInt8();
- break;
- case 0x0021:
- player_node->mAttrUp[LocalPlayer::AGI] = msg->readInt8();
- break;
- case 0x0022:
- player_node->mAttrUp[LocalPlayer::VIT] = msg->readInt8();
- break;
- case 0x0023:
- player_node->mAttrUp[LocalPlayer::INT] = msg->readInt8();
- break;
- case 0x0024:
- player_node->mAttrUp[LocalPlayer::DEX] = msg->readInt8();
- break;
- case 0x0025:
- player_node->mAttrUp[LocalPlayer::LUK] = msg->readInt8();
+ case GPMSG_LOWER_ATTRIBUTE_RESPONSE:
+ {
+ int errCode = msg.readInt8();
+ int attrNum = msg.readInt8() - CHAR_ATTR_BEGIN;
+ switch (errCode)
+ {
+ case ATTRIBMOD_OK:
+ {
+ // feel(acknowledgment);
+ } break;
+ case ATTRIBMOD_INVALID_ATTRIBUTE:
+ {
+ logger->log("Warning: Server denied reduction of attribute %d (unknown attribute) ", attrNum);
+ } break;
+ case ATTRIBMOD_NO_POINTS_LEFT:
+ {
+ // when the server says "you got no points" it
+ // has to be correct. The server is always right!
+ // undo attribute change and set points to 0
+ logger->log("Warning: Server denied reduction of attribute %d (no points left) ", attrNum);
+ int attrValue = player_node->getAttributeBase(attrNum) + 1;
+ player_node->setCorrectionPoints(0);
+ player_node->setAttributeBase(attrNum, attrValue);
break;
+ } break;
+ case ATTRIBMOD_DENIED:
+ {
+ // undo attribute change
+ logger->log("Warning: Server denied reduction of attribute %d (reason unknown) ", attrNum);
+ int charaPoints = player_node->getCharacterPoints() - 1;
+ player_node->setCharacterPoints(charaPoints);
+ int correctPoints = player_node->getCorrectionPoints() + 1;
+ player_node->setCorrectionPoints(correctPoints);
+ int attrValue = player_node->getAttributeBase(attrNum) + 1;
+ player_node->setAttributeBase(attrNum, attrValue);
+ } break;
}
- break;
+ } break;
+ /*
case SMSG_PLAYER_ARROW_MESSAGE:
{
- Sint16 type = msg->readInt16();
+ Sint16 type = msg.readInt16();
switch (type) {
case 0:
- chatWindow->chatLog(_("Equip arrows first"),
+ chatWindow->chatLog("Equip arrows first",
BY_SERVER);
break;
default:
@@ -413,5 +287,41 @@ void PlayerHandler::handleMessage(MessageIn *msg)
}
}
break;
+ */
}
}
+
+void
+PlayerHandler::handleMapChangeMessage(MessageIn &msg)
+{
+ const std::string mapName = msg.readString();
+ const unsigned short x = msg.readInt16();
+ const unsigned short y = msg.readInt16();
+ const bool nearby = (engine->getCurrentMapName() == mapName);
+
+ logger->log("Changing map to %s (%d, %d)", mapName.c_str(), x, y);
+
+ // Switch the actual map, deleting the previous one
+ engine->changeMap(mapName);
+
+ current_npc = 0;
+
+ const Vector &playerPos = player_node->getPosition();
+ float scrollOffsetX = 0.0f;
+ float scrollOffsetY = 0.0f;
+
+ /* Scroll if neccessary */
+ if (!nearby
+ || (abs(x - (int) playerPos.x) > MAP_TELEPORT_SCROLL_DISTANCE)
+ || (abs(y - (int) playerPos.y) > MAP_TELEPORT_SCROLL_DISTANCE)) {
+ scrollOffsetX = x - (int) playerPos.x;
+ scrollOffsetY = y - (int) playerPos.y;
+ }
+
+ player_node->setAction(Being::STAND);
+ player_node->setPosition(x, y);
+
+ logger->log("Adjust scrolling by %d,%d", (int) scrollOffsetX,
+ (int) scrollOffsetY);
+ viewport->scrollBy(scrollOffsetX, scrollOffsetY);
+}
diff --git a/src/net/playerhandler.h b/src/net/playerhandler.h
index 1a7c8da3..fef767da 100644
--- a/src/net/playerhandler.h
+++ b/src/net/playerhandler.h
@@ -29,7 +29,10 @@ class PlayerHandler : public MessageHandler
public:
PlayerHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
+
+ private:
+ void handleMapChangeMessage(MessageIn &msg);
};
#endif
diff --git a/src/net/protocol.h b/src/net/protocol.h
index e9053451..73dd65e0 100644
--- a/src/net/protocol.h
+++ b/src/net/protocol.h
@@ -1,162 +1,295 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#ifndef PROTOCOL_
-#define PROTOCOL_
-
-/*********************************
- * Packets from server to client *
- *********************************/
-#define SMSG_LOGIN_SUCCESS 0x0073 /**< Contains starting location */
-#define SMSG_SERVER_PING 0x007f /**< Contains server tick */
-#define SMSG_CONNECTION_PROBLEM 0x0081
-#define SMSG_UPDATE_HOST 0x0063 /**< Custom update host packet */
-#define SMSG_PLAYER_UPDATE_1 0x01d8
-#define SMSG_PLAYER_UPDATE_2 0x01d9
-#define SMSG_PLAYER_MOVE 0x01da /**< A nearby player moves */
-#define SMSG_PLAYER_STOP 0x0088 /**< Stop walking, set position */
-#define SMSG_PLAYER_MOVE_TO_ATTACK 0x0139 /**< Move to within attack range */
-#define SMSG_PLAYER_STAT_UPDATE_1 0x00b0
-#define SMSG_PLAYER_STAT_UPDATE_2 0x00b1
-#define SMSG_PLAYER_STAT_UPDATE_3 0x0141
-#define SMSG_PLAYER_STAT_UPDATE_4 0x00bc
-#define SMSG_PLAYER_STAT_UPDATE_5 0x00bd
-#define SMSG_PLAYER_STAT_UPDATE_6 0x00be
-#define SMSG_WHO_ANSWER 0x00c2
-#define SMSG_PLAYER_WARP 0x0091 /**< Warp player to map/location */
-#define SMSG_PLAYER_INVENTORY 0x01ee
-#define SMSG_PLAYER_INVENTORY_ADD 0x00a0
-#define SMSG_PLAYER_INVENTORY_REMOVE 0x00af
-#define SMSG_PLAYER_INVENTORY_USE 0x01c8
-#define SMSG_PLAYER_EQUIPMENT 0x00a4
-#define SMSG_PLAYER_EQUIP 0x00aa
-#define SMSG_PLAYER_UNEQUIP 0x00ac
-#define SMSG_PLAYER_ATTACK_RANGE 0x013a
-#define SMSG_PLAYER_ARROW_EQUIP 0x013c
-#define SMSG_PLAYER_ARROW_MESSAGE 0x013b
-#define SMSG_PLAYER_SKILLS 0x010f
-#define SMSG_SKILL_FAILED 0x0110
-#define SMSG_ITEM_USE_RESPONSE 0x00a8
-#define SMSG_ITEM_VISIBLE 0x009d /**< An item is on the floor */
-#define SMSG_ITEM_DROPPED 0x009e /**< An item is dropped */
-#define SMSG_ITEM_REMOVE 0x00a1 /**< An item disappers */
-#define SMSG_BEING_VISIBLE 0x0078
-#define SMSG_BEING_MOVE 0x007b /**< A nearby monster moves */
-#define SMSG_BEING_SPAWN 0x007c /**< A being spawns nearby */
-#define SMSG_BEING_MOVE2 0x0086 /**< New eAthena being moves */
-#define SMSG_BEING_REMOVE 0x0080
-#define SMSG_BEING_CHANGE_LOOKS 0x00c3
-#define SMSG_BEING_CHANGE_LOOKS2 0x01d7 /**< Same as 0x00c3, but 16 bit ID */
-#define SMSG_BEING_SELFEFFECT 0x019b
-#define SMSG_BEING_EMOTION 0x00c0
-#define SMSG_BEING_ACTION 0x008a /**< Attack, sit, stand up, ... */
-#define SMSG_BEING_CHAT 0x008d /**< A being talks */
-#define SMSG_BEING_NAME_RESPONSE 0x0095 /**< Has to be requested */
-
-#define SMSG_NPC_MESSAGE 0x00b4
-#define SMSG_NPC_NEXT 0x00b5
-#define SMSG_NPC_CLOSE 0x00b6
-#define SMSG_NPC_CHOICE 0x00b7 /**< Display a choice */
-#define SMSG_NPC_BUY_SELL_CHOICE 0x00c4
-#define SMSG_NPC_BUY 0x00c6
-#define SMSG_NPC_SELL 0x00c7
-#define SMSG_NPC_BUY_RESPONSE 0x00ca
-#define SMSG_NPC_SELL_RESPONSE 0x00cb
-#define SMSG_NPC_INT_INPUT 0x0142 /**< Integer input */
-#define SMSG_NPC_STR_INPUT 0x01d4 /**< String input */
-#define SMSG_PLAYER_CHAT 0x008e /**< Player talks */
-#define SMSG_WHISPER 0x0097 /**< Whisper Recieved */
-#define SMSG_WHISPER_RESPONSE 0x0098
-#define SMSG_GM_CHAT 0x009a /**< GM announce */
-#define SMSG_WALK_RESPONSE 0x0087
-
-#define SMSG_TRADE_REQUEST 0x00e5 /**< Receiving a request to trade */
-#define SMSG_TRADE_RESPONSE 0x00e7
-#define SMSG_TRADE_ITEM_ADD 0x00e9
-#define SMSG_TRADE_ITEM_ADD_RESPONSE 0x01b1 /**< Not standard eAthena! */
-#define SMSG_TRADE_OK 0x00ec
-#define SMSG_TRADE_CANCEL 0x00ee
-#define SMSG_TRADE_COMPLETE 0x00f0
-
-#define SMSG_PARTY_CREATE 0x00fa
-#define SMSG_PARTY_INFO 0x00fb
-#define SMSG_PARTY_INVITE 0x00fd
-#define SMSG_PARTY_INVITED 0x00fe
-#define SMSG_PARTY_SETTINGS 0x0102
-#define SMSG_PARTY_MEMBER_INFO 0x0104
-#define SMSG_PARTY_LEAVE 0x0105
-#define SMSG_PARTY_UPDATE_HP 0x0106
-#define SMSG_PARTY_UPDATE_COORDS 0x0107
-#define SMSG_PARTY_MESSAGE 0x0109
-
-#define SMSG_PLAYER_STORAGE_ITEMS 0x01f0 /**< Item list for storage */
-#define SMSG_PLAYER_STORAGE_EQUIP 0x00a6 /**< Equipment list for storage */
-#define SMSG_PLAYER_STORAGE_STATUS 0x00f2 /**< Slots used and total slots */
-#define SMSG_PLAYER_STORAGE_ADD 0x00f4 /**< Add item/equip to storage */
-#define SMSG_PLAYER_STORAGE_REMOVE 0x00f6 /**< Remove item/equip from storage */
-#define SMSG_PLAYER_STORAGE_CLOSE 0x00f8 /**< Storage access closed */
-
-/**********************************
- * Packets from client to server *
- **********************************/
-#define CMSG_CLIENT_PING 0x007e /**< Send to server with tick */
-#define CMSG_TRADE_RESPONSE 0x00e6
-#define CMSG_ITEM_PICKUP 0x009f
-#define CMSG_MAP_LOADED 0x007d
-#define CMSG_NPC_BUY_REQUEST 0x00c8
-#define CMSG_NPC_BUY_SELL_REQUEST 0x00c5
-#define CMSG_CHAT_MESSAGE 0x008c
-#define CMSG_CHAT_WHISPER 0x0096
-#define CMSG_CHAT_ANNOUNCE 0x0099
-#define CMSG_CHAT_WHO 0x00c1
-#define CMSG_NPC_LIST_CHOICE 0x00b8
-#define CMSG_NPC_NEXT_REQUEST 0x00b9
-#define CMSG_NPC_SELL_REQUEST 0x00c9
-#define CMSG_NPC_INT_RESPONSE 0x0143
-#define CMSG_NPC_STR_RESPONSE 0x01d5
-#define CMSG_SKILL_LEVELUP_REQUEST 0x0112
-#define CMSG_STAT_UPDATE_REQUEST 0x00bb
-#define CMSG_TRADE_ITEM_ADD_REQUEST 0x00e8
-#define CMSG_TRADE_CANCEL_REQUEST 0x00ed
-#define CMSG_TRADE_ADD_COMPLETE 0x00eb
-#define CMSG_TRADE_OK 0x00ef
-#define CMSG_NPC_TALK 0x0090
-#define CMSG_TRADE_REQUEST 0x00e4
-#define CMSG_PLAYER_INVENTORY_USE 0x00a7
-#define CMSG_PLAYER_INVENTORY_DROP 0x00a2
-#define CMSG_PLAYER_EQUIP 0x00a9
-#define CMSG_PLAYER_UNEQUIP 0x00ab
-
-#define CMSG_PARTY_CREATE 0x00f9
-#define CMSG_PARTY_INVITE 0x00fc
-#define CMSG_PARTY_INVITED 0x00ff
-#define CMSG_PARTY_LEAVE 0x0100 /** Undocumented */
-#define CMSG_PARTY_SETTINGS 0x0101
-#define CMSG_PARTY_MESSAGE 0x0108
-
-#define CMSG_MOVE_TO_STORAGE 0x00f3 /** Move item to storage */
-#define CSMG_MOVE_FROM_STORAGE 0x00f5 /** Remove item from storage */
-#define CMSG_CLOSE_STORAGE 0x00f7 /** Request storage close */
-
-/** Encodes coords and direction in 3 bytes data */
-void set_coordinates(char *data, unsigned short x, unsigned short y, unsigned char direction);
+#ifndef _TMW_PROTOCOL_
+#define _TMW_PROTOCOL_
+
+/**
+ * Enumerated type for communicated messages:
+ *
+ * - PAMSG_*: from client to account server
+ * - APMSG_*: from account server to client
+ * - PCMSG_*: from client to chat server
+ * - CPMSG_*: from chat server to client
+ * - PGMSG_*: from client to game server
+ * - GPMSG_*: from game server to client
+ *
+ * Components: B byte, W word, D double word, S variable-size string
+ * C tile-based coordinates (B*3)
+ *
+ * Hosts: P (player's client), A (account server), C (char server),
+ * G (game server)
+ */
+enum {
+ // Login/Register
+ PAMSG_REGISTER = 0x0000, // L version, S username, S password, S email
+ APMSG_REGISTER_RESPONSE = 0x0002, // B error [, S updatehost]
+ PAMSG_UNREGISTER = 0x0003, // -
+ APMSG_UNREGISTER_RESPONSE = 0x0004, // B error
+ PAMSG_LOGIN = 0x0010, // L version, S username, S password
+ APMSG_LOGIN_RESPONSE = 0x0012, // B error [, S updatehost]
+ PAMSG_LOGOUT = 0x0013, // -
+ APMSG_LOGOUT_RESPONSE = 0x0014, // B error
+ PAMSG_CHAR_CREATE = 0x0020, // S name, B hair style, B hair color, B gender, W*6 stats
+ APMSG_CHAR_CREATE_RESPONSE = 0x0021, // B error
+ PAMSG_CHAR_DELETE = 0x0022, // B index
+ APMSG_CHAR_DELETE_RESPONSE = 0x0023, // B error
+ APMSG_CHAR_INFO = 0x0024, // B index, S name, B gender, B hair style, B hair color, W level, W character points, W correction points, D money, W*6 stats
+ PAMSG_CHAR_SELECT = 0x0026, // B index
+ APMSG_CHAR_SELECT_RESPONSE = 0x0027, // B error, B*32 token, S game address, W game port, S chat address, W chat port
+ PAMSG_EMAIL_CHANGE = 0x0030, // S email
+ APMSG_EMAIL_CHANGE_RESPONSE = 0x0031, // B error
+ PAMSG_PASSWORD_CHANGE = 0x0034, // S old password, S new password
+ APMSG_PASSWORD_CHANGE_RESPONSE = 0x0035, // B error
+
+ PGMSG_CONNECT = 0x0050, // B*32 token
+ GPMSG_CONNECT_RESPONSE = 0x0051, // B error
+ PCMSG_CONNECT = 0x0053, // B*32 token
+ CPMSG_CONNECT_RESPONSE = 0x0054, // B error
+
+ PGMSG_DISCONNECT = 0x0060, // B reconnect account
+ GPMSG_DISCONNECT_RESPONSE = 0x0061, // B error, B*32 token
+ PCMSG_DISCONNECT = 0x0063, // -
+ CPMSG_DISCONNECT_RESPONSE = 0x0064, // B error
+
+ PAMSG_RECONNECT = 0x0065, // B*32 token
+ APMSG_RECONNECT_RESPONSE = 0x0066, // B error
+
+ // Game
+ GPMSG_PLAYER_MAP_CHANGE = 0x0100, // S filename, W x, W y
+ GPMSG_PLAYER_SERVER_CHANGE = 0x0101, // B*32 token, S game address, W game port
+ PGMSG_PICKUP = 0x0110, // W*2 position
+ PGMSG_DROP = 0x0111, // B slot, B amount
+ PGMSG_EQUIP = 0x0112, // B slot
+ PGMSG_UNEQUIP = 0x0113, // B slot
+ PGMSG_MOVE_ITEM = 0x0114, // B slot1, B slot2, B amount
+ GPMSG_INVENTORY = 0x0120, // { B slot, W item id [, B amount] }*
+ GPMSG_INVENTORY_FULL = 0x0121, // { B slot, W item id [, B amount] }*
+ GPMSG_PLAYER_ATTRIBUTE_CHANGE = 0x0130, // { B attribute, W base value, W modified value }*
+ GPMSG_PLAYER_EXP_CHANGE = 0x0140, // { B skill, D exp got, D exp needed }*
+ GPMSG_LEVELUP = 0x0150, // W new level
+ GPMSG_LEVEL_PROGRESS = 0x0151, // B percent completed to next levelup
+ PGMSG_RAISE_ATTRIBUTE = 0x0160, // B attribute
+ GPMSG_RAISE_ATTRIBUTE_RESPONSE = 0x0161, // B error, B attribute
+ PGMSG_LOWER_ATTRIBUTE = 0x0170, // B attribute
+ GPMSG_LOWER_ATTRIBUTE_RESPONSE = 0x0171, // B error, B attribute
+ PGMSG_RESPAWN = 0x0180, // -
+ GPMSG_BEING_ENTER = 0x0200, // B type, W being id, B action, W*2 position
+ // player: S name, B hair style, B hair color, B gender, B item bitmask, { W item id }*
+ // monster: W type id
+ // npc: W type id
+ GPMSG_BEING_LEAVE = 0x0201, // W being id
+ GPMSG_ITEM_APPEAR = 0x0202, // W item id, W*2 position
+ GPMSG_BEING_LOOKS_CHANGE = 0x0210, // W weapon, W hat, W top clothes, W bottom clothes
+ PGMSG_WALK = 0x0260, // W*2 destination
+ PGMSG_ACTION_CHANGE = 0x0270, // B Action
+ GPMSG_BEING_ACTION_CHANGE = 0x0271, // W being id, B action
+ PGMSG_DIRECTION_CHANGE = 0x0272, // B Direction
+ GPMSG_BEING_DIR_CHANGE = 0x0273, // W being id, B direction
+ GPMSG_BEINGS_MOVE = 0x0280, // { W being id, B flags [, C position, B speed] [, W*2 destination] }*
+ GPMSG_ITEMS = 0x0281, // { W item id, W*2 position }*
+ PGMSG_ATTACK = 0x0290, // B direction
+ PGMSG_USE_SPECIAL = 0x0292, // B specialID
+ GPMSG_BEING_ATTACK = 0x0291, // W being id
+ PGMSG_SAY = 0x02A0, // S text
+ GPMSG_SAY = 0x02A1, // W being id, S text
+ GPMSG_NPC_CHOICE = 0x02B0, // W being id, { S text }*
+ GPMSG_NPC_MESSAGE = 0x02B1, // W being id, B* text
+ PGMSG_NPC_TALK = 0x02B2, // W being id
+ PGMSG_NPC_TALK_NEXT = 0x02B3, // W being id
+ PGMSG_NPC_SELECT = 0x02B4, // W being id, B choice
+ GPMSG_NPC_BUY = 0x02B5, // W being id, { W item id, W amount, W cost }*
+ GPMSG_NPC_SELL = 0x02B6, // W being id, { W item id, W amount, W cost }*
+ PGMSG_NPC_BUYSELL = 0x02B7, // W item id, W amount
+ GPMSG_NPC_ERROR = 0x02B8, // B error
+ GPMSG_NPC_POST = 0x02D0, // W being id
+ PGMSG_NPC_POST_SEND = 0x02D1, // S name, S text, W item id
+ GPMSG_NPC_POST_GET = 0x02D2, // W being id, { S name, S text, W item id }
+ PGMSG_TRADE_REQUEST = 0x02C0, // W being id
+ GPMSG_TRADE_REQUEST = 0x02C1, // W being id
+ GPMSG_TRADE_START = 0x02C2, // -
+ GPMSG_TRADE_COMPLETE = 0x02C3, // -
+ PGMSG_TRADE_CANCEL = 0x02C4, // -
+ GPMSG_TRADE_CANCEL = 0x02C5, // -
+ PGMSG_TRADE_ACCEPT = 0x02C6, // -
+ GPMSG_TRADE_ACCEPT = 0x02C7, // -
+ PGMSG_TRADE_ADD_ITEM = 0x02C8, // B slot, B amount
+ GPMSG_TRADE_ADD_ITEM = 0x02C9, // W item id, B amount
+ PGMSG_TRADE_SET_MONEY = 0x02CA, // L amount
+ GPMSG_TRADE_SET_MONEY = 0x02CB, // L amount
+ PGMSG_USE_ITEM = 0x0300, // B slot
+ GPMSG_USE_RESPONSE = 0x0301, // B error
+ GPMSG_BEINGS_DAMAGE = 0x0310, // { W being id, W amount }*
+ GPMSG_CREATE_EFFECT = 0x0320, // W effect id, W*2 position
+
+ // Guild
+ PCMSG_GUILD_CREATE = 0x0350, // S name
+ CPMSG_GUILD_CREATE_RESPONSE = 0x0351, // B error, W guild, B rights, W channel
+ PCMSG_GUILD_INVITE = 0x0352, // W id, S name
+ CPMSG_GUILD_INVITE_RESPONSE = 0x0353, // B error
+ PCMSG_GUILD_ACCEPT = 0x0354, // W id
+ CPMSG_GUILD_ACCEPT_RESPONSE = 0x0355, // B error, W guild, B rights, W channel
+ PCMSG_GUILD_GET_MEMBERS = 0x0356, // W id
+ CPMSG_GUILD_GET_MEMBERS_RESPONSE = 0x0357, // S names, B online
+ CPMSG_GUILD_UPDATE_LIST = 0x0358, // W id, S name, B event
+ PCMSG_GUILD_QUIT = 0x0360, // W id
+ CPMSG_GUILD_QUIT_RESPONSE = 0x0361, // B error
+ PCMSG_GUILD_PROMOTE_MEMBER = 0x0365, // W guild, S name, B rights
+ CPMSG_GUILD_PROMOTE_MEMBER_RESPONSE = 0x0366, // B error
+
+ CPMSG_GUILD_INVITED = 0x0370, // S char name, S guild name, W id
+ CPMSG_GUILD_REJOIN = 0x0371, // S name, W guild, W rights, W channel, S announce
+
+ // Party
+ PCMSG_PARTY_INVITE = 0x03A0, // S name
+ CPMSG_PARTY_INVITE_RESPONSE = 0x03A1, // B error
+ CPMSG_PARTY_INVITED = 0x03A2, // S name
+ PCMSG_PARTY_ACCEPT_INVITE = 0x03A5, // S name
+ CPMSG_PARTY_ACCEPT_INVITE_RESPONSE = 0x03A6, // B error, { S name }
+ PCMSG_PARTY_QUIT = 0x03AA, // -
+ CPMSG_PARTY_QUIT_RESPONSE = 0x03AB, // B error
+ CPMSG_PARTY_NEW_MEMBER = 0x03B0, // W being id, S name
+ CPMSG_PARTY_MEMBER_LEFT = 0x03B1, // W being id
+
+ // Chat
+ CPMSG_ERROR = 0x0401, // B error
+ CPMSG_ANNOUNCEMENT = 0x0402, // S text
+ CPMSG_PRIVMSG = 0x0403, // S user, S text
+ CPMSG_PUBMSG = 0x0404, // W channel, S user, S text
+ PCMSG_CHAT = 0x0410, // S text, W channel
+ PCMSG_ANNOUNCE = 0x0411, // S text
+ PCMSG_PRIVMSG = 0x0412, // S user, S text
+ // -- Channeling
+ CPMSG_CHANNEL_EVENT = 0x0430, // W channel, B event, S info
+ PCMSG_ENTER_CHANNEL = 0x0440, // S channel, S password
+ CPMSG_ENTER_CHANNEL_RESPONSE = 0x0441, // B error, W id, S name, S topic, S userlist
+ PCMSG_QUIT_CHANNEL = 0x0443, // W channel id
+ CPMSG_QUIT_CHANNEL_RESPONSE = 0x0444, // B error, W channel id
+ PCMSG_LIST_CHANNELS = 0x0445, // -
+ CPMSG_LIST_CHANNELS_RESPONSE = 0x0446, // S names, W number of users
+ PCMSG_LIST_CHANNELUSERS = 0x0460, // S channel
+ CPMSG_LIST_CHANNELUSERS_RESPONSE = 0x0461, // S channel, { S user, B mode }
+ PCMSG_TOPIC_CHANGE = 0x0462, // W channel id, S topic
+ // -- User mode
+ PCMSG_USER_MODE = 0x0465, // W channel id, S name, B mode
+ PCMSG_KICK_USER = 0x0466, // W channel id, S name
+
+ XXMSG_INVALID = 0x7FFF
+};
+
+// Generic return values
+
+enum {
+ ERRMSG_OK = 0, // everything is fine
+ ERRMSG_FAILURE, // the action failed
+ ERRMSG_NO_LOGIN, // the user is not yet logged
+ ERRMSG_NO_CHARACTER_SELECTED, // the user needs a character
+ ERRMSG_INSUFFICIENT_RIGHTS, // the user is not privileged
+ ERRMSG_INVALID_ARGUMENT, // part of the received message was invalid
+ ERRMSG_EMAIL_ALREADY_EXISTS, // The Email Address already exists
+ ERRMSG_ALREADY_TAKEN, // name used was already taken
+ ERRMSG_SERVER_FULL, // the server is overloaded
+ ERRMSG_TIME_OUT // data failed to arrive in due time
+};
+
+// Login specific return values
+enum {
+ LOGIN_INVALID_VERSION = 0x40, // the user is using an incompatible protocol
+ LOGIN_SERVER_FULL // the server is overloaded
+};
+
+// Account register specific return values
+enum {
+ REGISTER_INVALID_VERSION = 0x40, // the user is using an incompatible protocol
+ REGISTER_EXISTS_USERNAME, // there already is an account with this username
+ REGISTER_EXISTS_EMAIL // there already is an account with this email address
+};
+
+// Character creation specific return values
+enum {
+ CREATE_INVALID_HAIRSTYLE = 0x40,
+ CREATE_INVALID_HAIRCOLOR,
+ CREATE_INVALID_GENDER,
+ CREATE_RAW_STATS_TOO_HIGH,
+ CREATE_RAW_STATS_TOO_LOW,
+ CREATE_RAW_STATS_EQUAL_TO_ZERO,
+ CREATE_EXISTS_NAME,
+ CREATE_TOO_MUCH_CHARACTERS
+};
+
+// Character attribute modification specific return value
+enum AttribmodResponseCode {
+ ATTRIBMOD_OK = ERRMSG_OK,
+ ATTRIBMOD_INVALID_ATTRIBUTE = 0x40,
+ ATTRIBMOD_NO_POINTS_LEFT,
+ ATTRIBMOD_DENIED
+};
+// Object type enumeration
+enum {
+ // A simple item
+ OBJECT_ITEM = 0,
+ // An item that can be activated (doors, switchs, sign, ...)
+ OBJECT_ACTOR,
+ // Non-Playable-Character is an actor capable of movement and maybe actions
+ OBJECT_NPC,
+ // A monster (moving actor with AI. able to toggle map/quest actions, too)
+ OBJECT_MONSTER,
+ // A player
+ OBJECT_PLAYER
+};
+
+// Moving object flags
+enum {
+ // Payload contains the current position.
+ MOVING_POSITION = 1,
+ // Payload contains the destination.
+ MOVING_DESTINATION = 2
+};
+
+// Email change specific return values
+enum {
+ EMAILCHG_EXISTS_EMAIL = 0x40
+};
+
+// Chat errors return values
+enum {
+ CHAT_USING_BAD_WORDS = 0x40,
+ CHAT_UNHANDLED_COMMAND
+};
+
+// Chat channels event values
+enum {
+ CHAT_EVENT_NEW_PLAYER = 0,
+ CHAT_EVENT_LEAVING_PLAYER,
+ CHAT_EVENT_TOPIC_CHANGE,
+ CHAT_EVENT_MODE_CHANGE,
+ CHAT_EVENT_KICKED_PLAYER
+};
+
+// Guild member event values
+enum {
+ GUILD_EVENT_NEW_PLAYER = 0,
+ GUILD_EVENT_LEAVING_PLAYER,
+ GUILD_EVENT_ONLINE_PLAYER,
+ GUILD_EVENT_OFFLINE_PLAYER
+};
#endif
diff --git a/src/net/tradehandler.cpp b/src/net/tradehandler.cpp
index c5465835..5d93016f 100644
--- a/src/net/tradehandler.cpp
+++ b/src/net/tradehandler.cpp
@@ -1,40 +1,41 @@
/*
* The Mana World
- * Copyright (C) 2004 The Mana World Development Team
+ * Copyright 2004 The Mana World Development Team
*
* This file is part of The Mana World.
*
- * This program is free software; you can redistribute it and/or modify
+ * The Mana World is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
- * This program is distributed in the hope that it will be useful,
+ * The Mana World is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
+ * along with The Mana World; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
+#include "tradehandler.h"
+
#include "messagein.h"
#include "protocol.h"
-#include "tradehandler.h"
-#include "../inventory.h"
+#include "gameserver/player.h"
+
+#include "../beingmanager.h"
#include "../item.h"
#include "../localplayer.h"
-#include "../player_relations.h"
#include "../gui/chat.h"
#include "../gui/confirm_dialog.h"
#include "../gui/trade.h"
-#include "../utils/gettext.h"
-
std::string tradePartnerName;
+int tradePartnerID;
/**
* Listener for request trade dialogs
@@ -44,174 +45,90 @@ namespace {
{
void action(const gcn::ActionEvent &event)
{
- player_node->tradeReply(event.getId() == "yes");
- };
+ if (event.getId() == "yes")
+ Net::GameServer::Player::requestTrade(tradePartnerID);
+ else
+ Net::GameServer::Player::acceptTrade(false);
+ }
} listener;
}
-TradeHandler::TradeHandler()
+TradeHandler::TradeHandler():
+ mAcceptTradeRequests(true)
{
static const Uint16 _messages[] = {
- SMSG_TRADE_REQUEST,
- SMSG_TRADE_RESPONSE,
- SMSG_TRADE_ITEM_ADD,
- SMSG_TRADE_ITEM_ADD_RESPONSE,
- SMSG_TRADE_OK,
- SMSG_TRADE_CANCEL,
- SMSG_TRADE_COMPLETE,
+ GPMSG_TRADE_REQUEST,
+ GPMSG_TRADE_CANCEL,
+ GPMSG_TRADE_START,
+ GPMSG_TRADE_COMPLETE,
+ GPMSG_TRADE_ACCEPT,
+ GPMSG_TRADE_ADD_ITEM,
+ GPMSG_TRADE_SET_MONEY,
0
};
handledMessages = _messages;
}
+void TradeHandler::setAcceptTradeRequests(bool acceptTradeRequests)
+{
+ mAcceptTradeRequests = acceptTradeRequests;
+ if (mAcceptTradeRequests) {
+ chatWindow->chatLog("Accepting incoming trade requests", BY_SERVER);
+ } else {
+ chatWindow->chatLog("Ignoring incoming trade requests", BY_SERVER);
+ }
+}
-void TradeHandler::handleMessage(MessageIn *msg)
+void TradeHandler::handleMessage(MessageIn &msg)
{
- switch (msg->getId())
+ switch (msg.getId())
{
- case SMSG_TRADE_REQUEST:
- // If a trade window or request window is already open, send a
- // trade cancel to any other trade request.
- //
- // Note that it would be nice if the server would prevent this
- // situation, and that the requesting player would get a
- // special message about the player being occupied.
- tradePartnerName = msg->readString(24);
-
- if (player_relations.hasPermission(tradePartnerName, PlayerRelation::TRADE))
- {
- if (!player_node->tradeRequestOk())
- {
- player_node->tradeReply(false);
- break;
- }
-
- player_node->setTrading(true);
- ConfirmDialog *dlg;
- dlg = new ConfirmDialog(_("Request for trade"),
- tradePartnerName +
- _(" wants to trade with you, do you accept?"));
- dlg->addActionListener(&listener);
- }
- else
- {
- player_node->tradeReply(false);
- break;
- }
- break;
-
- case SMSG_TRADE_RESPONSE:
- switch (msg->readInt8())
+ case GPMSG_TRADE_REQUEST:
+ {
+ Being *being = beingManager->findBeing(msg.readInt16());
+ if (!being || !mAcceptTradeRequests)
{
- case 0: // Too far away
- chatWindow->chatLog(_("Trading isn't possible. Trade partner is too far away."),
- BY_SERVER);
- break;
- case 1: // Character doesn't exist
- chatWindow->chatLog(_("Trading isn't possible. Character doesn't exist."),
- BY_SERVER);
- break;
- case 2: // Invite request check failed...
- chatWindow->chatLog(_("Trade cancelled due to an unknown reason."),
- BY_SERVER);
- break;
- case 3: // Trade accepted
- tradeWindow->reset();
- tradeWindow->setCaption(
- _("Trade: You and ") + tradePartnerName);
- tradeWindow->setVisible(true);
- break;
- case 4: // Trade cancelled
- if (player_relations.hasPermission(tradePartnerName,
- PlayerRelation::SPEECH_LOG))
- chatWindow->chatLog(_("Trade with ") + tradePartnerName +
- _(" cancelled"), BY_SERVER);
- // otherwise ignore silently
-
- tradeWindow->setVisible(false);
- player_node->setTrading(false);
- break;
- default: // Shouldn't happen as well, but to be sure
- chatWindow->chatLog(_("Unhandled trade cancel packet"),
- BY_SERVER);
- break;
+ Net::GameServer::Player::acceptTrade(false);
+ break;
}
- break;
+ player_node->setTrading(true);
+ tradePartnerName = being->getName();
+ tradePartnerID = being->getId();
+ ConfirmDialog *dlg = new ConfirmDialog("Request for trade",
+ tradePartnerName + " wants to trade with you, do you accept?");
+ dlg->addActionListener(&listener);
+ } break;
+
+ case GPMSG_TRADE_ADD_ITEM:
+ {
+ int type = msg.readInt16();
+ int amount = msg.readInt8();
+ tradeWindow->addItem(type, false, amount);
+ } break;
- case SMSG_TRADE_ITEM_ADD:
- {
- Sint32 amount = msg->readInt32();
- Sint16 type = msg->readInt16();
- msg->readInt8(); // identified flag
- msg->readInt8(); // attribute
- msg->readInt8(); // refine
- msg->skip(8); // card (4 shorts)
-
- // TODO: handle also identified, etc
- if (type == 0) {
- tradeWindow->addMoney(amount);
- } else {
- tradeWindow->addItem(type, false, amount, false);
- }
- }
+ case GPMSG_TRADE_SET_MONEY:
+ tradeWindow->setMoney(msg.readInt32());
break;
- case SMSG_TRADE_ITEM_ADD_RESPONSE:
- // Trade: New Item add response (was 0x00ea, now 01b1)
- {
- const int index = msg->readInt16();
- Item *item = player_node->getInventory()->getItem(index);
- if (!item)
- {
- tradeWindow->receivedOk(true);
- return;
- }
- Sint16 quantity = msg->readInt16();
-
- switch (msg->readInt8())
- {
- case 0:
- // Successfully added item
- if (item->isEquipment() && item->isEquipped())
- {
- player_node->unequipItem(item);
- }
- tradeWindow->addItem(item->getId(), true, quantity,
- item->isEquipment());
- item->increaseQuantity(-quantity);
- break;
- case 1:
- // Add item failed - player overweighted
- chatWindow->chatLog(_("Failed adding item. Trade partner is over weighted."),
- BY_SERVER);
- break;
- case 2:
- // Add item failed - player has no free slot
- chatWindow->chatLog(_("Failed adding item. Trade partner has no free slot."),
- BY_SERVER);
- break;
- default:
- chatWindow->chatLog(_("Failed adding item for unknown reason."),
- BY_SERVER);
- break;
- }
- }
+ case GPMSG_TRADE_START:
+ tradeWindow->reset();
+ tradeWindow->setCaption("Trading with " + tradePartnerName);
+ tradeWindow->setVisible(true);
break;
- case SMSG_TRADE_OK:
- // 0 means ok from myself, 1 means ok from other;
- tradeWindow->receivedOk(msg->readInt8() == 0);
+ case GPMSG_TRADE_ACCEPT:
+ tradeWindow->receivedOk();
break;
- case SMSG_TRADE_CANCEL:
- chatWindow->chatLog(_("Trade canceled."), BY_SERVER);
+ case GPMSG_TRADE_CANCEL:
+ chatWindow->chatLog("Trade canceled.", BY_SERVER);
tradeWindow->setVisible(false);
tradeWindow->reset();
player_node->setTrading(false);
break;
- case SMSG_TRADE_COMPLETE:
- chatWindow->chatLog(_("Trade completed."), BY_SERVER);
+ case GPMSG_TRADE_COMPLETE:
+ chatWindow->chatLog("Trade completed.", BY_SERVER);
tradeWindow->setVisible(false);
tradeWindow->reset();
player_node->setTrading(false);
diff --git a/src/net/tradehandler.h b/src/net/tradehandler.h
index d479e43f..6ffe17b5 100644
--- a/src/net/tradehandler.h
+++ b/src/net/tradehandler.h
@@ -24,14 +24,30 @@
#include "messagehandler.h"
-class Network;
-
class TradeHandler : public MessageHandler
{
public:
TradeHandler();
- void handleMessage(MessageIn *msg);
+ void handleMessage(MessageIn &msg);
+
+ /**
+ * Returns whether trade requests are accepted.
+ *
+ * @see setAcceptTradeRequests
+ */
+ bool acceptTradeRequests() const
+ { return mAcceptTradeRequests; }
+
+ /**
+ * Sets whether trade requests are accepted. When set to false, trade
+ * requests are automatically denied. When true, a popup will ask the
+ * player whether he wants to trade.
+ */
+ void setAcceptTradeRequests(bool acceptTradeRequests);
+
+ private:
+ bool mAcceptTradeRequests;
};
#endif
diff --git a/src/npc.cpp b/src/npc.cpp
index 92db9373..bc25fa5d 100644
--- a/src/npc.cpp
+++ b/src/npc.cpp
@@ -26,20 +26,30 @@
#include "gui/npc_text.h"
+#ifdef TMWSERV_SUPPORT
+#include "net/gameserver/player.h"
+#else
#include "net/messageout.h"
-#include "net/protocol.h"
+#include "net/ea/protocol.h"
+#endif
#include "resources/npcdb.h"
extern NpcTextDialog *npcTextDialog;
-NPC *current_npc = NULL;
+NPC *current_npc = 0;
static const int NAME_X_OFFSET = 15;
static const int NAME_Y_OFFSET = 30;
+#ifdef TMWSERV_SUPPORT
+NPC::NPC(Uint16 id, int job, Map *map):
+ Player(id, job, map)
+#else
NPC::NPC(Uint32 id, Uint16 job, Map *map, Network *network):
- Player(id, job, map), mNetwork(network)
+ Player(id, job, map),
+ mNetwork(network)
+#endif
{
NPCInfo info = NPCDB::get(job);
@@ -108,44 +118,60 @@ Being::Type NPC::getType() const
void NPC::talk()
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::talkToNPC(mId, true);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_TALK);
outMsg.writeInt32(mId);
outMsg.writeInt8(0);
+#endif
current_npc = this;
}
void NPC::nextDialog()
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::talkToNPC(mId, false);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_NEXT_REQUEST);
outMsg.writeInt32(mId);
+#endif
}
void NPC::dialogChoice(char choice)
{
+#ifdef TMWSERV_SUPPORT
+ Net::GameServer::Player::selectFromNPC(mId, choice);
+#else
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_LIST_CHOICE);
outMsg.writeInt32(mId);
outMsg.writeInt8(choice);
+#endif
}
void NPC::integerInput(int value)
{
+#ifdef EATHENA_SUPPORT
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_INT_RESPONSE);
outMsg.writeInt32(mId);
outMsg.writeInt32(value);
+#endif
}
void NPC::stringInput(const std::string &value)
{
+#ifdef EATHENA_SUPPORT
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_STR_RESPONSE);
outMsg.writeInt16(value.length() + 9);
outMsg.writeInt32(mId);
outMsg.writeString(value, value.length());
outMsg.writeInt8(0);
+#endif
}
/*
@@ -154,25 +180,39 @@ void NPC::stringInput(const std::string &value)
*/
void NPC::buy()
{
+ // XXX Convert for new server
+#ifdef EATHENA_SUPPORT
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_BUY_SELL_REQUEST);
outMsg.writeInt32(mId);
outMsg.writeInt8(0);
+#endif
}
void NPC::sell()
{
+ // XXX Convert for new server
+#ifdef EATHENA_SUPPORT
MessageOut outMsg(mNetwork);
outMsg.writeInt16(CMSG_NPC_BUY_SELL_REQUEST);
outMsg.writeInt32(mId);
outMsg.writeInt8(1);
+#endif
}
void NPC::updateCoords()
{
if (mName)
{
- mName->adviseXY(mPx + NAME_X_OFFSET, mPy + NAME_Y_OFFSET);
+#ifdef TMWSERV_SUPPORT
+ const Vector &pos = getPosition();
+ const int px = (int) pos.x + NAME_X_OFFSET;
+ const int py = (int) pos.y + NAME_Y_OFFSET;
+#else
+ const int px = mPx + NAME_X_OFFSET;
+ const int py = mPy + NAME_Y_OFFSET;
+#endif
+ mName->adviseXY(px, py);
}
}
diff --git a/src/npc.h b/src/npc.h
index 81b6d51e..b003b82e 100644
--- a/src/npc.h
+++ b/src/npc.h
@@ -24,14 +24,20 @@
#include "player.h"
+#ifdef EATHENA_SUPPORT
class Network;
+#endif
class Graphics;
class Text;
class NPC : public Player
{
public:
+#ifdef TMWSERV_SUPPORT
+ NPC(Uint16 id, int sprite, Map *map);
+#else
NPC(Uint32 id, Uint16 job, Map *map, Network *network);
+#endif
~NPC();
@@ -55,8 +61,23 @@ class NPC : public Player
* interface problems
*/
void handleDeath();
+
+ /**
+ * Gets the way an NPC is blocked by other things on the map
+ */
+ virtual unsigned char getWalkMask() const
+ { return 0x83; } // blocked like a monster by walls, monsters and characters ( bin 1000 0011)
+
protected:
+ /**
+ * Gets the way a monster blocks pathfinding for other objects
+ */
+ virtual Map::BlockType getBlockType() const
+ { return Map::BLOCKTYPE_CHARACTER; } //blocks like a player character
+
+#ifdef EATHENA_SUPPORT
Network *mNetwork;
+#endif
void updateCoords();
private:
Text *mName;
diff --git a/src/particle.cpp b/src/particle.cpp
index 45cbb4c9..f021f6e5 100644
--- a/src/particle.cpp
+++ b/src/particle.cpp
@@ -345,10 +345,11 @@ Particle *Particle::addTextSplashEffect(const std::string &text,
}
Particle *Particle::addTextRiseFadeOutEffect(const std::string &text,
+ int colorR, int colorG, int colorB,
gcn::Font *font,
int x, int y)
{
- Particle *newParticle = new TextParticle(mMap, text, 255, 255, 255, font);
+ Particle *newParticle = new TextParticle(mMap, text, colorR, colorG, colorB, font);
newParticle->moveTo(x, y);
newParticle->setVelocity(0.0f, 0.0f, 0.5f);
newParticle->setGravity(0.0015f);
diff --git a/src/particle.h b/src/particle.h
index 1baf11f8..008c343b 100644
--- a/src/particle.h
+++ b/src/particle.h
@@ -113,6 +113,7 @@ class Particle : public Sprite
* Creates a standalone text particle.
*/
Particle *addTextRiseFadeOutEffect(const std::string &text,
+ int colorR, int colorG, int colorB,
gcn::Font *font,
int x, int y);
@@ -284,7 +285,7 @@ class Particle : public Sprite
// follow-point particles
Particle *mTarget; /**< The particle that attracts this particle*/
- float mAcceleration; /**< Acceleration towards the target particle in pixels per game-tick²*/
+ float mAcceleration; /**< Acceleration towards the target particle in pixels per game-tick²*/
float mInvDieDistance; /**< Distance in pixels from the target particle that causes the destruction of the particle*/
float mMomentum; /**< How much speed the particle retains after each game tick*/
};
diff --git a/src/party.cpp b/src/party.cpp
index ae8df175..d22db55f 100644
--- a/src/party.cpp
+++ b/src/party.cpp
@@ -27,7 +27,7 @@
#include "gui/confirm_dialog.h"
#include "net/messageout.h"
-#include "net/protocol.h"
+#include "net/ea/protocol.h"
#include "utils/gettext.h"
#include "utils/strprintf.h"
diff --git a/src/player.cpp b/src/player.cpp
index f620e637..09eec0d1 100644
--- a/src/player.cpp
+++ b/src/player.cpp
@@ -21,6 +21,9 @@
#include "animatedsprite.h"
#include "game.h"
+#ifdef TMWSERV_SUPPORT
+#include "guild.h"
+#endif
#include "player.h"
#include "text.h"
@@ -65,6 +68,7 @@ void Player::setName(const std::string &name)
}
}
+#ifdef EATHENA_SUPPORT
void Player::logic()
{
switch (mAction)
@@ -82,7 +86,7 @@ void Player::logic()
break;
case WALK:
- mFrame = (get_elapsed_time(mWalkTime) * 6) / mWalkSpeed;
+ mFrame = (get_elapsed_time(mWalkTime) * 6) / getWalkSpeed();
if (mFrame >= 6)
nextStep();
@@ -107,6 +111,7 @@ void Player::logic()
Being::logic();
}
+#endif
Being::Type Player::getType() const
{
@@ -153,7 +158,7 @@ void Player::setHairStyle(int style, int color)
setAction(mAction);
}
-void Player::setSprite(int slot, int id, std::string color)
+void Player::setSprite(int slot, int id, const std::string &color)
{
// id = 0 means unequip
if (id == 0)
@@ -161,8 +166,10 @@ void Player::setSprite(int slot, int id, std::string color)
delete mSprites[slot];
mSprites[slot] = NULL;
+#ifdef EATHENA_SUPPORT
if (slot == WEAPON_SPRITE)
mEquippedWeapon = NULL;
+#endif
}
else
{
@@ -199,3 +206,55 @@ void Player::updateCoords()
mName->adviseXY(mPx + NAME_X_OFFSET, mPy + NAME_Y_OFFSET);
}
+#ifdef TMWSERV_SUPPORT
+
+Guild* Player::addGuild(short guildId, short rights)
+{
+ Guild *guild = new Guild(guildId, rights);
+ mGuilds.insert(std::pair<int, Guild*>(guildId, guild));
+ return guild;
+}
+
+void Player::removeGuild(int id)
+{
+ mGuilds.erase(id);
+}
+
+Guild* Player::getGuild(const std::string &guildName)
+{
+ std::map<int, Guild*>::iterator itr, itr_end = mGuilds.end();
+ for (itr = mGuilds.begin(); itr != itr_end; ++itr)
+ {
+ Guild *guild = itr->second;
+ if (guild->getName() == guildName)
+ {
+ return guild;
+ }
+ }
+
+ return NULL;
+}
+
+Guild* Player::getGuild(int id)
+{
+ std::map<int, Guild*>::iterator itr;
+ itr = mGuilds.find(id);
+ if (itr != mGuilds.end())
+ {
+ return itr->second;
+ }
+
+ return NULL;
+}
+
+short Player::getNumberOfGuilds()
+{
+ return mGuilds.size();
+}
+
+void Player::setInParty(bool value)
+{
+ mInParty = value;
+}
+
+#endif
diff --git a/src/player.h b/src/player.h
index f9911bb8..1904c6d9 100644
--- a/src/player.h
+++ b/src/player.h
@@ -27,6 +27,9 @@
class FlashText;
class Graphics;
class Map;
+#ifdef TMWSERV_SUPPORT
+class Guild;
+#endif
/**
* A player being. Players have their name drawn beneath them. This class also
@@ -36,6 +39,9 @@ class Map;
class Player : public Being
{
public:
+ /**
+ * Constructor.
+ */
Player(int id, int job, Map *map);
~Player();
@@ -45,7 +51,9 @@ class Player : public Being
*/
virtual void setName(const std::string &name);
+#ifdef EATHENA_SUPPORT
virtual void logic();
+#endif
virtual Type getType() const;
@@ -66,17 +74,76 @@ class Player : public Being
/**
* Sets visible equipments for this player.
*/
- virtual void setSprite(int slot, int id, std::string color = "");
+ virtual void setSprite(int slot, int id, const std::string &color = "");
/**
* Flash the player's name
*/
void flash(int time);
+#ifdef TMWSERV_SUPPORT
+ /**
+ * Adds a guild to the player.
+ */
+ Guild* addGuild(short guildId, short rights);
+
+ /**
+ * Removers a guild from the player.
+ */
+ void removeGuild(int id);
+
+ /**
+ * Returns a pointer to the specified guild.
+ */
+ Guild* getGuild(const std::string &guildName);
+
+ /**
+ * Returns a pointer to the guild with matching id.
+ */
+ Guild* getGuild(int id);
+
+ /**
+ * Get number of guilds the player belongs to.
+ */
+ short getNumberOfGuilds();
+
+ /**
+ * Set the player in party
+ */
+ void setInParty(bool value);
+
+ /**
+ * Returns whether player is in the party
+ */
+ bool getInParty() const { return mInParty; }
+#endif
+
+ /**
+ * Gets the way the character is blocked by other objects.
+ */
+ virtual unsigned char getWalkMask() const
+ { return 0x82; } // blocked by walls and monsters (bin 1000 0010)
+
protected:
+ /**
+ * Gets the way the monster blocks pathfinding for other objects.
+ */
+ virtual Map::BlockType getBlockType() const
+ { return Map::BLOCKTYPE_CHARACTER; }
+
virtual void updateCoords();
+#ifdef TMWSERV_SUPPORT
+ // Character guild information
+ std::map<int, Guild*> mGuilds;
+#endif
+
FlashText *mName;
+
+#ifdef TMWSERV_SUPPORT
+ private:
+ bool mInParty;
+#endif
};
#endif
diff --git a/src/resources/buddylist.cpp b/src/resources/buddylist.cpp
new file mode 100644
index 00000000..c85105c5
--- /dev/null
+++ b/src/resources/buddylist.cpp
@@ -0,0 +1,128 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <algorithm>
+#include <cstring>
+#include <iostream>
+#include <fstream>
+
+#include "buddylist.h"
+
+#include "../main.h"
+#include "../configuration.h"
+
+BuddyList::BuddyList()
+{
+ // TODO: A buddy list would have to use the Configuration class to store
+ // the buddies. Also, there is now a player relationship manager
+ // which probably makes this buddy list kind of obsolete.
+
+ // Find saved buddy list file
+ //mFilename = homeDir + "/buddy.txt";
+
+ // Load buddy from file
+ loadFile();
+}
+
+void BuddyList::loadFile()
+{
+ // Open file
+ std::ifstream inputStream(mFilename.c_str(), std::ios::in);
+ if (!inputStream) {
+ std::cerr << "Error opening input stream" << std::endl;
+ return;
+ }
+
+ do {
+ char *buddy = new char[LEN_MAX_USERNAME];
+ inputStream.getline(buddy, LEN_MAX_USERNAME);
+ // Ugly ?
+ if(strcmp(buddy,"")) mBuddylist.push_back(buddy);
+ delete [] buddy;
+ } while(!inputStream.eof());
+
+ // Read buddy and close file
+ inputStream.close();
+}
+
+void BuddyList::saveFile()
+{
+ std::string str;
+
+ // Open file
+ std::ofstream outputStream(mFilename.c_str(), std::ios::trunc);
+ if (!outputStream) {
+ std::cerr << "Error opening output stream" << std::endl;
+ return;
+ }
+
+ // Write buddy and close file
+ for (BuddyIterator i = mBuddylist.begin(); i != mBuddylist.end(); ++i)
+ {
+ outputStream << (const char*) i->c_str() << std::endl;
+ }
+ outputStream.close();
+}
+
+bool BuddyList::addBuddy(const std::string buddy)
+{
+ if (find(mBuddylist.begin(), mBuddylist.end(), buddy) != mBuddylist.end())
+ {
+ return false;
+ }
+
+ // Buddy doesnt exist, add it
+ mBuddylist.push_back(buddy);
+
+ // Save file
+ saveFile();
+
+ return true;
+}
+
+bool BuddyList::removeBuddy(const std::string buddy)
+{
+ BuddyIterator i = find(mBuddylist.begin(), mBuddylist.end(), buddy);
+
+ if (i != mBuddylist.end()) {
+ mBuddylist.erase(i);
+ saveFile();
+ return true;
+ }
+
+ return false;
+}
+
+int BuddyList::getNumberOfElements()
+{
+ return mBuddylist.size();
+}
+
+std::string BuddyList::getElementAt(int number)
+{
+ if (number >= (int) mBuddylist.size()) {
+ return "";
+ }
+
+ BuddyIterator i = mBuddylist.begin();
+ std::advance(i, number);
+ return *i;
+}
diff --git a/src/resources/buddylist.h b/src/resources/buddylist.h
new file mode 100644
index 00000000..6a3de8c4
--- /dev/null
+++ b/src/resources/buddylist.h
@@ -0,0 +1,79 @@
+/*
+ * The Mana World
+ * Copyright 2004 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _TMW_BUDDYLIST_H
+#define _TMW_BUDDYLIST_H
+
+#include <list>
+#include <string>
+
+#include <guichan/listmodel.hpp>
+
+class BuddyList : public gcn::ListModel {
+ public:
+ /**
+ * Constructor
+ */
+ BuddyList();
+
+ /**
+ * Destructor
+ */
+ virtual ~BuddyList() { }
+
+ /**
+ * Adds buddy to the list
+ */
+ bool addBuddy(const std::string buddy);
+
+ /**
+ * Removes buddy from the list
+ */
+ bool removeBuddy(const std::string buddy);
+
+ /**
+ * Returns the number of buddy on the list
+ */
+ int getNumberOfElements();
+
+ /**
+ * Returns the buddy of the number or null
+ */
+ std::string getElementAt(int number);
+
+ private:
+ /**
+ * Save buddy to file
+ */
+ void saveFile();
+
+ /**
+ * Load buddy from file
+ */
+ void loadFile();
+
+ typedef std::list<std::string> Buddies;
+ typedef Buddies::iterator BuddyIterator;
+ Buddies mBuddylist; /**< Buddy list */
+ std::string mFilename; /* File to work with */
+};
+
+#endif /* _TMW_BUDDYLIST_H */
diff --git a/src/resources/image.h b/src/resources/image.h
index fe3081ac..3160add8 100644
--- a/src/resources/image.h
+++ b/src/resources/image.h
@@ -40,8 +40,6 @@
#include "resource.h"
class Dye;
-class SDL_Rect;
-class SDL_Surface;
/**
* Defines a class for loading and storing images.
diff --git a/src/resources/itemdb.cpp b/src/resources/itemdb.cpp
index fec52150..7304f8a7 100644
--- a/src/resources/itemdb.cpp
+++ b/src/resources/itemdb.cpp
@@ -24,11 +24,13 @@
#include <libxml/tree.h>
#include "itemdb.h"
+#include "resourcemanager.h"
#include "../log.h"
#include "../utils/dtor.h"
#include "../utils/gettext.h"
+#include "../utils/strprintf.h"
#include "../utils/stringutils.h"
#include "../utils/xml.h"
@@ -44,6 +46,48 @@ namespace
static void loadSpriteRef(ItemInfo *itemInfo, xmlNodePtr node);
static void loadSoundRef(ItemInfo *itemInfo, xmlNodePtr node);
+static char const *const fields[][2] =
+{
+ { "attack", N_("Attack %+d") },
+ { "defense", N_("Defense %+d") },
+ { "hp", N_("HP %+d") },
+ { "mp", N_("MP %+d") }
+};
+
+static ItemType itemTypeFromString(const std::string &name, int id = 0)
+{
+ if (name=="generic") return ITEM_UNUSABLE;
+ else if (name=="usable") return ITEM_USABLE;
+ else if (name=="equip-1hand") return ITEM_EQUIPMENT_ONE_HAND_WEAPON;
+ else if (name=="equip-2hand") return ITEM_EQUIPMENT_TWO_HANDS_WEAPON;
+ else if (name=="equip-torso") return ITEM_EQUIPMENT_TORSO;
+ else if (name=="equip-arms") return ITEM_EQUIPMENT_ARMS;
+ else if (name=="equip-head") return ITEM_EQUIPMENT_HEAD;
+ else if (name=="equip-legs") return ITEM_EQUIPMENT_LEGS;
+ else if (name=="equip-shield") return ITEM_EQUIPMENT_SHIELD;
+ else if (name=="equip-ring") return ITEM_EQUIPMENT_RING;
+ else if (name=="equip-necklace") return ITEM_EQUIPMENT_NECKLACE;
+ else if (name=="equip-feet") return ITEM_EQUIPMENT_FEET;
+ else if (name=="equip-ammo") return ITEM_EQUIPMENT_AMMO;
+ else return ITEM_UNUSABLE;
+}
+
+static WeaponType weaponTypeFromString(const std::string &name, int id = 0)
+{
+ if (name=="knife") return WPNTYPE_KNIFE;
+ else if (name=="sword") return WPNTYPE_SWORD;
+ else if (name=="polearm") return WPNTYPE_POLEARM;
+ else if (name=="staff") return WPNTYPE_STAFF;
+ else if (name=="whip") return WPNTYPE_WHIP;
+ else if (name=="bow") return WPNTYPE_BOW;
+ else if (name=="shooting") return WPNTYPE_SHOOTING;
+ else if (name=="mace") return WPNTYPE_MACE;
+ else if (name=="axe") return WPNTYPE_AXE;
+ else if (name=="thrown") return WPNTYPE_THROWN;
+
+ else return WPNTYPE_NONE;
+}
+
void ItemDB::load()
{
if (mLoaded)
@@ -82,57 +126,77 @@ void ItemDB::load()
logger->log("ItemDB: Redefinition of item ID %d", id);
}
- std::string type = XML::getProperty(node, "type", "other");
+ std::string typeStr = XML::getProperty(node, "type", "other");
int weight = XML::getProperty(node, "weight", 0);
int view = XML::getProperty(node, "view", 0);
std::string name = XML::getProperty(node, "name", "");
std::string image = XML::getProperty(node, "image", "");
std::string description = XML::getProperty(node, "description", "");
- std::string effect = XML::getProperty(node, "effect", "");
+#ifdef TMWSERV_SUPPORT
+ int weaponType = weaponTypeFromString(XML::getProperty(node, "weapon-type", ""));
+#else
int weaponType = XML::getProperty(node, "weapon_type", 0);
+#endif
+ int attackRange = XML::getProperty(node, "attack-range", 0);
+
+ ItemInfo *itemInfo = new ItemInfo;
+ itemInfo->setId(id);
+ itemInfo->setImageName(image);
+ itemInfo->setName(name.empty() ? _("Unnamed") : name);
+ itemInfo->setDescription(description);
+#ifdef TMWSERV_SUPPORT
+ int type = itemTypeFromString(typeStr);
+ itemInfo->setType(type);
+#else
+ itemInfo->setType(typeStr);
+#endif
+ itemInfo->setView(view);
+ itemInfo->setWeight(weight);
+ itemInfo->setWeaponType(weaponType);
+ itemInfo->setAttackRange(attackRange);
+
+#ifdef TMWSERV_SUPPORT
+ std::string effect;
+ for (int i = 0; i < int(sizeof(fields) / sizeof(fields[0])); ++i)
+ {
+ int value = XML::getProperty(node, fields[i][0], 0);
+ if (!value) continue;
+ if (!effect.empty()) effect += " / ";
+ effect += strprintf(gettext(fields[i][1]), value);
+ }
+#else
+ std::string effect = XML::getProperty(node, "effect", "");
+#endif
+ itemInfo->setEffect(effect);
+
- if (id)
+ for_each_xml_child_node(itemChild, node)
{
- ItemInfo *itemInfo = new ItemInfo;
- itemInfo->setId(id);
- itemInfo->setImageName(image);
- itemInfo->setName(name.empty() ? _("Unnamed") : name);
- itemInfo->setDescription(description);
- itemInfo->setEffect(effect);
- itemInfo->setType(type);
- itemInfo->setView(view);
- itemInfo->setWeight(weight);
- itemInfo->setWeaponType(weaponType);
-
- for_each_xml_child_node(itemChild, node)
+ if (xmlStrEqual(itemChild->name, BAD_CAST "sprite"))
+ {
+ loadSpriteRef(itemInfo, itemChild);
+ }
+ else if (xmlStrEqual(itemChild->name, BAD_CAST "sound"))
{
- if (xmlStrEqual(itemChild->name, BAD_CAST "sprite"))
- {
- loadSpriteRef(itemInfo, itemChild);
- }
- else if (xmlStrEqual(itemChild->name, BAD_CAST "sound"))
- {
- loadSoundRef(itemInfo, itemChild);
- }
+ loadSoundRef(itemInfo, itemChild);
}
+ }
- mItemInfos[id] = itemInfo;
- if (!name.empty())
+ mItemInfos[id] = itemInfo;
+ if (!name.empty())
+ {
+ NamedItemInfoIterator itr = mNamedItemInfos.find(name);
+ if (itr == mNamedItemInfos.end())
+ {
+ std::string temp = name;
+ toLower(trim(temp));
+
+ mNamedItemInfos[temp] = itemInfo;
+ }
+ else
{
- NamedItemInfoIterator itr = mNamedItemInfos.find(name);
- if (itr == mNamedItemInfos.end())
- {
- std::string temp = name;
- toLower(trim(temp));
-
- mNamedItemInfos[temp] = itemInfo;
- }
- else
- {
- logger->log("ItemDB: Duplicate name of item found item %d",
- id);
- }
+ logger->log("ItemDB: Duplicate name of item found item %d", id);
}
}
diff --git a/src/resources/itemdb.h b/src/resources/itemdb.h
index 08a7acd0..68f3b039 100644
--- a/src/resources/itemdb.h
+++ b/src/resources/itemdb.h
@@ -29,7 +29,7 @@
class ItemInfo;
/**
- * The namespace that holds the item information.
+ * Item information database.
*/
namespace ItemDB
{
diff --git a/src/resources/iteminfo.cpp b/src/resources/iteminfo.cpp
index 2f118284..f7118755 100644
--- a/src/resources/iteminfo.cpp
+++ b/src/resources/iteminfo.cpp
@@ -44,6 +44,26 @@ void ItemInfo::setWeaponType(int type)
// See server item.hpp file for type values.
switch (type)
{
+#ifdef TMWSERV_SUPPORT
+ case WPNTYPE_NONE:
+ mAttackType = ACTION_DEFAULT;
+ break;
+ case WPNTYPE_KNIFE:
+ case WPNTYPE_SWORD:
+ mAttackType = ACTION_ATTACK_STAB;
+ break;
+ case WPNTYPE_THROWN:
+ mAttackType = ACTION_ATTACK_THROW;
+ break;
+ case WPNTYPE_BOW:
+ mAttackType = ACTION_ATTACK_BOW;
+ break;
+ case WPNTYPE_POLEARM:
+ mAttackType = ACTION_ATTACK_SWING;
+ break;
+ default:
+ mAttackType = ACTION_ATTACK;
+#else
case 0: // none
mAttackType = ACTION_DEFAULT;
break;
@@ -62,6 +82,7 @@ void ItemInfo::setWeaponType(int type)
break;
default:
mAttackType = ACTION_ATTACK;
+#endif
}
}
diff --git a/src/resources/iteminfo.h b/src/resources/iteminfo.h
index c03dec28..10749c9e 100644
--- a/src/resources/iteminfo.h
+++ b/src/resources/iteminfo.h
@@ -36,6 +36,74 @@ enum EquipmentSoundEvent
EQUIP_EVENT_HIT
};
+enum EquipmentSlot
+{
+ // Equipment rules:
+ // 1 Brest equipment
+ EQUIP_TORSO_SLOT = 0,
+ // 1 arms equipment
+ EQUIP_ARMS_SLOT = 1,
+ // 1 head equipment
+ EQUIP_HEAD_SLOT = 2,
+ // 1 legs equipment
+ EQUIP_LEGS_SLOT = 3,
+ // 1 feet equipment
+ EQUIP_FEET_SLOT = 4,
+ // 2 rings
+ EQUIP_RING1_SLOT = 5,
+ EQUIP_RING2_SLOT = 6,
+ // 1 necklace
+ EQUIP_NECKLACE_SLOT = 7,
+ // Fight:
+ // 2 one-handed weapons
+ // or 1 two-handed weapon
+ // or 1 one-handed weapon + 1 shield.
+ EQUIP_FIGHT1_SLOT = 8,
+ EQUIP_FIGHT2_SLOT = 9,
+ // Projectile:
+ // this item does not amount to one, it only indicates the chosen projectile.
+ EQUIP_PROJECTILE_SLOT = 10
+};
+
+
+/**
+ * Enumeration of available Item types.
+ */
+enum ItemType
+{
+ ITEM_UNUSABLE = 0,
+ ITEM_USABLE, // 1
+ ITEM_EQUIPMENT_ONE_HAND_WEAPON, // 2
+ ITEM_EQUIPMENT_TWO_HANDS_WEAPON,// 3
+ ITEM_EQUIPMENT_TORSO,// 4
+ ITEM_EQUIPMENT_ARMS,// 5
+ ITEM_EQUIPMENT_HEAD,// 6
+ ITEM_EQUIPMENT_LEGS,// 7
+ ITEM_EQUIPMENT_SHIELD,// 8
+ ITEM_EQUIPMENT_RING,// 9
+ ITEM_EQUIPMENT_NECKLACE,// 10
+ ITEM_EQUIPMENT_FEET,// 11
+ ITEM_EQUIPMENT_AMMO// 12
+};
+
+/**
+ * Enumeration of available weapon's types.
+ */
+enum WeaponType
+{
+ WPNTYPE_NONE = 0,
+ WPNTYPE_KNIFE,
+ WPNTYPE_SWORD,
+ WPNTYPE_POLEARM,
+ WPNTYPE_STAFF,
+ WPNTYPE_WHIP,
+ WPNTYPE_BOW,
+ WPNTYPE_SHOOTING,
+ WPNTYPE_MACE,
+ WPNTYPE_AXE,
+ WPNTYPE_THROWN
+};
+
/**
* Defines a class for storing item infos. This includes information used when
* the item is equipped.
@@ -47,7 +115,11 @@ class ItemInfo
* Constructor.
*/
ItemInfo():
+#ifdef TMWSERV_SUPPORT
+ mType(ITEM_UNUSABLE),
+#else
mType(""),
+#endif
mWeight(0),
mView(0),
mAttackType(ACTION_DEFAULT)
@@ -83,10 +155,18 @@ class ItemInfo
const std::string& getEffect() const { return mEffect; }
+#ifdef TMWSERV_SUPPORT
+ void setType(short type)
+ { mType = type; }
+
+ short getType() const
+ { return mType; }
+#else
void setType(const std::string& type)
{ mType = type; }
const std::string& getType() const { return mType; }
+#endif
void setWeight(short weight)
{ mWeight = weight; }
@@ -107,6 +187,12 @@ class ItemInfo
SpriteAction getAttackType() const
{ return mAttackType; }
+ int getAttackRange() const
+ { return mAttackRange; }
+
+ void setAttackRange(int r)
+ { mAttackRange = r; }
+
void addSound(EquipmentSoundEvent event, const std::string &filename);
const std::string& getSound(EquipmentSoundEvent event) const;
@@ -116,13 +202,18 @@ class ItemInfo
std::string mName;
std::string mDescription; /**< Short description. */
std::string mEffect; /**< Description of effects. */
+#ifdef TMWSERV_SUPPORT
+ char mType; /**< Item type. */
+#else
std::string mType; /**< Item type. */
+#endif
short mWeight; /**< Weight in grams. */
int mView; /**< Item ID of how this item looks. */
int mId; /**< Item ID */
// Equipment related members
SpriteAction mAttackType; /**< Attack type, in case of weapon. */
+ int mAttackRange; /**< Attack range, will be zero if non weapon. */
/** Maps gender to sprite filenames. */
std::map<int, std::string> mAnimationFiles;
diff --git a/src/resources/mapreader.cpp b/src/resources/mapreader.cpp
index 5fa47261..c4cb7447 100644
--- a/src/resources/mapreader.cpp
+++ b/src/resources/mapreader.cpp
@@ -310,7 +310,8 @@ static void setTile(Map *map, MapLayer *layer, int x, int y, int gid)
layer->setTile(x, y, img);
} else {
// Set collision tile
- map->setWalk(x, y, (!set || (gid - set->getFirstGid() == 0)));
+ if (set && (gid - set->getFirstGid() != 0))
+ map->blockTile(x, y, Map::BLOCKTYPE_WALL);
}
}
diff --git a/src/resources/monsterdb.cpp b/src/resources/monsterdb.cpp
index e0259b29..cee9eea5 100644
--- a/src/resources/monsterdb.cpp
+++ b/src/resources/monsterdb.cpp
@@ -95,8 +95,7 @@ void MonsterDB::load()
currentInfo->addSprite(
(const char*) spriteNode->xmlChildrenNode->content);
}
-
- if (xmlStrEqual(spriteNode->name, BAD_CAST "sound"))
+ else if (xmlStrEqual(spriteNode->name, BAD_CAST "sound"))
{
std::string event = XML::getProperty(spriteNode, "event", "");
const char *filename;
@@ -126,15 +125,16 @@ void MonsterDB::load()
currentInfo->getName().c_str());
}
}
-
- if (xmlStrEqual(spriteNode->name, BAD_CAST "attack"))
+ else if (xmlStrEqual(spriteNode->name, BAD_CAST "attack"))
{
- std::string event = XML::getProperty(
+ const int id = XML::getProperty(spriteNode, "id", 0);
+ const std::string particleEffect = XML::getProperty(
spriteNode, "particle-effect", "");
- currentInfo->addAttackParticleEffect(event);
+ SpriteAction spriteAction = SpriteDef::makeSpriteAction(
+ XML::getProperty(spriteNode, "action", "attack"));
+ currentInfo->addMonsterAttack(id, particleEffect, spriteAction);
}
-
- if (xmlStrEqual(spriteNode->name, BAD_CAST "particlefx"))
+ else if (xmlStrEqual(spriteNode->name, BAD_CAST "particlefx"))
{
currentInfo->addParticleEffect(
(const char*) spriteNode->xmlChildrenNode->content);
diff --git a/src/resources/monsterinfo.cpp b/src/resources/monsterinfo.cpp
index 503990e7..2fc16bef 100644
--- a/src/resources/monsterinfo.cpp
+++ b/src/resources/monsterinfo.cpp
@@ -25,7 +25,6 @@
MonsterInfo::MonsterInfo()
{
-
}
MonsterInfo::~MonsterInfo()
@@ -35,8 +34,7 @@ MonsterInfo::~MonsterInfo()
mSounds.clear();
}
-
-void MonsterInfo::addSound(MonsterSoundEvent event, std::string filename)
+void MonsterInfo::addSound(MonsterSoundEvent event, const std::string &filename)
{
if (mSounds.find(event) == mSounds.end())
{
@@ -46,24 +44,41 @@ void MonsterInfo::addSound(MonsterSoundEvent event, std::string filename)
mSounds[event]->push_back("sfx/" + filename);
}
+const std::string &MonsterInfo::getSound(MonsterSoundEvent event) const
+{
+ static std::string empty("");
+ std::map<MonsterSoundEvent, std::vector<std::string>* >::const_iterator i =
+ mSounds.find(event);
+ return (i == mSounds.end()) ? empty :
+ i->second->at(rand() % i->second->size());
+}
-std::string MonsterInfo::getSound(MonsterSoundEvent event) const
+const std::string &MonsterInfo::getAttackParticleEffect(int attackType) const
{
- std::map<MonsterSoundEvent, std::vector<std::string>* >::const_iterator i;
+ static std::string empty("");
+ std::map<int, MonsterAttack*>::const_iterator i =
+ mMonsterAttacks.find(attackType);
+ return (i == mMonsterAttacks.end()) ? empty : (*i).second->particleEffect;
+}
- i = mSounds.find(event);
+SpriteAction MonsterInfo::getAttackAction(int attackType) const
+{
+ std::map<int, MonsterAttack*>::const_iterator i =
+ mMonsterAttacks.find(attackType);
+ return (i == mMonsterAttacks.end()) ? ACTION_ATTACK : (*i).second->action;
+}
- if (i == mSounds.end())
- {
- return "";
- }
- else
- {
- return i->second->at(rand()%i->second->size());
- }
+void MonsterInfo::addMonsterAttack(int id,
+ const std::string &particleEffect,
+ SpriteAction action)
+{
+ MonsterAttack *a = new MonsterAttack;
+ a->particleEffect = particleEffect;
+ a->action = action;
+ mMonsterAttacks[id] = a;
}
-void MonsterInfo::addParticleEffect(std::string filename)
+void MonsterInfo::addParticleEffect(const std::string &filename)
{
mParticleEffects.push_back(filename);
}
diff --git a/src/resources/monsterinfo.h b/src/resources/monsterinfo.h
index 359791fd..02574147 100644
--- a/src/resources/monsterinfo.h
+++ b/src/resources/monsterinfo.h
@@ -37,6 +37,12 @@ enum MonsterSoundEvent
MONSTER_EVENT_DIE
};
+struct MonsterAttack
+{
+ std::string particleEffect;
+ SpriteAction action;
+};
+
/**
* Holds information about a certain type of monster. This includes the name
* of the monster, the sprite to display and the sounds the monster makes.
@@ -56,16 +62,17 @@ class MonsterInfo
*/
~MonsterInfo();
- void setName(std::string name) { mName = name; }
+ void setName(const std::string &name) { mName = name; }
- void addSprite(std::string filename) { mSprites.push_back(filename); }
+ void addSprite(const std::string &filename)
+ { mSprites.push_back(filename); }
void setTargetCursorSize(Being::TargetCursorSize targetCursorSize)
{ mTargetCursorSize = targetCursorSize; }
- void addSound(MonsterSoundEvent event, std::string filename);
+ void addSound(MonsterSoundEvent event, const std::string &filename);
- void addParticleEffect(std::string filename);
+ void addParticleEffect(const std::string &filename);
const std::string& getName() const
{ return mName; }
@@ -76,22 +83,25 @@ class MonsterInfo
Being::TargetCursorSize getTargetCursorSize() const
{ return mTargetCursorSize; }
- std::string getSound(MonsterSoundEvent event) const;
+ const std::string &getSound(MonsterSoundEvent event) const;
+
+ void addMonsterAttack(int id,
+ const std::string &particleEffect,
+ SpriteAction action);
- std::string getAttackParticleEffect() const { return mAttackParticle; }
+ const std::string &getAttackParticleEffect(int attackType) const;
- void addAttackParticleEffect(const std::string &particleEffect)
- { mAttackParticle = particleEffect; }
+ SpriteAction getAttackAction(int attackType) const;
const std::list<std::string>& getParticleEffects() const
{ return mParticleEffects; }
private:
std::string mName;
- std::string mAttackParticle;
std::list<std::string> mSprites;
Being::TargetCursorSize mTargetCursorSize;
std::map<MonsterSoundEvent, std::vector<std::string>* > mSounds;
+ std::map<int, MonsterAttack*> mMonsterAttacks;
std::list<std::string> mParticleEffects;
};
diff --git a/src/resources/spritedef.cpp b/src/resources/spritedef.cpp
index 0a87db16..390bd3d0 100644
--- a/src/resources/spritedef.cpp
+++ b/src/resources/spritedef.cpp
@@ -348,6 +348,38 @@ SpriteAction SpriteDef::makeSpriteAction(const std::string &action)
else if (action == "attack_throw") {
return ACTION_ATTACK_THROW;
}
+#ifdef TMWSERV_SUPPORT
+ else if (action == "special0") {
+ return ACTION_SPECIAL_0;
+ }
+ else if (action == "special1") {
+ return ACTION_SPECIAL_1;
+ }
+ else if (action == "special2") {
+ return ACTION_SPECIAL_2;
+ }
+ else if (action == "special3") {
+ return ACTION_SPECIAL_3;
+ }
+ else if (action == "special4") {
+ return ACTION_SPECIAL_4;
+ }
+ else if (action == "special5") {
+ return ACTION_SPECIAL_5;
+ }
+ else if (action == "special6") {
+ return ACTION_SPECIAL_6;
+ }
+ else if (action == "special7") {
+ return ACTION_SPECIAL_7;
+ }
+ else if (action == "special8") {
+ return ACTION_SPECIAL_8;
+ }
+ else if (action == "special9") {
+ return ACTION_SPECIAL_9;
+ }
+#endif
else if (action == "cast_magic") {
return ACTION_CAST_MAGIC;
}
diff --git a/src/resources/spritedef.h b/src/resources/spritedef.h
index b9d7b85d..c3db8d64 100644
--- a/src/resources/spritedef.h
+++ b/src/resources/spritedef.h
@@ -43,6 +43,18 @@ enum SpriteAction
ACTION_ATTACK_STAB,
ACTION_ATTACK_BOW,
ACTION_ATTACK_THROW,
+#ifdef TMWSERV_SUPPORT
+ ACTION_SPECIAL_0,
+ ACTION_SPECIAL_1,
+ ACTION_SPECIAL_2,
+ ACTION_SPECIAL_3,
+ ACTION_SPECIAL_4,
+ ACTION_SPECIAL_5,
+ ACTION_SPECIAL_6,
+ ACTION_SPECIAL_7,
+ ACTION_SPECIAL_8,
+ ACTION_SPECIAL_9,
+#endif
ACTION_CAST_MAGIC,
ACTION_USE_ITEM,
ACTION_SIT,
@@ -55,8 +67,8 @@ enum SpriteAction
enum SpriteDirection
{
DIRECTION_DEFAULT = 0,
- DIRECTION_DOWN,
DIRECTION_UP,
+ DIRECTION_DOWN,
DIRECTION_LEFT,
DIRECTION_RIGHT,
DIRECTION_INVALID
diff --git a/src/shopitem.h b/src/shopitem.h
index 3353ebe7..50af4991 100644
--- a/src/shopitem.h
+++ b/src/shopitem.h
@@ -49,7 +49,6 @@ class ShopItem : public Item
protected:
int mPrice;
- int mIndex;
std::string mDisplayName;
};
diff --git a/src/sound.h b/src/sound.h
index 4dd68870..c30ef7cd 100644
--- a/src/sound.h
+++ b/src/sound.h
@@ -29,6 +29,8 @@
#endif
#include <string>
+#include <string>
+
/** Sound engine
*
* \ingroup CORE
diff --git a/src/utils/sha256.cpp b/src/utils/sha256.cpp
new file mode 100644
index 00000000..82d1fc5c
--- /dev/null
+++ b/src/utils/sha256.cpp
@@ -0,0 +1,275 @@
+/*
+ * The Mana World
+ * Copyright 2008 The Mana World Development Team
+ *
+ * This file has been slighly modified as part of The Mana World.
+ *
+ * The Mana World is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * The Mana World is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with The Mana World; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/* +------------------------------------+
+ * | Inspire Internet Relay Chat Daemon |
+ * +------------------------------------+
+ *
+ * InspIRCd: (C) 2002-2008 InspIRCd Development Team
+ * See: http://www.inspircd.org/wiki/index.php/Credits
+ *
+ * This program is free but copyrighted software; see
+ * the file COPYING for details.
+ *
+ * ---------------------------------------------------
+ */
+
+/* m_sha256 - Based on m_opersha256 written by Special <john@yarbbles.com>
+ * Modified and improved by Craig Edwards, December 2006.
+ *
+ *
+ * FIPS 180-2 SHA-224/256/384/512 implementation
+ * Last update: 05/23/2005
+ * Issue date: 04/30/2005
+ *
+ * Copyright (C) 2005 Olivier Gay <olivier.gay@a3.epfl.ch>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the project nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "sha256.h"
+#include <memory.h>
+
+#ifdef HAS_STDINT
+#include <stdint.h>
+#endif
+#ifndef HAS_STDINT
+typedef unsigned int uint32_t;
+#endif
+
+#define SHA256_BLOCK_SIZE (512 / 8)
+
+/** An sha 256 context, used by original m_opersha256 */
+class SHA256Context
+{
+ public:
+ unsigned int tot_len;
+ unsigned int len;
+ unsigned char block[2 * SHA256_BLOCK_SIZE];
+ uint32_t h[8];
+};
+
+#define SHA256_DIGEST_SIZE (256 / 8)
+
+#define SHFR(x, n) (x >> n)
+#define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n)))
+#define ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n)))
+#define CH(x, y, z) ((x & y) ^ (~x & z))
+#define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
+
+#define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
+#define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
+#define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3))
+#define SHA256_F4(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHFR(x, 10))
+
+#define UNPACK32(x, str) \
+{ \
+ *((str) + 3) = (uint8_t) ((x) ); \
+ *((str) + 2) = (uint8_t) ((x) >> 8); \
+ *((str) + 1) = (uint8_t) ((x) >> 16); \
+ *((str) + 0) = (uint8_t) ((x) >> 24); \
+}
+
+#define PACK32(str, x) \
+{ \
+ *(x) = ((uint32_t) *((str) + 3) ) \
+ | ((uint32_t) *((str) + 2) << 8) \
+ | ((uint32_t) *((str) + 1) << 16) \
+ | ((uint32_t) *((str) + 0) << 24); \
+}
+
+/* Macros used for loops unrolling */
+
+#define SHA256_SCR(i) \
+{ \
+ w[i] = SHA256_F4(w[i - 2]) + w[i - 7] \
+ + SHA256_F3(w[i - 15]) + w[i - 16]; \
+}
+
+const unsigned int sha256_h0[8] =
+{
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
+};
+
+uint32_t sha256_k[64] =
+{
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
+ 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
+ 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
+ 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
+ 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
+ 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
+};
+
+void SHA256Init(SHA256Context *ctx)
+{
+ for (int i = 0; i < 8; i++)
+ ctx->h[i] = sha256_h0[i];
+ ctx->len = 0;
+ ctx->tot_len = 0;
+}
+
+void SHA256Transform(SHA256Context *ctx,
+ unsigned char *message,
+ unsigned int block_nb)
+{
+ uint32_t w[64];
+ uint32_t wv[8];
+ unsigned char *sub_block;
+ for (unsigned int i = 1; i <= block_nb; i++)
+ {
+ int j;
+ sub_block = message + ((i - 1) << 6);
+
+ for (j = 0; j < 16; j++)
+ PACK32(&sub_block[j << 2], &w[j]);
+ for (j = 16; j < 64; j++)
+ SHA256_SCR(j);
+ for (j = 0; j < 8; j++)
+ wv[j] = ctx->h[j];
+ for (j = 0; j < 64; j++)
+ {
+ uint32_t t1 = wv[7] + SHA256_F2(wv[4]) + CH(wv[4], wv[5], wv[6]) + sha256_k[j] + w[j];
+ uint32_t t2 = SHA256_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]);
+ wv[7] = wv[6];
+ wv[6] = wv[5];
+ wv[5] = wv[4];
+ wv[4] = wv[3] + t1;
+ wv[3] = wv[2];
+ wv[2] = wv[1];
+ wv[1] = wv[0];
+ wv[0] = t1 + t2;
+ }
+ for (j = 0; j < 8; j++)
+ ctx->h[j] += wv[j];
+ }
+}
+
+void SHA256Update(SHA256Context *ctx,
+ unsigned char *message,
+ unsigned int len)
+{
+ /*
+ * XXX here be dragons!
+ * After many hours of pouring over this, I think I've found the problem.
+ * When Special created our module from the reference one, he used:
+ *
+ * unsigned int rem_len = SHA256_BLOCK_SIZE - ctx->len;
+ *
+ * instead of the reference's version of:
+ *
+ * unsigned int tmp_len = SHA256_BLOCK_SIZE - ctx->len;
+ * unsigned int rem_len = len < tmp_len ? len : tmp_len;
+ *
+ * I've changed back to the reference version of this code, and it seems to work with no errors.
+ * So I'm inclined to believe this was the problem..
+ * -- w00t (January 06, 2008)
+ */
+ unsigned int tmp_len = SHA256_BLOCK_SIZE - ctx->len;
+ unsigned int rem_len = len < tmp_len ? len : tmp_len;
+
+ memcpy(&ctx->block[ctx->len], message, rem_len);
+ if (ctx->len + len < SHA256_BLOCK_SIZE)
+ {
+ ctx->len += len;
+ return;
+ }
+ unsigned int new_len = len - rem_len;
+ unsigned int block_nb = new_len / SHA256_BLOCK_SIZE;
+ unsigned char *shifted_message = message + rem_len;
+ SHA256Transform(ctx, ctx->block, 1);
+ SHA256Transform(ctx, shifted_message, block_nb);
+ rem_len = new_len % SHA256_BLOCK_SIZE;
+ memcpy(ctx->block, &shifted_message[block_nb << 6],rem_len);
+ ctx->len = rem_len;
+ ctx->tot_len += (block_nb + 1) << 6;
+}
+
+void SHA256Final(SHA256Context *ctx, unsigned char *digest)
+{
+ unsigned int block_nb = (1 + ((SHA256_BLOCK_SIZE - 9) < (ctx->len % SHA256_BLOCK_SIZE)));
+ unsigned int len_b = (ctx->tot_len + ctx->len) << 3;
+ unsigned int pm_len = block_nb << 6;
+ memset(ctx->block + ctx->len, 0, pm_len - ctx->len);
+ ctx->block[ctx->len] = 0x80;
+ UNPACK32(len_b, ctx->block + pm_len - 4);
+ SHA256Transform(ctx, ctx->block, block_nb);
+ for (int i = 0 ; i < 8; i++)
+ UNPACK32(ctx->h[i], &digest[i << 2]);
+}
+
+std::string SHA256Hash(const char *src, int len)
+{
+ // Generate the hash
+ unsigned char bytehash[SHA256_DIGEST_SIZE];
+ SHA256Context ctx;
+ SHA256Init(&ctx);
+ SHA256Update(&ctx, (unsigned char *)src, (unsigned int)len);
+ SHA256Final(&ctx, bytehash);
+ // Convert it to hex
+ const char* hxc = "0123456789abcdef";
+ std::string hash = "";
+ for (int i = 0; i < SHA256_DIGEST_SIZE; i++)
+ {
+ hash += hxc[bytehash[i] / 16];
+ hash += hxc[bytehash[i] % 16];
+ }
+ return hash;
+}
+
+std::string sha256(const std::string& string)
+{
+ return SHA256Hash(string.c_str(), string.length());
+}
diff --git a/src/utils/sha256.h b/src/utils/sha256.h
new file mode 100644
index 00000000..0aa5ba1f
--- /dev/null
+++ b/src/utils/sha256.h
@@ -0,0 +1,35 @@
+/*
+ * The Mana World
+ * Copyright (C) 2007 The Mana World Development Team
+ *
+ * This file is part of The Mana World.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef UTILS_SHA256_H
+#define UTILS_SHA256_H
+
+#include <string>
+
+/**
+ * Returns the SHA-256 hash for the given string.
+ *
+ * @param string the string to create the SHA-256 hash for
+ * @return the SHA-256 hash for the given string.
+ */
+std::string sha256(const std::string& string);
+
+#endif // UTILS_SHA256_H
diff --git a/src/utils/strprintf.cpp b/src/utils/strprintf.cpp
index 07fb3508..bed4a7c4 100644
--- a/src/utils/strprintf.cpp
+++ b/src/utils/strprintf.cpp
@@ -45,4 +45,3 @@ std::string strprintf(char const *format, ...)
delete [] buf2;
return res;
}
-
diff --git a/src/winver.h b/src/winver.h
index 4996bdfb..abf91e9f 100644
--- a/src/winver.h
+++ b/src/winver.h
@@ -1,6 +1,6 @@
/* VERSION DEFINITIONS */
#define VER_MAJOR 0
-#define VER_MINOR 0
-#define VER_RELEASE 29
+#define VER_MINOR 1
+#define VER_RELEASE 0
#define VER_BUILD 0
-#define PACKAGE_VERSION "0.0.29"
+#define PACKAGE_VERSION "0.1.0"