21 May 2009

Maya Plugin

[Edit: I added some clarification to the “cleanup” point  below]

I have started to write a new Maya plugin for Nebula3, which eventually may replace all (or parts of) our current plugin. The actual Maya plugin is only one small part of our asset pipeline, so this is not about rewriting the entire asset pipeline, just replacing one small gear in it. Otherwise it would be a truly Herculean task. In the beginning this will just be a private endeavour, free from time- or budget-limitations, so that no design compromises have to be made. This approach worked quite well for Nebula3 so it makes sense to use it more often in the future.

Our current Maya plugin is stable and fast, but at least the C++ part of it is beginning to show its age, it’s becoming harder to maintain, and since it’s based on Nebula2 code it is a lot harder to do low-level things like file io compared to similar Nebula3 code.

The new plugin will realize ideas I’ve been carrying around in the back of my head for quite some time, and which would be hard to implement into the existing plugin without a complete rewrite. The most important one is:

Separation into a platform-agnostic front-end and several specialized back-ends:
  • The actual Maya plugin will export into intermediate file formats which are completely platform-independent (and probably even somewhat engine-independent). Thus the plugin itself becomes more of a generic 3D engine exporter tool which doesn’t have to change every time a new target platform is supported or an engine feature is added or rewritten.
  • The back-end tools (or libs) convert the intermediate files into the files actually loaded by Nebula3. Those files can (and should) be highly platform-specific.

I’m expecting that the larger chunk of code goes into the platform-agnostic plugin, and that the back-ends are relatively small and straight-forward. The main advantage of this separation is better maintainability. The core plugin can remain relatively stable and clean, while the back-ends can have a higher frequency of change, and the “throw-away-and-rewrite” barrier is a lot lower since only the relatively small back-end-code has to be replaced without affecting the core plugin and the other platform-back-ends (too much). Also, the platform-mini-teams have more freedom to implement platform-specific optimizations into their engine-ports, since they have complete control over their exporter-backend.

The main disadvantage is that the export times will probably be a bit higher then now. A LOT of effort has gone into optimizing the performance of our toolkit plugin (exporting a scene with hundreds of thousands of polygon should only take up to a few seconds), and writing an additional set of output files may effect performance quite drastically. I’m planning to use XML only for the intermediate object hierarchy structure (which depends on the material complexity of the scene, but shouldn’t be more then a few dozen to a few hundred lines for a typical object), and to use binary file formats for “large stuff” like mesh and animation data. But if the XML files are hindering io performance too much, I will clearly go to a performance-optimized binary format, even if human-readability would be a major plus there (in the end, one set of the back-end tools could convert to human-readable ASCII file formats).

If you’re wondering why performance is so critical during export: consider that a project has about ten-thousand 3d models to be exported (which isn’t unrealistic for a complex RPG project like Drakensang for example). If the export time can be reduced by only one second per object, the time for a complete rebuild will be reduced by almost 3 hours! Actually, most 3d models batch-export in much less then 1 second in our build-pipeline, it’s the texture-conversion to DDS which eats the most build-time…

There are a lot of other things a Maya exporter tool should do right to be considered well-mannered:

  • It should support batch-exporting and automation (command-line batch-exporters, means of controlling export parameters on thousand of assets, standardized project directory structures, etc…).
  • It should be designed for a multi-project environment (a modeling artist or level designer must be able to quickly switch from one project to another).
  • It should of course offer a fast and exact preview for immediate quality control (the artist should be able to get an in-engine view of his work immediately)
  • It should not force artists to use archaic file formats. For instance, all texture conversion tools for the various console platforms I have encountered so far only accept crap like TGA or BMP as input, but NOT the industry standard PSD format! Quite baffling if one thinks about it. I don’t know how other companies deal with this, but I think it’s quite unacceptable to keep an extra TGA version for every one of tens-of-thousands textures around, just so that the batch exporter tools will work (for the console platforms we wrote our own wrappers, which first convert a PSD file to a temp TGA file and then invoke the conversion tools coming with the SDKs, but this is REALLY bad for the batch-export performance of course).
  • It should be fault-tolerant: Maya is an incredibly complex piece of technology, and plugins usually have no other chance then only supporting a specific subset of its features. The plugin should not crash or stop working when it encounters something slightly wrong or unknown in the Maya scene, instead it should provide the artist with clear warnings and readable error messages.
  • It should not require too many restrictions in the Maya scene: for instance, a very early version of our exporter tools required the artist to manually triangulate the scene, which is unacceptable of course.
  • It should cleanup the Maya scene during export: It’s relatively easy in Maya to create zero-area faces, or duplicate faces, or faces with a zero UV-area, etc... The exporter should remove those artefacts, and in those cases where an automatic handling is not possible, provide a detailed error log to the artist so that he has enough information to remove those problems manually. [EDIT: this was badly worded… of course the plugin should not modify the actual Maya scene, but instead remove artefacts from the data which has already been extracted from the Maya scene… it’s a bad idea to modify the Maya scene itself during export!]
  • It should optimize the Maya scene during export: For instance, the last time I looked at the XNA Maya plugin it exported a single material group for every Maya shape node, resulting in hundreds of draw calls for our simple Tiger tank example object. This is almost as bad as requiring the artist to work with a triangulated scene. Instead the plugin should try its best to optimize the scene for efficient rendering during export (like grouping polygons by material, sorting vertices for efficient vertex-cache usage, removing redundant vertices, and so on).

Of course this list could go on for a few more dozen points, there’s almost 10 years of work in our asset pipeline, and there’s probably more C++ and MEL code in it then in Nebula3 (which isn’t necessarily a good thing ;)

15 Apr 2009

N3 SDK Apr 2009 download

Here's the new SDK (see previous post), I hope releases will be a little more frequent in the future. As always, source code for the Xbox360 or Wii versions is not included for obvious legal reasons.

http://www.radonlabs.de/internal/N3SDK_Apr2009.exe

Have fun!

14 Apr 2009

New N3 SDK (Apr 2009)

The new SDK release should be ready by tomorrow (unless there's some last-minute fuckup). For now here's a rough What's New list since the last SDK from September 2008:

Tools:
  • new command line tool: archiver3 - multiplatform wrapper for generating file archives
  • new command line tool: n2converter3 - convert .n2 files to .n3 files (Nebula graphics objects)
  • new command line tool: suiconverter3 - batch converter for SUI resources (simple user interface), currently only useful for the Wii port
  • new command line tool: synctool3 - sync local project directory from build server (only useful with our inhouse asset pipeline)
  • new command line tool: countlines3 - count N3 source code lines and generate Excel-compatible csv-file (comma separated values)
Foundation Layer:
  • brought Wii port uptodate (not part of the public SDK of course)
  • Util::CmdLineArgs renamed to Util::CommandLineArgs
  • Scripting subsystem moved into an addon
  • Remote subsystem moved into an addon
  • new Macros __ConstructInterfaceSingleton / __DestructInterfaceSingleton
  • new standard define __MAYA__ if compiled as part of a Maya plugin
  • new concept: ExitHandlers (see Core::ExitHandler)
  • new low level debug feedback method Core::SysFunc::MessageBox()
  • new concept "root directory" (see CoreServer::SetRootDirectory)
  • various changes to enable using N3 code in N2/Mangalore apps (N2 now sits on top of a very slim N3 Foundation layer)
  • SizeT and IndexT now signed (had to be done for N2/Mangalore compatibility unfortunately)
  • IO::Console is now an InterfaceSingleton
  • various debug HTML page handlers can now sort table content by columns
  • Debug::DebugServer is now an InterfaceSingleton
  • added a minimal Debug::HelloWorldRequestHandler as example for a simple HttpRequestHandler
  • new comfort method Http::HtmlPageWriter::TableRow2(), saves code when creating a 2-column HTML table
  • added Http::HttpClient class, allows send requests to HTTP servers
  • Http::HttpInterface is now an InterfaceSingleton and derived from Interface::InterfaceBase
  • new class Http::HttpRequestWriter
  • new class Http::HttpResponseReader
  • added a "single thread mode" to HttpServer
  • added new classes InterfaceBase and InterfaceHandlerBase
  • moved IOInterface-stuff under IO
  • new class Debug::ConsolePageHandler, displays console output in web server
  • generalized Zip filesystem stuff into general archive filesystem, with ZIP support as one specialization (on Wii, ARC files are used instead)
  • ZipFileSystem is now an InterfaceSingleton (no more per-thread wasted memory for archive table-of-contents)
  • added an "AsString()" method to IO::FileTime
  • new methods in Win360FSWrapper: SetFileWriteTime(), GetAppDataDirectory(), GetProgramsDirectory()
  • moved IO::ZipFileStream class to io/zipfs
  • moved path assign methods from IoServer into new InterfaceSingleton: IO::AssignRegistry
  • new standard assigns under Windows: "appdata" and "programs", mainly useful for tools
  • bugfix in IO::ExcelXmlReader for tables with empty cells
  • new class IO::HistoryConsoleHandler, captures console output into a ring buffer (used by Debug::ConsolePageHandler)
  • moved URI scheme methods from IoServer into IO::SchemeRegistry InterfaceSingleton
  • removed critical section from Stream::Open / Stream::Close
  • new method: IO::XmlWriter::WriteComment()
  • new methods specialized float4-loading methods: Math::float4::load_float3(), Math::float4::load_ubyte4n_signed()
  • vector comparison methods in Math::float4 more intuitive and flexible
  • Math::matrix44() default constructor now sets object to the identity matrix (default constructor still empty in Math::float4!)
  • new constructor from float4 in Math::quaternion
  • moved lots of math functions from scalar.h to platform-specific d3dx9_scalar.h to enable platform-specific optimizations
  • Memory::Heap constructor now accepts initial and maximum heap size
  • memory leap detection for Memory::Heap (doesn't quite work as expected yet)
  • removed global heaps: SmallBlockHeap, LargeBlockHeap, StringHeap
  • added global heaps: PhysicsHeap, AppHeap, StringObjectHeap, StringDataHeap
  • new experimental Win360MemoryPoolClass
  • Messaging::AsyncPort: can now add message handlers to already opened ports
  • added "deferred handled" flag to Messaging::Message (used in the rendering thread to keep CreateEntity messages around until their resources are loaded)
  • wrapped socket and TCP/IP classes to enable "TCP/IP-over-HIO2-Tunneling" on the Wii
  • System::Win32Registry(): split Read() method into ReadString() and ReadInt()
  • System::ByteOrder::Convert<TYPE>() methods now return a value, added new methods System::ByteOrder::ConvertInPlace<TYPE>()
  • new methods Threading::Interlocked::Exchange() and CompareExchange()
  • Win360Thread::IsRunning() now uses the Win32 function GetExitCodeThread() to detect whether the thread is running
  • new method Threading::Thread::YieldThread() (gives up time-slice)
  • new class Threading::SafeFlag
  • new concept: Timing::MasterTime and Timing::SlaveTime, main thread has a MasterTime object, and distributes "main time" to slave threads (i.e. the render thread)
  • Util::Array now has a MinGrowSize and MaxGrowSize to prevent excessive memory waste for huge arrays
  • new experimental class Util::Delegate (doesn't work in Codewarrior unfortunately)
  • new method Util::FixedArray::AsArray()
  • new methods Util::Dictionary::KeysAs<TYPE>(), and Util::Dictionary::ValuesAs<TYPE>()
  • new class Util::PriorityArray (which actually isn't needed anymore I think)
  • new class Util::RandomNumberTable
  • new class Util::Round
  • made many non-essential Util::String methods non-inline
Render Layer
  • new Character subsystem (modular character rendering, fresh rewrite of N2's Character3 system)
  • new CoreFX subsystem (ported from Mangalore's VFX subsystem (visual effects)) -> NOTE: will be moved into addon
  • new CoreUI and UI subsystems (simple user interface system) -> NOTE: will be moved into addon
  • new Video subsystem (video playback, currently Xbox360 only) -> NOTE: will be moved into addon
  • new Particles subsystem (rewritten from scratch) -> NOTE: will be moved into addon
  • new PostEffect subsystem (ported from Mangalore) -> NOTE: will be moved into addon
  • new Vibration subsystem (game pad vibration support) -> NOTE: will be moved into addon
  • new Vegetation subsystem (Drakensang's grass renderer, currently broken under N3) -> NOTE: will be moved into addon
  • new concept: RenderModules, clean framework to add functionality to the render thread
  • new concept: AnimEvents, animations can emit events at certain sample times (i.e. for playing foot-step sounds at the right time)
  • new concept: character attachments (swords, etc...)
  • lots of bugfixes and improvements to Animation system
  • new concept: AnimDrivenMotion, synchronize character movement with its current animation
  • new concept: batched messages, drastically reduce communication overhead between threads by client-side batching of messages
  • new methods: Audio::AudioEmitter::Pause() and Resume()
  • new methods: AudioDevice::SetGlobalVariable() / GetGlobalVariable()
  • added/fixed Xbox360 support to XACT audio classes
  • new class: MultipleRenderTarget, wraps MRT rendering
  • new class: MouseRenderDevice (currently only implemented on Wii)
  • added support for GPU-instanced-rendering
  • RenderTarget: added support to resolve depth buffer into texture (Xbox360 only)
  • RenderTarget: added support to create a resolve-texture which can be efficiently read by the CPU
  • added "late-binding" to ShaderVariableInstance
  • D3D9StreamTextureLoader and D3D9Texture moved from win360 to d3d9, since specialized Xbox360 versions exist now
  • Debug::MeshPageHandler can now display a dump of the vertex data in the web browser
  • Debug::TexturePageHandler now displays the current resource state of textures (Initial, Pending, Loaded, etc...)
  • new class CoreGraphics::MemoryMeshLoader
  • renamed CoreGraphics::Shape to CoreGraphics::RenderShape (because of CodeWarrior problems with identical filenames in different directories)
  • added Multiple Render Target support to Frame::FramePass and Frame::FramePostEffect
  • Graphics::Display::GetDisplayMode() now returns display mode actually set by the CoreGraphics::DisplayDevice (may differ from the requested display mode)
  • Graphics::GlobalLightEntity: all light parameter changes are now transferred to the render-thread-side post-creation
  • Graphics::GraphicsEntity: internal entity handle now only becomes valid after resources have been loaded on the render-thread-side
  • Graphics::GraphicsInterface now uses batch messaging to communicate with render-thread (only 1 message sent per frame)
  • Graphics::Handle is now a smart pointer (fixes problems where render-thread graphics entities were disposed too early)
  • Graphics::ModelEntity: support for AnimDrivenMotion
  • new Input::GamePad methods: ButtonAsString(), AxisAsString(), GetStateAsInputEvents()
  • InternalGraphicsEntities are now registered with the InternalGraphicsServer
  • lots of changes in InternalGraphicsServer and InternalModelEntity which require a proper cleanup doh
  • added support for 2-sided lighting to global lights
  • new classes: Models::AnimatorNode and Models::AnimatorNodeInstance (legacy Nebula2 stuff)
  • new classes: Models::CharacterNode and Models::CharacterNodeInstance, integrate character rendering with model nodes
  • loading of ModelNodes completely rewritten (new .n3 file format, plus n2converter3 tool to convert .n2 files to .n3)
  • new Model::OnResourcesLoaded() method, if Model subclasses need to do initialization work after resources have finished loading
  • new methods to lookup ModelNodeInstances on ModelInstances
  • new class Models::StreamModelLoader
  • lots of other minor changes in namespace Models
  • new class: RenderUtil::MouseRayUtil, convert 2D mouse position into world-space 3D-ray
  • new method: ResourceManager::CheckPendingResources(), returns true when there are currently no pending resources waiting to be loaded
  • SharedResourceServer: several methods now accept a ResourceLoader object when creating shared resources

I also did some interesting line counting statistics recently for the Foundation and Render layers (hopefully the images won't be scaled down too much):

foundation_layer 

render_layer 

"General" is the platform-agnostic code, which is the same for all platforms, "Win360" is the code which is identical between Win32 and Xbox360.

4 Apr 2009

Still Alive

Just a quick update, since I haven’t posted for a while:

  • I’ve pretty much gone into hermit mode for the whole of March with 10 hour-days and six-day-weeks at the Labs because of an interesting new project. Pretty much everything I did falls under NDA unfortunately, so there wasn’t anything I could write about anyway… so that’s my half-assed apology for not posting anything. Although I must admit that it was quite relaxing to simply cut-off all non-essential communication and social contacts and just concentrate on the task at hand, almost feels like I just came back from a long vacation, even though I’m a bit exhausted physically ;)
  • The Larrabee instruction set looks damn impressive, but I’ll withhold my enthusiasm until it’s actually available and doesn’t turn out to be just another fucking “onboard graphics chip”.
  • Same for OnLive. Don’t have tech-journalists any fucking common sense to hype this shit up instead of looking behind the curtain? Even Xbox Live (the current Gold Standard) takes a nose-dive from time to time when a popular multiplayer game is released, and that’s just doing match-making over its servers with (probably) a few Kbytes of traffic per session. Maybe OnLive is capable to demonstrate a system which scales up to a million simultaneous players spread across the globe, running a taxing 3D game with “acceptable” lag and image quality. If that happens I would be truly impressed. I predict that OnLive will collect a considerable amount of money from eager investors (who seem to believe that little nuisances like the Laws Of Nature can be dealt with by throwing the right amount of money at them), waste that money over the next few years, while tech demonstrations become less and less impressive (even though they’ll be fabricated), and finally, if said investors are lucky, maybe one or two worthless patents and “yet another” video codec come out of the whole venture. It’s Phantom all over again.
  • Drakensang won the new “German Computer Game Award” for “Best German Game” and “Best Youth Game”. Please excuse this uncommon display of enthusiasm, but let me just say: Yay!

I love Resident Evil 5. Capcom are my official kings of next-gen. Funny thing is: I almost skipped the game because of the demo. I haven’t played any previous RE’s (at that time I hadn’t converted to the dark side of console gaming yet), so I was completely put off by the strange “tank controls”. Also, the demo took place in “generic Middle-Eastern/North-African town”) which I already know well enough from COD4, MGS4 and FarCry2. No-but-thank-you.

But the actual game… I’d almost go as far to say that this is the best game of this console generation. The only little imperfection are those controls, but it took me only an hour or so to not even think about them anymore and use them just as automatically as the GeOW, or COD, or Rainbow Six controls. They are different from the “standard FPS controls”, but that’s the point, they are just different then the others, but with a little practice just as easy and intuitive in their own way.

The pacing of the game, the location design (there are some really breathtaking locations after “Generic Town”), the sound track, the story-telling, the characters, the cutscenes, the BOSS-FIGHTS (OMG the bosses are epic) – the way how coop-gameplay is implemented – everything is absolutely perfect. And RE5 is a console game through and through, not some FPS with more or less obvious PC heritage like COD or Gears. Little things like the “persistent inventory”, the massive amount of unlockables, the NewGame+ and Mercenary mode - every little bit of RE5 feels, tastes and smells like a 100% pure next-gen console game. Alright that’s it, I need to go play some RE5 now. Bye.

23 Feb 2009

Bullshit Paradise

Dammit, what’s that EA-login bullshit in Burnout Paradise? Didn’t they get the memo from Konami? Turns out my usual email address for shit like this at fuck@you.com was already taken by somebody else, oh well… Crap like this should be prohibited by Microsoft’s certification process, it’s completely working against the whole idea of Xbox Live.

21 Feb 2009

N3’s Game Database Structure

Here’s some info on the game database structure used by N3 and N2’s Mangalore, which might be helpful for level editor tools.

“Game data” basically means “everything except graphics, audio or movie stuff”.

All Nebula game-data lives in 2 SQLite database files:

  • home:export/db/static.db4: This contains all “static” data which doesn’t change over the course of a game session.
  • home:export/db/game.db4: This contains all the data which may change during a game session.

Those files can be inspected and modified with the SQLiteSpy tool, but since some of the contained data are blobs it may be a good idea to access them with custom tools (N3’s db addon offers wrapper classes for this, but of course it’s also possible to use sqlite directly to access the database).

Both database files are normally populated by various exporter tools in our inhouse-asset-pipeline.

The game.db4 file is important for N3’s standardized NewGame/Continue/Save/Load feature:

  • on New Game, game.db4 will be copied to the user: directory of the application, changes during game play will be committed back to this copy (usually when a level is left)
  • on Continue Game, N3 will simply open the existing game.db4 file under “user:”
  • on Save Game, a copy of the game.db4 file under “user:” will be performed into the save-game directory
  • on Load Game, the game.db4 in “user:” will be overwritten with a copy from the save-game directory

The main chunk of data in both database files are game entity related. A game entity is completely described by a collection of key/value pairs called attributes, which live in a single row of a database table.

Application layer subsystems may store additional data in the database by managing their own tables in both databases. Usually, save-game relevant data lives in the game.db4 database, while read-only data lives in the static.db4 database file. Those custom-tables are usually read/written by derived Manager::OnLoad() and Manager::OnSave() methods.

The static.db4 database contains at least the following tables:

  • _Attributes: This table contains a description of all attribute types used in other database tables. This lets an application load a database in a meaningful way even if the attributes haven’t been defined in its C++ code. The columns of _Attribute are:
    • AttrName (string, primary, unique, indexed): the attributes name, doh
    • AttrType (string): the type of the attribute, this is how the different types are stored in the database:
      • int: stored as SQL type INTEGER
      • bool: stored as SQL type INTEGER
      • float: stored as SQL type REAL
      • string: stored as SQL type TEXT
      • vector3: a float[3] stored as SQL type BLOB
      • vector4: a float[4] stored as SQL type BLOB (a raw Math::float4 written to the database)
      • matrix44: a float[16] stored as SQL type BLOB (a raw Math::matrix44 written to the database)
      • guid: a ubyte[16] stored as SQL type BLOB (result of Util::Guid::AsBinary())
      • blob: can be used to efficiently store “anything else” in the database, hardly used though, Drakensang uses this to store the fog-of-war data for instance
    • AttrReadWrite (bool), AttrDynamic (bool): these two columns are currently not used in any meaningful way
  • _Categories: Contains a description of every entity category which shows up in the database. This is basically the lookup-table for the CategoryManager. The _Categories table has the following columns:
    • CategoryName (string, primary, unique, indexed): The name of the category (e.g. Camera, NPC, Actor, Monster, etc…). Some category names are hard-coded and standardized across games:
      • Light: describes level light sources
      • _Environment: describes “environment objects”, these are simple graphics objects which don’t have game-play functionality
      • Levels: a meta-table which contains one row for every level in the game
    • IsVirtualCategory (bool, indexed): a virtual category only has a ‘template table’ but no ‘instance table’, virtual categories can be used to provide read-only data (lookup tables, etc) to the game application without having to write a custom exporter tool
    • IsSpecialCategory (bool, indexed): only the above mentioned hard-coded categories are marked as “special”
    • CategoryTemplateTable (string): The name of the database table with entity templates, a template table contains “blueprints” for entities with their initial attribute values. The method FactoryManager::CreateEntityByTemplate() is used to instantiate a new entity from such a template. Template tables live in the static.db4 database.
    • CategoryInstanceTable (string): The name of the instance table (only if this is not a virtual category). Instance tables live in the game.db4 database file and contain one row per actual game entity.
  • Template tables: Template tables contain blueprint for entities which are created through the FactoryManager::CreateEntityByTemplate() method. A row in the template table contains the starting attribute values for a new entity of that type. A template table must contain at least the Id column, which must be (string, primary, unique, indexed).

The game.db4 database has the following tables:

  • _Attributes: this has the exact same structure as the _Attributes table in static.db4
  • _Globals: this is a simple global variable storage managed by the GlobalAttrsManager.
  • Instance tables: the instance tables as listed in the _Categories table of static.db4. Every game entity in the entire game has a row in one of the instance tables. The general structure of an instance table is the same as the associated template table, but with the following additional columns:
    • Guid (guid, primary, unique, indexed): a unique identifier for the entity
    • _ID (string): a human-readable unique identifier (only within the level)
    • _Level (string, indexed): the level where this entity currently resides (may change during game)
    • _Layers (string): The layers this entity is a member of. Entity layers can be used to “overlay” a specific group of entities at level load time. This can be used for day/night, intact/destroyed versions of a level without duplicating the entire level. An empty _Layers attribute means that this entity is always loaded into a level.
    • Transform (matrix44): the current world space transform of the entity

The _Instance_Levels instance table is special in that it doesn’t have the above mentioned hardcoded attributes. Instead it contains one row per level in the game with the following attributes:

  • Id (string, primary, unique, indexed): a unique-id string of the level
  • Name (string, indexed): the human-readable name of the level
  • StartLevel (bool): true if this is the start level which should be loaded on New Game, false for all other levels
  • _Layers (string): the currently active entity layers
  • Center (vector3): the midpoint of the level in world space
  • Extents (vector3): the extents vector of the level (Center and Extents are used to describe the bounding box of the level)
  • NavMesh, NavMeshTransform, NoGoArea, NoGoAreaTransform: used by the navigation subsystem (not currently implemented in Nebula3)

Most entity-related database accesses are wrapped by the CategoryManager, which currently caches most of the data in memory (all template tables, and all entity instance data of the current level). This may change in the future when we generally run SQLite through the in-memory mode. If the in-memory database accesses are fast enough we might drop the caching (which isn’t as good as I’d like because of the huge amount of memory allocations going on during reading from the database).

7 Feb 2009

EVA

I think I have a pretty good plan now for Nebula3’s asynchronous job subsystem, and (most importantly) I have a nifty name for it: EVA (Eingabe-Verarbeitung-Ausgabe, engl.: Input-Processing-Output). A job object is basically a piece of input data plus some code which asynchronously processes that data, resulting in the output data. Hence EVA. The main motivation is of course to make use of the PS3 stream processing units (I know, I know, the S in SPU actually stands for synergistic, but I think that’s wishful thinking at least in the context of a game engine, processing of individual data streams makes more sense then chaining the SPUs together IMHO, but I digress…).

I really don’t want an entire, important subsystem in N3 which only makes sense on the PS3 though. EVA jobs should also work on the CPU or GPU if desired.

The 2 main inspirations are Insomniacs “SPU Shaders” (treat a SPU job like a GPU shader), and DX11’s Compute Shaders (use GPU shaders for non-rendering purposes).

The main problem is to provide a simple, generic interface of how to get data to and from “external computation units” with as little synchronization as possible. GL and D3D had to solve that problem years ago in order to let the GPU work in parallel to the CPU. Vertex buffers and textures provide the input data, which is processed by shader code and the output is written to render targets. It’s a simple and intuitive pattern of how to communicate with an asynchronous processing unit, and best of all, every programmers knows (or should know) those concepts in and out.

EVA will simply wrap existing ideas under a common subsystem, with the emphasis on data-compatibility, not code compatibility. It should be relatively easy to “port” a job between the CPU, GPU or SPU. The main problem (how to structure the input and output data) should only be solved once (with the general rule-of-thumb that related data should be placed near to each other), while the processing code needs to re-written for each processing unit type (FX/HLSL for GPU jobs, simple, self-contained C or C++ code for CPU and SPU jobs).

Thus an EVA job object would have the following properties:

  • one or more input buffers
  • one output buffer
  • a small set of input parameters
  • the actual processing code

Buffers usually contain a stream of uniform data elements (similar to vertices or pixels), the input parameters can be used to cheaply tweak the behavior of an existing job object.

For a CPUJob, the input and output buffers would be simple system memory buffers, and the processing code would be standard C/C++ code which is running in a thread of a thread-pool. The processing code should not call any “non-trivial” external functions as to remain somewhat portable to the other job types.

A “DX9PixelShaderJob” would use textures as input buffers, and a render target as output buffer, the input parameters and the processing code would be described by an FX shader file.

SPU jobs would need a way to manually pull data from the input buffers to local memory, and to write blocks of processed data back to the output buffer, possibly using some sort of double buffering.

A way to cheaply convert/map buffers between the different job types would be desirable (for instance to use an output buffers directly as a DX texture, etc…). DX10 provides a pattern for this with its “resource views”.

A great plan is the simple part of course, the devil is in the implementation. And once EVA is ready for action the true challenge will be to “de-fragment” the game-loop in order to identify and isolate jobs which can be handled asynchronously.