ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/socket/request.C
Revision: 1.136
Committed: Sun Aug 10 16:31:18 2008 UTC (15 years, 9 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.135: +3 -1 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 /*
2 * This file is part of Deliantra, the Roguelike Realtime MMORPG.
3 *
4 * Copyright (©) 2005,2006,2007,2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5 * Copyright (©) 2001,2007 Mark Wedel
6 * Copyright (©) 1992,2007 Frank Tore Johansen
7 *
8 * Deliantra is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 * The authors can be reached via e-mail to <support@deliantra.net>
22 */
23
24 /**
25 * \file
26 * Client handling.
27 *
28 * \date 2003-12-02
29 *
30 * This file implements all of the goo on the server side for handling
31 * clients. It's got a bunch of global variables for keeping track of
32 * each of the clients.
33 *
34 * Note: All functions that are used to process data from the client
35 * have the prototype of (char *data, int datalen, int client_num). This
36 * way, we can use one dispatch table.
37 *
38 * esrv_map_new starts updating the map
39 *
40 */
41
42 #include <global.h>
43 #include <sproto.h>
44
45 #include <living.h>
46 #include <commands.h>
47
48 /* This block is basically taken from socket.c - I assume if it works there,
49 * it should work here.
50 */
51 #include <sys/types.h>
52 #include <sys/time.h>
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <netdb.h>
56
57 #include <unistd.h>
58 #include <sys/time.h>
59
60 #include "sounds.h"
61
62 /**
63 * This table translates the attack numbers as used within the
64 * program to the value we use when sending STATS command to the
65 * client. If a value is -1, then we don't send that to the
66 * client.
67 */
68 short atnr_cs_stat[NROFATTACKS] = { CS_STAT_RES_PHYS,
69 CS_STAT_RES_MAG, CS_STAT_RES_FIRE, CS_STAT_RES_ELEC,
70 CS_STAT_RES_COLD, CS_STAT_RES_CONF, CS_STAT_RES_ACID,
71 CS_STAT_RES_DRAIN, -1 /* weaponmagic */ ,
72 CS_STAT_RES_GHOSTHIT, CS_STAT_RES_POISON,
73 CS_STAT_RES_SLOW, CS_STAT_RES_PARA, CS_STAT_TURN_UNDEAD,
74 CS_STAT_RES_FEAR, -1 /* Cancellation */ ,
75 CS_STAT_RES_DEPLETE, CS_STAT_RES_DEATH,
76 -1 /* Chaos */ , -1 /* Counterspell */ ,
77 -1 /* Godpower */ , CS_STAT_RES_HOLYWORD,
78 CS_STAT_RES_BLIND,
79 -1, /* Internal */
80 -1, /* life stealing */
81 -1 /* Disease - not fully done yet */
82 };
83
84 static void
85 socket_map_scroll (client *ns, int dx, int dy)
86 {
87 struct Map newmap;
88 int x, y, mx, my;
89
90 ns->send_packet_printf ("map_scroll %d %d", dx, dy);
91
92 /* If we are using the Map1aCmd, we may in fact send
93 * head information that is outside the viewable map.
94 * So set the mx,my to the max value we want to
95 * look for. Removed code to do so - it caused extra
96 * complexities for the client, and probably doesn't make
97 * that much difference in bandwidth.
98 */
99 mx = ns->mapx;
100 my = ns->mapy;
101
102 /* the x and y here are coordinates for the new map, i.e. if we moved
103 * (dx,dy), newmap[x][y] = oldmap[x-dx][y-dy]. For this reason,
104 * if the destination x or y coordinate is outside the viewable
105 * area, we clear the values - otherwise, the old values
106 * are preserved, and the check_head thinks it needs to clear them.
107 */
108 for (x = 0; x < mx; x++)
109 {
110 for (y = 0; y < my; y++)
111 {
112 if (x >= ns->mapx || y >= ns->mapy)
113 /* clear cells outside the viewable area */
114 memset (&newmap.cells[x][y], 0, sizeof (struct MapCell));
115 else if ((x + dx) < 0 || (x + dx) >= ns->mapx || (y + dy) < 0 || (y + dy) >= ns->mapy)
116 /* clear newly visible tiles within the viewable area */
117 memset (&(newmap.cells[x][y]), 0, sizeof (struct MapCell));
118 else
119 memcpy (&(newmap.cells[x][y]), &(ns->lastmap.cells[x + dx][y + dy]), sizeof (struct MapCell));
120 }
121 }
122
123 memcpy (&(ns->lastmap), &newmap, sizeof (struct Map));
124
125 /* Make sure that the next "map1" command will be sent (even if it is
126 * empty).
127 */
128 ns->sent_scroll = 1;
129 }
130
131 static void
132 clear_map (player *pl)
133 {
134 pl->ns->mapinfo_queue_clear ();
135
136 memset (&pl->ns->lastmap, 0, sizeof (pl->ns->lastmap));
137
138 pl->ns->force_newmap = false;
139
140 if (pl->ns->newmapcmd == 1)
141 pl->ns->send_packet ("newmap");
142
143 pl->ns->floorbox_reset ();
144 }
145
146 static void
147 send_map_info (player *pl)
148 {
149 client &socket = *pl->ns;
150 object *ob = pl->observe;
151
152 if (socket.mapinfocmd)
153 {
154 if (ob->map && ob->map->path[0])
155 {
156 int flags = 0;
157
158 if (ob->map->tile_path[0]) flags |= 1;
159 if (ob->map->tile_path[1]) flags |= 2;
160 if (ob->map->tile_path[2]) flags |= 4;
161 if (ob->map->tile_path[3]) flags |= 8;
162
163 socket.send_packet_printf ("mapinfo - spatial %d %d %d %d %d %s",
164 flags, socket.mapx / 2 - ob->x, socket.mapy / 2 - ob->y,
165 ob->map->width, ob->map->height, &ob->map->path);
166 }
167 else
168 socket.send_packet ("mapinfo current");
169 }
170 }
171
172 /** check for map/region change and send new map data */
173 static void
174 check_map_change (player *pl)
175 {
176 client &socket = *pl->ns;
177 object *ob = pl->observe;
178
179 region *reg = ob->region ();
180 if (socket.current_region != reg)
181 {
182 INVOKE_PLAYER (REGION_CHANGE, pl, ARG_REGION (reg), ARG_REGION (socket.current_region));
183 socket.current_region = reg;
184 }
185
186 // first try to aovid a full newmap on tiled map scrolls
187 if (socket.current_map != ob->map && !socket.force_newmap)
188 {
189 rv_vector rv;
190
191 get_rangevector_from_mapcoord (socket.current_map, socket.current_x, socket.current_y, ob, &rv, 0);
192
193 // manhattan distance is very handy here
194 if (rv.distance < 8) // 8 works nicely for speed << 70 and buggy gcfclient
195 {
196 socket.current_map = ob->map;
197 socket.current_x = ob->x;
198 socket.current_y = ob->y;
199
200 socket_map_scroll (&socket, rv.distance_x, rv.distance_y);
201 socket.floorbox_reset ();
202 send_map_info (pl);
203 }
204 }
205
206 if (socket.current_map != ob->map || socket.force_newmap)
207 {
208 clear_map (pl);
209 socket.current_map = ob->map;
210 send_map_info (pl);
211 }
212 else if (socket.current_x != ob->x || socket.current_y != ob->y)
213 {
214 int dx = ob->x - socket.current_x;
215 int dy = ob->y - socket.current_y;
216
217 if (socket.buggy_mapscroll && (abs (dx) > 8 || abs (dy) > 8))
218 clear_map (pl); // current (<= 1.9.1) clients have unchecked buffer overflows
219 else
220 {
221 socket_map_scroll (&socket, ob->x - socket.current_x, ob->y - socket.current_y);
222 socket.floorbox_reset ();
223 }
224 }
225
226 socket.current_x = ob->x;
227 socket.current_y = ob->y;
228 }
229
230 /**
231 * RequestInfo is sort of a meta command. There is some specific
232 * request of information, but we call other functions to provide
233 * that information.
234 */
235 void
236 RequestInfo (char *buf, int len, client *ns)
237 {
238 char *params;
239
240 /* find the first space, make it null, and update the
241 * params pointer.
242 */
243 for (params = buf; *params; params++)
244 if (*params == ' ')
245 {
246 *params++ = 0;
247 break;
248 }
249
250 if (!strcmp (buf, "image_info"))
251 send_image_info (ns, params);
252 else if (!strcmp (buf, "image_sums"))
253 send_image_sums (ns, params);
254 else if (!strcmp (buf, "skill_info"))
255 send_skill_info (ns, params);
256 else if (!strcmp (buf, "spell_paths"))
257 send_spell_paths (ns, params);
258 else
259 {
260 // undo tokenisation above and send replyinfo with the request unchanged
261 if (*params)
262 *--params = ' ';
263
264 ns->send_packet_printf ("replyinfo %s", buf);
265 }
266 }
267
268 void
269 ExtCmd (char *buf, int len, player *pl)
270 {
271 INVOKE_PLAYER (EXTCMD, pl, ARG_DATA (buf, len));
272 }
273
274 void
275 ExtiCmd (char *buf, int len, client *ns)
276 {
277 INVOKE_CLIENT (EXTICMD, ns, ARG_DATA (buf, len));
278 }
279
280 void
281 client::mapinfo_queue_clear ()
282 {
283 for (auto (i, mapinfo_queue.begin ()); i != mapinfo_queue.end (); ++i)
284 free (*i);
285
286 mapinfo_queue.clear ();
287 }
288
289 bool
290 client::mapinfo_try (char *buf)
291 {
292 char *token = buf;
293 buf += strlen (buf) + 9;
294
295 // initial map and its origin
296 maptile *map = pl->observe->map;
297 int mapx = pl->ns->mapx / 2 - pl->observe->x;
298 int mapy = pl->ns->mapy / 2 - pl->observe->y;
299 int max_distance = 8; // limit maximum path length to something generous
300
301 while (*buf && map && max_distance)
302 {
303 int dir = *buf++ - '1';
304
305 if (dir >= 0 && dir <= 3)
306 {
307 if (!map->tile_path [dir])
308 map = 0;
309 else if (map->tile_available (dir, false))
310 {
311 maptile *neigh = map->tile_map [dir];
312
313 switch (dir)
314 {
315 case 0: mapy -= neigh->height; break;
316 case 2: mapy += map ->height; break;
317 case 3: mapx -= neigh->width ; break;
318 case 1: mapx += map ->width ; break;
319 }
320
321 map = neigh;
322 --max_distance;
323 }
324 else
325 return 0;
326 }
327 else
328 max_distance = 0;
329 }
330
331 if (!max_distance)
332 send_packet_printf ("mapinfo %s error", token);
333 else if (!map || !map->path)
334 send_packet_printf ("mapinfo %s nomap", token);
335 else
336 {
337 int flags = 0;
338
339 if (map->tile_path[0]) flags |= 1;
340 if (map->tile_path[1]) flags |= 2;
341 if (map->tile_path[2]) flags |= 4;
342 if (map->tile_path[3]) flags |= 8;
343
344 send_packet_printf ("mapinfo %s spatial %d %d %d %d %d %s", token, flags, mapx, mapy, map->width, map->height, &map->path);
345 }
346
347 return 1;
348 }
349
350 void
351 client::mapinfo_queue_run ()
352 {
353 if (mapinfo_queue.empty () || !pl)
354 return;
355
356 for (int i = 0; i < mapinfo_queue.size (); ++i)
357 if (mapinfo_try (mapinfo_queue [i]))
358 {
359 free (mapinfo_queue [i]);
360 mapinfo_queue.erase (i);
361 }
362 else
363 ++i;
364 }
365
366 void
367 MapInfoCmd (char *buf, int len, player *pl)
368 {
369 // <mapinfo tag spatial tile-path
370 // >mapinfo tag spatial flags x y w h hash
371
372 char *token = buf;
373
374 if (!(buf = strchr (buf, ' ')))
375 return;
376
377 if (!strncmp (buf, " spatial ", 9))
378 {
379 char *copy = strdup (token);
380 copy [buf - token] = 0;
381
382 #if 0
383 // this makes only sense when we flush the buffer immediately
384 if (pl->ns->mapinfo_try (copy))
385 free (copy);
386 else
387 #endif
388 pl->ns->mapinfo_queue.push_back (copy);
389 }
390 else
391 pl->ns->send_packet_printf ("mapinfo %s unsupported", token);
392 }
393
394 /** This is the Setup cmd */
395 void
396 SetUp (char *buf, int len, client * ns)
397 {
398 INVOKE_CLIENT (SETUP, ns, ARG_DATA (buf, len));
399 }
400
401 /**
402 * The client has requested to be added to the game.
403 * This is what takes care of it. We tell the client how things worked out.
404 * I am not sure if this file is the best place for this function. however,
405 * it either has to be here or init_sockets needs to be exported.
406 */
407 void
408 AddMeCmd (char *buf, int len, client *ns)
409 {
410 INVOKE_CLIENT (ADDME, ns, ARG_DATA (buf, len));
411 }
412
413 /** Reply to ExtendedInfos command */
414 void
415 ToggleExtendedInfos (char *buf, int len, client * ns)
416 {
417 char cmdback[MAX_BUF];
418 char command[50];
419 int info, nextinfo;
420
421 cmdback[0] = '\0';
422 nextinfo = 0;
423
424 while (1)
425 {
426 /* 1. Extract an info */
427 info = nextinfo;
428
429 while ((info < len) && (buf[info] == ' '))
430 info++;
431
432 if (info >= len)
433 break;
434
435 nextinfo = info + 1;
436
437 while ((nextinfo < len) && (buf[nextinfo] != ' '))
438 nextinfo++;
439
440 if (nextinfo - info >= 49) /*Erroneous info asked */
441 continue;
442
443 strncpy (command, &(buf[info]), nextinfo - info);
444
445 /* 2. Interpret info */
446 if (!strcmp ("smooth", command))
447 /* Toggle smoothing */
448 ns->EMI_smooth = !ns->EMI_smooth;
449 else
450 /*bad value */;
451
452 /*3. Next info */
453 }
454
455 strcpy (cmdback, "ExtendedInfoSet");
456
457 if (ns->EMI_smooth)
458 {
459 strcat (cmdback, " ");
460 strcat (cmdback, "smoothing");
461 }
462
463 ns->send_packet (cmdback);
464 }
465
466 /*
467 #define MSG_TYPE_BOOK 1
468 #define MSG_TYPE_CARD 2
469 #define MSG_TYPE_PAPER 3
470 #define MSG_TYPE_SIGN 4
471 #define MSG_TYPE_MONUMENT 5
472 #define MSG_TYPE_SCRIPTED_DIALOG 6*/
473
474 /** Reply to ExtendedInfos command */
475 void
476 ToggleExtendedText (char *buf, int len, client * ns)
477 {
478 char cmdback[MAX_BUF];
479 char temp[10];
480 char command[50];
481 int info, nextinfo, i, flag;
482
483 cmdback[0] = '\0';
484
485 nextinfo = 0;
486 while (1)
487 {
488 /* 1. Extract an info */
489 info = nextinfo;
490
491 while ((info < len) && (buf[info] == ' '))
492 info++;
493
494 if (info >= len)
495 break;
496
497 nextinfo = info + 1;
498
499 while ((nextinfo < len) && (buf[nextinfo] != ' '))
500 nextinfo++;
501
502 if (nextinfo - info >= 49) /*Erroneous info asked */
503 continue;
504
505 strncpy (command, &(buf[info]), nextinfo - info);
506 command[nextinfo - info] = '\0';
507 /* 2. Interpret info */
508 i = sscanf (command, "%d", &flag);
509
510 if ((i == 1) && (flag > 0) && (flag <= MSG_TYPE_LAST))
511 ns->supported_readables |= (1 << flag);
512 /*3. Next info */
513 }
514
515 /* Send resulting state */
516 strcpy (cmdback, "ExtendedTextSet");
517
518 for (i = 0; i <= MSG_TYPE_LAST; i++)
519 if (ns->supported_readables & (1 << i))
520 {
521 strcat (cmdback, " ");
522 snprintf (temp, sizeof (temp), "%d", i);
523 strcat (cmdback, temp);
524 }
525
526 ns->send_packet (cmdback);
527 }
528
529 /**
530 * This handles the general commands from the client (ie, north, fire, cast,
531 * etc.)
532 */
533 void
534 PlayerCmd (char *buf, int len, player *pl)
535 {
536 /* Check if there is a count. In theory, a zero count could also be
537 * sent, so check for that also.
538 */
539 if (atoi (buf) || buf[0] == '0')
540 {
541 pl->count = atoi ((char *) buf);
542
543 buf = strchr (buf, ' '); /* advance beyond the numbers */
544 if (!buf)
545 return;
546
547 buf++;
548 }
549
550 execute_newserver_command (pl->ob, (char *) buf);
551
552 /* Perhaps something better should be done with a left over count.
553 * Cleaning up the input should probably be done first - all actions
554 * for the command that issued the count should be done before any other
555 * commands.
556 */
557 pl->count = 0;
558 }
559
560 /**
561 * This handles the general commands from the client (ie, north, fire, cast,
562 * etc.). It is a lot like PlayerCmd above, but is called with the
563 * 'ncom' method which gives more information back to the client so it
564 * can throttle.
565 */
566 void
567 NewPlayerCmd (char *buf, int len, player *pl)
568 {
569 if (len <= 6)
570 {
571 LOG (llevDebug, "%s: corrupt ncom command <%s>: not long enough (%d) - discarding\n", pl->ns->host, buf, len);
572 return;
573 }
574
575 uint16 cmdid = net_uint16 ((uint8 *)buf);
576 sint32 repeat = net_sint32 ((uint8 *)buf + 2);
577
578 /* -1 is special - no repeat, but don't update */
579 if (repeat != -1)
580 pl->count = repeat;
581
582 buf += 6; //len -= 6;
583
584 execute_newserver_command (pl->ob, buf);
585
586 /* Perhaps something better should be done with a left over count.
587 * Cleaning up the input should probably be done first - all actions
588 * for the command that issued the count should be done before any other
589 * commands.
590 */
591 pl->count = 0;
592
593 //TODO: schmorp thinks whatever this calculates, it makes no sense at all
594 int time = fabs (pl->ob->speed) < 0.001
595 ? time = MAX_TIME * 100
596 : time = (int) (MAX_TIME / fabs (pl->ob->speed));
597
598 /* Send confirmation of command execution now */
599 packet sl ("comc");
600 sl << uint16 (cmdid) << uint32 (time);
601 pl->ns->send_packet (sl);
602 }
603
604 /** This is a reply to a previous query. */
605 void
606 ReplyCmd (char *buf, int len, client *ns)
607 {
608 if (ns->state == ST_CUSTOM)
609 {
610 INVOKE_CLIENT (REPLY, ns, ARG_DATA (buf, len));
611 return;
612 }
613
614 if (!ns->pl)
615 return; //TODO: depends on the exact reply we are after
616 //TODO: but right now, we always have a ns->pl
617
618 player *pl = ns->pl;
619
620 /* This is to synthesize how the data would be stored if it
621 * was normally entered. A bit of a hack, and should be cleaned up
622 * once all the X11 code is removed from the server.
623 *
624 * We pass 13 to many of the functions because this way they
625 * think it was the carriage return that was entered, and the
626 * function then does not try to do additional input.
627 */
628 snprintf (pl->write_buf, sizeof (pl->write_buf), ":%s", buf);
629
630 /* this avoids any hacking here */
631
632 switch (ns->state)
633 {
634 case ST_PLAYING:
635 LOG (llevError, "Got reply message with ST_PLAYING input state\n");
636 break;
637
638 case ST_GET_PARTY_PASSWORD: /* Get password for party */
639 receive_party_password (pl->ob, 13);
640 break;
641
642 default:
643 LOG (llevError, "Unknown input state: %d\n", ns->state);
644 }
645 }
646
647 /**
648 * Client tells its version. If there is a mismatch, we close the
649 * socket. In real life, all we should care about is the client having
650 * something older than the server. If we assume the client will be
651 * backwards compatible, having it be a later version should not be a
652 * problem.
653 */
654 void
655 VersionCmd (char *buf, int len, client * ns)
656 {
657 if (!buf)
658 {
659 LOG (llevError, "CS: received corrupted version command\n");
660 return;
661 }
662
663 ns->cs_version = atoi (buf);
664 ns->sc_version = ns->cs_version;
665
666 LOG (llevDebug, "connection from client <%s>\n", buf);
667
668 //TODO: should log here just for statistics
669
670 //if (VERSION_CS != ns->cs_version)
671 // unchecked;
672
673 char *cp = strchr (buf + 1, ' ');
674 if (!cp)
675 return;
676
677 ns->sc_version = atoi (cp);
678
679 //if (VERSION_SC != ns->sc_version)
680 // unchecked;
681
682 cp = strchr (cp + 1, ' ');
683
684 if (cp)
685 {
686 ns->version = cp + 1;
687
688 if (ns->sc_version < 1026)
689 ns->send_packet_printf ("drawinfo %d %s", NDI_RED,
690 "**** VERSION WARNING ****\n**** CLIENT IS TOO OLD!! UPDATE THE CLIENT!! ****");
691 }
692 }
693
694 /** sound related functions. */
695 void
696 SetSound (char *buf, int len, client * ns)
697 {
698 ns->sound = atoi (buf);
699 }
700
701 /** client wants the map resent */
702 void
703 MapRedrawCmd (char *buf, int len, player *pl)
704 {
705 /* This function is currently disabled; just clearing the map state results in
706 * display errors. It should clear the cache and send a newmap command.
707 * Unfortunately this solution does not work because some client versions send
708 * a mapredraw command after receiving a newmap command.
709 */
710 }
711
712 /**
713 * Moves an object (typically, container to inventory).
714 * syntax is: move (to) (tag) (nrof)
715 */
716 void
717 MoveCmd (char *buf, int len, player *pl)
718 {
719 int to, tag, nrof;
720
721 if (3 != sscanf (buf, "%d %d %d", &to, &tag, &nrof))
722 {
723 LOG (llevError, "Incomplete move command: %s\n", buf);
724 return;
725 }
726
727 esrv_move_object (pl->ob, to, tag, nrof);
728 }
729
730 /******************************************************************************
731 *
732 * Start of commands the server sends to the client.
733 *
734 ******************************************************************************/
735
736 /**
737 * Asks the client to query the user. This way, the client knows
738 * it needs to send something back (vs just printing out a message)
739 */
740 void
741 send_query (client *ns, uint8 flags, const char *text)
742 {
743 ns->send_packet_printf ("query %d %s", flags, text ? text : "");
744 }
745
746 /**
747 * Get player's current range attack in obuf.
748 */
749 static void
750 rangetostring (player *pl, char *obuf)
751 {
752 dynbuf_text buf;
753
754 if (pl->ranged_ob)
755 buf << " Range" << (pl->ob->current_weapon == pl->ranged_ob ? "*" : "") << ": " << pl->ranged_ob->name;
756
757 if (pl->combat_ob)
758 buf << " Combat" << (pl->ob->current_weapon == pl->combat_ob ? "*" : "") << ": " << pl->combat_ob->name;
759
760 #if 0
761 //TODO: remove this when slot system is working, this is only for debugging
762 if (pl->ob->chosen_skill)
763 buf << " Skill*: " << pl->ob->chosen_skill->name;
764 #endif
765
766 //TODO: maybe golem should become the current_weapon, quite simply?
767 if (pl->golem)
768 buf << " Golem*: " << pl->golem->name;
769
770 buf << '\0';
771 buf.linearise (obuf);
772 }
773
774 #define AddIfInt64(Old,New,Type) if (Old != New) {\
775 Old = New; \
776 sl << uint8 (Type) << uint64 (New); \
777 }
778
779 #define AddIfInt(Old,New,Type) if (Old != New) {\
780 Old = New; \
781 sl << uint8 (Type) << uint32 (New); \
782 }
783
784 #define AddIfShort(Old,New,Type) if (Old != New) {\
785 Old = New; \
786 sl << uint8 (Type) << uint16 (New); \
787 }
788
789 #define AddIfFloat(Old,New,Type,mult) if (Old != New) {\
790 Old = New; \
791 sl << uint8 (Type) << uint32 (New*FLOAT_MULTI*mult); \
792 }
793
794 #define AddIfString(Old,New,Type) if (Old == NULL || strcmp(Old,New)) {\
795 free(Old); Old = strdup (New);\
796 sl << uint8 (Type) << data8 (New); \
797 }
798
799 /**
800 * Sends a statistics update. We look at the old values,
801 * and only send what has changed. Stat mapping values are in newclient.h
802 * Since this gets sent a lot, this is actually one of the few binary
803 * commands for now.
804 */
805 void
806 esrv_update_stats (player *pl)
807 {
808 char buf[MAX_BUF];
809 uint16 flags;
810
811 client *ns = pl->ns;
812 if (!ns)
813 return;
814
815 object *ob = pl->observe;
816 if (!ob)
817 return;
818
819 player *opl = ob->contr ? static_cast<player *>(ob->contr) : pl;
820
821 packet sl ("stats");
822
823 AddIfShort (ns->last_stats.hp, ob->stats.hp, CS_STAT_HP);
824 AddIfShort (ns->last_stats.maxhp, ob->stats.maxhp, CS_STAT_MAXHP);
825 AddIfShort (ns->last_stats.sp, ob->stats.sp, CS_STAT_SP);
826 AddIfShort (ns->last_stats.maxsp, ob->stats.maxsp, CS_STAT_MAXSP);
827 AddIfShort (ns->last_stats.grace, ob->stats.grace, CS_STAT_GRACE);
828 AddIfShort (ns->last_stats.maxgrace, ob->stats.maxgrace, CS_STAT_MAXGRACE);
829 AddIfShort (ns->last_stats.Str, ob->stats.Str, CS_STAT_STR);
830 AddIfShort (ns->last_stats.Dex, ob->stats.Dex, CS_STAT_DEX);
831 AddIfShort (ns->last_stats.Con, ob->stats.Con, CS_STAT_CON);
832 AddIfShort (ns->last_stats.Int, ob->stats.Int, CS_STAT_INT);
833 AddIfShort (ns->last_stats.Wis, ob->stats.Wis, CS_STAT_WIS);
834 AddIfShort (ns->last_stats.Pow, ob->stats.Pow, CS_STAT_POW);
835 AddIfShort (ns->last_stats.Cha, ob->stats.Cha, CS_STAT_CHA);
836
837 for (int s = 0; s < NUM_SKILLS; s++)
838 if (object *skill = opl->last_skill_ob[s])
839 if (skill->stats.exp != ns->last_skill_exp [s])
840 {
841 ns->last_skill_exp [s] = skill->stats.exp;
842
843 /* Always send along the level if exp changes. This is only
844 * 1 extra byte, but keeps processing simpler.
845 */
846 sl << uint8 (s + CS_STAT_SKILLINFO)
847 << uint8 (skill->level)
848 << uint64 (skill->stats.exp);
849 }
850
851 AddIfInt64 (ns->last_stats.exp, ob->stats.exp, CS_STAT_EXP64);
852 AddIfShort (ns->last_level, ob->level, CS_STAT_LEVEL);
853 AddIfShort (ns->last_stats.wc, ob->stats.wc, CS_STAT_WC);
854 AddIfShort (ns->last_stats.ac, ob->stats.ac, CS_STAT_AC);
855 AddIfShort (ns->last_stats.dam, ob->stats.dam, CS_STAT_DAM);
856 AddIfFloat (ns->last_speed, ob->speed, CS_STAT_SPEED, 1.f/TICK);
857 AddIfShort (ns->last_stats.food, ob->stats.food, CS_STAT_FOOD);
858 AddIfFloat (ns->last_weapon_sp, pl->weapon_sp, CS_STAT_WEAP_SP, 1.f/TICK);
859 AddIfInt (ns->last_weight_limit, weight_limit[ob->stats.Str], CS_STAT_WEIGHT_LIM);
860
861 flags = 0;
862
863 if (opl->fire_on)
864 flags |= SF_FIREON;
865
866 if (opl->run_on)
867 flags |= SF_RUNON;
868
869 AddIfShort (ns->last_flags, flags, CS_STAT_FLAGS);
870
871 if (ns->sc_version < 1025)
872 { AddIfShort (ns->last_resist[ATNR_PHYSICAL], ob->resist[ATNR_PHYSICAL], CS_STAT_ARMOUR) }
873 else
874 for (int i = 0; i < NROFATTACKS; i++)
875 {
876 /* Skip ones we won't send */
877 if (atnr_cs_stat[i] == -1)
878 continue;
879
880 AddIfShort (ns->last_resist[i], ob->resist[i], atnr_cs_stat[i]);
881 }
882
883 if (pl->ns->monitor_spells)
884 {
885 AddIfInt (ns->last_path_attuned, ob->path_attuned, CS_STAT_SPELL_ATTUNE);
886 AddIfInt (ns->last_path_repelled, ob->path_repelled, CS_STAT_SPELL_REPEL);
887 AddIfInt (ns->last_path_denied, ob->path_denied, CS_STAT_SPELL_DENY);
888 }
889
890 rangetostring (opl, buf); /* we want use the new fire & run system in new client */
891 AddIfString (ns->stats.range, buf, CS_STAT_RANGE);
892 set_title (ob, buf);
893 AddIfString (ns->stats.title, buf, CS_STAT_TITLE);
894
895 /* Only send it away if we have some actual data */
896 if (sl.length () > 6)
897 ns->send_packet (sl);
898 }
899
900 /**
901 * Tells the client that here is a player it should start using.
902 */
903 void
904 esrv_new_player (player *pl)
905 {
906 sint32 weight = pl->ob->client_weight ();
907
908 packet sl ("player");
909
910 sl << uint32 (pl->ob->count)
911 << uint32 (weight)
912 << uint32 (pl->ob->face)
913 << data8 (pl->ob->name);
914
915 pl->ns->last_weight = weight;
916 pl->ns->send_packet (sl);
917 SET_FLAG (pl->ob, FLAG_CLIENT_SENT);
918 }
919
920 /******************************************************************************
921 *
922 * Start of map related commands.
923 *
924 ******************************************************************************/
925
926 /** Clears a map cell */
927 static void
928 map_clearcell (struct MapCell *cell, int count)
929 {
930 cell->faces[0] = 0;
931 cell->faces[1] = 0;
932 cell->faces[2] = 0;
933 cell->smooth[0] = 0;
934 cell->smooth[1] = 0;
935 cell->smooth[2] = 0;
936 cell->count = count;
937 cell->stat_hp = 0;
938 cell->flags = 0;
939 cell->player = 0;
940 }
941
942 #define MAX_LAYERS 3
943
944 /**
945 * Removes the need to replicate the same code for each layer.
946 * this returns true if this space is now in fact different than
947 * it was.
948 * sl is the socklist this data is going into.
949 * ns is the socket we are working on - all the info we care
950 * about is in this socket structure, so now need not pass the
951 * entire player object.
952 * layer is the layer to update, with 2 being the floor and 0 the
953 * top layer (this matches what the GET_MAP_FACE and GET_MAP_FACE_OBJ)
954 * take. Interesting to note that before this function, the map1 function
955 * numbers the spaces differently - I think this was a leftover from
956 * the map command, where the faces stack up. Sinces that is no longer
957 * the case, it seems to make more sense to have these layer values
958 * actually match.
959 */
960 static int
961 update_space (packet &sl, client &ns, mapspace &ms, MapCell &lastcell, int layer)
962 {
963 object *ob = ms.faces_obj [layer];
964
965 /* If there is no object for this space, or if the face for the object
966 * is the blank face, set the face number to zero.
967 * else if we have the stored head object for this space, that takes
968 * precedence over the other object for this space.
969 * otherwise, we do special head processing
970 */
971 uint16 face_num = ob && ob->face != blank_face ? ob->face : 0;
972
973 /* We've gotten what face we want to use for the object. Now see if
974 * if it has changed since we last sent it to the client.
975 */
976 if (lastcell.faces[layer] != face_num)
977 {
978 lastcell.faces[layer] = face_num;
979
980 if (!ns.faces_sent[face_num])
981 if (ob)
982 ns.send_faces (ob);
983 else
984 ns.send_face (face_num, 10);
985
986 sl << uint16 (face_num);
987 return 1;
988 }
989
990 /* Nothing changed */
991 return 0;
992 }
993
994 /**
995 * Returns the size of a data for a map square as returned by
996 * mapextended. There are CLIENTMAPX*CLIENTMAPY*LAYERS entries
997 * available.
998 */
999 int
1000 getExtendedMapInfoSize (client * ns)
1001 {
1002 int result = 0;
1003
1004 if (ns->ext_mapinfos)
1005 {
1006 if (ns->EMI_smooth)
1007 result += 1; /*One byte for smoothlevel */
1008 }
1009
1010 return result;
1011 }
1012
1013 // prefetch (and touch) all maps within a specific distancd
1014 static void
1015 prefetch_surrounding_maps (maptile *map, int distance)
1016 {
1017 map->last_access = runtime;
1018
1019 if (--distance)
1020 for (int dir = 4; --dir; )
1021 if (const shstr &path = map->tile_path [dir])
1022 if (maptile *&neigh = map->tile_map [dir])
1023 prefetch_surrounding_maps (neigh, distance);
1024 else
1025 neigh = maptile::find_async (path, map);
1026 }
1027
1028 // prefetch a generous area around the player
1029 static void
1030 prefetch_surrounding_maps (object *op)
1031 {
1032 prefetch_surrounding_maps (op->map, 3);
1033 }
1034
1035 /**
1036 * Draws client map.
1037 */
1038 void
1039 draw_client_map (player *pl)
1040 {
1041 object *ob = pl->observe;
1042 if (!ob->active)
1043 return;
1044
1045 maptile *plmap = ob->map;
1046
1047 /* If player is just joining the game, he isn't here yet, so the map
1048 * can get swapped out. If so, don't try to send them a map. All will
1049 * be OK once they really log in.
1050 */
1051 if (!plmap || plmap->in_memory != MAP_ACTIVE)
1052 return;
1053
1054 int x, y, ax, ay, startlen, max_x, max_y, oldlen;
1055 int estartlen, eoldlen;
1056 uint8 eentrysize;
1057 uint16 ewhatstart, ewhatflag;
1058 uint8 extendedinfos;
1059
1060 check_map_change (pl);
1061 prefetch_surrounding_maps (pl->ob);
1062
1063 /* do LOS after calls to update_position */
1064 if (ob != pl->ob)
1065 clear_los (pl);
1066 else if (pl->do_los)
1067 {
1068 update_los (ob);
1069 pl->do_los = 0;
1070 }
1071
1072 /**
1073 * This function uses the new map1 protocol command to send the map
1074 * to the client. It is necessary because the old map command supports
1075 * a maximum map size of 15x15.
1076 * This function is much simpler than the old one. This is because
1077 * the old function optimized to send as few face identifiers as possible,
1078 * at the expense of sending more coordinate location (coordinates were
1079 * only 1 byte, faces 2 bytes, so this was a worthwhile savings). Since
1080 * we need 2 bytes for coordinates and 2 bytes for faces, such a trade off
1081 * maps no sense. Instead, we actually really only use 12 bits for coordinates,
1082 * and use the other 4 bits for other informatiion. For full documentation
1083 * of what we send, see the doc/Protocol file.
1084 * I will describe internally what we do:
1085 * the ns->lastmap shows how the map last looked when sent to the client.
1086 * in the lastmap structure, there is a cells array, which is set to the
1087 * maximum viewable size (As set in config.h).
1088 * in the cells, there are faces and a count value.
1089 * we use the count value to hold the darkness value. If -1, then this space
1090 * is not viewable.
1091 * we use faces[0] faces[1] faces[2] to hold what the three layers
1092 * look like.
1093 */
1094
1095 client &socket = *pl->ns;
1096
1097 packet sl (socket.mapmode == Map1Cmd ? "map1" : "map1a");
1098 packet esl;
1099
1100 startlen = sl.length ();
1101
1102 /*Extendedmapinfo structure initialisation */
1103 if (socket.ext_mapinfos)
1104 {
1105 extendedinfos = EMI_NOREDRAW;
1106
1107 if (socket.EMI_smooth)
1108 extendedinfos |= EMI_SMOOTH;
1109
1110 ewhatstart = esl.length ();
1111 ewhatflag = extendedinfos; /*The EMI_NOREDRAW bit
1112 could need to be taken away */
1113 eentrysize = getExtendedMapInfoSize (&socket);
1114 esl << "mapextended "
1115 << uint8 (extendedinfos)
1116 << uint8 (eentrysize);
1117
1118 estartlen = esl.length ();
1119 }
1120
1121 /* x,y are the real map locations. ax, ay are viewport relative
1122 * locations.
1123 */
1124 ay = 0;
1125
1126 /* We could do this logic as conditionals in the if statement,
1127 * but that started to get a bit messy to look at.
1128 */
1129 max_x = ob->x + (socket.mapx + 1) / 2;
1130 max_y = ob->y + (socket.mapy + 1) / 2;
1131
1132 for (y = ob->y - socket.mapy / 2; y < max_y; y++, ay++)
1133 {
1134 sint16 nx, ny;
1135 maptile *m = 0;
1136
1137 ax = 0;
1138 for (x = ob->x - socket.mapx / 2; x < max_x; x++, ax++)
1139 {
1140 // check to see if we can simply go one right quickly
1141 ++nx;
1142 if (m && nx >= m->width)
1143 m = 0;
1144
1145 if (!m)
1146 {
1147 nx = x; ny = y; m = plmap;
1148
1149 if (xy_normalise (m, nx, ny))
1150 m->touch ();
1151 else
1152 m = 0;
1153 }
1154
1155 int emask, mask;
1156 emask = mask = (ax & 0x3f) << 10 | (ay & 0x3f) << 4;
1157
1158 MapCell &lastcell = socket.lastmap.cells[ax][ay];
1159
1160 /* If the coordinates are not valid, or it is too dark to see,
1161 * we tell the client as such
1162 */
1163 if (!m)
1164 {
1165 /* space is out of map. Update space and clear values
1166 * if this hasn't already been done. If the space is out
1167 * of the map, it shouldn't have a head
1168 */
1169 if (lastcell.count != -1)
1170 {
1171 sl << uint16 (mask);
1172 map_clearcell (&lastcell, -1);
1173 }
1174
1175 continue;
1176 }
1177
1178 int d = pl->blocked_los[ax][ay];
1179
1180 if (d > 3)
1181 {
1182 int need_send = 0, count;
1183
1184 /* This block deals with spaces that are not visible for whatever
1185 * reason. Still may need to send the head for this space.
1186 */
1187
1188 oldlen = sl.length ();
1189
1190 sl << uint16 (mask);
1191
1192 if (lastcell.count != -1)
1193 need_send = 1;
1194
1195 count = -1;
1196
1197 if (lastcell.faces[0] || lastcell.faces[1] || lastcell.faces[2]
1198 || lastcell.stat_hp || lastcell.flags || lastcell.player)
1199 need_send = 1;
1200
1201 /* properly clear a previously sent big face */
1202 map_clearcell (&lastcell, count);
1203
1204 if ((mask & 0xf) || need_send)
1205 sl[oldlen + 1] = mask & 0xff;
1206 else
1207 sl.reset (oldlen);
1208 }
1209 else
1210 {
1211 /* In this block, the space is visible.
1212 */
1213
1214 /* Rather than try to figure out what everything that we might
1215 * need to send is, then form the packet after that,
1216 * we presume that we will in fact form a packet, and update
1217 * the bits by what we do actually send. If we send nothing,
1218 * we just back out sl.length () to the old value, and no harm
1219 * is done.
1220 * I think this is simpler than doing a bunch of checks to see
1221 * what if anything we need to send, setting the bits, then
1222 * doing those checks again to add the real data.
1223 */
1224 oldlen = sl.length ();
1225 eoldlen = esl.length ();
1226
1227 sl << uint16 (mask);
1228
1229 unsigned char dummy;
1230 unsigned char *last_ext = &dummy;
1231
1232 /* Darkness changed */
1233 if (lastcell.count != d && socket.darkness)
1234 {
1235 mask |= 0x8;
1236
1237 if (socket.extmap)
1238 {
1239 *last_ext |= 0x80;
1240 last_ext = &sl[sl.length ()];
1241 sl << uint8 (d);
1242 }
1243 else
1244 sl << uint8 (255 - 64 * d);
1245 }
1246
1247 lastcell.count = d;
1248
1249 mapspace &ms = m->at (nx, ny);
1250 ms.update ();
1251
1252 if (socket.extmap)
1253 {
1254 uint8 stat_hp = 0;
1255 uint8 stat_width = 0;
1256 uint8 flags = 0;
1257 tag_t player = 0;
1258
1259 // send hp information, if applicable
1260 if (object *op = ms.faces_obj [0])
1261 if (op->is_head () && !op->invisible)
1262 {
1263 if (op->stats.maxhp > op->stats.hp
1264 && op->stats.maxhp > 0
1265 && (op->type == PLAYER
1266 || op->type == DOOR // does not work, have maxhp 0
1267 || QUERY_FLAG (op, FLAG_MONSTER)
1268 || QUERY_FLAG (op, FLAG_ALIVE)
1269 || QUERY_FLAG (op, FLAG_GENERATOR)))
1270 {
1271 stat_hp = 255 - (op->stats.hp * 255 + 254) / op->stats.maxhp;
1272 stat_width = op->arch->max_x - op->arch->x; //TODO: should be upper-left edge
1273 }
1274
1275 if (op->has_dialogue ())
1276 flags |= 1;
1277
1278 if (op->type == PLAYER)
1279 player = op == ob ? pl->ob->count
1280 : op == pl->ob ? ob->count
1281 : op->count;
1282 }
1283
1284 if (lastcell.stat_hp != stat_hp)
1285 {
1286 lastcell.stat_hp = stat_hp;
1287
1288 mask |= 0x8;
1289 *last_ext |= 0x80;
1290 last_ext = &sl[sl.length ()];
1291
1292 sl << uint8 (5) << uint8 (stat_hp);
1293
1294 if (stat_width > 1)
1295 {
1296 *last_ext |= 0x80;
1297 last_ext = &sl[sl.length ()];
1298
1299 sl << uint8 (6) << uint8 (stat_width);
1300 }
1301 }
1302
1303 if (lastcell.player != player)
1304 {
1305 lastcell.player = player;
1306
1307 mask |= 0x8;
1308 *last_ext |= 0x80;
1309 last_ext = &sl[sl.length ()];
1310
1311 sl << uint8 (0x47) << uint8 (4) << (uint32)player;
1312 }
1313
1314 if (lastcell.flags != flags)
1315 {
1316 lastcell.flags = flags;
1317
1318 mask |= 0x8;
1319 *last_ext |= 0x80;
1320 last_ext = &sl[sl.length ()];
1321
1322 sl << uint8 (8) << uint8 (flags);
1323 }
1324 }
1325
1326 /* Floor face */
1327 if (update_space (sl, socket, ms, lastcell, 2))
1328 mask |= 0x4;
1329
1330 /* Middle face */
1331 if (update_space (sl, socket, ms, lastcell, 1))
1332 mask |= 0x2;
1333
1334 if (ms.player () == ob
1335 && (ob->invisible & (ob->invisible < 50 ? 1 : 7)))
1336 {
1337 // force player to be visible to himself if invisible
1338 if (lastcell.faces[0] != ob->face)
1339 {
1340 lastcell.faces[0] = ob->face;
1341
1342 mask |= 0x1;
1343 sl << uint16 (ob->face);
1344
1345 socket.send_faces (ob);
1346 }
1347 }
1348 /* Top face */
1349 else if (update_space (sl, socket, ms, lastcell, 0))
1350 mask |= 0x1;
1351
1352 /* Check to see if we are in fact sending anything for this
1353 * space by checking the mask. If so, update the mask.
1354 * if not, reset the len to that from before adding the mask
1355 * value, so we don't send those bits.
1356 */
1357 if (mask & 0xf)
1358 sl[oldlen + 1] = mask & 0xff;
1359 else
1360 sl.reset (oldlen);
1361
1362 if (socket.ext_mapinfos)
1363 esl << uint16 (emask);
1364
1365 if (socket.EMI_smooth)
1366 {
1367 for (int layer = 2+1; layer--; )
1368 {
1369 object *ob = ms.faces_obj [layer];
1370
1371 // If there is no object for this space, or if the face for the object
1372 // is the blank face, set the smoothlevel to zero.
1373 int smoothlevel = ob && ob->face != blank_face ? ob->smoothlevel : 0;
1374
1375 // We've gotten what face we want to use for the object. Now see if
1376 // if it has changed since we last sent it to the client.
1377 if (lastcell.smooth[layer] != smoothlevel)
1378 {
1379 lastcell.smooth[layer] = smoothlevel;
1380 esl << uint8 (smoothlevel);
1381 emask |= 1 << layer;
1382 }
1383 }
1384
1385 if (emask & 0xf)
1386 esl[eoldlen + 1] = emask & 0xff;
1387 else
1388 esl.reset (eoldlen);
1389 }
1390 } /* else this is a viewable space */
1391 } /* for x loop */
1392 } /* for y loop */
1393
1394 socket.flush_fx ();
1395
1396 /* Verify that we in fact do need to send this */
1397 if (socket.ext_mapinfos)
1398 {
1399 if (!(sl.length () > startlen || socket.sent_scroll))
1400 {
1401 /* No map data will follow, so don't say the client
1402 * it doesn't need draw!
1403 */
1404 ewhatflag &= ~EMI_NOREDRAW;
1405 esl[ewhatstart + 1] = ewhatflag & 0xff;
1406 }
1407
1408 if (esl.length () > estartlen)
1409 socket.send_packet (esl);
1410 }
1411
1412 if (sl.length () > startlen || socket.sent_scroll)
1413 {
1414 socket.send_packet (sl);
1415 socket.sent_scroll = 0;
1416 }
1417 }
1418
1419 /*****************************************************************************/
1420 /* GROS: The following one is used to allow a plugin to send a generic cmd to*/
1421 /* a player. Of course, the client need to know the command to be able to */
1422 /* manage it ! */
1423 /*****************************************************************************/
1424 void
1425 send_plugin_custom_message (object *pl, char *buf)
1426 {
1427 pl->contr->ns->send_packet (buf);
1428 }
1429
1430 /**
1431 * This sends the skill number to name mapping. We ignore
1432 * the params - we always send the same info no matter what.
1433 */
1434 void
1435 send_skill_info (client *ns, char *params)
1436 {
1437 packet sl;
1438 sl << "replyinfo skill_info\n";
1439
1440 for (int i = 1; i < NUM_SKILLS; i++)
1441 sl.printf ("%d:%s\n", i + CS_STAT_SKILLINFO, &skill_names[i]);
1442
1443 if (sl.length () > MAXSOCKBUF)
1444 {
1445 LOG (llevError, "Buffer overflow in send_skill_info!\n");
1446 fatal (0);
1447 }
1448
1449 ns->send_packet (sl);
1450 }
1451
1452 /**
1453 * This sends the spell path to name mapping. We ignore
1454 * the params - we always send the same info no matter what.
1455 */
1456 void
1457 send_spell_paths (client * ns, char *params)
1458 {
1459 packet sl;
1460
1461 sl << "replyinfo spell_paths\n";
1462
1463 for (int i = 0; i < NRSPELLPATHS; i++)
1464 sl.printf ("%d:%s\n", 1 << i, spellpathnames[i]);
1465
1466 if (sl.length () > MAXSOCKBUF)
1467 {
1468 LOG (llevError, "Buffer overflow in send_spell_paths!\n");
1469 fatal (0);
1470 }
1471
1472 ns->send_packet (sl);
1473 }
1474
1475 /**
1476 * This looks for any spells the player may have that have changed their stats.
1477 * it then sends an updspell packet for each spell that has changed in this way
1478 */
1479 void
1480 esrv_update_spells (player *pl)
1481 {
1482 if (!pl->ns)
1483 return;
1484
1485 if (!pl->ns->monitor_spells)
1486 return;
1487
1488 for (object *spell = pl->ob->inv; spell; spell = spell->below)
1489 {
1490 if (spell->type == SPELL)
1491 {
1492 int flags = 0;
1493
1494 /* check if we need to update it */
1495 if (spell->cached_sp != SP_level_spellpoint_cost (pl->ob, spell, SPELL_MANA))
1496 {
1497 spell->cached_sp = SP_level_spellpoint_cost (pl->ob, spell, SPELL_MANA);
1498 flags |= UPD_SP_MANA;
1499 }
1500
1501 if (spell->cached_grace != SP_level_spellpoint_cost (pl->ob, spell, SPELL_GRACE))
1502 {
1503 spell->cached_grace = SP_level_spellpoint_cost (pl->ob, spell, SPELL_GRACE);
1504 flags |= UPD_SP_GRACE;
1505 }
1506
1507 if (spell->cached_eat != spell->stats.dam + SP_level_dam_adjust (pl->ob, spell))
1508 {
1509 spell->cached_eat = spell->stats.dam + SP_level_dam_adjust (pl->ob, spell);
1510 flags |= UPD_SP_DAMAGE;
1511 }
1512
1513 if (flags)
1514 {
1515 packet sl;
1516
1517 sl << "updspell "
1518 << uint8 (flags)
1519 << uint32 (spell->count);
1520
1521 if (flags & UPD_SP_MANA ) sl << uint16 (spell->cached_sp);
1522 if (flags & UPD_SP_GRACE ) sl << uint16 (spell->cached_grace);
1523 if (flags & UPD_SP_DAMAGE) sl << uint16 (spell->cached_eat);
1524
1525 pl->ns->send_packet (sl);
1526 }
1527 }
1528 }
1529 }
1530
1531 void
1532 esrv_remove_spell (player *pl, object *spell)
1533 {
1534 if (!pl->ns->monitor_spells)
1535 return;
1536
1537 if (!pl || !spell || spell->env != pl->ob)
1538 {
1539 LOG (llevError, "Invalid call to esrv_remove_spell");
1540 return;
1541 }
1542
1543 packet sl ("delspell");
1544
1545 sl << uint32 (spell->count);
1546
1547 pl->ns->send_packet (sl);
1548 }
1549
1550 /* appends the spell *spell to the Socklist we will send the data to. */
1551 static void
1552 append_spell (player *pl, packet &sl, object *spell)
1553 {
1554 int i, skill = 0;
1555
1556 if (!(spell->name))
1557 {
1558 LOG (llevError, "item number %d is a spell with no name.\n", spell->count);
1559 return;
1560 }
1561
1562 /* store costs and damage in the object struct, to compare to later */
1563 spell->cached_sp = SP_level_spellpoint_cost (pl->ob, spell, SPELL_MANA);
1564 spell->cached_grace = SP_level_spellpoint_cost (pl->ob, spell, SPELL_GRACE);
1565 spell->cached_eat = spell->stats.dam + SP_level_dam_adjust (pl->ob, spell);
1566
1567 /* figure out which skill it uses, if it uses one */
1568 if (spell->skill)
1569 {
1570 for (i = 1; i < NUM_SKILLS; i++)
1571 if (!strcmp (spell->skill, skill_names[i]))
1572 {
1573 skill = i + CS_STAT_SKILLINFO;
1574 break;
1575 }
1576 }
1577
1578 // spells better have a face
1579 if (!spell->face)
1580 {
1581 LOG (llevError, "%s: spell has no face, but face is mandatory.\n", &spell->name);
1582 spell->face = face_find ("burnout.x11", blank_face);
1583 }
1584
1585 pl->ns->send_face (spell->face);
1586
1587 /* send the current values */
1588 sl << uint32 (spell->count)
1589 << uint16 (spell->level)
1590 << uint16 (spell->casting_time)
1591 << uint16 (spell->cached_sp)
1592 << uint16 (spell->cached_grace)
1593 << uint16 (spell->cached_eat)
1594 << uint8 (skill)
1595 << uint32 (spell->path_attuned)
1596 << uint32 (spell->face)
1597 << data8 (spell->name)
1598 << data16 (spell->msg);
1599 }
1600
1601 /**
1602 * This tells the client to add the spell *ob, if *ob is NULL, then add
1603 * all spells in the player's inventory.
1604 */
1605 void
1606 esrv_add_spells (player *pl, object *spell)
1607 {
1608 if (!pl)
1609 {
1610 LOG (llevError, "esrv_add_spells, tried to add a spell to a NULL player");
1611 return;
1612 }
1613
1614 if (!pl->ns->monitor_spells)
1615 return;
1616
1617 packet sl ("addspell");
1618
1619 if (!spell)
1620 {
1621 for (spell = pl->ob->inv; spell; spell = spell->below)
1622 {
1623 /* were we to simply keep appending data here, we could exceed
1624 * MAXSOCKBUF if the player has enough spells to add, we know that
1625 * append_spells will always append 19 data bytes, plus 4 length
1626 * bytes and 3 strings (because that is the spec) so we need to
1627 * check that the length of those 3 strings, plus the 23 bytes,
1628 * won't take us over the length limit for the socket, if it does,
1629 * we need to send what we already have, and restart packet formation
1630 */
1631 if (spell->type != SPELL)
1632 continue;
1633
1634 /* Seeing crashes by overflowed buffers. Quick arithemetic seems
1635 * to show add_spell is 26 bytes + 2 strings. However, the overun
1636 * is hundreds of bytes off, so correcting 22 vs 26 doesn't seem
1637 * like it will fix this
1638 */
1639 if (sl.length () > (MAXSOCKBUF - (26 + strlen (spell->name) + (spell->msg ? strlen (spell->msg) : 0))))
1640 {
1641 pl->ns->flush_fx ();
1642 pl->ns->send_packet (sl);
1643
1644 sl.reset ();
1645 sl << "addspell ";
1646 }
1647
1648 append_spell (pl, sl, spell);
1649 }
1650 }
1651 else if (spell->type != SPELL)
1652 {
1653 LOG (llevError, "Asked to send a non-spell object as a spell");
1654 return;
1655 }
1656 else
1657 append_spell (pl, sl, spell);
1658
1659 if (sl.length () > MAXSOCKBUF)
1660 {
1661 LOG (llevError, "Buffer overflow in esrv_add_spells!\n");
1662 fatal (0);
1663 }
1664
1665 /* finally, we can send the packet */
1666 pl->ns->flush_fx ();
1667 pl->ns->send_packet (sl);
1668 }
1669