Search by

maize-tech / laravel-blender

maize-tech

Run Blender headless from your Laravel application: renders, conversions and Python scripts with a fluent API.

Package info

github.com/maize-tech/laravel-blender

pkg:composer/maize-tech/laravel-blender

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.0 2026-11-30 09:16 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Run Blender headless from your Laravel application: render images and animations, convert 3D models between formats, inspect scenes and run your own Python scripts with a fluent API.

use Maize\Blender\Facades\Blender;

// Render the first frame of a scene
Blender::render(storage_path('scenes/product.blend'))
    ->engine('CYCLES')
    ->output(storage_path('renders/product_####'))
    ->format('PNG')
    ->run()
    ->throw()
    ->savedFiles(); // ['/.../renders/product_0001.png']

// Convert an FBX model to glTF binary
Blender::convert(storage_path('models/chair.fbx'), storage_path('models/chair.glb'));

// Read scenes, objects and materials of a file
Blender::inspect(storage_path('models/chair.glb'));

Requirements

  • Blender installed on the machine running the code (the web server or, better, your queue workers). Blender 4.x and 5.x are supported; CI runs the integration tests against Blender 4.2 LTS, 4.5 LTS, 5.2 LTS and 5.3. The official builds are recommended: distribution packages often ship without some importers/exporters (e.g. USD) or without NumPy, which is required by the glTF add-on.
  • Rendering with EEVEE or Workbench needs OpenGL, see Headless servers and GPUs.

Installing Blender on a server

# Official build (recommended)
curl -L https://download.blender.org/release/Blender4.2/blender-4.2.3-linux-x64.tar.xz | tar -xJ -C /opt
ln -s /opt/blender-4.2.3-linux-x64/blender /usr/local/bin/blender

# Runtime libraries needed by Blender on a minimal Debian/Ubuntu image
apt-get install -y libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 libxkbcommon0 libsm6

Headless servers and GPUs

  • Cycles on the CPU works everywhere and needs no display or graphics driver. It is the engine used by default for thumbnails.

  • EEVEE and Workbench need OpenGL/EGL, provided by a GPU or by a software renderer. On a server without one Blender fails or crashes when rendering with them. Install a software fallback (e.g. Mesa's llvmpipe through libegl1, libgl1 and libgl1-mesa-dri on Debian/Ubuntu) and, if Blender still cannot create an OpenGL context, run your worker under a virtual display with xvfb-run.

  • Using the GPU with Cycles: choose the device with cyclesDevice(), one of CUDA, OPTIX, HIP, ONEAPI or METAL. Append +CPU to use the CPU too.

    Blender::render('scene.blend')->engine('CYCLES')->cyclesDevice('OPTIX')->run();
    Blender::render('scene.blend')->engine('CYCLES')->cyclesDevice('CUDA+CPU')->run();
  • Docker: to expose NVIDIA GPUs to the container install the NVIDIA Container Toolkit on the host and start the container with --gpus all.

  • Denoising requires OpenImageDenoise: the official builds include it, distribution packages may not.

Installation

You can install the package via composer:

composer require maize-tech/laravel-blender

Publish the config file and check that Blender can be executed:

php artisan blender:install

You can check the installation again at any time with php artisan blender:info (--fresh to detect the version again), or publish the config file alone with:

php artisan vendor:publish --tag="laravel-blender-config"

This is the content of the published config file:

return [
    // Path of the Blender executable
    'binary' => env('BLENDER_BINARY', 'blender'),

    // Maximum number of seconds a Blender process can run (null to disable)
    'timeout' => env('BLENDER_TIMEOUT', 600),

    // Number of threads (null or 0 means all cores)
    'threads' => env('BLENDER_THREADS'),

    // Ignore user preferences and startup file, for reproducible runs
    'factory_startup' => env('BLENDER_FACTORY_STARTUP', true),

    // Allow Python scripts embedded in .blend files to run: keep it disabled for untrusted files
    'allow_autoexec' => env('BLENDER_ALLOW_AUTOEXEC', false),

    // Base directory of the temporary working directories used by Blender::disk() (null for the system temp dir)
    'temporary_directory' => env('BLENDER_TEMPORARY_DIRECTORY', storage_path('app/blender-tmp')),

    // Maximum number of Blender processes running at the same time, see "Concurrency"
    'concurrency' => [
        'limit' => env('BLENDER_MAX_PROCESSES'),            // null means no limit
        'store' => env('BLENDER_LOCK_STORE'),               // cache store with atomic locks (null for the default one)
        'wait' => env('BLENDER_CONCURRENCY_WAIT', 600),     // seconds to wait for a free slot
        'lock_ttl' => env('BLENDER_LOCK_TTL'),              // null means the process timeout + 60 seconds
    ],

    // Extra environment variables passed to every Blender process
    'environment' => [],
];

Usage

Rendering

use Maize\Blender\Enums\Engine;
use Maize\Blender\Enums\OutputFormat;
use Maize\Blender\Facades\Blender;

// A single frame (defaults to the start frame of the scene)
Blender::render($blendFile)->frame(12)->run();

// Several frames, or a range
Blender::render($blendFile)->frame(1, 10, '20..30')->run();

// The whole animation, optionally overriding start, end and step
Blender::render($blendFile)->animation(start: 1, end: 120, step: 2)->run();

// Full control
$result = Blender::render($blendFile)
    ->scene('Studio')
    ->engine(Engine::Cycles)            // or Engine::Eevee, Engine::Workbench, ...
    ->cyclesDevice('OPTIX')             // CPU, CUDA, OPTIX, HIP, ONEAPI, METAL (append +CPU to combine)
    ->output('/renders/studio_####')    // "#" is replaced by the frame number
    ->format(OutputFormat::Png)
    ->threads(8)
    ->timeout(3600)
    ->run();

$result->successful();
$result->savedFiles();   // paths of the written images
$result->errors();       // Blender errors and Python tracebacks
$result->output();       // raw stdout

Blender processes its command line arguments in order (for example --render-output is ignored when it comes after --render-frame): the builder always emits them in the right sequence, regardless of the order in which you call the methods. Inspect the generated command with toArray() or toCommand().

EEVEE is named BLENDER_EEVEE before Blender 4.2 and since 5.0, BLENDER_EEVEE_NEXT from 4.2 up to 4.5: Engine::Eevee (as well as the deprecated Engine::EeveeNext and both strings) is emitted with the identifier of the binary in use. Its version is detected only for EEVEE, when the command is built; skip the detection with ->usingVersion('4.2.3').

Render settings

Common render settings that have no command line option can be set fluently:

Blender::render($blendFile)
    ->resolution(1920, 1080, percentage: 50)  // 960x540
    ->samples(64)                             // Cycles and EEVEE
    ->camera('CloseUp')                       // name of the camera object
    ->transparent()                           // transparent background, RGBA when the format supports it
    ->denoise(false)                          // Cycles denoising
    ->quality(85)                             // JPEG and WEBP quality
    ->viewTransform('Standard')               // color management view transform (and optional look)
    ->run();

The settings are applied to the scene being rendered (the one selected with ->scene(), or the active one) by a single Python step generated by the package. It runs after your own Python scripts, so it can use a camera created by them and it always wins over them, and before the render starts. Values are passed as base64 encoded JSON, never as Python code. When denoising is requested but the Blender build has no OpenImageDenoise support (e.g. some Linux distribution packages) it stays disabled, with a warning in the output.

To render a single image to an exact path, without frame number placeholders, use renderStill(). The image format is guessed from the extension (png, jpg, webp, tif, exr, ...):

$result = Blender::render($blendFile)
    ->resolution(800, 800)
    ->renderStill(storage_path('renders/product.webp'))
    ->run()
    ->throw();

$result->json('output'); // "/.../renders/product.webp"

For anything else, chain a Python expression or script. They run after the file is loaded and before rendering:

Blender::render($blendFile)
    ->pythonExpression(<<<'PY'
        import bpy
        bpy.context.scene.render.use_motion_blur = True
        PY)
    ->run();

Lights, world and materials

Change the lighting and the materials of the scene before rendering, without writing Python:

use Maize\Blender\Enums\LightType;

Blender::render($blendFile)
    ->withoutLights()                                       // hide the lights of the scene
    ->addLight(LightType::Sun, location: [4, -4, 6], energy: 3)
    ->addLight(LightType::Area, location: [-3, -2, 4], target: [0, 0, 1], energy: 500, size: 2, color: [1, 0.9, 0.8])
    ->light('Key', energy: 800, color: [1, 1, 1])           // change an existing light
    ->background([0.05, 0.05, 0.05])                        // uniform world color (RGB, linear, 0-1)
    ->environment('/hdri/studio.hdr', strength: 1.5, rotation: 90)  // or an environment image
    ->materialColor('Wood', [0.8, 0.4, 0.1])                // base color (RGB or RGBA)
    ->assignMaterial('Chair', 'Wood')                       // every material slot of the object
    ->renderStill(storage_path('renders/chair.png'))
    ->run()
    ->throw();

The overrides are applied in the order they are called, to the scene being rendered, by a Python step generated by the package. It runs after your own Python scripts, so it can use the objects and materials they create, and before the render settings. Values are passed as base64 encoded JSON, never as Python code, and validated first: colors are lists of non-negative numbers, locations and targets are lists of 3 numbers. When a light, an object or a material does not exist, Blender fails with an error such as Material not found: Wood.

Energy is in watts, or W/m² for sun lights (added lights default to 1000 W, 3 W/m² for the sun). The size of an added light is the angle in degrees of sun lights, the size of area lights and the radius of the others, in meters. Added lights point to the target (the origin by default). background() and environment() replace the color of the world background, creating a world when the scene has none.

Videos

renderVideo() renders the animation into a single video file, saved to exactly the given path (Blender does not add the frame range to the name). The container is guessed from the extension and the codec defaults to the usual one of the container:

Extension Container Default codec
.mp4 MPEG-4 H.264
.mkv Matroska H.264
.mov QuickTime H.264
.webm WebM VP9
.ogv Ogg Theora
.avi AVI MPEG-4
use Maize\Blender\Enums\VideoCodec;
use Maize\Blender\Enums\VideoQuality;

$result = Blender::render($blendFile)
    ->resolution(1280, 720)
    ->renderVideo(
        storage_path('renders/turntable.mp4'),
        start: 1,                       // frame range and step, the ones of the scene by default
        end: 120,
        fps: 30,                        // the frame rate of the scene by default
        codec: VideoCodec::H264,        // or Av1, Vp9, Ffv1, Png, Qtrle, ... (or any identifier as a string)
        quality: VideoQuality::High,    // constant rate factor of H.264, AV1 and VP9
    )
    ->run()
    ->throw();

$result->json('output');    // "/.../renders/turntable.mp4"
$result->json('frames');    // 120
$result->savedFiles();      // ['/.../renders/turntable.mp4']

The progress (onProgress()) counts the frames added to the video. The Blender build must include FFmpeg, as the official builds do. H.264 needs an even width and height. To keep the alpha channel of a transparent render use a lossless codec: Ffv1 (.mkv, .avi), Png or Qtrle (.mov).

Converting 3D files

// Returns the path of the converted file
Blender::convert('/models/chair.fbx', '/models/chair.glb');

// Pass keyword arguments to the Blender export (and import) operators
Blender::convert(
    input: '/models/chair.blend',
    output: '/models/chair.glb',
    exportOptions: ['export_draco_mesh_compression_enable' => true, 'export_apply' => true],
);

// Get the pending process instead of running it, e.g. to change the timeout
Blender::conversion('/models/city.obj', '/models/city.usdz')->timeout(1800)->run()->throw();

Formats are guessed from the file extensions:

Format Extensions Import Export
Blender .blend ✓ ✓
glTF 2.0 .glb, .gltf ✓ ✓
FBX .fbx ✓ ✓
Wavefront .obj ✓ ✓
STL .stl ✓ ✓
PLY .ply ✓ ✓
USD .usd, .usda, .usdc, .usdz ✓ ✓
Alembic .abc ✓ ✓
Collada .dae (removed in Blender 5) ✓ ✓
X3D/VRML .x3d, .wrl (requires the X3D extension) ✓ ✓ (.x3d)

To convert several files, use convertMany(): Blender starts only once, which saves its startup time (often longer than the conversion of a small file). Every file is loaded into a fresh scene (or opened, for .blend files) and exported with the same options:

// Returns the paths of the converted files, keyed by input path
Blender::convertMany([
    '/models/chair.fbx' => '/models/chair.glb',
    '/models/table.obj' => '/models/table.glb',
    '/models/lamp.blend' => '/models/lamp.usdz',
], exportOptions: ['export_apply' => true]);

// Get the pending process instead of running it
$result = Blender::conversions($files)->timeout(3600)->run();

$result->json('conversions'); // [['input' => ..., 'output' => ..., 'objects' => 3, ...], ...]

When a conversion fails (e.g. a missing or broken file) the next ones still run, then the process fails: convertMany() throws a BlenderProcessFailed exception, and each failed entry of json('conversions') has an error. Very long lists are better split into chunks, to keep the command line short and the timeout reasonable.

Thumbnails

Render a preview image of any file that can be imported (or of a .blend file): a camera framing all the visible objects is added and, when the scene has no lights, a simple lighting setup.

// Returns the path of the image: 512x512 pixels, with a transparent background
Blender::thumbnail('/models/chair.glb', '/thumbs/chair.png');

Blender::thumbnail('/models/chair.fbx', '/thumbs/chair.jpg', size: 256, options: [
    'elevation' => 30,      // camera angle above the horizon, in degrees (default 25)
    'azimuth' => -45,       // camera angle around the model, 0 is the front view (default 35)
    'margin' => 0.1,        // empty space around the model, as a fraction of the image (default 0.08)
    'lens' => 85,           // focal length, in millimeters (default 50)
    'samples' => 32,        // default 16
    'quality' => 85,        // JPEG/WEBP quality
]);

// Get the pending process instead of running it, to change any render setting
Blender::thumbnailing('/models/city.usdz', '/thumbs/city.webp', 1024)
    ->samples(128)
    ->timeout(300)
    ->run()
    ->throw();

The output format is guessed from the extension: png, jpg/jpeg or webp. The background is transparent, except for JPEG images (set the transparent option to change it). Other options: engine (default CYCLES, EEVEE is mapped to the name used by the Blender version), denoise, lights ('auto', true to always add lights, false to never add them), world_color ([r, g, b] ambient light, used when the scene has no world) and import_options.

Thumbnails are rendered by Cycles on the CPU, which works on servers without GPU or display; denoising is enabled only when the Blender build supports it. EEVEE and Workbench need a GPU (or a virtual display).

To render the same file from several points of view, use thumbnails(): the file is loaded and prepared once, in a single Blender process, and every view is saved to its own path (and format):

// Returns the paths of the images, in the order of the views
Blender::thumbnails('/models/chair.glb', [
    '/thumbs/chair-front.png' => ['azimuth' => 0, 'elevation' => 10],
    '/thumbs/chair-side.png' => ['azimuth' => 90, 'elevation' => 10],
    '/thumbs/chair-top.jpg' => ['elevation' => 90, 'margin' => 0.15],
    '/thumbs/chair.webp' => [],                     // the options below, or their defaults
], size: 512, options: ['samples' => 32, 'azimuth' => 35]);

// Get the pending process instead of running it
Blender::thumbnailingViews('/models/city.usdz', $views, 1024)->timeout(900)->run()->throw();

Each view accepts elevation, azimuth, margin, lens and transparent (JPEG views are not transparent by default): missing values come from the options. The camera is framed again for each view and the lights added by the thumbnails follow it, so every side of the model is lit. The progress (onProgress()) counts the rendered views. PendingBlender::renderViews() does the same on any scene with a camera.

Inspecting files

$info = Blender::inspect('/models/chair.glb');

$info['blender'];                       // "4.2.3"
$info['scenes'][0]['frame_end'];        // 250
$info['scenes'][0]['resolution'];       // ['x' => 1920, 'y' => 1080, 'percentage' => 100]
$info['objects'][0]['mesh']['faces'];   // 1284
$info['materials'];                     // ['Wood', 'Metal']

Running your own Python scripts

// A script file, with arguments and an optional file to open first
$result = Blender::script(resource_path('blender/thumbnail.py'), [
    '--output' => storage_path('thumbs/chair.png'),
    '--size' => 512,
], file: '/models/chair.blend')->run();

// Inline Python code
Blender::python('import bpy; print(len(bpy.data.objects))')->run();

Arguments are passed after -- and are available in sys.argv. Named arguments are emitted as two separate values (--output /path): if your script uses argparse and a value may start with a dash (e.g. an uploaded file named -chair.png), emit them as --output=/path instead with ->withArguments([...], inline: true), as the bundled scripts do. To send structured data back to PHP, print a JSON payload prefixed by @@LARAVEL_BLENDER_JSON@@, or use the helper module shipped with the package:

import os, sys
import bpy

sys.path.insert(0, os.environ["LARAVEL_BLENDER_SCRIPTS"])  # set automatically by the package
import laravel_blender

args = laravel_blender.arguments()      # arguments after "--"
laravel_blender.load("/models/chair.fbx")  # open or import any supported format
laravel_blender.output({"objects": len(bpy.data.objects)})
$result = Blender::script(resource_path('blender/stats.py'))
    ->run()
    ->throw();

$result->json('objects'); // 3

Python exceptions make the process fail (--python-exit-code 1 is added automatically, disable it with ->pythonExitCode(false)), and their traceback is available in $result->errors() and in the exception message thrown by throw().

Storage disks

Models and renders often live on a filesystem disk (local, s3, ...). Blender::disk() takes paths of that disk instead of local paths:

// Read from and write to the same disk
Blender::disk('s3')->convert('models/chair.fbx', 'models/chair.glb'); // "models/chair.glb"
Blender::disk('s3')->thumbnail('models/chair.glb', 'thumbs/chair.png', size: 512); // "thumbs/chair.png"

// Read from one disk and write to another one
Blender::fromDisk('uploads')
    ->toDisk('public')
    ->convert('chairs/chair.blend', 'web/chair.gltf'); // also uploads web/chair.bin and the textures

// Several files in a single Blender process
Blender::disk('s3')->convertMany(['models/chair.fbx' => 'web/chair.glb', 'models/table.obj' => 'web/table.glb']);

Blender::disk('s3')->inspect('models/chair.glb');

$result = Blender::fromDisk('s3')
    ->toDisk('public')
    ->render('scenes/product.blend')
    ->engine('CYCLES')
    ->output('previews/product_####')   // path on the target disk
    ->format('PNG')
    ->run()
    ->throw();

$result->savedFiles(); // ['previews/product_0001.png'], on the public disk

Every operation:

  1. creates a unique working directory inside temporary_directory (see the config file),
  2. streams the input file from the source disk into it, keeping its path,
  3. runs Blender on the local copies,
  4. streams every file Blender wrote to the target disk, keeping its path relative to the output path (a .gltf export uploads the .gltf, the .bin and the textures; a render uploads all the saved frames),
  5. deletes the working directory, also when Blender fails.

If the PHP process itself is killed (for example a queue worker reaching its timeout), step 5 never runs and the working directory is left behind. Schedule the blender:prune command to delete those leftovers:

// routes/console.php
use Illuminate\Support\Facades\Schedule;

Schedule::command('blender:prune --hours=6')->hourly();

It only deletes directories created by the package (blender- followed by 20 hex characters) that are older than --hours (24 by default); use --dry-run to list them first.

A missing input throws a Maize\Blender\Exceptions\FileNotFoundOnDisk exception before Blender is started. When the conversion fails nothing is uploaded; when a render fails, the frames saved before the failure are uploaded. The render output defaults to {directory of the file}/{file name}_####; renders can not be started asynchronously with start(), run them in a queued job instead. Blender::disk() also accepts a Filesystem instance.

Only the main file is downloaded. If it references other files, such as textures linked by a .blend file or the .bin of a .gltf file, download them with with() (files or whole directories): they keep their path on the disk, so relative references (//textures/wood.png) keep working. Absolute paths stored in the file and packed resources are not affected.

Blender::disk('s3')
    ->with(['scenes/textures/', 'scenes/hdri/studio.exr'])
    ->render('scenes/room.blend')
    ->output('renders/room_####')
    ->run();

To run your own scripts on files of a disk, use process(): it downloads the inputs, gives you the local paths and uploads everything written to the output paths.

use Maize\Blender\Storage\Workspace;

Blender::disk('s3')->process('models/chair.glb', function (Workspace $workspace) {
    Blender::script(resource_path('blender/thumbnail.py'), [
        '--input' => $workspace->input('models/chair.glb'),
        '--output' => $workspace->output('thumbs/chair.png'),
    ])->run()->throw();
});

Queues

Renders and conversions can take minutes: run them in a queued job, and make sure the job timeout is higher than the Blender timeout.

class RenderProductPreview implements ShouldQueue
{
    use Queueable;

    public $timeout = 1800;

    public function __construct(public Product $product) {}

    public function handle(): void
    {
        $files = Blender::render($this->product->scene_path)
            ->output(storage_path("app/previews/{$this->product->id}_####"))
            ->format('WEBP')
            ->timeout(1700)
            ->run()
            ->throw()
            ->savedFiles();

        $this->product->update(['preview_path' => $files[0]]);
    }
}

Concurrency

A single Blender process can use several GB of memory and every core of the machine: a few queue workers rendering at the same time are enough to exhaust a server. Set BLENDER_MAX_PROCESSES to cap the number of Blender processes running at the same time across every worker, web server and machine sharing the lock store:

BLENDER_MAX_PROCESSES=2
BLENDER_LOCK_STORE=redis
BLENDER_CONCURRENCY_WAIT=600

Before starting, every invocation (run(), start() and everything built on them: convert(), thumbnail(), inspect(), Blender::disk(), ...) takes one of the limit slots, waiting up to wait seconds for a free one. When none becomes available a Maize\Blender\Exceptions\ConcurrencyLimitReached exception is thrown (the process is never started): in a queued job, let it fail and be retried, or release the job back to the queue. The slot is released when the process ends, also when it fails or throws. Without a limit (the default) processes start right away and the cache is never used.

The slots are atomic cache locks named laravel-blender:slot:{n}, so the store must support locks and be shared by everything running Blender: redis, memcached, database or dynamodb. file only works for processes on the same machine and array only within a single PHP process (tests). Each slot has an owner token, so a process never releases a slot it does not hold, and a TTL (lock_ttl, by default the process timeout plus 60 seconds, or one day with forever()): if a worker is killed while Blender runs, its slot is freed when the TTL expires. Set lock_ttl when your processes have no timeout and can run longer than a day.

Per invocation:

// Wait at most 30 seconds for a free slot (0 to try only once)
Blender::render($blendFile)->waitForSlot(30)->run();

// Run only when no other Blender process is running, e.g. a huge render that needs all the memory
Blender::render($hugeScene)->exclusive()->run();

// Ignore the limit (e.g. for a quick script), or set one for this invocation only
Blender::open($file)->withoutConcurrencyLimit()->run();
Blender::open($file)->concurrencyLimit(1)->run();

An exclusive process first takes the laravel-blender:exclusive lock, which stops other processes from taking new slots (and other exclusive processes from starting), then waits for the running processes to finish and takes every slot. Waiting processes can not starve it, and it never runs alongside another Blender process. It has no effect without a limit. The slots are shared by every invocation: when you change the limit per invocation, use the same value everywhere.

Asynchronous processes: start() returns a process that holds its slot until it ends. The slot is released when wait() returns, when running() reports that the process ended, when it is stopped with stop() and when the returned object is destroyed (which also stops the Blender process). If you never wait for it and keep the object around, the slot is only freed by the TTL. start() waits for a slot like run() does, so starting more processes than the limit from the same PHP process, without waiting for the previous ones, ends with a ConcurrencyLimitReached exception.

Queue workers and Octane: nothing is kept in memory between invocations, so long running workers and Octane are safe. Make sure the job timeout covers both the time spent waiting for a slot and the Blender timeout, and keep retry_after higher than that: a job killed while it holds a slot (or, for an exclusive process, while it waits for the slots) keeps it until the TTL expires.

Asynchronous processes and real time output

// Stream Blender's output while rendering
Blender::render($blendFile)->animation()->run(function (string $type, string $output) {
    logger()->debug($output);
});

// Start the process without waiting for it
$process = Blender::render($blendFile)->animation()->start();

while ($process->running()) {
    // ...
}

$result = new \Maize\Blender\BlenderResult($process->wait());

Progress and events

onProgress() reports the render progress, parsed in real time from Blender's output (stdout and stderr, Blender 4 status lines such as Fra:12 Mem:... | Sample 64/128 and the unified logger of Blender 5), and onFrameSaved() is called for every file Blender saves. Both work together with the output callback given to run() or start().

use Maize\Blender\Progress\RenderProgress;

class RenderShot implements ShouldQueue
{
    use Queueable;

    public $timeout = 3600;

    public function __construct(public Shot $shot) {}

    public function handle(): void
    {
        Blender::render($this->shot->scene_path)
            ->output(storage_path("app/shots/{$this->shot->id}/frame_####"))
            ->animation(1, 250)
            ->timeout(3500)
            ->onProgress(function (RenderProgress $progress) {
                // Throttle the writes: progress is reported for every sample.
                if ((int) $progress->percent !== $this->shot->progress) {
                    $this->shot->update(['progress' => (int) $progress->percent]);
                }
            })
            ->onFrameSaved(fn (string $path, RenderProgress $progress) => $this->shot->frames()->create([
                'number' => $progress->frame,
                'path' => $path,
            ]))
            ->run()
            ->throw();
    }
}

RenderProgress is an immutable snapshot: frame, totalFrames, framesCompleted, samplesDone / samplesTotal (Cycles and EEVEE samples), tilesDone / tilesTotal (when Blender renders in tiles), percent, the raw line and savedFile (on Saved: '...' lines). percent (0 to 100) is the overall progress when the number of frames is known, i.e. with frame(), renderStill() or animation() with both a start and an end frame, and never goes backwards; otherwise (animation() without a range, Python scripts that render) totalFrames is null and percent is the progress of the current frame. Lines that do not change the progress are not reported and unknown lines are ignored.

Every invocation (renders, conversions, thumbnails, inspections, scripts) fires Laravel events:

Event When Properties
Maize\Blender\Events\BlenderStarted before the process starts blender (the pending invocation), command, startedAt, async
Maize\Blender\Events\BlenderFinished the process succeeded blender, result, duration (seconds), savedFiles, startedAt
Maize\Blender\Events\BlenderFailed the process failed or timed out blender, result, duration, startedAt, exception (the timeout, rethrown after the event)
use Illuminate\Support\Facades\Event;
use Maize\Blender\Events\BlenderFailed;
use Maize\Blender\Events\BlenderFinished;

Event::listen(function (BlenderFinished $event) {
    Log::info('Blender finished', [
        'command' => $event->result->command(),
        'duration' => $event->duration,
        'files' => count($event->savedFiles),
    ]);

    Metrics::histogram('blender.duration', $event->duration);
});

Event::listen(fn (BlenderFailed $event) => Log::warning('Blender failed', [
    'exit_code' => $event->result->exitCode(),
    'errors' => $event->result->errors(),
]));

run() (and runOrFail()) fire the finished or failed event before returning (or throwing). For processes started with start(), BlenderStarted is fired immediately and the finished or failed event when you call wait() on the returned process (an InvokedProcess that wraps Laravel's one and forwards every other method; wait() also reports the last progress): a process that is only polled with running() fires no finished event. The events carry the pending invocation and the process result, which can not be serialized: listen to them with synchronous listeners (dispatch a job with the data you need if the work is slow).

Advanced

Blender::make()                       // nothing opened
    ->open($file)
    ->binary('/opt/blender-5.0/blender')
    ->factoryStartup(false)           // load the user preferences and add-ons
    ->allowAutoexec()                 // trusted files only!
    ->withOptions(['--log-level', '0'])
    ->path('/projects/scenes')        // working directory
    ->env(['OCIO' => '/config.ocio'])
    ->forever()                       // no timeout
    ->tapProcess(fn ($process) => $process->idleTimeout(120))
    ->when($preview, fn ($blender) => $blender->engine('BLENDER_WORKBENCH'))
    ->run();

Both Blender and the pending invocation are macroable.

Blender::version() (also used by available() and to pick the EEVEE identifier) runs blender --version once per binary and caches the result in memory for the whole PHP process, so queue workers and Octane do not spawn it again: replacing or upgrading the executable invalidates it, failures are never cached, and Blender::flushVersionCache() forgets it.

Security

  • Scripts embedded in .blend files are not executed (--disable-autoexec) unless you enable allow_autoexec. Keep it disabled when processing files uploaded by users.
  • Never build Python code by concatenating user input: pass values as script arguments instead.
  • Paths and values are never interpreted as Blender options: the opened file is passed as ./-file.blend when its name starts with a dash, every other value directly follows its option, the bundled scripts receive --name=value arguments, and values containing NUL bytes are rejected with an InvalidArgument exception before Blender is started. Options added with withOptions() are passed as they are.
  • Blender can be resource hungry: prefer running it on dedicated queue workers, with a timeout.

Testing

Call Blender::fake() to stop real Blender processes: every invocation is recorded and answered with a fake result (a successful run by default; convert(), convertMany(), inspect(), renderStill() and renderVideo() return sensible payloads).

use Maize\Blender\Facades\Blender;
use Maize\Blender\Testing\RecordedInvocation;

Blender::fake([
    // keys match the opened file, a script path or name, or the command line (`*` wildcards)
    '/scenes/*.blend' => Blender::result(output: 'Fra:1', savedFiles: ['/renders/frame_0001.png']),
    'inspect.py' => Blender::result(json: ['scenes' => [], 'objects' => ['Cube'], 'materials' => []]),
    'broken.py' => Blender::result(errorOutput: 'boom', exitCode: 1),
]);

// ... run your code

Blender::assertRendered('/scenes/shot.blend', fn (RecordedInvocation $render) => $render->frames() === ['1']);
Blender::assertRenderedVideo('/scenes/shot.blend', '/renders/shot.mp4');
Blender::assertConverted('/in/model.fbx', '/out/model.glb');
Blender::assertInspected('/scenes/shot.blend');
Blender::assertThumbnailed('/models/chair.glb', '/thumbs/chair.png');
Blender::assertScriptRan('thumbnail.py');
Blender::assertRan(fn (RecordedInvocation $run) => $run->file() === '/scenes/shot.blend');
Blender::assertRanTimes('/scenes/shot.blend', 2);
Blender::assertNotRan('/scenes/other.blend');
Blender::assertNothingRan();

You can also pass a closure that receives the recorded invocation and returns a result (or null to use the default), and call ->preventStrayInvocations() to throw when an invocation has no matching fake result. Faked invocations never take a concurrency slot, so no lock store is needed in your tests: the settings of each invocation (exclusive(), waitForSlot(), ...) are available with $run->pending()->concurrency(). Blender::fake() also replaces Maize\Blender\Blender in the container, so injected instances are faked too.

The fake fires the same events as real invocations, so Event::fake() and your listeners work with it, and onProgress() / onFrameSaved() are called when the fake output contains progress or Saved: '...' lines:

use Illuminate\Support\Facades\Event;
use Maize\Blender\Events\BlenderFinished;

Event::fake();
Blender::fake([
    '/scenes/*.blend' => Blender::result(output: "Fra:1 Mem:9.71M | Scene, ViewLayer | Sample 8/8", savedFiles: ['/renders/frame_0001.png']),
]);

// ... run your code

Event::assertDispatched(BlenderFinished::class, fn (BlenderFinished $event) => $event->savedFiles === ['/renders/frame_0001.png']);

Since the package runs Blender through Laravel's Process facade, Process::fake() and its assertions work as well:

use Illuminate\Support\Facades\Process;

Process::fake([
    '*' => Process::result("Saved: '/renders/frame_0001.png'"),
]);

// ... run your code

Process::assertRan(fn ($process) => in_array('--render-frame', $process->command));

To run the package tests:

composer test

Integration tests run the real Blender binary (set BLENDER_BINARY if it is not in your $PATH) and are skipped when Blender is not available.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

Blender is a registered trademark of the Blender Foundation. This package is not affiliated with or endorsed by the Blender Foundation.

License

The PHP code of the package is released under the MIT License (MIT). Please see License File for more information.

The Python scripts in resources/scripts run inside Blender and use its Python API (bpy): following the Blender Foundation's position on scripts that use the API, they are released under the GNU General Public License v3.0 or later. The PHP code does not include or link to Blender or the scripts: it only starts Blender as a separate process and passes the scripts to it, which is why it can be released under the MIT License.