ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/Deliantra-Client/DC/Protocol.pm
Revision: 1.181
Committed: Wed Dec 26 19:11:13 2007 UTC (16 years, 4 months ago) by root
Branch: MAIN
Changes since 1.180: +1 -1 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 package CFPlus::Protocol;
2
3 use utf8;
4 use strict;
5
6 use Deliantra::Protocol::Constants;
7
8 use CFPlus;
9 use CFPlus::DB;
10 use CFPlus::UI;
11 use CFPlus::Pod;
12 use CFPlus::Macro;
13 use CFPlus::Item;
14
15 use base 'Deliantra::Protocol::Base';
16
17 sub new {
18 my ($class, %arg) = @_;
19
20 my $self = $class->SUPER::new (%arg,
21 setup_req => {
22 extmap => 1,
23 excmd => 1,
24 widget => 1,
25 %{$arg{setup_req} || {}},
26 },
27 );
28
29 $self->{map_widget}->clr_commands;
30
31 my @cmd_help = map {
32 $_->{kw}[0] =~ /^(\S+) (?:\s+ \( ([^\)]*) \) )?/x
33 or die "unparseable command help: $_->{kw}[0]";
34
35 my $cmd = $1;
36 my @args = split /\|/, $2;
37 @args = (".*") unless @args;
38
39 my (undef, @par) = CFPlus::Pod::section_of $_;
40 my $text = CFPlus::Pod::as_label @par;
41
42 $_ = $_ eq ".*" ? "" : " $_"
43 for @args;
44
45 map ["$cmd$_", $text],
46 sort { (length $a) <=> (length $b) }
47 @args
48 } sort { $a->{par} <=> $b->{par} }
49 CFPlus::Pod::find command => "*";
50
51 $self->{json_coder}
52 ->convert_blessed
53 ->filter_json_single_key_object ("\fw" => sub {
54 $self->{widget}{$_[0]}
55 })
56 ->filter_json_single_key_object ("\fc" => sub {
57 my ($id) = @_;
58 sub {
59 $self->send_exti_msg (w_e => $id, @_);
60 }
61 });
62
63 # destroy widgets on logout
64 $self->{on_stop_game_guard} = $self->{map_widget}{root}->connect (stop_game => sub {
65 for my $ws (values %{delete $self->{widgetset} || {}}) {
66 $_->destroy
67 for values %{delete $ws->{w} || {}};
68 }
69 });
70
71 $self->{map_widget}->add_command (@$_)
72 for @cmd_help;
73
74 {
75 $self->{dialogue} = my $tex = new_from_file CFPlus::Texture
76 CFPlus::find_rcfile "dialogue.png", minify => 1, mipmap => 1;
77 $self->{map}->set_texture (1, @$tex{qw(name w h s t)}, @{$tex->{minified}});
78 }
79
80 {
81 $self->{noface} = my $tex = new_from_file CFPlus::Texture
82 CFPlus::find_rcfile "noface.png", minify => 1, mipmap => 1;
83 $self->{map}->set_texture (2, @$tex{qw(name w h s t)}, @{$tex->{minified}});
84 }
85
86 $self->{open_container} = 0;
87
88 # per server
89 $self->{mapcache} = "mapcache_$self->{host}_$self->{port}";
90
91 $self
92 }
93
94 sub update_fx_want {
95 my ($self) = @_;
96
97 $self->send_exti_msg (fx_want => {
98 3 => !!$::CFG->{bgm_enable}, # FT_MUSIC
99 5 => !!$::CFG->{audio_enable}, # FT_SOUND
100 6 => 1, # FT_RSRC
101 });
102 }
103
104 sub ext_capabilities {
105 my ($self, %cap) = @_;
106
107 #$self->send ("setup sound 0"); # we use a different protocol
108 $self->update_fx_want;
109
110 $self->send_exti_req (resource => "exp_table", sub {
111 my ($exp_table) = @_;
112
113 $self->register_face_handler ($exp_table, sub {
114 my ($face) = @_;
115
116 $self->{exp_table} = $self->{json_coder}->decode (delete $face->{data});
117 $_->() for values %{ $self->{on_exp_update} || {} };
118 });
119
120 ()
121 });
122
123 if (my $ts = $cap{tileset}) {
124 if (my ($default) = grep $_->[2] & 1, @$ts) {
125 $self->{tileset} = $default;
126 $self->{tilesize} = $default->[3];
127 $self->setup_req (tileset => $default->[0]);
128
129 my $w = int $self->{mapw} * 32 / $self->{tilesize};
130 my $h = int $self->{maph} * 32 / $self->{tilesize};
131
132 $self->setup_req (mapsize => "${w}x${h}");
133 }
134 }
135 }
136
137 sub ext_ambient_music {
138 my ($self, $songs) = @_;
139 &::audio_music_set_ambient ($songs);
140 }
141
142 #############################################################################
143
144 sub widget_associate {
145 my ($self, $ws, $id, $widget) = @_;
146
147 $widget ||= new CFPlus::UI::Bin;
148
149 $widget->{s_id} = $id;
150 $self->{widget}{$id} = $widget;
151
152 if ($ws) {
153 $widget->{s_ws} = $ws;
154 $self->{widgetset}{$ws}{w}{$id} = $widget;
155 }
156
157 $widget->connect (on_destroy => sub {
158 my ($widget) = @_;
159
160 delete $self->{widget}{$widget->{s_id}};
161 delete $self->{widgetset}{$widget->{s_ws}}{$widget->{s_id}}
162 if exists $widget->{s_ws};
163 });
164 }
165
166 # widgetset new
167 sub ext_ws_n {
168 my ($self, $id) = @_;
169
170 $self->{widgetset}{$id} = {
171 w => {},
172 };
173 }
174
175 # widgetset destroy
176 sub ext_ws_d {
177 my ($self, $id) = @_;
178
179 my $ws = delete $self->{widgetset}{$id}
180 or return;
181
182 $_->destroy
183 for values %{$ws->{w}};
184 }
185
186 # widgetset create
187 sub ext_ws_c {
188 my ($self, $ws, $id, $class, $args) = @_;
189
190 $self->widget_associate (
191 $ws, $id => scalar eval {
192 local $SIG{__DIE__};
193 "CFPlus::UI::$class"->new (%$args)
194 }
195 );
196 }
197
198 # widgetset associate
199 sub ext_ws_a {
200 my ($self, %ass) = @_;
201
202 # everything that has a name, wether conceivably useful or not
203 my %wkw = (
204 root => $CFPlus::UI::ROOT,
205 tooltip => $CFPlus::UI::TOOLTIP,
206
207 mapwidget => $::MAPWIDGET,
208 buttonbar => $::BUTTONBAR,
209 metaserver => $::METASERVER,
210 buttonbar => $::BUTTONBAR,
211 login_button => $::LOGIN_BUTTON,
212 quit_dialog => $::QUIT_DIALOG,
213 host_entry => $::HOST_ENTRY,
214 metaserver => $::METASERVER,
215 server_info => $::SERVER_INFO,
216
217 setup_dialog => $::SETUP_DIALOG,
218 setup_notebook => $::SETUP_NOTEBOOK,
219 setup_server => $::SETUP_SERVER,
220 setup_keyboard => $::SETUP_KEYBOARD,
221
222 pl_notebook => $::PL_NOTEBOOK,
223 pl_window => $::PL_WINDOW,
224 inventory_page => $::INVENTORY_PAGE,
225 stats_page => $::STATS_PAGE,
226 skill_page => $::SKILL_PAGE,
227 spell_page => $::SPELL_PAGE,
228 spell_list => $::SPELL_LIST,
229
230 floorbox => $::FLOORBOX,
231 help_window => $::HELP_WINDOW,
232 message_window => $::MESSAGE_WINDOW,
233 statusbox => $::SDTATUSBOX,
234
235 inv => $::INV,
236 invr => $::INVR,
237 invr_hb => $::INVR_HB,
238 );
239
240 while (my ($id, $name) = each %ass) {
241 $self->widget_associate (undef, $id => $wkw{$name});
242 }
243 }
244
245 # widget call
246 sub ext_w_c {
247 my ($self, $id, $rcb, $method, @args) = @_;
248
249 my $w = $self->{widget}{$id}
250 or return;
251
252 if ($rcb) {
253 $rcb->($w->$method (@args));
254 } else {
255 $w->$method (@args);
256 }
257 }
258
259 # widget set
260 sub ext_w_s {
261 my ($self, $id, $attr) = @_;
262
263 my $w = $self->{widget}{$id}
264 or return;
265
266 for (my $i = 0; $i < $#$attr; $i += 2) {
267 my ($member, $value) = @$attr[$i, $i+1];
268 if (defined $value) {
269 $w->{$member} = $value;
270 } else {
271 delete $w->{$member};
272 }
273 $w->{parent}->realloc if $member =~ /^c_/ && $w->{visible};
274 }
275 }
276
277 # widget get
278 sub ext_w_g {
279 my ($self, $id, $rid, @attr) = @_;
280
281 my $w = $self->{widget}{$id}
282 or return;
283
284 $self->send_exti_msg (w_e => $rid, map $w->{$_}, @attr);
285 }
286
287 # message window
288 sub ext_channel_info {
289 my ($self, $info) = @_;
290 $self->{channels}->{$info->{id}} = $info;
291 $::MESSAGE_WINDOW->add_channel ($info);
292 }
293
294 #############################################################################
295
296 sub logprint {
297 my ($self, @a) = @_;
298
299 CFPlus::DB::logprint "$Deliantra::VARDIR/log.$self->{host}" => (join "", @a), sub { };
300 }
301
302 sub _stat_numdiff {
303 my ($self, $name, $old, $new) = @_;
304
305 my $diff = $new - $old;
306
307 $diff = 0.01 * int $diff * 100;
308
309 0.1 >= abs $diff ? ()
310 : $diff < 0 ? "$name$diff" : "$name+$diff"
311 }
312
313 sub _stat_skillmaskdiff {
314 my ($self, $name, $old, $new) = @_;
315
316 my $diff = $old ^ $new
317 or return;
318
319 my @diff = map
320 {
321 $diff & $_
322 ? (($new & $_ ? "+" : "-") . $self->{spell_paths}{$_})
323 : ()
324 }
325 sort { $a <=> $b } keys %{$self->{spell_paths}};
326
327 join "", @diff
328 }
329
330 # all stats that are chacked against changes
331 my @statchange = (
332 [&CS_STAT_STR => \&_stat_numdiff, "Str"],
333 [&CS_STAT_INT => \&_stat_numdiff, "Int"],
334 [&CS_STAT_WIS => \&_stat_numdiff, "Wis"],
335 [&CS_STAT_DEX => \&_stat_numdiff, "Dex"],
336 [&CS_STAT_CON => \&_stat_numdiff, "Con"],
337 [&CS_STAT_CHA => \&_stat_numdiff, "Cha"],
338 [&CS_STAT_POW => \&_stat_numdiff, "Pow"],
339 [&CS_STAT_WC => \&_stat_numdiff, "Wc"],
340 [&CS_STAT_AC => \&_stat_numdiff, "Ac"],
341 [&CS_STAT_DAM => \&_stat_numdiff, "Dam"],
342 [&CS_STAT_SPEED => \&_stat_numdiff, "Speed"],
343 [&CS_STAT_WEAP_SP => \&_stat_numdiff, "WSp"],
344 [&CS_STAT_MAXHP => \&_stat_numdiff, "HP"],
345 [&CS_STAT_MAXSP => \&_stat_numdiff, "Mana"],
346 [&CS_STAT_MAXGRACE => \&_stat_numdiff, "Grace"],
347 [&CS_STAT_WEIGHT_LIM => \&_stat_numdiff, "Weight"],
348 [&CS_STAT_SPELL_ATTUNE => \&_stat_skillmaskdiff, "attuned"],
349 [&CS_STAT_SPELL_REPEL => \&_stat_skillmaskdiff, "repelled"],
350 [&CS_STAT_SPELL_DENY => \&_stat_skillmaskdiff, "denied"],
351 [&CS_STAT_RES_PHYS => \&_stat_numdiff, "phys"],
352 [&CS_STAT_RES_MAG => \&_stat_numdiff, "magic"],
353 [&CS_STAT_RES_FIRE => \&_stat_numdiff, "fire"],
354 [&CS_STAT_RES_ELEC => \&_stat_numdiff, "electricity"],
355 [&CS_STAT_RES_COLD => \&_stat_numdiff, "cold"],
356 [&CS_STAT_RES_CONF => \&_stat_numdiff, "confusion"],
357 [&CS_STAT_RES_ACID => \&_stat_numdiff, "acid"],
358 [&CS_STAT_RES_DRAIN => \&_stat_numdiff, "drain"],
359 [&CS_STAT_RES_GHOSTHIT => \&_stat_numdiff, "ghosthit"],
360 [&CS_STAT_RES_POISON => \&_stat_numdiff, "poison"],
361 [&CS_STAT_RES_SLOW => \&_stat_numdiff, "slow"],
362 [&CS_STAT_RES_PARA => \&_stat_numdiff, "paralyse"],
363 [&CS_STAT_TURN_UNDEAD => \&_stat_numdiff, "turnundead"],
364 [&CS_STAT_RES_FEAR => \&_stat_numdiff, "fear"],
365 [&CS_STAT_RES_DEPLETE => \&_stat_numdiff, "depletion"],
366 [&CS_STAT_RES_DEATH => \&_stat_numdiff, "death"],
367 [&CS_STAT_RES_HOLYWORD => \&_stat_numdiff, "godpower"],
368 [&CS_STAT_RES_BLIND => \&_stat_numdiff, "blind"],
369 );
370
371 sub stats_update {
372 my ($self, $stats) = @_;
373
374 my $prev = $self->{prev_stats} || { };
375
376 if (my @diffs =
377 (
378 ($stats->{+CS_STAT_EXP64} > $prev->{+CS_STAT_EXP64} ? ($stats->{+CS_STAT_EXP64} - $prev->{+CS_STAT_EXP64}) . " experience gained" : ()),
379 map {
380 $stats->{$_} && $prev->{$_}
381 && $stats->{$_}[1] > $prev->{$_}[1] ? "($self->{skill_info}{$_}+" . ($stats->{$_}[1] - $prev->{$_}[1]) . ")" : ()
382 } sort { $a <=> $b } keys %{$self->{skill_info}}
383 )
384 ) {
385 my $msg = join " ", @diffs;
386 $self->{statusbox}->add ($msg, group => "experience $msg", fg => [0.5, 1, 0.5, 0.8], timeout => 5);
387 }
388
389 if (
390 my @diffs = map $_->[1]->($self, $_->[2], $prev->{$_->[0]}, $stats->{$_->[0]}), @statchange
391 ) {
392 my $msg = "<b>stat change</b>: " . (join " ", @diffs);
393 $self->{statusbox}->add ($msg, group => "stat $msg", fg => [0.8, 1, 0.2, 1], timeout => 20);
394 }
395
396 $self->update_stats_window ($stats, $prev);
397
398 $self->{prev_stats} = { %$stats };
399 }
400
401 my %RES_TBL = (
402 phys => CS_STAT_RES_PHYS,
403 magic => CS_STAT_RES_MAG,
404 fire => CS_STAT_RES_FIRE,
405 elec => CS_STAT_RES_ELEC,
406 cold => CS_STAT_RES_COLD,
407 conf => CS_STAT_RES_CONF,
408 acid => CS_STAT_RES_ACID,
409 drain => CS_STAT_RES_DRAIN,
410 ghit => CS_STAT_RES_GHOSTHIT,
411 pois => CS_STAT_RES_POISON,
412 slow => CS_STAT_RES_SLOW,
413 para => CS_STAT_RES_PARA,
414 tund => CS_STAT_TURN_UNDEAD,
415 fear => CS_STAT_RES_FEAR,
416 depl => CS_STAT_RES_DEPLETE,
417 deat => CS_STAT_RES_DEATH,
418 holyw => CS_STAT_RES_HOLYWORD,
419 blind => CS_STAT_RES_BLIND,
420 );
421
422 sub update_stats_window {
423 my ($self, $stats, $prev) = @_;
424
425 # I love text protocols...
426
427 my $hp = $stats->{+CS_STAT_HP} * 1;
428 my $hp_m = $stats->{+CS_STAT_MAXHP} * 1;
429 my $sp = $stats->{+CS_STAT_SP} * 1;
430 my $sp_m = $stats->{+CS_STAT_MAXSP} * 1;
431 my $fo = $stats->{+CS_STAT_FOOD} * 1;
432 my $fo_m = 999;
433 my $gr = $stats->{+CS_STAT_GRACE} * 1;
434 my $gr_m = $stats->{+CS_STAT_MAXGRACE} * 1;
435
436 $::GAUGES->{hp} ->set_value ($hp, $hp_m);
437 $::GAUGES->{mana} ->set_value ($sp, $sp_m);
438 $::GAUGES->{food} ->set_value ($fo, $fo_m);
439 $::GAUGES->{grace} ->set_value ($gr, $gr_m);
440 $::GAUGES->{exp} ->set_text ("Exp: " . (::formsep ($stats->{+CS_STAT_EXP64}))
441 . " (lvl " . ($stats->{+CS_STAT_LEVEL} * 1) . ")");
442 $::GAUGES->{prg} ->set_value ($stats->{+CS_STAT_LEVEL}, $stats->{+CS_STAT_EXP64});
443 $::GAUGES->{range} ->set_text ($stats->{+CS_STAT_RANGE});
444 my $title = $stats->{+CS_STAT_TITLE};
445 $title =~ s/^Player: //;
446 $::STATWIDS->{title} ->set_text ("Title: " . $title);
447
448 $::STATWIDS->{st_str} ->set_text (sprintf "%d" , $stats->{+CS_STAT_STR});
449 $::STATWIDS->{st_dex} ->set_text (sprintf "%d" , $stats->{+CS_STAT_DEX});
450 $::STATWIDS->{st_con} ->set_text (sprintf "%d" , $stats->{+CS_STAT_CON});
451 $::STATWIDS->{st_int} ->set_text (sprintf "%d" , $stats->{+CS_STAT_INT});
452 $::STATWIDS->{st_wis} ->set_text (sprintf "%d" , $stats->{+CS_STAT_WIS});
453 $::STATWIDS->{st_pow} ->set_text (sprintf "%d" , $stats->{+CS_STAT_POW});
454 $::STATWIDS->{st_cha} ->set_text (sprintf "%d" , $stats->{+CS_STAT_CHA});
455 $::STATWIDS->{st_wc} ->set_text (sprintf "%d" , $stats->{+CS_STAT_WC});
456 $::STATWIDS->{st_ac} ->set_text (sprintf "%d" , $stats->{+CS_STAT_AC});
457 $::STATWIDS->{st_dam} ->set_text (sprintf "%d" , $stats->{+CS_STAT_DAM});
458 $::STATWIDS->{st_arm} ->set_text (sprintf "%d" , $stats->{+CS_STAT_RES_PHYS});
459 $::STATWIDS->{st_spd} ->set_text (sprintf "%.1f", $stats->{+CS_STAT_SPEED});
460 $::STATWIDS->{st_wspd}->set_text (sprintf "%.1f", $stats->{+CS_STAT_WEAP_SP});
461
462 $self->update_weight;
463
464 $::STATWIDS->{"res_$_"}->set_text (sprintf "%d%", $stats->{$RES_TBL{$_}})
465 for keys %RES_TBL;
466
467 my $sktbl = $::STATWIDS->{skill_tbl};
468 my @skills = keys %{ $self->{skill_info} };
469
470 my @order = sort { $stats->{$b->[0]}[1] <=> $stats->{$a->[0]}[1] or $a->[1] cmp $b->[1] }
471 map [$_, $self->{skill_info}{$_}],
472 grep exists $stats->{$_},
473 @skills;
474
475 if ($self->{stat_order} ne join ",", map $_->[0], @order) {
476 $self->{stat_order} = join ",", map $_->[0], @order;
477
478 $sktbl->clear;
479
480 my $sw = $self->{skillwid}{""} ||= [
481 0, 0, (new CFPlus::UI::Label text => "Experience", align => 1),
482 1, 0, (new CFPlus::UI::Label text => "Lvl.", align => 1),
483 2, 0, (new CFPlus::UI::Label text => "Progress", align => 0),
484 3, 0, (new CFPlus::UI::Label text => "Skill", expand => 1),
485 4, 0, (new CFPlus::UI::Label text => "Experience", align => 1),
486 5, 0, (new CFPlus::UI::Label text => "Lvl.", align => 1),
487 6, 0, (new CFPlus::UI::Label text => "Progress", align => 0),
488 7, 0, (new CFPlus::UI::Label text => "Skill", expand => 1),
489 ];
490
491 my @add = @$sw;
492
493 my $TOOLTIP_ALL = "\n\n<small>Left click - ready skill\nMiddle click - use spell\nRight click - further options</small>";
494
495 my @TOOLTIP_LVL = (tooltip => "<b>Level</b>. The level of the skill.$TOOLTIP_ALL", can_events => 1, can_hover => 1);
496 my @TOOLTIP_EXP = (tooltip => "<b>Experience</b>. The experience points you have in this skill.$TOOLTIP_ALL", can_events => 1, can_hover => 1);
497
498 my ($x, $y) = (0, 1);
499 for (@order) {
500 my ($idx, $name) = @$_;
501
502 my $spell_cb = sub {
503 my ($widget, $ev) = @_;
504
505 if ($ev->{button} == 1) {
506 $::CONN->user_send ("ready_skill $name");
507 } elsif ($ev->{button} == 2) {
508 $::CONN->user_send ("use_skill $name");
509 } elsif ($ev->{button} == 3) {
510 my $shortname = CFPlus::shorten $name, 14;
511 (new CFPlus::UI::Menu
512 items => [
513 ["bind <i>ready_skill $shortname</i> to a key" => sub { CFPlus::Macro::quick_macro ["ready_skill $name"] }],
514 ["bind <i>use_skill $shortname</i> to a key" => sub { CFPlus::Macro::quick_macro ["use_skill $name"] }],
515 ],
516 )->popup ($ev);
517 } else {
518 return 0;
519 }
520
521 1
522 };
523
524 my $sw = $self->{skillwid}{$idx} ||= [
525 # exp
526 (new CFPlus::UI::Label
527 align => 1, font => $::FONT_FIXED, fg => [1, 1, 0], on_button_down => $spell_cb, @TOOLTIP_EXP),
528
529 # level
530 (new CFPlus::UI::Label
531 text => "0", align => 1, font => $::FONT_FIXED, fg => [0, 1, 0], padding_x => 4, on_button_down => $spell_cb, @TOOLTIP_LVL),
532
533 # progress
534 (new CFPlus::UI::ExperienceProgress),
535
536 # label
537 (new CFPlus::UI::Label text => $name, on_button_down => $spell_cb,
538 can_events => 1, can_hover => 1, tooltip => (CFPlus::Pod::section_label skill_description => $name) . $TOOLTIP_ALL),
539 ];
540
541 push @add,
542 $x * 4 + 0, $y, $sw->[0],
543 $x * 4 + 1, $y, $sw->[1],
544 $x * 4 + 2, $y, $sw->[2],
545 $x * 4 + 3, $y, $sw->[3],
546 ;
547
548 $x++ and ($x, $y) = (0, $y + 1);
549 }
550
551 $sktbl->add_at (@add);
552 }
553
554 for (@order) {
555 my ($idx, $name) = @$_;
556 my $val = $stats->{$idx};
557
558 next if $prev->{$idx}[1] eq $val->[1];
559
560 my $sw = $self->{skillwid}{$idx};
561 $sw->[0]->set_text (::formsep ($val->[1]));
562 $sw->[1]->set_text ($val->[0] * 1);
563 $sw->[2]->set_value (@$val);
564
565 $::GAUGES->{sklprg}->set_label ("$name %d%%");
566 $::GAUGES->{sklprg}->set_value (@$val);
567 }
568 }
569
570 sub user_send {
571 my ($self, $command) = @_;
572
573 $self->{record}->($command)
574 if $self->{record};
575
576 $self->logprint ("send: ", $command);
577 $self->send_command ($command);
578 }
579
580 sub record {
581 my ($self, $cb) = @_;
582
583 $self->{record} = $cb;
584 }
585
586 sub map_scroll {
587 my ($self, $dx, $dy) = @_;
588
589 $self->{map}->scroll ($dx, $dy);
590 }
591
592 sub feed_map1a {
593 my ($self, $data) = @_;
594
595 my $missing = $self->{map}->map1a_update ($data, $self->{setup}{extmap});
596 my $delay;
597
598 for my $tile (@$missing) {
599 next if $self->{delay}{$tile};
600
601 $delay = 1;
602
603 if (my $tex = $::CONN->{texture}[$tile]) {
604 $tex->upload;
605 } else {
606 $self->{delay}{$tile} = 1;
607
608 # we assume the face is in-flight and will eventually come
609 push @{$self->{tile_cb}{$tile}}, sub {
610 delete $self->{delay}{$tile};
611 $_[0]->upload;
612 };
613 }
614 }
615
616 if ($delay) {
617 # delay the map drawing a tiny bit in the hope of getting the missing fetched
618 EV::once undef, 0, 0.03, sub {
619 $self->{map_widget}->update
620 if $self->{map_widget};
621 };
622 } else {
623 $self->{map_widget}->update;
624 }
625 }
626
627 sub magicmap {
628 my ($self, $w, $h, $x, $y, $data) = @_;
629
630 $self->{map_widget}->set_magicmap ($w, $h, $x, $y, $data);
631 }
632
633 sub flush_map {
634 my ($self) = @_;
635
636 my $map_info = delete $self->{map_info}
637 or return;
638
639 my ($hash, $x, $y, $w, $h) = @$map_info;
640
641 my $data = Compress::LZF::compress $self->{map}->get_rect ($x, $y, $w, $h);
642 $self->{map_cache_new}{$hash} = \$data;
643 CFPlus::DB::put $self->{mapcache} => $hash => $data, sub { };
644 }
645
646 sub map_clear {
647 my ($self) = @_;
648
649 $self->flush_map;
650 delete $self->{neigh_map};
651
652 $self->{map}->clear;
653 delete $self->{map_widget}{magicmap};
654 }
655
656 sub bg_fetch {
657 my ($self) = @_;
658
659 my $tile;
660
661 do {
662 $tile = pop @{$self->{bg_fetch}}
663 or return;
664 } while $self->{texture}[$tile];
665
666 CFPlus::DB::get tilecache => $tile, sub {
667 my ($data) = @_;
668
669 return unless $self->{map}; # stop when destroyed
670
671 if (defined $data) {
672 $self->have_tile ($tile, $data);
673 $self->{texture}[$tile]->upload;
674 }
675
676 $self->bg_fetch;
677 };
678 }
679
680 sub load_map($$$) {
681 my ($self, $hash, $x, $y) = @_;
682
683 my $gen = $self->{map_change_gen};
684
685 my $cb = sub {
686 return unless $gen == $self->{map_change_gen};
687
688 my ($data) = @_;
689
690 if (defined $data) {
691 $self->{map_cache_new}{$hash} = \$data;
692
693 my $data = Compress::LZF::decompress $data;
694
695 my $inprogress = @{ $self->{bg_fetch} || [] };
696 unshift @{ $self->{bg_fetch} }, $self->{map}->set_rect ($x, $y, $data);
697 $self->bg_fetch unless $inprogress;
698 }
699 };
700
701 if (my $rdata = $self->{map_cache_old}{$hash}) {
702 $cb->($$rdata);
703 } else {
704 CFPlus::DB::get $self->{mapcache} => $hash, $cb;
705 }
706 }
707
708 # hardcode /world/world_xxx_xxx map names, the savings are enourmous,
709 # (server resource,s latency, bandwidth), so this hack is warranted.
710 # the right fix is to make real tiled maps with an overview file
711 sub send_mapinfo {
712 my ($self, $data, $cb) = @_;
713
714 if ($self->{map_info}[0] =~ m%^/world/world_(\d\d\d)_(\d\d\d)$%) {
715 my ($wx, $wy) = ($1, $2);
716
717 if ($data =~ /^spatial ([1-4]+)$/) {
718 my @dx = (0, 0, 1, 0, -1);
719 my @dy = (0, -1, 0, 1, 0);
720 my ($dx, $dy);
721
722 for (split //, $1) {
723 $dx += $dx[$_];
724 $dy += $dy[$_];
725 }
726
727 $cb->(spatial => 15,
728 $self->{map_info}[1] - $self->{map}->ox + $dx * 50,
729 $self->{map_info}[2] - $self->{map}->oy + $dy * 50,
730 50, 50,
731 sprintf "/world/world_%03d_%03d", $wx + $dx, $wy + $dy
732 );
733
734 return;
735 }
736 }
737
738 $self->SUPER::send_mapinfo ($data, $cb);
739 }
740
741 # this method does a "flood fill" into every tile direction
742 # it assumes that tiles are arranged in a rectangular grid,
743 # i.e. a map is the same as the left of the right map etc.
744 # failure to comply are harmless and result in display errors
745 # at worst.
746 sub flood_fill {
747 my ($self, $block, $gx, $gy, $path, $hash, $flags) = @_;
748
749 # the server does not allow map paths > 6
750 return if 7 <= length $path;
751
752 my ($x0, $y0, $x1, $y1) = @{$self->{neigh_rect}};
753
754 for (
755 [1, 3, 0, -1],
756 [2, 4, 1, 0],
757 [3, 1, 0, 1],
758 [4, 2, -1, 0],
759 ) {
760 my ($tile, $tile2, $dx, $dy) = @$_;
761
762 next if $block & (1 << $tile);
763 my $block = $block | (1 << $tile2);
764
765 my $gx = $gx + $dx;
766 my $gy = $gy + $dy;
767
768 next unless $flags & (1 << ($tile - 1));
769 next if $self->{neigh_grid}{$gx, $gy}++;
770
771 my $neigh = $self->{neigh_map}{$hash} ||= [];
772 if (my $info = $neigh->[$tile]) {
773 my ($flags, $x, $y, $w, $h, $hash) = @$info;
774
775 $self->flood_fill ($block, $gx, $gy, "$path$tile", $hash, $flags)
776 if $x >= $x0 && $x + $w < $x1 && $y >= $y0 && $y + $h < $y1;
777
778 } else {
779 my $gen = $self->{map_change_gen};
780 $self->send_mapinfo ("spatial $path$tile", sub {
781 return unless $gen == $self->{map_change_gen};
782
783 my ($mode, $flags, $x, $y, $w, $h, $hash) = @_;
784
785 return if $mode ne "spatial";
786
787 $x += $self->{map}->ox;
788 $y += $self->{map}->oy;
789
790 $self->load_map ($hash, $x, $y)
791 unless $self->{neigh_map}{$hash}[5]++;#d#
792
793 $neigh->[$tile] = [$flags, $x, $y, $w, $h, $hash];
794
795 $self->flood_fill ($block, $gx, $gy, "$path$tile", $hash, $flags)
796 if $x >= $x0 && $x + $w < $x1 && $y >= $y0 && $y + $h < $y1;
797 });
798 }
799 }
800 }
801
802 sub map_change {
803 my ($self, $mode, $flags, $x, $y, $w, $h, $hash) = @_;
804
805 $self->flush_map;
806
807 ++$self->{map_change_gen};
808 $self->{map_cache_old} = delete $self->{map_cache_new};
809
810 my ($ox, $oy) = ($::MAP->ox, $::MAP->oy);
811
812 my $mapmapw = $self->{mapmap}->{w};
813 my $mapmaph = $self->{mapmap}->{h};
814
815 $self->{neigh_rect} = [
816 $ox - $mapmapw * 0.5, $oy - $mapmapw * 0.5,
817 $ox + $mapmapw * 0.5 + $w, $oy + $mapmapw * 0.5 + $h,
818 ];
819
820 delete $self->{neigh_grid};
821
822 $x += $ox;
823 $y += $oy;
824
825 $self->{map_info} = [$hash, $x, $y, $w, $h];
826
827 (my $map = $hash) =~ s/^.*?\/([^\/]+)$/\1/;
828 $::STATWIDS->{map}->set_text ("Map: " . $map);
829
830 $self->load_map ($hash, $x, $y);
831 $self->flood_fill (0, 0, 0, "", $hash, $flags);
832 }
833
834 sub face_find {
835 my ($self, $facenum, $face, $cb) = @_;
836
837 if ($face->{type} == 0) { # FT_FACE
838 my $id = CFPlus::DB::get_tile_id_sync $face->{name};
839
840 $face->{id} = $id;
841 $self->{map}->set_tileid ($facenum => $id);
842
843 CFPlus::DB::get tilecache => $id, $cb;
844
845 } elsif ($face->{type} & 1) { # with metadata
846 CFPlus::DB::get res_meta => $face->{name}, $cb;
847
848 } else { # no metadata
849 CFPlus::DB::get res_data => $face->{name}, $cb;
850 }
851 }
852
853 sub face_update {
854 my ($self, $facenum, $face, $changed) = @_;
855
856 if ($face->{type} == 0) {
857 # image, FT_FACE
858 CFPlus::DB::put tilecache => $face->{id} => $face->{data}, sub { }
859 if $changed;
860
861 $self->have_tile ($face->{id}, delete $face->{data});
862
863 } elsif ($face->{type} & 1) {
864 # split metadata case, FT_MUSIC, FT_SOUND
865 if ($changed) { # new data
866 my ($meta, $data) = unpack "(w/a*)*", $face->{data};
867 $face->{data} = $meta;
868
869 # rely on strict ordering here and also on later fetch
870 CFPlus::DB::put res_data => $face->{name} => $data, sub { };
871 CFPlus::DB::put res_meta => $face->{name} => $meta, sub { };
872 }
873
874 $face->{data} = $self->{json_coder}->decode ($face->{data});
875 ::add_license ($face);
876 ::message ({ markup => CFPlus::asxml "downloaded resource '$face->{data}{name}', type $face->{type}." })
877 if $changed;
878
879 if ($face->{type} == 3) { # FT_MUSIC
880 &::audio_music_push ($facenum);
881 } elsif ($face->{type} == 5) { # FT_SOUND
882 &::audio_sound_push ($facenum);
883 }
884
885 } else {
886 # flat resource case, FT_RSRC
887 CFPlus::DB::put res_data => $face->{name} => $face->{data}, sub { }
888 if $changed;
889 }
890
891 if (my $cbs = $self->{face_cb}{$facenum}) {
892 $_->($face, $changed) for @$cbs;
893 }
894 }
895
896 sub smooth_update {
897 my ($self, $facenum, $face) = @_;
898
899 $self->{map}->set_smooth ($facenum, $face->{smoothface}, $face->{smoothlevel});
900 }
901
902 sub have_tile {
903 my ($self, $tile, $data) = @_;
904
905 return unless $self->{map};
906
907 my $tex = $self->{texture}[$tile] ||=
908 new CFPlus::Texture
909 tile => $tile,
910 image => $data, delete_image => 1,
911 minify => 1, mipmap => 1;
912
913 if (my $cbs = delete $self->{tile_cb}{$tile}) {
914 $_->($tex) for @$cbs;
915 }
916 }
917
918 # call in non-void context registers a temporary
919 # hook with handle, otherwise its permanent
920 sub on_face_change {
921 my ($self, $num, $cb) = @_;
922
923 push @{$self->{face_cb}{$num}}, $cb;
924
925 defined wantarray
926 ? CFPlus::guard {
927 @{$self->{face_cb}{$num}}
928 = grep $_ != $cb,
929 @{$self->{face_cb}{$num}};
930 }
931 : ()
932 }
933
934 # call in non-void context registers a temporary
935 # hook with handle, otherwise its permanent
936 sub register_face_handler {
937 my ($self, $num, $cb) = @_;
938
939 return unless $num;
940
941 # invoke if available right now
942 $cb->($self->{face}[$num], 0)
943 unless exists $self->{face}[$num]{loading};
944
945 # future changes
946 $self->on_face_change ($num => $cb)
947 }
948
949 sub sound_play {
950 my ($self, $type, $face, $dx, $dy, $vol) = @_;
951
952 &::audio_sound_play ($face, $dx, $dy, $vol)
953 unless $type & 1; # odd types are silent for future expansion
954 }
955
956 my $LAST_QUERY; # server is stupid, stupid, stupid
957
958 sub query {
959 my ($self, $flags, $prompt) = @_;
960
961 $prompt = $LAST_QUERY unless length $prompt;
962 $LAST_QUERY = $prompt;
963
964 $self->{query}-> ($self, $flags, $prompt);
965 }
966
967 sub sanitise_xml($) {
968 local $_ = shift;
969
970 # we now weed out all tags we do not support
971 s{ <(?! /?i> | /?u> | /?b> | /?big | /?small | /?s | /?tt | fg\ | /fg>)
972 }{
973 "&lt;"
974 }gex;
975
976 # now all entities
977 s/&(?!amp;|lt;|gt;|apos;|quot;|#[0-9]+;|#x[0-9a-fA-F]+;)/&amp;/g;
978
979 # handle some elements
980 s/<fg name='([^']*)'>(.*?)<\/fg>/<span foreground='$1'>$2<\/span>/gs;
981 s/<fg name="([^"]*)">(.*?)<\/fg>/<span foreground="$1">$2<\/span>/gs;
982
983 $_
984 }
985
986 our %NAME_TO_COLOR = (
987 black => 0,
988 white => 1,
989 darkblue => 2,
990 red => 3,
991 orange => 4,
992 lightblue => 5,
993 darkorange => 6,
994 green => 7,
995 darkgreen => 8,
996 grey => 9,
997 brown => 10,
998 yellow => 11,
999 tan => 12,
1000 );
1001
1002 our @CF_COLOR = (
1003 [1.00, 1.00, 1.00], #[0.00, 0.00, 0.00],
1004 [1.00, 1.00, 1.00],
1005 [0.50, 0.50, 1.00], #[0.00, 0.00, 0.55]
1006 [1.00, 0.00, 0.00],
1007 [1.00, 0.54, 0.00],
1008 [0.11, 0.56, 1.00],
1009 [0.93, 0.46, 0.00],
1010 [0.18, 0.54, 0.34],
1011 [0.56, 0.73, 0.56],
1012 [0.80, 0.80, 0.80],
1013 [0.75, 0.61, 0.20],
1014 [0.99, 0.77, 0.26],
1015 [0.74, 0.65, 0.41],
1016 );
1017
1018 sub msg {
1019 my ($self, $color, $type, $text, @extra) = @_;
1020
1021 $text = sanitise_xml $text;
1022
1023 if (my $cb = $self->{cb_msg}{$type}) {
1024 $_->($self, $color, $type, $text, @extra) for values %$cb;
1025 } elsif ($type =~ /^(?:chargen-race-title|chargen-race-description)$/) {
1026 $type =~ s/-/_/g;
1027 $self->{$type} = $text;
1028 } else {
1029 $self->logprint ("msg: ", $text);
1030 return if $color < 0; # negative color == ignore if not understood
1031
1032 my $fg = $CF_COLOR[$color & NDI_COLOR_MASK] || [1, 0, 0];
1033
1034 ## try to create single paragraphs of multiple lines sent by the server
1035 # no longer neecssary with TRT servers
1036 #$text =~ s/(?<=\S)\n(?=\w)/ /g;
1037
1038 for (split /\n/, $text) {
1039 ::message ({
1040 fg => $fg,
1041 markup => $_,
1042 type => $type,
1043 extra => [@extra],
1044 color_flags => $color, #d# ugly, kill
1045 });
1046
1047 $color &= ~NDI_CLEAR; # only clear once for multiline messages
1048 # actually, this is an ugly design. _we_ should control the channels,
1049 # not some random other widget, as the channels are clearly protocol-specific.
1050 # then we could also react to flags such as CLEAR without resorting to
1051 # hacks such as color_flags, above.
1052 }
1053
1054 $self->{statusbox}->add ($text,
1055 group => $text,
1056 fg => $fg,
1057 timeout => $color >= 2 ? 180 : 10,
1058 tooltip_font => $::FONT_FIXED,
1059 ) if $type eq "info";
1060 }
1061 }
1062
1063 sub spell_add {
1064 my ($self, $spell) = @_;
1065
1066 # try to create single paragraphs out of the multiple lines sent by the server
1067 $spell->{message} =~ s/(?<=\S)\n(?=\w)/ /g;
1068 $spell->{message} =~ s/\n+$//;
1069 $spell->{message} ||= "Server did not provide a description for this spell.";
1070
1071 $::SPELL_LIST->add_spell ($spell);
1072
1073 $self->{map_widget}->add_command ("invoke $spell->{name}", CFPlus::asxml $spell->{message});
1074 $self->{map_widget}->add_command ("cast $spell->{name}", CFPlus::asxml $spell->{message});
1075 }
1076
1077 sub spell_delete {
1078 my ($self, $spell) = @_;
1079
1080 $::SPELL_LIST->remove_spell ($spell);
1081 }
1082
1083 sub setup {
1084 my ($self, $setup) = @_;
1085
1086 $self->{map_widget}->set_tilesize ($self->{tilesize});
1087 $::MAP->resize ($self->{mapw}, $self->{maph});
1088 }
1089
1090 sub addme_success {
1091 my ($self) = @_;
1092
1093 my %skill_help;
1094
1095 for my $node (CFPlus::Pod::find skill_description => "*") {
1096 my (undef, @par) = CFPlus::Pod::section_of $node;
1097 $skill_help{$node->{kw}[0]} = CFPlus::Pod::as_label @par;
1098 };
1099
1100 for my $skill (values %{$self->{skill_info}}) {
1101 $self->{map_widget}->add_command ("ready_skill $skill",
1102 (CFPlus::asxml "Ready the skill '$skill'\n\n")
1103 . $skill_help{$skill});
1104 $self->{map_widget}->add_command ("use_skill $skill",
1105 (CFPlus::asxml "Immediately use the skill '$skill'\n\n")
1106 . $skill_help{$skill});
1107 }
1108 }
1109
1110 sub eof {
1111 my ($self) = @_;
1112
1113 $self->{map_widget}->clr_commands;
1114
1115 ::stop_game ();
1116 }
1117
1118 sub update_floorbox {
1119 $CFPlus::UI::ROOT->on_refresh ($::FLOORBOX => sub {
1120 return unless $::CONN;
1121
1122 $::FLOORBOX->clear;
1123
1124 my @add;
1125
1126 my $row;
1127 for (sort { $a->{count} <=> $b->{count} } values %{ $::CONN->{container}{$::CONN->{open_container} || 0} }) {
1128 if ($row < 6) {
1129 local $_->{face_widget}; # hack to force recreation of widget
1130 local $_->{desc_widget}; # hack to force recreation of widget
1131 CFPlus::Item::update_widgets $_;
1132
1133 push @add,
1134 0, $row, $_->{face_widget},
1135 1, $row, $_->{desc_widget};
1136
1137 $row++;
1138 } else {
1139 push @add, 1, $row, new CFPlus::UI::Button
1140 text => "More...",
1141 on_activate => sub { ::toggle_player_page ($::INVENTORY_PAGE); 0 },
1142 ;
1143 last;
1144 }
1145 }
1146 if ($::CONN->{open_container}) {
1147 push @add, 1, $row++, new CFPlus::UI::Button
1148 text => "Close container",
1149 on_activate => sub { $::CONN->send ("apply $::CONN->{open_container}") }
1150 ;
1151 }
1152
1153 $::FLOORBOX->add_at (@add);
1154 });
1155
1156 $::WANT_REFRESH = 1;
1157 }
1158
1159 sub set_opencont {
1160 my ($conn, $tag, $name) = @_;
1161 $conn->{open_container} = $tag;
1162 update_floorbox;
1163
1164 $::INVR_HB->clear ();
1165 $::INVR_HB->add (new CFPlus::UI::Label align => 0, expand => 1, text => $name);
1166
1167 if ($tag != 0) { # Floor isn't closable, is it?
1168 $::INVR_HB->add (new CFPlus::UI::Button
1169 text => "Close container",
1170 tooltip => "Close the currently open container (if one is open)",
1171 on_activate => sub {
1172 $::CONN->send ("apply $tag") # $::CONN->{open_container}")
1173 if $tag != 0;
1174 0
1175 },
1176 );
1177 }
1178
1179 $::INVR->set_items ($conn->{container}{$tag});
1180 }
1181
1182 sub update_containers {
1183 my ($self) = @_;
1184
1185 $CFPlus::UI::ROOT->on_refresh ("update_containers_$self" => sub {
1186 my $todo = delete $self->{update_container}
1187 or return;
1188
1189 for my $tag (keys %$todo) {
1190 update_floorbox if $tag == 0 or $tag == $self->{open_container};
1191 if ($tag == 0) {
1192 $::INVR->set_items ($self->{container}{0})
1193 if $tag == $self->{open_container};
1194 } elsif ($tag == $self->{player}{tag}) {
1195 $::INV->set_items ($self->{container}{$tag})
1196 } else {
1197 $::INVR->set_items ($self->{container}{$tag})
1198 if $tag == $self->{open_container};
1199 }
1200 }
1201 });
1202 }
1203
1204 sub container_add {
1205 my ($self, $tag, $items) = @_;
1206
1207 $self->{update_container}{$tag}++;
1208 $self->update_containers;
1209 }
1210
1211 sub container_clear {
1212 my ($self, $tag) = @_;
1213
1214 $self->{update_container}{$tag}++;
1215 $self->update_containers;
1216 }
1217
1218 sub item_delete {
1219 my ($self, @items) = @_;
1220
1221 $self->{update_container}{$_->{container}}++
1222 for @items;
1223
1224 $self->update_containers;
1225 }
1226
1227 sub item_update {
1228 my ($self, $item) = @_;
1229
1230 #d# print "item_update: $item->{tag} in $item->{container} ($self->{player}{tag}) ($::CONN->{open_container})\n";
1231
1232 CFPlus::Item::update_widgets $item;
1233
1234 if ($item->{tag} == $::CONN->{open_container} && not ($item->{flags} & F_OPEN)) {
1235 set_opencont ($::CONN, 0, "Floor");
1236
1237 } elsif ($item->{flags} & F_OPEN) {
1238 set_opencont ($::CONN, $item->{tag}, CFPlus::Item::desc_string $item);
1239
1240 } else {
1241 $self->{update_container}{$item->{container}}++;
1242 $self->update_containers;
1243 }
1244 }
1245
1246 sub player_update {
1247 my ($self, $player) = @_;
1248
1249 $self->update_weight;
1250 }
1251
1252 sub update_weight {
1253 my ($self) = @_;
1254
1255 my $weight = .001 * $self->{player}{weight};
1256 my $limit = .001 * $self->{stat}{+CS_STAT_WEIGHT_LIM};
1257
1258 $::STATWIDS->{weight}->set_text (sprintf "Weight: %.1fkg", $weight);
1259 $::STATWIDS->{m_weight}->set_text (sprintf "%.1fkg", $limit);
1260 $::STATWIDS->{i_weight}->set_text (sprintf "%.1f/%.1fkg", $weight, $limit);
1261 }
1262
1263 sub update_server_info {
1264 my ($self) = @_;
1265
1266 my @yesno = ("<span foreground='red'>no</span>", "<span foreground='green'>yes</span>");
1267
1268 $::SERVER_INFO->set_markup (
1269 "server <tt>$self->{host}:$self->{port}</tt>\n"
1270 . "protocol version <tt>$self->{version}</tt>\n"
1271 . "minimap support $yesno[$self->{setup}{mapinfocmd} > 0]\n"
1272 . "extended command support $yesno[$self->{setup}{extcmd} > 0]\n"
1273 . "examine command support $yesno[$self->{setup}{excmd} > 0]\n"
1274 . "editing support $yesno[!!$self->{editor_support}]\n"
1275 . "map attributes $yesno[$self->{setup}{extmap} > 0]\n"
1276 . "big image protocol support $yesno[$self->{setup}{fxix} > 0]\n"
1277 . "cfplus support $yesno[$self->{cfplus_ext} > 0]"
1278 . ($self->{cfplus_ext} > 0 ? ", version $self->{cfplus_ext}" : "") ."\n"
1279 . "map size $self->{mapw}×$self->{maph}\n"
1280 );
1281
1282 }
1283
1284 sub logged_in {
1285 my ($self) = @_;
1286
1287 $self->send_ext_req (cfplus_support => version => 2, sub {
1288 my (%msg) = @_;
1289
1290 $self->{cfplus_ext} = $msg{version};
1291 $self->update_server_info;
1292
1293 if ($self->{cfplus_ext} >= 2) {
1294 $self->send_ext_req ("editor_support", sub {
1295 $self->{editor_support} = { @_ };
1296 $self->update_server_info;
1297
1298 0
1299 });
1300 }
1301
1302 0
1303 });
1304
1305 $self->update_server_info;
1306
1307 $self->send_command ("output-rate $::CFG->{output_rate}") if $::CFG->{output_rate} > 0;
1308 $self->send_command ("pickup $::CFG->{pickup}");
1309 }
1310
1311 sub lookat {
1312 my ($self, $x, $y) = @_;
1313
1314 if ($self->{cfplus_ext}) {
1315 $self->send_ext_req (lookat => $x, $y, sub {
1316 my (%msg) = @_;
1317
1318 if (exists $msg{npc_dialog}) {
1319 # start npc chat dialog
1320 $self->{npc_dialog} = new CFPlus::NPCDialog::
1321 token => $msg{npc_dialog},
1322 title => "$msg{npc_dialog}[0] (NPC)",
1323 conn => $self,
1324 ;
1325 }
1326 });
1327 }
1328
1329 $self->send ("lookat $x $y");
1330 }
1331
1332 sub destroy {
1333 my ($self) = @_;
1334
1335 (delete $self->{npc_dialog})->destroy
1336 if $self->{npc_dialog};
1337
1338 $self->SUPER::destroy;
1339
1340 %$self = ();
1341 }
1342
1343 package CFPlus::NPCDialog;
1344
1345 our @ISA = 'CFPlus::UI::Toplevel';
1346
1347 sub new {
1348 my $class = shift;
1349
1350 my $self = $class->SUPER::new (
1351 x => 'center',
1352 y => 'center',
1353 name => "npc_dialog",
1354 force_w => $::WIDTH * 0.7,
1355 force_h => $::HEIGHT * 0.7,
1356 title => "NPC Dialog",
1357 kw => { hi => 0, yes => 0, no => 0 },
1358 has_close_button => 1,
1359 @_,
1360 );
1361
1362 CFPlus::weaken (my $this = $self);
1363
1364 $self->connect (delete => sub { $this->destroy; 1 });
1365
1366 # better use a pane...
1367 $self->add (my $hbox = new CFPlus::UI::HBox);
1368 $hbox->add ($self->{textview} = new CFPlus::UI::TextScroller expand => 1);
1369
1370 $hbox->add (my $vbox = new CFPlus::UI::VBox);
1371
1372 $vbox->add (new CFPlus::UI::Label text => "Message Entry:");
1373 $vbox->add ($self->{entry} = new CFPlus::UI::Entry
1374 tooltip => "#npc_message_entry",
1375 on_activate => sub {
1376 my ($entry, $text) = @_;
1377
1378 return unless $text =~ /\S/;
1379
1380 $entry->set_text ("");
1381 $this->send ($text);
1382
1383 0
1384 },
1385 );
1386
1387 $vbox->add ($self->{options} = new CFPlus::UI::VBox);
1388
1389 $self->{bye_button} = new CFPlus::UI::Button
1390 text => "Bye (close)",
1391 tooltip => "Use this button to end talking to the NPC. This also closes the dialog window.",
1392 on_activate => sub { $this->destroy; 1 },
1393 ;
1394
1395 $self->update_options;
1396
1397 $self->{id} = "npc-channel-" . $self->{conn}->token;
1398 $self->{conn}->connect_ext ($self->{id} => sub {
1399 $this->feed (@_) if $this;
1400 });
1401
1402 $self->{conn}->send_ext_msg (npc_dialog_begin => $self->{id}, $self->{token});
1403
1404 $self->{entry}->grab_focus;
1405
1406 $self->{textview}->add_paragraph ({
1407 fg => [1, 1, 0, 1],
1408 markup => "<small>[starting conversation with <b>$self->{title}</b>]</small>\n\n",
1409 });
1410
1411 $self->show;
1412 $self
1413 };
1414
1415 sub update_options {
1416 my ($self) = @_;
1417
1418 CFPlus::weaken $self;
1419
1420 $self->{options}->clear;
1421 $self->{options}->add ($self->{bye_button});
1422
1423 for my $kw (sort keys %{ $self->{kw} }) {
1424 $self->{options}->add (new CFPlus::UI::Button
1425 text => $kw,
1426 on_activate => sub {
1427 $self->send ($kw);
1428 0
1429 },
1430 );
1431 }
1432 }
1433
1434 sub feed {
1435 my ($self, $type, @arg) = @_;
1436
1437 CFPlus::weaken $self;
1438
1439 if ($type eq "update") {
1440 my (%info) = @arg;
1441
1442 $self->{kw}{$_} = 1 for @{$info{add_topics} || []};
1443 $self->{kw}{$_} = 0 for @{$info{del_topics} || []};
1444
1445 if (exists $info{msg}) {
1446 my $text = "\n" . CFPlus::Protocol::sanitise_xml $info{msg};
1447 my $match = join "|", map "\\b\Q$_\E\\b", sort { (length $b) <=> (length $a) } keys %{ $self->{kw} };
1448 my @link;
1449 $text =~ s{
1450 ($match)
1451 }{
1452 my $kw = $1;
1453
1454 push @link, new CFPlus::UI::Label
1455 markup => "<span foreground='#c0c0ff' underline='single'>$kw</span>",
1456 can_hover => 1,
1457 can_events => 1,
1458 padding_x => 0,
1459 padding_y => 0,
1460 on_button_up => sub {
1461 $self->send ($kw);
1462 };
1463
1464 "\x{fffc}"
1465 }giex;
1466
1467 $self->{textview}->add_paragraph ({ markup => $text, widget => \@link });
1468 $self->{textview}->scroll_to_bottom;
1469 }
1470
1471 $self->update_options;
1472 } else {
1473 $self->destroy;
1474 }
1475
1476 1
1477 }
1478
1479 sub send {
1480 my ($self, $msg) = @_;
1481
1482 $self->{textview}->add_paragraph ({ markup => "\n" . CFPlus::asxml $msg });
1483 $self->{textview}->scroll_to_bottom;
1484
1485 $self->{conn}->send_ext_msg (npc_dialog_tell => $self->{id}, $msg);
1486 }
1487
1488 sub destroy {
1489 my ($self) = @_;
1490
1491 #Carp::cluck "debug\n";#d# #todo# enable: destroy gets called twice because scalar keys {} is 1
1492
1493 if ($self->{conn}) {
1494 $self->{conn}->send_ext_msg (npc_dialog_end => $self->{id}) if $self->{id};
1495 delete $self->{conn}{npc_dialog};
1496 $self->{conn}->disconnect_ext ($self->{id});
1497 }
1498
1499 $self->SUPER::destroy;
1500 }
1501
1502 1
1503