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.485 by root, Mon Oct 12 14:12:54 2009 UTC vs.
Revision 1.513 by root, Mon Apr 12 05:22:38 2010 UTC

1# 1#
2# This file is part of Deliantra, the Roguelike Realtime MMORPG. 2# This file is part of Deliantra, the Roguelike Realtime MMORPG.
3# 3#
4# Copyright (©) 2006,2007,2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team 4# Copyright (©) 2006,2007,2008,2009,2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5# 5#
6# Deliantra is free software: you can redistribute it and/or modify it under 6# Deliantra is free software: you can redistribute it and/or modify it under
7# the terms of the Affero GNU General Public License as published by the 7# the terms of the Affero GNU General Public License as published by the
8# Free Software Foundation, either version 3 of the License, or (at your 8# Free Software Foundation, either version 3 of the License, or (at your
9# option) any later version. 9# option) any later version.
32use EV; 32use EV;
33use Opcode; 33use Opcode;
34use Safe; 34use Safe;
35use Safe::Hole; 35use Safe::Hole;
36use Storable (); 36use Storable ();
37use Carp ();
37 38
38use Guard (); 39use Guard ();
39use Coro (); 40use Coro ();
40use Coro::State; 41use Coro::State;
41use Coro::Handle; 42use Coro::Handle;
52use Coro::Util (); 53use Coro::Util ();
53 54
54use JSON::XS 2.01 (); 55use JSON::XS 2.01 ();
55use BDB (); 56use BDB ();
56use Data::Dumper; 57use Data::Dumper;
57use Digest::MD5;
58use Fcntl; 58use Fcntl;
59use YAML::XS (); 59use YAML::XS ();
60use IO::AIO (); 60use IO::AIO ();
61use Time::HiRes; 61use Time::HiRes;
62use Compress::LZF; 62use Compress::LZF;
108our $PIDFILE = "$LOCALDIR/pid"; 108our $PIDFILE = "$LOCALDIR/pid";
109our $RUNTIMEFILE = "$LOCALDIR/runtime"; 109our $RUNTIMEFILE = "$LOCALDIR/runtime";
110 110
111our %RESOURCE; 111our %RESOURCE;
112 112
113our $OUTPUT_RATE_MIN = 4000;
114our $OUTPUT_RATE_MAX = 100000;
115
113our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 116our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
114our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 117our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
115our $NEXT_TICK; 118our $NEXT_TICK;
116our $USE_FSYNC = 1; # use fsync to write maps - default on 119our $USE_FSYNC = 1; # use fsync to write maps - default on
117 120
228returns directly I<after> the tick processing (and consequently, can only wake one process 231returns directly I<after> the tick processing (and consequently, can only wake one process
229per tick), while cf::wait_for_tick wakes up all waiters after tick processing. 232per tick), while cf::wait_for_tick wakes up all waiters after tick processing.
230 233
231=item @cf::INVOKE_RESULTS 234=item @cf::INVOKE_RESULTS
232 235
233This array contains the results of the last C<invoke ()> call. When 236This array contains the results of the last C<invoke ()> call. When
234C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of 237C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of
235that call. 238that call.
236 239
237=item %cf::REFLECT 240=item %cf::REFLECT
238 241
289)) { 292)) {
290 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 293 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
291} 294}
292 295
293$EV::DIED = sub { 296$EV::DIED = sub {
294 warn "error in event callback: @_"; 297 Carp::cluck "error in event callback: @_";
295}; 298};
296 299
297############################################################################# 300#############################################################################
298 301
299=head2 UTILITY FUNCTIONS 302=head2 UTILITY FUNCTIONS
423 426
424=cut 427=cut
425 428
426our @SLOT_QUEUE; 429our @SLOT_QUEUE;
427our $SLOT_QUEUE; 430our $SLOT_QUEUE;
431our $SLOT_DECAY = 0.9;
428 432
429$SLOT_QUEUE->cancel if $SLOT_QUEUE; 433$SLOT_QUEUE->cancel if $SLOT_QUEUE;
430$SLOT_QUEUE = Coro::async { 434$SLOT_QUEUE = Coro::async {
431 $Coro::current->desc ("timeslot manager"); 435 $Coro::current->desc ("timeslot manager");
432 436
433 my $signal = new Coro::Signal; 437 my $signal = new Coro::Signal;
438 my $busy;
434 439
435 while () { 440 while () {
436 next_job: 441 next_job:
442
437 my $avail = cf::till_tick; 443 my $avail = cf::till_tick;
438 if ($avail > 0.01) { 444
439 for (0 .. $#SLOT_QUEUE) { 445 for (0 .. $#SLOT_QUEUE) {
440 if ($SLOT_QUEUE[$_][0] < $avail) { 446 if ($SLOT_QUEUE[$_][0] <= $avail) {
447 $busy = 0;
441 my $job = splice @SLOT_QUEUE, $_, 1, (); 448 my $job = splice @SLOT_QUEUE, $_, 1, ();
442 $job->[2]->send; 449 $job->[2]->send;
443 Coro::cede; 450 Coro::cede;
444 goto next_job; 451 goto next_job;
445 } 452 } else {
453 $SLOT_QUEUE[$_][0] *= $SLOT_DECAY;
446 } 454 }
447 } 455 }
448 456
449 if (@SLOT_QUEUE) { 457 if (@SLOT_QUEUE) {
450 # we do not use wait_for_tick() as it returns immediately when tick is inactive 458 # we do not use wait_for_tick() as it returns immediately when tick is inactive
451 push @cf::WAIT_FOR_TICK, $signal; 459 push @cf::WAIT_FOR_TICK, $signal;
452 $signal->wait; 460 $signal->wait;
453 } else { 461 } else {
462 $busy = 0;
454 Coro::schedule; 463 Coro::schedule;
455 } 464 }
456 } 465 }
457}; 466};
458 467
459sub get_slot($;$$) { 468sub get_slot($;$$) {
460 return if tick_inhibit || $Coro::current == $Coro::main; 469 return if tick_inhibit || $Coro::current == $Coro::main;
461 470
462 my ($time, $pri, $name) = @_; 471 my ($time, $pri, $name) = @_;
463 472
464 $time = $TICK * .6 if $time > $TICK * .6; 473 $time = clamp $time, 0.01, $TICK * .6;
474
465 my $sig = new Coro::Signal; 475 my $sig = new Coro::Signal;
466 476
467 push @SLOT_QUEUE, [$time, $pri, $sig, $name]; 477 push @SLOT_QUEUE, [$time, $pri, $sig, $name];
468 @SLOT_QUEUE = sort { $b->[1] <=> $a->[1] } @SLOT_QUEUE; 478 @SLOT_QUEUE = sort { $b->[1] <=> $a->[1] } @SLOT_QUEUE;
469 $SLOT_QUEUE->ready; 479 $SLOT_QUEUE->ready;
496 506
497sub sync_job(&) { 507sub sync_job(&) {
498 my ($job) = @_; 508 my ($job) = @_;
499 509
500 if ($Coro::current == $Coro::main) { 510 if ($Coro::current == $Coro::main) {
501 my $time = EV::time; 511 my $time = AE::time;
502 512
503 # this is the main coro, too bad, we have to block 513 # this is the main coro, too bad, we have to block
504 # till the operation succeeds, freezing the server :/ 514 # till the operation succeeds, freezing the server :/
505 515
506 LOG llevError, Carp::longmess "sync job";#d# 516 LOG llevError, Carp::longmess "sync job";#d#
523 } else { 533 } else {
524 EV::loop EV::LOOP_ONESHOT; 534 EV::loop EV::LOOP_ONESHOT;
525 } 535 }
526 } 536 }
527 537
528 my $time = EV::time - $time; 538 my $time = AE::time - $time;
529 539
530 $TICK_START += $time; # do not account sync jobs to server load 540 $TICK_START += $time; # do not account sync jobs to server load
531 541
532 wantarray ? @res : $res[0] 542 wantarray ? @res : $res[0]
533 } else { 543 } else {
1303} 1313}
1304 1314
1305use File::Glob (); 1315use File::Glob ();
1306 1316
1307cf::player->attach ( 1317cf::player->attach (
1308 on_command => sub { 1318 on_unknown_command => sub {
1309 my ($pl, $name, $params) = @_; 1319 my ($pl, $name, $params) = @_;
1310 1320
1311 my $cb = $COMMAND{$name} 1321 my $cb = $COMMAND{$name}
1312 or return; 1322 or return;
1313 1323
1392 . "\n};\n1"; 1402 . "\n};\n1";
1393 1403
1394 $todo{$base} = \%ext; 1404 $todo{$base} = \%ext;
1395 } 1405 }
1396 1406
1407 my $pass = 0;
1397 my %done; 1408 my %done;
1398 while (%todo) { 1409 while (%todo) {
1399 my $progress; 1410 my $progress;
1400 1411
1412 ++$pass;
1413
1414 ext:
1401 while (my ($k, $v) = each %todo) { 1415 while (my ($k, $v) = each %todo) {
1402 for (split /,\s*/, $v->{meta}{depends}) { 1416 for (split /,\s*/, $v->{meta}{depends}) {
1403 goto skip 1417 next ext
1404 unless exists $done{$_}; 1418 unless exists $done{$_};
1405 } 1419 }
1406 1420
1407 warn "... loading '$k' into '$v->{pkg}'\n"; 1421 warn "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1408 1422
1409 unless (eval $v->{source}) { 1423 my $active = eval $v->{source};
1424
1425 if (length $@) {
1410 my $msg = $@ ? "$v->{path}: $@\n" 1426 warn "$v->{path}: $@\n";
1411 : "$v->{base}: extension inactive.\n";
1412 1427
1413 if (exists $v->{meta}{mandatory}) {
1414 warn $msg;
1415 cf::cleanup "mandatory extension failed to load, exiting."; 1428 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1416 } 1429 if exists $v->{meta}{mandatory};
1417 1430 } else {
1418 warn $msg; 1431 $done{$k} = delete $todo{$k};
1432 push @EXTS, $v->{pkg};
1433 $progress = 1;
1434
1435 warn "$v->{base}: extension inactive.\n"
1436 unless $active;
1419 } 1437 }
1420
1421 $done{$k} = delete $todo{$k};
1422 push @EXTS, $v->{pkg};
1423 $progress = 1;
1424 } 1438 }
1425 1439
1426 skip: 1440 unless ($progress) {
1427 die "cannot load " . (join ", ", keys %todo) . ": unable to resolve dependencies\n" 1441 warn "cannot load " . (join ", ", keys %todo) . ": unable to resolve dependencies\n";
1428 unless $progress; 1442
1443 while (my ($k, $v) = each %todo) {
1444 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting."
1445 if exists $v->{meta}{mandatory};
1446 }
1447 }
1429 } 1448 }
1430 }; 1449 };
1431} 1450}
1432 1451
1433############################################################################# 1452#############################################################################
1517 $cf::PLAYER{$login} = $pl 1536 $cf::PLAYER{$login} = $pl
1518 } 1537 }
1519 } 1538 }
1520} 1539}
1521 1540
1541cf::player->attach (
1542 on_load => sub {
1543 my ($pl, $path) = @_;
1544
1545 # restore slots saved in save, below
1546 my $slots = delete $pl->{_slots};
1547
1548 $pl->ob->current_weapon ($slots->[0]);
1549 $pl->combat_ob ($slots->[1]);
1550 $pl->ranged_ob ($slots->[2]);
1551 },
1552);
1553
1522sub save($) { 1554sub save($) {
1523 my ($pl) = @_; 1555 my ($pl) = @_;
1524 1556
1525 return if $pl->{deny_save}; 1557 return if $pl->{deny_save};
1526 1558
1531 1563
1532 aio_mkdir playerdir $pl, 0770; 1564 aio_mkdir playerdir $pl, 0770;
1533 $pl->{last_save} = $cf::RUNTIME; 1565 $pl->{last_save} = $cf::RUNTIME;
1534 1566
1535 cf::get_slot 0.01; 1567 cf::get_slot 0.01;
1568
1569 # save slots, to be restored later
1570 local $pl->{_slots} = [$pl->ob->current_weapon, $pl->combat_ob, $pl->ranged_ob];
1536 1571
1537 $pl->save_pl ($path); 1572 $pl->save_pl ($path);
1538 cf::cede_to_tick; 1573 cf::cede_to_tick;
1539} 1574}
1540 1575
1753 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM 1788 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM
1754 1789
1755 # mit "rum" bekleckern, nicht 1790 # mit "rum" bekleckern, nicht
1756 $self->_create_random_map ( 1791 $self->_create_random_map (
1757 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle}, 1792 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1758 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, 1793 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, $rmp->{miningstyle},
1759 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map}, 1794 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1760 $rmp->{exit_on_final_map}, 1795 $rmp->{exit_on_final_map},
1761 $rmp->{xsize}, $rmp->{ysize}, 1796 $rmp->{xsize}, $rmp->{ysize},
1762 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3}, 1797 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3},
1763 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase}, 1798 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase},
2009 2044
2010 $cf::MAP{$path} = $map 2045 $cf::MAP{$path} = $map
2011 } 2046 }
2012} 2047}
2013 2048
2014sub pre_load { } 2049sub pre_load { }
2015sub post_load { } 2050#sub post_load { } # XS
2016 2051
2017sub load { 2052sub load {
2018 my ($self) = @_; 2053 my ($self) = @_;
2019 2054
2020 local $self->{deny_reset} = 1; # loading can take a long time 2055 local $self->{deny_reset} = 1; # loading can take a long time
2077 } 2112 }
2078 2113
2079 $self->post_load; 2114 $self->post_load;
2080} 2115}
2081 2116
2117# customize the map for a given player, i.e.
2118# return the _real_ map. used by e.g. per-player
2119# maps to change the path to ~playername/mappath
2082sub customise_for { 2120sub customise_for {
2083 my ($self, $ob) = @_; 2121 my ($self, $ob) = @_;
2084 2122
2085 return find "~" . $ob->name . "/" . $self->{path} 2123 return find "~" . $ob->name . "/" . $self->{path}
2086 if $self->per_player; 2124 if $self->per_player;
2341 : normalise $_ 2379 : normalise $_
2342 } @{ aio_readdir $UNIQUEDIR or [] } 2380 } @{ aio_readdir $UNIQUEDIR or [] }
2343 ] 2381 ]
2344} 2382}
2345 2383
2384=item cf::map::static_maps
2385
2386Returns an arrayref if paths of all static maps (all preinstalled F<.map>
2387file in the shared directory excluding F</styles> and F</editor>). May
2388block.
2389
2390=cut
2391
2392sub static_maps() {
2393 my @dirs = "";
2394 my @maps;
2395
2396 while (@dirs) {
2397 my $dir = shift @dirs;
2398
2399 next if $dir eq "/styles" || $dir eq "/editor";
2400
2401 my ($dirs, $files) = Coro::AIO::aio_scandir "$MAPDIR$dir", 2
2402 or return;
2403
2404 for (@$files) {
2405 s/\.map$// or next;
2406 utf8::decode $_;
2407 push @maps, "$dir/$_";
2408 }
2409
2410 push @dirs, map "$dir/$_", @$dirs;
2411 }
2412
2413 \@maps
2414}
2415
2346=back 2416=back
2347 2417
2348=head3 cf::object 2418=head3 cf::object
2349 2419
2350=cut 2420=cut
2545 ($x, $y) = (-1, -1) 2615 ($x, $y) = (-1, -1)
2546 unless (defined $x) && (defined $y); 2616 unless (defined $x) && (defined $y);
2547 2617
2548 # use -1 or undef as default coordinates, not 0, 0 2618 # use -1 or undef as default coordinates, not 0, 0
2549 ($x, $y) = ($map->enter_x, $map->enter_y) 2619 ($x, $y) = ($map->enter_x, $map->enter_y)
2550 if $x <=0 && $y <= 0; 2620 if $x <= 0 && $y <= 0;
2551 2621
2552 $map->load; 2622 $map->load;
2553 $map->load_neighbours; 2623 $map->load_neighbours;
2554 2624
2555 return unless $self->contr->active; 2625 return unless $self->contr->active;
2754 2824
2755 utf8::encode $text; 2825 utf8::encode $text;
2756 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text); 2826 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text);
2757} 2827}
2758 2828
2829=item $client->send_big_packet ($pkt)
2830
2831Like C<send_packet>, but tries to compress large packets, and fragments
2832them as required.
2833
2834=cut
2835
2836our $MAXFRAGSIZE = cf::MAXSOCKBUF - 64;
2837
2838sub cf::client::send_big_packet {
2839 my ($self, $pkt) = @_;
2840
2841 # try lzf for large packets
2842 $pkt = "lzf " . Compress::LZF::compress $pkt
2843 if 1024 <= length $pkt and $self->{can_lzf};
2844
2845 # split very large packets
2846 if ($MAXFRAGSIZE < length $pkt and $self->{can_lzf}) {
2847 $self->send_packet ("frag $_") for unpack "(a$MAXFRAGSIZE)*", $pkt;
2848 $pkt = "frag";
2849 }
2850
2851 $self->send_packet ($pkt);
2852}
2853
2759=item $client->send_msg ($channel, $msg, $color, [extra...]) 2854=item $client->send_msg ($channel, $msg, $color, [extra...])
2760 2855
2761Send a drawinfo or msg packet to the client, formatting the msg for the 2856Send a drawinfo or msg packet to the client, formatting the msg for the
2762client if neccessary. C<$type> should be a string identifying the type of 2857client if neccessary. C<$type> should be a string identifying the type of
2763the message, with C<log> being the default. If C<$color> is negative, suppress 2858the message, with C<log> being the default. If C<$color> is negative, suppress
2765 2860
2766=cut 2861=cut
2767 2862
2768# non-persistent channels (usually the info channel) 2863# non-persistent channels (usually the info channel)
2769our %CHANNEL = ( 2864our %CHANNEL = (
2865 "c/motd" => {
2866 id => "infobox",
2867 title => "MOTD",
2868 reply => undef,
2869 tooltip => "The message of the day",
2870 },
2770 "c/identify" => { 2871 "c/identify" => {
2771 id => "infobox", 2872 id => "infobox",
2772 title => "Identify", 2873 title => "Identify",
2773 reply => undef, 2874 reply => undef,
2774 tooltip => "Items recently identified", 2875 tooltip => "Items recently identified",
2776 "c/examine" => { 2877 "c/examine" => {
2777 id => "infobox", 2878 id => "infobox",
2778 title => "Examine", 2879 title => "Examine",
2779 reply => undef, 2880 reply => undef,
2780 tooltip => "Signs and other items you examined", 2881 tooltip => "Signs and other items you examined",
2882 },
2883 "c/shopinfo" => {
2884 id => "infobox",
2885 title => "Shop Info",
2886 reply => undef,
2887 tooltip => "What your bargaining skill tells you about the shop",
2781 }, 2888 },
2782 "c/book" => { 2889 "c/book" => {
2783 id => "infobox", 2890 id => "infobox",
2784 title => "Book", 2891 title => "Book",
2785 reply => undef, 2892 reply => undef,
2901 my $pkt = "msg " 3008 my $pkt = "msg "
2902 . $self->{json_coder}->encode ( 3009 . $self->{json_coder}->encode (
2903 [$color & cf::NDI_CLIENT_MASK, $channel, $msg, @extra] 3010 [$color & cf::NDI_CLIENT_MASK, $channel, $msg, @extra]
2904 ); 3011 );
2905 3012
2906 # try lzf for large packets
2907 $pkt = "lzf " . Compress::LZF::compress $pkt
2908 if 1024 <= length $pkt and $self->{can_lzf};
2909
2910 # split very large packets
2911 if (8192 < length $pkt and $self->{can_lzf}) {
2912 $self->send_packet ("frag $_") for unpack "(a8192)*", $pkt;
2913 $pkt = "frag";
2914 }
2915
2916 $self->send_packet ($pkt); 3013 $self->send_big_packet ($pkt);
2917} 3014}
2918 3015
2919=item $client->ext_msg ($type, @msg) 3016=item $client->ext_msg ($type, @msg)
2920 3017
2921Sends an ext event to the client. 3018Sends an ext event to the client.
2924 3021
2925sub cf::client::ext_msg($$@) { 3022sub cf::client::ext_msg($$@) {
2926 my ($self, $type, @msg) = @_; 3023 my ($self, $type, @msg) = @_;
2927 3024
2928 if ($self->extcmd == 2) { 3025 if ($self->extcmd == 2) {
2929 $self->send_packet ("ext " . $self->{json_coder}->encode ([$type, @msg])); 3026 $self->send_big_packet ("ext " . $self->{json_coder}->encode ([$type, @msg]));
2930 } elsif ($self->extcmd == 1) { # TODO: remove 3027 } elsif ($self->extcmd == 1) { # TODO: remove
2931 push @msg, msgtype => "event_$type"; 3028 push @msg, msgtype => "event_$type";
2932 $self->send_packet ("ext " . $self->{json_coder}->encode ({@msg})); 3029 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
2933 } 3030 }
2934} 3031}
2935 3032
2936=item $client->ext_reply ($msgid, @msg) 3033=item $client->ext_reply ($msgid, @msg)
2937 3034
2941 3038
2942sub cf::client::ext_reply($$@) { 3039sub cf::client::ext_reply($$@) {
2943 my ($self, $id, @msg) = @_; 3040 my ($self, $id, @msg) = @_;
2944 3041
2945 if ($self->extcmd == 2) { 3042 if ($self->extcmd == 2) {
2946 $self->send_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg])); 3043 $self->send_big_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg]));
2947 } elsif ($self->extcmd == 1) { 3044 } elsif ($self->extcmd == 1) {
2948 #TODO: version 1, remove 3045 #TODO: version 1, remove
2949 unshift @msg, msgtype => "reply", msgid => $id; 3046 unshift @msg, msgtype => "reply", msgid => $id;
2950 $self->send_packet ("ext " . $self->{json_coder}->encode ({@msg})); 3047 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
2951 } 3048 }
2952} 3049}
2953 3050
2954=item $success = $client->query ($flags, "text", \&cb) 3051=item $success = $client->query ($flags, "text", \&cb)
2955 3052
3056 3153
3057 $coro 3154 $coro
3058} 3155}
3059 3156
3060cf::client->attach ( 3157cf::client->attach (
3061 on_destroy => sub { 3158 on_client_destroy => sub {
3062 my ($ns) = @_; 3159 my ($ns) = @_;
3063 3160
3064 $_->cancel for values %{ (delete $ns->{_coro}) || {} }; 3161 $_->cancel for values %{ (delete $ns->{_coro}) || {} };
3065 }, 3162 },
3066); 3163);
3082our $safe_hole = new Safe::Hole; 3179our $safe_hole = new Safe::Hole;
3083 3180
3084$SIG{FPE} = 'IGNORE'; 3181$SIG{FPE} = 'IGNORE';
3085 3182
3086$safe->permit_only (Opcode::opset qw( 3183$safe->permit_only (Opcode::opset qw(
3087 :base_core :base_mem :base_orig :base_math 3184 :base_core :base_mem :base_orig :base_math :base_loop
3088 grepstart grepwhile mapstart mapwhile 3185 grepstart grepwhile mapstart mapwhile
3089 sort time 3186 sort time
3090)); 3187));
3091 3188
3092# here we export the classes and methods available to script code 3189# here we export the classes and methods available to script code
3144 $qcode =~ s/"/‟/g; # not allowed in #line filenames 3241 $qcode =~ s/"/‟/g; # not allowed in #line filenames
3145 $qcode =~ s/\n/\\n/g; 3242 $qcode =~ s/\n/\\n/g;
3146 3243
3147 %vars = (_dummy => 0) unless %vars; 3244 %vars = (_dummy => 0) unless %vars;
3148 3245
3246 my @res;
3149 local $_; 3247 local $_;
3150 local @safe::cf::_safe_eval_args = values %vars;
3151 3248
3152 my $eval = 3249 my $eval =
3153 "do {\n" 3250 "do {\n"
3154 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 3251 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
3155 . "#line 0 \"{$qcode}\"\n" 3252 . "#line 0 \"{$qcode}\"\n"
3156 . $code 3253 . $code
3157 . "\n}" 3254 . "\n}"
3158 ; 3255 ;
3159 3256
3257 if ($CFG{safe_eval}) {
3160 sub_generation_inc; 3258 sub_generation_inc;
3259 local @safe::cf::_safe_eval_args = values %vars;
3161 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval); 3260 @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
3162 sub_generation_inc; 3261 sub_generation_inc;
3262 } else {
3263 local @cf::_safe_eval_args = values %vars;
3264 @res = wantarray ? eval eval : scalar eval $eval;
3265 }
3163 3266
3164 if ($@) { 3267 if ($@) {
3165 warn "$@"; 3268 warn "$@";
3166 warn "while executing safe code '$code'\n"; 3269 warn "while executing safe code '$code'\n";
3167 warn "with arguments " . (join " ", %vars) . "\n"; 3270 warn "with arguments " . (join " ", %vars) . "\n";
3186=cut 3289=cut
3187 3290
3188sub register_script_function { 3291sub register_script_function {
3189 my ($fun, $cb) = @_; 3292 my ($fun, $cb) = @_;
3190 3293
3191 no strict 'refs'; 3294 $fun = "safe::$fun" if $CFG{safe_eval};
3192 *{"safe::$fun"} = $safe_hole->wrap ($cb); 3295 *$fun = $safe_hole->wrap ($cb);
3193} 3296}
3194 3297
3195=back 3298=back
3196 3299
3197=cut 3300=cut
3218 3321
3219 $facedata->{version} == 2 3322 $facedata->{version} == 2
3220 or cf::cleanup "$path: version mismatch, cannot proceed."; 3323 or cf::cleanup "$path: version mismatch, cannot proceed.";
3221 3324
3222 # patch in the exptable 3325 # patch in the exptable
3326 my $exp_table = $enc->encode ([map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]);
3223 $facedata->{resource}{"res/exp_table"} = { 3327 $facedata->{resource}{"res/exp_table"} = {
3224 type => FT_RSRC, 3328 type => FT_RSRC,
3225 data => $enc->encode ([map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]), 3329 data => $exp_table,
3330 hash => (Digest::MD5::md5 $exp_table),
3226 }; 3331 };
3227 cf::cede_to_tick; 3332 cf::cede_to_tick;
3228 3333
3229 { 3334 {
3230 my $faces = $facedata->{faceinfo}; 3335 my $faces = $facedata->{faceinfo};
3232 while (my ($face, $info) = each %$faces) { 3337 while (my ($face, $info) = each %$faces) {
3233 my $idx = (cf::face::find $face) || cf::face::alloc $face; 3338 my $idx = (cf::face::find $face) || cf::face::alloc $face;
3234 3339
3235 cf::face::set_visibility $idx, $info->{visibility}; 3340 cf::face::set_visibility $idx, $info->{visibility};
3236 cf::face::set_magicmap $idx, $info->{magicmap}; 3341 cf::face::set_magicmap $idx, $info->{magicmap};
3237 cf::face::set_data $idx, 0, $info->{data32}, Digest::MD5::md5 $info->{data32}; 3342 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32};
3238 cf::face::set_data $idx, 1, $info->{data64}, Digest::MD5::md5 $info->{data64}; 3343 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64};
3239 3344
3240 cf::cede_to_tick; 3345 cf::cede_to_tick;
3241 } 3346 }
3242 3347
3243 while (my ($face, $info) = each %$faces) { 3348 while (my ($face, $info) = each %$faces) {
3267 3372
3268 cf::anim::invalidate_all; # d'oh 3373 cf::anim::invalidate_all; # d'oh
3269 } 3374 }
3270 3375
3271 { 3376 {
3272 # TODO: for gcfclient pleasure, we should give resources
3273 # that gcfclient doesn't grok a >10000 face index.
3274 my $res = $facedata->{resource}; 3377 my $res = $facedata->{resource};
3275 3378
3276 while (my ($name, $info) = each %$res) { 3379 while (my ($name, $info) = each %$res) {
3277 if (defined $info->{type}) { 3380 if (defined $info->{type}) {
3278 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3381 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3279 my $data;
3280 3382
3281 if ($info->{type} & 1) { 3383 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3282 # prepend meta info
3283
3284 my $meta = $enc->encode ({
3285 name => $name,
3286 %{ $info->{meta} || {} },
3287 });
3288
3289 $data = pack "(w/a*)*", $meta, $info->{data};
3290 } else {
3291 $data = $info->{data};
3292 }
3293
3294 cf::face::set_data $idx, 0, $data, Digest::MD5::md5 $data;
3295 cf::face::set_type $idx, $info->{type}; 3384 cf::face::set_type $idx, $info->{type};
3296 } else { 3385 } else {
3297 $RESOURCE{$name} = $info; 3386 $RESOURCE{$name} = $info;
3298 } 3387 }
3299 3388
3462 }; 3551 };
3463 3552
3464 evthread_start IO::AIO::poll_fileno; 3553 evthread_start IO::AIO::poll_fileno;
3465 3554
3466 cf::sync_job { 3555 cf::sync_job {
3556 cf::load_settings;
3557 cf::load_materials;
3558
3467 reload_resources; 3559 reload_resources;
3468 reload_config; 3560 reload_config;
3469 db_init; 3561 db_init;
3470 3562
3471 cf::load_settings;
3472 cf::load_materials;
3473 cf::init_uuid; 3563 cf::init_uuid;
3474 cf::init_signals; 3564 cf::init_signals;
3475 cf::init_commands;
3476 cf::init_skills; 3565 cf::init_skills;
3477 3566
3478 cf::init_beforeplay; 3567 cf::init_beforeplay;
3479 3568
3480 atomic; 3569 atomic;
3498 3587
3499# install some emergency cleanup handlers 3588# install some emergency cleanup handlers
3500BEGIN { 3589BEGIN {
3501 our %SIGWATCHER = (); 3590 our %SIGWATCHER = ();
3502 for my $signal (qw(INT HUP TERM)) { 3591 for my $signal (qw(INT HUP TERM)) {
3503 $SIGWATCHER{$signal} = EV::signal $signal, sub { 3592 $SIGWATCHER{$signal} = AE::signal $signal, sub {
3504 cf::cleanup "SIG$signal"; 3593 cf::cleanup "SIG$signal";
3505 }; 3594 };
3506 } 3595 }
3507} 3596}
3508 3597
3509sub write_runtime_sync { 3598sub write_runtime_sync {
3599 my $t0 = AE::time;
3600
3510 # first touch the runtime file to show we are still running: 3601 # first touch the runtime file to show we are still running:
3511 # the fsync below can take a very very long time. 3602 # the fsync below can take a very very long time.
3512 3603
3513 IO::AIO::aio_utime $RUNTIMEFILE, undef, undef; 3604 IO::AIO::aio_utime $RUNTIMEFILE, undef, undef;
3514 3605
3515 my $guard = cf::lock_acquire "write_runtime"; 3606 my $guard = cf::lock_acquire "write_runtime";
3516 3607
3517 my $fh = aio_open "$RUNTIMEFILE~", O_WRONLY | O_CREAT, 0644 3608 my $fh = aio_open "$RUNTIMEFILE~", O_WRONLY | O_CREAT | O_TRUNC, 0644
3518 or return; 3609 or return;
3519 3610
3520 my $value = $cf::RUNTIME + 90 + 10; 3611 my $value = $cf::RUNTIME + 90 + 10;
3521 # 10 is the runtime save interval, for a monotonic clock 3612 # 10 is the runtime save interval, for a monotonic clock
3522 # 60 allows for the watchdog to kill the server. 3613 # 60 allows for the watchdog to kill the server.
3535 or return; 3626 or return;
3536 3627
3537 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 3628 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3538 and return; 3629 and return;
3539 3630
3540 warn "runtime file written.\n"; 3631 warn sprintf "runtime file written (%gs).\n", AE::time - $t0;
3541 3632
3542 1 3633 1
3543} 3634}
3544 3635
3545our $uuid_lock; 3636our $uuid_lock;
3683 return; 3774 return;
3684 } 3775 }
3685 3776
3686 return if $RELOAD++; 3777 return if $RELOAD++;
3687 3778
3688 my $t1 = EV::time; 3779 my $t1 = AE::time;
3689 3780
3690 while ($RELOAD) { 3781 while ($RELOAD) {
3691 warn "reloading..."; 3782 warn "reloading...";
3692 3783
3693 warn "entering sync_job"; 3784 warn "entering sync_job";
3796 3887
3797 warn "reloaded"; 3888 warn "reloaded";
3798 --$RELOAD; 3889 --$RELOAD;
3799 } 3890 }
3800 3891
3801 $t1 = EV::time - $t1; 3892 $t1 = AE::time - $t1;
3802 warn "reload completed in ${t1}s\n"; 3893 warn "reload completed in ${t1}s\n";
3803}; 3894};
3804 3895
3805our $RELOAD_WATCHER; # used only during reload 3896our $RELOAD_WATCHER; # used only during reload
3806 3897
3809 # coro crashes during coro_state_free->destroy here. 3900 # coro crashes during coro_state_free->destroy here.
3810 3901
3811 $RELOAD_WATCHER ||= cf::async { 3902 $RELOAD_WATCHER ||= cf::async {
3812 Coro::AIO::aio_wait cache_extensions; 3903 Coro::AIO::aio_wait cache_extensions;
3813 3904
3814 $RELOAD_WATCHER = EV::timer $TICK * 1.5, 0, sub { 3905 $RELOAD_WATCHER = AE::timer $TICK * 1.5, 0, sub {
3815 do_reload_perl; 3906 do_reload_perl;
3816 undef $RELOAD_WATCHER; 3907 undef $RELOAD_WATCHER;
3817 }; 3908 };
3818 }; 3909 };
3819} 3910}
3836 3927
3837our @WAIT_FOR_TICK; 3928our @WAIT_FOR_TICK;
3838our @WAIT_FOR_TICK_BEGIN; 3929our @WAIT_FOR_TICK_BEGIN;
3839 3930
3840sub wait_for_tick { 3931sub wait_for_tick {
3841 return if tick_inhibit || $Coro::current == $Coro::main; 3932 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
3842 3933
3843 my $signal = new Coro::Signal; 3934 my $signal = new Coro::Signal;
3844 push @WAIT_FOR_TICK, $signal; 3935 push @WAIT_FOR_TICK, $signal;
3845 $signal->wait; 3936 $signal->wait;
3846} 3937}
3847 3938
3848sub wait_for_tick_begin { 3939sub wait_for_tick_begin {
3849 return if tick_inhibit || $Coro::current == $Coro::main; 3940 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
3850 3941
3851 my $signal = new Coro::Signal; 3942 my $signal = new Coro::Signal;
3852 push @WAIT_FOR_TICK_BEGIN, $signal; 3943 push @WAIT_FOR_TICK_BEGIN, $signal;
3853 $signal->wait; 3944 $signal->wait;
3854} 3945}
3859 unless ++$bug_warning > 10; 3950 unless ++$bug_warning > 10;
3860 return; 3951 return;
3861 } 3952 }
3862 3953
3863 cf::server_tick; # one server iteration 3954 cf::server_tick; # one server iteration
3955
3956 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d#
3864 3957
3865 if ($NOW >= $NEXT_RUNTIME_WRITE) { 3958 if ($NOW >= $NEXT_RUNTIME_WRITE) {
3866 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.; 3959 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
3867 Coro::async_pool { 3960 Coro::async_pool {
3868 $Coro::current->{desc} = "runtime saver"; 3961 $Coro::current->{desc} = "runtime saver";
3891} 3984}
3892 3985
3893{ 3986{
3894 # configure BDB 3987 # configure BDB
3895 3988
3896 BDB::min_parallel 8; 3989 BDB::min_parallel 16;
3897 BDB::max_poll_reqs $TICK * 0.1; 3990 BDB::max_poll_reqs $TICK * 0.1;
3898 $AnyEvent::BDB::WATCHER->priority (1); 3991 $AnyEvent::BDB::WATCHER->priority (1);
3899 3992
3900 unless ($DB_ENV) { 3993 unless ($DB_ENV) {
3901 $DB_ENV = BDB::db_env_create; 3994 $DB_ENV = BDB::db_env_create;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines