ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/Deliantra-Client/DC/Protocol.pm
Revision: 1.156
Committed: Tue Aug 21 00:59:34 2007 UTC (16 years, 9 months ago) by root
Branch: MAIN
Changes since 1.155: +78 -35 lines
Log Message:
- reworked the fxix handling more or less completely. i do see a structure now,
  but haven't implemented it fully. what we have will have to do.
- added generic flat resource support
- used this to retrieve the exp table resource
- cleaned up face handling (uses less memory now)
- implemented clean callbacks for face changes
- halved latency for tile loading

File Contents

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