ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/socket/request.c
Revision: 1.3
Committed: Sun Apr 16 02:56:46 2006 UTC (18 years, 2 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.2: +12 -3 lines
Log Message:
add some tile info to the mapinfo notification

File Contents

# User Rev Content
1 root 1.1 /*
2     * static char *rcsid_init_c =
3 root 1.2 * "$Id$";
4 root 1.1 */
5    
6     /*
7     CrossFire, A Multiplayer game for X-windows
8    
9     Copyright (C) 2001 Mark Wedel
10     Copyright (C) 1992 Frank Tore Johansen
11    
12     This program is free software; you can redistribute it and/or modify
13     it under the terms of the GNU General Public License as published by
14     the Free Software Foundation; either version 2 of the License, or
15     (at your option) any later version.
16    
17     This program is distributed in the hope that it will be useful,
18     but WITHOUT ANY WARRANTY; without even the implied warranty of
19     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20     GNU General Public License for more details.
21    
22     You should have received a copy of the GNU General Public License
23     along with this program; if not, write to the Free Software
24     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25    
26     The author can be reached via e-mail to crossfire-devel@real-time.com
27     */
28    
29     /**
30     * \file
31     * Client handling.
32     *
33     * \date 2003-12-02
34     *
35     * This file implements all of the goo on the server side for handling
36     * clients. It's got a bunch of global variables for keeping track of
37     * each of the clients.
38     *
39     * Note: All functions that are used to process data from the client
40     * have the prototype of (char *data, int datalen, int client_num). This
41     * way, we can use one dispatch table.
42     *
43     * esrv_map_new starts updating the map
44     *
45     * esrv_map_setbelow allows filling in all of the faces for the map.
46     * if a face has not already been sent to the client, it is sent now.
47     *
48     * mapcellchanged, compactlayer, compactstack, perform the map compressing
49     * operations
50     *
51     * esrv_map_doneredraw finishes the map update, and ships across the
52     * map updates.
53     *
54     * esrv_map_scroll tells the client to scroll the map, and does similarily
55     * for the locally cached copy.
56     */
57    
58     #include <global.h>
59     #include <sproto.h>
60    
61     #include <newclient.h>
62     #include <newserver.h>
63     #include <living.h>
64     #include <commands.h>
65    
66     /* This block is basically taken from socket.c - I assume if it works there,
67     * it should work here.
68     */
69     #ifndef WIN32 /* ---win32 exclude unix headers */
70     #include <sys/types.h>
71     #include <sys/time.h>
72     #include <sys/socket.h>
73     #include <netinet/in.h>
74     #include <netdb.h>
75     #endif /* win32 */
76    
77     #ifdef HAVE_UNISTD_H
78     #include <unistd.h>
79     #endif
80    
81     #ifdef HAVE_SYS_TIME_H
82     #include <sys/time.h>
83     #endif
84    
85     #include "sounds.h"
86    
87     /**
88     * This table translates the attack numbers as used within the
89     * program to the value we use when sending STATS command to the
90     * client. If a value is -1, then we don't send that to the
91     * client.
92     */
93     short atnr_cs_stat[NROFATTACKS] = {CS_STAT_RES_PHYS,
94     CS_STAT_RES_MAG,CS_STAT_RES_FIRE, CS_STAT_RES_ELEC,
95     CS_STAT_RES_COLD, CS_STAT_RES_CONF, CS_STAT_RES_ACID,
96     CS_STAT_RES_DRAIN, -1 /* weaponmagic */,
97     CS_STAT_RES_GHOSTHIT, CS_STAT_RES_POISON,
98     CS_STAT_RES_SLOW, CS_STAT_RES_PARA, CS_STAT_TURN_UNDEAD,
99     CS_STAT_RES_FEAR, -1 /* Cancellation */,
100     CS_STAT_RES_DEPLETE, CS_STAT_RES_DEATH,
101     -1 /* Chaos */, -1 /* Counterspell */,
102     -1 /* Godpower */, CS_STAT_RES_HOLYWORD,
103     CS_STAT_RES_BLIND,
104     -1, /* Internal */
105     -1, /* life stealing */
106     -1 /* Disease - not fully done yet */
107     };
108    
109 root 1.2 /** check for map change and send new map data */
110     static void
111     check_map_change (player *pl)
112     {
113     char buf[MAX_BUF]; /* eauugggh */
114    
115     object *ob = pl->ob;
116    
117     if (!pl->socket.mapinfocmd)
118     return;
119    
120     if (pl->socket.current_map != ob->map)
121     {
122     pl->socket.current_map = ob->map;
123    
124     if (ob->map && ob->map->path [0])
125 root 1.3 {
126     int flags = 0;
127    
128     if (ob->map->tile_map [0]) flags |= 1;
129     if (ob->map->tile_map [1]) flags |= 2;
130     if (ob->map->tile_map [2]) flags |= 4;
131     if (ob->map->tile_map [3]) flags |= 8;
132    
133     snprintf (buf, MAX_BUF, "mapinfo current %d %d %d %d %d %s",
134     flags, ob->x, ob->y,
135     ob->map->width, ob->map->height, ob->map->path);
136     }
137 root 1.2 else
138     snprintf (buf, MAX_BUF, "mapinfo current");
139    
140     Write_String_To_Socket (&pl->socket, buf, strlen (buf));
141     }
142     }
143    
144 root 1.1 /** This is the Setup cmd - easy first implementation */
145     void SetUp(char *buf, int len, NewSocket *ns)
146     {
147 root 1.2 int s, slen;
148 root 1.1 char *cmd, *param, cmdback[HUGE_BUF];
149    
150     /* run through the cmds of setup
151     * syntax is setup <cmdname1> <parameter> <cmdname2> <parameter> ...
152     *
153     * we send the status of the cmd back, or a FALSE is the cmd is the server unknown
154     * The client then must sort this out
155     */
156    
157     LOG(llevInfo,"Get SetupCmd:: %s\n", buf);
158     strcpy(cmdback,"setup");
159     for(s=0;s<len; ) {
160    
161     cmd = &buf[s];
162    
163     /* find the next space, and put a null there */
164     for(;buf[s] && buf[s] != ' ';s++) ;
165     buf[s++]=0;
166     while (buf[s] == ' ') s++;
167    
168     if(s>=len)
169     break;
170    
171     param = &buf[s];
172    
173     for(;buf[s] && buf[s] != ' ';s++) ;
174     buf[s++]=0;
175     while (buf[s] == ' ') s++;
176    
177 root 1.2 slen = strlen(cmdback);
178     safe_strcat(cmdback, " ", &slen, HUGE_BUF);
179     safe_strcat(cmdback, cmd, &slen, HUGE_BUF);
180     safe_strcat(cmdback, " ", &slen, HUGE_BUF);
181 root 1.1
182     if (!strcmp(cmd,"sound")) {
183     ns->sound = atoi(param);
184 root 1.2 safe_strcat(cmdback, param, &slen, HUGE_BUF);
185 root 1.1 }
186     else if (!strcmp(cmd,"exp64")) {
187     ns->exp64 = atoi(param);
188 root 1.2 safe_strcat(cmdback, param, &slen, HUGE_BUF);
189 root 1.1 } else if (!strcmp(cmd, "spellmon")) {
190     ns->monitor_spells = atoi(param);
191 root 1.2 safe_strcat(cmdback, param, &slen, HUGE_BUF);
192 root 1.1 } else if (!strcmp(cmd,"darkness")) {
193     ns->darkness = atoi(param);
194 root 1.2 safe_strcat(cmdback, param, &slen, HUGE_BUF);
195 root 1.1 } else if (!strcmp(cmd,"map1cmd")) {
196     if (atoi(param)) ns->mapmode = Map1Cmd;
197     /* if beyond this size, need to use map1cmd no matter what */
198     if (ns->mapx>11 || ns->mapy>11) ns->mapmode = Map1Cmd;
199 root 1.2 safe_strcat(cmdback, ns->mapmode == Map1Cmd?"1":"0", &slen, HUGE_BUF);
200 root 1.1 } else if (!strcmp(cmd,"map1acmd")) {
201     if (atoi(param)) ns->mapmode = Map1aCmd;
202     /* if beyond this size, need to use map1acmd no matter what */
203     if (ns->mapx>11 || ns->mapy>11) ns->mapmode = Map1aCmd;
204 root 1.2 safe_strcat(cmdback, ns->mapmode == Map1aCmd?"1":"0", &slen, HUGE_BUF);
205 root 1.1 } else if (!strcmp(cmd,"newmapcmd")) {
206     ns->newmapcmd= atoi(param);
207 root 1.2 safe_strcat(cmdback, param, &slen, HUGE_BUF);
208     // } else if (!strcmp(cmd,"plugincmd")) {
209     // ns->plugincmd = atoi(param);
210     // safe_strcat(cmdback, param, &slen, HUGE_BUF);
211     } else if (!strcmp(cmd,"mapinfocmd")) {
212     ns->mapinfocmd = atoi(param);
213     safe_strcat(cmdback, param, &slen, HUGE_BUF);
214 root 1.1 } else if (!strcmp(cmd,"facecache")) {
215     ns->facecache = atoi(param);
216 root 1.2 safe_strcat(cmdback, param, &slen, HUGE_BUF);
217 root 1.1 } else if (!strcmp(cmd,"faceset")) {
218     char tmpbuf[20];
219     int q = atoi(param);
220    
221     if (is_valid_faceset(q))
222     ns->faceset=q;
223     sprintf(tmpbuf,"%d", ns->faceset);
224 root 1.2 safe_strcat(cmdback, tmpbuf, &slen, HUGE_BUF);
225 root 1.1 /* if the client is using faceset, it knows about image2 command */
226     ns->image2=1;
227     } else if (!strcmp(cmd,"itemcmd")) {
228     /* Version of the item protocol command to use. Currently,
229     * only supported versions are 1 and 2. Using a numeric
230     * value will make it very easy to extend this in the future.
231     */
232     char tmpbuf[20];
233     int q = atoi(param);
234     if (q<1 || q>2) {
235     strcpy(tmpbuf,"FALSE");
236     } else {
237     ns->itemcmd = q;
238     sprintf(tmpbuf,"%d", ns->itemcmd);
239     }
240 root 1.2 safe_strcat(cmdback, tmpbuf, &slen, HUGE_BUF);
241 root 1.1 } else if (!strcmp(cmd,"mapsize")) {
242     int x, y=0;
243     char tmpbuf[MAX_BUF], *cp;
244    
245     x = atoi(param);
246     for (cp = param; *cp!=0; cp++)
247     if (*cp == 'x' || *cp == 'X') {
248     y = atoi(cp+1);
249     break;
250     }
251     if (x < 9 || y < 9 || x>MAP_CLIENT_X || y > MAP_CLIENT_Y) {
252     sprintf(tmpbuf," %dx%d", MAP_CLIENT_X, MAP_CLIENT_Y);
253 root 1.2 safe_strcat(cmdback, tmpbuf, &slen, HUGE_BUF);
254 root 1.1 } else {
255     ns->mapx = x;
256     ns->mapy = y;
257     /* better to send back what we are really using and not the
258     * param as given to us in case it gets parsed differently.
259     */
260     sprintf(tmpbuf,"%dx%d", x,y);
261 root 1.2 safe_strcat(cmdback, tmpbuf, &slen, HUGE_BUF);
262 root 1.1 /* If beyond this size and still using orig map command, need to
263     * go to map1cmd.
264     */
265     if ((x>11 || y>11) && ns->mapmode == Map0Cmd) ns->mapmode = Map1Cmd;
266     }
267     } else if (!strcmp(cmd,"extendedMapInfos")) {
268 root 1.2 /* Added by tchize
269     * prepare to use the mapextended command
270     */
271 root 1.1 char tmpbuf[20];
272 root 1.2 ns->ext_mapinfos = (atoi(param));
273 root 1.1 sprintf(tmpbuf,"%d", ns->ext_mapinfos);
274 root 1.2 safe_strcat(cmdback, tmpbuf, &slen, HUGE_BUF);
275 root 1.1 } else if (!strcmp(cmd,"extendedTextInfos")) {
276 root 1.2 /* Added by tchize
277     * prepare to use the extended text commands
278     * Client toggle this to non zero to get exttext
279     */
280 root 1.1 char tmpbuf[20];
281 root 1.2
282     ns->has_readable_type = (atoi(param));
283 root 1.1 sprintf(tmpbuf,"%d", ns->has_readable_type);
284 root 1.2 safe_strcat(cmdback, tmpbuf, &slen, HUGE_BUF);
285 root 1.1 } else {
286     /* Didn't get a setup command we understood -
287     * report a failure to the client.
288     */
289 root 1.2 safe_strcat(cmdback, "FALSE", &slen, HUGE_BUF);
290 root 1.1 }
291     } /* for processing all the setup commands */
292     LOG(llevInfo,"SendBack SetupCmd:: %s\n", cmdback);
293     Write_String_To_Socket(ns, cmdback, strlen(cmdback));
294     }
295    
296     /**
297     * The client has requested to be added to the game.
298     * This is what takes care of it. We tell the client how things worked out.
299     * I am not sure if this file is the best place for this function. however,
300     * it either has to be here or init_sockets needs to be exported.
301     */
302     void AddMeCmd(char *buf, int len, NewSocket *ns)
303     {
304     Settings oldsettings;
305     oldsettings=settings;
306     if (ns->status != Ns_Add || add_player(ns)) {
307     Write_String_To_Socket(ns, "addme_failed",12);
308     } else {
309     /* Basically, the add_player copies the socket structure into
310     * the player structure, so this one (which is from init_sockets)
311     * is not needed anymore. The write below should still work, as the
312     * stuff in ns is still relevant.
313     */
314     Write_String_To_Socket(ns, "addme_success",13);
315     socket_info.nconns--;
316     ns->status = Ns_Avail;
317     }
318     settings=oldsettings;
319     }
320    
321     /** Reply to ExtendedInfos command */
322     void ToggleExtendedInfos (char *buf, int len, NewSocket *ns){
323     char cmdback[MAX_BUF];
324     char command[50];
325     int info,nextinfo;
326     cmdback[0]='\0';
327     nextinfo=0;
328     while (1){
329     /* 1. Extract an info*/
330     info=nextinfo;
331     while ( (info<len) && (buf[info]==' ') ) info++;
332     if (info>=len)
333     break;
334     nextinfo=info+1;
335     while ( (nextinfo<len) && (buf[nextinfo]!=' ') )
336     nextinfo++;
337     if (nextinfo-info>=49) /*Erroneous info asked*/
338     continue;
339     strncpy (command,&(buf[info]),nextinfo-info);
340     command[nextinfo-info]='\0';
341     /* 2. Interpret info*/
342     if (!strcmp("smooth",command)){
343     /* Toggle smoothing*/
344     ns->EMI_smooth=!ns->EMI_smooth;
345     }else{
346     /*bad value*/
347     }
348     /*3. Next info*/
349     }
350     strcpy (cmdback,"ExtendedInfoSet");
351     if (ns->EMI_smooth){
352     strcat (cmdback," ");
353     strcat (cmdback,"smoothing");
354     }
355     Write_String_To_Socket(ns, cmdback,strlen(cmdback));
356     }
357     /*
358     #define MSG_TYPE_BOOK 1
359     #define MSG_TYPE_CARD 2
360     #define MSG_TYPE_PAPER 3
361     #define MSG_TYPE_SIGN 4
362     #define MSG_TYPE_MONUMENT 5
363     #define MSG_TYPE_SCRIPTED_DIALOG 6*/
364     /** Reply to ExtendedInfos command */
365     void ToggleExtendedText (char *buf, int len, NewSocket *ns){
366     char cmdback[MAX_BUF];
367     char temp[10];
368     char command[50];
369     int info,nextinfo,i,flag;
370     cmdback[0]='\0';
371     nextinfo=0;
372     while (1){
373     /* 1. Extract an info*/
374     info=nextinfo;
375     while ( (info<len) && (buf[info]==' ') ) info++;
376     if (info>=len)
377     break;
378     nextinfo=info+1;
379     while ( (nextinfo<len) && (buf[nextinfo]!=' ') )
380     nextinfo++;
381     if (nextinfo-info>=49) /*Erroneous info asked*/
382     continue;
383     strncpy (command,&(buf[info]),nextinfo-info);
384     command[nextinfo-info]='\0';
385     /* 2. Interpret info*/
386     i = sscanf(command,"%d",&flag);
387     if ( (i==1) && (flag>0) && (flag<=MSG_TYPE_LAST))
388     ns->supported_readables|=(1<<flag);
389     /*3. Next info*/
390     }
391     /* Send resulting state */
392     strcpy (cmdback,"ExtendedTextSet");
393     for (i=0;i<=MSG_TYPE_LAST;i++)
394     if (ns->supported_readables &(1<<i)){
395     strcat (cmdback," ");
396     snprintf(temp,sizeof(temp),"%d",i);
397     strcat (cmdback,temp);
398     }
399     Write_String_To_Socket(ns, cmdback,strlen(cmdback));
400     }
401    
402     /**
403     * A lot like the old AskSmooth (in fact, now called by AskSmooth).
404     * Basically, it makes no sense to wait for the client to request a
405     * a piece of data from us that we know the client wants. So
406     * if we know the client wants it, might as well push it to the
407     * client.
408     */
409 root 1.2 static void SendSmooth(NewSocket *ns, uint16 face) {
410 root 1.1 uint16 smoothface;
411     uint8 reply[MAX_BUF];
412     SockList sl;
413    
414     /* If we can't find a face, return and set it so we won't try to send this
415     * again.
416     */
417     if ((!FindSmooth (face, &smoothface)) &&
418     (!FindSmooth ( smooth_face->number, &smoothface))) {
419    
420     LOG(llevError,"could not findsmooth for %d. Neither default (%s)\n",face,smooth_face->name);
421     ns->faces_sent[face] |= NS_FACESENT_SMOOTH;
422     return;
423     }
424    
425     if (!(ns->faces_sent[smoothface] & NS_FACESENT_FACE))
426     esrv_send_face(ns, smoothface, 0);
427    
428     ns->faces_sent[face] |= NS_FACESENT_SMOOTH;
429    
430     sl.buf=reply;
431     strcpy((char*)sl.buf,"smooth ");
432     sl.len=strlen((char*)sl.buf);
433     SockList_AddShort(&sl, face);
434     SockList_AddShort(&sl, smoothface);
435     Send_With_Handling(ns, &sl);
436     }
437    
438     /**
439     * Tells client the picture it has to use
440     * to smooth a picture number given as argument.
441     */
442     void AskSmooth (char *buf, int len, NewSocket *ns){
443     uint16 facenbr;
444    
445     facenbr=atoi (buf);
446     SendSmooth(ns, facenbr);
447     }
448    
449    
450    
451    
452    
453     /**
454     * This handles the general commands from the client (ie, north, fire, cast,
455     * etc.)
456     */
457     void PlayerCmd(char *buf, int len, player *pl)
458     {
459    
460     /* The following should never happen with a proper or honest client.
461     * Therefore, the error message doesn't have to be too clear - if
462     * someone is playing with a hacked/non working client, this gives them
463     * an idea of the problem, but they deserve what they get
464     */
465     if (pl->state!=ST_PLAYING) {
466     new_draw_info_format(NDI_UNIQUE, 0,pl->ob,
467     "You can not issue commands - state is not ST_PLAYING (%s)", buf);
468     return;
469     }
470     /* Check if there is a count. In theory, a zero count could also be
471     * sent, so check for that also.
472     */
473     if (atoi(buf) || buf[0]=='0') {
474     pl->count=atoi((char*)buf);
475     buf=strchr(buf,' '); /* advance beyond the numbers */
476     if (!buf) {
477     #ifdef ESRV_DEBUG
478     LOG(llevDebug,"PlayerCmd: Got count but no command.\n");
479     #endif
480     return;
481     }
482     buf++;
483     }
484     /* This should not happen anymore. */
485     if (pl->ob->speed_left<-1.0) {
486     LOG(llevError,"Player has negative time - shouldn't do command.\n");
487     }
488     /* In c_new.c */
489     execute_newserver_command(pl->ob, (char*)buf);
490     /* Perhaps something better should be done with a left over count.
491     * Cleaning up the input should probably be done first - all actions
492     * for the command that issued the count should be done before any other
493     * commands.
494     */
495    
496     pl->count=0;
497    
498     }
499    
500    
501     /**
502     * This handles the general commands from the client (ie, north, fire, cast,
503     * etc.). It is a lot like PlayerCmd above, but is called with the
504     * 'ncom' method which gives more information back to the client so it
505     * can throttle.
506     */
507     void NewPlayerCmd(uint8 *buf, int len, player *pl)
508     {
509     int time,repeat;
510     short packet;
511     char command[MAX_BUF];
512     SockList sl;
513    
514     if (len < 7) {
515     LOG(llevDebug,"Corrupt ncom command - not long enough - discarding\n");
516     return;
517     }
518    
519     packet = GetShort_String(buf);
520     repeat = GetInt_String(buf+2);
521     /* -1 is special - no repeat, but don't update */
522     if (repeat!=-1) {
523     pl->count=repeat;
524     }
525     if ((len-4) >= MAX_BUF) len=MAX_BUF-5;
526    
527     strncpy(command, (char*)buf+6, len-4);
528     command[len-4]='\0';
529    
530     /* The following should never happen with a proper or honest client.
531     * Therefore, the error message doesn't have to be too clear - if
532     * someone is playing with a hacked/non working client, this gives them
533     * an idea of the problem, but they deserve what they get
534     */
535     if (pl->state!=ST_PLAYING) {
536     new_draw_info_format(NDI_UNIQUE, 0,pl->ob,
537     "You can not issue commands - state is not ST_PLAYING (%s)", buf);
538     return;
539     }
540    
541     /* This should not happen anymore. */
542     if (pl->ob->speed_left<-1.0) {
543     LOG(llevError,"Player has negative time - shouldn't do command.\n");
544     }
545     /* In c_new.c */
546     execute_newserver_command(pl->ob, command);
547     /* Perhaps something better should be done with a left over count.
548     * Cleaning up the input should probably be done first - all actions
549     * for the command that issued the count should be done before any other
550     * commands.
551     */
552     pl->count=0;
553    
554     /* Send confirmation of command execution now */
555     sl.buf = (uint8*)command;
556     strcpy((char*)sl.buf,"comc ");
557     sl.len=5;
558     SockList_AddShort(&sl,packet);
559     if (FABS(pl->ob->speed) < 0.001) time=MAX_TIME * 100;
560     else
561     time = ( int )( MAX_TIME/ FABS(pl->ob->speed) );
562     SockList_AddInt(&sl,time);
563     Send_With_Handling(&pl->socket, &sl);
564     }
565    
566    
567     /** This is a reply to a previous query. */
568     void ReplyCmd(char *buf, int len, player *pl)
569     {
570     /* This is to synthesize how the data would be stored if it
571     * was normally entered. A bit of a hack, and should be cleaned up
572     * once all the X11 code is removed from the server.
573     *
574     * We pass 13 to many of the functions because this way they
575     * think it was the carriage return that was entered, and the
576     * function then does not try to do additional input.
577     */
578     snprintf(pl->write_buf, sizeof(pl->write_buf), ":%s", buf);
579    
580     /* this avoids any hacking here */
581    
582     switch (pl->state) {
583     case ST_PLAYING:
584     LOG(llevError,"Got reply message with ST_PLAYING input state\n");
585     break;
586    
587     case ST_PLAY_AGAIN:
588     /* We can check this for return value (2==quit). Maybe we
589     * should, and do something appropriate?
590     */
591     receive_play_again(pl->ob, buf[0]);
592     break;
593    
594     case ST_ROLL_STAT:
595     key_roll_stat(pl->ob,buf[0]);
596     break;
597    
598     case ST_CHANGE_CLASS:
599    
600     key_change_class(pl->ob, buf[0]);
601     break;
602    
603     case ST_CONFIRM_QUIT:
604     key_confirm_quit(pl->ob, buf[0]);
605     break;
606    
607     case ST_CONFIGURE:
608     LOG(llevError,"In client input handling, but into configure state\n");
609     pl->state = ST_PLAYING;
610     break;
611    
612     case ST_GET_NAME:
613     receive_player_name(pl->ob,13);
614     break;
615    
616     case ST_GET_PASSWORD:
617     case ST_CONFIRM_PASSWORD:
618     receive_player_password(pl->ob,13);
619     break;
620    
621     case ST_GET_PARTY_PASSWORD: /* Get password for party */
622     receive_party_password(pl->ob,13);
623     break;
624    
625     default:
626     LOG(llevError,"Unknown input state: %d\n", pl->state);
627     }
628     }
629    
630     /**
631     * Client tells its version. If there is a mismatch, we close the
632     * socket. In real life, all we should care about is the client having
633     * something older than the server. If we assume the client will be
634     * backwards compatible, having it be a later version should not be a
635     * problem.
636     */
637     void VersionCmd(char *buf, int len,NewSocket *ns)
638     {
639     char *cp;
640     char version_warning[256];
641    
642     if (!buf) {
643     LOG(llevError, "CS: received corrupted version command\n");
644     return;
645     }
646    
647     ns->cs_version = atoi(buf);
648     ns->sc_version = ns->cs_version;
649     if (VERSION_CS != ns->cs_version) {
650     #ifdef ESRV_DEBUG
651     LOG(llevDebug, "CS: csversion mismatch (%d,%d)\n", VERSION_CS,ns->cs_version);
652     #endif
653     }
654     cp = strchr(buf+1,' ');
655     if (!cp) return;
656     ns->sc_version = atoi(cp);
657     if (VERSION_SC != ns->sc_version) {
658     #ifdef ESRV_DEBUG
659     LOG(llevDebug, "CS: scversion mismatch (%d,%d)\n",VERSION_SC,ns->sc_version);
660     #endif
661     }
662     cp = strchr(cp+1, ' ');
663     if (cp) {
664 root 1.2 LOG(llevDebug,"CS: connection from client of type <%s>, ip %s\n", cp, ns->host);
665 root 1.1
666     /* This is first implementation - i skip all beta DX clients with it
667     * Add later stuff here for other clients
668     */
669    
670     /* these are old dxclients */
671     /* Version 1024 added support for singular + plural name values -
672     * requiing this minimal value reduces complexity of that code, and it
673     * has been around for a long time.
674     */
675     if(!strcmp(" CF DX CLIENT", cp) || ns->sc_version < 1024 )
676     {
677     sprintf(version_warning,"drawinfo %d %s", NDI_RED, "**** VERSION WARNING ****\n**** CLIENT IS TOO OLD!! UPDATE THE CLIENT!! ****");
678     Write_String_To_Socket(ns, version_warning, strlen(version_warning));
679     }
680    
681     }
682     }
683    
684     /** sound related functions. */
685    
686     void SetSound(char *buf, int len, NewSocket *ns)
687     {
688     ns->sound = atoi(buf);
689     }
690    
691     /** client wants the map resent */
692    
693     void MapRedrawCmd(char *buf, int len, player *pl)
694     {
695     /* This function is currently disabled; just clearing the map state results in
696     * display errors. It should clear the cache and send a newmap command.
697     * Unfortunately this solution does not work because some client versions send
698     * a mapredraw command after receiving a newmap command.
699     */
700     #if 0
701     /* Okay, this is MAJOR UGLY. but the only way I know how to
702     * clear the "cache"
703     */
704     memset(&pl->socket.lastmap, 0, sizeof(struct Map));
705     draw_client_map(pl->ob);
706     #endif
707     }
708    
709     /** Newmap command */
710     void MapNewmapCmd( player *pl)
711     {
712     if( pl->socket.newmapcmd == 1) {
713     memset(&pl->socket.lastmap, 0, sizeof(pl->socket.lastmap));
714     Write_String_To_Socket( &pl->socket, "newmap", 6);
715     }
716 root 1.2 check_map_change (pl);
717 root 1.1 }
718    
719    
720    
721     /**
722     * Moves an object (typically, container to inventory).
723     * syntax is: move (to) (tag) (nrof)
724     */
725     void MoveCmd(char *buf, int len,player *pl)
726     {
727     int vals[3], i;
728    
729     /* A little funky here. We only cycle for 2 records, because
730     * we obviously am not going to find a space after the third
731     * record. Perhaps we should just replace this with a
732     * sscanf?
733     */
734     for (i=0; i<2; i++) {
735     vals[i]=atoi(buf);
736     if (!(buf = strchr(buf, ' '))) {
737     LOG(llevError,"Incomplete move command: %s\n", buf);
738     return;
739     }
740     buf++;
741     }
742     vals[2]=atoi(buf);
743    
744     /* LOG(llevDebug,"Move item %d (nrof=%d) to %d.\n", vals[1], vals[2], vals[0]);*/
745     esrv_move_object(pl->ob,vals[0], vals[1], vals[2]);
746     }
747    
748    
749    
750     /******************************************************************************
751     *
752     * Start of commands the server sends to the client.
753     *
754     ******************************************************************************/
755    
756     /**
757     * Asks the client to query the user. This way, the client knows
758     * it needs to send something back (vs just printing out a message)
759     */
760     void send_query(NewSocket *ns, uint8 flags, char *text)
761     {
762     char buf[MAX_BUF];
763    
764     sprintf(buf,"query %d %s", flags, text?text:"");
765     Write_String_To_Socket(ns, buf, strlen(buf));
766     }
767    
768     #define AddIfInt64(Old,New,Type) if (Old != New) {\
769     Old = New; \
770     SockList_AddChar(&sl, Type); \
771     SockList_AddInt64(&sl, New); \
772     }
773    
774     #define AddIfInt(Old,New,Type) if (Old != New) {\
775     Old = New; \
776     SockList_AddChar(&sl, Type); \
777     SockList_AddInt(&sl, New); \
778     }
779    
780     #define AddIfShort(Old,New,Type) if (Old != New) {\
781     Old = New; \
782     SockList_AddChar(&sl, Type); \
783     SockList_AddShort(&sl, New); \
784     }
785    
786     #define AddIfFloat(Old,New,Type) if (Old != New) {\
787     Old = New; \
788     SockList_AddChar(&sl, Type); \
789     SockList_AddInt(&sl,(long)(New*FLOAT_MULTI));\
790     }
791    
792     #define AddIfString(Old,New,Type) if (Old == NULL || strcmp(Old,New)) {\
793     if (Old) free(Old);\
794     Old = strdup_local(New);\
795     SockList_AddChar(&sl, Type); \
796     SockList_AddChar(&sl, ( char )strlen(New)); \
797     strcpy((char*)sl.buf + sl.len, New); \
798     sl.len += strlen(New); \
799     }
800    
801     /**
802     * Sends a statistics update. We look at the old values,
803     * and only send what has changed. Stat mapping values are in newclient.h
804     * Since this gets sent a lot, this is actually one of the few binary
805     * commands for now.
806     */
807     void esrv_update_stats(player *pl)
808     {
809     SockList sl;
810     char buf[MAX_BUF];
811     uint16 flags;
812    
813     sl.buf=malloc(MAXSOCKBUF);
814     strcpy((char*)sl.buf,"stats ");
815     sl.len=strlen((char*)sl.buf);
816    
817     if(pl->ob != NULL)
818     {
819     AddIfShort(pl->last_stats.hp, pl->ob->stats.hp, CS_STAT_HP);
820     AddIfShort(pl->last_stats.maxhp, pl->ob->stats.maxhp, CS_STAT_MAXHP);
821     AddIfShort(pl->last_stats.sp, pl->ob->stats.sp, CS_STAT_SP);
822     AddIfShort(pl->last_stats.maxsp, pl->ob->stats.maxsp, CS_STAT_MAXSP);
823     AddIfShort(pl->last_stats.grace, pl->ob->stats.grace, CS_STAT_GRACE);
824     AddIfShort(pl->last_stats.maxgrace, pl->ob->stats.maxgrace, CS_STAT_MAXGRACE);
825     AddIfShort(pl->last_stats.Str, pl->ob->stats.Str, CS_STAT_STR);
826     AddIfShort(pl->last_stats.Int, pl->ob->stats.Int, CS_STAT_INT);
827     AddIfShort(pl->last_stats.Pow, pl->ob->stats.Pow, CS_STAT_POW);
828     AddIfShort(pl->last_stats.Wis, pl->ob->stats.Wis, CS_STAT_WIS);
829     AddIfShort(pl->last_stats.Dex, pl->ob->stats.Dex, CS_STAT_DEX);
830     AddIfShort(pl->last_stats.Con, pl->ob->stats.Con, CS_STAT_CON);
831     AddIfShort(pl->last_stats.Cha, pl->ob->stats.Cha, CS_STAT_CHA);
832     }
833     if(pl->socket.exp64) {
834     uint8 s;
835     for(s=0;s<NUM_SKILLS;s++) {
836     if (pl->last_skill_ob[s] &&
837     pl->last_skill_exp[s] != pl->last_skill_ob[s]->stats.exp) {
838    
839     /* Always send along the level if exp changes. This is only
840     * 1 extra byte, but keeps processing simpler.
841     */
842     SockList_AddChar(&sl, ( char )( s + CS_STAT_SKILLINFO ));
843     SockList_AddChar(&sl, ( char )pl->last_skill_ob[s]->level);
844     SockList_AddInt64(&sl, pl->last_skill_ob[s]->stats.exp);
845     pl->last_skill_exp[s] = pl->last_skill_ob[s]->stats.exp;
846     }
847     }
848     }
849     if (pl->socket.exp64) {
850     AddIfInt64(pl->last_stats.exp, pl->ob->stats.exp, CS_STAT_EXP64);
851     } else {
852     AddIfInt(pl->last_stats.exp, ( int )pl->ob->stats.exp, CS_STAT_EXP);
853     }
854     AddIfShort(pl->last_level, ( char )pl->ob->level, CS_STAT_LEVEL);
855     AddIfShort(pl->last_stats.wc, pl->ob->stats.wc, CS_STAT_WC);
856     AddIfShort(pl->last_stats.ac, pl->ob->stats.ac, CS_STAT_AC);
857     AddIfShort(pl->last_stats.dam, pl->ob->stats.dam, CS_STAT_DAM);
858     AddIfFloat(pl->last_speed, pl->ob->speed, CS_STAT_SPEED);
859     AddIfShort(pl->last_stats.food, pl->ob->stats.food, CS_STAT_FOOD);
860     AddIfFloat(pl->last_weapon_sp, pl->weapon_sp, CS_STAT_WEAP_SP);
861     AddIfInt(pl->last_weight_limit, (sint32)weight_limit[pl->ob->stats.Str], CS_STAT_WEIGHT_LIM);
862     flags=0;
863     if (pl->fire_on) flags |=SF_FIREON;
864     if (pl->run_on) flags |= SF_RUNON;
865    
866     AddIfShort(pl->last_flags, flags, CS_STAT_FLAGS);
867     if (pl->socket.sc_version<1025) {
868     AddIfShort(pl->last_resist[ATNR_PHYSICAL], pl->ob->resist[ATNR_PHYSICAL], CS_STAT_ARMOUR);
869     } else {
870     int i;
871    
872     for (i=0; i<NROFATTACKS; i++) {
873     /* Skip ones we won't send */
874     if (atnr_cs_stat[i]==-1) continue;
875     AddIfShort(pl->last_resist[i], pl->ob->resist[i], ( char )atnr_cs_stat[i]);
876     }
877     }
878     if (pl->socket.monitor_spells) {
879     AddIfInt(pl->last_path_attuned, pl->ob->path_attuned, CS_STAT_SPELL_ATTUNE);
880     AddIfInt(pl->last_path_repelled, pl->ob->path_repelled, CS_STAT_SPELL_REPEL);
881     AddIfInt(pl->last_path_denied, pl->ob->path_denied, CS_STAT_SPELL_DENY);
882     }
883     rangetostring(pl->ob, buf); /* we want use the new fire & run system in new client */
884     AddIfString(pl->socket.stats.range, buf, CS_STAT_RANGE);
885     set_title(pl->ob, buf);
886     AddIfString(pl->socket.stats.title, buf, CS_STAT_TITLE);
887    
888     /* Only send it away if we have some actual data */
889     if (sl.len>6) {
890     #ifdef ESRV_DEBUG
891     LOG(llevDebug,"Sending stats command, %d bytes long.\n", sl.len);
892     #endif
893     Send_With_Handling(&pl->socket, &sl);
894     }
895     free(sl.buf);
896     }
897    
898    
899     /**
900     * Tells the client that here is a player it should start using.
901     */
902     void esrv_new_player(player *pl, uint32 weight)
903     {
904     SockList sl;
905    
906     pl->last_weight = weight;
907    
908     sl.buf=malloc(MAXSOCKBUF);
909    
910     strcpy((char*)sl.buf,"player ");
911     sl.len=strlen((char*)sl.buf);
912     SockList_AddInt(&sl, pl->ob->count);
913     SockList_AddInt(&sl, weight);
914     SockList_AddInt(&sl, pl->ob->face->number);
915    
916     SockList_AddChar(&sl, ( char )strlen(pl->ob->name));
917     strcpy((char*)sl.buf+sl.len, pl->ob->name);
918     sl.len += strlen(pl->ob->name);
919    
920     Send_With_Handling(&pl->socket, &sl);
921     free(sl.buf);
922     SET_FLAG(pl->ob, FLAG_CLIENT_SENT);
923     }
924    
925    
926     /**
927     * Need to send an animation sequence to the client.
928     * We will send appropriate face commands to the client if we haven't
929     * sent them the face yet (this can become quite costly in terms of
930     * how much we are sending - on the other hand, this should only happen
931     * when the player logs in and picks stuff up.
932     */
933     void esrv_send_animation(NewSocket *ns, short anim_num)
934     {
935     SockList sl;
936     int i;
937    
938     /* Do some checking on the anim_num we got. Note that the animations
939     * are added in contigous order, so if the number is in the valid
940     * range, it must be a valid animation.
941     */
942     if (anim_num < 0 || anim_num > num_animations) {
943     LOG(llevError,"esrv_send_anim (%d) out of bounds??\n",anim_num);
944     return;
945     }
946    
947     sl.buf = malloc(MAXSOCKBUF);
948     strcpy((char*)sl.buf, "anim ");
949     sl.len=5;
950     SockList_AddShort(&sl, anim_num);
951     SockList_AddShort(&sl, 0); /* flags - not used right now */
952     /* Build up the list of faces. Also, send any information (ie, the
953     * the face itself) down to the client.
954     */
955     for (i=0; i<animations[anim_num].num_animations; i++) {
956     if (!(ns->faces_sent[animations[anim_num].faces[i]] & NS_FACESENT_FACE))
957     esrv_send_face(ns,animations[anim_num].faces[i],0);
958     SockList_AddShort(&sl, animations[anim_num].faces[i]); /* flags - not used right now */
959     }
960     Send_With_Handling(ns, &sl);
961     free(sl.buf);
962     ns->anims_sent[anim_num] = 1;
963     }
964    
965    
966     /******************************************************************************
967     *
968     * Start of map related commands.
969     *
970     ******************************************************************************/
971    
972     /**
973     * This adds face_num to a map cell at x,y. If the client doesn't have
974     * the face yet, we will also send it.
975     */
976     static void esrv_map_setbelow(NewSocket *ns, int x,int y,
977     short face_num, struct Map *newmap)
978     {
979     if(newmap->cells[x][y].count >= MAP_LAYERS) {
980     LOG(llevError,"Too many faces in map cell %d %d\n",x,y);
981     return;
982     abort();
983     }
984     newmap->cells[x][y].faces[newmap->cells[x][y].count] = face_num;
985     newmap->cells[x][y].count ++;
986     if (!(ns->faces_sent[face_num] & NS_FACESENT_FACE))
987     esrv_send_face(ns,face_num,0);
988     }
989    
990     struct LayerCell {
991     uint16 xy;
992     short face;
993     };
994    
995     struct MapLayer {
996     int count;
997     struct LayerCell lcells[MAP_CLIENT_X * MAP_CLIENT_Y];
998     };
999    
1000     /** Checkes if map cells have changed */
1001     static int mapcellchanged(NewSocket *ns,int i,int j, struct Map *newmap)
1002     {
1003     int k;
1004    
1005     if (ns->lastmap.cells[i][j].count != newmap->cells[i][j].count)
1006     return 1;
1007     for(k=0;k<newmap->cells[i][j].count;k++) {
1008     if (ns->lastmap.cells[i][j].faces[k] !=
1009     newmap->cells[i][j].faces[k]) {
1010     return 1;
1011     }
1012     }
1013     return 0;
1014     }
1015    
1016     /**
1017     * Basically, what this does is pack the data into layers.
1018     * cnum is the client number, cur is the the buffer we put all of
1019     * this data into. we return the end of the data. layers is
1020     * how many layers of data we should back.
1021     */
1022     static uint8 *compactlayer(NewSocket *ns, unsigned char *cur, int numlayers,
1023     struct Map *newmap)
1024     {
1025     int x,y,k;
1026     int face;
1027     unsigned char *fcur;
1028     struct MapLayer layers[MAP_LAYERS];
1029    
1030     for(k = 0;k<MAP_LAYERS;k++)
1031     layers[k].count = 0;
1032     fcur = cur;
1033     for(x=0;x<ns->mapx;x++) {
1034     for(y=0;y<ns->mapy;y++) {
1035     if (!mapcellchanged(ns,x,y,newmap))
1036     continue;
1037     if (newmap->cells[x][y].count == 0) {
1038     *cur = x*ns->mapy+y; /* mark empty space */
1039     cur++;
1040     continue;
1041     }
1042     for(k=0;k<newmap->cells[x][y].count;k++) {
1043     layers[k].lcells[layers[k].count].xy = x*ns->mapy+y;
1044     layers[k].lcells[layers[k].count].face =
1045     newmap->cells[x][y].faces[k];
1046     layers[k].count++;
1047     }
1048     }
1049     }
1050     /* If no data, return now. */
1051     if (fcur == cur && layers[0].count == 0)
1052     return cur;
1053     *cur = 255; /* mark end of explicitly cleared cells */
1054     cur++;
1055     /* First pack by layers. */
1056     for(k=0;k<numlayers;k++) {
1057     if (layers[k].count == 0)
1058     break; /* once a layer is entirely empty, no layer below it can
1059     have anything in it either */
1060     /* Pack by entries in thie layer */
1061     for(x=0;x<layers[k].count;) {
1062     fcur = cur;
1063     *cur = layers[k].lcells[x].face >> 8;
1064     cur++;
1065     *cur = layers[k].lcells[x].face & 0xFF;
1066     cur++;
1067     face = layers[k].lcells[x].face;
1068     /* Now, we back the redundant data into 1 byte xy pairings */
1069     for(y=x;y<layers[k].count;y++) {
1070     if (layers[k].lcells[y].face == face) {
1071     *cur = ( uint8 )layers[k].lcells[y].xy;
1072     cur++;
1073     layers[k].lcells[y].face = -1;
1074     }
1075     }
1076     *(cur-1) = *(cur-1) | 128; /* mark for end of xy's; 11*11 < 128 */
1077     /* forward over the now redundant data */
1078     while(x < layers[k].count &&
1079     layers[k].lcells[x].face == -1)
1080     x++;
1081     }
1082     *fcur = *fcur | 128; /* mark for end of faces at this layer */
1083     }
1084     return cur;
1085     }
1086    
1087     static void esrv_map_doneredraw(NewSocket *ns, struct Map *newmap)
1088     {
1089     static long frames,bytes,tbytes,tframes;
1090     uint8 *cur;
1091     SockList sl;
1092    
1093    
1094     sl.buf=malloc(MAXSOCKBUF);
1095     strcpy((char*)sl.buf,"map ");
1096     sl.len=strlen((char*)sl.buf);
1097    
1098     cur = compactlayer(ns,sl.buf+sl.len,MAP_LAYERS,newmap);
1099     sl.len=cur-sl.buf;
1100    
1101     /* LOG(llevDebug, "Sending map command.\n");*/
1102    
1103     if (sl.len>( int )strlen("map ") || ns->sent_scroll) {
1104     /* All of this is just accounting stuff */
1105     if (tframes>100) {
1106     tframes = tbytes = 0;
1107     }
1108     tframes++;
1109     frames++;
1110     tbytes += sl.len;
1111     bytes += sl.len;
1112     memcpy(&ns->lastmap,newmap,sizeof(struct Map));
1113     Send_With_Handling(ns, &sl);
1114     ns->sent_scroll = 0;
1115     }
1116     free(sl.buf);
1117     }
1118    
1119    
1120     /** Clears a map cell */
1121     static void map_clearcell(struct MapCell *cell, int face0, int face1, int face2, int count)
1122     {
1123     cell->count=count;
1124     cell->faces[0] = face0;
1125     cell->faces[1] = face1;
1126     cell->faces[2] = face2;
1127     }
1128    
1129     #define MAX_HEAD_POS MAX(MAX_CLIENT_X, MAX_CLIENT_Y)
1130     #define MAX_LAYERS 3
1131    
1132     /* Using a global really isn't a good approach, but saves the over head of
1133     * allocating and deallocating such a block of data each time run through,
1134     * and saves the space of allocating this in the socket object when we only
1135     * need it for this cycle. If the serve is ever threaded, this needs to be
1136     * re-examined.
1137     */
1138    
1139     static object *heads[MAX_HEAD_POS * MAX_HEAD_POS * MAX_LAYERS];
1140    
1141     /**
1142     * Returns true if any of the heads for this
1143     * space is set. Returns false if all are blank - this is used
1144     * for empty space checking.
1145     */
1146     static inline int have_head(int ax, int ay) {
1147    
1148     if (heads[(ay * MAX_HEAD_POS + ax) * MAX_LAYERS] ||
1149     heads[(ay * MAX_HEAD_POS + ax) * MAX_LAYERS + 1] ||
1150     heads[(ay * MAX_HEAD_POS + ax) * MAX_LAYERS + 2]) return 1;
1151     return 0;
1152     }
1153    
1154     /**
1155     * check_head is a bit simplistic version of update_space below.
1156     * basically, it only checks the that the head on space ax,ay at layer
1157     * needs to get sent - if so, it adds the data, sending the head
1158     * if needed, and returning 1. If this no data needs to get
1159     * sent, it returns zero.
1160     */
1161     static inline int check_head(SockList *sl, NewSocket *ns, int ax, int ay, int layer)
1162     {
1163     short face_num;
1164    
1165     if (heads[(ay * MAX_HEAD_POS + ax) * MAX_LAYERS + layer])
1166     face_num = heads[(ay * MAX_HEAD_POS + ax) * MAX_LAYERS + layer]->face->number;
1167     else
1168     face_num = 0;
1169    
1170     if (face_num != ns->lastmap.cells[ax][ay].faces[layer]) {
1171     SockList_AddShort(sl, face_num);
1172     if (face_num && !(ns->faces_sent[face_num] & NS_FACESENT_FACE))
1173     esrv_send_face(ns, face_num, 0);
1174     heads[(ay * MAX_HEAD_POS + ax) * MAX_LAYERS + layer] = NULL;
1175     ns->lastmap.cells[ax][ay].faces[layer] = face_num;
1176     return 1;
1177     }
1178    
1179     return 0; /* No change */
1180     }
1181    
1182     /**
1183     * Removes the need to replicate the same code for each layer.
1184     * this returns true if this space is now in fact different than
1185     * it was.
1186     * sl is the socklist this data is going into.
1187     * ns is the socket we are working on - all the info we care
1188     * about is in this socket structure, so now need not pass the
1189     * entire player object.
1190     * mx and my are map coordinate offsets for map mp
1191     * sx and sy are the offsets into the socket structure that
1192     * holds the old values.
1193     * layer is the layer to update, with 2 being the floor and 0 the
1194     * top layer (this matches what the GET_MAP_FACE and GET_MAP_FACE_OBJ)
1195     * take. Interesting to note that before this function, the map1 function
1196     * numbers the spaces differently - I think this was a leftover from
1197     * the map command, where the faces stack up. Sinces that is no longer
1198     * the case, it seems to make more sense to have these layer values
1199     * actually match.
1200     */
1201    
1202     static inline int update_space(SockList *sl, NewSocket *ns, mapstruct *mp, int mx, int my, int sx, int sy, int layer)
1203     {
1204     object *ob, *head;
1205     uint16 face_num;
1206     int bx, by,i;
1207    
1208     /* If there is a multipart object stored away, treat that as more important.
1209     * If not, then do the normal processing.
1210     */
1211    
1212     head = heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + layer];
1213    
1214     /* Check to see if this head is part of the set of objects
1215     * we would normally send for this space. If so, then
1216     * don't use the head value. We need to do the check
1217     * here and not when setting up the heads[] value for two reasons -
1218     * 1) the heads[] values will get used even if the space is not visible.
1219     * 2) its possible the head is not on the same map as a part, and I'd
1220     * rather not need to do the map translation overhead.
1221     * 3) We need to do some extra checking to make sure that we will
1222     * otherwise send the image as this layer, eg, either it matches
1223     * the head value, or is not multipart.
1224     */
1225     if (head && !head->more) {
1226     for (i=0; i<MAP_LAYERS; i++) {
1227     ob = GET_MAP_FACE_OBJ(mp, mx, my, i);
1228     if (!ob) continue;
1229    
1230     if (ob->head) ob=ob->head;
1231    
1232     if (ob == head) {
1233     heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + layer] = NULL;
1234     head = NULL;
1235     break;
1236     }
1237     }
1238     }
1239    
1240     ob = head;
1241     if (!ob) ob = GET_MAP_FACE_OBJ(mp, mx, my, layer);
1242    
1243     /* If there is no object for this space, or if the face for the object
1244     * is the blank face, set the face number to zero.
1245     * else if we have the stored head object for this space, that takes
1246     * precedence over the other object for this space.
1247     * otherwise, we do special head processing
1248     */
1249     if (!ob || ob->face == blank_face) face_num=0;
1250     else if (head){
1251     /* if this is a head that had previously been stored */
1252     face_num = ob->face->number;
1253     } else {
1254     /* if the faces for the different parts of a multipart object
1255     * are the same, we only want to send the bottom right most
1256     * portion of the object. That info is in the tail_.. values
1257     * of the head. Note that for the head itself, ob->head will
1258     * be null, so we only do this block if we are working on
1259     * a tail piece.
1260     */
1261    
1262     /* tail_x and tail_y will only be set in the head object. If
1263     * this is the head object and these are set, we proceed
1264     * with logic to only send bottom right. Similarly, if
1265     * this is one of the more parts but the head has those values
1266     * set, we want to do the processing. There can be cases where
1267     * the head is not visible but one of its parts is, so we just
1268     * can always expect that ob->arch->tail_x will be true for all
1269     * object we may want to display.
1270     */
1271     if ((ob->arch->tail_x || ob->arch->tail_y) ||
1272     (ob->head && (ob->head->arch->tail_x || ob->head->arch->tail_y))) {
1273    
1274     if (ob->head) head = ob->head;
1275     else head = ob;
1276    
1277     /* Basically figure out where the offset is from where we are right
1278     * now. the ob->arch->clone.{x,y} values hold the offset that this current
1279     * piece is from the head, and the tail is where the tail is from the
1280     * head. Note that bx and by will equal sx and sy if we are already working
1281     * on the bottom right corner. If ob is the head, the clone values
1282     * will be zero, so the right thing will still happen.
1283     */
1284     bx = sx + head->arch->tail_x - ob->arch->clone.x;
1285     by = sy + head->arch->tail_y - ob->arch->clone.y;
1286    
1287     /* I don't think this can ever happen, but better to check for it just
1288     * in case.
1289     */
1290     if (bx < sx || by < sy) {
1291     LOG(llevError,"update_space: bx (%d) or by (%d) is less than sx (%d) or sy (%d)\n",
1292     bx, by, sx, sy);
1293     face_num = 0;
1294     }
1295     /* single part object, multipart object with non merged faces,
1296     * of multipart object already at lower right.
1297     */
1298     else if (bx == sx && by == sy) {
1299     face_num = ob->face->number;
1300    
1301     /* if this face matches one stored away, clear that one away.
1302     * this code relies on the fact that the map1 commands
1303     * goes from 2 down to 0.
1304     */
1305     for (i=0; i<MAP_LAYERS; i++)
1306     if (heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + i] &&
1307     heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + i]->face->number == face_num)
1308     heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + i] = NULL;
1309     }
1310     else {
1311     /* If this head is stored away, clear it - otherwise,
1312     * there can be cases where a object is on multiple layers -
1313     * we only want to send it once.
1314     */
1315     face_num = head->face->number;
1316     for (i=0; i<MAP_LAYERS; i++)
1317     if (heads[(by * MAX_HEAD_POS + bx) * MAX_LAYERS + i] &&
1318     heads[(by * MAX_HEAD_POS + bx) * MAX_LAYERS + i]->face->number == face_num)
1319     heads[(by * MAX_HEAD_POS + bx) * MAX_LAYERS + i] = NULL;
1320    
1321     /* First, try to put the new head on the same layer. If that is used up,
1322     * then find another layer.
1323     */
1324     if (heads[(by * MAX_HEAD_POS + bx) * MAX_LAYERS + layer] == NULL) {
1325     heads[(by * MAX_HEAD_POS + bx) * MAX_LAYERS + layer] = head;
1326     } else for (i=0; i<MAX_LAYERS; i++) {
1327     if (heads[(by * MAX_HEAD_POS + bx) * MAX_LAYERS + i] == NULL ||
1328     heads[(by * MAX_HEAD_POS + bx) * MAX_LAYERS + i] == head) {
1329     heads[(by * MAX_HEAD_POS + bx) * MAX_LAYERS + i] = head;
1330     }
1331     }
1332     face_num = 0; /* Don't send this object - we'll send the head later */
1333     }
1334     } else {
1335     /* In this case, we are already at the lower right or single part object,
1336     * so nothing special
1337     */
1338     face_num = ob->face->number;
1339    
1340     /* clear out any head entries that have the same face as this one */
1341     for (bx=0; bx<layer; bx++)
1342     if (heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + bx] &&
1343     heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + bx]->face->number == face_num)
1344     heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + bx] = NULL;
1345     }
1346     } /* else not already head object or blank face */
1347    
1348     /* This is a real hack. Basically, if we have nothing to send for this layer,
1349     * but there is a head on the next layer, send that instead.
1350     * Without this, what happens is you can get the case where the player stands
1351     * on the same space as the head. However, if you have overlapping big objects
1352     * of the same type, what happens then is it doesn't think it needs to send
1353     * This tends to make stacking also work/look better.
1354     */
1355     if (!face_num && layer > 0 && heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + layer -1]) {
1356     face_num = heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + layer -1]->face->number;
1357     heads[(sy * MAX_HEAD_POS + sx) * MAX_LAYERS + layer -1] = NULL;
1358     }
1359    
1360     /* Another hack - because of heads and whatnot, this face may match one
1361     * we already sent for a lower layer. In that case, don't send
1362     * this one.
1363     */
1364     if (face_num && layer+1<MAP_LAYERS && ns->lastmap.cells[sx][sy].faces[layer+1] == face_num) {
1365     face_num = 0;
1366     }
1367    
1368     /* We've gotten what face we want to use for the object. Now see if
1369     * if it has changed since we last sent it to the client.
1370     */
1371     if (ns->lastmap.cells[sx][sy].faces[layer] != face_num) {
1372     ns->lastmap.cells[sx][sy].faces[layer] = face_num;
1373     if (!(ns->faces_sent[face_num] & NS_FACESENT_FACE))
1374     esrv_send_face(ns, face_num, 0);
1375     SockList_AddShort(sl, face_num);
1376     return 1;
1377     }
1378     /* Nothing changed */
1379     return 0;
1380     }
1381    
1382     /**
1383     * This function is mainly a copy of update_space,
1384     * except it handles update of the smoothing updates,
1385     * not the face updates.
1386     * Removes the need to replicate the same code for each layer.
1387     * this returns true if this smooth is now in fact different
1388     * than it was.
1389     * sl is the socklist this data is going into.
1390     * ns is the socket we are working on - all the info we care
1391     * about is in this socket structure, so know need to pass the
1392     * entire player object.
1393     * mx and my are map coordinate offsets for map mp
1394     * sx and sy are the offsets into the socket structure that
1395     * holds the old values.
1396     * layer is the layer to update, with 2 being the floor and 0 the
1397     * top layer (this matches what the GET_MAP_FACE and GET_MAP_FACE_OBJ
1398     * take.
1399     */
1400    
1401     static inline int update_smooth(SockList *sl, NewSocket *ns, mapstruct *mp, int mx, int my, int sx, int sy, int layer)
1402     {
1403     object *ob;
1404     int smoothlevel; /* old face_num;*/
1405    
1406     ob = GET_MAP_FACE_OBJ(mp, mx, my, layer);
1407    
1408     /* If there is no object for this space, or if the face for the object
1409     * is the blank face, set the smoothlevel to zero.
1410     */
1411     if (!ob || ob->face == blank_face || MAP_NOSMOOTH(mp)) smoothlevel=0;
1412     else {
1413     smoothlevel = ob->smoothlevel;
1414     if (smoothlevel && !(ns->faces_sent[ob->face->number] & NS_FACESENT_SMOOTH))
1415     SendSmooth(ns, ob->face->number);
1416     } /* else not already head object or blank face */
1417    
1418     /* We've gotten what face we want to use for the object. Now see if
1419     * if it has changed since we last sent it to the client.
1420     */
1421     if (smoothlevel>255)
1422     smoothlevel=255;
1423     else if (smoothlevel<0)
1424     smoothlevel=0;
1425     if (ns->lastmap.cells[sx][sy].smooth[layer] != smoothlevel) {
1426     ns->lastmap.cells[sx][sy].smooth[layer] = smoothlevel;
1427     SockList_AddChar(sl, (uint8) (smoothlevel&0xFF));
1428     return 1;
1429     }
1430     /* Nothing changed */
1431     return 0;
1432     }
1433    
1434     /**
1435     * Returns the size of a data for a map square as returned by
1436     * mapextended. There are CLIENTMAPX*CLIENTMAPY*LAYERS entries
1437     * available.
1438     */
1439     int getExtendedMapInfoSize(NewSocket* ns){
1440     int result=0;
1441     if (ns->ext_mapinfos){
1442     if (ns->EMI_smooth)
1443     result+=1; /*One byte for smoothlevel*/
1444     }
1445     return result;
1446     }
1447     /**
1448     * This function uses the new map1 protocol command to send the map
1449     * to the client. It is necessary because the old map command supports
1450     * a maximum map size of 15x15.
1451     * This function is much simpler than the old one. This is because
1452     * the old function optimized to send as few face identifiers as possible,
1453     * at the expense of sending more coordinate location (coordinates were
1454     * only 1 byte, faces 2 bytes, so this was a worthwhile savings). Since
1455     * we need 2 bytes for coordinates and 2 bytes for faces, such a trade off
1456     * maps no sense. Instead, we actually really only use 12 bits for coordinates,
1457     * and use the other 4 bits for other informatiion. For full documentation
1458     * of what we send, see the doc/Protocol file.
1459     * I will describe internally what we do:
1460     * the socket->lastmap shows how the map last looked when sent to the client.
1461     * in the lastmap structure, there is a cells array, which is set to the
1462     * maximum viewable size (As set in config.h).
1463     * in the cells, there are faces and a count value.
1464     * we use the count value to hold the darkness value. If -1, then this space
1465     * is not viewable.
1466     * we use faces[0] faces[1] faces[2] to hold what the three layers
1467     * look like.
1468     */
1469     void draw_client_map1(object *pl)
1470     {
1471     int x,y,ax, ay, d, startlen, max_x, max_y, oldlen;
1472     sint16 nx, ny;
1473     int estartlen, eoldlen;
1474     SockList sl;
1475     SockList esl; /*For extended Map info*/
1476     uint16 mask,emask;
1477     uint8 eentrysize;
1478     uint16 ewhatstart,ewhatflag;
1479     uint8 extendedinfos;
1480     mapstruct *m;
1481    
1482 root 1.2 check_map_change (pl->contr);
1483    
1484 root 1.1 sl.buf=malloc(MAXSOCKBUF);
1485     if (pl->contr->socket.mapmode == Map1Cmd)
1486     strcpy((char*)sl.buf,"map1 ");
1487     else
1488     strcpy((char*)sl.buf,"map1a ");
1489     sl.len=strlen((char*)sl.buf);
1490     startlen = sl.len;
1491     /*Extendedmapinfo structure initialisation*/
1492     if (pl->contr->socket.ext_mapinfos){
1493     esl.buf=malloc(MAXSOCKBUF);
1494     strcpy((char*)esl.buf,"mapextended ");
1495     esl.len=strlen((char*)esl.buf);
1496     extendedinfos=EMI_NOREDRAW;
1497     if (pl->contr->socket.EMI_smooth)
1498     extendedinfos|=EMI_SMOOTH;
1499     ewhatstart=esl.len;
1500     ewhatflag=extendedinfos; /*The EMI_NOREDRAW bit
1501     could need to be taken away*/
1502     SockList_AddChar(&esl, extendedinfos);
1503     eentrysize=getExtendedMapInfoSize(&(pl->contr->socket));
1504     SockList_AddChar(&esl, eentrysize);
1505     estartlen = esl.len;
1506     } else {
1507     /* suppress compiler warnings */
1508     ewhatstart = 0;
1509     ewhatflag = 0;
1510     estartlen = 0;
1511     }
1512     /* Init data to zero */
1513     memset(heads, 0, sizeof(object *) * MAX_HEAD_POS * MAX_HEAD_POS * MAX_LAYERS);
1514    
1515     /* x,y are the real map locations. ax, ay are viewport relative
1516     * locations.
1517     */
1518     ay=0;
1519    
1520     /* We could do this logic as conditionals in the if statement,
1521     * but that started to get a bit messy to look at.
1522     */
1523     max_x = pl->x+(pl->contr->socket.mapx+1)/2;
1524     max_y = pl->y+(pl->contr->socket.mapy+1)/2;
1525     if (pl->contr->socket.mapmode == Map1aCmd) {
1526     max_x += MAX_HEAD_OFFSET;
1527     max_y += MAX_HEAD_OFFSET;
1528     }
1529    
1530     for(y=pl->y-pl->contr->socket.mapy/2; y<max_y; y++,ay++) {
1531     ax=0;
1532     for(x=pl->x-pl->contr->socket.mapx/2;x<max_x;x++,ax++) {
1533    
1534     mask = (ax & 0x3f) << 10 | (ay & 0x3f) << 4;
1535     emask = (ax & 0x3f) << 10 | (ay & 0x3f) << 4;
1536    
1537     /* If this space is out of the normal viewable area, we only check
1538     * the heads value ax or ay will only be greater than what
1539     * the client wants if using the map1a command - this is because
1540     * if the map1a command is not used, max_x and max_y will be
1541     * set to lower values.
1542     */
1543     if (ax >= pl->contr->socket.mapx || ay >= pl->contr->socket.mapy) {
1544     int i, got_one;
1545    
1546     oldlen = sl.len;
1547    
1548    
1549     SockList_AddShort(&sl, mask);
1550    
1551     if (check_head(&sl, &pl->contr->socket, ax, ay, 2))
1552     mask |= 0x4;
1553     if (check_head(&sl, &pl->contr->socket, ax, ay, 1))
1554     mask |= 0x2;
1555     if (check_head(&sl, &pl->contr->socket, ax, ay, 0))
1556     mask |= 0x1;
1557    
1558     /* If all we are doing is sending 0 (blank) faces, we don't
1559     * actually need to send that - just the coordinates
1560     * with no faces tells the client to blank out the
1561     * space.
1562     */
1563     got_one=0;
1564     for (i=oldlen+2; i<sl.len; i++) {
1565     if (sl.buf[i]) got_one=1;
1566     }
1567    
1568     if (got_one && (mask & 0xf)) {
1569     sl.buf[oldlen+1] = mask & 0xff;
1570     } else { /*either all faces blank, either no face at all*/
1571     if (mask & 0xf) /*at least 1 face, we know it's blank, only send coordinates*/
1572     sl.len = oldlen + 2;
1573     else
1574     sl.len = oldlen;
1575     }
1576     /*What concerns extendinfos, nothing to be done for now
1577     * (perhaps effects layer later)
1578     */
1579     continue; /* don't do processing below */
1580     }
1581    
1582     d = pl->contr->blocked_los[ax][ay];
1583    
1584     /* If the coordinates are not valid, or it is too dark to see,
1585     * we tell the client as such
1586     */
1587     nx=x;
1588     ny=y;
1589     m = get_map_from_coord(pl->map, &nx, &ny);
1590     if (!m) {
1591     /* space is out of map. Update space and clear values
1592     * if this hasn't already been done. If the space is out
1593     * of the map, it shouldn't have a head
1594     */
1595     if (pl->contr->socket.lastmap.cells[ax][ay].count != -1) {
1596     SockList_AddShort(&sl, mask);
1597     map_clearcell(&pl->contr->socket.lastmap.cells[ax][ay],0,0,0,-1);
1598     }
1599     } else if (d>3) {
1600     int need_send=0, count;
1601     /* This block deals with spaces that are not visible for whatever
1602     * reason. Still may need to send the head for this space.
1603     */
1604    
1605     oldlen = sl.len;
1606     #if 0
1607     /* First thing we do is blank out this space (clear it)
1608     * if not already done. If the client is using darkness, and
1609     * this space is at the edge, we also include the darkness.
1610     */
1611     if (d==4) {
1612     if (pl->contr->socket.darkness && pl->contr->socket.lastmap.cells[ax][ay].count != d) {
1613     mask |= 8;
1614     SockList_AddShort(&sl, mask);
1615     SockList_AddChar(&sl, 0);
1616     }
1617     count = d;
1618     } else
1619     #endif
1620     {
1621     SockList_AddShort(&sl, mask);
1622     if (pl->contr->socket.lastmap.cells[ax][ay].count != -1) need_send=1;
1623     count = -1;
1624     }
1625    
1626     if (pl->contr->socket.mapmode == Map1aCmd && have_head(ax, ay)) {
1627     /* Now check to see if any heads need to be sent */
1628    
1629     if (check_head(&sl, &pl->contr->socket, ax, ay, 2))
1630     mask |= 0x4;
1631     if (check_head(&sl, &pl->contr->socket, ax, ay, 1))
1632     mask |= 0x2;
1633     if (check_head(&sl, &pl->contr->socket, ax, ay, 0))
1634     mask |= 0x1;
1635     pl->contr->socket.lastmap.cells[ax][ay].count = count;
1636    
1637     } else {
1638     struct MapCell *cell = &pl->contr->socket.lastmap.cells[ax][ay];
1639     /* properly clear a previously sent big face */
1640     if(cell->faces[0] != 0
1641     || cell->faces[1] != 0
1642     || cell->faces[2] != 0)
1643     need_send = 1;
1644     map_clearcell(&pl->contr->socket.lastmap.cells[ax][ay], 0, 0, 0, count);
1645     }
1646    
1647     if ((mask & 0xf) || need_send) {
1648     sl.buf[oldlen+1] = mask & 0xff;
1649     } else {
1650     sl.len = oldlen;
1651     }
1652     } else {
1653     /* In this block, the space is visible or there are head objects
1654     * we need to send.
1655     */
1656    
1657     /* Rather than try to figure out what everything that we might
1658     * need to send is, then form the packet after that,
1659     * we presume that we will in fact form a packet, and update
1660     * the bits by what we do actually send. If we send nothing,
1661     * we just back out sl.len to the old value, and no harm
1662     * is done.
1663     * I think this is simpler than doing a bunch of checks to see
1664     * what if anything we need to send, setting the bits, then
1665     * doing those checks again to add the real data.
1666     */
1667     oldlen = sl.len;
1668     mask = (ax & 0x3f) << 10 | (ay & 0x3f) << 4;
1669     eoldlen = esl.len;
1670     emask = (ax & 0x3f) << 10 | (ay & 0x3f) << 4;
1671     SockList_AddShort(&sl, mask);
1672    
1673     if (pl->contr->socket.ext_mapinfos)
1674     SockList_AddShort(&esl, emask);
1675    
1676     /* Darkness changed */
1677     if (pl->contr->socket.lastmap.cells[ax][ay].count != d && pl->contr->socket.darkness) {
1678     pl->contr->socket.lastmap.cells[ax][ay].count = d;
1679     mask |= 0x8; /* darkness bit */
1680    
1681     /* Protocol defines 255 full bright, 0 full dark.
1682     * We currently don't have that many darkness ranges,
1683     * so we current what limited values we do have.
1684     */
1685     if (d==0) SockList_AddChar(&sl, 255);
1686     else if (d==1) SockList_AddChar(&sl, 191);
1687     else if (d==2) SockList_AddChar(&sl, 127);
1688     else if (d==3) SockList_AddChar(&sl, 63);
1689     }
1690     else {
1691     /* need to reset from -1 so that if it does become blocked again,
1692     * the code that deals with that can detect that it needs to tell
1693     * the client that this space is now blocked.
1694     */
1695     pl->contr->socket.lastmap.cells[ax][ay].count = d;
1696     }
1697    
1698     /* Floor face */
1699     if (update_space(&sl, &pl->contr->socket, m, nx, ny, ax, ay, 2))
1700     mask |= 0x4;
1701    
1702     if (pl->contr->socket.EMI_smooth)
1703     if (update_smooth(&esl, &pl->contr->socket, m, nx, ny, ax, ay, 2)){
1704     emask |= 0x4;
1705     }
1706    
1707     /* Middle face */
1708     if (update_space(&sl, &pl->contr->socket, m, nx, ny, ax, ay, 1))
1709     mask |= 0x2;
1710    
1711     if (pl->contr->socket.EMI_smooth)
1712     if (update_smooth(&esl, &pl->contr->socket, m, nx, ny, ax, ay, 1)){
1713     emask |= 0x2;
1714     }
1715    
1716    
1717     if(nx == pl->x && ny == pl->y && pl->invisible & (pl->invisible < 50 ? 4 : 1)) {
1718     if (pl->contr->socket.lastmap.cells[ax][ay].faces[0] != pl->face->number) {
1719     pl->contr->socket.lastmap.cells[ax][ay].faces[0] = pl->face->number;
1720     mask |= 0x1;
1721     if (!(pl->contr->socket.faces_sent[pl->face->number] &NS_FACESENT_FACE))
1722     esrv_send_face(&pl->contr->socket, pl->face->number, 0);
1723     SockList_AddShort(&sl, pl->face->number);
1724     }
1725     }
1726     /* Top face */
1727     else {
1728     if (update_space(&sl, &pl->contr->socket, m, nx, ny, ax, ay, 0))
1729     mask |= 0x1;
1730     if (pl->contr->socket.EMI_smooth)
1731     if (update_smooth(&esl, &pl->contr->socket, m, nx, ny, ax, ay, 0)){
1732     emask |= 0x1;
1733     }
1734     }
1735     /* Check to see if we are in fact sending anything for this
1736     * space by checking the mask. If so, update the mask.
1737     * if not, reset the len to that from before adding the mask
1738     * value, so we don't send those bits.
1739     */
1740     if (mask & 0xf) {
1741     sl.buf[oldlen+1] = mask & 0xff;
1742     } else {
1743     sl.len = oldlen;
1744     }
1745     if (emask & 0xf) {
1746     esl.buf[eoldlen+1] = emask & 0xff;
1747     } else {
1748     esl.len = eoldlen;
1749     }
1750     } /* else this is a viewable space */
1751     } /* for x loop */
1752     } /* for y loop */
1753    
1754     /* Verify that we in fact do need to send this */
1755     if (pl->contr->socket.ext_mapinfos){
1756     if (!(sl.len>startlen || pl->contr->socket.sent_scroll)){
1757     /* No map data will follow, so don't say the client
1758     * it doesn't need draw!
1759     */
1760     ewhatflag&=(~EMI_NOREDRAW);
1761     esl.buf[ewhatstart+1] = ewhatflag & 0xff;
1762     }
1763     if (esl.len>estartlen) {
1764     Send_With_Handling(&pl->contr->socket, &esl);
1765     }
1766     free(esl.buf);
1767     }
1768     if (sl.len>startlen || pl->contr->socket.sent_scroll) {
1769     Send_With_Handling(&pl->contr->socket, &sl);
1770     pl->contr->socket.sent_scroll = 0;
1771     }
1772     free(sl.buf);
1773     }
1774    
1775     /**
1776     * Draws client map.
1777     */
1778     void draw_client_map(object *pl)
1779     {
1780     int i,j;
1781     sint16 ax, ay, nx, ny;/* ax and ay goes from 0 to max-size of arrays */
1782     New_Face *face,*floor;
1783     New_Face *floor2;
1784     int d, mflags;
1785     struct Map newmap;
1786 root 1.2 mapstruct *m, *pm;
1787 root 1.1
1788     if (pl->type != PLAYER) {
1789     LOG(llevError,"draw_client_map called with non player/non eric-server\n");
1790     return;
1791     }
1792    
1793 root 1.2 if (pl->contr->transport) {
1794     pm = pl->contr->transport->map;
1795     }
1796     else
1797     pm = pl->map;
1798    
1799     /* If player is just joining the game, he isn't here yet, so the map
1800 root 1.1 * can get swapped out. If so, don't try to send them a map. All will
1801     * be OK once they really log in.
1802     */
1803 root 1.2 if (pm==NULL || pm->in_memory!=MAP_IN_MEMORY) return;
1804 root 1.1
1805     memset(&newmap, 0, sizeof(struct Map));
1806    
1807     for(j = (pl->y - pl->contr->socket.mapy/2) ; j < (pl->y + (pl->contr->socket.mapy+1)/2); j++) {
1808     for(i = (pl->x - pl->contr->socket.mapx/2) ; i < (pl->x + (pl->contr->socket.mapx+1)/2); i++) {
1809     ax=i;
1810     ay=j;
1811 root 1.2 m = pm;
1812 root 1.1 mflags = get_map_flags(m, &m, ax, ay, &ax, &ay);
1813     if (mflags & P_OUT_OF_MAP)
1814     continue;
1815     if (mflags & P_NEED_UPDATE)
1816     update_position(m, ax, ay);
1817     /* If a map is visible to the player, we don't want to swap it out
1818     * just to reload it. This should really call something like
1819     * swap_map, but this is much more efficient and 'good enough'
1820     */
1821     if (mflags & P_NEW_MAP)
1822     m->timeout = 50;
1823     }
1824     }
1825     /* do LOS after calls to update_position */
1826     if(pl->contr->do_los) {
1827     update_los(pl);
1828     pl->contr->do_los = 0;
1829     }
1830    
1831     if (pl->contr->socket.mapmode == Map1Cmd || pl->contr->socket.mapmode == Map1aCmd) {
1832     /* Big maps need a different drawing mechanism to work */
1833     draw_client_map1(pl);
1834     return;
1835     }
1836    
1837     if(pl->invisible & (pl->invisible < 50 ? 4 : 1)) {
1838     esrv_map_setbelow(&pl->contr->socket,pl->contr->socket.mapx/2,
1839     pl->contr->socket.mapy/2,pl->face->number,&newmap);
1840     }
1841    
1842     /* j and i are the y and x coordinates of the real map (which is
1843     * basically some number of spaces around the player)
1844     * ax and ay are values from within the viewport (ie, 0, 0 is upper
1845     * left corner) and are thus disconnected from the map values.
1846     * Subtract 1 from the max values so that we properly handle cases where
1847     * player has specified an even map. Otherwise, we try to send them too
1848     * much, ie, if mapx is 10, we would try to send from -5 to 5, which is actually
1849     * 11 spaces. Now, we would send from -5 to 4, which is properly. If mapx is
1850     * odd, this still works fine.
1851     */
1852     ay=0;
1853     for(j=pl->y-pl->contr->socket.mapy/2; j<=pl->y+(pl->contr->socket.mapy-1)/2;j++, ay++) {
1854     ax=0;
1855     for(i=pl->x-pl->contr->socket.mapx/2;i<=pl->x+(pl->contr->socket.mapx-1)/2;i++, ax++) {
1856    
1857     d = pl->contr->blocked_los[ax][ay];
1858     /* note the out_of_map and d>3 checks are both within the same
1859     * negation check.
1860     */
1861     nx = i;
1862     ny = j;
1863 root 1.2 m = get_map_from_coord(pm, &nx, &ny);
1864 root 1.1 if (m && d<4) {
1865     face = GET_MAP_FACE(m, nx, ny,0);
1866     floor2 = GET_MAP_FACE(m, nx, ny,1);
1867     floor = GET_MAP_FACE(m, nx, ny,2);
1868    
1869     /* If all is blank, send a blank face. */
1870     if ((!face || face == blank_face) &&
1871     (!floor2 || floor2 == blank_face) &&
1872     (!floor || floor == blank_face)) {
1873     esrv_map_setbelow(&pl->contr->socket,ax,ay,
1874     blank_face->number,&newmap);
1875     } else { /* actually have something interesting */
1876     /* send the darkness mask, if any. */
1877     if (d && pl->contr->socket.darkness)
1878     esrv_map_setbelow(&pl->contr->socket,ax,ay,
1879     dark_faces[d-1]->number,&newmap);
1880    
1881     if (face && face != blank_face)
1882     esrv_map_setbelow(&pl->contr->socket,ax,ay,
1883     face->number,&newmap);
1884     if (floor2 && floor2 != blank_face)
1885     esrv_map_setbelow(&pl->contr->socket,ax,ay,
1886     floor2->number,&newmap);
1887     if (floor && floor != blank_face)
1888     esrv_map_setbelow(&pl->contr->socket,ax,ay,
1889     floor->number,&newmap);
1890     }
1891     } /* Is a valid space */
1892     }
1893     }
1894     esrv_map_doneredraw(&pl->contr->socket, &newmap);
1895     }
1896    
1897    
1898     void esrv_map_scroll(NewSocket *ns,int dx,int dy)
1899     {
1900     struct Map newmap;
1901     int x,y, mx, my;
1902     char buf[MAXSOCKBUF];
1903    
1904     sprintf(buf,"map_scroll %d %d", dx, dy);
1905     Write_String_To_Socket(ns, buf, strlen(buf));
1906    
1907     /* If we are using the Map1aCmd, we may in fact send
1908     * head information that is outside the viewable map.
1909     * So set the mx,my to the max value we want to
1910     * look for. Removed code to do so - it caused extra
1911     * complexities for the client, and probably doesn't make
1912     * that much difference in bandwidth.
1913     */
1914     mx = ns->mapx;
1915     my = ns->mapy;
1916    
1917     if (ns->mapmode == Map1aCmd) {
1918     mx += MAX_HEAD_OFFSET;
1919     my += MAX_HEAD_OFFSET;
1920     }
1921    
1922     /* the x and y here are coordinates for the new map, i.e. if we moved
1923     * (dx,dy), newmap[x][y] = oldmap[x-dx][y-dy]. For this reason,
1924     * if the destination x or y coordinate is outside the viewable
1925     * area, we clear the values - otherwise, the old values
1926     * are preserved, and the check_head thinks it needs to clear them.
1927     */
1928     for(x=0; x<mx; x++) {
1929     for(y=0; y<my; y++) {
1930     if(x >= ns->mapx || y >= ns->mapy) {
1931     /* clear cells outside the viewable area */
1932     memset(&newmap.cells[x][y], 0, sizeof(struct MapCell));
1933     }
1934     else if ((x+dx) < 0 || (x+dx) >= ns->mapx || (y+dy) < 0 || (y + dy) >= ns->mapy) {
1935     /* clear newly visible tiles within the viewable area */
1936     memset(&(newmap.cells[x][y]), 0, sizeof(struct MapCell));
1937     }
1938     else {
1939     memcpy(&(newmap.cells[x][y]),
1940     &(ns->lastmap.cells[x+dx][y+dy]),sizeof(struct MapCell));
1941     }
1942     }
1943     }
1944    
1945     memcpy(&(ns->lastmap), &newmap,sizeof(struct Map));
1946    
1947     /* Make sure that the next "map1" command will be sent (even if it is
1948     * empty).
1949     */
1950     ns->sent_scroll = 1;
1951     }
1952    
1953     /*****************************************************************************/
1954     /* GROS: The following one is used to allow a plugin to send a generic cmd to*/
1955     /* a player. Of course, the client need to know the command to be able to */
1956     /* manage it ! */
1957     /*****************************************************************************/
1958     void send_plugin_custom_message(object *pl, char *buf)
1959     {
1960     cs_write_string(&pl->contr->socket,buf,strlen(buf));
1961     }
1962    
1963     /**
1964     * This sends the skill number to name mapping. We ignore
1965     * the params - we always send the same info no matter what.
1966     */
1967     void send_skill_info(NewSocket *ns, char *params)
1968     {
1969     SockList sl;
1970     int i;
1971    
1972     sl.buf = malloc(MAXSOCKBUF);
1973 root 1.2 strcpy((char*)sl.buf,"replyinfo skill_info\n");
1974 root 1.1 for (i=1; i< NUM_SKILLS; i++) {
1975 root 1.2 sprintf((char*)sl.buf + strlen((char*)sl.buf), "%d:%s\n", i + CS_STAT_SKILLINFO,
1976 root 1.1 skill_names[i]);
1977     }
1978 root 1.2 sl.len = strlen((char*)sl.buf);
1979 root 1.1 if (sl.len > MAXSOCKBUF) {
1980     LOG(llevError,"Buffer overflow in send_skill_info!\n");
1981     fatal(0);
1982     }
1983     Send_With_Handling(ns, &sl);
1984     free(sl.buf);
1985     }
1986    
1987     /**
1988     * This sends the spell path to name mapping. We ignore
1989     * the params - we always send the same info no matter what.
1990     */
1991     void send_spell_paths (NewSocket *ns, char *params) {
1992     SockList sl;
1993     int i;
1994    
1995     sl.buf = malloc(MAXSOCKBUF);
1996 root 1.2 strcpy((char*)sl.buf,"replyinfo spell_paths\n");
1997 root 1.1 for(i=0; i<NRSPELLPATHS; i++)
1998 root 1.2 sprintf((char*)sl.buf + strlen((char*)sl.buf), "%d:%s\n", 1<<i, spellpathnames[i]);
1999     sl.len = strlen((char*)sl.buf);
2000 root 1.1 if (sl.len > MAXSOCKBUF) {
2001     LOG(llevError,"Buffer overflow in send_spell_paths!\n");
2002     fatal(0);
2003     }
2004     Send_With_Handling(ns, &sl);
2005     free(sl.buf);
2006     }
2007    
2008     /**
2009     * This looks for any spells the player may have that have changed their stats.
2010     * it then sends an updspell packet for each spell that has changed in this way
2011     */
2012     void esrv_update_spells(player *pl) {
2013     SockList sl;
2014     int flags=0;
2015     object *spell;
2016     if (!pl->socket.monitor_spells) return;
2017     for (spell=pl->ob->inv; spell!=NULL; spell=spell->below) {
2018     if (spell->type == SPELL) {
2019     /* check if we need to update it*/
2020     if (spell->last_sp != SP_level_spellpoint_cost(pl->ob, spell, SPELL_MANA)) {
2021     spell->last_sp = SP_level_spellpoint_cost(pl->ob, spell, SPELL_MANA);
2022     flags |= UPD_SP_MANA;
2023     }
2024     if (spell->last_grace != SP_level_spellpoint_cost(pl->ob, spell, SPELL_GRACE)) {
2025     spell->last_grace = SP_level_spellpoint_cost(pl->ob, spell, SPELL_GRACE);
2026     flags |= UPD_SP_GRACE;
2027     }
2028     if (spell->last_eat != spell->stats.dam+SP_level_dam_adjust(pl->ob, spell)) {
2029     spell->last_eat = spell->stats.dam+SP_level_dam_adjust(pl->ob, spell);
2030     flags |= UPD_SP_DAMAGE;
2031     }
2032     if (flags !=0) {
2033     sl.buf = malloc(MAXSOCKBUF);
2034 root 1.2 strcpy((char*)sl.buf,"updspell ");
2035 root 1.1 sl.len=strlen((char*)sl.buf);
2036     SockList_AddChar(&sl, flags);
2037     SockList_AddInt(&sl, spell->count);
2038     if (flags & UPD_SP_MANA) SockList_AddShort(&sl, spell->last_sp);
2039     if (flags & UPD_SP_GRACE) SockList_AddShort(&sl, spell->last_grace);
2040     if (flags & UPD_SP_DAMAGE) SockList_AddShort(&sl, spell->last_eat);
2041     flags = 0;
2042     Send_With_Handling(&pl->socket, &sl);
2043     free(sl.buf);
2044     }
2045     }
2046     }
2047     }
2048    
2049     void esrv_remove_spell(player *pl, object *spell) {
2050     SockList sl;
2051    
2052     if (!pl->socket.monitor_spells) return;
2053     if (!pl || !spell || spell->env != pl->ob) {
2054     LOG(llevError, "Invalid call to esrv_remove_spell");
2055     return;
2056     }
2057     sl.buf = malloc(MAXSOCKBUF);
2058 root 1.2 strcpy((char*)sl.buf,"delspell ");
2059 root 1.1 sl.len=strlen((char*)sl.buf);
2060     SockList_AddInt(&sl, spell->count);
2061     Send_With_Handling(&pl->socket, &sl);
2062     free(sl.buf);
2063     }
2064    
2065     /* appends the spell *spell to the Socklist we will send the data to. */
2066     static void append_spell (player *pl, SockList *sl, object *spell) {
2067 root 1.2 int len, i, skill=0;
2068 root 1.1
2069     if (!(spell->name)) {
2070     LOG(llevError, "item number %d is a spell with no name.\n", spell->count);
2071     return;
2072     }
2073     SockList_AddInt(sl, spell->count);
2074     SockList_AddShort(sl, spell->level);
2075     SockList_AddShort(sl, spell->casting_time);
2076     /* store costs and damage in the object struct, to compare to later */
2077     spell->last_sp = SP_level_spellpoint_cost(pl->ob, spell, SPELL_MANA);
2078     spell->last_grace = SP_level_spellpoint_cost(pl->ob, spell, SPELL_GRACE);
2079     spell->last_eat = spell->stats.dam+SP_level_dam_adjust(pl->ob, spell);
2080     /* send the current values */
2081     SockList_AddShort(sl, spell->last_sp);
2082     SockList_AddShort(sl, spell->last_grace);
2083     SockList_AddShort(sl, spell->last_eat);
2084    
2085 root 1.2 /* figure out which skill it uses, if it uses one */
2086     if (spell->skill) {
2087     for (i=1; i< NUM_SKILLS; i++)
2088     if (!strcmp(spell->skill, skill_names[i])) {
2089     skill = i+CS_STAT_SKILLINFO;
2090     break;
2091     }
2092     }
2093 root 1.1 SockList_AddChar(sl, skill);
2094    
2095     SockList_AddInt(sl, spell->path_attuned);
2096     SockList_AddInt(sl, (spell->face)?spell->face->number:0);
2097    
2098     len = strlen(spell->name);
2099     SockList_AddChar(sl, (char)len);
2100     memcpy(sl->buf+sl->len, spell->name, len);
2101     sl->len+=len;
2102    
2103     if (!spell->msg) {
2104     SockList_AddShort(sl, 0);
2105     }
2106     else {
2107     len = strlen(spell->msg);
2108     SockList_AddShort(sl, len);
2109     memcpy(sl->buf+sl->len, spell->msg, len);
2110     sl->len+=len;
2111     }
2112     }
2113    
2114     /**
2115     * This tells the client to add the spell *ob, if *ob is NULL, then add
2116     * all spells in the player's inventory.
2117     */
2118     void esrv_add_spells(player *pl, object *spell) {
2119     SockList sl;
2120     if (!pl) {
2121     LOG(llevError, "esrv_add_spells, tried to add a spell to a NULL player");
2122     return;
2123     }
2124     if (!pl->socket.monitor_spells) return;
2125     sl.buf = malloc(MAXSOCKBUF);
2126 root 1.2 strcpy((char*)sl.buf,"addspell ");
2127 root 1.1 sl.len=strlen((char*)sl.buf);
2128     if (!spell) {
2129     for (spell=pl->ob->inv; spell!=NULL; spell=spell->below) {
2130     /* were we to simply keep appending data here, we could exceed
2131     * MAXSOCKBUF if the player has enough spells to add, we know that
2132     * append_spells will always append 19 data bytes, plus 4 length
2133     * bytes and 3 strings (because that is the spec) so we need to
2134     * check that the length of those 3 strings, plus the 23 bytes,
2135     * won't take us over the length limit for the socket, if it does,
2136     * we need to send what we already have, and restart packet formation
2137     */
2138     /* Seeing crashes by overflowed buffers. Quick arithemetic seems
2139     * to show add_spell is 26 bytes + 2 strings. However, the overun
2140     * is hundreds of bytes off, so correcting 22 vs 26 doesn't seem
2141     * like it will fix this
2142     */
2143     if (spell->type != SPELL) continue;
2144     if (sl.len > (MAXSOCKBUF - (26 + strlen(spell->name) +
2145     (spell->msg?strlen(spell->msg):0)))) {
2146     Send_With_Handling(&pl->socket, &sl);
2147 root 1.2 strcpy((char*)sl.buf,"addspell ");
2148 root 1.1 sl.len=strlen((char*)sl.buf);
2149     }
2150     append_spell(pl, &sl, spell);
2151     }
2152     }
2153     else if (spell->type != SPELL) {
2154     LOG(llevError, "Asked to send a non-spell object as a spell");
2155     return;
2156     }
2157     else append_spell(pl, &sl, spell);
2158     if (sl.len > MAXSOCKBUF) {
2159     LOG(llevError,"Buffer overflow in esrv_add_spells!\n");
2160     fatal(0);
2161     }
2162     /* finally, we can send the packet */
2163     Send_With_Handling(&pl->socket, &sl);
2164     free(sl.buf);
2165     }
2166