@echo off
setlocal
title 3D Maker Place - install a reconstruction pipeline
cd /d "%~dp0"
set "BASE=https://3dmakerplace.com"
rem A copy downloaded from the builder preview carries the preview's address, which this
rem PC cannot reach - use the published site instead of failing the adapter download.
echo %BASE% | findstr /i /c:"localhost" /c:"127.0.0.1" >nul 2>nul && set "BASE=https://3dmakerplace.base44.app"
set "ROOT=%USERPROFILE%\maker-pipelines"
set "VENV=%ROOT%\venv"
set "REPO=%ROOT%\TripoSR"
set "ADAPTER=%ROOT%\triposr-run.py"
set "VPY=%VENV%\Scripts\python.exe"
set "BLENDER_ROOT=%ROOT%\blender"
set "BLENDER=%BLENDER_ROOT%\blender.exe"

echo.
echo   3D Maker Place - agent setup
echo   ---------------------------
echo.
echo   Installs TripoSR (image to 3D) in its own Python environment and a portable
echo   Blender for surface finishing. The first run downloads a few gigabytes and
echo   runs on its own - keep this window open.

if not exist "%ROOT%" mkdir "%ROOT%"

rem ---------- adapter ----------
rem Fetched first, because its --check is what tells a second run of this file that
rem the pipeline is already installed and nothing has to be downloaded again.
if exist "%ADAPTER%" goto haveadapter
echo   Fetching the runner adapter...
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -UseBasicParsing -Uri '%BASE%/api/agent/pipeline-adapter' -OutFile '%ADAPTER%' } catch { exit 1 }"
if not exist "%ADAPTER%" goto noadapter
:haveadapter

rem ---------- already installed? ----------
set "PIPE_OK=0"
if not exist "%VPY%" goto buildpipe
"%VPY%" "%ADAPTER%" --check >nul 2>nul
if errorlevel 1 goto buildpipe
set "PIPE_OK=1"
echo   TripoSR is already installed - keeping it.

rem ---------- Git ----------
:buildpipe
if "%PIPE_OK%"=="1" goto blender

where git >nul 2>nul
if not errorlevel 1 goto havegit
if exist "%ProgramFiles%\Git\cmd\git.exe" set "PATH=%ProgramFiles%\Git\cmd;%PATH%"
where git >nul 2>nul
if not errorlevel 1 goto havegit
echo   Installing Git...
winget install --id Git.Git -e --source winget --silent --accept-package-agreements --accept-source-agreements >nul 2>nul
set "PATH=%ProgramFiles%\Git\cmd;%PATH%"
where git >nul 2>nul
if errorlevel 1 goto nogit
:havegit
echo   Git ready.

rem ---------- Python ----------
set "PY="
py -3 -c "import sys" >nul 2>nul
if not errorlevel 1 set "PY=py -3"
if defined PY goto havepython
python -c "import sys" >nul 2>nul
if not errorlevel 1 set "PY=python"
if defined PY goto havepython
echo   Installing Python 3.12...
winget install --id Python.Python.3.12 -e --source winget --silent --accept-package-agreements --accept-source-agreements >nul 2>nul
set "PATH=%LocalAppData%\Programs\Python\Python312;%LocalAppData%\Programs\Python\Python312\Scripts;%PATH%"
set "PY=python"
python -c "import sys" >nul 2>nul
if errorlevel 1 goto nopython
:havepython
echo   Python ready.

rem ---------- environment ----------
if exist "%VPY%" goto havevenv
echo   Creating the Python environment...
%PY% -m venv "%VENV%"
if not exist "%VPY%" goto novenv
:havevenv
"%VPY%" -m pip install --upgrade pip setuptools wheel

echo   Installing PyTorch - the CUDA build first, plain build as a fallback...
"%VPY%" -m pip install --upgrade torch torchvision --index-url https://download.pytorch.org/whl/cu124
if errorlevel 1 "%VPY%" -m pip install --upgrade torch torchvision

rem ---------- TripoSR ----------
if exist "%REPO%\tsr\system.py" goto haverepo
echo   Fetching TripoSR...
git clone --depth 1 https://github.com/VAST-AI-Research/TripoSR "%REPO%"
if not exist "%REPO%\tsr\system.py" goto norepo
:haverepo
rem Installed in small groups: one unavailable package cannot block the rest.
echo   Installing the pipeline dependencies...
rem trimesh 5 needs numpy 2, and the checkpoint needs numpy 1 - keep the pair that works.
"%VPY%" -m pip install --upgrade "trimesh<5" pillow "numpy<2"
rem transformers 4.35 cannot run on Python 3.12 - the tokenizers it pins has no wheel for it,
rem and the import stops before any model loads. 4.44 ships a tokenizer that installs there,
rem and the adapter matches TripoSR's older weight names itself.
"%VPY%" -m pip install --upgrade transformers==4.44.2 "tokenizers<0.20"
"%VPY%" -m pip install --upgrade huggingface_hub<1.0 einops omegaconf
"%VPY%" -m pip install --upgrade safetensors regex pyyaml filelock packaging tqdm requests
"%VPY%" -m pip install --upgrade opencv-python-headless onnxruntime moderngl
"%VPY%" -m pip install --upgrade imageio scikit-image
"%VPY%" -m pip install --upgrade rembg
rem numpy 2 breaks torch and the pinned transformers, and the scipy and trimesh built for
rem numpy 2 cannot load on numpy 1 - the set goes in together.
"%VPY%" -m pip install --upgrade numpy==1.26.4 "scipy<1.15" "trimesh<5"

echo   Checking the install...
"%VPY%" "%ADAPTER%" --check
if errorlevel 1 goto checkfailed

rem ---------- Blender ----------
rem The finisher retopologises a finished mesh to the maker's triangle budget and bakes the
rem dense surface into a normal map, which only Blender does. The portable build needs no
rem installer and no administrator prompt: it is unpacked into this folder and the agent is
rem pointed straight at its exe.
:blender
if exist "%BLENDER%" goto haveblender
echo.
echo   Installing Blender for surface finishing - about 350 MB, once...
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; try { [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; $url=$null; foreach ($v in @('Blender4.5','Blender4.2')) { try { $page=(Invoke-WebRequest -UseBasicParsing ('https://download.blender.org/release/'+$v+'/')).Content; $names=@([regex]::Matches($page,'blender-[0-9]+\.[0-9]+\.[0-9]+-windows-x64\.zip') | ForEach-Object { $_.Value } | Select-Object -Unique | Sort-Object { [version](($_ -split '-')[1]) }); if ($names.Count -gt 0) { $url='https://download.blender.org/release/'+$v+'/'+$names[$names.Count-1]; break } } catch {} }; if (-not $url) { exit 1 }; Write-Host ('  Downloading ' + $url); $zip=Join-Path $env:TEMP 'blender-portable.zip'; Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $zip; if (Test-Path '%BLENDER_ROOT%.new') { Remove-Item '%BLENDER_ROOT%.new' -Recurse -Force }; Expand-Archive -LiteralPath $zip -DestinationPath '%BLENDER_ROOT%.new' -Force; Remove-Item $zip -Force } catch { exit 1 }"
if errorlevel 1 goto noblender
rem The zip unpacks into a versioned folder; the exe inside it is what gets pointed at.
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { $exe=Get-ChildItem -LiteralPath '%BLENDER_ROOT%.new' -Filter 'blender.exe' -Recurse -File | Select-Object -First 1; if (-not $exe) { exit 1 }; if (Test-Path '%BLENDER_ROOT%') { Remove-Item '%BLENDER_ROOT%' -Recurse -Force }; Move-Item -LiteralPath $exe.Directory.FullName -Destination '%BLENDER_ROOT%' } catch { exit 1 }"
if errorlevel 1 goto noblender
if not exist "%BLENDER%" goto noblender
echo   Blender ready.
goto haveblender
:noblender
rem Never fatal: without it the run keeps the full-detail mesh instead of a baked one.
echo   Blender could not be installed now. Models still generate - they keep their
echo   full-detail mesh instead of a retopologised one. Run this file again to retry.
:haveblender

rem ---------- wire it into the agent ----------
if exist "agent-config.bat" goto trimconfig
> "agent-config.bat" echo @echo off
goto writeconfig
:trimconfig
findstr /v /i /c:"MP_PYTHON=" /c:"MP_LOCAL_SCRIPT=" /c:"MP_TRIPOSR_SCRIPT=" /c:"MP_BLENDER=" "agent-config.bat" > "agent-config.tmp"
move /y "agent-config.tmp" "agent-config.bat" >nul
:writeconfig
>>"agent-config.bat" echo set "MP_PYTHON=%VPY%"
>>"agent-config.bat" echo set "MP_LOCAL_SCRIPT=%ADAPTER%"
>>"agent-config.bat" echo set "MP_TRIPOSR_SCRIPT=%ADAPTER%"
set "WIRE_BLENDER="
if exist "%BLENDER%" set "WIRE_BLENDER=1"
if not defined WIRE_BLENDER goto havegen
>>"agent-config.bat" echo set "MP_BLENDER=%BLENDER%"
:havegen
findstr /i /c:"MP_GENERATE_COMMAND=" "agent-config.bat" >nul 2>nul
if not errorlevel 1 goto wired
>>"agent-config.bat" echo set "MP_GENERATE_COMMAND=node %~dp0openmesh-runner.mjs"
:wired

echo.
echo   Done. The agent now points at this machine's pipeline:
echo     %ADAPTER%
if exist "%BLENDER%" echo     %BLENDER%
echo.
echo   Next:
echo     1. Right-click the orange tray icon and choose Restart.
echo     2. Start the generation again - it runs on this machine's GPU.
echo.
rem The agent starter runs this file itself and carries on, so it asks for no keypress.
if not "%MP_NO_PAUSE%"=="1" pause
exit /b 0

:nogit
echo.
echo   Git could not be installed. Install it from https://git-scm.com, then run this file again.
echo.
if not "%MP_NO_PAUSE%"=="1" pause
exit /b 1

:nopython
echo.
echo   Python could not be installed. Install Python 3.10+ from https://python.org and run this file again.
echo.
if not "%MP_NO_PAUSE%"=="1" pause
exit /b 1

:novenv
echo.
echo   The Python environment could not be created at %VENV%.
echo   Run this file again from a normal (non-admin) prompt.
echo.
if not "%MP_NO_PAUSE%"=="1" pause
exit /b 1

:norepo
echo.
echo   TripoSR could not be fetched from GitHub. Check your connection and run this file again.
echo.
if not "%MP_NO_PAUSE%"=="1" pause
exit /b 1

:noadapter
echo.
echo   The runner adapter could not be downloaded from %BASE%.
echo   Check your connection and run this file again.
echo.
if not "%MP_NO_PAUSE%"=="1" pause
exit /b 1

:checkfailed
echo.
echo   Python could not load the pipeline. The install is incomplete:
echo     "%VPY%" "%ADAPTER%" --check
echo   Run that line to see the missing package, or reinstall with this file again.
echo.
if not "%MP_NO_PAUSE%"=="1" pause
exit /b 1
