An OpenMW mod that lets you play the whole Elder Scrolls III: Morrowind as a top-down isometric game — with full online co-op or MMO modes.
C++
Click to move, camera rotation, the aim line, and the journal as an inventory page
pw-tf88a695d12f71
diff --git a/README.md b/README.mdindex 3a7d71a..584311f 100644--- a/README.md+++ b/README.md@@ -316,19 +316,40 @@ The defaults; Options > Controls rebinds them (and Options > Scripts > Isowind t| F1 | Morrowind's quick key menu || Mouse wheel | Zoom, within the view you are in || F7 | Switch view: top-down, then third person, then first person |+| Middle mouse held | With camera rotation on (Options > Scripts > Isowind): move the mouse to turn the view || Tab | Inventory |-| J | Journal |+| J | Journal (the inventory screen's last page) || T | Rest || Esc | Menu || F5 / F9 | Quick save / quick load || F11 / F12 | Hide the HUD / screenshot || `` ` `` | Console (the key left of 1) |+**Click to move** (asked the first time you play; Options > Scripts > Isowind changes it)++| Key | What it does |+|--------------------|-------------------------------------------------------------------------------------------------|+| Right click | On the ground: run there (a red X splashes onto the spot). Hold it to keep steering toward the cursor. Stairs can be clicked from any side |+| Right click | On a person or a thing: walk right up to it and use it (talk, pick up, open) |+| Left click | As without click to move: attack / cast where you stand, otherwise use what is under the cursor. The power attack is then on a controller's left trigger only |+| Shift | Stand still while held (instead of walking): you keep aiming and attacking, but no click (or WASD) moves you |++Options > Scripts > Isowind can put click to move on the left button instead: then a left click on a hostile creature+with a weapon or spell ready walks into range and attacks (hold to keep attacking; bows, thrown weapons and target+spells stop short, with a clear shot), Shift + left click attacks where you stand, and right click power attacks as+usual.++Drawing a bow or crossbow (or readying a throw), or having a spell cast at a target ready, draws a thin line a few+metres out from your character the way they aim, a small ring at its end. With click to move, right click only moves+and uses things: it never attacks.+| Left / right arrow | With camera rotation on: turn the view |+| W A S D | Still move, and take over from a click |+**Keyboard and mouse, in the menus**| Key | What it does ||--------------------|-------------------------------------------------------------------------------------------------|-| Q / E | Previous / next page of the inventory screen (Map, Inventory, Magic, Stats), or tab in Options |+| Q / E | Previous / next page of the inventory screen (Map, Inventory, Magic, Stats, Journal), or tab in Options. Z / C turn the journal's pages || Z / C | Previous / next tab inside a window: the kinds of item in the inventory or a shop, a chest's containers opened together, the local or world map, in Options the Video tab's (Detail Level, Water, Lights) and the Controls tab's mouse and keyboard / controller. With a chest or shop open, the window under the pointer || Click a tab | That page. The HUD's bars, weapon, spell and minimap go to theirs too || 1 - 0 | Over an item, spell or enchanted item: puts it on that quick key |@@ -353,10 +374,9 @@ Q / E and Z / C type as usual in a text box.| Left trigger | Power attack || Bumpers | Previous / next quick key || D-pad up / down | Zoom (hold to keep going) |-| D-pad right | Quest log |-| D-pad left | Nothing for now |+| D-pad left / right | With camera rotation on (Options > Scripts > Isowind): turn the view, held || Start | Menu |-| Back | Inventory (hold: journal) |+| Back | Inventory (hold: journal, the inventory screen's last page) || Left stick in | Sneak. In water, hold it in to dive || Right stick in | Rest |diff --git a/apps/openmw/mwgui/inventorytabsoverlay.cpp b/apps/openmw/mwgui/inventorytabsoverlay.cppindex 6d22708..08317f2 100644--- a/apps/openmw/mwgui/inventorytabsoverlay.cpp+++ b/apps/openmw/mwgui/inventorytabsoverlay.cpp@@ -17,7 +17,8 @@ namespace MWGui: WindowBase("openmw_inventory_tabs.layout"){MyGUI::Button* tab;- constexpr std::string_view kTabIds[] = { "TabMap", "TabInventory", "TabSpells", "TabStats" };+ // (in the order of the inventory screen's pages, WindowManager's mGuiModeStates[GM_Inventory])+ constexpr std::string_view kTabIds[] = { "TabMap", "TabInventory", "TabSpells", "TabStats", "TabJournal" };for (const std::string_view id : kTabIds){diff --git a/apps/openmw/mwgui/journalwindow.cpp b/apps/openmw/mwgui/journalwindow.cppindex f7f76cf..7e8eaa3 100644--- a/apps/openmw/mwgui/journalwindow.cpp+++ b/apps/openmw/mwgui/journalwindow.cpp@@ -59,6 +59,9 @@ namespacebool mOptionsMode;bool mTopicsMode;bool mAllQuests;+ // Isowind: the journal is a page of the inventory screen too: whether it is the page shown (since the screen+ // opened)+ bool mPageShown = false;template <typename T>T* getWidget(std::string_view name)@@ -263,7 +266,10 @@ namespaceif (Settings::gui().mControllerMenus)setControllerFocusedQuest(0);- MWBase::Environment::get().getWindowManager()->setKeyFocusWidget(getWidget<MyGUI::Widget>(CloseBTN));+ // (Isowind: not as the inventory screen's page, which may not be the one shown)+ MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();+ if (winMgr->getMode() == MWGui::GM_Journal)+ winMgr->setKeyFocusWidget(getWidget<MyGUI::Widget>(CloseBTN));}void onClose() override@@ -277,10 +283,37 @@ namespacemStates.pop();mTopicIndexBook.reset();+ mPageShown = false;}void setVisible(bool newValue) override { WindowBase::setVisible(newValue); }+ // Isowind: as the inventory screen's page. The book is on a layer of its own (JournalBooks), a screen of 600 x+ // 520 scaled up to fit the real one, so not placed as the other pages are (in the real screen's units):+ // centred on its layer it sits clear of the tab bar and the controller's legend at any size. A page not shown+ // waits far below. Turned to, it opens with the book's sound.+ void setInventoryPage(bool shown) override+ {+ if (shown)+ center();+ else+ mMainWidget->setPosition(mMainWidget->getLeft(), 100000);+ MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager();+ if (shown && !mPageShown)+ winMgr->playSound(ESM::RefId::stringRefId("book open"));+ mPageShown = shown;+ }++ // Isowind: the keyboard's Z / C turn its pages (as the controller's triggers do, through its bumpers)+ bool stepTab(int delta) override+ {+ if (delta > 0)+ notifyNextPage(getWidget<MyGUI::Widget>(NextPageBTN));+ else+ notifyPrevPage(getWidget<MyGUI::Widget>(PrevPageBTN));+ return true;+ }+void setBookMode(){mOptionsMode = false;diff --git a/apps/openmw/mwgui/windowbase.hpp b/apps/openmw/mwgui/windowbase.hppindex 53f3de7..5610400 100644--- a/apps/openmw/mwgui/windowbase.hpp+++ b/apps/openmw/mwgui/windowbase.hpp@@ -88,6 +88,7 @@ namespace MWGuivirtual std::string_view getWindowIdForLua() const { return {}; }void setDisabledByLua(bool disabled) { mDisabledByLua = disabled; }+ bool isDisabledByLua() const { return mDisabledByLua; }static void clampWindowCoordinates(MyGUI::Window* window);diff --git a/apps/openmw/mwgui/windowmanagerimp.cpp b/apps/openmw/mwgui/windowmanagerimp.cppindex 3ada2d9..5f72cf5 100644--- a/apps/openmw/mwgui/windowmanagerimp.cpp+++ b/apps/openmw/mwgui/windowmanagerimp.cpp@@ -367,7 +367,10 @@ namespace MWGuiconstexpr VFS::Path::NormalizedView menubookOptionsOverTexture("textures/tx_menubook_options_over.dds");const bool questList = mResourceSystem->getVFS()->exists(menubookOptionsOverTexture);auto journal = JournalWindow::create(JournalViewModel::create(), questList, mEncoding);+ mJournal = journal.get();mGuiModeStates[GM_Journal] = GuiModeState(journal.get());+ // Isowind: and the inventory screen's last page (Map, Inventory, Magic, Stats, Journal)+ mGuiModeStates[GM_Inventory].mWindows.push_back(journal.get());mWindows.push_back(std::move(journal));mMessageBoxManager = std::make_unique<MessageBoxManager>(@@ -732,6 +735,9 @@ namespace MWGuimInventoryWindow->setVisible(eff & GW_Inventory);mSpellWindow->setVisible(eff & GW_Magic);mStatsWindow->setVisible(eff & GW_Stats);+ // Isowind: the journal too, once it can be had (made again only when it opens: that reads the journal)+ if (isJournalInventoryPage() != mJournal->isVisible())+ mJournal->setVisible(isJournalInventoryPage());// Isowind: they are pages (one opened just now goes below the screen, or is the page shown)layoutInventoryPages();}@@ -1044,6 +1050,11 @@ namespace MWGuiplaySound(ESM::RefId::stringRefId("Menu Size"));}+ bool WindowManager::isJournalInventoryPage() const+ {+ return mJournal && (mAllowed & GW_Magic) != 0 && !mJournal->isDisabledByLua(); // (as getJournalAllowed)+ }+void WindowManager::layoutInventoryPages(){const std::vector<WindowBase*>& pages = mGuiModeStates[GM_Inventory].mWindows;@@ -1502,6 +1513,31 @@ namespace MWGuiif (mode == GM_Inventory && mAllowed == GW_None)return;+ // Isowind: the journal is the inventory screen's last page, wherever it is opened from (J, the controller's+ // Back held, scripts); opened again from that page it closes the screen, as J closes the journal+ if (mode == GM_Journal && isJournalInventoryPage())+ {+ const size_t page = mGuiModeStates[GM_Inventory].mWindows.size() - 1;+ if (!mGuiModes.empty() && mGuiModes.back() == GM_Inventory)+ {+ if (mActiveControllerWindows[GM_Inventory] == page)+ popGuiMode();+ else+ {+ setActiveControllerWindow(GM_Inventory, page);+ // (Lua asked for the journal on top: it is told the inventory screen is still what is open)+ MWBase::Environment::get().getLuaManager()->uiModeChanged(MWWorld::Ptr());+ }+ return;+ }+ // The inventory screen opens on the page after the one before this (see below): this one+ mActiveControllerWindows[GM_Inventory] = page;+ mode = GM_Inventory;+ }+ // Isowind: the journal on its own (a Lua window in its place): back from below the screen, where a page waits+ else if (mode == GM_Journal)+ mJournal->center();+// The first menu to open opens as made for what was used lastif (mGuiModes.empty())applyWantedControllerMenus();@@ -3025,6 +3061,9 @@ namespace MWGuires.push_back(mSpellWindow->getWindowIdForLua());if (mAllowed & GW_Stats)res.push_back(mStatsWindow->getWindowIdForLua());+ // Isowind: the journal is a page here too (so setMode('Interface', { windows = {} }) hides it as well)+ if (mAllowed & GW_Magic)+ res.push_back(mJournal->getWindowIdForLua());}else{diff --git a/apps/openmw/mwgui/windowmanagerimp.hpp b/apps/openmw/mwgui/windowmanagerimp.hppindex 4dfa6b3..169489e 100644--- a/apps/openmw/mwgui/windowmanagerimp.hpp+++ b/apps/openmw/mwgui/windowmanagerimp.hpp@@ -477,6 +477,7 @@ namespace MWGuiSettingsWindow* mSettingsWindow;ConfirmationDialog* mConfirmationDialog;SpellWindow* mSpellWindow;+ JournalWindow* mJournal = nullptr;QuickKeysMenu* mQuickKeysMenu;LoadingScreen* mLoadingScreen;WaitDialog* mWaitDialog;@@ -555,6 +556,9 @@ namespace MWGuibool hasActiveControllerWindow() const;void layoutInventoryPages();void updateInventoryTabs();+ /// Isowind: the journal is the inventory screen's last page, unless it can't be had yet (character creation)+ /// or a Lua script has put a window of its own in its place+ bool isJournalInventoryPage() const;std::unique_ptr<SDLUtil::SDLCursorManager> mCursorManager;diff --git a/files/data/mygui/openmw_inventory_tabs.layout b/files/data/mygui/openmw_inventory_tabs.layoutindex d142bda..71e724e 100644--- a/files/data/mygui/openmw_inventory_tabs.layout+++ b/files/data/mygui/openmw_inventory_tabs.layout@@ -48,6 +48,13 @@<Property key="TextShadow" value="true"/><Property key="TextShadowColour" value="0 0 0"/></Widget>+ <!-- Isowind: the journal is a page too -->+ <Widget type="Button" skin="SandTextButton" align="Center" position="0 0 100 48" name="TabJournal">+ <Property key="Caption" value="#{sJournal}"/>+ <Property key="TextAlign" value="Center"/>+ <Property key="TextShadow" value="true"/>+ <Property key="TextShadowColour" value="0 0 0"/>+ </Widget><Widget type="AutoSizedTextBox" skin="SandText" align="Center" name="KeyNextText"><Property key="Caption" value="E"/><Property key="TextShadow" value="true"/>diff --git a/isowind/mod/l10n/Isowind/en.yaml b/isowind/mod/l10n/Isowind/en.yamlindex 9a14f9d..66876f5 100644--- a/isowind/mod/l10n/Isowind/en.yaml+++ b/isowind/mod/l10n/Isowind/en.yaml@@ -8,3 +8,19 @@ switch_view: "Switch view"switch_view_desc: "Top-down, then third person, then first person."switch_view_key_desc: "Top-down, then third person, then first person (F7 unless changed). Click it (or A on it), then press a key or button."switch_view_button_desc: "A second binding, for a controller button. Move onto it with the D-pad and press A (or click it), then press the button."+move_mode: "Movement"+move_mode_desc: "WASD moves the character relative to the screen. Click to move: right click on the ground runs there (hold to keep steering), and on a person or a thing walks up to it and uses it; it never attacks. Left click attacks and casts where you stand, and Shift held keeps you standing still. WASD and the controller move in both."+move_wasd: "WASD"+move_click: "Click to move"+move_button: "Click to move button"+move_button_desc: "Right: right click moves and uses things, and left click attacks and uses things where you stand (the power attack is then only on the controller's left trigger). Left: left click moves, uses things, and walks up to enemies to attack them, Shift and left click attacks where you stand, and the right button power attacks."+move_button_right: "Right"+move_button_left: "Left"+camera_rotation: "Camera rotation"+camera_rotation_desc: "Turn the top-down view: hold the middle mouse button and move the mouse, or with click to move the left and right arrow keys; on a controller, hold the D-pad left or right."+move_prompt_title: "How would you like to move?"+move_prompt_wasd: "WASD to move"+move_prompt_wasd_desc: "Move with W, A, S and D. The mouse aims, and left click attacks or uses what is under it. (1)"+move_prompt_click: "Click to move"+move_prompt_click_desc: "Right click where to go, or on people and things to walk up and use them. Left click attacks. (2)"+move_prompt_later: "This can be changed in Options -> Scripts -> Isowind."diff --git a/isowind/mod/scripts/isowind/clicktomove.lua b/isowind/mod/scripts/isowind/clicktomove.luanew file mode 100644index 0000000..3288674--- /dev/null+++ b/isowind/mod/scripts/isowind/clicktomove.lua@@ -0,0 +1,525 @@+-- Click to move, with the mouse in the top-down view (Options -> Scripts -> Isowind, or the question asked the first+-- time the game is played: moveprompt.lua).+-- Right click on the ground runs there (held: the spot follows the cursor); on a person or a thing walks right+-- up to it and uses it (talks, picks up, opens); it never attacks: on a hostile creature, to the+-- ground there+-- Left click as without click to move (topdown.lua): an attack or a spell where the character stands, or with+-- nothing ready, use what is under the cursor+-- Shift held the character stands still (topdown.lua): no click sends them anywhere, nor WASD, and they keep+-- aiming at the cursor (it isn't walking, as it is without click to move)+-- With the left button chosen to move instead (MoveButton), it does all of that, and on a hostile creature with a weapon+-- or spell ready walks into range (bows, thrown weapons and target spells stop short, with a clear shot) and attacks+-- once, held attacks again and again; Shift and left click attacks where the character stands, and the right button+-- power attacks. WASD or a stick takes over at once; with a controller it is as ever.+-- Used by topdown.lua, which lends what it knows (init) and turns the way to go into the character's movement.++local camera = require('openmw.camera')+local core = require('openmw.core')+local input = require('openmw.input')+local nearby = require('openmw.nearby')+local self = require('openmw.self')+local storage = require('openmw.storage')+local types = require('openmw.types')+local util = require('openmw.util')++local Actor = types.Actor+local v3 = util.vector3+local controls = storage.playerSection('Settings/Isowind/Controls') -- MoveButton (settings.lua)++local WAYPOINT_REACHED = 40 -- a point on the way this close counts as passed...+local GROUND_ARRIVED = 30 -- ...and the spot clicked this close as arrived at+local USE_DISTANCE = 45 -- people and things are used from this close (to the side of their box)...+local REACH_MARGIN = 0.5 -- ...and melee and touch attacks walk this far into their reach+local RANGED_ENGAGE = 1200 -- bows, thrown weapons and spells cast at a target attack from this close+local STEER_INTERVAL = 0.15 -- how often the spot (and the way) is found again while the button is held+local TARGET_MOVED = 100 -- the way is found again once the target is this far from where it was found to+local STUCK_TIME = 0.5 -- getting no closer for this long finds the way again (or, near enough to what+ -- was clicked, uses or attacks it from there: a counter between)...+local STUCK_TRIES = 3 -- ...this many times, then the character gives up+local ATTACK_WINDUP = 0.45 -- a click's attack is held this long (at weapon speed 1) for a full swing or draw+local ATTACK_REST = 0.1 -- with the button held on the enemy, let go this long between attacks+local GROUND_NORMAL_Z = 0.7 -- a surface this level or more can be walked to (up 1, a wall 0)+local SNAP_BOX = v3(30, 30, 60) -- a surface clicked counts as on the navigation mesh this near it (half extents)+local STAIRS_REACH = 400 -- stairs clicked anywhere (a side, the back): their steps up to this far above it+local STEP_SNAP_HEIGHT = 40 -- the navigation mesh found for a step must be this near it in height (not the floor)+local DIRECT_END = 50 -- a way found ending farther than this from stairs clicked: straight there instead+local NAV_STEP = 12 -- past a surface that can't be walked on, the cursor's ray is followed in steps this+local NAV_DEPTH = 300 -- long, this far, looking for walkable ground hidden behind it...+local NAV_PROBES = 80 -- ...at most this many looks for the whole ray+local NAV_PROBE_BOX = v3(10, 10, 30) -- how near the ray the ground must come (half extents)+local STAIRS_WORDS = { 'stair', 'step', 'ramp' } -- in a static's id or model: stairs (Morrowind has no kind for them)++-- What topdown.lua lends (init): weaponReach(), RANGED_REACH, isHostile(actor), lockToolReady(),+-- withinReachHeight(object), activate(object), ACTIVATE_SLACK+local lent++-- Where the character is going: { kind = 'ground' | 'use' | 'attack', point, object, button (the one clicked), direct+-- (stairs: straight there where the navigation mesh doesn't reach) }+local order = nil+local path, pathIndex = nil, 1 -- the way there (nearby.findPath), and the point on it gone for next+local pathTo = nil -- where the way was found to+local steerIn = 0 -- seconds until the spot held to is found again+local stuckFor, stuckTries, closest = 0, 0, math.huge+local steering = false -- the button is held from a click on the ground: the spot follows the cursor+local attackFor = 0 -- the click's own attack: seconds left holding it (use), then...+local restFor = 0 -- ...seconds left letting go+local castPending = false -- ...or the click's spell, cast this frame+local shiftAttack = false -- Shift and click: the engine's own attack where the character stands, as held+local isStairsRecord = {} -- record id -> whether it is stairs++local M = {}++function M.init(fromTopDown)+ lent = fromTopDown+end++-- The mouse button that moves: 3 the right one (the default), 1 the left+function M.button()+ return controls:get('MoveButton') == 'move_button_left' and 1 or 3+end++function M.cancel()+ order, path, pathTo, steering = nil, nil, nil, false+ attackFor, restFor, castPending = 0, 0, false+end++-- Whether the character is going somewhere+function M.going()+ return order ~= nil+end++-- The spot clicked on the ground being gone to (for the red X), or nil+function M.groundTarget()+ return order and order.kind == 'ground' and order.point or nil+end++local function startOrder(kind, point, object, button)+ order = { kind = kind, point = point, object = object, button = button }+ path, pathTo = nil, nil+ steerIn, stuckFor, stuckTries, closest = STEER_INTERVAL, 0, 0, math.huge+end++local function activateReach()+ return core.getGMST('iMaxActivateDist') + lent.ACTIVATE_SLACK+end++-- How far the player is across the ground from something: to the nearest side of its box+local function gapTo(object)+ local box = object:getBoundingBox()+ local p = self.position+ local x = util.clamp(p.x, box.center.x - box.halfSize.x, box.center.x + box.halfSize.x)+ local y = util.clamp(p.y, box.center.y - box.halfSize.y, box.center.y + box.halfSize.y)+ return math.sqrt((p.x - x) ^ 2 + (p.y - y) ^ 2)+end++local function isStairs(object)+ if not (object and types.Static.objectIsInstance(object)) then return false end+ local id = object.recordId+ local known = isStairsRecord[id]+ if known == nil then+ local ok, record = pcall(types.Static.record, object)+ local text = id .. ' ' .. string.lower(ok and record and record.model or '')+ known = false+ for _, word in ipairs(STAIRS_WORDS) do+ if text:find(word, 1, true) then known = true end+ end+ isStairsRecord[id] = known+ end+ return known+end++-- The range (core.magic.RANGE) of the spell or enchanted item ready to cast, by its first effect+local function castRange()+ local effects+ local spell = Actor.getSelectedSpell(self)+ if spell then+ effects = spell.effects+ else+ local item = Actor.getSelectedEnchantedItem(self)+ local ok, record = pcall(function() return item.type.record(item) end)+ local enchantment = ok and record and record.enchant and core.magic.enchantments.records[record.enchant]+ effects = enchantment and enchantment.effects+ end+ local first = effects and effects[1]+ return first and first.range or core.magic.RANGE.Touch+end++-- How close to go to attack with what is ready: the distance, its full reach (attacked from as far as that when a+-- table or the like is in the way), and whether that is from afar (then it wants a clear shot)+local function attackDistance()+ if Actor.getStance(self) == Actor.STANCE.Spell then+ local range = castRange()+ if range == core.magic.RANGE.Self then return math.huge, math.huge, false end+ if range == core.magic.RANGE.Target then return RANGED_ENGAGE, RANGED_ENGAGE, true end+ local touch = core.getGMST('fCombatDistance')+ return touch * REACH_MARGIN, touch, false+ end+ local reach = lent.weaponReach()+ if reach >= lent.RANGED_REACH then return RANGED_ENGAGE, RANGED_ENGAGE, true end+ return reach * REACH_MARGIN, reach, false+end++local function clearShot(target)+ local hit = nearby.castRay(self.position + v3(0, 0, 100), target:getBoundingBox().center, { ignore = self })+ return not hit.hit or hit.hitObject == target+end++-- A click's attack: a weapon held long enough for a full swing or draw (quicker weapons need less), a spell cast once+local function startAttack()+ restFor = ATTACK_REST+ if Actor.getStance(self) == Actor.STANCE.Spell then+ castPending = true+ return+ end+ local weapon = Actor.getEquipment(self, Actor.EQUIPMENT_SLOT.CarriedRight)+ local speed = 1+ if weapon and types.Weapon.objectIsInstance(weapon) then+ speed = math.max(types.Weapon.record(weapon).speed, 0.25)+ end+ attackFor = ATTACK_WINDUP / speed+end++local function attacking()+ return castPending or attackFor > 0 or restFor > 0+end++-- Whether the click's own attack is going on (topdown.lua's aim line shows meanwhile)+function M.attacking()+ return attacking()+end++-- Whether a spell (or enchanted item) cast at a target is ready+function M.targetSpellReady()+ return Actor.getStance(self) == Actor.STANCE.Spell and castRange() == core.magic.RANGE.Target+end++-- The way there over the navigation mesh (straight there where there is none, or none yet). Stairs clicked (direct)+-- whose way doesn't end on them (tall stairs the navigation mesh stops part way up, though the character can climb+-- them): straight there, not round to the floor nearest them, behind or under them.+local function findWay(destination)+ local ok, status, points = pcall(nearby.findPath, self.position, destination,+ { agentBounds = Actor.getPathfindingAgentBounds(self) })+ local S = nearby.FIND_PATH_STATUS+ if ok and (status == S.Success or status == S.PartialPath) and #points > 0 then+ path = points+ if order and order.direct and (status ~= S.Success or (points[#points] - destination):length() > DIRECT_END) then+ path = { destination }+ end+ -- Where the navigation mesh misses the floor the player stands on, the way starts from the one nearest below+ -- (or above) it: a spot on this same floor is gone to straight, not down there and back up+ local level = STEP_SNAP_HEIGHT * 1.5+ if math.abs(points[1].z - self.position.z) > level and math.abs(destination.z - self.position.z) <= level then+ path = { destination }+ end+ else+ path = { destination }+ end+ pathIndex, pathTo = 1, destination+end++-- What a click on the ground picked, in openmw.log, with LOG_GROUND on (for finding where clicks on upper floors go)+local LOG_GROUND = false+local function note(kind, point, hit)+ if not LOG_GROUND then return end+ local function at(p) return p and string.format('(%.0f, %.0f, %.0f)', p.x, p.y, p.z) or 'none' end+ print(string.format('[Isowind click to move] %s: %s, ray hit %s, player %s', kind, at(point), at(hit),+ at(self.position)))+end++-- The top of the stairs (a step) straight above or below where they were hit: where a click on their side, back or+-- underside means. Past anything else above (a floor over them).+local function stairsTop(object, point)+ local from, to = point + v3(0, 0, STAIRS_REACH), point - v3(0, 0, 1)+ for _ = 1, 4 do+ local hit = nearby.castRay(from, to, { ignore = self })+ if not hit.hit then return nil end+ if hit.hitObject == object then return hit.hitPos end+ from = hit.hitPos - v3(0, 0, 1)+ end+ return nil+end++-- Where the cursor's ray meets the ground, for a click there: never on what stands between (a tree, a rooftop, a wall),+-- nor behind or under the stairs. Morrowind has no kind of object for stairs: they are statics with 'stair' (or+-- 'step', 'ramp') in their id or model. Along the ray, the first of:+-- stairs, hit anywhere (not what the cutaway removes): the step above where the ray hit them, on the navigation mesh+-- if it is there and the player can walk to it; else that step itself, gone to straight where the navigation mesh+-- stops (direct: tall stairs it covers only part way, which the character climbs all the same)+-- a floor (facing up: GROUND_NORMAL_Z; not people, not what the cutaway removes) the player can walk to, or where+-- the navigation mesh misses it, that spot itself (direct); never past it to a floor below+-- walkable ground hidden just behind anything else in the way (not a floor)+-- So not a rooftop in front of the street, nor the floor behind or under the stairs. With nothing reachable (no+-- navigation mesh yet), the surface nearest the player's own level; over an edge, the plane at the player's feet.+-- from, dir: the camera and the cursor's direction from it. Returns the spot (nil: none), and whether it is direct.+function M.ground(from, dir)+ local bounds = Actor.getPathfindingAgentBounds(self)+ local function reachable(point)+ local ok, status = pcall(nearby.findPath, self.position, point, { agentBounds = bounds })+ return ok and status == nearby.FIND_PATH_STATUS.Success+ end+ local function onNavMesh(point, box, maxHeight)+ local ok, found = pcall(nearby.findNearestNavMeshPosition, point,+ { agentBounds = bounds, searchAreaHalfExtents = box })+ if ok and found and (not maxHeight or math.abs(found.z - point.z) <= maxHeight) and reachable(found) then+ return found+ end+ return nil+ end+ local probes = NAV_PROBES+ local unreachable = nil -- the last ground found and not reachable (a roof): not tried again near there+ local function groundBehind(start)+ for s = 0, NAV_DEPTH, NAV_STEP do+ if probes <= 0 then return nil end+ probes = probes - 1+ local ok, point = pcall(nearby.findNearestNavMeshPosition, start + dir * s,+ { agentBounds = bounds, searchAreaHalfExtents = NAV_PROBE_BOX })+ if ok and point and not (unreachable and (point - unreachable):length() < 50) then+ if reachable(point) then return point end+ unreachable = point+ end+ end+ return nil+ end++ local to = from + dir * 30000+ local start = from+ local best, bestHeight = nil, math.huge+ for _ = 1, 12 do+ local result = nearby.castRenderingRay(start, to, { ignore = self })+ if not result.hit then break end+ local object = result.hitObject+ local isActor = object and Actor.objectIsInstance(object)+ local whole = object and (isActor or types.Door.objectIsInstance(object))+ local normal = result.hitNormal+ local facing = normal and normal:dot(dir) < 0+ if not isActor and not camera.isCutAway(result.hitPos, whole, object) then+ if isStairs(object) then+ -- (never on past them: that is the floor behind or under them)+ local top = stairsTop(object, result.hitPos)+ note('stairs ' .. object.recordId, top, result.hitPos)+ if not top then return nil, false end+ return onNavMesh(top, SNAP_BOX, STEP_SNAP_HEIGHT) or top, true+ elseif facing and normal.z >= GROUND_NORMAL_Z then+ -- A floor: the navigation mesh on it (this floor's, never one a little below or above it:+ -- STEP_SNAP_HEIGHT), if the player can walk there; mapped but out of reach (a rooftop), on past it; and+ -- where the navigation mesh misses it (though the character walks on it), that very spot, gone to+ -- straight (direct). Never past a floor to one below it.+ local ok, found = pcall(nearby.findNearestNavMeshPosition, result.hitPos,+ { agentBounds = bounds, searchAreaHalfExtents = SNAP_BOX })+ if ok and found and math.abs(found.z - result.hitPos.z) <= STEP_SNAP_HEIGHT then+ if reachable(found) then+ note('floor', found, result.hitPos)+ return found, false+ end+ else+ note('floor (not on the navigation mesh)', result.hitPos, found)+ return result.hitPos, true+ end+ local height = math.abs(result.hitPos.z - self.position.z)+ if height < bestHeight then best, bestHeight = result.hitPos, height end+ elseif facing then+ local behind = groundBehind(result.hitPos)+ if behind then+ note('behind ' .. tostring(object and object.recordId or 'terrain'), behind, result.hitPos)+ return behind, false+ end+ end+ end+ start = result.hitPos + dir * 2+ end+ if not best and dir.z < -0.001 then+ best = from + dir * ((self.position.z - from.z) / dir.z)+ end+ note('nothing reachable', best)+ return best, false+end++-- Which way along the path from here, across the ground (a direction as topdown.lua's wantedDirection gives it)+local function pathDirection(destination)+ local near = WAYPOINT_REACHED * WAYPOINT_REACHED+ while pathIndex < #path do+ local d = path[pathIndex] - self.position+ if d.x * d.x + d.y * d.y > near then break end+ pathIndex = pathIndex + 1+ end+ local d = path[pathIndex] - self.position+ -- At the path's end, which can stop short of the spot (the navigation mesh's edge): straight on to it+ if pathIndex == #path and d.x * d.x + d.y * d.y <= near then+ d = destination - self.position+ end+ local length = math.sqrt(d.x * d.x + d.y * d.y)+ if length < 1 then return 0, 0 end+ return d.x / length, d.y / length+end++-- The button held from a click on the ground: the spot follows the cursor until it is let go (found every+-- STEER_INTERVAL, the way with it: it takes a dozen rays), whether or not the character has caught up with it+local function updateSteering(dt, groundFn)+ if not steering then return end+ if input.isMouseButtonPressed(order.button) then+ steerIn = steerIn - dt+ if steerIn <= 0 then+ steerIn = STEER_INTERVAL+ local spot, direct = groundFn()+ if spot then+ order.point, order.direct = spot, direct+ path = nil+ end+ end+ return+ end+ steering = false+ stuckFor, closest = 0, math.huge+ findWay(order.point)+end++-- Getting no closer (STUCK_TIME): near enough to what was clicked, it is used or attacked from where the character+-- stands (a counter between); else the way is found again, a few times, then the character gives up. True when it+-- has given up.+local function onStuck(destination)+ local object = order.object+ if order.kind == 'use' and gapTo(object) <= activateReach() and lent.withinReachHeight(object) then+ order.close = true+ return false+ elseif order.kind == 'attack' then+ local _, fullReach = attackDistance()+ if gapTo(object) <= fullReach then+ order.close = true+ return false+ end+ end+ stuckTries = stuckTries + 1+ if stuckTries > STUCK_TRIES then return true end+ findWay(destination)+ return false+end++-- Carries out the order: the way to go (as wantedDirection gives it) and where to aim (nil: as ever, so with a bow+-- drawn the character still aims at the cursor while running the other way; a point: the target attacked), or nothing+-- with no order. groundFn: where the cursor points on the ground (topdown.lua's groundUnderCursor)+function M.update(dt, groundFn)+ if not order then return nil end+ updateSteering(dt, groundFn)+ local object = order.object+ if object and not (object:isValid() and object.enabled) then+ M.cancel()+ return nil+ end+ local destination = object and object.position or order.point++ if order.kind == 'ground' then+ local d = destination - self.position+ if d.x * d.x + d.y * d.y <= GROUND_ARRIVED * GROUND_ARRIVED then+ if not steering then M.cancel() end+ return 0, 0, nil+ end+ elseif order.kind == 'use' then+ if (order.close or gapTo(object) <= USE_DISTANCE) and lent.withinReachHeight(object) then+ M.cancel()+ lent.activate(object)+ return 0, 0, nil+ end+ else+ -- Attack: once in range, stand and attack, again and again while the button stays held+ if Actor.isDead(object) or Actor.getStance(self) == Actor.STANCE.Nothing then+ M.cancel()+ return nil+ end+ if order.attacked and not attacking() and not input.isMouseButtonPressed(order.button) then+ M.cancel()+ return nil+ end+ local center = object:getBoundingBox().center+ local reach, fullReach, ranged = attackDistance()+ local gap = gapTo(object)+ if (gap <= reach or (order.close and gap <= fullReach)) and (not ranged or clearShot(object)) then+ if not attacking() then+ startAttack()+ order.attacked = true+ end+ return 0, 0, center+ end+ -- An attack begun is finished where it was begun; then, held, after it again should it have stepped away+ if attacking() then return 0, 0, center end+ end++ -- On the way: found again every so often while the spot follows the cursor, once the target has moved off where it+ -- was found to, and when getting no closer+ if not path or (pathTo - destination):length() > TARGET_MOVED then+ findWay(destination)+ end+ if not steering then+ local remaining = (destination - self.position):length()+ if remaining < closest - 5 then+ closest, stuckFor = remaining, 0+ else+ stuckFor = stuckFor + dt+ if stuckFor > STUCK_TIME then+ stuckFor, closest = 0, remaining+ if onStuck(destination) then+ M.cancel()+ return 0, 0, nil+ end+ end+ end+ end+ local dx, dy = pathDirection(destination)+ return dx, dy, nil+end++-- A click of the move button (M.button: 1 left, 3 right): what the cursor is on (hovered, or nil), and groundFn, where+-- it points on the ground (M.ground). Returns the spot when the character is to go there (for the red X).+function M.click(hovered, groundFn, button)+ local stance = Actor.getStance(self)+ local target = hovered and hovered:isValid() and hovered or nil+ -- Shift held: the character stands where they are (topdown.lua), so a click doesn't send them anywhere; with the+ -- left button moving, it attacks where they stand+ if input.isShiftPressed() then+ M.cancel()+ shiftAttack = button == 1 and stance ~= Actor.STANCE.Nothing+ return nil+ end+ local hostile = target and Actor.objectIsInstance(target) and lent.isHostile(target)+ if hostile and button == 3 then+ target = nil -- the right button never attacks: to the ground there, as anywhere+ end+ if target and hostile and stance ~= Actor.STANCE.Nothing and not lent.lockToolReady() then+ startOrder('attack', nil, target, button)+ elseif target then+ startOrder('use', nil, target, button)+ else+ local spot, direct = groundFn()+ if spot then+ startOrder('ground', spot, nil, button)+ order.direct = direct+ steering = true+ return spot+ end+ end+ return nil+end++-- The click's own attack; with the left button moving, the left button doesn't attack by itself (it is bound to Use,+-- and a click on the ground moves): then only the click's attack, Shift and click, and the power attack (the right+-- button) do. With the right button moving the left one attacks where the character stands as ever. Runs after the+-- built-in controls (scripts/omw/input/playercontrols.lua) have set use. enabled: click to move is on, with the mouse.+function M.updateAttack(dt, enabled)+ if shiftAttack and not input.isMouseButtonPressed(1) then shiftAttack = false end+ if not enabled or shiftAttack then return end+ local leftMoves = M.button() == 1+ if leftMoves and Actor.getStance(self) == Actor.STANCE.Weapon and input.isMouseButtonPressed(3) then return end+ if not leftMoves and not attacking() then return end+ local use = self.ATTACK_TYPE.NoAttack+ if castPending then+ castPending = false+ use = self.ATTACK_TYPE.Any+ elseif attackFor > 0 then+ attackFor = attackFor - dt+ use = self.ATTACK_TYPE.Any+ elseif restFor > 0 then+ restFor = restFor - dt+ end+ self.controls.use = use+end++return Mdiff --git a/isowind/mod/scripts/isowind/moveprompt.lua b/isowind/mod/scripts/isowind/moveprompt.luanew file mode 100644index 0000000..ad36656--- /dev/null+++ b/isowind/mod/scripts/isowind/moveprompt.lua@@ -0,0 +1,141 @@+-- The first time the game is played: how to move, WASD or click to move (clicktomove.lua), asked in a small window+-- (changed later in Options -> Scripts -> Isowind). The game waits under it (the Interface mode, its windows hidden).+-- 1 or 2 choose too, and a controller's A takes WASD (click to move is for the mouse); closing it some other way (Esc)+-- leaves WASD, the default. The choice is the installation's, not the character's (permanent storage). Playing with a+-- controller it isn't asked (topdown.lua: the menus made for a controller, Isowind.exe's Controller tick box, or the+-- controller last used): its own controls, never click to move; it is asked once the mouse and keyboard are used.+-- Used by topdown.lua, which calls update every frame in the top-down view.++local async = require('openmw.async')+local core = require('openmw.core')+local input = require('openmw.input')+local storage = require('openmw.storage')+local ui = require('openmw.ui')+local util = require('openmw.util')+local I = require('openmw.interfaces')++local v2 = util.vector2+local l10n = core.l10n('Isowind')+local controls = storage.playerSection('Settings/Isowind/Controls')+local ownSettings = storage.playerSection('IsowindTopDown')++local prompt = nil+local keysUp = false -- 1, 2 and A have been up since it opened (one held as it opened doesn't choose)+local modeCame = false -- the Interface mode asked for has come (I.UI.getMode says so from a frame later)++local M = {}++local function close(mode)+ controls:set('MoveMode', mode)+ ownSettings:set('MoveModeChosen', true)+ if prompt then+ prompt:destroy()+ prompt = nil+ end+ -- Interface again (bringing back the windows it hid), then no mode: as Questman's ui.lua closes its own+ if I.UI.getMode() == 'Interface' then+ I.UI.setMode('Interface')+ I.UI.setMode()+ end+end++local CHOICE_WIDTH = 280 -- each choice's text wraps at this width, so the two are the same size side by side+local CHOICE_TEXT_HEIGHT = 72 -- room for its description's lines+local GAP = v2(16, 16) -- between the two choices, and around the window's lines++local function choice(name, description, mode)+ local templates = I.MWUI.templates+ return {+ template = templates.boxSolid,+ events = { mouseClick = async:callback(function() close(mode) end) },+ content = ui.content {+ {+ template = templates.padding,+ content = ui.content {+ {+ type = ui.TYPE.Flex,+ props = { arrange = ui.ALIGNMENT.Center },+ content = ui.content {+ { template = templates.textHeader, props = { text = l10n(name) } },+ { template = templates.interval },+ {+ template = templates.textNormal,+ props = {+ text = l10n(description),+ autoSize = false,+ size = v2(CHOICE_WIDTH, CHOICE_TEXT_HEIGHT),+ multiline = true,+ wordWrap = true,+ textAlignH = ui.ALIGNMENT.Center,+ },+ },+ },+ },+ },+ },+ },+ }+end++local function open()+ local templates = I.MWUI.templates+ I.UI.setMode('Interface', { windows = {} })+ keysUp, modeCame = false, false+ prompt = ui.create {+ layer = 'Windows',+ template = templates.boxTransparentThick,+ props = { relativePosition = v2(0.5, 0.5), anchor = v2(0.5, 0.5) },+ content = ui.content {+ {+ template = templates.padding,+ content = ui.content {+ {+ type = ui.TYPE.Flex,+ props = { arrange = ui.ALIGNMENT.Center },+ content = ui.content {+ { template = templates.textHeader, props = { text = l10n('move_prompt_title') } },+ { props = { size = GAP } },+ {+ type = ui.TYPE.Flex,+ props = { horizontal = true },+ content = ui.content {+ choice('move_prompt_wasd', 'move_prompt_wasd_desc', 'move_wasd'),+ { props = { size = GAP } },+ choice('move_prompt_click', 'move_prompt_click_desc', 'move_click'),+ },+ },+ { props = { size = GAP } },+ { template = templates.textNormal, props = { text = l10n('move_prompt_later') } },+ },+ },+ },+ },+ },+ }+end++-- canAsk: the player has control of the character (it is asked then, once)+function M.update(canAsk)+ -- (the topdown view's onFrame keeps calling while it is up: the game paused under it doesn't stop that)+ if not prompt then+ if canAsk and not ownSettings:get('MoveModeChosen') then open() end+ return+ end+ if I.UI.getMode() == 'Interface' then+ modeCame = true+ else+ if modeCame then close('move_wasd') end+ return+ end+ local one, two = input.isKeyPressed(input.KEY._1), input.isKeyPressed(input.KEY._2)+ local a = input.isControllerButtonPressed(input.CONTROLLER_BUTTON.A)+ if not keysUp then+ keysUp = not (one or two or a)+ elseif one or a then+ close('move_wasd')+ elseif two then+ close('move_click')+ end+end++return Mdiff --git a/isowind/mod/scripts/isowind/settings.lua b/isowind/mod/scripts/isowind/settings.luaindex 91b3639..ad74b46 100644--- a/isowind/mod/scripts/isowind/settings.lua+++ b/isowind/mod/scripts/isowind/settings.lua@@ -37,7 +37,8 @@ I.Settings.registerGroup {},}--- Two bindings, so a key and a controller button can both switch the view (one button each)+-- Two bindings, so a key and a controller button can both switch the view (one button each). How the mouse moves the+-- character is asked the first time the game is played (topdown.lua), and can be changed here.I.Settings.registerGroup {key = 'Settings/Isowind/Controls',page = 'Isowind',@@ -45,6 +46,29 @@ I.Settings.registerGroup {name = 'settings_controls',permanentStorage = true,settings = {+ {+ key = 'MoveMode',+ renderer = 'select',+ name = 'move_mode',+ description = 'move_mode_desc',+ default = 'move_wasd',+ argument = { l10n = 'Isowind', items = { 'move_wasd', 'move_click' } },+ },+ {+ key = 'MoveButton',+ renderer = 'select',+ name = 'move_button',+ description = 'move_button_desc',+ default = 'move_button_right',+ argument = { l10n = 'Isowind', items = { 'move_button_right', 'move_button_left' } },+ },+ {+ key = 'CameraRotation',+ renderer = 'checkbox',+ name = 'camera_rotation',+ description = 'camera_rotation_desc',+ default = false,+ },{key = 'SwitchView',renderer = 'inputBinding',diff --git a/isowind/mod/scripts/isowind/topdown.lua b/isowind/mod/scripts/isowind/topdown.luaindex 7cd3676..ee4b9ca 100644--- a/isowind/mod/scripts/isowind/topdown.lua+++ b/isowind/mod/scripts/isowind/topdown.lua@@ -14,6 +14,19 @@-- bindable to a controller button, in Options -> Scripts -> Isowind); with an attack held (an-- arrow drawn) the view still switches, and the attack starts again in the new view--+-- Or click to move, asked the first time the game is played (and in Options -> Scripts -> Isowind): right click runs to+-- the spot on the ground, a red X splashing onto it (held, the spot follows the cursor); on a person or a thing walks+-- right up to it and uses it. It never attacks. Left click does as above; the power attack is then on a controller's+-- left trigger only. Shift held, the character stands still (instead of walking): aiming, attacking, not moving. WASD+-- still moves, and takes over from a click. (clicktomove.lua; the left button can do the moving instead, attacks and+-- all.)+--+-- A bow, crossbow or thrown weapon drawn, or a spell cast at a target ready: a thin line draws out a few metres from the+-- character the way they aim, a small ring at its end (updateAimLine).+--+-- Camera rotation, off unless turned on there: the middle mouse button held and the mouse moved turns the view, with+-- click to move the left and right arrow keys too, and on a controller the D-pad left and right held.+---- With a controller (it takes over as soon as a stick or button is used, the mouse as soon as it moves):-- left stick move right stick aim / pick what X uses-- A jump B ready weapon@@ -21,8 +34,8 @@-- right trigger attack / cast left trigger power attack-- bumpers previous / next quick key-- D-pad up / down zoom (hold to keep zooming), within the view; in menus they move through the options--- D-pad left not assigned--- Start menu Back inventory (hold: journal)+-- D-pad left / right turn the view, held (with camera rotation on)+-- Start menu Back inventory (hold: the journal, its last page)-- left stick in sneak right stick in rest-- in water, A held swims up and the left stick held in dives (the Jump and Sneak bindings)-- There is no cursor then: what the right stick points at (or else what is nearest in front) gets the ring and the@@ -42,7 +55,8 @@-- view at that distance; closer than FIRST_PERSON_BELOW, first person. Zooming stays within the view's range and the-- switch view trigger (F7) moves between them, each keeping its own zoom. Zooming and the first / third person switch-- are taken from the built-in camera script for good (claimCamera).--- The view is a fixed isometric angle: turned 45 degrees, looking down at the classic isometric 35.26 degrees.+-- The view is an isometric angle: turned 45 degrees (unless turned with camera rotation), looking down at the classic+-- isometric 35.26 degrees.-- The camera slides in toward the player rather than go underground on slopes, and creatures (and hurt or hostile-- people) get health bars (healthbars.lua). In multiplayer, party members (MMO) get a green ring, and other players-- off the screen an arrow at its edge pointing their way: party members in MMO mode, everyone in co-op.@@ -63,6 +77,8 @@ local util = require('openmw.util')local I = require('openmw.interfaces')local healthbars = require('scripts.isowind.healthbars')+local clickToMove = require('scripts.isowind.clicktomove')+local movePrompt = require('scripts.isowind.moveprompt')local Actor = types.Actorlocal Player = types.Player@@ -79,6 +95,7 @@ endlocal controlSettings = storage.playerSection('SettingsOMWControls')local ownSettings = storage.playerSection('IsowindTopDown')+local isowindControls = storage.playerSection('Settings/Isowind/Controls') -- MoveMode, CameraRotation (settings.lua)-- Tuning ---------------------------------------------------------------------------------------------------------local VIEW_YAW = math.rad(45) -- the view is turned 45 degrees, so the world's grid runs diagonally@@ -116,6 +133,15 @@ local SIGN_RANGE = 500 -- signs this close to the player show theirlocal SIGN_REFRESH = 0.25 -- how often to look for signs nearby (seconds)local SIGN_LABELS = 8 -- at most this many sign names at once (the nearest)local SIGN_TEXT_SIZE = 16+local ROTATE_MOUSE_SPEED = 0.006 -- camera rotation per pixel the mouse moves with the middle button held (radians)+local ROTATE_KEY_SPEED = math.rad(90) -- ...and per second with an arrow key or the D-pad held+local MARKER_SIZE = 18 -- click to move's red X where the character is going: half its length (world units)+local MARKER_SPLASH = 0.5 -- seconds its splash takes when clicked (it bounces into place in the first part)+local MARKER_FADE = 0.4 -- seconds it fades over once there+local AIM_LINE_LENGTH = 250 -- the aim line reaches this far out (a few metres)...+local AIM_DRAW_TIME = 0.5 -- ...drawing out over this long+local AIM_LINE_OPACITY = 0.5+local AIM_LINE_HEIGHT = 100 -- the shot leaves from this high (the chest, as updateFacing aims from)--------------------------------------------------------------------------------------------------------------------local active = false -- whether the top-down view's overrides are currently applied@@ -137,6 +163,8 @@ local aimLocked = false -- hovered is the hostile creature the contrlocal backPressedAt, journalOpened = nil, falselocal dpadHeld = 0 -- how long D-pad up / down has been held; nil while a hold begun in a menu lastslocal pendingMode = nil -- the first / third person camera mode asked for, until the camera is in it+local rotating = false -- the middle mouse button is turning the view (the cursor stays where it is)+local marker = { point = nil, alpha = 0, pop = 1 } -- click to move's red X (showMarker)-- Defined further downlocal nearestUsable, setRingVisible, hideSignLabels@@ -234,6 +262,7 @@ local function release()self.controls.sideMovement = 0self.controls.yawChange = 0self.controls.pitchChange = 0+ clickToMove.cancel()setUiVisible(false)setRingVisible(false)hideSignLabels()@@ -331,6 +360,7 @@ local function worldToScreen(pos)endlocal function updateCursor()+ if rotating then return end -- the mouse turns the view insteadlocal screen = ui.screenSize()cursor = v2(util.clamp(cursor.x + input.getMouseMoveX() * CURSOR_SPEED / screen.x, 0, 1),@@ -352,6 +382,35 @@ local function updateZoom()if notches ~= 0 then zoomBy(math.exp(-notches * ZOOM_STEP)) endend+local function held(pressed)+ return pressed and 1 or 0+end++-- Turning the view, once camera rotation is on (Options -> Scripts -> Isowind): the middle mouse button held and the+-- mouse moved, with click to move the left and right arrow keys too, and on a controller the D-pad left and right.+-- Everything screen-relative (WASD, the sticks, the cursor) goes by viewYaw, and so turns with it.+local function updateRotation(dt)+ rotating = false+ if not isowindControls:get('CameraRotation') then+ viewYaw = VIEW_YAW+ return+ end+ local turn = 0+ if input.isMouseButtonPressed(2) then+ rotating = true+ turn = turn + input.getMouseMoveX() * ROTATE_MOUSE_SPEED+ end+ if isowindControls:get('MoveMode') == 'move_click' then+ local K = input.KEY+ turn = turn + (held(input.isKeyPressed(K.RightArrow)) - held(input.isKeyPressed(K.LeftArrow)))+ * ROTATE_KEY_SPEED * dt+ end+ local B = input.CONTROLLER_BUTTON+ turn = turn + (held(input.isControllerButtonPressed(B.DPadRight)) - held(input.isControllerButtonPressed(B.DPadLeft)))+ * ROTATE_KEY_SPEED * dt+ viewYaw = wrapAngle(viewYaw + turn)+end+local function segmentDistance(p, a, b)local ab = b - alocal t = util.clamp((p - a):dot(ab) / math.max(ab:dot(ab), 1e-4), 0, 1)@@ -380,6 +439,12 @@ local function castThroughCutaway(from, dir)return { hit = false }end+-- Where on the ground the cursor points, for click to move (clicktomove.lua's ground: never on a tree or rooftop in the+-- way)+local function groundUnderCursor()+ return clickToMove.ground(view.position, cursorDirection())+end+-- What is under the cursor, and the point the character should face.local function updatePick()local from = view.position@@ -470,11 +535,47 @@ local function hidesRing()local shader = getRingShader()if shader and shader:isEnabled() thenshader:setVector4('uSelection', util.vector4(0, 0, 0, 0))+ shader:setVector4('uMoveMarker', util.vector4(0, 0, 0, 0))+ shader:setVector4('uAimLineStyle', util.vector4(0, 0, 0, 0))shader:setVector4Array('uParty', noMarks)shader:setVector4Array('uArrows', noMarks)endend+-- The red X on the ground where click to move is going (shaders/isowind_selection.omwfx): it splashes down when clicked+-- (a ripple and drops spread out as it bounces into place), follows the cursor while the button is held, and fades+-- once the character is there (or stops going).+local function showMarker(point)+ marker.point = point+ marker.alpha = 1+ marker.pop = 0+end++local function updateMoveMarker(dt)+ local shader = getRingShader()+ if not shader then return end+ local going = clickToMove.groundTarget()+ if going then+ marker.point, marker.alpha = going, 1+ else+ marker.alpha = math.max(0, marker.alpha - dt / MARKER_FADE)+ end+ marker.pop = math.min(1, marker.pop + dt / MARKER_SPLASH)+ if not marker.point or marker.alpha <= 0 then+ shader:setVector4('uMoveMarker', util.vector4(0, 0, 0, 0))+ return+ end+ local p = marker.point+ -- Bouncing into place in the splash's first part: from nothing, past its size and back+ local t = math.min(1, marker.pop * 1.6)+ local size = MARKER_SIZE * math.max(0.05, 1 - (1 - t) ^ 3 * math.cos(t * 3 * math.pi))+ shader:setVector4('uMoveMarker', util.vector4(p.x, p.y, p.z, size))+ -- Its arms cross on the screen's diagonals: the screen's right across the ground, how strongly it shows, and how far+ -- the splash has got (1: done)+ shader:setVector4('uMoveMarkerAxes',+ util.vector4(math.cos(viewYaw), -math.sin(viewYaw), marker.alpha, marker.pop))+end+local function weaponReach()local weapon = Actor.getEquipment(self, Actor.EQUIPMENT_SLOT.CarriedRight)if weapon and types.Weapon.objectIsInstance(weapon) then@@ -488,6 +589,45 @@ local function weaponReach()return core.getGMST('fCombatDistance') -- hand-to-handend+-- The aim line: a thin line drawing out a few metres from the character the way they aim, a small ring at its end,+-- while a bow, crossbow or thrown weapon is drawn (the left button; the right one where it power attacks, not where it+-- moves; a click to move attack; a controller's triggers) and while a spell cast at a target is ready. It goes the way+-- the character faces, from the chest updateFacing aims from, down or up to what the cursor (or the right stick) is+-- on: on the cursor once the character has turned to it, showing it while they haven't yet.+-- rightAttacks: the right button power attacks (it doesn't move: clickMoveOn).+local aimDrawn = 0 -- seconds the line has been drawing out+local function updateAimLine(dt, rightAttacks)+ local shader = getRingShader()+ if not shader then return end+ local stance = Actor.getStance(self)+ local drawing = stance == Actor.STANCE.Weapon and weaponReach() >= RANGED_REACH+ and (input.getBooleanActionValue('Use') or (rightAttacks and input.isMouseButtonPressed(3))+ or clickToMove.attacking() or input.getAxisValue(input.CONTROLLER_AXIS.TriggerLeft) >= 0.6)+ if not (drawing or clickToMove.targetSpellReady()) then+ aimDrawn = 0+ shader:setVector4('uAimLineStyle', util.vector4(0, 0, 0, 0))+ return+ end+ aimDrawn = aimDrawn + dt+ local yaw = self.rotation:getYaw()+ local from = self.position + v3(0, 0, AIM_LINE_HEIGHT)+ local dir = v3(math.sin(yaw), math.cos(yaw), 0)+ if aimPoint then+ local d = aimPoint - from+ local across = math.sqrt(d.x * d.x + d.y * d.y)+ if across > 1 then dir = v3(dir.x * across, dir.y * across, d.z):normalize() end+ end+ local length = AIM_LINE_LENGTH * math.min(1, aimDrawn / AIM_DRAW_TIME)+ local x0, y0, depth0 = viewCoordinates(from)+ local x1, y1, depth1 = viewCoordinates(from + dir * length)+ if depth0 < 1 or depth1 < 1 then+ shader:setVector4('uAimLineStyle', util.vector4(0, 0, 0, 0))+ return+ end+ shader:setVector4('uAimLine', util.vector4((x0 + 1) / 2, (y0 + 1) / 2, (x1 + 1) / 2, (y1 + 1) / 2))+ shader:setVector4('uAimLineStyle', util.vector4(AIM_LINE_OPACITY, 1, 0, 0))+end+local function updateRing()local shader = getRingShader()if not shader then return end@@ -748,14 +888,15 @@ end-- With a weapon or spell ready the character always aims at the cursor; the engine (twin-stick movement in-- character.cpp) turns their legs to run the way they move while the upper body keeps aiming. Otherwise they face--- the way they walk.-local function updateFacing(dt, dx, dy)- local aiming = Actor.getStance(self) ~= Actor.STANCE.Nothing and aimPoint+-- the way they walk. aimAt, given, says otherwise: a point to aim at, or false to face the way walked (click to move).+local function updateFacing(dt, dx, dy, aimAt)+ local aiming = aimAt+ if aiming == nil then aiming = Actor.getStance(self) ~= Actor.STANCE.Nothing and aimPoint endself.controls.yawChange = 0if aiming then-- Dead zone: with the cursor right on the character, tiny cursor moves would swing the aim wildly.- local d = aimPoint - self.position+ local d = aiming - self.positionif d.x * d.x + d.y * d.y > AIM_DEAD_ZONE * AIM_DEAD_ZONE thenturnTowards(math.atan2(d.x, d.y), dt)end@@ -766,7 +907,7 @@ local function updateFacing(dt, dx, dy)-- When aiming, pitch toward the target so arrows and spells go where the cursor points.local pitch = 0if aiming then- local fromChest = aimPoint - (self.position + v3(0, 0, 100))+ local fromChest = aiming - (self.position + v3(0, 0, 100))local horizontal = math.sqrt(fromChest.x * fromChest.x + fromChest.y * fromChest.y)pitch = util.clamp(-math.atan2(fromChest.z, horizontal), math.rad(-60), math.rad(60))end@@ -786,11 +927,13 @@ local function powerAttackType()return bestend-local function updatePowerAttack()+-- rightMoves: click to move has the right button (then it doesn't power attack).+local function updatePowerAttack(rightMoves)-- Runs after the built-in controls (scripts/omw/input/playercontrols.lua), which set use from the left button-- and release the attack again once neither button is held.local leftTrigger = input.getAxisValue(input.CONTROLLER_AXIS.TriggerLeft) >= 0.6- if Actor.getStance(self) == Actor.STANCE.Weapon and (input.isMouseButtonPressed(3) or leftTrigger) then+ local rightButton = input.isMouseButtonPressed(3) and not rightMoves+ if Actor.getStance(self) == Actor.STANCE.Weapon and (rightButton or leftTrigger) thenself.controls.use = powerAttackType()endend@@ -1013,6 +1156,12 @@ local function switchView(wanted)endend+-- Click to move (clicktomove.lua): chosen in Options -> Scripts -> Isowind (or the first time: moveprompt.lua), and only+-- with the mouse+local function clickMoveOn()+ return isowindControls:get('MoveMode') == 'move_click' and not gamepad+end+local function onFrame(dt)claimCamera()updateDevice()@@ -1029,13 +1178,17 @@ local function onFrame(dt)returnendapply()+ -- (asked of the mouse and keyboard only: with a controller, its own controls, and WASD stays chosen until then)+ movePrompt.update(controlsAllowed() and not gamepad and not input._isControllerMenusEnabled())if not controlsAllowed() then- -- Menus, dialogue, paused: keep the camera, stop driving the character.+ -- Menus, dialogue, paused: keep the camera, stop driving the character (and drop where it was going).self.controls.movement = 0self.controls.sideMovement = 0self.controls.yawChange = 0self.controls.pitchChange = 0+ clickToMove.cancel()+ marker.alpha = 0if not core.isWorldPaused() or I.UI.getMode() then updateCamera(dt) endsetUiVisible(false)hidesRing()@@ -1044,6 +1197,7 @@ local function onFrame(dt)returnend+ updateRotation(dt)updateCursor()updateCamera(dt)if gamepad then updateGamepadPick() else updatePick() end@@ -1054,9 +1208,21 @@ local function onFrame(dt)updateParty()healthbars.update(worldToScreen, hovered) -- (the one the cursor or the right stick is on already has the label)local dx, dy = wantedDirection()- updateFacing(dt, dx, dy)+ local aimAt = nil+ -- Click to move: Shift held, the character stands where they are (and aims, with a weapon or spell ready)+ if clickMoveOn() and input.isShiftPressed() then+ dx, dy = 0, 0+ clickToMove.cancel()+ end+ if clickToMove.going() and (dx * dx + dy * dy > 0.01 or gamepad) then clickToMove.cancel() end -- WASD or a stick+ local ox, oy, orderAim = clickToMove.update(dt, groundUnderCursor)+ if ox then dx, dy, aimAt = ox, oy, orderAim end+ updateFacing(dt, dx, dy, aimAt)updateMovement(dx, dy)- updatePowerAttack()+ updatePowerAttack(clickMoveOn() and clickToMove.button() == 3)+ clickToMove.updateAttack(dt, clickMoveOn())+ updateMoveMarker(dt)+ updateAimLine(dt, not (clickMoveOn() and clickToMove.button() == 3))jumpRequested = falseupdateSignLabels(dt) -- last: should it fail, the character still movesend@@ -1065,6 +1231,16 @@ local function activate(object)core.sendGlobalEvent('Isowind_Activate', { object = object, actor = self.object })end+clickToMove.init {+ weaponReach = weaponReach,+ RANGED_REACH = RANGED_REACH,+ isHostile = isHostile,+ lockToolReady = lockToolReady,+ withinReachHeight = withinReachHeight,+ activate = activate,+ ACTIVATE_SLACK = ACTIVATE_SLACK,+}+local function activateHovered()if not hovered then return false endif hoveredInRange then@@ -1128,8 +1304,14 @@ nearestUsable = function(direction, locksOnly)endlocal function onMouseButtonPress(button)- if not (active and button == 1 and controlsAllowed()) then return end- if Actor.getStance(self) ~= Actor.STANCE.Nothing then return end+ if not (active and controlsAllowed()) then return end+ if clickMoveOn() and button == clickToMove.button() then+ local spot = clickToMove.click(hovered, groundUnderCursor, button)+ if spot then showMarker(spot) end+ return+ end+ -- The left button, as without click to move (when the right one moves)+ if button ~= 1 or Actor.getStance(self) ~= Actor.STANCE.Nothing then return endactivateHovered()end@@ -1189,6 +1371,7 @@ local lastFrameError = nillocal function onFrameSafe(dt)local ok, err = pcall(onFrame, dt)if not ok then+ pcall(clickToMove.cancel) -- (the character mustn't keep running somewhere)pcall(hidesRing)pcall(hideSignLabels)pcall(healthbars.clear)@@ -1208,12 +1391,15 @@ return {onTeleported = function()camera.instantTransition()signRefreshIn = 0 -- the signs found before are in another cell now+ clickToMove.cancel() -- and where the character was going+ marker.alpha = 0end,onSave = function()return {distance = targetDistance,topDownDistance = lastTopDownDistance,thirdDistance = lastThirdDistance,+ viewYaw = viewYaw,}end,onLoad = function(data)@@ -1221,6 +1407,7 @@ return {targetDistance = data.distance or targetDistancelastTopDownDistance = data.topDownDistance or lastTopDownDistancelastThirdDistance = data.thirdDistance or lastThirdDistance+ viewYaw = data.viewYaw or viewYaw-- A save from before the zoom chose the view, made in the normal viewif data.enabled == false and targetDistance >= TOPDOWN_FROM thentargetDistance = THIRD_PERSON_DISTANCEdiff --git a/isowind/mod/shaders/isowind_selection.omwfx b/isowind/mod/shaders/isowind_selection.omwfxindex 179d8b1..b13a526 100644--- a/isowind/mod/shaders/isowind_selection.omwfx+++ b/isowind/mod/shaders/isowind_selection.omwfx@@ -10,6 +10,30 @@ uniform_vec4 uSelectionColor {description = "Ring colour (rgb) and strength (a).";}+uniform_vec4 uMoveMarker {+ default = vec4(0.0, 0.0, 0.0, 0.0);+ static = false;+ description = "Where click to move is going (xyz) and half the length of the red X there (w, 0 = none).";+}++uniform_vec4 uMoveMarkerAxes {+ default = vec4(1.0, 0.0, 0.0, 0.0);+ static = false;+ description = "The screen's right across the ground (xy), which the X's arms cross diagonally, its strength (z), and how far its splash has got (w, 1 = done).";+}++uniform_vec4 uAimLine {+ default = vec4(0.0, 0.0, 0.0, 0.0);+ static = false;+ description = "The bow's aim line on the screen: from (xy) to (zw), 0 to 1 from the bottom left; none when the same.";+}++uniform_vec4 uAimLineStyle {+ default = vec4(0.0, 0.0, 0.0, 0.0);+ static = false;+ description = "The aim line's strength (x), and whether it ends in a small ring (y, 1 = a ring).";+}+uniform_vec4 uParty {size = 8;static = false;@@ -53,6 +77,70 @@ fragment ring {return max(line, fill) * ground;}+ // The red X where click to move is going, painted on the ground like the rings: two arms, each `width` wide,+ // crossing on the screen's diagonals (uMoveMarkerAxes.xy is the screen's right across the ground)+ const float MARKER_WIDTH = 5.0; // world units+ const float MARKER_OUTLINE = 3.0;+ const vec3 MARKER_COLOR = vec3(0.9, 0.08, 0.05);+ const vec3 MARKER_OUTLINE_COLOR = vec3(0.2, 0.02, 0.01);++ float markerAmount(vec3 world, float width)+ {+ vec2 local = world.xy - uMoveMarker.xy;+ vec2 right = uMoveMarkerAxes.xy;+ float u = dot(local, right);+ float v = dot(local, vec2(-right.y, right.x));+ float a = abs(u - v) * 0.70710678; // distance from one arm...+ float b = abs(u + v) * 0.70710678; // ...and from the other+ float halfLength = uMoveMarker.w + width * 0.5;+ float armA = (1.0 - smoothstep(width * 0.5, width, a)) * (1.0 - smoothstep(halfLength - 2.0, halfLength, b));+ float armB = (1.0 - smoothstep(width * 0.5, width, b)) * (1.0 - smoothstep(halfLength - 2.0, halfLength, a));+ float ground = 1.0 - smoothstep(GROUND_RANGE * 0.5, GROUND_RANGE, abs(world.z - uMoveMarker.z));+ return max(armA, armB) * ground;+ }++ // The X's splash as it lands (uMoveMarkerAxes.w: how far it has got, 0 to 1): a ripple spreading out and thinning,+ // and drops flung out past it, shrinking, all fading as they go+ const float SPLASH_RADIUS = 46.0; // world units+ const int SPLASH_DROPS = 7;++ float splashAmount(vec3 world, float progress)+ {+ vec2 local = world.xy - uMoveMarker.xy;+ float fade = 1.0 - progress;+ float radius = SPLASH_RADIUS * (1.0 - fade * fade); // quick at first, slowing+ float width = mix(6.0, 1.0, progress);+ float ripple = 1.0 - smoothstep(width * 0.5, width, abs(length(local) - radius));+ vec2 right = uMoveMarkerAxes.xy;+ vec2 up = vec2(-right.y, right.x);+ float dropSize = mix(5.0, 0.5, progress);+ float drops = 0.0;+ for (int i = 0; i < SPLASH_DROPS; ++i)+ {+ // Unevenly round, and not all as far: a splash, not a pattern+ float angle = (float(i) + 0.35 * sin(float(i) * 2.7)) * 6.2831853 / float(SPLASH_DROPS);+ float reach = radius * (1.25 + 0.25 * sin(float(i) * 1.9));+ vec2 drop = (right * cos(angle) + up * sin(angle)) * reach;+ drops = max(drops, 1.0 - smoothstep(dropSize * 0.5, dropSize, length(local - drop)));+ }+ float ground = 1.0 - smoothstep(GROUND_RANGE * 0.5, GROUND_RANGE, abs(world.z - uMoveMarker.z));+ return max(ripple, drops) * fade * ground;+ }++ // The bow's aim line (uAimLine, on the screen): its distance in pixels from this one+ const float AIM_LINE_WIDTH = 1.2; // pixels at 1080 lines+ const float AIM_LINE_OUTLINE = 1.0;+ const float AIM_END_RING = 5.0; // the ring at its end: its radius, pixels at 1080 lines+ const vec3 AIM_LINE_COLOR = vec3(0.95, 0.88, 0.62);+ const vec3 AIM_LINE_OUTLINE_COLOR = vec3(0.1, 0.07, 0.03);++ float segmentDistance(vec2 pixel, vec2 a, vec2 b)+ {+ vec2 ab = b - a;+ float t = clamp(dot(pixel - a, ab) / max(dot(ab, ab), 0.0001), 0.0, 1.0);+ return length(pixel - (a + ab * t));+ }+// Distance in pixels outside a triangle pointing along +x, its tip at x = tip and its base at x = tip - sizefloat triangleDistance(float along, float side, float tip, float size, float halfWidth){@@ -81,6 +169,15 @@ fragment ring {scene.rgb = mix(scene.rgb, PARTY_COLOR, ringAmount(world, uParty[i]) * 0.85);}+ if (uMoveMarker.w > 0.0)+ {+ if (uMoveMarkerAxes.w < 1.0)+ scene.rgb = mix(scene.rgb, MARKER_COLOR, splashAmount(world, uMoveMarkerAxes.w) * 0.85);+ scene.rgb = mix(scene.rgb, MARKER_OUTLINE_COLOR,+ markerAmount(world, MARKER_WIDTH + MARKER_OUTLINE * 2.0) * uMoveMarkerAxes.z * 0.8);+ scene.rgb = mix(scene.rgb, MARKER_COLOR, markerAmount(world, MARKER_WIDTH) * uMoveMarkerAxes.z);+ }+if (uSelection.w > 0.0)scene.rgb = mix(scene.rgb, uSelectionColor.rgb, ringAmount(world, uSelection) * uSelectionColor.a);@@ -98,12 +195,36 @@ fragment ring {}}+ if (uAimLineStyle.x > 0.0)+ {+ vec2 from = uAimLine.xy * omw.resolution;+ vec2 to = uAimLine.zw * omw.resolution;+ float width = AIM_LINE_WIDTH * scale * 0.5;+ float dist;+ if (uAimLineStyle.y > 0.0)+ {+ // A small ring at the end, the line stopping at its edge+ float radius = AIM_END_RING * scale;+ vec2 along = to - from;+ float span = length(along);+ vec2 lineEnd = span > radius ? to - along / span * radius : from;+ dist = min(segmentDistance(pixel, from, lineEnd), abs(length(pixel - to) - radius));+ }+ else+ dist = segmentDistance(pixel, from, to);+ float outline = 1.0 - smoothstep(width + AIM_LINE_OUTLINE * scale - 0.5,+ width + AIM_LINE_OUTLINE * scale + 0.5, dist);+ float line = 1.0 - smoothstep(width - 0.5, width + 0.5, dist);+ scene.rgb = mix(scene.rgb, AIM_LINE_OUTLINE_COLOR, outline * uAimLineStyle.x * 0.5);+ scene.rgb = mix(scene.rgb, AIM_LINE_COLOR, line * uAimLineStyle.x);+ }+omw_FragColor = scene;}}technique {- description = "Selection ring under the creature under the cursor, party rings and arrows to players off the screen (Isowind top-down mode).";+ description = "Selection ring under the creature under the cursor, the red X where click to move is going, party rings, arrows to players off the screen and the bow's aim line (Isowind top-down mode).";version = "1.0";author = "Isowind";passes = ring;