Skip to content

Instantly share code, notes, and snippets.

@allanon
Created September 2, 2017 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allanon/afbb3afb9453122641dd180bb82d5936 to your computer and use it in GitHub Desktop.
Save allanon/afbb3afb9453122641dd180bb82d5936 to your computer and use it in GitHub Desktop.
package OpenKore::Plugins::ItemWeightRecorder;
###############################################################################
# Record item weights into tables/item_weights.txt.
use strict;
use Globals qw( $char );
our $name = 'item_weight_recorder';
our $filename = 'item_weights.txt';
our $item_weights ||= {};
our $loader ||= Settings::addTableFile( 'item_weights.txt', loader => [ \&FileParsers::parseDataFile2, $item_weights ], mustExist => 0 );
Settings::loadByHandle( $loader );
our $last_item;
our $last_weight;
Plugins::register( $name, "$name plugin", \&Unload, \&Unload );
my $hooks = Plugins::addHooks( #
[ 'packet/inventory_item_added' => \&onInventoryItemAdded ],
[ 'packet_pre/inventory_item_removed' => \&onInventoryItemRemoved ],
[ 'packet/stat_info' => \&onStatInfo ],
);
sub Unload {
Plugins::delHooks( $hooks );
}
sub onInventoryItemAdded {
my ( undef, $args ) = @_;
return if $args->{fail};
my $item = $char->inventory->getByID( $args->{ID} );
return if !$item || !$args->{amount};
$last_item = { time => time, item_id => $item->{nameID}, amount => $args->{amount} };
}
sub onInventoryItemRemoved {
my ( undef, $args ) = @_;
return if $args->{reason};
my $item = $char->inventory->getByID( $args->{ID} );
return if !$item || !$args->{amount};
$last_item = { time => time, item_id => $item->{nameID}, amount => $args->{amount} };
}
# The server sends weight changes immediately after each inventory change.
sub onStatInfo {
my ( undef, $args ) = @_;
# 0x18 is WEIGHT.
return if $args->{type} != 0x18;
if ( $last_item && $last_item->{amount} && defined $last_weight ) {
my $weight = abs( $args->{val} - $last_weight ) / $last_item->{amount};
if ( $item_weights->{ $last_item->{item_id} } ne $weight ) {
$item_weights->{ $last_item->{item_id} } = $weight;
Log::debug( sprintf( "Item [%s] has weight [%.1f]. (%s / %s)\n", $last_item->{item_id}, $weight / 10, $args->{val} - $last_weight, $last_item->{amount} ), $name );
log_update( $last_item->{item_id} );
}
}
$last_item = undef;
$last_weight = $args->{val};
}
sub log_update {
my ( $item_id ) = @_;
open FP, '>>', Settings::getTableFilename( $filename );
print FP "$item_id $item_weights->{$item_id}\n";
close FP;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment