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.9 by root, Fri Mar 17 03:22:00 2006 UTC vs.
Revision 1.38 by root, Thu Aug 24 17:29:30 2006 UTC

1package cf; 1package cf;
2 2
3use Symbol; 3use Symbol;
4use List::Util; 4use List::Util;
5use Storable; 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
6 13
7use strict; 14use strict;
8 15
9our %COMMAND; 16our %COMMAND;
10our @EVENT; 17our @EVENT;
18our @PLUGIN_EVENT;
11our %PROP_TYPE; 19our %PROP_TYPE;
12our %PROP_IDX; 20our %PROP_IDX;
21our $LIBDIR = maps_directory "perl";
22
23our $TICK = MAX_TIME * 1e-6;
24our $TICK_WATCHER;
25our $NEXT_TICK;
13 26
14BEGIN { 27BEGIN {
15 @EVENT = map lc, @EVENT; 28 @PLUGIN_EVENT = map lc, @PLUGIN_EVENT;
16 29
17 *CORE::GLOBAL::warn = sub { 30 *CORE::GLOBAL::warn = sub {
18 my $msg = join "", @_; 31 my $msg = join "", @_;
19 $msg .= "\n" 32 $msg .= "\n"
20 unless $msg =~ /\n$/; 33 unless $msg =~ /\n$/;
58prop_gen MAP_PROP => "cf::map"; 71prop_gen MAP_PROP => "cf::map";
59prop_gen ARCH_PROP => "cf::arch"; 72prop_gen ARCH_PROP => "cf::arch";
60 73
61# guessed hierarchies 74# guessed hierarchies
62 75
63@cf::object::player::ISA = 'cf::object'; 76@ext::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
64@cf::object::map::ISA = 'cf::object'; 77@ext::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
78
79# we bless all objects into 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 @{"ext::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
84}
85
86$Event::DIED = sub {
87 warn "error in event callback: @_";
88};
65 89
66my %ext_pkg; 90my %ext_pkg;
67my @exts; 91my @exts;
68my @hook; 92my @hook;
69my %command; 93my %command;
94my %extcmd;
70 95
71sub inject_event { 96sub inject_event {
72 my ($data) = @_; 97 my $extension = shift;
98 my $event_code = shift;
73 99
74 my $cb = $hook[$data->{event_code}]{$data->{extension}} 100 my $cb = $hook[$event_code]{$extension}
75 or return; 101 or return;
76 102
77 $cb->($data) 103 &$cb
78} 104}
79 105
80sub inject_global_event { 106sub inject_global_event {
81 my ($data) = @_; 107 my $event = shift;
82 108
83 my $cb = $hook[$data->{event_code}] 109 my $cb = $hook[$event]
84 or return; 110 or return;
85 111
86 $_->($data) for values %$cb; 112 List::Util::max map &$_, values %$cb
87
88 ()
89} 113}
90 114
91sub inject_command { 115sub inject_command {
92 my ($name, $obj, $params) = @_; 116 my ($name, $obj, $params) = @_;
93 117
100 124
101sub register_command { 125sub register_command {
102 my ($name, $time, $cb) = @_; 126 my ($name, $time, $cb) = @_;
103 127
104 my $caller = caller; 128 my $caller = caller;
105
106 warn "registering command '$name/$time' to '$caller'"; 129 #warn "registering command '$name/$time' to '$caller'";
107 130
108 push @{ $command{$name} }, [$time, $cb, $caller]; 131 push @{ $command{$name} }, [$time, $cb, $caller];
109 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} }; 132 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} };
110} 133}
111 134
135sub register_extcmd {
136 my ($name, $cb) = @_;
137
138 my $caller = caller;
139 #warn "registering extcmd '$name' to '$caller'";
140
141 $extcmd{$name} = [$cb, $caller];
142}
143
112sub register { 144sub register {
113 my ($base, $pkg) = @_; 145 my ($base, $pkg) = @_;
114 146
115 for my $idx (0 .. $#EVENT) { 147 for my $idx (0 .. $#PLUGIN_EVENT) {
116 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) { 148 if (my $ref = $pkg->can ("on_$PLUGIN_EVENT[$idx]")) {
117 warn "registering $EVENT[$idx] hook to '$pkg'\n"; 149 #warn "registering $PLUGIN_EVENT[$idx] hook to '$pkg'\n";
118 $hook[$idx]{$base} = $ref; 150 $hook[$idx]{$base} = $ref;
119 } 151 }
120 } 152 }
121} 153}
122 154
145 177
146 push @exts, $pkg; 178 push @exts, $pkg;
147 $ext_pkg{$base} = $pkg; 179 $ext_pkg{$base} = $pkg;
148 180
149# no strict 'refs'; 181# no strict 'refs';
150# @{"$pkg\::ISA"} = cf::ext::; 182# @{"$pkg\::ISA"} = ext::;
151 183
152 register $base, $pkg; 184 register $base, $pkg;
153} 185}
154 186
155sub unload_extension { 187sub unload_extension {
156 my ($pkg) = @_; 188 my ($pkg) = @_;
157 189
158 warn "removing extension $pkg\n"; 190 warn "removing extension $pkg\n";
159 191
160 # remove hooks 192 # remove hooks
161 for my $idx (0 .. $#EVENT) { 193 for my $idx (0 .. $#PLUGIN_EVENT) {
162 delete $hook[$idx]{$pkg}; 194 delete $hook[$idx]{$pkg};
163 } 195 }
164 196
165 # remove commands 197 # remove commands
166 for my $name (keys %command) { 198 for my $name (keys %command) {
173 delete $command{$name}; 205 delete $command{$name};
174 delete $COMMAND{"$name\000"}; 206 delete $COMMAND{"$name\000"};
175 } 207 }
176 } 208 }
177 209
210 # remove extcmds
211 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
212 delete $extcmd{$name};
213 }
214
215 if (my $cb = $pkg->can ("on_unload")) {
216 eval {
217 $cb->($pkg);
218 1
219 } or warn "$pkg unloaded, but with errors: $@";
220 }
221
178 Symbol::delete_package $pkg; 222 Symbol::delete_package $pkg;
179} 223}
180 224
181sub load_extensions { 225sub load_extensions {
182 my $LIBDIR = maps_directory "perl"; 226 my $LIBDIR = maps_directory "perl";
188 1 232 1
189 } or warn "$ext not loaded: $@"; 233 } or warn "$ext not loaded: $@";
190 } 234 }
191} 235}
192 236
237sub _perl_reload(&) {
238 my ($msg) = @_;
239
240 $msg->("reloading...");
241
242 eval {
243 # 1. cancel all watchers
244 $_->cancel for Event::all_watchers;
245
246 # 2. unload all extensions
247 for (@exts) {
248 $msg->("unloading <$_>");
249 unload_extension $_;
250 }
251
252 # 3. unload all modules loaded from $LIBDIR
253 while (my ($k, $v) = each %INC) {
254 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
255
256 $msg->("removing <$k>");
257 delete $INC{$k};
258
259 $k =~ s/\.pm$//;
260 $k =~ s/\//::/g;
261
262 if (my $cb = $k->can ("unload_module")) {
263 $cb->();
264 }
265
266 Symbol::delete_package $k;
267 }
268
269 # 4. get rid of ext::, as good as possible
270 Symbol::delete_package "ext::$_"
271 for qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region);
272
273 # 5. remove register_script_function callbacks
274 # TODO
275
276 # 6. unload cf.pm "a bit"
277 delete $INC{"cf.pm"};
278
279 # don't, removes xs symbols, too
280 #Symbol::delete_package __PACKAGE__;
281
282 # 7. reload cf.pm
283 $msg->("reloading cf.pm");
284 require cf;
285 };
286 $msg->($@) if $@;
287
288 $msg->("reloaded");
289};
290
291sub perl_reload() {
292 _perl_reload {
293 warn $_[0];
294 print "$_[0]\n";
295 };
296}
297
193register_command "perl-reload", 0, sub { 298register_command "perl-reload", 0, sub {
194 my ($who, $arg) = @_; 299 my ($who, $arg) = @_;
195 300
196 if ($who->flag (FLAG_WIZ)) { 301 if ($who->flag (FLAG_WIZ)) {
197 $who->message ("reloading..."); 302 _perl_reload {
198 303 warn $_[0];
199 warn "reloading...\n"; 304 $who->message ($_[0]);
200 eval {
201 unload_extension $_ for @exts;
202 delete $INC{"cf.pm"};
203
204 # don't, removes xs symbols, too
205 #Symbol::delete_package $pkg;
206
207 require cf;
208 }; 305 };
209 warn $@ if $@; 306 }
210 $who->message ($@) if $@; 307};
211 warn "reloaded\n";
212 308
213 $who->message ("reloaded"); 309#############################################################################
310# utility functions
311
312use JSON::Syck (); # TODO# replace by JSON::PC once working
313
314sub from_json($) {
315 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
316 JSON::Syck::Load $_[0]
317}
318
319sub to_json($) {
320 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
321 JSON::Syck::Dump $_[0]
322}
323
324#############################################################################
325# extcmd framework, basically convert ext <msg>
326# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
327
328sub on_extcmd {
329 my ($pl, $buf) = @_;
330
331 my $msg = eval { from_json $buf };
332
333 if (ref $msg) {
334 if (my $cb = $extcmd{$msg->{msgtype}}) {
335 if (my %reply = $cb->[0]->($pl, $msg)) {
336 $pl->ext_reply ($msg->{msgid}, %reply);
337 }
338 }
214 } else { 339 } else {
215 $who->message ("Intruder Alert!"); 340 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
341 }
342
216 } 343 1
217}; 344}
218 345
219############################################################################# 346#############################################################################
220# load/save/clean perl data associated with a map 347# load/save/clean perl data associated with a map
221 348
222*on_mapclean = sub { 349*on_mapclean = sub {
223 my $map = shift->{map}; 350 my ($map) = @_;
224 351
225 my $path = $map->tmpname; 352 my $path = $map->tmpname;
226 defined $path or return; 353 defined $path or return;
227 354
228 unlink "$path.cfperl"; 355 unlink "$path.cfperl";
229}; 356};
230 357
231*on_mapin = 358*on_mapin =
232*on_mapload = sub { 359*on_mapload = sub {
233 my $map = shift->{map}; 360 my ($map) = @_;
234 361
235 my $path = $map->tmpname; 362 my $path = $map->tmpname;
236 $path = $map->path unless defined $path; 363 $path = $map->path unless defined $path;
237 364
238 open my $fh, "<:raw", "$path.cfperl" 365 open my $fh, "<:raw", "$path.cfperl"
245 372
246 $map->_set_obs ($data->{obs}); 373 $map->_set_obs ($data->{obs});
247}; 374};
248 375
249*on_mapout = sub { 376*on_mapout = sub {
250 my $map = shift->{map}; 377 my ($map) = @_;
251 378
252 my $path = $map->tmpname; 379 my $path = $map->tmpname;
253 $path = $map->path unless defined $path; 380 $path = $map->path unless defined $path;
254 381
255 my $obs = $map->_get_obs; 382 my $obs = $map->_get_obs;
274}; 401};
275 402
276############################################################################# 403#############################################################################
277# load/save perl data associated with player->ob objects 404# load/save perl data associated with player->ob objects
278 405
406sub all_objects(@) {
407 @_, map all_objects ($_->inv), @_
408}
409
279*on_player_load = sub { 410*on_player_load = sub {
280 my ($event) = @_; 411 my ($ob, $path) = @_;
281 my $path = $event->{message};
282 my $ob = $event->{who};
283 412
284 open my $fh, "<:raw", "$path.cfperl" 413 for my $o (all_objects $ob) {
285 or return; # no perl data 414 if (my $value = $o->get_ob_key_value ("_perl_data")) {
415 $o->set_ob_key_value ("_perl_data");
286 416
287 my $data = Storable::thaw do { local $/; <$fh> }; 417 %$o = %{ Storable::thaw pack "H*", $value };
288 418 }
289 $data->{version} <= 1 419 }
290 or return; # too new
291
292 %$ob = %{$data->{ob}};
293}; 420};
294 421
295*on_player_save = sub { 422*on_player_save = sub {
296 my ($event) = @_; 423 my ($ob, $path) = @_;
297 my $path = $event->{message};
298 my $ob = $event->{who};
299 424
300 if (keys %$ob) { 425 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
301 open my $fh, ">:raw", "$path.cfperl" 426 for grep %$_, all_objects $ob;
302 or die "$path.cfperl: $!"; 427};
303 428
304 stat $path; 429#############################################################################
430# core extensions - in perl
305 431
306 print $fh Storable::nfreeze { 432=item cf::player::exists $login
307 size => (stat _)[7],
308 time => (stat _)[9],
309 version => 1,
310 ob => $ob,
311 };
312 433
313 chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g* 434Returns true when the given account exists.
435
436=cut
437
438sub cf::player::exists($) {
439 cf::player::find $_[0]
440 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
441}
442
443=item $player->reply ($npc, $msg[, $flags])
444
445Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
446can be C<undef>. Does the right thing when the player is currently in a
447dialogue with the given NPC character.
448
449=cut
450
451# rough implementation of a future "reply" method that works
452# with dialog boxes.
453sub cf::object::player::reply($$$;$) {
454 my ($self, $npc, $msg, $flags) = @_;
455
456 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
457
458 if ($self->{record_replies}) {
459 push @{ $self->{record_replies} }, [$npc, $msg, $flags];
314 } else { 460 } else {
315 unlink "$path.cfperl"; 461 $msg = $npc->name . " says: $msg" if $npc;
462 $self->message ($msg, $flags);
463 }
464}
465
466=item $player->ext_reply ($msgid, $msgtype, %msg)
467
468Sends an ext reply to the player.
469
470=cut
471
472sub cf::player::ext_reply($$$%) {
473 my ($self, $id, %msg) = @_;
474
475 $msg{msgid} = $id;
476
477 $self->send ("ext " . to_json \%msg);
478}
479
480#############################################################################
481# map scripting support
482
483our $safe = new Safe "ext";
484our $safe_hole = new Safe::Hole;
485
486$SIG{FPE} = 'IGNORE';
487
488$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
489
490# here we export the classes and methods available to script code
491
492for (
493 ["cf::object" => qw(contr pay_amount pay_player)],
494 ["cf::object::player" => qw(player)],
495 ["cf::player" => qw(peaceful)],
496) {
497 no strict 'refs';
498 my ($pkg, @funs) = @$_;
499 *{"ext::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
500 for @funs;
501}
502
503sub safe_eval($;@) {
504 my ($code, %vars) = @_;
505
506 my $qcode = $code;
507 $qcode =~ s/"/‟/g; # not allowed in #line filenames
508 $qcode =~ s/\n/\\n/g;
509
510 local $_;
511 local @ext::cf::_safe_eval_args = values %vars;
512
513 $code =
514 "do {\n"
515 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
516 . "#line 0 \"{$qcode}\"\n"
517 . $code
518 . "\n}"
316 } 519 ;
317}; 520
521 sub_generation_inc;
522 my @res = wantarray ? $safe->reval ($code) : scalar $safe->reval ($code);
523 sub_generation_inc;
524
525 wantarray ? @res : $res[0]
526}
527
528sub register_script_function {
529 my ($fun, $cb) = @_;
530
531 no strict 'refs';
532 *{"ext::$fun"} = $safe_hole->wrap ($cb);
533}
534
535#############################################################################
536# the server's main()
537
538sub run {
539 Event::loop;
540}
541
542#############################################################################
543# initialisation
318 544
319register "<global>", __PACKAGE__; 545register "<global>", __PACKAGE__;
320 546
547unshift @INC, $LIBDIR;
548
321load_extensions; 549load_extensions;
322 550
551$TICK_WATCHER = Event->timer (
552 prio => 1,
553 at => $NEXT_TICK || 1,
554 cb => sub {
555 cf::server_tick; # one server iteration
556
557 my $NOW = Event::time;
558 $NEXT_TICK += $TICK;
559
560 # if we are delayed by four ticks, skip them all
561 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
562
563 $TICK_WATCHER->at ($NEXT_TICK);
564 $TICK_WATCHER->start;
565 },
566);
567
3231 5681
324 569

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines