NAME

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

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();

DESCRIPTION

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 Affix. The shared library is supplied by Alien::PhysFS.

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

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

Paths and notation

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

Functions that shadow Perl builtins

Several PhysicsFS names are also Perl builtins (close, delete, exists, mkdir, seek, and stat). Importing them with :all does not override the builtin when you call a bare word such as 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);

Features

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

:all

Import all functions, types, and constants.

:version - Version information

Version

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

getLinkedVersion( $version )

getLinkedVersion( \my %version );

Get the version of PhysicsFS that is actually linked into the program. $version must be a hash reference; it is filled with major, minor, and patch keys. The return value is 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 init( ).

VER_MAJOR, VER_MINOR, VER_PATCH

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

VERSION( )

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

:init - Initialization and paths

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 $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 GetError() for details. Not thread-safe.

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, init( ) may be called again to restart the subsystem with default state.

isInit( )

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

setSaneConfig( $organization, $appName, $archiveExt, $includeCdRoms, $archivesFirst )

Helper that builds a common configuration. The write directory is set to 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 $archiveExt are discovered in those paths and mounted at /; $archiveExt is case-insensitive and must not include the dot. Use undef to skip archive discovery. $includeCdRoms may block while drives spin up. $archivesFirst prepends rather than appends discovered archives. Returns non-zero on success.

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 deinit(); copy it if you need to keep it. Returns undef on failure.

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

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 deinit(). On Android this may be the APK path, which can be mounted and narrowed with setRoot().

getWriteDir( )

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

setWriteDir( $newDir )

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

getDirSeparator( )

Return the platform's native directory separator string: \ on Windows, / on Unix, and : 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 /.

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. $allow is any boolean. Calling this after init() is safe. stat() never follows a symlink; if links are denied, stat() treats a symlink as nonexistent.

symbolicLinksPermitted( )

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

setRoot( $archive, $subdir )

Make a subdirectory of a mounted archive or directory its virtual root. For example, if x.zip contains y/z.txt and is mounted at /a, then setRoot( 'x.zip', '/y' ) makes /a/z.txt resolve to that file. $archive is the platform-dependent path originally mounted; $subdir is a platform-independent virtual path. Pass undef or / 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.

:error - Error handling

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

ErrorCode and the ERR_* constants

The PHYSFS_ErrorCode enum. Upstream describes the values as follows:

ERR_OK

Success; no error.

ERR_OTHER_ERROR

Error not otherwise covered here.

ERR_OUT_OF_MEMORY

Memory allocation failed.

ERR_NOT_INITIALIZED

PhysicsFS is not initialized.

ERR_IS_INITIALIZED

PhysicsFS is already initialized.

ERR_ARGV0_IS_NULL

Needed argv[0], but it was NULL.

ERR_UNSUPPORTED

Operation or feature unsupported.

ERR_PAST_EOF

Attempted to access past end of file.

ERR_FILES_STILL_OPEN

Files still open.

ERR_INVALID_ARGUMENT

Bad parameter passed to a function.

ERR_NOT_MOUNTED

Requested archive/dir not mounted.

ERR_NOT_FOUND

File (or whatever) not found.

Symlink seen when not permitted.

ERR_NO_WRITE_DIR

No write directory has been specified.

ERR_OPEN_FOR_READING

Wrote to a file opened for reading.

ERR_OPEN_FOR_WRITING

Read from a file opened for writing.

ERR_NOT_A_FILE

Needed a file, got a directory, etc.

ERR_READ_ONLY

Wrote to a read-only filesystem.

ERR_CORRUPT

Corrupted data encountered.

Infinite symbolic link loop.

ERR_IO

I/O error (hardware failure, etc).

ERR_PERMISSION

Permission denied.

ERR_NO_SPACE

No space (disk full, over quota, etc).

ERR_BAD_FILENAME

Filename is bogus or insecure.

ERR_BUSY

Tried to modify a file the OS needs.

ERR_DIR_NOT_EMPTY

Tried to delete a directory with files in it.

ERR_OS_ERROR

Unspecified OS-level error.

ERR_DUPLICATE

Duplicate entry.

ERR_BAD_PASSWORD

Bad password.

ERR_APP_CALLBACK

Application callback reported an error.

getLastErrorCode( )

Return the current thread's last error as an ErrorCode value. Returns ERR_OK if no error has been recorded since the last read. Calling this function clears the thread's error state, as does reading the deprecated text error. If you need both the code and its message, read the code and pass it to getErrorByCode( ). Safe before init( ).

getErrorByCode( $code )

Return a read-only, static English description for an error code, or undef if the code is unknown. The strings are stable and suitable as keys for your own localization. Safe before init( ).

setErrorCode( $code )

Set the current thread's error code. This is mainly useful inside custom I/O callbacks. Any subsequent PhysicsFS call may overwrite it, so it is not a general-purpose error-reporting mechanism.

GetError( )

Perl helper that reads the current thread's error code, converts it with getErrorByCode( ), and returns the string (or Unknown PhysicsFS error if the code has no description). Like getLastErrorCode( ), this consumes the error state.

:mount - Mounting archives and directories

mount( $newDir, $mountPoint, $appendToPath )

Add a directory or archive to the search path. $newDir is a platform-dependent path. $mountPoint is a platform-independent virtual location; undef or '' means /. $appendToPath appends rather than prepends. Returns non-zero on success.

Mount points need not already exist. Multiple archives may be mounted at the same point; their files are interpolated into one tree and earlier search-path entries win when names overlap. This makes archives useful for overrides and mods. Duplicate mounts of the same archive are ignored, even if a different mount point is requested. A symlink in $newDir is allowed regardless of permitSymbolicLinks( ).

unmount( $oldDir )

Remove a directory or archive from the search path. $oldDir must be the exact platform-dependent string passed to mount( ), not the virtual mount point. Matching is case-sensitive. This fails if any files from that entry are still open. Returns non-zero on success.

getMountPoint($dir)

Return the virtual mount point for a previously mounted platform-dependent path, or undef on failure. The returned string is read-only and valid until the entry is unmounted. Entries mounted with a null mount point report /.

:files - File access

File handles are opaque objects returned by openRead, openWrite, or openAppend. Pass them unmodified to the other functions in this tag. The _File typedef is exported as the handle type.

Remember that close, delete, exists, mkdir, seek, and stat shadow Perl builtins; see "Functions that shadow Perl builtins".

mkdir( $dirName )

Create a directory under the write directory using platform-independent notation. Missing parents are created too. If a parent is created but a later component fails, the parent is left behind. Returns non-zero on success.

delete( $filename )

Delete a file or empty directory under the write directory using platform-independent notation. A directory must be empty to be deleted. Deleting a symlink removes the link, not its target. Returns non-zero on success.

exists( $filename )

Return non-zero if a matching entry exists anywhere in the search path. The name is in platform-independent notation. Symlinks are ignored unless permitSymbolicLinks( 1 ) has been called.

openWrite( $filename ), openAppend( $filename ), openRead( $filename )

Open a file under the write directory (write/append) or search path (read) using platform-independent notation. openWrite creates or truncates the file and starts at byte 0. openAppend creates the file or starts at its end. openRead starts at byte 0. Each returns an opaque handle or undef on failure. Symlinks are ignored unless enabled with permitSymbolicLinks().

close( $handle )

Close a PhysicsFS file handle. Returns non-zero on success; failure is possible if buffered writes cannot be flushed, and a failed handle stays open. Always check the result of closing a file opened for writing.

eof( $handle )

Return non-zero when a read handle has reached end of file.

tell( $handle )

Return the current byte offset from the start of the file, or -1 on error.

seek( $handle, $pos )

Move the next read or write position to $pos bytes from the start of the file. Seeking before byte 0 or past the end is an error. Returns non-zero on success.

fileLength( $handle )

Return the file's length in bytes, or -1 if it cannot be determined. Another thread or process writing the same file can make this value stale immediately.

setBuffer( $handle, $bufsize )

Set the I/O buffer size in bytes for a handle. Reading buffers up to $bufsize ahead; writing buffers until the buffer is full or flushed. Compressed archives decompress into the buffer, which can offset CPU cost. Passing 0 removes an existing buffer. Handles are unbuffered by default. Returns non-zero on success.

flush( $handle )

Flush a buffered write handle. For read handles and unbuffered handles this is a successful no-op. Returns non-zero on success.

readBytes( $handle, \$buffer, $len )

Read up to $len bytes from a read handle into the scalar referenced by $buffer. Returns the number of bytes read, which may be less than requested at EOF, or -1 on complete failure. eof() and GetError() can explain a short read.

writeBytes( $handle, \$data, $len )

Write $len bytes from the scalar referenced by $data to a write handle. Returns the number of bytes written, which may be less than requested, or -1 on complete failure. Upstream limits a single call to 63 bits of data so that -1 remains distinguishable.

ReadFile( $filename )

Perl helper that opens a file for reading, sizes it with fileLength( ), reads it with readBytes( ), closes the handle, and returns the whole file as a scalar. Returns undef if any step fails.

WriteFile($filename, $data)

Perl helper that opens a file for writing, writes all of $data with writeBytes( ), closes the handle, and returns a boolean.

:list - Listing and searching

EnumerateCallback

The PHYSFS_EnumerateCallback callback type. Affix passes three arguments: $data (the application value supplied to enumerate( )), $origdir (the full platform-independent directory being enumerated), and $fname (one entry's name, without the directory). The callback returns an integer: 1 to keep going (PHYSFS_ENUM_OK), 0 to stop successfully (PHYSFS_ENUM_STOP), or -1 to stop with an error (PHYSFS_ENUM_ERROR). These enum constants are not exported, so use the documented numbers.

getSearchPath( )

Low-level accessor for the current search path. The default is an empty list. In C the result must be released with freeList( ); Affix currently copies the strings into a Perl array reference, so prefer GetSearchPath( ).

enumerateFiles( $dir )

Low-level directory listing for a platform-independent directory. Matching directories in the search path are interpolated: results contain no duplicates and are sorted in case-sensitive Unicode order. Since PhysicsFS 2.1 a failure returns no partial list. In C the result must be released with freeList( ); prefer EnumerateFiles( ).

getCdRomDirs( )

Low-level list of platform-dependent paths for drives with accessible inserted media. "CD-ROM" includes DVD, HD-DVD, CDRW, and Blu-Ray filesystems, but not audio-only discs. This call may block while drives spin up. In C the result must be released with freeList( ).

enumerate( $dir, $callback, $data )

Call $callback once per entry found in platform-independent directory $dir, passing $data through as the first argument. Returns non-zero on success; stopping early with return value 0 also counts as success. Returning -1 from the callback makes this fail with ERR_APP_CALLBACK.

Unlike enumerateFiles( ), this form does not sort and may report duplicate names. It reports entries as they are found in each archive.

freeList( $list )

Low-level deallocator for C-style lists returned by PhysicsFS. Passing 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.

GetSearchPath( )

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

EnumerateFiles( [ $dir ] )

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

:stat - Metadata

FileType and the FILETYPE_* constants

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

Stat

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

filesize

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

modtime, createtime, accesstime

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

filetype

One of the FILETYPE_* values.

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.

stat( $filename, \%info )

Fill %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.

GetStat( $filename )

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

SEE ALSO

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

AUTHOR

Sanko Robinson - https://github.com/sanko/

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.