-- name: Map Scaler \\#EE4B2B\\improved -- description: A working Map Scaler for SM64CoopDX!!\n\nBased on Super Mario 64 Y-Scaled by \\#2CB3FF\\Rovertronic\\#dcdcdc\\.\n\nStretch the map, flatten it, or flip an axis. The host changes the scale for the whole lobby. Press L while paused to open the menu, or use /scale X Y Z, /scale N, or /scale reset in chat.\n\n- \\#FFFF00\\Credits\\#dcdcdc\\:\n\n\\#FF0000\\LYNX\\#ffff00\\64\\#dcdcdc\\: Made the mod with alot of improvements and bug fixes, inspired by the Y-Scaled mod.\n\\#00f000\\Kitans54\\#dcdcdc\\: Contributed to the mod.\n\\#ffff00\\THE C-CAM IS RECOMMENDED!\n\n\\#EE4B2B\\DISCLAIMER\\#dcdcdc\\: This mod becomes very unstable when scaled beyond 4 or higher values. -- version: 1.0 -- category: gameplay local normalScale = "1 1 1" local applied = normalScale local attempted, retryAfter local pendingObjects, objectsCheckbox local function objectsEnabled() return gGlobalSyncTable.mapScalerObjects ~= false end local function menuObjects() if pendingObjects ~= nil then return pendingObjects end return objectsEnabled() end local firstSurface, areaScale local spawns, water = {}, {} local scene local backroomsRestart = false local castleRestart local lowerLimit = gLevelValues.floorLowerLimit local hudKey, hudLabel local pauseMenu local pendingScale, pendingCamera, resumeRequested local parallelCamera, cameraOverride = false, nil local axisNames = { "X", "Y", "Z" } local scaleNotice = "mapScalerScaleChanged" local function readNumber(text) local n = tonumber(text) if n and n > -math.huge and n < math.huge then return n + 0.0 end end local function readCommandNumber(text) if text and (text:match("^[+-]?%d+$") or text:match("^[+-]?%d*%.%d%d?$")) then return readNumber(text) end end local function parseScale(msg) local a, b, c = msg:match("^(%S+)%s+(%S+)%s+(%S+)$") local x, y, z = readNumber(a), readNumber(b), readNumber(c) if x and y and z then return x, y, z end end local function parseCommandScale(msg) local a, b, c = msg:match("^(%S+)%s+(%S+)%s+(%S+)$") if not a then a = msg:match("^(%S+)$") if not a then return end b, c = a, a end local overPrecision = "^[+-]?%d*%.%d%d%d+$" if a:match(overPrecision) or b:match(overPrecision) or c:match(overPrecision) then return nil, nil, nil, true end local x, y, z = readCommandNumber(a), readCommandNumber(b), readCommandNumber(c) if x and y and z then return x, y, z end end local function formatScale(n) return (math.abs(n) < 1e12 and "%.2f" or "%.2E"):format(n) end local function multiplier(n) local label = formatScale(n) if math.abs(n) < 1e12 then label = label:gsub("0+$", ""):gsub("%.$", "") end return "x" .. label end local function isUnstable(n) return math.abs(n) > 3 end local function announceScale(x, y, z) local label = multiplier(x) if x ~= y or y ~= z then label = label .. " " .. multiplier(y) .. " " .. multiplier(z) end if isUnstable(x) or isUnstable(y) or isUnstable(z) then djui_chat_message_create([[\#FFFF00\WARNING: \#dcdcdc\World scale changed to an \#FF0000\UNSTABLE \#DCDCDC\number: ]] .. label .. ".") else djui_chat_message_create([[\#00FF00\SUCCESS: \#dcdcdc\World scale changed to ]] .. label .. "!") end end local function changeScale(x, y, z) if not network_is_server() then return false end local value = ("%.17g %.17g %.17g"):format(x, y, z) if value == (gGlobalSyncTable.worldScale or normalScale) then return false end gGlobalSyncTable.worldScale = value announceScale(x, y, z) -- A live notice, separate from the scale a late joiner receives. network_send(true, { [scaleNotice] = value }) return true end local function inPause() return get_current_play_mode() == PLAY_MODE_PAUSED end local function requestScale(x, y, z) if not network_is_server() then return end if inPause() then pendingScale = ("%.17g %.17g %.17g"):format(x, y, z) else changeScale(x, y, z) end end local function onPacket(data) if network_is_server() or type(data[scaleNotice]) ~= "string" then return end local x, y, z = parseScale(data[scaleNotice]) if x then announceScale(x, y, z) end end local function scaleCommand(msg) if not network_is_server() then djui_chat_message_create("The host sets the scale for the whole lobby.") return true end msg = (msg or ""):match("^%s*(.-)%s*$") local command = msg:lower() local x, y, z, extraDecimals if command == "reset" or command == "r" then x, y, z = 1, 1, 1 else x, y, z, extraDecimals = parseCommandScale(msg) end if extraDecimals then djui_chat_message_create([[\#FF0000\ERROR: \#dcdcdc\Maximum \#FFFF00\two \#dcdcdc\decimals are allowed!]]) return true end if not x then djui_chat_message_create([[\#FF0000\ERROR: \#dcdcdc\Invalid scale. Use /scale X Y Z, /scale N, /scale reset, or /scale r.]]) return true end requestScale(x, y, z) return true end local function readPauseScale(menu) local key = pendingScale or gGlobalSyncTable.worldScale or normalScale if key ~= menu.key then local x, y, z = parseScale(key) menu.key = key menu.axes = { x or 1, y or 1, z or 1 } end end local function openScalePause() local camera = pendingCamera if camera == nil then camera = parallelCamera end pauseMenu = { row = 1, h = 0, v = 0, hFrames = 0, vFrames = 0, camera = camera, objects = menuObjects() } readPauseScale(pauseMenu) set_pause_menu_hidden(true) end local function closeScalePause() if pauseMenu then pauseMenu = nil set_pause_menu_hidden(false) end end local function menuDirection(pressed, held, positive, negative, stick, threshold) local buttons = pressed | held local plus = (buttons & positive) ~= 0 local minus = (buttons & negative) ~= 0 if plus ~= minus then return plus and 1 or -1 end if stick >= threshold then return 1 end if stick <= -threshold then return -1 end return 0 end local function heldFrames(direction, previous, frames) if direction == 0 then return 0 end if direction ~= previous then return 1 end return frames + 1 end local function onPlayMode(mode) if mode ~= PLAY_MODE_PAUSED or not is_game_paused() or not gNetworkPlayers[0].connected or not gMarioStates[0].area then closeScalePause() return end if djui_hud_is_pause_menu_created() or djui_is_chatbox_open() or djui_is_playerlist_open() then return end local c = gControllers[0] local pressed, held = c.buttonPressed, c.buttonDown if (pressed & R_TRIG) ~= 0 then closeScalePause() return end if not pauseMenu then if (pressed & L_TRIG) ~= 0 and not is_pause_menu_hidden() then c.buttonPressed = pressed & ~L_TRIG openScalePause() end return end -- CoopDX also uses L for developer reload; consume it only in our menu. if (pressed & L_TRIG) ~= 0 then pressed = pressed & ~L_TRIG c.buttonPressed = pressed end local menu = pauseMenu readPauseScale(menu) if (pressed & B_BUTTON) ~= 0 then c.buttonPressed = pressed & ~(B_BUTTON | A_BUTTON | START_BUTTON) closeScalePause() return end if menu.row == 6 and network_is_server() and (pressed & (A_BUTTON | START_BUTTON)) == A_BUTTON then c.buttonPressed = pressed & ~A_BUTTON menu.objects = not menu.objects play_sound(SOUND_MENU_CHANGE_SELECT, gGlobalSoundSource) return end if (pressed & (A_BUTTON | START_BUTTON)) ~= 0 then c.buttonPressed = pressed & ~(A_BUTTON | START_BUTTON) pendingCamera = menu.camera if network_is_server() then pendingObjects = menu.objects end requestScale(table.unpack(menu.axes)) closeScalePause() resumeRequested = (pressed & START_BUTTON) ~= 0 return end local v = menuDirection(pressed, held, D_JPAD, U_JPAD, -c.rawStickY, 60) local h = menuDirection(pressed, held, R_JPAD, L_JPAD, c.rawStickX, 30) menu.vFrames = heldFrames(v, menu.v, menu.vFrames) menu.hFrames = heldFrames(h, menu.h, menu.hFrames) menu.v, menu.h = v, h if menu.vFrames == 1 or (menu.vFrames > 12 and menu.vFrames % 4 == 1) then local row = math.max(1, math.min(6, menu.row + v)) if row ~= menu.row then menu.row = row play_sound(SOUND_MENU_CHANGE_SELECT, gGlobalSoundSource) return end end local axis = menu.row - 1 if axis >= 1 and axis <= 3 and network_is_server() and (menu.hFrames == 1 or menu.hFrames > 15) then local step = menu.hFrames > 60 and 0.10 or 0.05 local n = tonumber(("%.2f"):format(menu.axes[axis] + h * step)) + 0.0 if n ~= menu.axes[axis] then menu.axes[axis] = n play_sound(SOUND_MENU_CHANGE_SELECT, gGlobalSoundSource) end elseif menu.row == 5 and menu.hFrames == 1 then menu.camera = h > 0 play_sound(SOUND_MENU_CHANGE_SELECT, gGlobalSoundSource) elseif menu.row == 6 and network_is_server() and menu.hFrames == 1 then menu.objects = h > 0 play_sound(SOUND_MENU_CHANGE_SELECT, gGlobalSoundSource) end end local lakituModes = { [CAMERA_MODE_RADIAL] = true, [CAMERA_MODE_OUTWARD_RADIAL] = true, [CAMERA_MODE_CLOSE] = true, [CAMERA_MODE_FREE_ROAM] = true, } local function updateParallelCamera(m) local camera = m.area.camera if not camera then return end if cameraOverride and (cameraOverride.camera ~= camera or ~cameraOverride.camera) then cameraOverride = nil end if camera.cutscene ~= 0 then return end if parallelCamera and lakituModes[camera.mode] then local old = camera.mode set_camera_mode(camera, CAMERA_MODE_8_DIRECTIONS, 1) if camera.mode == CAMERA_MODE_8_DIRECTIONS then cameraOverride = { camera = camera, mode = old } end elseif not parallelCamera and cameraOverride then if camera.mode == CAMERA_MODE_8_DIRECTIONS then set_camera_mode(camera, cameraOverride.mode, 1) end cameraOverride = nil end end local pauseHint = "L: Map Scaler Menu" local courseGlyphWidths = { L = 5, [":"] = 4, [" "] = 5, M = 8, a = 6, p = 5, S = 6, c = 5, l = 3, e = 5, r = 5, n = 5, u = 5 } local courseGlyphs local function pauseTextScale() -- Match the size of CoopDX's R button hint while keeping the N64 menu layout. djui_hud_set_resolution(RESOLUTION_DJUI) local uiHeight = djui_hud_get_screen_height() djui_hud_set_resolution(RESOLUTION_N64) return djui_hud_get_screen_height() / math.max(uiHeight, 1) end local function printShadowedPauseHint(x, y, scale) djui_hud_set_color(0, 0, 0, 255) djui_hud_set_text_color(0, 0, 0, 255) djui_hud_print_text(pauseHint, x, y + 2 * scale, scale) djui_hud_set_color(255, 255, 255, 255) djui_hud_set_text_color(255, 255, 255, 255) djui_hud_print_text(pauseHint, x, y, scale) end local function drawPauseHintGlyphs(x, y, glyphScale) for char in pauseHint:gmatch(".") do if char ~= " " then djui_hud_render_texture(courseGlyphs[char], x + 8 * glyphScale, y + 16 * glyphScale, glyphScale, -glyphScale) end x = x + courseGlyphWidths[char] * glyphScale end end local function renderPauseHint(x, y, scale) if not courseGlyphs then courseGlyphs = {} for char in pairs(courseGlyphWidths) do if char ~= " " then local glyph = char == ":" and "ellipsis" or char:gsub("%u", "%0_") local texture = get_texture_info("texture_font_char_us_" .. glyph) if not texture or texture.width ~= 16 or texture.height ~= 8 then courseGlyphs = false break end courseGlyphs[char] = texture end end end if courseGlyphs == false then djui_hud_set_font(FONT_NORMAL) djui_hud_set_text_alignment(0, 0) printShadowedPauseHint(x, y, scale) return end local filter = djui_hud_get_filter() local rotation, pivotX, pivotY = djui_hud_get_rotation() local glyphScale = scale * 2 -- This font uses 16px glyph cells; the R hint uses 32px cells. djui_hud_set_filter(FILTER_NEAREST) -- The course font stores each glyph sideways and flipped. djui_hud_set_rotation(0x4000, 0, 0) djui_hud_set_color(0, 0, 0, 255) drawPauseHintGlyphs(x, y + glyphScale, glyphScale) djui_hud_set_color(255, 255, 255, 255) drawPauseHintGlyphs(x, y, glyphScale) djui_hud_set_rotation(rotation, pivotX, pivotY) djui_hud_set_filter(filter) end local function drawPauseCursor(x, y, scale) -- Recreate the vanilla cursor's 8-by-16 triangle with pixel-wide strips. djui_hud_set_color(255, 255, 255, 255) for column = 0, 7 do djui_hud_render_rect(x + column * scale, y + column * scale, scale, (16 - column * 2) * scale) end end local function renderPause(menu, scale) local width, height = djui_hud_get_screen_width(), djui_hud_get_screen_height() local x = math.max(16, math.floor((width - 320) * 0.5 + 50)) local step = math.max(14, 28 * scale) local hintGap = math.max(17, 34 * scale) local hintStep = math.max(11, 28 * scale) local host = network_is_server() local menuHeight = 5 * step + hintGap + (host and hintStep or 0) + 32 * scale local top = math.max(8, math.min(64, height - 12 - menuHeight)) djui_hud_set_color(0, 0, 0, 110) djui_hud_render_rect(0, 0, width, height) djui_hud_set_font(FONT_NORMAL) djui_hud_set_text_alignment(0, 0) djui_hud_set_text_color(255, 255, 255, 255) drawPauseCursor(x - 20 * scale, top + (menu.row - 1) * step + 7 * scale, scale) djui_hud_print_text("Return", x, top, scale) for i, axis in ipairs(axisNames) do local n = menu.axes[i] local text = axis .. " Scale: " .. formatScale(n) .. (isUnstable(n) and " (UNSTABLE)" or "") djui_hud_print_text(text, x, top + i * step, scale) end djui_hud_print_text("Parallel Lakitu Cam: " .. (menu.camera and "On" or "Off"), x, top + step * 4, scale) local objects = menu.objects if not host then objects = objectsEnabled() end djui_hud_print_text("Enable Scalable Objects: " .. (objects and "On" or "Off"), x, top + step * 5, scale) local hint = host and "A: Keep changes B: Cancel" or "Only the host can change the scale" if host and menu.row == 6 then hint = "A: Toggle B: Cancel" end local hintY = top + 5 * step + hintGap djui_hud_print_text(hint, x, hintY, scale) if host then djui_hud_print_text("START: Resume and apply", x, hintY + hintStep, scale) end end local function renderScale() if not gNetworkPlayers[0].connected or not gMarioStates[0].area then return end if pauseMenu and not djui_hud_is_pause_menu_created() then renderPause(pauseMenu, pauseTextScale()) return end if inPause() and is_game_paused() and not is_pause_menu_hidden() and not djui_hud_is_pause_menu_created() then djui_hud_set_resolution(RESOLUTION_N64) -- The ROM's 320x240 menu anchors the 16-pixel glyphs at (20, 180) from the bottom. local left = (djui_hud_get_screen_width() - 320) * 0.5 + 20 renderPauseHint(left, djui_hud_get_screen_height() - 196, 5 / 16) end if hud_is_hidden() or hud_get_value(HUD_DISPLAY_FLAGS) == HUD_DISPLAY_FLAGS_NONE then return end local key = gGlobalSyncTable.worldScale or normalScale if key ~= hudKey then local x, y, z = parseScale(key) -- FONT_HUD maps @ to the original multiply glyph. hudLabel = ("X @%s\nY @%s\nZ @%s"):format(formatScale(x or 1), formatScale(y or 1), formatScale(z or 1)) hudKey = key end djui_hud_set_resolution(RESOLUTION_N64) djui_hud_set_font(FONT_HUD) djui_hud_set_filter(FILTER_NEAREST) djui_hud_set_text_alignment(0, 0) djui_hud_set_text_color(255, 255, 255, 255) local x, step = 22, 20 -- Put the last row where Y-Scaled draws its original single row. local y = djui_hud_get_screen_height() - 35 - step * 2 djui_hud_print_text(hudLabel, x, y, 1) end local function mirrorsHorizontally(x, z) return (x < 0) ~= (z < 0) end local function coord(v, factor) local n = (v + 0.0) * factor n = n < 0 and math.ceil(n) or math.floor(n) return math.max(-32760, math.min(32760, n)) end function _G.mapScalerAreaFactors() if areaScale and firstSurface and not (~firstSurface) then return areaScale[2], areaScale[3], areaScale[4] end return 1, 1, 1 end local function onSurface(s, dynamic) if dynamic or s.object ~= nil then return end if not firstSurface or ~firstSurface then firstSurface = s local key = gGlobalSyncTable.worldScale or normalScale local x, y, z = parseScale(key) areaScale = x and { key, x, y, z } or { normalScale, 1, 1, 1 } areaScale.objects = objectsEnabled() end if areaScale[1] == normalScale then return end -- This hook runs before CoopDX adds the triangle to its collision grid. local _, x, y, z = table.unpack(areaScale) local a, b, c = s.vertex1, s.vertex2, s.vertex3 local ax, ay, az = coord(a.x, x), coord(a.y, y), coord(a.z, z) local bx, by, bz = coord(b.x, x), coord(b.y, y), coord(b.z, z) local cx, cy, cz = coord(c.x, x), coord(c.y, y), coord(c.z, z) -- Keep floors facing up for a horizontal mirror. Negative Y follows Y-Scaled's winding. if mirrorsHorizontally(x, z) then bx, by, bz, cx, cy, cz = cx, cy, cz, bx, by, bz end local ux, uy, uz, vx, vy, vz = bx-ax, by-ay, bz-az, cx-ax, cy-ay, cz-az local nx, ny, nz = uy*vz-uz*vy, uz*vx-ux*vz, ux*vy-uy*vx local length = math.sqrt(1.0*nx*nx + 1.0*ny*ny + 1.0*nz*nz) a.x, a.y, a.z = ax, ay, az b.x, b.y, b.z = bx, by, bz c.x, c.y, c.z = cx, cy, cz vec3s_set(s.prevVertex1, ax, ay, az) vec3s_set(s.prevVertex2, bx, by, bz) vec3s_set(s.prevVertex3, cx, cy, cz) if length == 0 or (y <= 0 and ny > 0 and s.type == SURFACE_DEATH_PLANE) then -- Hide collapsed triangles and Y-Scaled's death floors from both collision passes. s.type = SURFACE_CAMERA_BOUNDARY s.flags = s.flags | SURFACE_FLAG_NO_CAM_COLLISION nx, ny, nz = 1, 0, 0 else nx, ny, nz = nx / length, ny / length, nz / length end vec3f_set(s.normal, nx, ny, nz) s.originOffset = -(nx*ax + ny*ay + nz*az) s.lowerY, s.upperY = math.min(ay, by, cy) - 5, math.max(ay, by, cy) + 5 s.flags = s.flags & ~SURFACE_FLAG_X_PROJECTION end local function triangleVertices(word, reverse) local a, b, c = (word >> 17) & 0x7f, (word >> 9) & 0x7f, (word >> 1) & 0x7f if reverse then b, c = c, b end return a, b, c end local function writeTriangles(cmd, op, w0, w1, reverse) local a, b, c = triangleVertices(w0, reverse) if op == G_TRI1 then gfx_set_command(cmd, "gsSP1Triangle(%i, %i, %i, 0)", a, b, c) else local d, e, f = triangleVertices(w1, reverse) gfx_set_command(cmd, "gsSP2Triangles(%i, %i, %i, 0, %i, %i, %i, 0)", a, b, c, d, e, f) end end local function scaleDisplayList(list, state) if state.display[list._pointer] then return end state.display[list._pointer] = true local cmd = list while cmd do local op = gfx_get_op(cmd) if op == G_DL then local child = gfx_get_display_list(cmd) if child then scaleDisplayList(child, state) end if (cmd.w0 & 0x10000) ~= 0 then break end elseif op == G_VTX or op == G_VTX_EXT then local v = gfx_get_vertex_buffer(cmd) local count = gfx_get_vertex_count(cmd) for i = 1, count do if not v then break end local key = v._pointer if not state.vertex[key] then -- Area GeoLayouts point to CoopDX's writable DynOS vertex copies. state.vertex[key] = { v, v.x, v.y, v.z } v.x, v.y, v.z = coord(v.x, state.x), coord(v.y, state.y), coord(v.z, state.z) end if i < count then v = vtx_get_next_vertex(v) end end elseif state.mirrored and (op == G_TRI1 or op == G_TRI2) and not state.triangles[cmd._pointer] then local w0, w1 = cmd.w0, cmd.w1 state.triangles[cmd._pointer] = { cmd, op, w0, w1 } writeTriangles(cmd, op, w0, w1, true) elseif op == G_ENDDL then break end cmd = gfx_get_next_command(cmd) end end local displayNodes = { [GRAPH_NODE_TYPE_DISPLAY_LIST] = true, [GRAPH_NODE_TYPE_SCALE] = true, [GRAPH_NODE_TYPE_SCALE_XYZ] = true, [GRAPH_NODE_TYPE_TRANSLATION] = true, [GRAPH_NODE_TYPE_ROTATION] = true, [GRAPH_NODE_TYPE_TRANSLATION_ROTATION] = true, } local function prepareGraph(first, state, underCamera) if not first then return end local node = first repeat local kind = node.type if kind ~= GRAPH_NODE_TYPE_OBJECT_PARENT and kind ~= GRAPH_NODE_TYPE_OBJECT then if underCamera and displayNodes[kind] then local graph = cast_graph_node(node) local source = graph.displayList if source then scaleDisplayList(source, state) end end prepareGraph(node.children, state, underCamera or kind == GRAPH_NODE_TYPE_CAMERA) end node = node.next until node == nil or node == first end local function restoreTerrain() if not scene then return end for _, saved in pairs(scene.vertex) do local v, x, y, z = table.unpack(saved) if not (~v) then v.x, v.y, v.z = x, y, z end end for _, saved in pairs(scene.triangles) do local cmd, op, w0, w1 = table.unpack(saved) if not (~cmd) then writeTriangles(cmd, op, w0, w1, false) end end for _, saved in ipairs(scene.paintings) do local p, x, y, z = table.unpack(saved) p.posX, p.posY, p.posZ = x, y, z end end -- Keep level fixtures explicit: solid enemies also run in CoopDX's surface list. local scenery = {} for name in ([[ BreakableBoxSmall PointLight AmbientLight WaterfallSoundLoop VolcanoSoundLoop SandSoundLoop BirdsSoundLoop ActivatedBackAndForthPlatform AnimatesOnFloorSwitchPress AnotherElavator AnotherTiltingPlatform ArrowLift BbhTiltingTrapPlatform BbhTumblingBridge BetaChestBottom BetaChestLid BetaTrampolineSpring BetaTrampolineTop BitfsSinkingCagePlatform BitfsSinkingPlatforms BitfsTiltingInvertedPyramid BlueCoinSwitch BooBossSpawnedBridge BookSwitch BowserSubDoor BowsersSub BreakableBox BulletBillCannon Cannon CannonBarrel CannonBaseUnused CannonClosed CapSwitch CapSwitchBase CastleFlagWaving CastleFloorTrap ChainChompGate CheckerboardElevatorGroup CheckerboardPlatformSub ClockHourHand ClockMinuteHand Coffin CoffinSpawner ControllablePlatform ControllablePlatformSub DDDPole DddMovingPole DddWarp DecorativePendulum DonutPlatform DonutPlatformSpawner Door DoorWarp ExclamationBox ExitPodiumWarp FallingBowserPlatform FallingPillar FallingPillarHitbox FerrisWheelAxle FerrisWheelPlatform FloorSwitchAnimatesObject FloorSwitchGrills FloorSwitchHardcodedModel FloorSwitchHiddenObjects FloorTrapInCastle GiantPole HauntedBookshelf HauntedBookshelfManager HiddenAt120Stars HiddenObject HiddenStaircaseStep HmcElevatorPlatform Igloo InSunkenShip InSunkenShip2 InSunkenShip3 InvisibleObjectsUnderBridge JrbFloatingBox JrbFloatingPlatform JrbSlidingBox KickableBoard KoopaFlag KoopaRaceEndpoint LargeBomp LllBowserPuzzle LllBowserPuzzlePiece LllDrawbridge LllDrawbridgeSpawner LllFloatingWoodBridge LllHexagonalMesh LllMovingOctagonalMeshPlatform LllRollingLog LllRotatingBlockWithFireBars LllRotatingHexagonalPlatform LllRotatingHexagonalRing LllSinkingRectangularPlatform LllSinkingRockBlock LllSinkingSquarePlatforms LllTiltingInvertedPyramid LllTumblingBridge LllVolcanoFallingTrap LllWoodPiece MerryGoRound MeshElevator MessagePanel MoatGrills MontyMoleHole OctagonalPlatformRotating OpenableCageDoor OpenableGrill PenguinRaceFinishLine PenguinRaceShortcutCheck PillarBase PlatformOnTrack PoleGrabbing PurpleSwitchHiddenBoxes PushableMetalBox PyramidElevator PyramidElevatorTrajectoryMarkerBall PyramidTop RockSolid RotatingCounterClockwise RotatingPlatform RrCruiserWing RrElevatorPlatform RrRotatingBridgePlatform Seaweed SeaweedBundle SeesawPlatform ShipPart3 SignOnWall SlidingPlatform2 SlidingSnowMound SmallBomp SquarishPathMoving SquarishPathParent SquishablePlatform SslMovingPyramidWall StarDoor StaticCheckeredPlatform StaticObject SunkenShipPart SunkenShipPart2 SunkenShipSetRotation SwingPlatform TTC2DRotator TTCCog TTCElevator TTCMovingBar TTCPendulum TTCPitBlock TTCRotatingSolid TTCSpinner TTCTreadmill ThiHugeIslandTop ThiTinyIslandTop TiltingBowserLavaPlatform Tower TowerDoor TowerPlatformGroup TrackBall TreasureChestBottom TreasureChestTop TreasureChests TreasureChestsJrb TreasureChestsShip Tree TtmRollingLog TumblingBridgePlatform UkikiCage UkikiCageChild UnusedPoundablePlatform WarpPipe WaterBombCannon WaterLevelDiamond WaterLevelPillar WdwExpressElevator WdwExpressElevatorPlatform WdwRectangularFloatingPlatform WdwSquareFloatingPlatform WfBreakableWallLeft WfBreakableWallRight WfElevatorTowerPlatform WfRotatingWoodenPlatform WfSlidingPlatform WfSlidingTowerPlatform WfSolidTowerPlatform WfTumblingBridge WoodenPost ]]):gmatch("%S+") do local id = _G["id_bhv" .. name] if id then scenery[id] = true end end -- Custom level behaviors can opt in without classifying a mob as scenery. function _G.mapScalerRegisterScenery(id) if type(id) == "number" then scenery[id] = true end end local groundProps = { [id_bhvTree] = true, [id_bhvMessagePanel] = true, [id_bhvWoodenPost] = true, [id_bhvPoleGrabbing] = true, [id_bhvGiantPole] = true, [id_bhvCannonClosed] = true, } local mobs = {} for name in ([[Goomba Koopa Bobomb BobombBuddy PiranhaPlant ChainChomp SmallBully BigBully SmallChillBully BigChillBully Chuckya Scuttlebug Spindrift SmallWhomp KingBobomb WhompKingBoss ToadMessage SmallPenguin TuxiesMother RacingPenguin SLWalkingPenguin PenguinBaby]]):gmatch("%S+") do mobs[_G["id_bhv" .. name]] = true end for name in ([[FlyGuy Boo YellowCoin OneCoin RedCoin MovingYellowCoin MovingBlueCoin HiddenBlueCoin CoinFormation RecoveryHeart]]):gmatch("%S+") do mobs[_G["id_bhv" .. name]] = false end local starPlacements = { [id_bhvStar] = true, [id_bhvHiddenStar] = true, [id_bhvHiddenRedCoinStar] = true, [id_bhvBowserCourseRedCoinStar] = true, } local starFloorOffsets = {{1,0}, {-1,0}, {0,1}, {0,-1}, {1,1}, {-1,1}, {1,-1}, {-1,-1}} local starFloorRadii = {80, 160, 320, 640} local function safeStarFloor(x, z) local y, floor = find_floor(x, 100, z) if floor and floor.type ~= SURFACE_DEATH_PLANE and floor.type ~= SURFACE_BURNING and floor.type ~= SURFACE_INSTANT_QUICKSAND and floor.type ~= SURFACE_INSTANT_MOVING_QUICKSAND then return y end end local function flatStarPosition(x, z) local y = safeStarFloor(x, z) if y then return x, y + 64, z end for _, radius in ipairs(starFloorRadii) do for _, direction in ipairs(starFloorOffsets) do local nx, nz = x + direction[1] * radius, z + direction[2] * radius if math.abs(nx) <= 32760 and math.abs(nz) <= 32760 then y = safeStarFloor(nx, nz) if y then return nx, y + 64, nz end end end end return x, 64, z end local function placeObject(o, x, y, z) o.oPosX, o.oPosY, o.oPosZ = x, y, z local gfx = o.header.gfx vec3f_set(gfx.pos, x, y + (o.oGraphYOffset or 0), z) end local aliases = {} local function placementId(o) local id = get_id_from_behavior(o.behavior) if scenery[id] or starPlacements[id] or id < id_bhv_max_count then return id end if o.initBhvCommand then local original = get_id_from_behavior(o.initBhvCommand) if original < id_bhv_max_count then return original end end -- A fully replaced vanilla behavior has a new ID in both script pointers. if aliases[id] == nil then aliases[id] = id for vanilla in pairs(scenery) do if vanilla < id_bhv_max_count and obj_has_behavior_id(o, vanilla) ~= 0 then aliases[id] = vanilla break end end end return aliases[id] end local function placeSpawn(o, late) if ~o or o.activeFlags == 0 or (o.coopFlags & COOP_OBJ_FLAG_NETWORK) ~= 0 then return end local gfx = o.header.gfx if gfx.areaIndex ~= scene.areaIndex then return end local slot = o._pointer or o if scene.placed[slot] == o then return end local id = placementId(o) local warp = get_mario_spawn_type(o) ~= 0 if not (warp or starPlacements[id] or mobs[id] ~= nil or (scene.objects and scenery[id])) then return end -- Children such as bridge planks and chest lids inherit their parent's world position. local parent = o.parentObj if parent and parent ~= o and parent.behavior then return end if late and starPlacements[id] and o.respawnInfoType == RESPAWN_INFO_TYPE_NULL then return end scene.placed[slot] = o local ox, oy, oz = o.oPosX, o.oPosY, o.oPosZ local x, y, z = scene.x, scene.y, scene.z local px, py, pz = coord(ox,x), coord(oy,y), coord(oz,z) local hx, hy, hz = coord(o.oHomeX,x), coord(o.oHomeY,y), coord(o.oHomeZ,z) if y == 0 and starPlacements[id] then px, py, pz = flatStarPosition(px, pz) hx, hy, hz = px, py, pz elseif mobs[id] or (y == 0 and groundProps[id]) then local height, floor = find_floor(px, py + 100, pz) if floor then py, hy = height, height end end o.oHomeX, o.oHomeY, o.oHomeZ = hx, hy, hz if scene.objects and scenery[id] then local s = o.header.gfx.scale obj_scale_xyz(o, s.x * math.abs(x), s.y * math.abs(y), s.z * math.abs(z)) local width = math.max(math.abs(x), math.abs(z)) o.hitboxRadius = o.hitboxRadius * width o.hitboxHeight = o.hitboxHeight * math.abs(y) o.hurtboxRadius = o.hurtboxRadius * width o.hurtboxHeight = o.hurtboxHeight * math.abs(y) o.oCollisionDistance = o.oCollisionDistance * math.max(width, math.abs(y), 1) end placeObject(o, px, py, pz) -- If the native collision loader already built the object's matrix, move its -- origin as well. Keep the rotation, local vertices and scale untouched. local matrix = gfx.throwMatrix if matrix and matrix == o.transform then matrix.m30, matrix.m31, matrix.m32 = matrix.m30 + px-ox, matrix.m31 + py-oy, matrix.m32 + pz-oz end if warp then scene.warpOrigins[slot] = { ox, oy, oz } end if late and o.oSyncID ~= 0 and (o.coopFlags & COOP_OBJ_FLAG_LUA) ~= 0 and sync_object_is_initialized(o.oSyncID) and sync_object_is_owned_locally(o.oSyncID) then network_send_object(o, true) end end local function placeQueued() if #spawns == 0 then return end local queue = spawns spawns = {} for _, o in ipairs(queue) do placeSpawn(o, true) end end local function placeLoaded() -- Level-script, macro and terrain objects need not arrive through the same callback. -- Walk the actual engine lists once after the level has assigned positions and parents. for list = 0, NUM_OBJ_LISTS - 1 do local o = obj_get_first(list) while o do placeSpawn(o, false) o = obj_get_next(o) end end for _, o in ipairs(spawns) do placeSpawn(o, false) end end local function placeMario(m, x, y, z) vec3f_set(m.pos, x, y, z) m.marioObj.oPosX, m.marioObj.oPosY, m.marioObj.oPosZ = x, y, z vec3f_set(m.marioObj.header.gfx.pos, x, y, z) vec3f_set(m.nonInstantWarpPos, x, y, z) end local function scaleStart(m, x, y, z, installed, warpObject) local spawn = m.spawnInfo and m.spawnInfo.startPos or m.pos local sx, sy, sz = coord(spawn.x, x), coord(spawn.y, y), coord(spawn.z, z) local last = scene.start local base = warpObject and scene.warpOrigins[warpObject._pointer or warpObject] if not installed and base and m.usedObj == warpObject then -- A warp in an already installed area reads the moved node, including its door offset. sx, sy, sz = spawn.x, spawn.y, spawn.z elseif last and spawn.x == last.x and spawn.y == last.y and spawn.z == last.z then return elseif base and (installed or (get_mario_spawn_type(warpObject) == MARIO_SPAWN_DOOR_WARP and spawn.y == base[2] and math.abs((spawn.x-base[1])^2 + (spawn.z-base[3])^2 - 300^2) < 1000)) then -- DynOS reads its door offset from the unscaled script even after the area is installed. sx = warpObject.oPosX + spawn.x - base[1] sy = warpObject.oPosY + spawn.y - base[2] sz = warpObject.oPosZ + spawn.z - base[3] end local floor = find_floor_height(sx, math.min(32760, sy + 100), sz) if y < 0 and floor <= gLevelValues.floorLowerLimit then floor = find_floor_height(sx, 32760, sz) end sy = math.max(sy, floor) if m.spawnInfo then vec3s_set(m.spawnInfo.startPos, coord(sx, 1), coord(math.ceil(sy), 1), coord(sz, 1)) scene.start = { x = m.spawnInfo.startPos.x, y = m.spawnInfo.startPos.y, z = m.spawnInfo.startPos.z } end placeMario(m, sx, sy, sz) if m.area.camera then soft_reset_camera(m.area.camera) end end local function installArea(m) if not firstSurface or ~firstSurface or not m or not m.area or not m.marioObj or not m.area.root then return end if scene and not (~scene.firstSurface) and scene.firstSurface == firstSurface then return end restoreTerrain() local key, x, y, z = table.unpack(areaScale) scene = { firstSurface = firstSurface, areaIndex = m.area.index, objects = areaScale.objects, warpOrigins = {}, placed = {}, x = x, y = y, z = z, mirrored = mirrorsHorizontally(x, z), display = {}, vertex = {}, triangles = {}, paintings = {}, } applied, attempted, retryAfter = key, nil, nil local location = gNetworkPlayers[0].currLevelNum .. ":" .. m.area.index if not water[location] then local levels = {} for i = 1, 20 do local height = get_environment_region(i) if height == gLevelValues.floorLowerLimit then break end levels[i] = height end water[location] = levels end for i, height in ipairs(water[location]) do set_environment_region(i, y > 0 and coord(height, y) or -32760) end if key ~= normalScale then gLevelValues.floorLowerLimit = math.min(lowerLimit, coord(lowerLimit, math.abs(y))) placeLoaded() for _, p in pairs(gPaintingValues) do if p and scene.objects then scene.paintings[#scene.paintings + 1] = { p, p.posX, p.posY, p.posZ } p.posX, p.posY, p.posZ = coord(p.posX, x), coord(p.posY, y), coord(p.posZ, z) end end prepareGraph(m.area.root.node.children, scene, false) set_override_far(30000 * math.min(4, math.max(math.abs(x), math.abs(y), math.abs(z), 1))) else gLevelValues.floorLowerLimit = lowerLimit set_override_far(0) end spawns = {} return true end -- SSL64 changes areas without using a regular warp node. function _G.mapScalerInstallArea(m) installArea(m) end local function finishCastleRestart(m) local start = castleRestart.start local sx, sy, sz = _G.mapScalerAreaFactors() local x, y, z = coord(start.x, sx), coord(start.y, sy), coord(start.z, sz) local height, floor = find_floor(x, y, z) if not floor then height, floor = find_floor(x, 32760, z) end if floor then y = math.max(y, height) end local waterLevel = math.floor(find_water_level(x, z)) if y < waterLevel then y = math.min(32760, waterLevel + 20) end local yaw = start.yaw if sx < 0 then yaw = -yaw end if sz < 0 then yaw = 0x8000 - yaw end yaw = ((yaw + 0x8000) & 0xffff) - 0x8000 -- Keep the engine's fallback spawn in the same coordinate space as Mario. vec3s_set(m.spawnInfo.startPos, x, math.ceil(y), z) vec3s_set(m.spawnInfo.startAngle, 0, yaw, 0) placeMario(m, x, y, z) vec3s_set(m.faceAngle, 0, yaw, 0) vec3s_set(m.marioObj.header.gfx.angle, 0, yaw, 0) m.marioObj.oMoveAnglePitch, m.marioObj.oMoveAngleYaw, m.marioObj.oMoveAngleRoll = 0, yaw, 0 vec3f_set(m.vel, 0, 0, 0) m.forwardVel, m.waterLevel, m.floorHeight, m.floor = 0, waterLevel, height, floor set_mario_action(m, floor and y <= height + 1 and ACT_IDLE or ACT_FREEFALL, 0) if m.area.camera then soft_reset_camera(m.area.camera) end if scene then scene.start = { x = x, y = math.ceil(y), z = z } end castleRestart = nil end local function onWarp(warpType, level, area, node) local m = gMarioStates[0] local installed = installArea(m) if castleRestart and level == LEVEL_CASTLE_GROUNDS and area == 1 and m and m.area and m.marioObj and m.spawnInfo then if not castleRestart.start then castleRestart.start = { x = -1328, y = 260, z = 4664, yaw = -0x8000 } end finishCastleRestart(m) return end if backroomsRestart and level == LEVEL_BOB and area == 2 and node == 0x0A and m and m.marioObj and m.area and m.area.index == 2 then backroomsRestart = false -- The Backrooms has an exit warp, but the actual entrance is at the origin. local y = math.max(0, find_floor_height(0, 100, 0)) if m.spawnInfo then vec3s_set(m.spawnInfo.startPos, 0, math.ceil(y), 0) end placeMario(m, 0, y, 0) set_mario_action(m, ACT_FREEFALL, 0) if m.area.camera then soft_reset_camera(m.area.camera) end return end if not scene or ~scene.firstSurface or applied == normalScale then return end -- DynOS can set Mario's final spawn after the earlier level-init callback. -- A same-area door already uses the destination object's scaled position. if m and m.area and m.marioObj and (installed or warpType ~= WARP_TYPE_SAME_AREA) then local warp = node and area_get_warp_node(node) local object = warp and warp.object scaleStart(m, scene.x, scene.y, scene.z, installed, object) end end local function onLevelInit(warpType, level, area, node) local m = gMarioStates[0] if castleRestart and gNetworkPlayers[0].currLevelNum == LEVEL_CASTLE_GROUNDS and m and m.area and m.area.index == 1 and m.spawnInfo then -- MARIO_POS is available here, before DynOS replaces it with the warp position. local pos, angle = m.spawnInfo.startPos, m.spawnInfo.startAngle castleRestart.start = { x = pos.x, y = pos.y, z = pos.z, yaw = angle.y } installArea(m) return end onWarp(warpType, level, area, node) end local function restartForScale(m) local player = gNetworkPlayers[0] local level, act = player.currLevelNum, player.currActNum or 0 backroomsRestart, castleRestart = false, nil if level == LEVEL_CASTLE_GROUNDS then if warp_to_warpnode(level, 1, act, 0x04) or warp_restart_level() then castleRestart = {} return true end return false end if level == LEVEL_BOB and _G.ssl64MapScalerCompatible then local area = m.area.index if area == 4 then return false end if area == 2 or area == 3 then local success = warp_to_warpnode(level, area, act, 0x0A) backroomsRestart = success and area == 2 return success end end return warp_restart_level() end local function onInstantWarp(_, _, displacement) local m = gMarioStates[0] installArea(m) if not scene or ~scene.firstSurface or applied == normalScale then return end local dx = coord(displacement.x, scene.x) - displacement.x local dy = coord(displacement.y, scene.y) - displacement.y local dz = coord(displacement.z, scene.z) - displacement.z placeMario(m, m.pos.x + dx, m.pos.y + dy, m.pos.z + dz) warp_camera(dx, dy, dz) end local function update() local m = gMarioStates[0] if not m or not m.area or not m.marioObj or not gNetworkPlayers[0].connected then return end if resumeRequested then resumeRequested = nil -- Run after the native pause renderer has written its result for this frame. if inPause() and is_game_paused() then game_unpause() end return end if get_current_play_mode() ~= PLAY_MODE_NORMAL or is_game_paused() then return end if pendingCamera ~= nil then parallelCamera, pendingCamera = pendingCamera, nil end if pendingObjects ~= nil and network_is_server() then if pendingObjects ~= objectsEnabled() then gGlobalSyncTable.mapScalerObjects = pendingObjects end if objectsCheckbox then update_mod_menu_element_checkbox(objectsCheckbox, pendingObjects) end pendingObjects = nil end if pendingScale then local x, y, z = parseScale(pendingScale) pendingScale = nil changeScale(x, y, z) end updateParallelCamera(m) if installArea(m) and applied ~= normalScale then scaleStart(m, scene.x, scene.y, scene.z) end if scene and not (~scene.firstSurface) and applied ~= normalScale then placeQueued() end local value = gGlobalSyncTable.worldScale or normalScale local key = value .. (objectsEnabled() and ":on" or ":off") if value == applied and (applied == normalScale or not scene or scene.objects == objectsEnabled()) then attempted, retryAfter = nil, nil return end if is_transition_playing() then return end if key == attempted then if not retryAfter then return end if retryAfter > 0 then retryAfter = retryAfter - 1; return end end local firstTry = key ~= attempted attempted, retryAfter = key, nil if not restartForScale(m) then if not (_G.ssl64MapScalerCompatible and gNetworkPlayers[0].currLevelNum == LEVEL_BOB and m.area.index == 4) then retryAfter = 30 end if firstTry then djui_chat_message_create("Waiting for the course to reload at the new scale.") end end end if network_is_server() then objectsCheckbox = hook_mod_menu_checkbox("Enable Scalable Objects", objectsEnabled(), function(_, value) pendingObjects = value if pauseMenu then pauseMenu.objects = value end end) end hook_chat_command("scale", "X Y Z, N, reset, or r - Scale the course (host only)", scaleCommand) hook_event(HOOK_ON_ADD_SURFACE, onSurface) hook_event(HOOK_ON_OBJECT_LOAD, function(o) if not scene or ~scene.firstSurface or applied ~= normalScale then spawns[#spawns + 1] = o end end) hook_event(HOOK_ON_OBJECT_UNLOAD, function(o) if scene then local slot = o._pointer or o scene.placed[slot], scene.warpOrigins[slot] = nil, nil end end) hook_event(HOOK_ON_WARP, onWarp) hook_event(HOOK_ON_LEVEL_INIT, onLevelInit) hook_event(HOOK_ON_INSTANT_WARP, onInstantWarp) hook_event(HOOK_UPDATE, update) hook_event(HOOK_ON_HUD_RENDER, renderScale) hook_event(HOOK_ON_PLAY_MODE_UPDATE, onPlayMode) hook_event(HOOK_ON_PACKET_RECEIVE, onPacket) hook_event(HOOK_ON_CLEAR_AREAS, function() closeScalePause() resumeRequested, cameraOverride = nil, nil end) -- Native rolling logs store their travel limits in absolute course coordinates. local function moveLogTrack(o) if not scene or not scene.objects or applied == normalScale or ~scene.firstSurface or scene.areaIndex ~= o.header.gfx.areaIndex or (o.coopFlags & COOP_OBJ_FLAG_NETWORK) ~= 0 then return end local x = sins(o.oMoveAngleYaw) * scene.x local z = coss(o.oMoveAngleYaw) * scene.z o.oPitouneUnkF8 = coord(o.oPitouneUnkF8, scene.x) o.oPitouneUnkFC = coord(o.oPitouneUnkFC, scene.z) o.oPitouneUnkF4 = math.min(2 * 65520^2, o.oPitouneUnkF4 * (x*x + z*z)) if x ~= 0 or z ~= 0 then o.oMoveAngleYaw = atan2s(z, x) end end hook_behavior(id_bhvTtmRollingLog, OBJ_LIST_SURFACE, false, moveLogTrack, nil) hook_behavior(id_bhvLllRollingLog, OBJ_LIST_SURFACE, false, moveLogTrack, nil) -- These managers create chest bases at absolute coordinates; lids are relative to each base. local function moveChestBases(manager) if not scene or not scene.objects or applied == normalScale or ~scene.firstSurface or scene.areaIndex ~= manager.header.gfx.areaIndex then return end local chest = obj_get_first_with_behavior_id(id_bhvTreasureChestBottom) while chest do if chest.parentObj == manager and (chest.coopFlags & COOP_OBJ_FLAG_NETWORK) == 0 then local x, y, z = coord(chest.oPosX, scene.x), coord(chest.oPosY, scene.y), coord(chest.oPosZ, scene.z) placeObject(chest, x, y, z) chest.oHomeX, chest.oHomeY, chest.oHomeZ = x, y, z end chest = obj_get_next_with_same_behavior_id(chest) end end hook_behavior(id_bhvTreasureChestsShip, OBJ_LIST_DEFAULT, false, moveChestBases, nil) hook_behavior(id_bhvTreasureChestsJrb, OBJ_LIST_DEFAULT, false, moveChestBases, nil) hook_behavior(id_bhvTreasureChests, OBJ_LIST_DEFAULT, false, moveChestBases, nil) local nativeStarTargets = { "BalconyBooStarPos", "BigBullyStarPos", "BigBullyTrioStarPos", "BigPiranhasStarPos", "CcmSlideStarPos", "ChillBullyStarPos", "EyerockStarPos", "GhostHuntBooStarPos", "JetstreamRingStarPos", "KingBobombStarPos", "KingWhompStarPos", "KleptoStarPos", "KoopaBobStarPos", "KoopaThiStarPos", "MantaRayStarPos", "MerryGoRoundStarPos", "MrIStarPos", "PssSlideStarPos", "RacingPenguinStarPos", "SnowmanHeadStarPos", "TreasureChestStarPos", "TreasureJrbStarPos", "TuxieMotherStarPos", "UkikiCageStarPos", "UnagiStarPos", "WigglerStarPos", } local function inScaledArea(o) return scene and applied ~= normalScale and not (~scene.firstSurface) and o.header.gfx.areaIndex == scene.areaIndex end local function isNativeStarTarget(x, y, z) local targets = gLevelValues.starPositions if not targets then return false end for _, name in ipairs(nativeStarTargets) do local target = targets[name] if target and x == target.x and y == target.y and z == target.z then return true end end return false end local function scaleRewardStar(o) if not inScaledArea(o) or o.oAction ~= 0 then return end local x, y, z = o.oHomeX, o.oHomeY, o.oHomeZ if o.oBehParams2ndByte == 0 and isNativeStarTarget(x, y, z) then x, y, z = coord(x, scene.x), coord(y, scene.y), coord(z, scene.z) end if scene.y == 0 then x, y, z = flatStarPosition(x, z) end if x == o.oHomeX and y == o.oHomeY and z == o.oHomeZ then return end o.oHomeX, o.oHomeY, o.oHomeZ = x, y, z local dx, dz = x - o.oPosX, z - o.oPosZ local distance = math.sqrt(dx * dx + dz * dz) -- Native init has already run. Update the path without replaying the cutscene. o.oMoveAngleYaw = atan2s(dz, dx) o.oStarSpawnDisFromHome = distance o.oVelY, o.oForwardVel = (y - o.oPosY) / 30, distance / 30 o.oStarSpawnUnkFC = o.oPosY end local function settleFlatStar(o, x, z) if not inScaledArea(o) or scene.y ~= 0 then return end local px, py, pz = flatStarPosition(x, z) o.oHomeX, o.oHomeY, o.oHomeZ = px, py, pz placeObject(o, px, py, pz) end local function lowerFlatStar(o) settleFlatStar(o, o.oPosX, o.oPosZ) end local function finishBoxStar(o) if o.oAction == 3 and o.oTimer == 0 then lowerFlatStar(o) end end local function finishRewardStar(o) if o.oAction == 3 and o.oTimer == 0 then settleFlatStar(o, o.oHomeX, o.oHomeZ) end end hook_behavior(id_bhvStar, OBJ_LIST_LEVEL, false, lowerFlatStar, nil) hook_behavior(id_bhvStarSpawnCoordinates, OBJ_LIST_LEVEL, false, scaleRewardStar, finishRewardStar) hook_behavior(id_bhvSpawnedStar, OBJ_LIST_LEVEL, false, nil, finishBoxStar) hook_behavior(id_bhvSpawnedStarNoLevelExit, OBJ_LIST_LEVEL, false, nil, finishBoxStar) local lookingUp = false hook_event(HOOK_ON_FIND_WATER_LEVEL, function(x, z) if lookingUp then return end local sx, _, sz = _G.mapScalerAreaFactors() if sx == 0 or sz == 0 or (sx == 1 and sz == 1) then return end lookingUp = true local level = find_water_level(x / sx, z / sz) lookingUp = false return level end) hook_event(HOOK_UPDATE, function() if not (scene and scene.objects) then return end local x, y, z = _G.mapScalerAreaFactors() local width = math.max(math.abs(x), math.abs(z)) local height = math.abs(y) local function fix(id, radius, tall) local o = obj_get_first_with_behavior_id(id) while o do o.hitboxRadius = radius * width o.hitboxHeight = tall * height o = obj_get_next_with_same_behavior_id(o) end end fix(id_bhvTree, 80, 500) fix(id_bhvMessagePanel, 150, 80) local sign = obj_get_first_with_behavior_id(id_bhvMessagePanel) while sign do sign.oCollisionDistance = 500 * math.max(width, height, 1) sign = obj_get_next_with_same_behavior_id(sign) end -- Signs mounted on walls fix(id_bhvSignOnWall, 150, 80) fix(id_bhvGiantPole, 80, 2100) fix(id_bhvKoopaFlag, 80, 700) local box = obj_get_first_with_behavior_id(id_bhvBreakableBox) while box do box.oCollisionDistance = 500 * math.max(width, height, 1) box = obj_get_next_with_same_behavior_id(box) end -- Level poles each have their own height local p = obj_get_first_with_behavior_id(id_bhvPoleGrabbing) while p do p.hitboxRadius = 80 * width p.hitboxHeight = ((p.oBehParams >> 16) & 0xFF) * 10 * height p = obj_get_next_with_same_behavior_id(p) end end) hook_event(HOOK_UPDATE, function() if not (scene and scene.objects) then return end local x, y, z = _G.mapScalerAreaFactors() x, y, z = math.abs(x), math.abs(y), math.abs(z) local o = obj_get_first_with_behavior_id(id_bhvFloorTrapInCastle) while o do local p = o.parentObj if p and p ~= o then o.oPosX = p.oPosX - coss(o.oFaceAngleYaw) * 358 * x o.oPosY = p.oPosY o.oPosZ = p.oPosZ + sins(o.oFaceAngleYaw) * 358 * z obj_scale_xyz(o, x, y, z) o.oCollisionDistance = 1000 * math.max(x, y, z, 1) end o = obj_get_next_with_same_behavior_id(o) end end) hook_event(HOOK_UPDATE, function() local x, y, z = _G.mapScalerAreaFactors() if x == 1 and y == 1 and z == 1 then return end local s = math.max(math.abs(x), math.abs(z)) local reach = 40 + 40 * s for _, id in ipairs({ id_bhvDoor, id_bhvDoorWarp, id_bhvStarDoor }) do local o = obj_get_first_with_behavior_id(id) while o do o.hitboxRadius = reach o.hitboxHeight = 100 * math.max(1, math.abs(y)) o.oCollisionDistance = 2000 * s o = obj_get_next_with_same_behavior_id(o) end end end) local squares = {} hook_event(HOOK_ON_LEVEL_INIT, function() squares = {} end) hook_event(HOOK_UPDATE, function() if not (scene and scene.objects) then return end local x, y, z = _G.mapScalerAreaFactors() if x == 1 and y == 1 and z == 1 then return end local o = obj_get_first_with_behavior_id(id_bhvSquarishPathMoving) while o do local p, s = o.parentObj, squares[o._pointer] if not s or math.abs(o.oPosX - s.x) + math.abs(o.oPosZ - s.z) > 100 then s = { rx = o.oPosX, rz = o.oPosZ, x = o.oPosX, z = o.oPosZ } squares[o._pointer] = s end local dx, dz = o.oPosX - s.x, o.oPosZ - s.z s.rx, s.rz = s.rx + dx, s.rz + dz s.x = p.oPosX + (s.rx - p.oPosX) * math.abs(x) s.z = p.oPosZ + (s.rz - p.oPosZ) * math.abs(z) o.oPosX, o.oPosZ = s.x, s.z o.header.gfx.pos.x, o.header.gfx.pos.z = s.x, s.z obj_scale_xyz(o, math.abs(x), math.abs(y), math.abs(z)) o.oCollisionDistance = 1000 * math.max(math.abs(x), math.abs(z), 1) o = obj_get_next_with_same_behavior_id(o) end end) hook_event(HOOK_BEFORE_MARIO_UPDATE, function(m) if m.playerIndex ~= 0 or not (scene and scene.objects) then return end local o = m.floor and m.floor.object if not o or get_id_from_behavior(o.behavior) ~= id_bhvSquarishPathMoving then return end if m.pos.y - m.floorHeight > 10 then return end local x, _, z = _G.mapScalerAreaFactors() local vx = o.oForwardVel * sins(o.oMoveAngleYaw) local vz = o.oForwardVel * coss(o.oMoveAngleYaw) m.pos.x = m.pos.x + vx * (math.abs(x) - 1) m.pos.z = m.pos.z + vz * (math.abs(z) - 1) end) local last = {} hook_behavior(id_bhvFerrisWheelPlatform, OBJ_LIST_SURFACE, false, nil, function(o) if not (scene and scene.objects) then return end local x, y, z = _G.mapScalerAreaFactors() if x == 1 and y == 1 and z == 1 then o.oCollisionDistance = 1000 return end local ax, ay, az = math.abs(x), math.abs(y), math.abs(z) local a = o.parentObj local px = a.oPosX + (o.oPosX - a.oPosX) * x local py = a.oPosY + (o.oPosY - a.oPosY) * y local pz = a.oPosZ + (o.oPosZ - a.oPosZ) * z local p = last[o._pointer] or { px, py, pz } o.oVelX, o.oVelY, o.oVelZ = px - p[1], py - p[2], pz - p[3] last[o._pointer] = { px, py, pz } o.oPosX, o.oPosY, o.oPosZ = px, py, pz o.header.gfx.pos.x, o.header.gfx.pos.y, o.header.gfx.pos.z = px, py, pz obj_scale_xyz(o, ax, ay, az) obj_scale_xyz(a, ax, ay, az) o.oCollisionDistance = 4000 * math.max(ax, ay, az, 1) load_object_collision_model() o.oCollisionDistance = 0 end) local gates = {} hook_event(HOOK_ON_LEVEL_INIT, function() gates = {} end) hook_event(HOOK_UPDATE, function() if not (scene and scene.objects) then return end local x, y, z = _G.mapScalerAreaFactors() local o = obj_get_first_with_behavior_id(id_bhvOpenableCageDoor) while o do local p = o.parentObj local r = gates[o._pointer] if not r then r = { o.oPosX - p.oPosX, o.oPosY - p.oPosY, o.oPosZ - p.oPosZ } gates[o._pointer] = r end o.oPosX = p.oPosX + r[1] * x o.oPosY = p.oPosY + r[2] * y o.oPosZ = p.oPosZ + r[3] * z obj_scale_xyz(o, math.abs(x), math.abs(y), math.abs(z)) o.oCollisionDistance = 2000 * math.max(math.abs(x), math.abs(y), math.abs(z), 1) o = obj_get_next_with_same_behavior_id(o) end end) local starPass hook_event(HOOK_MARIO_UPDATE, function(m) if m.playerIndex ~= 0 then return end local x, _, z = _G.mapScalerAreaFactors() local s = math.max(math.abs(x), math.abs(z)) if m.action == ACT_ENTERING_STAR_DOOR then if not starPass and s >= 2 and m.usedObj then local fx, fz = sins(m.faceAngle.y), coss(m.faceAngle.y) local d = (m.usedObj.oPosX - m.pos.x) * fx + (m.usedObj.oPosZ - m.pos.z) * fz local far = math.max(2 * math.abs(d), math.abs(d) + 150 * s) starPass = { x = m.pos.x + fx * far, z = m.pos.z + fz * far } end elseif starPass then m.pos.x, m.pos.z = starPass.x, starPass.z starPass = nil end end)