Alien-PhysFS

 view release on metacpan or  search on metacpan

lib/Game/PhysicsFS.pm  view on Meta::CPAN

package Game::PhysicsFS v0.0.1 {
    use v5.40;
    use base 'Exporter';
    use Affix qw[affix typedef Enum Struct Pointer /Int/ Void Callback String Bool];
    use Alien::PhysFS;
    use Carp   qw[croak confess];
    use Config qw[%Config];

=encoding utf-8

=head1 NAME

Game::PhysicsFS - Perl wrapper for PhysicsFS, the portable game asset filesystem

=head1 SYNOPSIS

    use v5.40;
    use Game::PhysicsFS qw[:all];

    init($0) or die Game::PhysicsFS::GetError();
    setSaneConfig( 'My Company', 'My Game', 'ZIP', 0, 1 )
        or die Game::PhysicsFS::GetError();

    my $png = ReadFile('/game/player.png');
    say scalar @{ EnumerateFiles('/game') };

    my $stat = GetStat('/game/player.png');
    say $stat->{filesize} if $stat;

    deinit();

=head1 DESCRIPTION

C<Game::PhysicsFS> gives Perl programs a virtual filesystem layered over directories and archives (ZIP, 7z, GRP, WAD,
and more, depending on how PhysicsFS was built). These bindings are made with C<Affix>. The shared library is supplied
by C<Alien::PhysFS>.

Every C function keeps its upstream name, minus the C<PHYSFS_> prefix. A few Perl-friendly helpers are also provided:
C<ReadFile>, C<WriteFile>, C<GetSearchPath>, C<EnumerateFiles>, C<GetStat>, and C<GetError>.

Full upstream API documentation is at L<https://icculus.org/physfs/docs/html/physfs_8h.html>.

=head2 Paths and notation

Functions that set up search paths and write directories take I<platform-dependent> paths: C<C:\MyGame\assets> on
Windows, C</home/me/assets> on Unix. Once paths are mounted, all file names passed to the virtual filesystem use
I<platform-independent> notation: forward slashes, no drive letters, and no leading separator is required.
C<getDirSeparator()> returns the native separator for the current platform; virtual paths always use C</>.

=head2 Functions that shadow Perl builtins

Several PhysicsFS names are also Perl builtins (C<close>, C<delete>, C<exists>, C<mkdir>, C<seek>, and C<stat>).
Importing them with C<:all> does not override the builtin when you call a bare word such as C<exists($path)>. Call the
PhysicsFS version fully qualified:

    Game::PhysicsFS::exists('/game/player.png');
    Game::PhysicsFS::stat('/game/player.png', \%info);
    Game::PhysicsFS::close($handle);

Conversely, call Perl's builtin explicitly when you need it:

    CORE::close($fh);

=head2 Features

Each feature below is an Exporter tag. C<:all> is the default catch-all.

=cut

    my $alien = Alien::PhysFS->new;
    my $info  = $alien->package_info;
    croak 'Could not find PhysicsFS' unless $info;
    my $lib = $info->libpath;    # libfiles[0] is the import library on Windows; libpath is the DLL
    croak 'PhysicsFS has no loadable library' unless defined $lib && length $lib;
    _all();                      # Always load everything
    $ENV{PATH} = join( $Config{path_sep}, ( @{ $info->bindirs // [] } ), $ENV{PATH} // '' );
    our ( %EXPORT_TAGS, @EXPORT_OK );

    sub import ( $pkg, @wants ) {
        {
            no strict 'refs';
            (s[^:][_]r)->() for @wants;
        }
        @EXPORT_OK = sort map {@$_} values %EXPORT_TAGS;
        $EXPORT_TAGS{all} = [@EXPORT_OK];
        __PACKAGE__->export_to_level( 1, $pkg, @wants );
    }

    sub _affix_and_export ( $name, $args, $ret ) {
        my ($n) = ref $name ? @$name : $name;
        confess "Failed to affix $n" unless affix( $lib, [ 'PHYSFS_' . $name, $name ], $args, $ret );
        push @{ $EXPORT_TAGS{ [ caller(1) ]->[3] =~ s/^.+?_//r } }, $n;
    }

    sub _const_and_export ( $name, $value ) {
        no strict 'refs';
        *{$name} = sub () {$value};
        push @{ $EXPORT_TAGS{ [ caller(1) ]->[3] =~ s/^.+?_//r } }, $name;
    }

    sub _func_and_export ( $name, $sub ) {
        no strict 'refs';
        *{$name} = $sub;
        push @{ $EXPORT_TAGS{ [ caller(1) ]->[3] =~ s/^.+?_//r } }, $name;
    }

    sub _typedef_and_export ( $name, $type //= () ) {
        no strict 'refs';
        defined $type ? typedef( $name, $type ) : typedef($name);
        push @{ $EXPORT_TAGS{ [ caller(1) ]->[3] =~ s/^.+?_//r } }, $name;
    }

    sub _enum_and_export ( $name, $values ) {
        no strict 'refs';
        typedef $name, Enum [@$values];
        push @{ $EXPORT_TAGS{ [ caller(1) ]->[3] =~ s/^.+?_//r } }, $name;
        push @{ $EXPORT_TAGS{ [ caller(1) ]->[3] =~ s/^.+?_//r } }, ref $_ ? $_->[0] : $_ for @$values;
    }

    # Affix marshals char ** returns as a plain Perl ARRAY ref of strings. Keep a fallback for an explicit
    # Pointer[String] in case a future Affix changes that.
    sub _string_list ($list) {
        return () unless defined $list;
        return @$list if ref $list eq 'ARRAY';
        return ()     if is_null($list);
        my @out;
        for ( my $i = 0;; $i++ ) {
            my $item = $list->[$i];
            last unless defined $item && length $item;
            push @out, $item;
        }
        return @out;
    }

=head3 C<:all>

Import all functions, types, and constants.

=cut

    sub _all () {
        state $done++ && return;
        _version();
        _init();
        _error();
        _mount();
        _files();
        _list();
        _stat();
    }

=head3 C<:version> - Version information

=head4 C<Version>

The underlying struct exposed as a hash reference with C<major>, C<minor>, and C<patch> keys. Upstream defines these as
unsigned 8-bit fields: C<major> revision, C<minor> revision, and C<patch>level.

=head4 C<getLinkedVersion( $version )>

    getLinkedVersion( \my %version );

Get the version of PhysicsFS that is actually linked into the program. C<$version> must be a hash reference; it is
filled with C<major>, C<minor>, and C<patch> keys. The return value is C<void>.

With a shared library the runtime version can differ from the version you compiled against. This is a real function and
is safe to call at any time, even before C<init( )>.

=head4 C<VER_MAJOR>, C<VER_MINOR>, C<VER_PATCH>

Constants holding the linked library's major, minor, and patch values.

=head4 C<VERSION( )>

Returns the linked PhysicsFS version as a version string such as C<v3.3.0>. This is not the module version
(C<$Game::PhysicsFS::VERSION>).

=cut

    sub _version () {
        state $done++ && return;
        _typedef_and_export Version => Struct [ major => UInt8, minor => UInt8, patch => UInt8 ];
        _affix_and_export getLinkedVersion => [ Pointer [ Version() ] ], Void;
        getLinkedVersion( \my %version );
        _const_and_export VER_MAJOR => $version{major};
        _const_and_export VER_MINOR => $version{minor};
        _const_and_export VER_PATCH => $version{patch};
        _func_and_export VERSION => sub ( $class = undef ) {
            state $ver //= sprintf 'v%d.%d.%d', map { $version{$_} } qw[major minor patch];
            $ver;
        };
    }

=head3 C<:init> - Initialization and paths

=head4 C<init( $argv0 )>

Initialize the PhysicsFS library. This must be called before any other PhysicsFS function and, ideally, before the
program changes its working directory. Pass C<$0>, or the platform-specific value described by upstream (for example an
Android init struct pointer). Returns non-zero on success and zero on failure; use C<GetError()> for details. Not
thread-safe.

=head4 C<deinit( )>

Deinitialize PhysicsFS. This closes files opened through PhysicsFS, blanks the search and write paths, frees memory,
and invalidates all PhysicsFS file handles. Returns non-zero on success. It can fail if an open write handle cannot be
flushed, so close write handles yourself first. After a successful deinit, C<init( )> may be called again to restart
the subsystem with default state.

=head4 C<isInit( )>

Returns non-zero if PhysicsFS has been initialized, zero before C<init( )> and after C<deinit( )>. Safe to call at any
time.

=head4 C<setSaneConfig( $organization, $appName, $archiveExt, $includeCdRoms, $archivesFirst )>

Helper that builds a common configuration. The write directory is set to C<getPrefDir($organization, $appName)>,
created if needed. The search path becomes the write directory, the base directory, and optionally CD-ROM directories.
Files whose extension matches C<$archiveExt> are discovered in those paths and mounted at C</>; C<$archiveExt> is
case-insensitive and must not include the dot. Use C<undef> to skip archive discovery. C<$includeCdRoms> may block
while drives spin up. C<$archivesFirst> prepends rather than appends discovered archives. Returns non-zero on success.

=head4 C<getPrefDir( $org, $app )>

Return the platform-specific directory where the user can store preferences and save games for this application. The
directory is created if needed. The returned string is read-only and valid until the next call to this function or
C<deinit()>; copy it if you need to keep it. Returns C<undef> on failure.

Keep C<$org> stable and C<$app> unique and stable for each application. Use letters, numbers, and spaces; UTF-8 is
accepted. On Windows this may resemble C<C:\Users\bob\AppData\Roaming\My Company\My Game>; on Linux,
C</home/bob/.local/share/My Game>.

=head4 C<getBaseDir( )>

Return the directory the application was launched from, in platform-dependent notation. This is usually the install
directory and may differ from the process working directory. The string is read-only and remains valid until
C<deinit()>. On Android this may be the APK path, which can be mounted and narrowed with C<setRoot()>.

=head4 C<getWriteDir( )>

Return the current write directory in platform-dependent notation, or C<undef> if none is set. The default is no write
directory.

=head4 C<setWriteDir( $newDir )>

Set the root directory for all files opened for writing. The path is platform-dependent. Passing C<undef> disables
writing until another directory is set. This fails if the current write directory still has open files. Returns
non-zero on success.

=head4 C<getDirSeparator( )>

Return the platform's native directory separator string: C<\> on Windows, C</> on Unix, and C<:> on classic Mac OS. It
may be more than one character. This is only for constructing native search and write paths; virtual filesystem paths
always use C</>.

=head4 C<permitSymbolicLinks( $allow )>

Enable or disable following symbolic links inside the virtual filesystem. Symlinks are denied by default because a link
could escape the search or write paths. C<$allow> is any boolean. Calling this after C<init()> is safe. C<stat()> never
follows a symlink; if links are denied, C<stat()> treats a symlink as nonexistent.

=head4 C<symbolicLinksPermitted( )>

Return non-zero if symbolic links are currently permitted, zero otherwise. Defaults to false after initialization.

=head4 C<setRoot( $archive, $subdir )>

Make a subdirectory of a mounted archive or directory its virtual root. For example, if C<x.zip> contains C<y/z.txt>
and is mounted at C</a>, then C<setRoot( 'x.zip', '/y' )> makes C</a/z.txt> resolve to that file. C<$archive> is the
platform-dependent path originally mounted; C<$subdir> is a platform-independent virtual path. Pass C<undef> or C</> to
clear a previously set root. Returns non-zero on success.

Only future path lookups are affected; handles already open keep their old view. A root may be set on the write
directory too.

=cut

    sub _init () {
        state $done++ && return;
        _affix_and_export init                   => [String], Bool;
        _affix_and_export deinit                 => [], Bool;
        _affix_and_export isInit                 => [], Bool;
        _affix_and_export setSaneConfig          => [ String, String, String, Bool, Bool ], Bool;
        _affix_and_export getPrefDir             => [ String, String ], String;
        _affix_and_export getBaseDir             => [], String;
        _affix_and_export getWriteDir            => [], String;
        _affix_and_export setWriteDir            => [String], Bool;
        _affix_and_export getDirSeparator        => [], String;
        _affix_and_export permitSymbolicLinks    => [Bool], Void;
        _affix_and_export symbolicLinksPermitted => [], Bool;
        _affix_and_export setRoot                => [ String, String ], Bool;
    }

=head3 C<:error> - Error handling

Errors are per-thread. Most calls report failure with a boolean or null return; these functions explain why.

=head4 C<ErrorCode> and the C<ERR_*> constants

The C<PHYSFS_ErrorCode> enum. Upstream describes the values as follows:

=over

=item C<ERR_OK>

Success; no error.

=item C<ERR_OTHER_ERROR>

Error not otherwise covered here.

=item C<ERR_OUT_OF_MEMORY>

Memory allocation failed.

=item C<ERR_NOT_INITIALIZED>

PhysicsFS is not initialized.

=item C<ERR_IS_INITIALIZED>

lib/Game/PhysicsFS.pm  view on Meta::CPAN

Low-level deallocator for C-style lists returned by PhysicsFS. Passing C<undef> is a safe no-op. Do not pass the Perl
array references returned by Affix to this function; those are already copied Perl values.

=head4 C<GetSearchPath( )>

Perl helper returning an array reference of search path entries as strings.

=head4 C<EnumerateFiles( [ $dir ] )>

Perl helper returning an array reference of file names in C<$dir>. Defaults to the virtual root (C<'/'>). Results are
interpolated, deduplicated, and sorted.

=cut

    sub _list () {
        state $done++ && return;
        _typedef_and_export EnumerateCallback => Callback [ [ Pointer [Void], String, String ] => Int ];
        _affix_and_export getSearchPath  => [], Pointer [String];
        _affix_and_export enumerateFiles => [String], Pointer [String];
        _affix_and_export getCdRomDirs   => [], Pointer [String];
        _affix_and_export enumerate      => [ String, EnumerateCallback(), Pointer [Void] ], Int;
        _affix_and_export freeList       => [ Pointer [Void] ], Void;
        _func_and_export GetSearchPath  => sub () { return [ _string_list( getSearchPath() ) ] };
        _func_and_export EnumerateFiles => sub ( $dir = '/' ) {
            return [ _string_list( enumerateFiles($dir) ) ];
        };
    }

=head3 C<:stat> - Metadata

=head4 C<FileType> and the C<FILETYPE_*> constants

The C<PHYSFS_FileType> enum: C<FILETYPE_REGULAR> (a normal file), C<FILETYPE_DIRECTORY>, C<FILETYPE_SYMLINK>, and
C<FILETYPE_OTHER> (something like a device).

=head4 C<Stat>

The C<PHYSFS_Stat> struct, exposed as a hash reference with these fields:

=over

=item C<filesize>

Size in bytes, or C<-1> for non-files and unknown sizes.

=item C<modtime>, C<createtime>, C<accesstime>

Seconds since the Unix epoch, or C<-1> when unavailable or not applicable.

=item C<filetype>

One of the C<FILETYPE_*> values.

=item C<readonly>

Non-zero when the archive considers the entry read-only. This is an estimate: an overlapping write directory can still
make the path writable by creating it elsewhere.

=back

=head4 C<stat( $filename, \%info )>

Fill C<%info> with metadata for a platform-independent path. Returns non-zero on success; on failure the hash contents
are undefined. This function never follows symlinks: if links are denied, a symlink is treated as nonexistent; if links
are permitted, the link itself is described.

=head4 C<GetStat( $filename )>

Perl helper around C<stat( )>. Returns a hash reference with the fields described under C<Stat>, or C<undef> on
failure.

=cut

    sub _stat () {
        state $done++ && return;
        _enum_and_export FileType => [qw[FILETYPE_REGULAR FILETYPE_DIRECTORY FILETYPE_SYMLINK FILETYPE_OTHER]];
        _typedef_and_export Stat =>
            Struct [ filesize => Int64, modtime => Int64, createtime => Int64, accesstime => Int64, filetype => FileType(), readonly => Int ];
        _affix_and_export stat => [ String, Pointer [ Stat() ] ], Bool;
        _func_and_export GetStat => sub ($filename) {
            my %stat;
            return undef unless Game::PhysicsFS::stat( $filename, \%stat );
            return \%stat;
        };
    }

=head1 SEE ALSO

L<Affix>, L<Alien::PhysFS>, L<https://icculus.org/physfs/>, L<https://icculus.org/physfs/docs/html/physfs_8h.html>

=head1 AUTHOR

Sanko Robinson - L<https://github.com/sanko/>

=head1 LICENSE

Copyright (C) 2026 by Sanko Robinson.

This library is free software; you can redistribute it and/or modify it under the terms of the Artistic License 2.0.

=cut

};
#
1;



( run in 0.981 second using v1.01-cache-2.11-cpan-eb134014566 )