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.5 by root, Wed Feb 8 03:46:15 2006 UTC vs.
Revision 1.44 by root, Sat Aug 26 08:44:06 2006 UTC

1package cf; 1package cf;
2 2
3use Symbol; 3use Symbol;
4use List::Util; 4use List::Util;
5use Storable;
6use Opcode;
7use Safe;
8use Safe::Hole;
9
10use Time::HiRes;
11use Event;
12$Event::Eval = 1; # no idea why this is required, but it is
5 13
6use strict; 14use strict;
7 15
8our %COMMAND; 16our %COMMAND = ();
9our @EVENT; 17our @EVENT;
18our @PLUGIN_EVENT;
10our %PROP_TYPE; 19our %PROP_TYPE;
11our %PROP_IDX; 20our %PROP_IDX;
21our $LIBDIR = maps_directory "perl";
22
23our $TICK = MAX_TIME * 1e-6;
24our $TICK_WATCHER;
25our $NEXT_TICK;
12 26
13BEGIN { 27BEGIN {
14 @EVENT = map lc, @EVENT; 28 @PLUGIN_EVENT = map lc, @PLUGIN_EVENT;
15 29
16 *CORE::GLOBAL::warn = sub { 30 *CORE::GLOBAL::warn = sub {
17 my $msg = join "", @_; 31 my $msg = join "", @_;
18 $msg .= "\n" 32 $msg .= "\n"
19 unless $msg =~ /\n$/; 33 unless $msg =~ /\n$/;
21 print STDERR "cfperl: $msg"; 35 print STDERR "cfperl: $msg";
22 LOG llevError, "cfperl: $msg"; 36 LOG llevError, "cfperl: $msg";
23 }; 37 };
24} 38}
25 39
40my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply!
41
26# generate property mutators 42# generate property mutators
27sub prop_gen { 43sub prop_gen {
28 my ($prefix, $class) = @_; 44 my ($prefix, $class) = @_;
29 45
30 no strict 'refs'; 46 no strict 'refs';
40 $_[0]->get_property ($type, $idx) 56 $_[0]->get_property ($type, $idx)
41 }; 57 };
42 58
43 *{"$class\::set_$sub"} = sub { 59 *{"$class\::set_$sub"} = sub {
44 $_[0]->set_property ($type, $idx, $_[1]); 60 $_[0]->set_property ($type, $idx, $_[1]);
45 }; 61 } unless $ignore_set{$prop};
46 } 62 }
47} 63}
48 64
49# auto-generate most of the API 65# auto-generate most of the API
50 66
55prop_gen MAP_PROP => "cf::map"; 71prop_gen MAP_PROP => "cf::map";
56prop_gen ARCH_PROP => "cf::arch"; 72prop_gen ARCH_PROP => "cf::arch";
57 73
58# guessed hierarchies 74# guessed hierarchies
59 75
60@cf::object::player::ISA = 'cf::object'; 76@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
61@cf::object::map::ISA = 'cf::object'; 77@safe::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
78
79# we bless all objects into (empty) derived classes to force a method lookup
80# within the Safe compartment.
81for my $pkg (qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region cf::arch)) {
82 no strict 'refs';
83 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
84}
85
86$Event::DIED = sub {
87 warn "error in event callback: @_";
88};
62 89
63my %ext_pkg; 90my %ext_pkg;
64my @exts; 91my @exts;
65my @hook; 92my @hook;
66my %command; 93my %command;
94my %extcmd;
95
96#############################################################################
97# object support
98
99sub reattach {
100 warn "reattach<@_>\n";
101}
102
103sub instantiate {
104 warn "instantiate<@_>\n";
105}
106
107sub clone {
108 warn "clone<@_>\n";
109}
110
111#############################################################################
112# "new" plug-in system
113
114=item cf::object::attach ... # NYI
115
116=item cf::attach_global ...
117
118=item cf::attach_to_type ...
119
120=item cf::attach_to_objects ...
121
122=item cf::attach_to_players ...
123
124=item cf::attach_to_maps ...
125
126 prio => $number, # lower is earlier
127 on_xxx => \&cb,
128 package => package::,
129
130=cut
131
132# the following variables are defined in .xs and must not be re-created
133our @CB_GLOBAL = (); # registry for all global events
134our @CB_OBJECT = ();
135our @CB_PLAYER = ();
136our @CB_TYPE = (); # registry for type (cf-object class) based events
137our @CB_MAP = ();
138
139sub _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).
156sub _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
198sub cf::object::attach {
199 die;
200}
201
202sub attach_global {
203 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
204}
205
206sub attach_to_type {
207 my $type = shift;
208 _attach @{$CB_TYPE[$type]}, KLASS_OBJECT, @_
209}
210
211sub attach_to_objects {
212 _attach @CB_OBJECT, KLASS_OBJECT, @_
213}
214
215sub attach_to_players {
216 _attach @CB_PLAYER, KLASS_PLAYER, @_
217}
218
219sub attach_to_maps {
220 _attach @CB_MAP, KLASS_MAP, @_
221}
222
223our $override;
224
225sub override() {
226 $override = 1
227}
228
229sub invoke {
230 my $event = shift;
231 my $callbacks = shift;
232
233 local $override;
234
235 for (@$callbacks) {
236 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
67 252
68sub inject_event { 253sub inject_event {
69 my ($data) = @_; 254 my $extension = shift;
255 my $event_code = shift;
70 256
71 my $cb = $hook[$data->{event_code}]{$data->{extension}} 257 my $cb = $hook[$event_code]{$extension}
72 or return; 258 or return;
73 259
74 $cb->($data) 260 &$cb
75} 261}
76 262
77sub inject_global_event { 263sub inject_global_event {
78 my ($data) = @_; 264 my $event = shift;
79 265
80 my $cb = $hook[$data->{event_code}] 266 my $cb = $hook[$event]
81 or return; 267 or return;
82 268
83 $_->($data) for values %$cb; 269 List::Util::max map &$_, values %$cb
84
85 ()
86} 270}
87 271
88sub inject_command { 272sub inject_command {
89 my ($name, $obj, $params) = @_; 273 my ($name, $obj, $params) = @_;
90 274
97 281
98sub register_command { 282sub register_command {
99 my ($name, $time, $cb) = @_; 283 my ($name, $time, $cb) = @_;
100 284
101 my $caller = caller; 285 my $caller = caller;
102
103 warn "registering command '$name/$time' to '$caller'"; 286 #warn "registering command '$name/$time' to '$caller'";
104 287
105 push @{ $command{$name} }, [$time, $cb, $caller]; 288 push @{ $command{$name} }, [$time, $cb, $caller];
106 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} }; 289 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} };
290}
291
292sub 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
301sub register {
302 my ($base, $pkg) = @_;
303
304 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 $hook[$idx]{$base} = $ref;
308 }
309 }
107} 310}
108 311
109sub load_extension { 312sub load_extension {
110 my ($path) = @_; 313 my ($path) = @_;
111 314
112 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 315 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
113 my $base = $1; 316 my $base = $1;
114 my $pkg = $1; 317 my $pkg = $1;
115 $pkg =~ s/[^[:word:]]/_/g; 318 $pkg =~ s/[^[:word:]]/_/g;
116 $pkg = "cf::ext::$pkg"; 319 $pkg = "ext::$pkg";
117 320
118 warn "loading '$path' into '$pkg'\n"; 321 warn "loading '$path' into '$pkg'\n";
119 322
120 open my $fh, "<:utf8", $path 323 open my $fh, "<:utf8", $path
121 or die "$path: $!"; 324 or die "$path: $!";
130 or die "$path: $@"; 333 or die "$path: $@";
131 334
132 push @exts, $pkg; 335 push @exts, $pkg;
133 $ext_pkg{$base} = $pkg; 336 $ext_pkg{$base} = $pkg;
134 337
135 no strict 'refs'; 338# no strict 'refs';
136
137# @{"$pkg\::ISA"} = cf::ext::; 339# @{"$pkg\::ISA"} = ext::;
138 340
139 for my $idx (0 .. $#EVENT) { 341 register $base, $pkg;
140 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) {
141 warn "registering $EVENT[$idx] hook\n";
142 $hook[$idx]{$base} = $ref;
143 }
144 }
145} 342}
146 343
147sub unload_extension { 344sub unload_extension {
148 my ($pkg) = @_; 345 my ($pkg) = @_;
149 346
150 warn "removing extension $pkg\n"; 347 warn "removing extension $pkg\n";
151 348
152 # remove hooks 349 # remove hooks
153 for my $idx (0 .. $#EVENT) { 350 for my $idx (0 .. $#PLUGIN_EVENT) {
154 delete $hook[$idx]{$pkg}; 351 delete $hook[$idx]{$pkg};
155 } 352 }
156 353
157 # remove commands 354 # remove commands
158 for my $name (keys %command) { 355 for my $name (keys %command) {
165 delete $command{$name}; 362 delete $command{$name};
166 delete $COMMAND{"$name\000"}; 363 delete $COMMAND{"$name\000"};
167 } 364 }
168 } 365 }
169 366
367 # remove extcmds
368 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
369 delete $extcmd{$name};
370 }
371
372 if (my $cb = $pkg->can ("unload")) {
373 eval {
374 $cb->($pkg);
375 1
376 } or warn "$pkg unloaded, but with errors: $@";
377 }
378
170 Symbol::delete_package $pkg; 379 Symbol::delete_package $pkg;
171} 380}
172 381
173sub load_extensions { 382sub load_extensions {
174 my $LIBDIR = maps_directory "perl"; 383 my $LIBDIR = maps_directory "perl";
180 1 389 1
181 } or warn "$ext not loaded: $@"; 390 } or warn "$ext not loaded: $@";
182 } 391 }
183} 392}
184 393
394sub _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
416 $k =~ s/\.pm$//;
417 $k =~ s/\//::/g;
418
419 if (my $cb = $k->can ("unload_module")) {
420 $cb->();
421 }
422
423 Symbol::delete_package $k;
424 }
425
426 # 4. get rid of safe::, as good as possible
427 Symbol::delete_package "safe::$_"
428 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 # don't, removes xs symbols, too,
437 # and global variables created in xs
438 #Symbol::delete_package __PACKAGE__;
439
440 # 7. reload cf.pm
441 $msg->("reloading cf.pm");
442 require cf;
443 };
444 $msg->($@) if $@;
445
446 $msg->("reloaded");
447};
448
449sub perl_reload() {
450 _perl_reload {
451 warn $_[0];
452 print "$_[0]\n";
453 };
454}
455
185register_command "perl-reload", 0, sub { 456register_command "perl-reload", 0, sub {
186 my ($who, $arg) = @_; 457 my ($who, $arg) = @_;
187 458
188 if ($who->flag (FLAG_WIZ)) { 459 if ($who->flag (FLAG_WIZ)) {
189 $who->message ("reloading..."); 460 _perl_reload {
190 461 warn $_[0];
191 warn "reloading...\n"; 462 $who->message ($_[0]);
192 eval {
193 unload_extension $_ for @exts;
194 delete $INC{"cf.pm"};
195
196 # don't, removes xs symbols, too
197 #Symbol::delete_package $pkg;
198
199 require cf;
200 }; 463 };
201 warn $@ if $@; 464 }
202 $who->message ($@) if $@; 465};
203 warn "reloaded\n";
204 466
205 $who->message ("reloaded"); 467#############################################################################
468# utility functions
469
470use JSON::Syck (); # TODO# replace by JSON::PC once working
471
472sub from_json($) {
473 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
474 JSON::Syck::Load $_[0]
475}
476
477sub to_json($) {
478 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
479 JSON::Syck::Dump $_[0]
480}
481
482#############################################################################
483# extcmd framework, basically convert ext <msg>
484# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
485
486attach_to_players
487 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 }
498 } else {
499 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
500 }
501
502 cf::override;
503 },
504;
505
506#############################################################################
507# load/save/clean perl data associated with a map
508
509*cf::mapsupport::on_clean = sub {
510 my ($map) = @_;
511
512 my $path = $map->tmpname;
513 defined $path or return;
514
515 unlink "$path.cfperl";
516};
517
518*cf::mapsupport::on_swapin =
519*cf::mapsupport::on_load = sub {
520 my ($map) = @_;
521
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*cf::mapsupport::on_swapout = sub {
537 my ($map) = @_;
538
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 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*
206 } else { 558 } else {
207 $who->message ("Intruder Alert!"); 559 unlink "$path.cfperl";
208 } 560 }
209}; 561};
210 562
563attach_to_maps prio => -10000, package => cf::mapsupport::;
564
565#############################################################################
566# load/save perl data associated with player->ob objects
567
568sub all_objects(@) {
569 @_, map all_objects ($_->inv), @_
570}
571
572attach_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
580 %$o = %{ Storable::thaw pack "H*", $value };
581 }
582 }
583 },
584 on_save => sub {
585 my ($pl, $path) = @_;
586
587 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
588 for grep %$_, all_objects $pl->ob;
589 },
590;
591
592#############################################################################
593# core extensions - in perl
594
595=item cf::player::exists $login
596
597Returns true when the given account exists.
598
599=cut
600
601sub 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=item $player->reply ($npc, $msg[, $flags])
607
608Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
609can be C<undef>. Does the right thing when the player is currently in a
610dialogue with the given NPC character.
611
612=cut
613
614# rough implementation of a future "reply" method that works
615# with dialog boxes.
616sub cf::object::player::reply($$$;$) {
617 my ($self, $npc, $msg, $flags) = @_;
618
619 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
620
621 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}
628
629=item $player->ext_reply ($msgid, $msgtype, %msg)
630
631Sends an ext reply to the player.
632
633=cut
634
635sub 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#############################################################################
644# map scripting support
645
646our $safe = new Safe "safe";
647our $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# here we export the classes and methods available to script code
654
655for (
656 ["cf::object" => qw(contr pay_amount pay_player)],
657 ["cf::object::player" => qw(player)],
658 ["cf::player" => qw(peaceful)],
659) {
660 no strict 'refs';
661 my ($pkg, @funs) = @$_;
662 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
663 for @funs;
664}
665
666sub 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 local @safe::cf::_safe_eval_args = values %vars;
675
676 my $eval =
677 "do {\n"
678 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
679 . "#line 0 \"{$qcode}\"\n"
680 . $code
681 . "\n}"
682 ;
683
684 sub_generation_inc;
685 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
686 sub_generation_inc;
687
688 if ($@) {
689 warn "$@";
690 warn "while executing safe code '$code'\n";
691 warn "with arguments " . (join " ", %vars) . "\n";
692 }
693
694 wantarray ? @res : $res[0]
695}
696
697sub register_script_function {
698 my ($fun, $cb) = @_;
699
700 no strict 'refs';
701 *{"safe::$fun"} = $safe_hole->wrap ($cb);
702}
703
704#############################################################################
705# the server's main()
706
707sub main {
708 Event::loop;
709}
710
711#############################################################################
712# initialisation
713
714register "<global>", __PACKAGE__;
715
716unshift @INC, $LIBDIR;
717
211load_extensions; 718load_extensions;
212 719
720$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 # if we are delayed by four ticks, skip them all
730 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
731
732 $TICK_WATCHER->at ($NEXT_TICK);
733 $TICK_WATCHER->start;
734 },
735);
736
2131 7371
214 738

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines