Lua and Fable<br />Jonathan Shaw<br />
How does Fable use Lua?<br />AI<br />Quest scripts<br />Camera<br />Start-up settings<br />Miscellaneous scripts<br />Debu...
A (very) brief history<br />The original Fable used C++ as its “scripting” language, using macros to make it more “user fr...
Enter Lua<br />Like all good scripting languages Lua is easy to write, and can give you almost-instant feedback when chang...
AI<br />An AI entity in Fable II and III has a brain, defined in Fable’s general game editor.<br />A brain has a list of b...
Deciding what behaviour to run<br />Iterate through the behaviour groups, starting with the highest priority – see if they...
Same priority behaviours<br />If some behaviours or behaviour groups have the same priority, we want to iterate through th...
Quests<br />A quest will have one “master” coroutine, with a number of “child” coroutines – when the master coroutine is f...
Saving quests<br />We wanted players to be able to save the game wherever they were in the game and for it to be a “perfec...
The patch challenge<br />Using Pluto allows you to save coroutines and to resume them where they left off after loading th...
Nasty tricks<br />This forces you to come up with some “creative” solutions.<br />
Making it a little easier<br />In Fable III some of our scripters have started changing how they format their while loops:...
Bring on the Watch Dogs<br />Lua is extremely flexible and inspectable.<br />Add scripts to run in their own coroutines an...
Lua/C++ interface<br />We wanted it to be as easy as possible to register C++ functions in Lua.<br />The more functions ex...
Lua Plus Call Dispatcher<br />We use Joshua Jensen’s Lua Plus Call Dispatcher.<br />This lets you expose a function with a...
Hiding the Lua stack<br />For a C++ programmer used to dealing with objects, it can be useful to be able to treat Lua tabl...
A quick example<br />class CEntity; class Vec3;<br />Vec3 CEntity::GetPos() const;<br />luaL_newmetatable(L, “EntityMetaTa...
Using that in Lua<br />local hero = GetHero()<br />local trigger = GetEntity(“Trig1”)<br />-- The hero is now within 10 un...
Debugging Lua<br />Lua provides debugging hooks to allow the creation of a debugger application without needing to modify ...
Debugging with Lua<br />Our in-game debug console ran in the game’s Lua environment.<br />This meant everything scripts or...
Automation<br />Having remote access to the Lua environment means we can very easily write external scripts (ours are in P...
Profiling Lua<br />This is something we struggled with, partly due to our heavy reliance on coroutines.<br />Profilers tha...
Memory usage<br />When Fable II shipped Lua was using roughly 8 to 15Mb of memory.<br />We had a custom allocator designed...
Reducing memory footprint<br />Using Lua 5.1’s module system made demand-loading quest scripts very simple.<br />Changing ...
Taming the garbage collector<br />We turn the garbage collector off and manually run it once per game frame.<br />We playe...
Smoothing the spikes<br />One of our colleagues from Turn 10 gave us the solution.<br />To this:<br />double start_time = ...
Lua and Fable III<br />We were very happy with our use of Lua in Fable II, so haven’t really changed that much with Lua in...
Conclusion<br />Lua lets us develop systems quickly with fast iteration.<br />Performance is an issue and can be too much ...
References<br />Lua:<br />http://www.lua.org<br />Pluto for Lua:<br />http://luaforge.net/projects/pluto/<br />LuaPlus:<br...
Upcoming SlideShare
Loading in …5
×

Lua and fable jonathan shaw (lionhead)

5,141 views
5,021 views

Published on

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,141
On SlideShare
0
From Embeds
0
Number of Embeds
1,547
Actions
Shares
0
Downloads
56
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • Custom iterators allow you to track state between iterations so you construct a hidden table of all behaviours with the same priority, and then for each iteration return a random example from that table.But this is a benefit of Lua – it’s usually very easy to move functions from Lua to C++ if they turn out to be expensive
  • Talk about the graveyard demon door decapitation bug.Why did we let Lua crash the game? Optimisation!
  • Adding const overloads.
  • Define __sub in your metatable to define the behaviour of subtraction for your own typesThe calculation of distance done this way in Lua is actually pretty inefficient, due to the creation and subsequent deletion of three Vec3s on the heap.
  • When reloading scripts you need to do more than just reload the Lua file.Commercial debuggers at the time just weren’t up to standard, but the situation has now improved. VSLua, Kore
  • Performance is about 10 times slower on PC, even slower on in-order chips in consoles.
  • Consistency and predictability is key here.
  • Lua and fable jonathan shaw (lionhead)

    1. 1. Lua and Fable<br />Jonathan Shaw<br />
    2. 2. How does Fable use Lua?<br />AI<br />Quest scripts<br />Camera<br />Start-up settings<br />Miscellaneous scripts<br />Debugging<br />Patching<br />
    3. 3. A (very) brief history<br />The original Fable used C++ as its “scripting” language, using macros to make it more “user friendly”.<br />We used micro-threads (or fibres) to give each AI entity and each quest its own non-pre-emptive thread.<br />We liked micro-threads, but didn’t like C++ as a scripting language.<br />
    4. 4. Enter Lua<br />Like all good scripting languages Lua is easy to write, and can give you almost-instant feedback when changing scripts while your game is running.<br />Lua’s first class support for coroutines made Lua an ideal choice for Fable.<br />Fable II and III make extensive use of coroutines.<br />On busy levels we can have upwards of 100 coroutines running.<br />
    5. 5. AI<br />An AI entity in Fable II and III has a brain, defined in Fable’s general game editor.<br />A brain has a list of behaviour groups with priorities (some of which can be the same).<br />A behaviour group has a list of behaviours with priorities (some of which can be the same).<br />
    6. 6. Deciding what behaviour to run<br />Iterate through the behaviour groups, starting with the highest priority – see if they’re valid to run.<br />E.g. a “work in the factory” behaviour group isn’t valid to run if it’s night time.<br />For each valid behaviour group, iterate through the behaviours, starting with the highest priority, to see if they’re valid to run.<br />
    7. 7. Same priority behaviours<br />If some behaviours or behaviour groups have the same priority, we want to iterate through them in a random order.<br />Custom iterators in Lua were the perfect solution for this design.<br />Sadly, very nice to write, but a performance bottleneck, so we moved the logic to C++.<br />
    8. 8. Quests<br />A quest will have one “master” coroutine, with a number of “child” coroutines – when the master coroutine is finished we automatically kill the child coroutines.<br />We have the concept of “entity threads” – these are automatically tied to specific entities and die when the entity dies (or suspend when the entity is unloaded when the player changes level).<br />
    9. 9. Saving quests<br />We wanted players to be able to save the game wherever they were in the game and for it to be a “perfect save” – without quest scripters having to do anything to make it work.<br />Quite a challenge, until we learned about Pluto for Lua, by Ben Sunshine-Hill.<br />
    10. 10. The patch challenge<br />Using Pluto allows you to save coroutines and to resume them where they left off after loading the save game.<br />What if you want to patch a function that a coroutine was yielded in?<br />If you change the line numbering (of the resultant Lua byte code) before the final yield in the function, you can’t.<br />
    11. 11. Nasty tricks<br />This forces you to come up with some “creative” solutions.<br />
    12. 12. Making it a little easier<br />In Fable III some of our scripters have started changing how they format their while loops:<br />while true do<br /> -- Check for various<br /> -- conditions and act<br /> -- on them<br />coroutine.yield()<br />end<br />while true do<br />coroutine.yield()<br /> -- Check for various<br /> -- conditions and act<br /> -- on them<br />end<br />
    13. 13. Bring on the Watch Dogs<br />Lua is extremely flexible and inspectable.<br />Add scripts to run in their own coroutines and inspect the state of the known problem scripts – when they detect the problem, fix it and shut down.<br />
    14. 14. Lua/C++ interface<br />We wanted it to be as easy as possible to register C++ functions in Lua.<br />The more functions exposed to Lua, the more power you have when it comes to debugging and releasing DLC without requiring a Title Update.<br />There were features in Fable II’s second DLC that we had to drop because the one function the scripts needed hadn’t been exposed.<br />
    15. 15. Lua Plus Call Dispatcher<br />We use Joshua Jensen’s Lua Plus Call Dispatcher.<br />This lets you expose a function with any arbitrary signature to Lua (it doesn’t have to be a lua_Cfunction).<br />You can describe to the call dispatcher how to interpret any type you might want to expose to Lua.<br />
    16. 16. Hiding the Lua stack<br />For a C++ programmer used to dealing with objects, it can be useful to be able to treat Lua tables and functions as C++ objects.<br />Using inspiration from LuaPlus we wrote CLuaTable and CLuaFunction classes.<br />These use the Lua registry to keep handles to the table and functions alive even if no handles to them in Lua remain.<br />
    17. 17. A quick example<br />class CEntity; class Vec3;<br />Vec3 CEntity::GetPos() const;<br />luaL_newmetatable(L, “EntityMetaTableName”);<br />lua_pushvalue(L, -1); // Pushes the metatable<br />lua_setfield(L, -2, "__index");// mt.__index = mt<br />CLuaTableentity_mt (L);// This pops the metatable off the stack<br />entity_mt.RegisterDirectMemberFunction<CEntity>(<br />“GetPos", &CEntity::GetPos);<br />
    18. 18. Using that in Lua<br />local hero = GetHero()<br />local trigger = GetEntity(“Trig1”)<br />-- The hero is now within 10 units of the trigger<br />while (hero:GetPos()-trigger:GetPos()):GetLength() > 10 do<br />coroutine.yield()<br />end<br />while IsDistanceBetweenEntitiesOver(hero, trigger, 10) do<br />coroutine.yield()<br />end<br />
    19. 19. Debugging Lua<br />Lua provides debugging hooks to allow the creation of a debugger application without needing to modify any of the Lua source code.<br />Our Lua Debugger supported breakpoints, step into, step over, per-coroutine breakpoints, a watch window and the ability to break into Lua from a C++ assert.<br />Saving a file in the debugger would automatically reload it in the game.<br />
    20. 20. Debugging with Lua<br />Our in-game debug console ran in the game’s Lua environment.<br />This meant everything scripts or AI could do, you could do in the console (including inspecting the current state of the AI and quests).<br />On Fable III we have remote access to this same console (including niceties like auto-complete).<br />
    21. 21. Automation<br />Having remote access to the Lua environment means we can very easily write external scripts (ours are in Python) to drive the game however we like.<br />We change start-up settings (so Lua is one of the first systems in the game we initialise) and test that every level in the game loads successfully, and get performance metrics from the game using this system.<br />
    22. 22. Profiling Lua<br />This is something we struggled with, partly due to our heavy reliance on coroutines.<br />Profilers that hooked into function entries and exits wouldn’t stop the timer during yields, giving very skewed results.<br />For Fable II, we didn’t have anything more sophisticated than manually timing suspected expensive functions and printing times to the debug output channel.<br />
    23. 23. Memory usage<br />When Fable II shipped Lua was using roughly 8 to 15Mb of memory.<br />We had a custom allocator designed for many small, fragmenting allocations.<br />Tracking memory “leaks” in Lua was extremely difficult.<br />We found that pre-compiling our Lua scripts massively reduced fragmentation (in addition to the small improvement in loading time).<br />
    24. 24. Reducing memory footprint<br />Using Lua 5.1’s module system made demand-loading quest scripts very simple.<br />Changing lua_Number to float from double saved us 1 or 2Mb, because those extra 4 bytes exist in every Lua type, whether table, Boolean, function, etc.<br />The problem with floats comes when you want to pass 32 bit hashes or UIDs to and from Lua (because integers above 8 million lose precision when converted to floats).<br /> Light user data was the solution.<br />
    25. 25. Taming the garbage collector<br />We turn the garbage collector off and manually run it once per game frame.<br />We played around with the step size to try to balance the time the collector takes and the collector having enough time to clean up the general memory churn in any given frame.<br />Even when we found a number we were reasonably happy with, the collector would sit at about 3ms, often spiking over 6ms.<br />
    26. 26. Smoothing the spikes<br />One of our colleagues from Turn 10 gave us the solution.<br />To this:<br />double start_time = LHTiming::GetTime();<br />double end_time = start_time + g_SecondsForGarbageCollection; // 2ms<br />do<br />{<br />lua_gc(L, LUA_GCSTEP, 0);<br />}<br />while(LHTiming::GetTime() < end_time);<br /><ul><li>From this:</li></ul>lua_gc(L, LUA_GCSTEP, 120);<br />
    27. 27. Lua and Fable III<br />We were very happy with our use of Lua in Fable II, so haven’t really changed that much with Lua in Fable III.<br />Our quest scripts now support mid-quest “skip points” so that when debugging a quest you can now skip (forwards or backwards) to a decent number of points in the middle of quests.<br />We’re using Kore in Fable III, which gives us improved performance and improved tools, including a profiler.<br />
    28. 28. Conclusion<br />Lua lets us develop systems quickly with fast iteration.<br />Performance is an issue and can be too much of a “black box”.<br />Having a rich and full interface between your game and scripting language will serve you well when it comes to extending the game.<br />
    29. 29. References<br />Lua:<br />http://www.lua.org<br />Pluto for Lua:<br />http://luaforge.net/projects/pluto/<br />LuaPlus:<br />http://luaplus.org<br />Kore<br />http://www.kore.net<br />

    ×