ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/lib/cf.pm
Revision: 1.44
Committed: Sat Aug 26 08:44:06 2006 UTC (17 years, 9 months ago) by root
Branch: MAIN
Changes since 1.43: +16 -1 lines
Log Message:
many, many cleanups

File Contents

# User Rev Content
1 root 1.1 package cf;
2    
3     use Symbol;
4     use List::Util;
5 root 1.6 use Storable;
6 root 1.23 use Opcode;
7     use Safe;
8     use Safe::Hole;
9 root 1.19
10 root 1.32 use Time::HiRes;
11 root 1.18 use Event;
12 root 1.19 $Event::Eval = 1; # no idea why this is required, but it is
13 root 1.1
14     use strict;
15    
16 root 1.39 our %COMMAND = ();
17 root 1.1 our @EVENT;
18 root 1.38 our @PLUGIN_EVENT;
19 root 1.1 our %PROP_TYPE;
20     our %PROP_IDX;
21 root 1.27 our $LIBDIR = maps_directory "perl";
22 root 1.1
23 root 1.35 our $TICK = MAX_TIME * 1e-6;
24     our $TICK_WATCHER;
25     our $NEXT_TICK;
26    
27 root 1.1 BEGIN {
28 root 1.38 @PLUGIN_EVENT = map lc, @PLUGIN_EVENT;
29 root 1.1
30     *CORE::GLOBAL::warn = sub {
31     my $msg = join "", @_;
32     $msg .= "\n"
33     unless $msg =~ /\n$/;
34    
35     print STDERR "cfperl: $msg";
36     LOG llevError, "cfperl: $msg";
37     };
38     }
39    
40 root 1.9 my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply!
41    
42 root 1.1 # generate property mutators
43     sub prop_gen {
44     my ($prefix, $class) = @_;
45    
46     no strict 'refs';
47    
48     for my $prop (keys %PROP_TYPE) {
49     $prop =~ /^\Q$prefix\E_(.*$)/ or next;
50     my $sub = lc $1;
51    
52     my $type = $PROP_TYPE{$prop};
53     my $idx = $PROP_IDX {$prop};
54    
55     *{"$class\::get_$sub"} = *{"$class\::$sub"} = sub {
56     $_[0]->get_property ($type, $idx)
57     };
58    
59     *{"$class\::set_$sub"} = sub {
60     $_[0]->set_property ($type, $idx, $_[1]);
61 root 1.9 } unless $ignore_set{$prop};
62 root 1.1 }
63     }
64    
65     # auto-generate most of the API
66    
67     prop_gen OBJECT_PROP => "cf::object";
68     # CFAPI_OBJECT_ANIMATION?
69     prop_gen PLAYER_PROP => "cf::object::player";
70    
71     prop_gen MAP_PROP => "cf::map";
72     prop_gen ARCH_PROP => "cf::arch";
73    
74     # guessed hierarchies
75    
76 root 1.41 @safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
77     @safe::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
78 root 1.25
79 root 1.41 # we bless all objects into (empty) derived classes to force a method lookup
80 root 1.25 # within the Safe compartment.
81 elmex 1.30 for my $pkg (qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region cf::arch)) {
82 root 1.25 no strict 'refs';
83 root 1.41 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
84 root 1.25 }
85 root 1.1
86 root 1.18 $Event::DIED = sub {
87     warn "error in event callback: @_";
88     };
89    
90 root 1.5 my %ext_pkg;
91 root 1.1 my @exts;
92     my @hook;
93     my %command;
94 root 1.15 my %extcmd;
95 root 1.1
96 root 1.39 #############################################################################
97 root 1.44 # object support
98    
99     sub reattach {
100     warn "reattach<@_>\n";
101     }
102    
103     sub instantiate {
104     warn "instantiate<@_>\n";
105     }
106    
107     sub clone {
108     warn "clone<@_>\n";
109     }
110    
111     #############################################################################
112 root 1.39 # "new" plug-in system
113    
114     =item cf::object::attach ... # NYI
115    
116 root 1.40 =item cf::attach_global ...
117 root 1.39
118 root 1.40 =item cf::attach_to_type ...
119 root 1.39
120 root 1.40 =item cf::attach_to_objects ...
121 root 1.39
122 root 1.40 =item cf::attach_to_players ...
123 root 1.39
124 root 1.40 =item cf::attach_to_maps ...
125 root 1.39
126 root 1.40 prio => $number, # lower is earlier
127 root 1.39 on_xxx => \&cb,
128     package => package::,
129    
130     =cut
131    
132 root 1.40 # the following variables are defined in .xs and must not be re-created
133 root 1.39 our @CB_GLOBAL = (); # registry for all global events
134 root 1.40 our @CB_OBJECT = ();
135     our @CB_PLAYER = ();
136 root 1.39 our @CB_TYPE = (); # registry for type (cf-object class) based events
137 root 1.40 our @CB_MAP = ();
138 root 1.39
139     sub _attach_cb($\%$$$) {
140     my ($registry, $undo, $event, $prio, $cb) = @_;
141    
142     use sort 'stable';
143    
144     $cb = [$prio, $cb];
145    
146     @{$registry->[$event]} = sort
147     { $a->[0] cmp $b->[0] }
148     @{$registry->[$event] || []}, $cb;
149    
150     push @{$undo->{cb}}, [$event, $cb];
151     }
152    
153     # attach handles attaching event callbacks
154     # the only thing the caller has to do is pass the correct
155     # registry (== where the callback attaches to).
156     sub _attach(\@$\@) {
157     my ($registry, $klass, $arg) = @_;
158    
159     my $prio = 0;
160    
161     my %undo = (
162     registry => $registry,
163     cb => [],
164     );
165    
166     my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
167    
168     while (@$arg) {
169     my $type = shift @$arg;
170    
171     if ($type eq "prio") {
172     $prio = shift @$arg;
173    
174     } elsif ($type eq "package") {
175     my $pkg = shift @$arg;
176    
177     while (my ($name, $id) = each %cb_id) {
178     if (my $cb = $pkg->can ($name)) {
179     _attach_cb $registry, %undo, $id, $prio, $cb;
180     }
181     }
182    
183     } elsif (exists $cb_id{$type}) {
184     _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @$arg;
185    
186     } elsif (ref $type) {
187     warn "attaching objects not supported, ignoring.\n";
188    
189     } else {
190     shift @$arg;
191     warn "attach argument '$type' not supported, ignoring.\n";
192     }
193     }
194    
195     \%undo
196     }
197    
198     sub cf::object::attach {
199     die;
200     }
201    
202     sub attach_global {
203     _attach @CB_GLOBAL, KLASS_GLOBAL, @_
204     }
205    
206 root 1.40 sub attach_to_type {
207 root 1.39 my $type = shift;
208 root 1.40 _attach @{$CB_TYPE[$type]}, KLASS_OBJECT, @_
209 root 1.39 }
210    
211     sub attach_to_objects {
212 root 1.40 _attach @CB_OBJECT, KLASS_OBJECT, @_
213 root 1.39 }
214    
215     sub attach_to_players {
216 root 1.40 _attach @CB_PLAYER, KLASS_PLAYER, @_
217 root 1.39 }
218    
219     sub attach_to_maps {
220 root 1.40 _attach @CB_MAP, KLASS_MAP, @_
221 root 1.39 }
222    
223     our $override;
224    
225     sub override() {
226     $override = 1
227     }
228    
229     sub invoke {
230     my $event = shift;
231 root 1.40 my $callbacks = shift;
232 root 1.39
233     local $override;
234    
235 root 1.40 for (@$callbacks) {
236 root 1.39 eval { &{$_->[1]} };
237    
238     if ($@) {
239     warn "$@";
240     warn "... while processing $EVENT[$event][0] event, skipping processing altogether.\n";
241     override;
242     }
243    
244     return 1 if $override;
245     }
246    
247     0
248     }
249    
250     #############################################################################
251     # old plug-in events
252    
253 root 1.1 sub inject_event {
254 root 1.14 my $extension = shift;
255     my $event_code = shift;
256 root 1.1
257 root 1.14 my $cb = $hook[$event_code]{$extension}
258 root 1.5 or return;
259    
260 root 1.14 &$cb
261 root 1.5 }
262    
263     sub inject_global_event {
264 root 1.12 my $event = shift;
265 root 1.5
266 root 1.12 my $cb = $hook[$event]
267 root 1.1 or return;
268    
269 root 1.12 List::Util::max map &$_, values %$cb
270 root 1.1 }
271    
272     sub inject_command {
273     my ($name, $obj, $params) = @_;
274    
275     for my $cmd (@{ $command{$name} }) {
276     $cmd->[1]->($obj, $params);
277     }
278    
279     -1
280     }
281    
282     sub register_command {
283     my ($name, $time, $cb) = @_;
284    
285     my $caller = caller;
286 root 1.16 #warn "registering command '$name/$time' to '$caller'";
287 root 1.4
288 root 1.1 push @{ $command{$name} }, [$time, $cb, $caller];
289     $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} };
290     }
291    
292 root 1.16 sub register_extcmd {
293     my ($name, $cb) = @_;
294    
295     my $caller = caller;
296     #warn "registering extcmd '$name' to '$caller'";
297    
298     $extcmd{$name} = [$cb, $caller];
299     }
300    
301 root 1.6 sub register {
302     my ($base, $pkg) = @_;
303    
304 root 1.38 for my $idx (0 .. $#PLUGIN_EVENT) {
305     if (my $ref = $pkg->can ("on_$PLUGIN_EVENT[$idx]")) {
306     #warn "registering $PLUGIN_EVENT[$idx] hook to '$pkg'\n";
307 root 1.6 $hook[$idx]{$base} = $ref;
308     }
309     }
310     }
311    
312 root 1.1 sub load_extension {
313     my ($path) = @_;
314    
315     $path =~ /([^\/\\]+)\.ext$/ or die "$path";
316 root 1.5 my $base = $1;
317 root 1.1 my $pkg = $1;
318     $pkg =~ s/[^[:word:]]/_/g;
319 root 1.41 $pkg = "ext::$pkg";
320 root 1.1
321     warn "loading '$path' into '$pkg'\n";
322    
323     open my $fh, "<:utf8", $path
324     or die "$path: $!";
325    
326     my $source =
327     "package $pkg; use strict; use utf8;\n"
328     . "#line 1 \"$path\"\n{\n"
329     . (do { local $/; <$fh> })
330     . "\n};\n1";
331    
332     eval $source
333     or die "$path: $@";
334    
335     push @exts, $pkg;
336 root 1.5 $ext_pkg{$base} = $pkg;
337 root 1.1
338 root 1.6 # no strict 'refs';
339 root 1.23 # @{"$pkg\::ISA"} = ext::;
340 root 1.1
341 root 1.6 register $base, $pkg;
342 root 1.1 }
343    
344     sub unload_extension {
345     my ($pkg) = @_;
346    
347     warn "removing extension $pkg\n";
348    
349     # remove hooks
350 root 1.38 for my $idx (0 .. $#PLUGIN_EVENT) {
351 root 1.1 delete $hook[$idx]{$pkg};
352     }
353    
354     # remove commands
355     for my $name (keys %command) {
356     my @cb = grep $_->[2] ne $pkg, @{ $command{$name} };
357    
358     if (@cb) {
359     $command{$name} = \@cb;
360     $COMMAND{"$name\000"} = List::Util::max map $_->[0], @cb;
361     } else {
362     delete $command{$name};
363     delete $COMMAND{"$name\000"};
364     }
365     }
366    
367 root 1.15 # remove extcmds
368 root 1.16 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
369     delete $extcmd{$name};
370 root 1.15 }
371    
372 root 1.43 if (my $cb = $pkg->can ("unload")) {
373 elmex 1.31 eval {
374     $cb->($pkg);
375     1
376     } or warn "$pkg unloaded, but with errors: $@";
377     }
378    
379 root 1.1 Symbol::delete_package $pkg;
380     }
381    
382     sub load_extensions {
383     my $LIBDIR = maps_directory "perl";
384    
385     for my $ext (<$LIBDIR/*.ext>) {
386 root 1.3 next unless -r $ext;
387 root 1.2 eval {
388     load_extension $ext;
389     1
390     } or warn "$ext not loaded: $@";
391 root 1.1 }
392     }
393    
394 root 1.36 sub _perl_reload(&) {
395     my ($msg) = @_;
396    
397     $msg->("reloading...");
398    
399     eval {
400     # 1. cancel all watchers
401     $_->cancel for Event::all_watchers;
402    
403     # 2. unload all extensions
404     for (@exts) {
405     $msg->("unloading <$_>");
406     unload_extension $_;
407     }
408    
409     # 3. unload all modules loaded from $LIBDIR
410     while (my ($k, $v) = each %INC) {
411     next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
412    
413     $msg->("removing <$k>");
414     delete $INC{$k};
415 root 1.1
416 root 1.36 $k =~ s/\.pm$//;
417     $k =~ s/\//::/g;
418 root 1.3
419 root 1.36 if (my $cb = $k->can ("unload_module")) {
420     $cb->();
421 root 1.27 }
422    
423 root 1.36 Symbol::delete_package $k;
424     }
425 root 1.27
426 root 1.41 # 4. get rid of safe::, as good as possible
427     Symbol::delete_package "safe::$_"
428 root 1.36 for qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region);
429    
430     # 5. remove register_script_function callbacks
431     # TODO
432    
433     # 6. unload cf.pm "a bit"
434     delete $INC{"cf.pm"};
435    
436 root 1.41 # don't, removes xs symbols, too,
437     # and global variables created in xs
438 root 1.36 #Symbol::delete_package __PACKAGE__;
439    
440     # 7. reload cf.pm
441     $msg->("reloading cf.pm");
442     require cf;
443     };
444     $msg->($@) if $@;
445 root 1.27
446 root 1.36 $msg->("reloaded");
447     };
448 root 1.27
449 root 1.36 sub perl_reload() {
450     _perl_reload {
451     warn $_[0];
452     print "$_[0]\n";
453     };
454     }
455 root 1.27
456 root 1.36 register_command "perl-reload", 0, sub {
457     my ($who, $arg) = @_;
458 root 1.27
459 root 1.36 if ($who->flag (FLAG_WIZ)) {
460     _perl_reload {
461     warn $_[0];
462     $who->message ($_[0]);
463 root 1.4 };
464 root 1.1 }
465     };
466    
467 root 1.8 #############################################################################
468 root 1.28 # utility functions
469    
470     use JSON::Syck (); # TODO# replace by JSON::PC once working
471    
472     sub from_json($) {
473 root 1.29 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
474 root 1.28 JSON::Syck::Load $_[0]
475     }
476    
477     sub to_json($) {
478 root 1.29 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
479 root 1.28 JSON::Syck::Dump $_[0]
480     }
481    
482     #############################################################################
483     # extcmd framework, basically convert ext <msg>
484 root 1.15 # into pkg::->on_extcmd_arg1 (...) while shortcutting a few
485    
486 root 1.44 attach_to_players
487 root 1.43 on_extcmd => sub {
488     my ($pl, $buf) = @_;
489    
490     my $msg = eval { from_json $buf };
491    
492     if (ref $msg) {
493     if (my $cb = $extcmd{$msg->{msgtype}}) {
494     if (my %reply = $cb->[0]->($pl, $msg)) {
495     $pl->ext_reply ($msg->{msgid}, %reply);
496     }
497 root 1.28 }
498 root 1.43 } else {
499     warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
500 root 1.28 }
501 root 1.15
502 root 1.43 cf::override;
503     },
504     ;
505 root 1.15
506     #############################################################################
507 root 1.8 # load/save/clean perl data associated with a map
508    
509 root 1.39 *cf::mapsupport::on_clean = sub {
510 root 1.13 my ($map) = @_;
511 root 1.7
512     my $path = $map->tmpname;
513     defined $path or return;
514    
515     unlink "$path.cfperl";
516     };
517    
518 root 1.39 *cf::mapsupport::on_swapin =
519     *cf::mapsupport::on_load = sub {
520 root 1.13 my ($map) = @_;
521 root 1.6
522     my $path = $map->tmpname;
523     $path = $map->path unless defined $path;
524    
525     open my $fh, "<:raw", "$path.cfperl"
526     or return; # no perl data
527    
528     my $data = Storable::thaw do { local $/; <$fh> };
529    
530     $data->{version} <= 1
531     or return; # too new
532    
533     $map->_set_obs ($data->{obs});
534     };
535    
536 root 1.39 *cf::mapsupport::on_swapout = sub {
537 root 1.13 my ($map) = @_;
538 root 1.6
539     my $path = $map->tmpname;
540     $path = $map->path unless defined $path;
541    
542     my $obs = $map->_get_obs;
543    
544     if (defined $obs) {
545     open my $fh, ">:raw", "$path.cfperl"
546     or die "$path.cfperl: $!";
547    
548 root 1.8 stat $path;
549    
550     print $fh Storable::nfreeze {
551     size => (stat _)[7],
552     time => (stat _)[9],
553     version => 1,
554     obs => $obs,
555     };
556    
557     chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g*
558     } else {
559     unlink "$path.cfperl";
560     }
561     };
562    
563 root 1.39 attach_to_maps prio => -10000, package => cf::mapsupport::;
564    
565 root 1.8 #############################################################################
566     # load/save perl data associated with player->ob objects
567    
568 root 1.33 sub all_objects(@) {
569     @_, map all_objects ($_->inv), @_
570     }
571    
572 root 1.39 attach_to_players
573     on_load => sub {
574     my ($pl, $path) = @_;
575    
576     for my $o (all_objects $pl->ob) {
577     if (my $value = $o->get_ob_key_value ("_perl_data")) {
578     $o->set_ob_key_value ("_perl_data");
579 root 1.8
580 root 1.39 %$o = %{ Storable::thaw pack "H*", $value };
581     }
582 root 1.11 }
583 root 1.39 },
584     on_save => sub {
585     my ($pl, $path) = @_;
586 root 1.8
587 root 1.39 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
588     for grep %$_, all_objects $pl->ob;
589     },
590     ;
591 root 1.6
592 root 1.22 #############################################################################
593     # core extensions - in perl
594    
595 root 1.23 =item cf::player::exists $login
596    
597     Returns true when the given account exists.
598    
599     =cut
600    
601     sub cf::player::exists($) {
602     cf::player::find $_[0]
603     or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
604     }
605    
606 root 1.28 =item $player->reply ($npc, $msg[, $flags])
607    
608     Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
609     can be C<undef>. Does the right thing when the player is currently in a
610     dialogue with the given NPC character.
611    
612     =cut
613    
614 root 1.22 # rough implementation of a future "reply" method that works
615     # with dialog boxes.
616 root 1.23 sub cf::object::player::reply($$$;$) {
617     my ($self, $npc, $msg, $flags) = @_;
618    
619     $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
620 root 1.22
621 root 1.24 if ($self->{record_replies}) {
622     push @{ $self->{record_replies} }, [$npc, $msg, $flags];
623     } else {
624     $msg = $npc->name . " says: $msg" if $npc;
625     $self->message ($msg, $flags);
626     }
627 root 1.22 }
628    
629 root 1.28 =item $player->ext_reply ($msgid, $msgtype, %msg)
630    
631     Sends an ext reply to the player.
632    
633     =cut
634    
635     sub cf::player::ext_reply($$$%) {
636     my ($self, $id, %msg) = @_;
637    
638     $msg{msgid} = $id;
639    
640     $self->send ("ext " . to_json \%msg);
641     }
642    
643 root 1.22 #############################################################################
644 root 1.23 # map scripting support
645    
646 root 1.42 our $safe = new Safe "safe";
647 root 1.23 our $safe_hole = new Safe::Hole;
648    
649     $SIG{FPE} = 'IGNORE';
650    
651     $safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
652    
653 root 1.25 # here we export the classes and methods available to script code
654    
655     for (
656 root 1.27 ["cf::object" => qw(contr pay_amount pay_player)],
657 root 1.25 ["cf::object::player" => qw(player)],
658     ["cf::player" => qw(peaceful)],
659     ) {
660     no strict 'refs';
661     my ($pkg, @funs) = @$_;
662 root 1.41 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
663 root 1.25 for @funs;
664     }
665 root 1.23
666     sub safe_eval($;@) {
667     my ($code, %vars) = @_;
668    
669     my $qcode = $code;
670     $qcode =~ s/"/‟/g; # not allowed in #line filenames
671     $qcode =~ s/\n/\\n/g;
672    
673     local $_;
674 root 1.41 local @safe::cf::_safe_eval_args = values %vars;
675 root 1.23
676 root 1.42 my $eval =
677 root 1.23 "do {\n"
678     . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
679     . "#line 0 \"{$qcode}\"\n"
680     . $code
681     . "\n}"
682 root 1.25 ;
683    
684     sub_generation_inc;
685 root 1.42 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
686 root 1.25 sub_generation_inc;
687    
688 root 1.42 if ($@) {
689     warn "$@";
690     warn "while executing safe code '$code'\n";
691     warn "with arguments " . (join " ", %vars) . "\n";
692     }
693    
694 root 1.25 wantarray ? @res : $res[0]
695 root 1.23 }
696    
697     sub register_script_function {
698     my ($fun, $cb) = @_;
699    
700     no strict 'refs';
701 root 1.41 *{"safe::$fun"} = $safe_hole->wrap ($cb);
702 root 1.23 }
703    
704     #############################################################################
705 root 1.34 # the server's main()
706    
707 root 1.39 sub main {
708 root 1.34 Event::loop;
709     }
710    
711     #############################################################################
712 root 1.22 # initialisation
713    
714 root 1.6 register "<global>", __PACKAGE__;
715    
716 root 1.27 unshift @INC, $LIBDIR;
717 root 1.17
718 root 1.1 load_extensions;
719    
720 root 1.35 $TICK_WATCHER = Event->timer (
721     prio => 1,
722     at => $NEXT_TICK || 1,
723     cb => sub {
724     cf::server_tick; # one server iteration
725    
726     my $NOW = Event::time;
727     $NEXT_TICK += $TICK;
728    
729 root 1.37 # if we are delayed by four ticks, skip them all
730     $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
731 root 1.35
732     $TICK_WATCHER->at ($NEXT_TICK);
733     $TICK_WATCHER->start;
734     },
735     );
736    
737 root 1.1 1
738