ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/lib/cf.pm
(Generate patch)

Comparing deliantra/server/lib/cf.pm (file contents):
Revision 1.85 by root, Mon Dec 11 22:56:57 2006 UTC vs.
Revision 1.96 by root, Fri Dec 22 06:02:29 2006 UTC

1package cf; 1package cf;
2
3use utf8;
4use strict;
2 5
3use Symbol; 6use Symbol;
4use List::Util; 7use List::Util;
5use Storable; 8use Storable;
6use Opcode; 9use Opcode;
7use Safe; 10use Safe;
8use Safe::Hole; 11use Safe::Hole;
9 12
13use Coro;
14use Coro::Event;
15use Coro::Timer;
16use Coro::Signal;
17use Coro::Semaphore;
18
10use IO::AIO (); 19use IO::AIO;
11use YAML::Syck (); 20use YAML::Syck ();
12use Time::HiRes; 21use Time::HiRes;
13use Event; 22
14$Event::Eval = 1; # no idea why this is required, but it is 23use Event; $Event::Eval = 1; # no idea why this is required, but it is
15 24
16# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode? 25# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
17$YAML::Syck::ImplicitUnicode = 1; 26$YAML::Syck::ImplicitUnicode = 1;
18 27
19use strict; 28$Coro::main->prio (Coro::PRIO_MIN);
29
30sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
20 31
21our %COMMAND = (); 32our %COMMAND = ();
22our %COMMAND_TIME = (); 33our %COMMAND_TIME = ();
23our %EXTCMD = (); 34our %EXTCMD = ();
24 35
25_init_vars; 36_init_vars;
26 37
27our @EVENT; 38our @EVENT;
28our $LIBDIR = maps_directory "perl"; 39our $LIBDIR = datadir . "/ext";
29 40
30our $TICK = MAX_TIME * 1e-6; 41our $TICK = MAX_TIME * 1e-6;
31our $TICK_WATCHER; 42our $TICK_WATCHER;
32our $NEXT_TICK; 43our $NEXT_TICK;
33 44
72 print STDERR "cfperl: $msg"; 83 print STDERR "cfperl: $msg";
73 LOG llevError, "cfperl: $msg"; 84 LOG llevError, "cfperl: $msg";
74 }; 85 };
75} 86}
76 87
88@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable';
89@safe::cf::object::ISA = @cf::object::ISA = 'cf::attachable';
90@safe::cf::player::ISA = @cf::player::ISA = 'cf::attachable';
91@safe::cf::client::ISA = @cf::client::ISA = 'cf::attachable';
92@safe::cf::map::ISA = @cf::map::ISA = 'cf::attachable';
77@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; 93@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
78 94
79# we bless all objects into (empty) derived classes to force a method lookup 95# we bless all objects into (empty) derived classes to force a method lookup
80# within the Safe compartment. 96# within the Safe compartment.
81for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) { 97for my $pkg (qw(
98 cf::global
99 cf::object cf::object::player
100 cf::client cf::player
101 cf::arch cf::living
102 cf::map cf::party cf::region
103)) {
82 no strict 'refs'; 104 no strict 'refs';
83 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 105 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
84} 106}
85 107
86$Event::DIED = sub { 108$Event::DIED = sub {
125 147
126=cut 148=cut
127 149
128############################################################################# 150#############################################################################
129 151
130=head2 EVENTS AND OBJECT ATTACHMENTS 152=head2 ATTACHABLE OBJECTS
153
154Many objects in crossfire are so-called attachable objects. That means you can
155attach callbacks/event handlers (a collection of which is called an "attachment")
156to it. All such attachable objects support the following methods.
157
158In the following description, CLASS can be any of C<global>, C<object>
159C<player>, C<client> or C<map> (i.e. the attachable objects in
160crossfire+).
131 161
132=over 4 162=over 4
133 163
134=item $object->attach ($attachment, key => $value...)
135
136=item $object->detach ($attachment)
137
138Attach/detach a pre-registered attachment to an object.
139
140=item $player->attach ($attachment, key => $value...)
141
142=item $player->detach ($attachment)
143
144Attach/detach a pre-registered attachment to a player.
145
146=item $map->attach ($attachment, key => $value...) 164=item $attachable->attach ($attachment, key => $value...)
147 165
148=item $map->detach ($attachment) 166=item $attachable->detach ($attachment)
149 167
150Attach/detach a pre-registered attachment to a map. 168Attach/detach a pre-registered attachment to a specific object and give it
169the specified key/value pairs as arguments.
151 170
152=item $bool = $object->attached ($name) 171Example, attach a minesweeper attachment to the given object, making it a
17210x10 minesweeper game:
153 173
154=item $bool = $player->attached ($name) 174 $obj->attach (minesweeper => width => 10, height => 10);
155 175
156=item $bool = $map->attached ($name) 176=item $bool = $attachable->attached ($name)
157 177
158Checks wether the named attachment is currently attached to the object. 178Checks wether the named attachment is currently attached to the object.
159 179
160=item cf::attach_global ... 180=item cf::CLASS->attach ...
161 181
162Attach handlers for global events. 182=item cf::CLASS->detach ...
163 183
164This and all following C<attach_*>-functions expect any number of the 184Define an anonymous attachment and attach it to all objects of the given
165following handler/hook descriptions: 185CLASS. See the next function for an explanation of its arguments.
186
187You can attach to global events by using the C<cf::global> class.
188
189Example, log all player logins:
190
191 cf::player->attach (
192 on_login => sub {
193 my ($pl) = @_;
194 ...
195 },
196 );
197
198Example, attach to the jeweler skill:
199
200 cf::object->attach (
201 type => cf::SKILL,
202 subtype => cf::SK_JEWELER,
203 on_use_skill => sub {
204 my ($sk, $ob, $part, $dir, $msg) = @_;
205 ...
206 },
207 );
208
209=item cf::CLASS::attachment $name, ...
210
211Register an attachment by C<$name> through which attachable objects of the
212given CLASS can refer to this attachment.
213
214Some classes such as crossfire maps and objects can specify attachments
215that are attached at load/instantiate time, thus the need for a name.
216
217These calls expect any number of the following handler/hook descriptions:
166 218
167=over 4 219=over 4
168 220
169=item prio => $number 221=item prio => $number
170 222
172by another C<prio> setting). Lower priority handlers get executed 224by another C<prio> setting). Lower priority handlers get executed
173earlier. The default priority is C<0>, and many built-in handlers are 225earlier. The default priority is C<0>, and many built-in handlers are
174registered at priority C<-1000>, so lower priorities should not be used 226registered at priority C<-1000>, so lower priorities should not be used
175unless you know what you are doing. 227unless you know what you are doing.
176 228
229=item type => $type
230
231(Only for C<< cf::object->attach >> calls), limits the attachment to the
232given type of objects only (the additional parameter C<subtype> can be
233used to further limit to the given subtype).
234
177=item on_I<event> => \&cb 235=item on_I<event> => \&cb
178 236
179Call the given code reference whenever the named event happens (event is 237Call the given code reference whenever the named event happens (event is
180something like C<instantiate>, C<apply>, C<use_skill> and so on, and which 238something like C<instantiate>, C<apply>, C<use_skill> and so on, and which
181handlers are recognised generally depends on the type of object these 239handlers are recognised generally depends on the type of object these
190package and register them. Only handlers for eevents supported by the 248package and register them. Only handlers for eevents supported by the
191object/class are recognised. 249object/class are recognised.
192 250
193=back 251=back
194 252
195=item cf::attach_to_type $object_type, $subtype, ... 253Example, define an attachment called "sockpuppet" that calls the given
254event handler when a monster attacks:
196 255
197Attach handlers for a specific object type (e.g. TRANSPORT) and 256 cf::object::attachment sockpuppet =>
198subtype. If C<$subtype> is zero or undef, matches all objects of the given 257 on_skill_attack => sub {
199type. 258 my ($self, $victim) = @_;
200 259 ...
201=item cf::attach_to_objects ...
202
203Attach handlers to all objects. Do not use this except for debugging or
204very rare events, as handlers are (obviously) called for I<all> objects in
205the game.
206
207=item cf::attach_to_players ...
208
209Attach handlers to all players.
210
211=item cf::attach_to_maps ...
212
213Attach handlers to all maps.
214
215=item cf:register_attachment $name, ...
216
217Register an attachment by name through which objects can refer to this
218attachment.
219
220=item cf:register_player_attachment $name, ...
221
222Register an attachment by name through which players can refer to this
223attachment.
224
225=item cf:register_map_attachment $name, ...
226
227Register an attachment by name through which maps can refer to this
228attachment.
229
230=cut
231
232# the following variables are defined in .xs and must not be re-created
233our @CB_GLOBAL = (); # registry for all global events
234our @CB_OBJECT = (); # all objects (should not be used except in emergency)
235our @CB_PLAYER = ();
236our @CB_TYPE = (); # registry for type (cf-object class) based events
237our @CB_MAP = ();
238
239my %attachment;
240
241sub _attach_cb($\%$$$) {
242 my ($registry, $undo, $event, $prio, $cb) = @_;
243
244 use sort 'stable';
245
246 $cb = [$prio, $cb];
247
248 @{$registry->[$event]} = sort
249 { $a->[0] cmp $b->[0] }
250 @{$registry->[$event] || []}, $cb;
251
252 push @{$undo->{cb}}, [$event, $cb];
253}
254
255# attach handles attaching event callbacks
256# the only thing the caller has to do is pass the correct
257# registry (== where the callback attaches to).
258sub _attach(\@$@) {
259 my ($registry, $klass, @arg) = @_;
260
261 my $prio = 0;
262
263 my %undo = (
264 registry => $registry,
265 cb => [],
266 );
267
268 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
269
270 while (@arg) {
271 my $type = shift @arg;
272
273 if ($type eq "prio") {
274 $prio = shift @arg;
275
276 } elsif ($type eq "package") {
277 my $pkg = shift @arg;
278
279 while (my ($name, $id) = each %cb_id) {
280 if (my $cb = $pkg->can ($name)) {
281 _attach_cb $registry, %undo, $id, $prio, $cb;
282 }
283 } 260 }
284
285 } elsif (exists $cb_id{$type}) {
286 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @arg;
287
288 } elsif (ref $type) {
289 warn "attaching objects not supported, ignoring.\n";
290
291 } else {
292 shift @arg;
293 warn "attach argument '$type' not supported, ignoring.\n";
294 }
295 }
296
297 \%undo
298}
299
300sub _attach_attachment {
301 my ($obj, $name, %arg) = @_;
302
303 return if exists $obj->{_attachment}{$name};
304
305 my $res;
306
307 if (my $attach = $attachment{$name}) {
308 my $registry = $obj->registry;
309
310 for (@$attach) {
311 my ($klass, @attach) = @$_;
312 $res = _attach @$registry, $klass, @attach;
313 }
314
315 $obj->{$name} = \%arg;
316 } else {
317 warn "object uses attachment '$name' that is not available, postponing.\n";
318 }
319
320 $obj->{_attachment}{$name} = undef;
321
322 $res->{attachment} = $name;
323 $res
324}
325
326*cf::object::attach =
327*cf::player::attach =
328*cf::map::attach = sub {
329 my ($obj, $name, %arg) = @_;
330
331 _attach_attachment $obj, $name, %arg;
332};
333
334# all those should be optimised
335*cf::object::detach =
336*cf::player::detach =
337*cf::map::detach = sub {
338 my ($obj, $name) = @_;
339
340 delete $obj->{_attachment}{$name};
341 reattach ($obj);
342};
343
344*cf::object::attached =
345*cf::player::attached =
346*cf::map::attached = sub {
347 my ($obj, $name) = @_;
348
349 exists $obj->{_attachment}{$name}
350};
351
352sub attach_global {
353 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
354}
355
356sub attach_to_type {
357 my $type = shift;
358 my $subtype = shift;
359
360 _attach @{$CB_TYPE[$type + $subtype * NUM_SUBTYPES]}, KLASS_OBJECT, @_
361}
362
363sub attach_to_objects {
364 _attach @CB_OBJECT, KLASS_OBJECT, @_
365}
366
367sub attach_to_players {
368 _attach @CB_PLAYER, KLASS_PLAYER, @_
369}
370
371sub attach_to_maps {
372 _attach @CB_MAP, KLASS_MAP, @_
373}
374
375sub register_attachment {
376 my $name = shift;
377
378 $attachment{$name} = [[KLASS_OBJECT, @_]];
379}
380
381sub register_player_attachment {
382 my $name = shift;
383
384 $attachment{$name} = [[KLASS_PLAYER, @_]];
385}
386
387sub register_map_attachment {
388 my $name = shift;
389
390 $attachment{$name} = [[KLASS_MAP, @_]];
391}
392
393our $override;
394our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
395
396sub override {
397 $override = 1;
398 @invoke_results = ();
399}
400
401sub do_invoke {
402 my $event = shift;
403 my $callbacks = shift;
404
405 @invoke_results = ();
406
407 local $override;
408
409 for (@$callbacks) {
410 eval { &{$_->[1]} };
411
412 if ($@) {
413 warn "$@";
414 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
415 override;
416 }
417
418 return 1 if $override;
419 }
420
421 0 261 }
422}
423 262
424=item $bool = cf::invoke EVENT_GLOBAL_XXX, ... 263=item $attachable->valid
425
426=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...)
427
428=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...)
429
430=item $bool = $map->invoke (EVENT_MAP_XXX, ...)
431
432Generate a global/object/player/map-specific event with the given arguments.
433
434This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be
435removed in future versions), and there is no public API to access override
436results (if you must, access C<@cf::invoke_results> directly).
437
438=back
439
440=cut
441
442#############################################################################
443
444=head2 METHODS VALID FOR ALL CORE OBJECTS
445
446=over 4
447
448=item $object->valid, $player->valid, $map->valid
449 264
450Just because you have a perl object does not mean that the corresponding 265Just because you have a perl object does not mean that the corresponding
451C-level object still exists. If you try to access an object that has no 266C-level object still exists. If you try to access an object that has no
452valid C counterpart anymore you get an exception at runtime. This method 267valid C counterpart anymore you get an exception at runtime. This method
453can be used to test for existence of the C object part without causing an 268can be used to test for existence of the C object part without causing an
454exception. 269exception.
455 270
271=cut
272
273# the following variables are defined in .xs and must not be re-created
274our @CB_GLOBAL = (); # registry for all global events
275our @CB_OBJECT = (); # all objects (should not be used except in emergency)
276our @CB_PLAYER = ();
277our @CB_CLIENT = ();
278our @CB_TYPE = (); # registry for type (cf-object class) based events
279our @CB_MAP = ();
280
281my %attachment;
282
283sub _attach_cb($$$$) {
284 my ($registry, $event, $prio, $cb) = @_;
285
286 use sort 'stable';
287
288 $cb = [$prio, $cb];
289
290 @{$registry->[$event]} = sort
291 { $a->[0] cmp $b->[0] }
292 @{$registry->[$event] || []}, $cb;
293}
294
295# attach handles attaching event callbacks
296# the only thing the caller has to do is pass the correct
297# registry (== where the callback attaches to).
298sub _attach {
299 my ($registry, $klass, @arg) = @_;
300
301 my $object_type;
302 my $prio = 0;
303 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
304
305 while (@arg) {
306 my $type = shift @arg;
307
308 if ($type eq "prio") {
309 $prio = shift @arg;
310
311 } elsif ($type eq "type") {
312 $object_type = shift @arg;
313 $registry = $CB_TYPE[$object_type] ||= [];
314
315 } elsif ($type eq "subtype") {
316 defined $object_type or Carp::croak "subtype specified without type";
317 my $object_subtype = shift @arg;
318 $registry = $CB_TYPE[$object_type + $object_subtype * NUM_SUBTYPES] ||= [];
319
320 } elsif ($type eq "package") {
321 my $pkg = shift @arg;
322
323 while (my ($name, $id) = each %cb_id) {
324 if (my $cb = $pkg->can ($name)) {
325 _attach_cb $registry, $id, $prio, $cb;
326 }
327 }
328
329 } elsif (exists $cb_id{$type}) {
330 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
331
332 } elsif (ref $type) {
333 warn "attaching objects not supported, ignoring.\n";
334
335 } else {
336 shift @arg;
337 warn "attach argument '$type' not supported, ignoring.\n";
338 }
339 }
340}
341
342sub _object_attach {
343 my ($obj, $name, %arg) = @_;
344
345 return if exists $obj->{_attachment}{$name};
346
347 if (my $attach = $attachment{$name}) {
348 my $registry = $obj->registry;
349
350 for (@$attach) {
351 my ($klass, @attach) = @$_;
352 _attach $registry, $klass, @attach;
353 }
354
355 $obj->{$name} = \%arg;
356 } else {
357 warn "object uses attachment '$name' that is not available, postponing.\n";
358 }
359
360 $obj->{_attachment}{$name} = undef;
361}
362
363sub cf::attachable::attach {
364 if (ref $_[0]) {
365 _object_attach @_;
366 } else {
367 _attach shift->_attach_registry, @_;
368 }
369};
370
371# all those should be optimised
372sub cf::attachable::detach {
373 my ($obj, $name) = @_;
374
375 if (ref $obj) {
376 delete $obj->{_attachment}{$name};
377 reattach ($obj);
378 } else {
379 Carp::croak "cannot, currently, detach class attachments";
380 }
381};
382
383sub cf::attachable::attached {
384 my ($obj, $name) = @_;
385
386 exists $obj->{_attachment}{$name}
387}
388
389for my $klass (qw(GLOBAL OBJECT PLAYER CLIENT MAP)) {
390 eval "#line " . __LINE__ . " 'cf.pm'
391 sub cf::\L$klass\E::_attach_registry {
392 (\\\@CB_$klass, KLASS_$klass)
393 }
394
395 sub cf::\L$klass\E::attachment {
396 my \$name = shift;
397
398 \$attachment{\$name} = [[KLASS_$klass, \@_]];
399 }
400 ";
401 die if $@;
402}
403
404our $override;
405our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
406
407sub override {
408 $override = 1;
409 @invoke_results = ();
410}
411
412sub do_invoke {
413 my $event = shift;
414 my $callbacks = shift;
415
416 @invoke_results = ();
417
418 local $override;
419
420 for (@$callbacks) {
421 eval { &{$_->[1]} };
422
423 if ($@) {
424 warn "$@";
425 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
426 override;
427 }
428
429 return 1 if $override;
430 }
431
432 0
433}
434
435=item $bool = cf::global::invoke (EVENT_CLASS_XXX, ...)
436
437=item $bool = $attachable->invoke (EVENT_CLASS_XXX, ...)
438
439Generate an object-specific event with the given arguments.
440
441This API is preliminary (most likely, the EVENT_CLASS_xxx prefix will be
442removed in future versions), and there is no public API to access override
443results (if you must, access C<@cf::invoke_results> directly).
444
456=back 445=back
457 446
458=cut 447=cut
459
460*cf::object::valid =
461*cf::player::valid =
462*cf::map::valid = \&cf::_valid;
463 448
464############################################################################# 449#############################################################################
465# object support 450# object support
466 451
467sub instantiate { 452sub instantiate {
487 472
488 for my $name (keys %{ $obj->{_attachment} || {} }) { 473 for my $name (keys %{ $obj->{_attachment} || {} }) {
489 if (my $attach = $attachment{$name}) { 474 if (my $attach = $attachment{$name}) {
490 for (@$attach) { 475 for (@$attach) {
491 my ($klass, @attach) = @$_; 476 my ($klass, @attach) = @$_;
492 _attach @$registry, $klass, @attach; 477 _attach $registry, $klass, @attach;
493 } 478 }
494 } else { 479 } else {
495 warn "object uses attachment '$name' that is not available, postponing.\n"; 480 warn "object uses attachment '$name' that is not available, postponing.\n";
496 } 481 }
497 } 482 }
553 } 538 }
554 539
555 () 540 ()
556} 541}
557 542
558attach_to_objects 543cf::object->attach (
559 prio => -1000000, 544 prio => -1000000,
560 on_clone => sub { 545 on_clone => sub {
561 my ($src, $dst) = @_; 546 my ($src, $dst) = @_;
562 547
563 @{$dst->registry} = @{$src->registry}; 548 @{$dst->registry} = @{$src->registry};
565 %$dst = %$src; 550 %$dst = %$src;
566 551
567 %{$dst->{_attachment}} = %{$src->{_attachment}} 552 %{$dst->{_attachment}} = %{$src->{_attachment}}
568 if exists $src->{_attachment}; 553 if exists $src->{_attachment};
569 }, 554 },
570; 555);
571 556
572############################################################################# 557#############################################################################
573# command handling &c 558# command handling &c
574 559
575=item cf::register_command $name => \&callback($ob,$args); 560=item cf::register_command $name => \&callback($ob,$args);
604 #warn "registering extcmd '$name' to '$caller'"; 589 #warn "registering extcmd '$name' to '$caller'";
605 590
606 $EXTCMD{$name} = [$cb, $caller]; 591 $EXTCMD{$name} = [$cb, $caller];
607} 592}
608 593
609attach_to_players 594cf::player->attach (
610 on_command => sub { 595 on_command => sub {
611 my ($pl, $name, $params) = @_; 596 my ($pl, $name, $params) = @_;
612 597
613 my $cb = $COMMAND{$name} 598 my $cb = $COMMAND{$name}
614 or return; 599 or return;
634 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 619 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
635 } 620 }
636 621
637 cf::override; 622 cf::override;
638 }, 623 },
639; 624);
640 625
641sub register { 626sub register {
642 my ($base, $pkg) = @_; 627 my ($base, $pkg) = @_;
643 628
644 #TODO 629 #TODO
713 698
714 Symbol::delete_package $pkg; 699 Symbol::delete_package $pkg;
715} 700}
716 701
717sub load_extensions { 702sub load_extensions {
718 my $LIBDIR = maps_directory "perl";
719
720 for my $ext (<$LIBDIR/*.ext>) { 703 for my $ext (<$LIBDIR/*.ext>) {
721 next unless -r $ext; 704 next unless -r $ext;
722 eval { 705 eval {
723 load_extension $ext; 706 load_extension $ext;
724 1 707 1
736 defined $path or return; 719 defined $path or return;
737 720
738 unlink "$path.pst"; 721 unlink "$path.pst";
739}; 722};
740 723
741attach_to_maps prio => -10000, package => cf::mapsupport::; 724cf::map->attach (prio => -10000, package => cf::mapsupport::);
742 725
743############################################################################# 726#############################################################################
744# load/save perl data associated with player->ob objects 727# load/save perl data associated with player->ob objects
745 728
746sub all_objects(@) { 729sub all_objects(@) {
747 @_, map all_objects ($_->inv), @_ 730 @_, map all_objects ($_->inv), @_
748} 731}
749 732
750# TODO: compatibility cruft, remove when no longer needed 733# TODO: compatibility cruft, remove when no longer needed
751attach_to_players 734cf::player->attach (
752 on_load => sub { 735 on_load => sub {
753 my ($pl, $path) = @_; 736 my ($pl, $path) = @_;
754 737
755 for my $o (all_objects $pl->ob) { 738 for my $o (all_objects $pl->ob) {
756 if (my $value = $o->get_ob_key_value ("_perl_data")) { 739 if (my $value = $o->get_ob_key_value ("_perl_data")) {
758 741
759 %$o = %{ Storable::thaw pack "H*", $value }; 742 %$o = %{ Storable::thaw pack "H*", $value };
760 } 743 }
761 } 744 }
762 }, 745 },
763; 746);
764 747
765############################################################################# 748#############################################################################
766 749
767=head2 CORE EXTENSIONS 750=head2 CORE EXTENSIONS
768 751
769Functions and methods that extend core crossfire objects. 752Functions and methods that extend core crossfire objects.
753
754=head3 cf::player
770 755
771=over 4 756=over 4
772 757
773=item cf::player::exists $login 758=item cf::player::exists $login
774 759
779sub cf::player::exists($) { 764sub cf::player::exists($) {
780 cf::player::find $_[0] 765 cf::player::find $_[0]
781 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 766 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
782} 767}
783 768
769=item $player->ext_reply ($msgid, $msgtype, %msg)
770
771Sends an ext reply to the player.
772
773=cut
774
775sub cf::player::ext_reply($$$%) {
776 my ($self, $id, %msg) = @_;
777
778 $msg{msgid} = $id;
779
780 $self->send ("ext " . to_json \%msg);
781}
782
783=back
784
785=head3 cf::object::player
786
787=over 4
788
784=item $player_object->reply ($npc, $msg[, $flags]) 789=item $player_object->reply ($npc, $msg[, $flags])
785 790
786Sends a message to the player, as if the npc C<$npc> replied. C<$npc> 791Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
787can be C<undef>. Does the right thing when the player is currently in a 792can be C<undef>. Does the right thing when the player is currently in a
788dialogue with the given NPC character. 793dialogue with the given NPC character.
789 794
790=cut 795=cut
791 796
792# rough implementation of a future "reply" method that works 797# rough implementation of a future "reply" method that works
793# with dialog boxes. 798# with dialog boxes.
799#TODO: the first argument must go, split into a $npc->reply_to ( method
794sub cf::object::player::reply($$$;$) { 800sub cf::object::player::reply($$$;$) {
795 my ($self, $npc, $msg, $flags) = @_; 801 my ($self, $npc, $msg, $flags) = @_;
796 802
797 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4; 803 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
798 804
802 $msg = $npc->name . " says: $msg" if $npc; 808 $msg = $npc->name . " says: $msg" if $npc;
803 $self->message ($msg, $flags); 809 $self->message ($msg, $flags);
804 } 810 }
805} 811}
806 812
807=item $player->ext_reply ($msgid, $msgtype, %msg)
808
809Sends an ext reply to the player.
810
811=cut
812
813sub cf::player::ext_reply($$$%) {
814 my ($self, $id, %msg) = @_;
815
816 $msg{msgid} = $id;
817
818 $self->send ("ext " . to_json \%msg);
819}
820
821=item $player_object->may ("access") 813=item $player_object->may ("access")
822 814
823Returns wether the given player is authorized to access resource "access" 815Returns wether the given player is authorized to access resource "access"
824(e.g. "command_wizcast"). 816(e.g. "command_wizcast").
825 817
832 (ref $cf::CFG{"may_$access"} 824 (ref $cf::CFG{"may_$access"}
833 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}} 825 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}}
834 : $cf::CFG{"may_$access"}) 826 : $cf::CFG{"may_$access"})
835} 827}
836 828
837=cut 829=head3 cf::client
838 830
839############################################################################# 831=over 4
832
833=item $client->send_drawinfo ($text, $flags)
834
835Sends a drawinfo packet to the client. Circumvents output buffering so
836should not be used under normal circumstances.
837
838=cut
839
840sub cf::client::send_drawinfo {
841 my ($self, $text, $flags) = @_;
842
843 utf8::encode $text;
844 $self->send_packet (sprintf "drawinfo %d %s", $flags, $text);
845}
846
847
848=item $success = $client->query ($flags, "text", \&cb)
849
850Queues a query to the client, calling the given callback with
851the reply text on a reply. flags can be C<cf::CS_QUERY_YESNO>,
852C<cf::CS_QUERY_SINGLECHAR> or C<cf::CS_QUERY_HIDEINPUT> or C<0>.
853
854Queries can fail, so check the return code. Or don't, as queries will become
855reliable at some point in the future.
856
857=cut
858
859sub cf::client::query {
860 my ($self, $flags, $text, $cb) = @_;
861
862 return unless $self->state == ST_PLAYING
863 || $self->state == ST_SETUP
864 || $self->state == ST_CUSTOM;
865
866 $self->state (ST_CUSTOM);
867
868 utf8::encode $text;
869 push @{ $self->{query_queue} }, [(sprintf "query %d %s", $flags, $text), $cb];
870
871 $self->send_packet ($self->{query_queue}[0][0])
872 if @{ $self->{query_queue} } == 1;
873}
874
875cf::client->attach (
876 on_reply => sub {
877 my ($ns, $msg) = @_;
878
879 # this weird shuffling is so that direct followup queries
880 # get handled first
881 my $queue = delete $ns->{query_queue};
882
883 (shift @$queue)->[1]->($msg);
884
885 push @{ $ns->{query_queue} }, @$queue;
886
887 if (@{ $ns->{query_queue} } == @$queue) {
888 if (@$queue) {
889 $ns->send_packet ($ns->{query_queue}[0][0]);
890 } else {
891 $ns->state (ST_PLAYING);
892 }
893 }
894 },
895);
896
897=item $client->coro (\&cb)
898
899Create a new coroutine, running the specified callback. The coroutine will
900be automatically cancelled when the client gets destroyed (e.g. on logout,
901or loss of connection).
902
903=cut
904
905sub cf::client::coro {
906 my ($self, $cb) = @_;
907
908 my $coro; $coro = async {
909 eval {
910 $cb->();
911 };
912 warn $@ if $@;
913 warn "cancel myself\n";#d#
914 delete $self->{_coro}{$coro+0};
915 };
916
917 $self->{_coro}{$coro+0} = $coro;
918}
919
920cf::client->attach (
921 on_destroy => sub {
922 my ($ns) = @_;
923
924 warn "cancel $_" for values %{ $ns->{_coro} || {} };#d#
925 $_->cancel for values %{ $ns->{_coro} || {} };
926 },
927);
928
929=back
930
840 931
841=head2 SAFE SCRIPTING 932=head2 SAFE SCRIPTING
842 933
843Functions that provide a safe environment to compile and execute 934Functions that provide a safe environment to compile and execute
844snippets of perl code without them endangering the safety of the server 935snippets of perl code without them endangering the safety of the server
859 950
860=pod 951=pod
861 952
862The following fucntions and emthods are available within a safe environment: 953The following fucntions and emthods are available within a safe environment:
863 954
864 cf::object contr pay_amount pay_player 955 cf::object contr pay_amount pay_player map
865 cf::object::player player 956 cf::object::player player
866 cf::player peaceful 957 cf::player peaceful
958 cf::map trigger
867 959
868=cut 960=cut
869 961
870for ( 962for (
871 ["cf::object" => qw(contr pay_amount pay_player)], 963 ["cf::object" => qw(contr pay_amount pay_player map)],
872 ["cf::object::player" => qw(player)], 964 ["cf::object::player" => qw(player)],
873 ["cf::player" => qw(peaceful)], 965 ["cf::player" => qw(peaceful)],
966 ["cf::map" => qw(trigger)],
874) { 967) {
875 no strict 'refs'; 968 no strict 'refs';
876 my ($pkg, @funs) = @$_; 969 my ($pkg, @funs) = @$_;
877 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 970 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
878 for @funs; 971 for @funs;
1018 sub db_sync() { 1111 sub db_sync() {
1019 db_save if $dirty; 1112 db_save if $dirty;
1020 undef $dirty; 1113 undef $dirty;
1021 } 1114 }
1022 1115
1023 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, cb => sub { 1116 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, data => WF_AUTOCANCEL, cb => sub {
1024 db_sync; 1117 db_sync;
1025 }); 1118 });
1026 1119
1027 sub db_dirty() { 1120 sub db_dirty() {
1028 $dirty = 1; 1121 $dirty = 1;
1042 $DB->{$_[0]} = $_[1]; 1135 $DB->{$_[0]} = $_[1];
1043 } 1136 }
1044 db_dirty; 1137 db_dirty;
1045 } 1138 }
1046 1139
1047 attach_global 1140 cf::global->attach (
1048 prio => 10000, 1141 prio => 10000,
1049 on_cleanup => sub { 1142 on_cleanup => sub {
1050 db_sync; 1143 db_sync;
1051 }, 1144 },
1052 ; 1145 );
1053} 1146}
1054 1147
1055############################################################################# 1148#############################################################################
1056# the server's main() 1149# the server's main()
1057 1150
1078 1171
1079 $msg->("reloading..."); 1172 $msg->("reloading...");
1080 1173
1081 eval { 1174 eval {
1082 # cancel all watchers 1175 # cancel all watchers
1083 $_->cancel for Event::all_watchers; 1176 for (Event::all_watchers) {
1177 $_->cancel if $_->data & WF_AUTOCANCEL;
1178 }
1084 1179
1085 # unload all extensions 1180 # unload all extensions
1086 for (@exts) { 1181 for (@exts) {
1087 $msg->("unloading <$_>"); 1182 $msg->("unloading <$_>");
1088 unload_extension $_; 1183 unload_extension $_;
1164}; 1259};
1165 1260
1166unshift @INC, $LIBDIR; 1261unshift @INC, $LIBDIR;
1167 1262
1168$TICK_WATCHER = Event->timer ( 1263$TICK_WATCHER = Event->timer (
1169 prio => 1, 1264 prio => 0,
1170 async => 1,
1171 at => $NEXT_TICK || 1, 1265 at => $NEXT_TICK || 1,
1266 data => WF_AUTOCANCEL,
1172 cb => sub { 1267 cb => sub {
1173 cf::server_tick; # one server iteration 1268 cf::server_tick; # one server iteration
1174 1269
1175 my $NOW = Event::time; 1270 my $NOW = Event::time;
1176 $NEXT_TICK += $TICK; 1271 $NEXT_TICK += $TICK;
1186IO::AIO::max_poll_time $TICK * 0.2; 1281IO::AIO::max_poll_time $TICK * 0.2;
1187 1282
1188Event->io (fd => IO::AIO::poll_fileno, 1283Event->io (fd => IO::AIO::poll_fileno,
1189 poll => 'r', 1284 poll => 'r',
1190 prio => 5, 1285 prio => 5,
1286 data => WF_AUTOCANCEL,
1191 cb => \&IO::AIO::poll_cb); 1287 cb => \&IO::AIO::poll_cb);
1192 1288
11931 12891
1194 1290

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines