Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,20 @@ Like `build`, `run` accepts map archives or folders and auto-detects the input w

Grill selects Warcraft III from `--wc3-path`, then a valid `.vscode/settings.json` path (`wurst.wc3path`), then automatic detection. It warns about project/client patch mismatches; use `--wc3-path` to choose another client. The built map is passed via `-loadfile`; Reforged also receives `-launch` and `-editor` to preserve the authentication session. Older clients receive a copy in `Maps/Test/GrillRunMap.w3x`, under the installation for 1.27 and older or the Warcraft III documents folder for 1.28–1.31. Linux launches through Wine and respects `WINEPREFIX` for the documents location. Build failures prevent launch. The command returns after starting Warcraft III.

### Hot reloading a Lua map

A Lua project (`scriptMode: lua`) can change the code of a running single-player game without restarting it:

```cmd
> grill run --hot ExampleMap.w3x
... edit the Wurst code ...
> grill reload
```

`run --hot` builds the map with the compiler's `-luaHotReload` flag, starts a hot reload session for `_build`, and then launches Warcraft III with a copy of the map in `_build/grill/hot-run`, so that the game does not hold the file each reload builds again. After each edit, `reload` builds the project again, with the map and `--dev` setting of the hot run unless you name another map, and writes the next payload for the running map to pick up. It prints the payload and any warnings. When the edit cannot be hot reloaded (for example a field's type changed), or no map was started with `run --hot` (or a hot run from VS Code), it prints the reasons, writes nothing and exits with 1; rebuild and restart with `run --hot`.

Payloads go to the `CustomMapData` folder of the Warcraft III documents folder (the same documents folder `run` uses), unless `--custom-map-data <dir>` or the VS Code setting `wurst.customMapDataPath` names another folder. Hot reload is Lua only: Jass projects are rejected; use Jass Hot Code Reload (JHCR) for them. What can be reloaded is described in the compiler's `docs/LUA_HOT_RELOAD.md`.

## How it works

### Wurst Installation
Expand Down
9 changes: 7 additions & 2 deletions src/main/kotlin/config/WurstProjectConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -151,14 +151,19 @@ object WurstProjectConfig {
Files.write(projectRoot.resolve(CONFIG_FILE_NAME), projectYaml.toByteArray())
}

fun configuredGamePath(projectRoot: Path): Path? {
fun configuredGamePath(projectRoot: Path): Path? = configuredPath(projectRoot, "wurst.wc3path")

/** The VS Code extension's `wurst.customMapDataPath`, which the language server's hot reload also uses. */
fun configuredCustomMapDataPath(projectRoot: Path): Path? = configuredPath(projectRoot, "wurst.customMapDataPath")

private fun configuredPath(projectRoot: Path, setting: String): Path? {
val settings = projectRoot.resolve(".vscode").resolve("settings.json")
if (!Files.isRegularFile(settings)) {
return null
}
return try {
MAPPER.readTree(Files.readString(settings))
?.get("wurst.wc3path")
?.get(setting)
?.asText()
?.takeIf(String::isNotBlank)
?.let(Paths::get)
Expand Down
11 changes: 11 additions & 0 deletions src/main/kotlin/file/CLICommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ enum class CLICommand {
PATCH,
BUILD,
RUN,
RELOAD,
EXPORTOBJECTS,
SELF_UPDATE
}
Expand Down Expand Up @@ -99,6 +100,16 @@ enum class GlobalOptions(val optionName: String = "", val argCount: Int = 0) {
}
}
},
HOT("--hot") {
override fun runOption(setupMain: SetupMain, args: List<String>) {
setupMain.hotReload = true
}
},
CUSTOM_MAP_DATA("--custom-map-data", 1) {
override fun runOption(setupMain: SetupMain, args: List<String>) {
setupMain.customMapDataPath = java.nio.file.Paths.get(args[0])
}
},
WC3_PATH("--wc3-path", 1) {
override fun runOption(setupMain: SetupMain, args: List<String>) {
setupMain.gamePath = java.nio.file.Paths.get(args[0])
Expand Down
145 changes: 137 additions & 8 deletions src/main/kotlin/file/SetupApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import net.ConnectionManager
import org.slf4j.LoggerFactory
import org.eclipse.jgit.api.Git
import java.awt.GraphicsEnvironment
import java.io.IOException
import java.net.URL
import java.nio.charset.StandardCharsets
import java.nio.file.Files
Expand Down Expand Up @@ -126,6 +127,7 @@ object SetupApp {
setup.command == CLICommand.TYPECHECK ||
setup.command == CLICommand.BUILD ||
setup.command == CLICommand.RUN ||
setup.command == CLICommand.RELOAD ||
setup.command == CLICommand.EXPORTOBJECTS -> {
// Only needs to know a compiler is present; skip the version subprocess and update check.
InstallationManager.verifyInstallation(probeVersion = false)
Expand Down Expand Up @@ -154,6 +156,7 @@ object SetupApp {
| grill test
| grill build ExampleMap.w3x
| grill run ExampleMap.w3x
| grill run --hot ExampleMap.w3x, then grill reload after each edit (Lua)
|
|Project commands:
| install [dep|wurstscript|grill] Install/update dependencies, WurstScript compiler, or Grill itself
Expand All @@ -165,6 +168,7 @@ object SetupApp {
| patch [align] Compare project/client patches; align config and stdlib on request
| build <mapfile|map-folder> Build the project using the given map archive or folder
| run [mapfile|map-folder] Build and launch the map in Warcraft III
| reload [mapfile|map-folder] Rebuild and send the edit to the map started by `run --hot` (Lua)
| exportobjects <mapfile|folder> Export object editor data to Wurst source
|
|Global options:
Expand All @@ -176,6 +180,10 @@ object SetupApp {
|
|Run options (also accepts build options):
| --wc3-path <dir> Override the configured/detected Warcraft III installation
| --hot Build for Lua hot reload and start a session for `grill reload`
|
|Run --hot and reload options:
| --custom-map-data <dir> Warcraft III CustomMapData folder that payloads are written to
|
|Generate options:
| --script-mode lua|jass Script mode (default: lua)
Expand Down Expand Up @@ -290,7 +298,16 @@ object SetupApp {
handlePatchAlignment(configData)
}
}
setup.command == CLICommand.BUILD || setup.command == CLICommand.RUN -> {
setup.command == CLICommand.BUILD || setup.command == CLICommand.RUN || setup.command == CLICommand.RELOAD -> {
val hot = setup.command == CLICommand.RELOAD || (setup.command == CLICommand.RUN && setup.hotReload)
if (hot && configData != null && configData.scriptMode != ScriptMode.LUA) {
fail("❌ Hot reload needs a Lua project (`scriptMode: lua` in wurst.build). " +
"For Jass maps use Jass Hot Code Reload (JHCR), a separate tool.")
ExitHandler.exit(1)
}
if (setup.command == CLICommand.RELOAD) {
applyHotRunBuildArgs()
}
progress("🔨 Building project...")
val mapArg = if (setup.commandArg.isBlank()) {
val maps = Files.list(setup.projectRoot).use { stream ->
Expand All @@ -312,7 +329,7 @@ object SetupApp {
} else {
setup.commandArg = mapArg
val client = if (setup.command == CLICommand.RUN) resolveRunClient(configData) else null
buildProject(configData, client)
buildProject(configData, client, hot)
}
}
}
Expand Down Expand Up @@ -1181,11 +1198,90 @@ object SetupApp {
return client
}

private fun buildProject(configData: WurstProjectConfigData, client: Wc3ClientDetector.ClientInfo? = null) {
/** The compiler's command line entry point for hot reload sessions (`start`, `send`). */
private const val HOT_RELOAD_SESSION_CLASS = "de.peeeq.wurstio.languageserver.requests.LuaHotReloadSession"

/** Starts Warcraft III with a built map; replaced in tests, which must never launch the game. */
internal var launchMap: (Wc3ClientDetector.ClientInfo, Path) -> Unit = Wc3MapRunner::launch

/** What `run --hot` built with, so that `reload` builds the same script. */
private fun hotRunRecord(): Path = compilerOutputDir().resolve("hot-run.properties")

private fun recordHotRunBuildArgs() {
val properties = Properties()
properties.setProperty("map", setup.commandArg)
properties.setProperty("dev", setup.devBuild.toString())
Files.createDirectories(compilerOutputDir())
Files.newBufferedWriter(hotRunRecord()).use { properties.store(it, "Written by grill run --hot") }
}

/** `reload` builds with the map and `--dev` of the hot run, unless the command names another map. */
private fun applyHotRunBuildArgs() {
val record = hotRunRecord()
if (!Files.isRegularFile(record)) return
val properties = Properties()
Files.newBufferedReader(record).use { properties.load(it) }
val map = properties.getProperty("map").orEmpty()
if (setup.commandArg.isBlank() && map.isNotBlank()) {
setup.commandArg = map
}
if (properties.getProperty("dev").toBoolean() && setup.commandArg == map) {
setup.devBuild = true
}
}

private fun runHotReloadSession(action: String): WurstProcessResult {
val command = InstallationManager.compilerClassCommand(HOT_RELOAD_SESSION_CLASS, action,
setup.projectRoot.resolve("_build").toAbsolutePath().toString(),
Wc3MapRunner.customMapDataPath(setup).toAbsolutePath().toString())
val result = runWurstProcess(ArrayList(command), compactFallback = false)
if (setup.quiet) {
// The session prints only what the user needs: the payload and its warnings, or why it was refused.
val stream = if (result.exitCode == 0) System.out else System.err
result.output.forEach(stream::println)
}
if (result.exitCode != 0 && result.output.any { it.contains("Could not find or load main class") }) {
detail("The installed compiler has no Lua hot reload. Try: grill install wurstscript")
}
return result
}

private fun startHotReloadSession(): Boolean {
val result = runHotReloadSession("start")
if (result.exitCode != 0) {
fail("❌ Could not start the hot reload session; Warcraft III was not launched.")
return false
}
recordHotRunBuildArgs()
progress("Hot reload session started. After an edit, run `grill reload`.")
return true
}

private fun sendHotReloadPayload(): Nothing {
val result = runHotReloadSession("send")
if (result.exitCode == 0) {
pass("✅ Hot reload payload written.")
ExitHandler.exit(0)
}
fail("❌ Hot reload refused; no payload was written.")
if (result.output.any { it.contains("no map was started with hot run") }) {
detail("Try: start the map with `grill run --hot` first.")
} else {
detail("Try: rebuild and restart the map with `grill run --hot`.")
}
ExitHandler.exit(1)
}

private fun buildProject(configData: WurstProjectConfigData, client: Wc3ClientDetector.ClientInfo? = null,
hot: Boolean = false) {
val args = commonArgs(configData)

args.add("-build")

if (hot) {
args.add("-luaHotReload")
}

if (setup.devBuild) {
args.add("-dev")
}
Expand All @@ -1204,15 +1300,25 @@ object SetupApp {
when (result.exitCode) {
0 -> {
pass("✅ Map built.")
if (setup.command == CLICommand.RELOAD) {
sendHotReloadPayload()
}
if (client != null) {
val built = try {
Wc3MapRunner.builtMap(setup.projectRoot, configData, result.output)
} catch (e: Exception) {
launchFailed(e)
}
val map = if (hot) hotRunMap(built) else built
// The session goes first: it deletes an earlier session's payloads, which the new map would read.
if (hot && !startHotReloadSession()) {
ExitHandler.exit(1)
}
try {
val map = Wc3MapRunner.builtMap(setup.projectRoot, configData, result.output)
Wc3MapRunner.launch(client, map)
launchMap(client, map)
pass("Warcraft III launched.")
} catch (e: Exception) {
fail("Could not launch Warcraft III: ${e.message}. Select another installation with --wc3-path <dir>.")
if (setup.debug) e.printStackTrace()
ExitHandler.exit(1)
launchFailed(e)
}
}
ExitHandler.exit(0)
Expand All @@ -1224,6 +1330,29 @@ object SetupApp {
}
}

/**
* The map a hot run launches: a copy of the built map, because the game keeps the map it runs open and each
* `reload` builds the map again.
*/
private fun hotRunMap(built: Path): Path {
val target = compilerOutputDir().resolve("hot-run").resolve(built.fileName)
try {
Files.createDirectories(target.parent)
Files.copy(built, target, StandardCopyOption.REPLACE_EXISTING)
} catch (e: IOException) {
fail("❌ Could not copy the map for the hot run: ${e.message}. Close Warcraft III if it still runs an earlier hot run.")
if (setup.debug) e.printStackTrace()
ExitHandler.exit(1)
}
return target.toAbsolutePath().normalize()
}

private fun launchFailed(e: Exception): Nothing {
fail("Could not launch Warcraft III: ${e.message}. Select another installation with --wc3-path <dir>.")
if (setup.debug) e.printStackTrace()
ExitHandler.exit(1)
}

private fun exportObjects(mapPath: Path) {
val args = ArrayList(InstallationManager.compilerLaunchCommand().toList())
args.add("-exportobjects")
Expand Down
12 changes: 12 additions & 0 deletions src/main/kotlin/file/SetupMain.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ class SetupMain {

var devBuild = false

/** `run --hot`: build for Lua hot reload and start a hot reload session before launching. */
var hotReload = false

/** Overrides the Warcraft III CustomMapData folder that hot reload payloads are written to. */
var customMapDataPath: Path? = null

var projectRoot: Path = SetupApp.DEFAULT_DIR

var gamePath: Path? = null
Expand Down Expand Up @@ -101,12 +107,18 @@ class SetupMain {
opt.runOption(this, argsList.subList(i + 1, argEnd))
i += 1 + opt.argCount
} else {
// A map may follow the flags (`grill run --hot Map.w3x`).
if (commandArg.isEmpty() && command in MAP_COMMANDS && !argsList[i].startsWith("-")) {
commandArg = argsList[i]
}
i++
}
}
}

companion object {
private val MAP_COMMANDS = setOf(CLICommand.BUILD, CLICommand.RUN, CLICommand.RELOAD)

@JvmStatic
fun main(args: Array<String>) {
SetupMain().doMain(args)
Expand Down
10 changes: 10 additions & 0 deletions src/main/kotlin/file/Wc3MapRunner.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ internal object Wc3MapRunner {
return target.toAbsolutePath().normalize()
}

/**
* Where a hot reload writes its payloads for the running map to read: `--custom-map-data`, then the VS Code setting
* `wurst.customMapDataPath`, then `CustomMapData` in the Warcraft III documents folder (as the language server).
*/
fun customMapDataPath(setup: SetupMain, documentsRoot: () -> Path = ::warcraftDocumentsRoot): Path {
setup.customMapDataPath?.let { return it }
WurstProjectConfig.configuredCustomMapDataPath(setup.projectRoot)?.let { return it }
return documentsRoot().resolve("CustomMapData")
}

private fun warcraftDocumentsRoot(): Path {
return when {
System.getProperty("os.name").startsWith("Linux", ignoreCase = true) -> {
Expand Down
6 changes: 6 additions & 0 deletions src/main/kotlin/global/InstallationManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,12 @@ object InstallationManager {
return arrayOf(java, "-jar", compiler.toAbsolutePath().toString(), *extraArgs)
}

/** Runs [mainClass] from the installed compiler jar, for its entry points other than the compiler's main. */
fun compilerClassCommand(mainClass: String, vararg extraArgs: String): List<String> {
val compiler = detectCompilerJar() ?: compilerJar
return listOf(bundledJavaCommand(), "-cp", compiler.toAbsolutePath().toString(), mainClass, *extraArgs)
}

private fun bundledJavaCommand(): String {
return if (Files.exists(bundledJava) && Files.isExecutable(bundledJava)) {
bundledJava.toAbsolutePath().toString()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package de.peeeq.wurstio.languageserver.requests;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;

/**
* Stands in for the compiler's hot reload session class (same name, so Grill's command line reaches it) without a
* running map: it records each call and answers as the compiler does.
*/
public class LuaHotReloadSession {
public static void main(String[] args) throws Exception {
Path buildDir = Path.of(args[1]);
Path customMapData = Path.of(args[2]);
Path project = buildDir.getParent();
Files.write(project.resolve("session-arguments.txt"), List.of(String.join("|", args)),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Path session = buildDir.resolve("luaHotReload/session.json");
if (args[0].equals("start")) {
Files.createDirectories(session.getParent());
Files.writeString(session, "{}");
System.out.println("session started");
return;
}
if (!Files.exists(session)) {
System.out.println("The edit cannot be hot reloaded, rebuild and restart the map:\n"
+ " no map was started with hot run (or -luaHotReload): start the map with hot run first");
System.exit(1);
}
if (Files.exists(project.resolve("refuse-reload"))) {
System.out.println("The edit cannot be hot reloaded, rebuild and restart the map:\n"
+ " the type of field Hello_Unit_hp changed");
System.exit(1);
}
Path file = customMapData.resolve("Wurst/hotreload-1.pld");
Files.createDirectories(file.getParent());
Files.writeString(file, "payload");
System.out.println("payload 1 (Hello_greet) written to " + file);
System.out.println("warning: closure Hello_init_closure1 was removed; instances made before keep their old body");
}
}
Loading
Loading