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.24 by root, Wed Jul 19 22:51:40 2006 UTC vs.
Revision 1.63 by root, Fri Sep 8 17:41:41 2006 UTC

5use Storable; 5use Storable;
6use Opcode; 6use Opcode;
7use Safe; 7use Safe;
8use Safe::Hole; 8use Safe::Hole;
9 9
10use Time::HiRes;
10use Event; 11use Event;
11$Event::Eval = 1; # no idea why this is required, but it is 12$Event::Eval = 1; # no idea why this is required, but it is
12 13
13use strict; 14use strict;
14 15
16_init_vars;
17
15our %COMMAND; 18our %COMMAND = ();
16our @EVENT; 19our @EVENT;
17our %PROP_TYPE; 20our $LIBDIR = maps_directory "perl";
18our %PROP_IDX; 21
22our $TICK = MAX_TIME * 1e-6;
23our $TICK_WATCHER;
24our $NEXT_TICK;
19 25
20BEGIN { 26BEGIN {
21 @EVENT = map lc, @EVENT;
22
23 *CORE::GLOBAL::warn = sub { 27 *CORE::GLOBAL::warn = sub {
24 my $msg = join "", @_; 28 my $msg = join "", @_;
25 $msg .= "\n" 29 $msg .= "\n"
26 unless $msg =~ /\n$/; 30 unless $msg =~ /\n$/;
27 31
28 print STDERR "cfperl: $msg"; 32 print STDERR "cfperl: $msg";
29 LOG llevError, "cfperl: $msg"; 33 LOG llevError, "cfperl: $msg";
30 }; 34 };
31} 35}
32 36
33my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply! 37@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
34 38
35# generate property mutators 39# we bless all objects into (empty) derived classes to force a method lookup
36sub prop_gen { 40# within the Safe compartment.
37 my ($prefix, $class) = @_; 41for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) {
38
39 no strict 'refs'; 42 no strict 'refs';
40 43 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
41 for my $prop (keys %PROP_TYPE) {
42 $prop =~ /^\Q$prefix\E_(.*$)/ or next;
43 my $sub = lc $1;
44
45 my $type = $PROP_TYPE{$prop};
46 my $idx = $PROP_IDX {$prop};
47
48 *{"$class\::get_$sub"} = *{"$class\::$sub"} = sub {
49 $_[0]->get_property ($type, $idx)
50 };
51
52 *{"$class\::set_$sub"} = sub {
53 $_[0]->set_property ($type, $idx, $_[1]);
54 } unless $ignore_set{$prop};
55 }
56} 44}
57
58# auto-generate most of the API
59
60prop_gen OBJECT_PROP => "cf::object";
61# CFAPI_OBJECT_ANIMATION?
62prop_gen PLAYER_PROP => "cf::object::player";
63
64prop_gen MAP_PROP => "cf::map";
65prop_gen ARCH_PROP => "cf::arch";
66
67# guessed hierarchies
68
69@cf::object::player::ISA = 'cf::object';
70@cf::object::map::ISA = 'cf::object';
71 45
72$Event::DIED = sub { 46$Event::DIED = sub {
73 warn "error in event callback: @_"; 47 warn "error in event callback: @_";
74}; 48};
75 49
77my @exts; 51my @exts;
78my @hook; 52my @hook;
79my %command; 53my %command;
80my %extcmd; 54my %extcmd;
81 55
56#############################################################################
57# utility functions
58
59use JSON::Syck (); # TODO# replace by JSON::PC once working
60
61sub from_json($) {
62 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
63 JSON::Syck::Load $_[0]
64}
65
66sub to_json($) {
67 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
68 JSON::Syck::Dump $_[0]
69}
70
71#############################################################################
72# "new" plug-in system
73
74=head3 EVENTS AND OBJECT ATTACHMENTS
75
76=over 4
77
78=item $object->attach ($attachment, key => $value...)
79
80=item $object->detach ($attachment)
81
82Attach/detach a pre-registered attachment to an object.
83
84=item $player->attach ($attachment, key => $value...)
85
86=item $player->detach ($attachment)
87
88Attach/detach a pre-registered attachment to a player.
89
90=item $map->attach ($attachment, key => $value...)
91
92=item $map->detach ($attachment)
93
94Attach/detach a pre-registered attachment to a map.
95
96=item $bool = $object->attached ($name)
97
98=item $bool = $player->attached ($name)
99
100=item $bool = $map->attached ($name)
101
102Checks wether the named attachment is currently attached to the object.
103
104=item cf::attach_global ...
105
106Attach handlers for global events.
107
108This and all following C<attach_*>-functions expect any number of the
109following handler/hook descriptions:
110
111=over 4
112
113=item prio => $number
114
115Set the priority for all following handlers/hooks (unless overwritten
116by another C<prio> setting). Lower priority handlers get executed
117earlier. The default priority is C<0>, and many built-in handlers are
118registered at priority C<-1000>, so lower priorities should not be used
119unless you know what you are doing.
120
121=item on_I<event> => \&cb
122
123Call the given code reference whenever the named event happens (event is
124something like C<instantiate>, C<apply>, C<use_skill> and so on, and which
125handlers are recognised generally depends on the type of object these
126handlers attach to).
127
128See F<include/eventinc.h> for the full list of events supported, and their
129class.
130
131=item package => package::
132
133Look for sub functions of the name C<< on_I<event> >> in the given
134package and register them. Only handlers for eevents supported by the
135object/class are recognised.
136
137=back
138
139=item cf::attach_to_type $object_type, $subtype, ...
140
141Attach handlers for a specific object type (e.g. TRANSPORT) and
142subtype. If C<$subtype> is zero or undef, matches all objects of the given
143type.
144
145=item cf::attach_to_objects ...
146
147Attach handlers to all objects. Do not use this except for debugging or
148very rare events, as handlers are (obviously) called for I<all> objects in
149the game.
150
151=item cf::attach_to_players ...
152
153Attach handlers to all players.
154
155=item cf::attach_to_maps ...
156
157Attach handlers to all maps.
158
159=item cf:register_attachment $name, ...
160
161Register an attachment by name through which objects can refer to this
162attachment.
163
164=item cf:register_player_attachment $name, ...
165
166Register an attachment by name through which players can refer to this
167attachment.
168
169=item cf:register_map_attachment $name, ...
170
171Register an attachment by name through which maps can refer to this
172attachment.
173
174=cut
175
176# the following variables are defined in .xs and must not be re-created
177our @CB_GLOBAL = (); # registry for all global events
178our @CB_OBJECT = (); # all objects (should not be used except in emergency)
179our @CB_PLAYER = ();
180our @CB_TYPE = (); # registry for type (cf-object class) based events
181our @CB_MAP = ();
182
183my %attachment;
184
185sub _attach_cb($\%$$$) {
186 my ($registry, $undo, $event, $prio, $cb) = @_;
187
188 use sort 'stable';
189
190 $cb = [$prio, $cb];
191
192 @{$registry->[$event]} = sort
193 { $a->[0] cmp $b->[0] }
194 @{$registry->[$event] || []}, $cb;
195
196 push @{$undo->{cb}}, [$event, $cb];
197}
198
199# attach handles attaching event callbacks
200# the only thing the caller has to do is pass the correct
201# registry (== where the callback attaches to).
202sub _attach(\@$@) {
203 my ($registry, $klass, @arg) = @_;
204
205 my $prio = 0;
206
207 my %undo = (
208 registry => $registry,
209 cb => [],
210 );
211
212 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
213
214 while (@arg) {
215 my $type = shift @arg;
216
217 if ($type eq "prio") {
218 $prio = shift @arg;
219
220 } elsif ($type eq "package") {
221 my $pkg = shift @arg;
222
223 while (my ($name, $id) = each %cb_id) {
224 if (my $cb = $pkg->can ($name)) {
225 _attach_cb $registry, %undo, $id, $prio, $cb;
226 }
227 }
228
229 } elsif (exists $cb_id{$type}) {
230 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @arg;
231
232 } elsif (ref $type) {
233 warn "attaching objects not supported, ignoring.\n";
234
235 } else {
236 shift @arg;
237 warn "attach argument '$type' not supported, ignoring.\n";
238 }
239 }
240
241 \%undo
242}
243
244sub _attach_attachment {
245 my ($obj, $name, %arg) = @_;
246
247 return if exists $obj->{_attachment}{$name};
248
249 my $res;
250
251 if (my $attach = $attachment{$name}) {
252 my $registry = $obj->registry;
253
254 for (@$attach) {
255 my ($klass, @attach) = @$_;
256 $res = _attach @$registry, $klass, @attach;
257 }
258
259 $obj->{$name} = \%arg;
260 } else {
261 warn "object uses attachment '$name' that is not available, postponing.\n";
262 }
263
264 $obj->{_attachment}{$name} = undef;
265
266 $res->{attachment} = $name;
267 $res
268}
269
270*cf::object::attach =
271*cf::player::attach =
272*cf::map::attach = sub {
273 my ($obj, $name, %arg) = @_;
274
275 _attach_attachment $obj, $name, %arg;
276};
277
278# all those should be optimised
279*cf::object::detach =
280*cf::player::detach =
281*cf::map::detach = sub {
282 my ($obj, $name) = @_;
283
284 delete $obj->{_attachment}{$name};
285 reattach ($obj);
286};
287
288*cf::object::attached =
289*cf::player::attached =
290*cf::map::attached = sub {
291 my ($obj, $name) = @_;
292
293 exists $obj->{_attachment}{$name}
294};
295
296sub attach_global {
297 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
298}
299
300sub attach_to_type {
301 my $type = shift;
302 my $subtype = shift;
303
304 _attach @{$CB_TYPE[$type + $subtype * NUM_SUBTYPES]}, KLASS_OBJECT, @_
305}
306
307sub attach_to_objects {
308 _attach @CB_OBJECT, KLASS_OBJECT, @_
309}
310
311sub attach_to_players {
312 _attach @CB_PLAYER, KLASS_PLAYER, @_
313}
314
315sub attach_to_maps {
316 _attach @CB_MAP, KLASS_MAP, @_
317}
318
319sub register_attachment {
320 my $name = shift;
321
322 $attachment{$name} = [[KLASS_OBJECT, @_]];
323}
324
325sub register_player_attachment {
326 my $name = shift;
327
328 $attachment{$name} = [[KLASS_PLAYER, @_]];
329}
330
331sub register_map_attachment {
332 my $name = shift;
333
334 $attachment{$name} = [[KLASS_MAP, @_]];
335}
336
337our $override;
338our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
339
340sub override {
341 $override = 1;
342 @invoke_results = ();
343}
344
345sub do_invoke {
346 my $event = shift;
347 my $callbacks = shift;
348
349 @invoke_results = ();
350
351 local $override;
352
353 for (@$callbacks) {
354 eval { &{$_->[1]} };
355
356 if ($@) {
357 warn "$@";
358 warn "... while processing $EVENT[$event][0] event, skipping processing altogether.\n";
359 override;
360 }
361
362 return 1 if $override;
363 }
364
365 0
366}
367
368=item $bool = cf::invoke EVENT_GLOBAL_XXX, ...
369
370=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...)
371
372=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...)
373
374=item $bool = $map->invoke (EVENT_MAP_XXX, ...)
375
376Generate a global/object/player/map-specific event with the given arguments.
377
378This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be
379removed in future versions), and there is no public API to access override
380results (if you must, access C<@cf::invoke_results> directly).
381
382=back
383
384=head2 methods valid for all pointers
385
386=over 4
387
388=item $object->valid
389
390=item $player->valid
391
392=item $map->valid
393
394Just because you have a perl object does not mean that the corresponding
395C-level object still exists. If you try to access an object that has no
396valid C counterpart anymore you get an exception at runtime. This method
397can be used to test for existence of the C object part without causing an
398exception.
399
400=back
401
402=cut
403
404*cf::object::valid =
405*cf::player::valid =
406*cf::map::valid = \&cf::_valid;
407
408#############################################################################
409# object support
410
411sub instantiate {
412 my ($obj, $data) = @_;
413
414 $data = from_json $data;
415
416 for (@$data) {
417 my ($name, $args) = @$_;
418
419 $obj->attach ($name, %{$args || {} });
420 }
421}
422
423# basically do the same as instantiate, without calling instantiate
424sub reattach {
425 my ($obj) = @_;
426 my $registry = $obj->registry;
427
428 @$registry = ();
429
430 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} };
431
432 for my $name (keys %{ $obj->{_attachment} || {} }) {
433 if (my $attach = $attachment{$name}) {
434 for (@$attach) {
435 my ($klass, @attach) = @$_;
436 _attach @$registry, $klass, @attach;
437 }
438 } else {
439 warn "object uses attachment '$name' that is not available, postponing.\n";
440 }
441 }
442}
443
444sub object_freezer_save {
445 my ($filename, $rdata, $objs) = @_;
446
447 if (length $$rdata) {
448 warn sprintf "saving %s (%d,%d)\n",
449 $filename, length $$rdata, scalar @$objs;
450
451 if (open my $fh, ">:raw", "$filename~") {
452 chmod SAVE_MODE, $fh;
453 syswrite $fh, $$rdata;
454 close $fh;
455
456 if (@$objs && open my $fh, ">:raw", "$filename.pst~") {
457 chmod SAVE_MODE, $fh;
458 syswrite $fh, Storable::nfreeze { version => 1, objs => $objs };
459 close $fh;
460 rename "$filename.pst~", "$filename.pst";
461 } else {
462 unlink "$filename.pst";
463 }
464
465 rename "$filename~", $filename;
466 } else {
467 warn "FATAL: $filename~: $!\n";
468 }
469 } else {
470 unlink $filename;
471 unlink "$filename.pst";
472 }
473}
474
475sub object_thawer_load {
476 my ($filename) = @_;
477
478 local $/;
479
480 my $av;
481
482 #TODO: use sysread etc.
483 if (open my $data, "<:raw:perlio", $filename) {
484 $data = <$data>;
485 if (open my $pst, "<:raw:perlio", "$filename.pst") {
486 $av = eval { (Storable::thaw <$pst>)->{objs} };
487 }
488 return ($data, $av);
489 }
490
491 ()
492}
493
494attach_to_objects
495 prio => -1000000,
496 on_clone => sub {
497 my ($src, $dst) = @_;
498
499 @{$dst->registry} = @{$src->registry};
500
501 %$dst = %$src;
502
503 %{$dst->{_attachment}} = %{$src->{_attachment}}
504 if exists $src->{_attachment};
505 },
506;
507
508#############################################################################
509# old plug-in events
510
82sub inject_event { 511sub inject_event {
83 my $extension = shift; 512 my $extension = shift;
84 my $event_code = shift; 513 my $event_code = shift;
85 514
86 my $cb = $hook[$event_code]{$extension} 515 my $cb = $hook[$event_code]{$extension}
128} 557}
129 558
130sub register { 559sub register {
131 my ($base, $pkg) = @_; 560 my ($base, $pkg) = @_;
132 561
133 for my $idx (0 .. $#EVENT) { 562 #TODO
134 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) {
135 #warn "registering $EVENT[$idx] hook to '$pkg'\n";
136 $hook[$idx]{$base} = $ref;
137 }
138 }
139} 563}
140 564
141sub load_extension { 565sub load_extension {
142 my ($path) = @_; 566 my ($path) = @_;
143 567
144 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 568 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
145 my $base = $1; 569 my $base = $1;
146 my $pkg = $1; 570 my $pkg = $1;
147 $pkg =~ s/[^[:word:]]/_/g; 571 $pkg =~ s/[^[:word:]]/_/g;
148 $pkg = "cf::ext::$pkg"; 572 $pkg = "ext::$pkg";
149 573
150 warn "loading '$path' into '$pkg'\n"; 574 warn "loading '$path' into '$pkg'\n";
151 575
152 open my $fh, "<:utf8", $path 576 open my $fh, "<:utf8", $path
153 or die "$path: $!"; 577 or die "$path: $!";
173sub unload_extension { 597sub unload_extension {
174 my ($pkg) = @_; 598 my ($pkg) = @_;
175 599
176 warn "removing extension $pkg\n"; 600 warn "removing extension $pkg\n";
177 601
178 if (my $cb = $pkg->can ("on_unload")) {
179 $cb->($pkg);
180 }
181
182 # remove hooks 602 # remove hooks
603 #TODO
183 for my $idx (0 .. $#EVENT) { 604# for my $idx (0 .. $#PLUGIN_EVENT) {
184 delete $hook[$idx]{$pkg}; 605# delete $hook[$idx]{$pkg};
185 } 606# }
186 607
187 # remove commands 608 # remove commands
188 for my $name (keys %command) { 609 for my $name (keys %command) {
189 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} }; 610 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} };
190 611
200 # remove extcmds 621 # remove extcmds
201 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 622 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
202 delete $extcmd{$name}; 623 delete $extcmd{$name};
203 } 624 }
204 625
626 if (my $cb = $pkg->can ("unload")) {
627 eval {
628 $cb->($pkg);
629 1
630 } or warn "$pkg unloaded, but with errors: $@";
631 }
632
205 Symbol::delete_package $pkg; 633 Symbol::delete_package $pkg;
206} 634}
207 635
208sub load_extensions { 636sub load_extensions {
209 my $LIBDIR = maps_directory "perl"; 637 my $LIBDIR = maps_directory "perl";
215 1 643 1
216 } or warn "$ext not loaded: $@"; 644 } or warn "$ext not loaded: $@";
217 } 645 }
218} 646}
219 647
648sub _perl_reload(&) {
649 my ($msg) = @_;
650
651 $msg->("reloading...");
652
653 eval {
654 # 1. cancel all watchers
655 $_->cancel for Event::all_watchers;
656
657 # 2. unload all extensions
658 for (@exts) {
659 $msg->("unloading <$_>");
660 unload_extension $_;
661 }
662
663 # 3. unload all modules loaded from $LIBDIR
664 while (my ($k, $v) = each %INC) {
665 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
666
667 $msg->("removing <$k>");
668 delete $INC{$k};
669
670 $k =~ s/\.pm$//;
671 $k =~ s/\//::/g;
672
673 if (my $cb = $k->can ("unload_module")) {
674 $cb->();
675 }
676
677 Symbol::delete_package $k;
678 }
679
680 # 4. get rid of safe::, as good as possible
681 Symbol::delete_package "safe::$_"
682 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region);
683
684 # 5. remove register_script_function callbacks
685 # TODO
686
687 # 6. unload cf.pm "a bit"
688 delete $INC{"cf.pm"};
689
690 # don't, removes xs symbols, too,
691 # and global variables created in xs
692 #Symbol::delete_package __PACKAGE__;
693
694 # 7. reload cf.pm
695 $msg->("reloading cf.pm");
696 require cf;
697
698 $msg->("load extensions");
699 cf::load_extensions;
700
701 $msg->("reattach");
702 _global_reattach;
703 };
704 $msg->($@) if $@;
705
706 $msg->("reloaded");
707};
708
709sub perl_reload() {
710 _perl_reload {
711 warn $_[0];
712 print "$_[0]\n";
713 };
714}
715
220register_command "perl-reload", 0, sub { 716register_command "perl-reload", 0, sub {
221 my ($who, $arg) = @_; 717 my ($who, $arg) = @_;
222 718
223 if ($who->flag (FLAG_WIZ)) { 719 if ($who->flag (FLAG_WIZ)) {
224 $who->message ("reloading..."); 720 _perl_reload {
225 721 warn $_[0];
226 warn "reloading...\n"; 722 $who->message ($_[0]);
227 eval {
228 $_->cancel for Event::all_watchers;
229
230 unload_extension $_ for @exts;
231 delete $INC{"cf.pm"};
232
233 # don't, removes xs symbols, too
234 #Symbol::delete_package __PACKAGE__;
235
236 require cf;
237 }; 723 };
238 warn $@ if $@;
239 $who->message ($@) if $@;
240 warn "reloaded\n";
241
242 $who->message ("reloaded");
243 } else {
244 $who->message ("Intruder Alert!");
245 } 724 }
246}; 725};
247 726
248############################################################################# 727#############################################################################
249# extcmd framework, basically convert ext <id> <pkg> arg1 args 728# extcmd framework, basically convert ext <msg>
250# into pkg::->on_extcmd_arg1 (...) while shortcutting a few 729# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
251 730
252sub on_extcmd { 731attach_to_players
732 on_extcmd => sub {
253 my ($pl, $buf) = @_; 733 my ($pl, $buf) = @_;
254 734
255 my ($type) = $buf =~ s/^(\S+) // ? $1 : ""; 735 my $msg = eval { from_json $buf };
256 736
257 $extcmd{$type}[0]->($pl, $buf) 737 if (ref $msg) {
258 if $extcmd{$type}; 738 if (my $cb = $extcmd{$msg->{msgtype}}) {
259} 739 if (my %reply = $cb->[0]->($pl, $msg)) {
740 $pl->ext_reply ($msg->{msgid}, %reply);
741 }
742 }
743 } else {
744 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
745 }
746
747 cf::override;
748 },
749;
260 750
261############################################################################# 751#############################################################################
262# load/save/clean perl data associated with a map 752# load/save/clean perl data associated with a map
263 753
264*on_mapclean = sub { 754*cf::mapsupport::on_clean = sub {
265 my ($map) = @_; 755 my ($map) = @_;
266 756
267 my $path = $map->tmpname; 757 my $path = $map->tmpname;
268 defined $path or return; 758 defined $path or return;
269 759
270 unlink "$path.cfperl"; 760 unlink "$path.pst";
271}; 761};
272 762
273*on_mapin = 763attach_to_maps prio => -10000, package => cf::mapsupport::;
274*on_mapload = sub {
275 my ($map) = @_;
276
277 my $path = $map->tmpname;
278 $path = $map->path unless defined $path;
279
280 open my $fh, "<:raw", "$path.cfperl"
281 or return; # no perl data
282
283 my $data = Storable::thaw do { local $/; <$fh> };
284
285 $data->{version} <= 1
286 or return; # too new
287
288 $map->_set_obs ($data->{obs});
289};
290
291*on_mapout = sub {
292 my ($map) = @_;
293
294 my $path = $map->tmpname;
295 $path = $map->path unless defined $path;
296
297 my $obs = $map->_get_obs;
298
299 if (defined $obs) {
300 open my $fh, ">:raw", "$path.cfperl"
301 or die "$path.cfperl: $!";
302
303 stat $path;
304
305 print $fh Storable::nfreeze {
306 size => (stat _)[7],
307 time => (stat _)[9],
308 version => 1,
309 obs => $obs,
310 };
311
312 chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g*
313 } else {
314 unlink "$path.cfperl";
315 }
316};
317 764
318############################################################################# 765#############################################################################
319# load/save perl data associated with player->ob objects 766# load/save perl data associated with player->ob objects
320 767
321*on_player_load = sub { 768sub all_objects(@) {
769 @_, map all_objects ($_->inv), @_
770}
771
772# TODO: compatibility cruft, remove when no longer needed
773attach_to_players
774 on_load => sub {
322 my ($ob, $path) = @_; 775 my ($pl, $path) = @_;
323 776
324 if (open my $fh, "<:raw", "$path.cfperl") { 777 for my $o (all_objects $pl->ob) {
325
326 #d##TODO#remove
327
328 my $data = Storable::thaw do { local $/; <$fh> };
329
330 $data->{version} <= 1
331 or return; # too new
332
333 %$ob = %{$data->{ob}};
334 return;
335 }
336
337 for my $o ($ob, $ob->inv) {
338 if (my $value = $o->get_ob_key_value ("_perl_data")) { 778 if (my $value = $o->get_ob_key_value ("_perl_data")) {
339 $o->set_ob_key_value ("_perl_data"); 779 $o->set_ob_key_value ("_perl_data");
340 780
341 %$o = %{ Storable::thaw pack "H*", $value }; 781 %$o = %{ Storable::thaw pack "H*", $value };
342 } 782 }
783 }
343 } 784 },
344}; 785;
345
346*on_player_save = sub {
347 my ($ob, $path) = @_;
348
349 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
350 for grep %$_, $ob, $ob->inv;
351
352 unlink "$path.cfperl";#d##TODO#remove
353};
354 786
355############################################################################# 787#############################################################################
356# core extensions - in perl 788# core extensions - in perl
357 789
358=item cf::player::exists $login 790=item cf::player::exists $login
363 795
364sub cf::player::exists($) { 796sub cf::player::exists($) {
365 cf::player::find $_[0] 797 cf::player::find $_[0]
366 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 798 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
367} 799}
800
801=item $player->reply ($npc, $msg[, $flags])
802
803Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
804can be C<undef>. Does the right thing when the player is currently in a
805dialogue with the given NPC character.
806
807=cut
368 808
369# rough implementation of a future "reply" method that works 809# rough implementation of a future "reply" method that works
370# with dialog boxes. 810# with dialog boxes.
371sub cf::object::player::reply($$$;$) { 811sub cf::object::player::reply($$$;$) {
372 my ($self, $npc, $msg, $flags) = @_; 812 my ($self, $npc, $msg, $flags) = @_;
379 $msg = $npc->name . " says: $msg" if $npc; 819 $msg = $npc->name . " says: $msg" if $npc;
380 $self->message ($msg, $flags); 820 $self->message ($msg, $flags);
381 } 821 }
382} 822}
383 823
824=item $player->ext_reply ($msgid, $msgtype, %msg)
825
826Sends an ext reply to the player.
827
828=cut
829
830sub cf::player::ext_reply($$$%) {
831 my ($self, $id, %msg) = @_;
832
833 $msg{msgid} = $id;
834
835 $self->send ("ext " . to_json \%msg);
836}
837
384############################################################################# 838#############################################################################
385# map scripting support 839# map scripting support
386 840
387our $safe = new Safe "ext"; 841our $safe = new Safe "safe";
388our $safe_hole = new Safe::Hole; 842our $safe_hole = new Safe::Hole;
389 843
390$SIG{FPE} = 'IGNORE'; 844$SIG{FPE} = 'IGNORE';
391 845
392$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 846$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
393 847
394# here we would export the classes and methods available to script code 848# here we export the classes and methods available to script code
395#@ext::cf::object::player::ISA = @cf::object::player::ISA; 849
396#@ext::cf::object::map::ISA = @cf::object::map::ISA; 850for (
851 ["cf::object" => qw(contr pay_amount pay_player)],
852 ["cf::object::player" => qw(player)],
853 ["cf::player" => qw(peaceful)],
854) {
855 no strict 'refs';
856 my ($pkg, @funs) = @$_;
857 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
858 for @funs;
859}
397 860
398sub safe_eval($;@) { 861sub safe_eval($;@) {
399 my ($code, %vars) = @_; 862 my ($code, %vars) = @_;
400 863
401 my $qcode = $code; 864 my $qcode = $code;
402 $qcode =~ s/"/‟/g; # not allowed in #line filenames 865 $qcode =~ s/"/‟/g; # not allowed in #line filenames
403 $qcode =~ s/\n/\\n/g; 866 $qcode =~ s/\n/\\n/g;
404 867
405 local $_; 868 local $_;
406 local @ext::cf::_safe_eval_args = values %vars; 869 local @safe::cf::_safe_eval_args = values %vars;
407 870
408 $safe->reval ( 871 my $eval =
409 "do {\n" 872 "do {\n"
410 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 873 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
411 . "#line 0 \"{$qcode}\"\n" 874 . "#line 0 \"{$qcode}\"\n"
412 . $code 875 . $code
413 . "\n}" 876 . "\n}"
414 ) 877 ;
878
879 sub_generation_inc;
880 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
881 sub_generation_inc;
882
883 if ($@) {
884 warn "$@";
885 warn "while executing safe code '$code'\n";
886 warn "with arguments " . (join " ", %vars) . "\n";
887 }
888
889 wantarray ? @res : $res[0]
415} 890}
416 891
417sub register_script_function { 892sub register_script_function {
418 my ($fun, $cb) = @_; 893 my ($fun, $cb) = @_;
419 894
420 no strict 'refs'; 895 no strict 'refs';
421 *{"ext::$fun"} = $safe_hole->wrap ($cb); 896 *{"safe::$fun"} = $safe_hole->wrap ($cb);
897}
898
899#############################################################################
900# the server's main()
901
902sub main {
903 load_extensions;
904 Event::loop;
422} 905}
423 906
424############################################################################# 907#############################################################################
425# initialisation 908# initialisation
426 909
427register "<global>", __PACKAGE__; 910register "<global>", __PACKAGE__;
428 911
429unshift @INC, maps_directory "perl"; 912unshift @INC, $LIBDIR;
430 913
431load_extensions; 914$TICK_WATCHER = Event->timer (
915 prio => 1,
916 at => $NEXT_TICK || 1,
917 cb => sub {
918 cf::server_tick; # one server iteration
919
920 my $NOW = Event::time;
921 $NEXT_TICK += $TICK;
922
923 # if we are delayed by four ticks, skip them all
924 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
925
926 $TICK_WATCHER->at ($NEXT_TICK);
927 $TICK_WATCHER->start;
928 },
929);
432 930
4331 9311
434 932

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines