Gradle task to convert blend files in powershell
Based on what i tried to do here: https://hub.jmonkeyengine.org/t/jmeconvert-tool/41831
And then posted about here: https://hub.jmonkeyengine.org/t/blender-to-gltf-converter-as-a-gradle-task-in-powershell/42922
These files add a gradle task to convert all .blend
files in your JMonkeyEngine3 assets folder to .blend.glb
files (in place)
The gradle task works by calling a powershell file which enumerates the folder and checks if the generated file needs updating.
This calls the blender.exe as a background task with the python script over each file to convert them.
Task in gradle:
task convertBlendFiles(type: Exec) {
workingDir 'src/assets'
//sorry windows only unless you install powershell on linux
commandLine 'cmd', '/c', 'Powershell -File blend2gltf.ps1'
}
The blend2gltf.ps1
called in gradle:
<#
.SYNOPSIS
Converts all .blend files in the project assets folder to .blend.glb files
.NOTES
Author: murph9y@gmail.com
#>
$ErrorActionPreference = "Stop"
$blenderPath = 'C:\Program Files\Blender Foundation\Blender 2.81\'
$blenderPythonFile = 'blend2gltf.py'
function Convert-gltf {
param(
[Parameter(Mandatory="true")] [string] $FilePath,
[Parameter(Mandatory = "true")] [string] $BlenderPython
)
$generatedFile = @(Get-ChildItem -ErrorAction SilentlyContinue "$FilePath.glb")
$blendFile = Get-ChildItem $FilePath
if (($generatedFile.Length -gt 0) -and ($blendFile.LastWriteTime -lt $generatedFile[0].LastWriteTime)) {
Write-Host "Ignored: $blendFile"
return $false # already converted, so ignore
}
#run blender command and ignore output
& "$blenderPath\blender" $FilePath --background --python $BlenderPython > $null
Write-Host "Converted: $FilePath"
return $true
}
$files = Get-ChildItem -Recurse -Include '*.blend'
Write-Host "$(($files).Length) .blend files found"
$results = $files | ForEach-Object { Convert-gltf $_ $blenderPythonFile } | Where-Object { $_ }
Write-Host "$(($results).Length) updated .blend.glb files"
And the called blend2gltf.py
file:
import bpy
import sys
bpy.ops.export_scene.gltf(filepath=bpy.data.filepath)
This has now been updated to be an purely in gradle task (still possibly windows only):
def blenderCommand = "C:\\Program Files\\Blender Foundation\\Blender 2.82\\blender"
def blenderPythonFile = "$projectDir\\assets\\blend2gltf.py"
task convertAllBlendFiles {
doFirst {
ConfigurableFileTree files = fileTree(dir: 'assets', include: '**/*.blend')
files.each { File file ->
File glbFile = new File(file.path + '.glb')
if (!glbFile.exists() && file.lastModified() > glbFile.lastModified()) {
println 'Running: ' + file.path
def ip = new ByteArrayOutputStream()
exec {
standardOutput = ip
def command = '"' + blenderCommand + '" "'+file.path+'" ' + '--background ' + '--python "' + blenderPythonFile + '"'
commandLine 'cmd', '/s', '/c', '"'+command+'"'
}
//println ip
} else {
println file.name + ' ignoring: generated file is newer'
}
}
}
}