Reference.dox 216 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585
  1. namespace Urho3D
  2. {
  3. /**
  4. \page Containers Container types
  5. Urho3D implements its own string type and template containers instead of using STL. The rationale for this consists of the following:
  6. - Increased performance in some cases, for example when using the PODVector class.
  7. - Guaranteed binary size of strings and containers, to allow eg. embedding inside the Variant object.
  8. - Reduced compile time.
  9. - Straightforward naming and implementation that aids in debugging and profiling.
  10. - Convenient member functions can be added, for example String::Split() or Vector::Compact().
  11. - Consistency with the rest of the classes, see \ref CodingConventions "Coding conventions".
  12. The classes in question are String, Vector, PODVector, List, HashSet and HashMap. PODVector is only to be used when the elements of the vector need no construction or destruction and can be moved with a block memory copy.
  13. The list, set and map classes use a fixed-size allocator internally. This can also be used by the application, either by using the procedural functions AllocatorInitialize(), AllocatorUninitialize(), AllocatorReserve() and AllocatorFree(), or through the template class Allocator.
  14. In script, the String class is exposed as it is. The template containers can not be directly exposed to script, but instead a template Array type exists, which behaves like a Vector, but does not expose iterators. In addition the VariantMap is available, which is a HashMap<StringHash, Variant>.
  15. \page ObjectTypes %Object types and factories
  16. Classes that derive from Object contain type-identification, they can be created through object factories, and they can send and receive \ref Events "events". Examples of these are all Component, Resource and UIElement subclasses. To be able to be constructed by a factory, they need to have a constructor that takes a Context pointer as the only parameter.
  17. %Object factory registration and object creation through factories are directly accessible only in C++, not in script.
  18. The definition of an Object subclass must contain the OBJECT(className) macro. Type identification is available both as text (GetTypeName() or GetTypeNameStatic()) and as a 32-bit hash of the type name (GetType() or GetTypeStatic()).
  19. To register an object factory for a specific type, call the \ref Context::RegisterFactory "RegisterFactory()" template function on Context. You can get its pointer from any Object either via the \ref Object::context_ "context_" member variable, or by calling \ref Object::GetContext "GetContext()". An example:
  20. \code
  21. context_->RegisterFactory<MyClass>();
  22. \endcode
  23. To create an object using a factory, call Context's \ref Context::CreateObject "CreateObject()" function. This takes the 32-bit hash of the type name as a parameter. The created object (or null if there was no matching factory registered) will be returned inside a SharedPtr<Object>. For example:
  24. \code
  25. SharedPtr<Object> newComponent = context_->CreateObject(type));
  26. \endcode
  27. \page Subsystems Subsystems
  28. Any Object can be registered to the Context as a subsystem, by using the function \ref Context::RegisterSubsystem "RegisterSubsystem()". They can then be accessed by any other Object inside the same context by calling \ref Object::GetSubsystem "GetSubsystem()". Only one instance of each object type can exist as a subsystem.
  29. After Engine initialization, the following subsystems will always exist:
  30. - Time: manages frame updates, frame number and elapsed time counting, and controls the frequency of the operating system low-resolution timer.
  31. - WorkQueue: executes background tasks in worker threads.
  32. - FileSystem: provides directory operations.
  33. - Log: provides logging services.
  34. - ResourceCache: loads resources and keeps them cached for later access.
  35. - Network: provides UDP networking and scene replication.
  36. - Input: handles keyboard and mouse input. Will be inactive in headless mode.
  37. - UI: the graphical user interface. Will be inactive in headless mode.
  38. - Audio: provides sound output. Will be inactive if sound disabled.
  39. - Engine: creates the other subsystems and controls the main loop iteration and framerate limiting.
  40. The following subsystems are optional, so GetSubsystem() may return null if they have not been created:
  41. - Profiler: Provides hierarchical function execution time measurement using the operating system performance counter. Exists if profiling has been compiled in (configurable from the root CMakeLists.txt)
  42. - Graphics: Manages the application window, the rendering context and resources. Exists if not in headless mode.
  43. - Renderer: Renders scenes in 3D and manages rendering quality settings. Exists if not in headless mode.
  44. - Script: Provides the AngelScript execution environment. Needs to be created and registered manually.
  45. - Console: provides an interactive AngelScript console and log display. Created by calling \ref Engine::CreateConsole "CreateConsole()".
  46. - DebugHud: displays rendering mode information and statistics and profiling data. Created by calling \ref Engine::CreateDebugHud "CreateDebugHud()".
  47. In script, the subsystems are available through the following global properties:
  48. time, fileSystem, log, cache, network, input, ui, audio, engine, graphics, renderer, script, console, debugHud. Note that WorkQueue and Profiler are not available to script due to their low-level nature.
  49. \page Events Events
  50. The Urho3D event system allows for data transport and function invocation without the sender and receiver having to explicitly know of each other. Both the event sender and receiver must derive from Object. An event receiver must subscribe to each event type it wishes to receive: one can either subscribe to the event coming from any sender, or from a specific sender. The latter is useful for example when handling events from the user interface elements.
  51. Events themselves do not need to be registered. They are identified by 32-bit hashes of their names. Event parameters (the data payload) are optional and are contained inside a VariantMap, identified by 32-bit parameter name hashes. For the inbuilt Urho3D events, event type (E_UPDATE, E_KEYDOWN, E_MOUSEMOVE etc.) and parameter hashes (P_TIMESTEP, P_DX, P_DY etc.) are defined as constants inside include files such as CoreEvents.h or InputEvents.h.
  52. When subscribing to an event, a handler function must be specified. In C++ these must have the signature void HandleEvent(StringHash eventType, VariantMap& eventData). The HANDLER(className, function) macro helps in defining the required class-specific function pointers. For example:
  53. \code
  54. SubscribeToEvent(E_UPDATE, HANDLER(MyClass, MyEventHandler));
  55. \endcode
  56. In script events are identified by their string names instead of name hashes (though these are internally converted to hashes.) %Script event handlers can either have the same signature as in C++, or a simplified signature void HandleEvent() when event type and parameters are not required. The same event subscription would look like:
  57. \code
  58. SubscribeToEvent("Update", "MyEventHandler");
  59. \endcode
  60. In C++ events must always be handled by a member function. In script procedural event handling is also possible; in this case the ScriptFile where the event handler function is located becomes the event receiver. See \ref Scripting "Scripting" for more details.
  61. Events can also be unsubscribed from. See \ref Object::UnsubscribeFromEvent "UnsubscribeFromEvent()" for details.
  62. To send an event, fill the event parameters (if necessary) and call \ref Object::SendEvent "SendEvent()". For example, this (in C++) is how the Engine subsystem sends the Update event on each frame. Note how for the inbuilt Urho3D events, the parameter name hashes are always put inside a namespace (the event's name) to prevent name clashes:
  63. \code
  64. using namespace Update;
  65. VariantMap eventData;
  66. eventData[P_TIMESTEP] = timeStep_;
  67. SendEvent(E_UPDATE, eventData);
  68. \endcode
  69. In script event parameters, like event types, are referred to with strings, so the same code would look like:
  70. \code
  71. VariantMap eventData;
  72. eventData["TimeStep"] = timeStep;
  73. SendEvent("Update", eventData);
  74. \endcode
  75. \section Events_AnotherObject Sending events through another object
  76. Because the \ref Object::SendEvent "SendEvent()" function is public, an event can be "masqueraded" as originating from any object, even when not actually sent by that object's member function code. This can be used to simplify communication, particularly between components in the scene. For example, the \ref Physics "physics simulation" signals collision events by using the participating \ref Node "scene nodes" as senders. This means that any component can easily subscribe to its own node's collisions without having to know of the actual physics components involved. The same principle can also be used in any game-specific messaging, for example making a "damage received" event originate from the scene node, though it itself has no concept of damage or health.
  77. \page MainLoop %Engine initialization and main loop
  78. Before a Urho3D application can enter its main loop, the Engine subsystem object must be created and initialized by calling its \ref Engine::Initialize "Initialize()" function. Parameters sent in a VariantMap can be used to direct how the Engine initializes itself and the subsystems. One way to configure the parameters is to parse them from the command line like the Urho3DPlayer application does: this is accomplished by the helper function \ref Engine::ParseParameters "ParseParameters()".
  79. The full list of supported parameters, their datatypes and default values:
  80. - Headless (bool) Headless mode enable. Default false.
  81. - LogLevel (int) %Log verbosity level. Default LOG_INFO in release builds and LOG_DEBUG in debug builds.
  82. - LogQuiet (bool) %Log quiet mode, ie. to not write warning/info/debug log entries into standard output. Default false.
  83. - LogName (string) %Log filename. Default "Urho3D.log".
  84. - FrameLimiter (bool) Whether to cap maximum framerate to 200 (desktop) or 60 (Android/iOS.) Default true.
  85. - WorkerThreads (bool) Whether to create worker threads for the %WorkQueue subsystem according to available CPU cores. Default true.
  86. - ResourcePaths (string) A semicolon-separated list of resource paths to use. If corresponding packages (ie. Data.pak for Data directory) exist they will be used instead. Default "Data;CoreData".
  87. - ResourcePackages (string) A semicolon-separated list of resource packages to use. Default empty.
  88. - AutoloadPaths (string) A semicolon-separated list of autoload paths to use. Any resource packages and subdirectories inside an autoload path will be added to the resource system. Default "Extra".
  89. - ForceSM2 (bool) Whether to force %Shader %Model 2, effective in Direct3D9 mode only. Default false.
  90. - ExternalWindow (void ptr) External window handle to use instead of creating an application window. Default null.
  91. - WindowIcon (string) %Window icon image resource name. Default empty (use application default icon.)
  92. - WindowTitle (string) %Window title. Default "Urho3D".
  93. - WindowWidth (int) %Window horizontal dimension. Default 0 (use desktop resolution, or 1024 in windowed mode.)
  94. - WindowHeight (int) %Window vertical dimension. Default 0 (use desktop resolution, or 768 in windowed mode.)
  95. - WindowPositionX (int) %Window horizontal position. Default center to screen.
  96. - WindowPositionY (int) %Window vertical position. Default center to screen.
  97. - WindowResizable (bool) Whether window is resizable. Default false.
  98. - FullScreen (bool) Whether to create a full-screen window. Default true.
  99. - Borderless (bool) Whether to create the window as borderless. Default false.
  100. - TripleBuffer (bool) Whether to use triple-buffering. Default false.
  101. - VSync (bool) Whether to wait for vertical sync when presenting rendering window contents. Default false.
  102. - FlushGPU (bool) Whether to flush GPU command buffer each frame for less input latency. Effective only on Direct3D9. Default false.
  103. - Multisample (int) Hardware multisampling level. Default 1 (no multisampling.)
  104. - Orientations (string) Space-separated list of allowed orientations. Effective only on iOS. All possible values are "LandscapeLeft", "LandscapeRight", "Portrait" and "PortraitUpsideDown". Default "LandscapeLeft LandscapeRight".
  105. - DumpShaders (string) Filename to dump used shader variations to for precaching.
  106. - %RenderPath (string) Default renderpath resource name. Default empty, which causes forward rendering (Bin/CoreData/RenderPaths/Forward.xml) to be used.
  107. - Shadows (bool) Shadow rendering enable. Default true.
  108. - LowQualityShadows (bool) Low-quality (1 sample) shadow mode. Default false.
  109. - MaterialQuality (int) %Material quality level. Default 2 (high)
  110. - TextureQuality (int) %Texture quality level. Default 2 (high)
  111. - TextureFilterMode (int) %Texture default filter mode. Default 2 (trilinear)
  112. - TextureAnisotropy (int) %Texture anisotropy level. Default 4. This has only effect for anisotropically filtered textures.
  113. - %Sound (bool) %Sound enable. Default true.
  114. - SoundBuffer (int) %Sound buffer length in milliseconds. Default 100.
  115. - SoundMixRate (int) %Sound output frequency in Hz. Default 44100.
  116. - SoundStereo (bool) Stereo sound output mode. Default true.
  117. - SoundInterpolation (bool) Interpolated sound output mode to improve quality. Default true.
  118. - TouchEmulation (bool) %Touch emulation on desktop platform. Default false.
  119. \section MainLoop_Frame Main loop iteration
  120. The main loop iteration (also called a frame) is driven by the Engine. In contrast it is the program's (for example Urho3DPlayer) responsibility to continuously loop this iteration by calling \ref Engine::RunFrame "RunFrame()". This function calls in turn the Time subsystem's \ref Time::BeginFrame "BeginFrame()" and \ref Time::EndFrame "EndFrame()" functions, and sends various update events in between. The event order is:
  121. - E_BEGINFRAME: signals the beginning of the new frame. Input and Network react to this to check for operating system window messages and arrived network packets.
  122. - E_UPDATE: application-wide logic update event. By default each update-enabled Scene reacts to this and triggers the scene update (more on this below.)
  123. - E_POSTUPDATE: application-wide logic post-update event. The UI subsystem updates its logic here.
  124. - E_RENDERUPDATE: Renderer updates its viewports here to prepare for rendering, and the UI generates render commands necessary to render the user interface.
  125. - E_POSTRENDERUPDATE: by default nothing hooks to this. This can be used to implement logic that requires the rendering views to be up-to-date, for example to do accurate raycasts. Scenes may not be modified at this point; especially scene objects may not be deleted or crashes may occur.
  126. - E_ENDFRAME: signals the end of the frame. Before this, rendering the frame and measuring the next frame's timestep will have occurred.
  127. The update of each Scene causes further events to be sent:
  128. - E_SCENEUPDATE: variable timestep scene update. This is a good place to implement any scene logic that does not need to happen at a fixed step.
  129. - E_SCENESUBSYSTEMUPDATE: update scene-wide subsystems. Currently only the PhysicsWorld component listens to this, which causes it to step the physics simulation and send the following two events for each simulation step:
  130. - E_PHYSICSPRESTEP: called before the simulation iteration. Happens at a fixed rate (the physics FPS.) If fixed timestep logic updates are needed, this is a good event to listen to.
  131. - E_PHYSICSPOSTSTEP: called after the simulation iteration. Happens at the same rate as E_PHYSICSPRESTEP.
  132. - E_SMOOTHINGUPDATE: update SmoothedTransform components in network client scenes.
  133. - E_SCENEPOSTUPDATE: variable timestep scene post-update. ParticleEmitter and AnimationController update themselves as a response to this event.
  134. Variable timestep logic updates are preferable to fixed timestep, because they are only executed once per frame. In contrast, if the rendering framerate is low, several physics simulation steps will be performed on each frame to keep up the apparent passage of time, and if this also causes a lot of logic code to be executed for each step, the program may bog down further if the CPU can not handle the load. Note that the Engine's \ref Engine::SetMinFps "minimum FPS", by default 10, sets a hard cap for the timestep to prevent spiraling down to a complete halt; if exceeded, animation and physics will instead appear to slow down.
  135. \section MainLoop_ApplicationState Main loop and the application activation state
  136. The application window's state (has input focus, minimized or not) can be queried from the Input subsystem. It can also effect the main loop in the following ways:
  137. - Rendering is always skipped when the window is minimized.
  138. - To avoid spinning the CPU and GPU unnecessarily, it is possible to define a smaller maximum FPS when no input focus. See \ref Engine::SetMaxInactiveFps "SetMaxInactiveFps()"
  139. - It is also possible to automatically pause update events and audio when the window is minimized. Use \ref Engine::SetPauseMinimized "SetPauseMinimized()" to control this behaviour. By default it is not enabled on desktop, and enabled on mobile devices (Android and iOS.) For singleplayer games this is recommended to avoid unwanted progression while away from the program. However in a multiplayer game this should not be used, as the missing scene updates would likely desync the client with the server.
  140. - On mobile devices the window becoming minimized can mean that it will never become maximized again, in case the OS decides it needs to free memory and kills your program. Therefore you should listen for the E_INPUTFOCUS event from the Input subsystem and immediately save your program state as applicable if the program loses input focus or is minimized.
  141. - On mobile devices it is also unsafe to access or create any graphics resources while the window is minimized (as the graphics context may be destroyed during this time); doing so can crash the program. It is recommended to leave the pause-minimized feature on to ensure you do not have to check for this in your update code.
  142. Note that on iOS calling \ref Engine::Exit "Exit()" is a no-op as there is no officially sanctioned way to manually exit your program. On Android it will cause the activity to manually exit.
  143. \section MainLoop_ApplicationFramework Application framework
  144. The Application class provides a minimal framework for a Urho3D C++ application with a main loop. It has virtual functions Setup(), Start() and Stop() which can be defined by the application subclass. The header file also provides a macro for defining a program entry point, which
  145. will instantiate the Context object and then the user-specified application class. A minimal example, which would just display a blank rendering window and exit by pressing ESC:
  146. \code
  147. #include "Application.h"
  148. #include "Engine.h"
  149. #include "InputEvents.h"
  150. class MyApp : public Application
  151. {
  152. public:
  153. MyApp(Context* context) :
  154. Application(context)
  155. {
  156. }
  157. virtual void Setup()
  158. {
  159. // Called before engine initialization. engineParameters_ member variable can be modified here
  160. }
  161. virtual void Start()
  162. {
  163. // Called after engine initialization. Setup application & subscribe to events here
  164. SubscribeToEvent(E_KEYDOWN, HANDLER(MyApp, HandleKeyDown));
  165. }
  166. virtual void Stop()
  167. {
  168. // Perform optional cleanup after main loop has terminated
  169. }
  170. void HandleKeyDown(StringHash eventType, VariantMap& eventData)
  171. {
  172. using namespace KeyDown;
  173. // Check for pressing ESC. Note the engine_ member variable for convenience access to the Engine object
  174. int key = eventData[P_KEY].GetInt();
  175. if (key == KEY_ESC)
  176. engine_->Exit();
  177. }
  178. };
  179. DEFINE_APPLICATION_MAIN(MyApp)
  180. \endcode
  181. \page SceneModel %Scene model
  182. Urho3D's scene model can be described as a component-based scene graph. The Scene consists of a hierarchy of scene nodes, starting from the root node, which also represents the whole scene. Each Node has a 3D transform (position, rotation and scale), a name and an ID, and a freeform VariantMap for \ref Node::GetVars "user variables", but no other functionality.
  183. \section SceneModel_Components Components
  184. Rendering 3D objects, sound playback, physics and scripted logic updates are all enabled by creating different \ref Component "Components" into the nodes by calling \ref Node::CreateComponent "CreateComponent()". As with events, in C++ components are identified by type name hashes, and template forms of the component creation and retrieval functions exist for convenience. For example:
  185. \code
  186. Light* light = node->CreateComponent<Light>();
  187. \endcode
  188. In script, strings are used to identify component types instead, so the same code would look like:
  189. \code
  190. Light@ light = node.CreateComponent("Light");
  191. \endcode
  192. Because components are created using \ref ObjectTypes "object factories", a factory must be registered for each component type.
  193. Components created into the Scene itself have a special role: to implement scene-wide functionality. They should be created before all other components, and include the following:
  194. - Octree: implements spatial partitioning and accelerated visibility queries. Without this 3D objects can not be rendered.
  195. - PhysicsWorld: implements physics simulation. Physics components such as RigidBody or CollisionShape can not function properly without this.
  196. - DebugRenderer: implements debug geometry rendering.
  197. "Ordinary" components like Light, Camera or StaticModel should not be created directly into the Scene, but rather into child nodes.
  198. \section SceneModel_Identification Identification and scene hierarchy
  199. Unlike nodes, components do not have names; components inside the same node are only identified by their type, and index in the node's component list, which is filled in creation order. See the various overloads of \ref Node::GetComponent "GetComponent()" or \ref Node::GetComponents "GetComponents()" for details.
  200. When created, both nodes and components get scene-global integer IDs. They can be queried from the Scene by using the functions \ref Scene::GetNodeByID "GetNodeByID()" and \ref Scene::GetComponentByID "GetComponentByID()". This is much faster than for example doing recursive name-based scene node queries.
  201. There is no inbuilt concept of an entity or a game object; rather it is up to the programmer to decide the node hierarchy, and in which nodes to place any scripted logic. Typically, free-moving objects in the 3D world would be created as children of the root node. Nodes can be created either with or without a name, see \ref Node::CreateChild "CreateChild()". Uniqueness of node names is not enforced.
  202. Whenever there is some hierarchical composition, it is recommended (and in fact necessary, because components do not have their own 3D transforms) to create a child node. For example if a character was holding an object in his hand, the object should have its own node, which would be parented to the character's hand bone (also a Node.) The exception is the physics CollisionShape, which can be offsetted and rotated individually in relation to the node. See \ref Physics "Physics" for more details. Note that Scene's own transform is purposefully ignored as an optimization when calculating world derived transforms of child nodes, so changing it has no effect and it should be left as it is (position at origin, no rotation, no scaling.)
  203. %Scene nodes can be freely reparented. In contrast components are always created to the node they belong to, and can not be moved between nodes. Both child nodes and components are stored using SharedPtr containers; this means that detaching a child node from its parent or removing a component will also destroy it, if no other references to it exist. Both Node & Component provide the \ref Node::Remove "Remove()" function to accomplish this without having to go through the parent. Note that no operations on the node or component in question are safe after calling that function.
  204. It is also legal to create a Node that does not belong to a scene. This is useful for example with a camera moving in a scene that may be loaded or saved, because then the camera will not be saved along with the actual scene, and will not be destroyed when the scene is loaded. However, note that creating geometry, physics or script components to an unattached node, and then moving it into a scene later will cause those components to not work correctly.
  205. \section SceneModel_Update Scene updates
  206. A Scene whose updates are enabled (default) will be automatically updated on each main loop iteration. See \ref Scene::SetUpdateEnabled "SetUpdateEnabled()".
  207. Nodes and components can be excluded from the scene update by disabling them, see \ref Node::SetEnabled "SetEnabled()". Disabling for example a drawable component also makes it invisible, a sound source component becomes inaudible etc. If a node is disabled, all of its components are treated as disabled regardless of their own enable/disable state.
  208. \section SceneModel_Logic Creating logic functionality
  209. To implement your game logic you typically either create script objects (when using scripting) or new components (when using C++). %Script objects exist in a C++ placeholder component, but can be basically thought of as components themselves. For a simple example to get you started, check the 05_AnimatingScene sample, which creates a Rotator object to scene nodes to perform rotation on each frame update.
  210. Unless you have extremely serious reasons for doing so, you should not subclass the Node class in C++ for implementing your own logic. Doing so will theoretically work, but has the following drawbacks:
  211. - Loading and saving will not work properly without changes. It assumes that the root node is a %Scene, and all the child nodes are of the %Node class. It will not know how to instantiate your custom subclass.
  212. - The Editor does not know how to edit your subclass.
  213. \section SceneModel_LoadSave Loading and saving scenes
  214. Scenes can be loaded and saved in either binary or XML format; see the functions \ref Scene::Load "Load()", \ref Scene::LoadXML "LoadXML()", \ref Scene::Save "Save()" and \ref Scene::SaveXML "SaveXML()". See \ref Serialization
  215. "Serialization" for the technical details on how this works. When a scene is loaded, all existing content in it (child nodes and components) is removed first.
  216. Nodes and components that are marked temporary will not be saved. See \ref Serializable::SetTemporary "SetTemporary()".
  217. To be able to track the progress of loading a (large) scene without having the program stall for the duration of the loading, a scene can also be loaded asynchronously. This means that on each frame the scene loads resources and child nodes until a certain amount of milliseconds has been exceeded. See \ref Scene::LoadAsync "LoadAsync()" and \ref Scene::LoadAsyncXML "LoadAsyncXML()". Use the functions \ref Scene::IsAsyncLoading "IsAsyncLoading()" and \ref Scene::GetAsyncProgress "GetAsyncProgress()" to track the loading progress; the latter returns a float value between 0 and 1, where 1 is fully loaded. The scene will not update or render before it is fully loaded.
  218. \section SceneModel_Instantiation Object prefabs
  219. Just loading or saving whole scenes is not flexible enough for eg. games where new objects need to be dynamically created. On the other hand, creating complex objects and setting their properties in code will also be tedious. For this reason, it is also possible to save a scene node (and its child nodes, components and attributes) to either binary or XML to be able to instantiate it later into a scene. Such a saved object is often referred to as a prefab. There are three ways to do this:
  220. - In code by calling \ref Node::Save "Save()" or \ref Node::SaveXML "SaveXML()" on the Node in question.
  221. - In the editor, by selecting the node in the hierarchy window and choosing "Save node as" from the "File" menu.
  222. - Using the "node" command in AssetImporter, which will save the scene node hierarchy and any models contained in the input asset (eg. a Collada file)
  223. To instantiate the saved node into a scene, call \ref Scene::Instantiate "Instantiate()" or \ref Scene::InstantiateXML "InstantiateXML()" depending on the format. The node will be created as a child of the Scene but can be freely reparented after that. Position and rotation for placing the node need to be specified. The NinjaSnowWar example uses XML format for its object prefabs; these exist in the Bin/Data/Objects directory.
  224. \section SceneModel_FurtherInformation Further information
  225. For more information on the component-based scene model, see for example http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/. Note that the Urho3D scene model is not a pure Entity-Component-System design, which would have the components just as bare data containers, and only systems acting on them. Instead the Urho3D components contain logic of their own, and actively communicate with the systems (such as rendering, physics or script engine) they depend on.
  226. \page Resources Resources
  227. Resources include most things in Urho3D that are loaded from mass storage during initialization or runtime:
  228. - Animation
  229. - Image
  230. - Model
  231. - Material
  232. - ParticleEffect
  233. - ScriptFile
  234. - Shader
  235. - Sound
  236. - Technique
  237. - Texture2D
  238. - Texture3D
  239. - TextureCube
  240. - XMLFile
  241. They are managed and loaded by the ResourceCache subsystem. Like with all other \ref ObjectTypes "typed objects", resource types are identified by 32-bit type name hashes (C++) or type names (script). An object factory must be registered for each resource type.
  242. The resources themselves are identified by their file paths, relative to the registered resource directories or \ref PackageFile "package files". By default, the engine registers the resource directories Data and CoreData, or the packages Data.pak and CoreData.pak if they exist.
  243. If loading a resource fails, an error will be logged and a null pointer is returned.
  244. Typical C++ example of requesting a resource from the cache, in this case, a texture for a UI element. Note the use of a convenience template argument to specify the resource type, instead of using the type hash.
  245. \code
  246. healthBar->SetTexture(GetSubsystem<ResourceCache>()->GetResource<Texture2D>("Textures/HealthBarBorder.png"));
  247. \endcode
  248. The same in script would look like this (note the use of a property instead of a setter function):
  249. \code
  250. healthBar.texture = cache.GetResource("Texture2D", "Textures/HealthBarBorder.png");
  251. \endcode
  252. Resources can also be created manually and stored to the resource cache as if they had been loaded from disk.
  253. Memory budgets can be set per resource type: if resources consume more memory than allowed, the oldest resources will be removed from the cache if not in use anymore. By default the memory budgets are set to unlimited.
  254. \section Resources_Background Background loading of resources
  255. Normally, when requesting resources using \ref ResourceCache::GetResource "GetResource()", they are loaded immediately in the main thread, which may take several milliseconds for all the required steps (load file from disk,
  256. parse data, upload to GPU if necessary) and can therefore result in framerate drops.
  257. If you know in advance what resources you need, you can request them to be loaded in a background thread by calling \ref ResourceCache::BackgroundLoadResource "BackgroundLoadResource()". The event E_RESOURCEBACKGROUNDLOADED will be sent after the loading is complete; it will tell if the loading actually was a success or a failure. Depending on the resource, only a part of the loading process may be moved to a background thread, for example the finishing GPU upload step always needs to happen in the main thread. Note that if you call GetResource() for a resource that is queued for background loading, the main thread will stall until its loading is complete.
  258. The asynchronous scene loading functionality \ref Scene::LoadAsync "LoadAsync()" and \ref Scene::LoadAsyncXML "LoadAsyncXML()" has the option to background load the resources first before proceeding to load the scene content. It can also be used to only load the resources without modifying the scene, by specifying the LOAD_RESOURCES_ONLY mode. This allows to prepare a scene or object prefab file for fast instantiation.
  259. Finally the maximum time (in milliseconds) spent each frame on finishing background loaded resources can be configured, see \ref ResourceCache::SetFinishBackgroundResourcesMs "SetFinishBackgroundResourcesMs()".
  260. \section Resources_BackgroundImplementation Implementing background loading
  261. When writing new resource types, the background loading mechanism requires implementing two functions: \ref Resource::BeginLoad "BeginLoad()" and \ref Resource::EndLoad "EndLoad()". BeginLoad() is potentially called in a background thread and should do as much work (such as file I/O) as possible without violating the \ref Multithreading "multithreading" rules. EndLoad() should perform the main thread finishing step, such as GPU upload. Either step can return false to indicate failure to load the resource.
  262. If a resource depends on other resources, writing efficient threaded loading for it can be hard, as calling GetResource() is not allowed inside BeginLoad() when background loading. There are a few options: it is allowed to queue new background load requests by calling BackgroundLoadResource() within BeginLoad(), or if the needed resource does not need to be permanently stored in the cache and is safe to load outside the main thread (for example Image or XMLFile, which do not possess any GPU-side data), \ref ResourceCache::GetTempResource "GetTempResource()" can be called inside BeginLoad.
  263. \page Scripting Scripting
  264. To enable AngelScript scripting support, the Script subsystem needs to be created and registered after initializing the Engine. This is accomplished by the following code, seen eg. in Tools/Urho3DPlayer/Urho3DPlayer.cpp:
  265. \code
  266. context_->RegisterSubsystem(new Script(context_));
  267. \endcode
  268. There are three ways the AngelScript language can be interacted with in Urho3D:
  269. \section Scripting_Immediate Immediate execution
  270. Immediate execution takes one line of AngelScript, compiles it, and executes. This is not recommended for anything that needs high performance, but can be used for example to implement a developer console. Call the Script subsystem's \ref Script::Execute "Execute()" function to use. For example:
  271. \code
  272. GetSubsystem<Script>()->Execute("Print(\"Hello World!\");");
  273. \endcode
  274. It may be useful to be able to access a specific scene or a script file while executing immediate script code. These can be set on the Script subsystem by calling \ref Script::SetDefaultScene "SetDefaultScene()" and \ref Script::SetDefaultScriptFile "SetDefaultScriptFile()".
  275. \section Scripting_Procedural Calling a function from a script file
  276. This requires a successfully loaded ScriptFile resource, whose \ref ScriptFile::Execute "Execute()" function will be used. To identify the function to be called, its full declaration is needed. Parameters are passed in a VariantVector. For example:
  277. \code
  278. ScriptFile* file = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>("Scripts/MyScript.as");
  279. VariantVector parameters;
  280. parameters.Push(Variant(100)); // Add an int parameter
  281. file->Execute("void MyFunction(int)", parameters); // Execute
  282. \endcode
  283. \ref ScriptFile::Execute "Execute()" also has an overload which takes a function pointer instead of querying by declaration. Using a pointer is naturally faster than a query, but also more risky: in case the ScriptFile resource is unloaded or reloaded, any function pointers will be invalidated.
  284. \section Scripting_Object Instantiating a script object
  285. The component ScriptInstance can be used to instantiate a specific class from within a script file. After instantiation, the the script object can respond to scene updates, \ref Events "events" and \ref Serialization "serialization" much like a component written in C++ would do, if it has the appropriate methods implemented. For example:
  286. \code
  287. ScriptInstance* instance = node->CreateComponent<ScriptInstance>();
  288. instance->CreateObject(GetSubsystem<ResourceCache>()->GetResource<ScriptFile>("Scripts/MyClass.as"), "MyClass");
  289. \endcode
  290. The class must implement the empty interface ScriptObject to make its base class statically known. This enables accessing any script object in the scene using ScriptInstance's \ref ScriptInstance::GetScriptObject "GetScriptObject()" function.
  291. The following methods that implement the component behaviour will be checked for. None of them are required.
  292. - void Start()
  293. - void Stop()
  294. - void DelayedStart()
  295. - void Update(float)
  296. - void PostUpdate(float)
  297. - void FixedUpdate(float)
  298. - void FixedPostUpdate(float)
  299. - void Save(Serializer&)
  300. - void Load(Deserializer&)
  301. - void WriteNetworkUpdate(Serializer&)
  302. - void ReadNetworkUpdate(Deserializer&)
  303. - void ApplyAttributes()
  304. - void TransformChanged()
  305. The update methods above correspond to the variable timestep scene update and post-update, and the fixed timestep physics world update and post-update. The application-wide update events are not handled by default.
  306. The Start() and Stop() methods do not have direct counterparts in C++ components. Start() is called just after the script object has been created. Stop() is called just before the script object is destroyed. This happens when the ScriptInstance is destroyed, or if the script class is changed.
  307. When a scene node hierarchy with script objects is instantiated (such as when loading a scene) any child nodes may not have been created yet when Start() is executed, and can thus not be relied upon for initialization. The DelayedStart() method can be used in this case instead: if defined, it is called immediately before any of the Update() calls.
  308. TransformChanged() is called whenever the scene node transform changes, similar to C++ components' OnMarkedDirty() function.
  309. Subscribing to \ref Events "events" in script behaves differently depending on whether \ref Object::SubscribeToEvent "SubscribeToEvent()" is called from a script object's method, or from a procedural script function. If called from an instantiated script object, the ScriptInstance becomes the event receiver on the C++ side, and calls the specified handler method when the event arrives. If called from a function, the ScriptFile will be the event receiver and the handler must be a free function in the same script file. The third case is if the event is subscribed to from a script object that does not belong to a ScriptInstance. In that case the ScriptFile will create a proxy C++ object on demand to be able to forward the event to the script object.
  310. The script object's enabled state can be controlled through the \ref ScriptInstance::SetEnabled "SetEnabled()" function. When disabled, the scripted update methods or event handlers will not be called. This can be used to reduce CPU load in a large or densely populated scene.
  311. There are shortcut methods on the script side for creating and accessing a node's script object: node.CreateScriptObject() and node.GetScriptObject(). Alternatively, if the node has only one ScriptInstance, and a specific class is not needed, the node's scriptObject property can also be used. CreateScriptObject() takes the script file name (or alternatively, a ScriptFile object handle) and class name as parameters and creates a ScriptInstance component automatically, then creates the script object. For example:
  312. \code
  313. ScriptObject@ object = node.CreateScriptObject("Scripts/MyClass.as", "MyClass");
  314. \endcode
  315. Note that these are not actual Node member functions on the C++ side, as the %Scene classes are not allowed to depend on scripting.
  316. \section Scripting_ObjectSerialization Script object serialization
  317. After instantiation, the script object's public member variables that can be converted into Variant, and that don't begin with an underscore are automatically available as attributes of the ScriptInstance, and will be serialized.
  318. Node and Component handles are also converted into nodeID and componentID attributes automatically. Note: this automatic attribute mechanism means that a ScriptInstance's attribute list changes dynamically depending on the class that has been instantiated.
  319. If the script object contains more complex data structures, you can also serialize and deserialize into a binary buffer manually by implementing the Load() and Save() methods.
  320. %Network replication of the script object variables must be handled manually by implementing WriteNetworkUpdate() and ReadNetworkUpdate() methods, that also write and read a binary buffer. These methods should write/read all replicated of variables of the object. Additionally, the ScriptInstance must be marked for network replication by calling MarkNetworkUpdate() whenever the replicated data changes. Because this replication mechanism can not sync per variable, but always sends the whole binary buffer if even one bit of the data changes, also consider using the automatically replicated node user variables.
  321. \section Script_DelayedCalls Delayed method calls
  322. Delayed method calls can be used in script objects to implement time-delayed actions. Use the DelayedExecute() function in script object code to add a method to be executed later. The parameters are the delay in seconds, repeat flag, the full declaration of the function, and optionally parameters, which must be placed in a Variant array. For example:
  323. \code
  324. class Test : ScriptObject
  325. {
  326. void Start()
  327. {
  328. Array<Variant> parameters;
  329. parameters.Push(Variant(100));
  330. DelayedExecute(1.0, false, "void Trigger(int)", parameters);
  331. }
  332. void Trigger(int parameter)
  333. {
  334. Print("Delayed function triggered with parameter " + parameter);
  335. }
  336. }
  337. \endcode
  338. Delayed method calls can be removed by full declaration using the ClearDelayedExecute() function. If an empty declaration (default) is given as parameter, all delayed calls are removed.
  339. When a scene is saved/loaded, any pending delayed calls are also saved and restored properly.
  340. \section Script_ScriptAPI The script API
  341. Much of the Urho3D classes are exposed to scripts, however things that require low-level access or high performance (like direct vertex buffer access) are not. Also for scripting convenience some things have been changed from the C++ API:
  342. - The template array and string classes are exposed as Array<type> and String.
  343. - Public member variables are exposed without the underscore appended. For example x, y, z in Vector3.
  344. - Whenever only a single parameter is needed, setter and getter functions are replaced with properties. Such properties start with a lowercase letter. If an index parameter is needed, the property will be indexed. Indexed properties are in plural.
  345. - The element count property of arrays and other dynamic structures such as VariantMap and ResourceRefList is called "length", though the corresponding C++ function is usually Size().
  346. - Subsystems exist as global properties: time, fileSystem, log, cache, network, input, ui, audio, engine, graphics, renderer, script, console, debugHud.
  347. - Additional global properties exist for accessing the script object's node, the scene and the scene-wide components: node, scene, octree, physicsWorld, debugRenderer. When an object method is not executing, these are null. An exception: when the default scene for immediate execution has been set by calling \ref Script::SetDefaultScene "SetDefaultScene()", it is always available as "scene".
  348. - The currently executing script object's ScriptInstance component is available through the global property self.
  349. - The currently executing script file is available through the global property scriptFile.
  350. - The first script object created to a node is available as its scriptObject property.
  351. - Printing raw output to the log is simply called Print(). The rest of the logging functions are accessed by calling log.Debug(), log.Info(), log.Warning() and log.Error().
  352. - Functions that would take a StringHash parameter usually take a string instead. For example sending events, requesting resources and accessing components.
  353. - Most of StringUtils have been exposed as methods of the string class. For example String.ToBool().
  354. - Template functions for getting components or resources by type are not supported. Instead automatic type casts are performed as necessary.
  355. Check the automatically built \ref ScriptAPI "Scripting API" documentation for the exact function signatures. Note that the API documentation can be regenerated to the Urho3D log file by calling \ref Script::DumpAPI "DumpAPI()" function on the Script subsystem or by using \ref Tools_ScriptCompiler "ScriptCompiler tool".
  356. \section Script_Bytecode Precompiling scripts to bytecode
  357. Instead of compiling scripts from source on-the-fly during startup, they can also be precompiled to bytecode, then loaded. Use the \ref Tools_ScriptCompiler "ScriptCompiler" utility for this. In this case the resource request has to be pointed to the compiled file, which by default has the .asc extension:
  358. \code
  359. ScriptFile* file = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>("Scripts/MyScript.asc");
  360. \endcode
  361. \section Scripting_Limitations Limitations
  362. There are some complexities of the scripting system one has to watch out for:
  363. - During the execution of the script object's constructor, the object is not yet associated with the ScriptInstance, and therefore subscribing to events, adding delayed method calls, or trying to access the node or scene will fail. The use of the constructor is best reserved for initializing member variables only.
  364. - When the resource request for a particular ScriptFile is initially made, the script file and the files it includes are compiled into an AngelScript script module. Each script module has its own class hierarchy that is not usable from other script modules, unless the classes are declared shared. See AngelScript documentation for more details.
  365. - If a ScriptFile resource is reloaded, all the script objects created from it will be destroyed, then recreated. They will lose any stored state as their constructors and Start() methods will be run again. This is rarely useful when running an actual game, but may be helpful during development.
  366. \section Scripting_Modifications AngelScript modifications
  367. The following changes have been made to AngelScript in Urho3D:
  368. - For performance reasons and to guarantee immediate removal of expired objects, AngelScript garbage collection has been disabled for script classes and the Array type. This has the downside that circular references will not be detected. Therefore, whenever you have object handles in your script, think of them as if they were C++ shared pointers and avoid creating circular references with them. For safety, consider using the value type WeakHandle, which is a WeakPtr<RefCounted> exposed to script and can be used to point to any engine object (but not to script objects.) An example of using WeakHandle:
  369. \code
  370. WeakHandle rigidBodyWeak = node.CreateComponent("RigidBody");
  371. RigidBody@ rigidBodyShared = rigidBodyWeak.Get(); // Is null if expired
  372. \endcode
  373. - %Object handle assignment can be done without the @ symbol if the object in question does not support value assignment. All exposed Urho3D C++ classes that derive from RefCounted never support value assignment. For example, when assigning the Model and Material of a StaticModel component:
  374. \code
  375. object.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  376. object.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  377. \endcode
  378. In unmodified AngelScript, this would have to be written as:
  379. \code
  380. @object.model = cache.GetResource("Model", "Models/Mushroom.mdl");
  381. @object.material = cache.GetResource("Material", "Materials/Mushroom.xml");
  382. \endcode
  383. \page LuaScripting Lua scripting
  384. Lua scripting in Urho3D has its dedicated LuaScript subsystem that must be instantiated before the scripting capabilities can be used. Lua support is not compiled in by default but must be enabled by the CMake
  385. build option -DURHO3D_LUA=1. For more details see \ref Build_Options "Build options". Instantiating the subsystem is done like this:
  386. \code
  387. context_->RegisterSubsystem(new LuaScript(context_));
  388. \endcode
  389. Like AngelScript, Lua scripting supports immediate compiling and execution of single script lines, loading script files and executing procedural functions from them, and instantiating script objects
  390. to scene nodes using the LuaScriptInstance component.
  391. \section LuaScripting_Immediate Immediate execution
  392. Use \ref LuaScript::ExecuteString "ExecuteString()" to compile and run a line of Lua script. This should not be used for performance-critical operations.
  393. \section LuaScripting_ScriptFiles Script files and functions
  394. In contrast to AngelScript modules, which exist as separate entities and do not share functions or variables unless explicitly marked shared, in the Lua subsystem everything is loaded and executed in one Lua state, so scripts can naturally access everything loaded so far. To load and execute a Lua script file, call \ref LuaScript::ExecuteFile "ExecuteFile()".
  395. After that, the functions in the script file are available for calling. Use \ref LuaScript::GetFunction "GetFunction()" to get a Lua function by name. This returns a LuaFunction object, on which you should call \ref LuaFunction::BeginCall "BeginCall()" first, followed by pushing the function parameters if any, and finally execute the function with \ref LuaFunction::EndCall "EndCall()".
  396. \section LuaScripting_ScriptObjects Script objects
  397. By using the LuaScriptInstance component, Lua script objects can be added to scene nodes. After the component has been created, there are two ways to specify the object to instantiate: either specifying both the script file name and the object class name, in which case the script file is loaded and executed first, or specifying only the class name, in which case the Lua code containing the class definition must already have been executed. An example of creating a script object in C++ from the LuaIntegration sample, where a class called Rotator is instantiated from the script file Rotator.lua:
  398. \code
  399. LuaScriptInstance* instance = node->CreateComponent<LuaScriptInstance>();
  400. instance->CreateObject("LuaScripts/Rotator.lua", "Rotator");
  401. \endcode
  402. After instantiation, use \ref LuaScriptInstance::GetScriptObjectFunction "GetScriptObjectFunction()" to get the object's functions by name; calling happens like above.
  403. Like their AngelScript counterparts, script object classes can define functions which are automatically called by LuaScriptInstance for operations like initialization, scene update, or load/save. These functions are listed below. Refer to the \ref Scripting "AngelScript scripting" page for details.
  404. - Start()
  405. - Stop()
  406. - Update(timeStep)
  407. - PostUpdate(timeStep)
  408. - FixedUpdate(timeStep)
  409. - FixedPostUpdate(timeStep)
  410. - Save(serializer)
  411. - Load(deserializer)
  412. - WriteNetworkUpdate(serializer)
  413. - ReadNetworkUpdate(deserializer)
  414. - ApplyAttributes()
  415. - TransformChanged()
  416. \section LuaScripting_Events Event handling
  417. Like in AngelScript, both procedural and object event handling is supported. In procedural event handling the LuaScript subsystem acts as the event receiver on the C++ side, and forwards the event to a Lua function. Use SubscribeToEvent and give the event name and the function to use as the handler. Optionally a specific sender object can be given as the first argument instead. For example, subscribing to the application-wide Update event, and getting its timestep parameter in the event handler function.
  418. \code
  419. SubscribeToEvent("Update", "HandleUpdate")
  420. ...
  421. function HandleUpdate(eventType, eventData)
  422. local timeStep = eventData:GetFloat("TimeStep")
  423. ...
  424. end
  425. \endcode
  426. When subscribing a script object to receive an event, use the form self:SubscribeToEvent instead. The function to use as the handler is given as "ClassName:FunctionName". For example subscribing to the NodeCollision physics event, and getting the participating other scene node and the contact point VectorBuffer in the handler function. Note that in Lua retrieving an object pointer from a VariantMap requires the object type as the first parameter:
  427. \code
  428. CollisionDetector = ScriptObject()
  429. function CollisionDetector:Start()
  430. self:SubscribeToEvent(self.node, "NodeCollision", "CollisionDetector:HandleNodeCollision")
  431. end
  432. function CollisionDetector:HandleNodeCollision(eventType, eventData)
  433. local otherNode = eventData:GetPtr("Node", "OtherNode")
  434. local contacts = eventData:GetBuffer("Contacts")
  435. ...
  436. end
  437. \endcode
  438. \section LuaScripting_API The script API
  439. The binding of Urho3D C++ classes is accomplished with the tolua++ library, which for the most part binds the exact same function parameters as C++. Compared to the AngelScript API, you will always have the classes' Get / Set functions available, but in addition convenience properties also exist.
  440. As seen above from the event handling examples, VariantMap handling has some differences to both C++ and AngelScript. To get a value, supply its key name as a string. To get a pointer to an object, supply first the object type, then the key name.
  441. For the rest of the functions and classes, see the generated \ref LuaScriptAPI "Lua script API reference". Also, look at the Lua counterparts of the sample applications in the Bin/Data/LuaScripts directory and compare them to the C++ and AngelScript versions to familiarize yourself with how things are done on the Lua side.
  442. \section LuaScripting_Allocation Object allocation & Lua garbage collection
  443. There are two ways to allocate a C++ object in Lua scripting, which behave differently with respect to Lua's automatic garbage collection:
  444. 1) Call object's contructor:
  445. \code
  446. local scene = Scene()
  447. \endcode
  448. tolua++ will register this C++ object with garbage collection, and Lua will collect it eventually. Do not use this form if you will add the
  449. object to an object hierarchy that is kept alive on the C++ side with SharedPtr's, for example child scene nodes or %UI child elements.
  450. Otherwise the object will be double-deleted, resulting in a crash.
  451. 2) Call the new function:
  452. \code
  453. local text = Text:new()
  454. \endcode
  455. When using this form the object will not collected by Lua, so it is safe to pass into C++ object hierarchies.
  456. Otherwise, to prevent memory leaks it needs to be deleted manually by calling the delete function on it:
  457. \code
  458. text:delete()
  459. \endcode
  460. When you call the \ref ResourceCache::GetFile "GetFile()" function of ResourceCache from Lua, the file you receive must also be manually deleted like described above once you are done with it.
  461. \page Rendering Rendering
  462. Much of the rendering functionality in Urho3D is built on two subsystems, Graphics and Renderer.
  463. \section Rendering_Graphics Graphics
  464. Graphics implements the low-level functionality:
  465. - Creating the window and the rendering context
  466. - Setting the screen mode
  467. - Keeping track of GPU resources
  468. - Keeping track of rendering context state (current rendertarget, vertex and index buffers, textures, shaders and renderstates)
  469. - Loading shaders
  470. - Performing primitive rendering operations
  471. - Handling lost device
  472. Screen resolution, fullscreen/windowed, vertical sync and hardware multisampling level are all set at once by calling Graphics's \ref Graphics::SetMode "SetMode()" function. There is also an experimental option of rendering to an existing window by passing its OS-specific handle to \ref Graphics::SetExternalWindow "SetExternalWindow()" before setting the initial screen mode.
  473. When setting the initial screen mode, Graphics does a few checks:
  474. - For Direct3D9, the supported shader model is checked. 2 is minimum, but 3 will be used if available. For testing, SM2 can be forced by calling \ref Graphics::SetForceSM2 "SetForceSM2()" before setting the initial screen mode.
  475. - For OpenGL, version 2.0 with EXT_framebuffer_object, EXT_packed_depth_stencil and EXT_texture_filter_anisotropic extensions is checked for.
  476. - Is hardware instancing supported? This requires %Shader %Model 3 on Direct3D9 and the ARB_instanced_arrays extension on OpenGL.
  477. - Are hardware shadow maps supported? Both AMD & NVIDIA style shadow maps can be used. If neither are available, no shadows will be rendered.
  478. - Are light pre-pass and deferred rendering modes supported? These require sufficient multiple rendertarget support, and R32F texture format support.
  479. %Shader model 2 has the following limitations due to limited pixel shader instruction count:
  480. - Directional light shadows support a maximum of 3 cascade splits instead of 4.
  481. - Shadowed point lights do not support specular calculations in forward rendering.
  482. - Complex materials do not combine the ambient pass with the first forward light (lit base pass optimization.)
  483. - Complex forward rendered materials (eg. normal + specular map + alpha masking) combined with shadow mapping or height fog may not work.
  484. \section Rendering_Renderer Renderer
  485. Renderer implements the actual rendering of 3D views each frame, and controls global settings such as texture quality, material quality, specular lighting and shadow map base resolution.
  486. To render, it needs a Scene with an Octree component, and a Camera that does not necessarily have to belong to the scene. The octree stores all visible components (derived from Drawable) to allow querying for them in an accelerated manner. The needed information is collected in a Viewport object, which can be assigned with Renderer's \ref Renderer::SetViewport "SetViewport()" function.
  487. By default there is one viewport, but the amount can be increased with the function \ref Renderer::SetNumViewports "SetNumViewports()". The viewport(s) should cover the entire screen or otherwise hall-of-mirrors artifacts may occur. By specifying a zero screen rectangle the whole window will be used automatically. The viewports will be rendered in ascending order, so if you want for example to have a small overlay window on top of the main viewport, use viewport index 0 for the main view, and 1 for the overlay.
  488. Viewports can also be defined for rendertarget textures. See \ref AuxiliaryViews "Auxiliary views" for details.
  489. Each viewport defines a command sequence for rendering the scene, the \ref RenderPaths "render path". By default there exist forward, light pre-pass and deferred render paths in the Bin/CoreData/RenderPaths directory, see \ref Renderer::SetDefaultRenderPath "SetDefaultRenderPath()" to set the default for new viewports. If not overridden from the command line, forward rendering is the default. Deferred rendering modes will be advantageous once there is a large number of per-pixel lights affecting each object, but their disadvantages are the lack of hardware multisampling and inability to choose the lighting model per material. In place of multisample antialiasing, a FXAA post-processing edge filter can be used, see the MultipleViewports sample application (Bin/Data/Scripts/09_MultipleViewports.as) for an example of how to use.
  490. The steps for rendering each viewport on each frame are roughly the following:
  491. - Query the octree for visible objects and lights in the camera's view frustum.
  492. - Check the influence of each visible light on the objects. If the light casts shadows, query the octree for shadowcaster objects.
  493. - Construct render operations (batches) for the visible objects, according to the scene passes in the render path command sequence.
  494. - Perform the render path command sequence during the rendering step at the end of the frame.
  495. - If the scene has a DebugRenderer component and the viewport has debug rendering enabled, render debug geometry last. Can be controlled with \ref Viewport::SetDrawDebug "SetDrawDebug()", default is enabled.
  496. In the default render paths, the rendering operations proceed in the following order:
  497. - Opaque geometry ambient pass, or G-buffer pass in deferred rendering modes.
  498. - Opaque geometry per-pixel lighting passes. For shadow casting lights, the shadow map is rendered first.
  499. - (%Light pre-pass only) Opaque geometry material pass, which renders the objects with accumulated per-pixel lighting.
  500. - Post-opaque pass for custom render ordering such as the skybox.
  501. - Refractive geometry pass.
  502. - Transparent geometry pass. Transparent, alpha-blended objects are sorted according to distance and rendered back-to-front to ensure correct blending.
  503. - Post-alpha pass, can be used for 3D overlays that should appear on top of everything else.
  504. \section Rendering_Drawable Rendering components
  505. The rendering-related components defined by the %Graphics and %UI libraries are:
  506. - Octree: spatial partitioning of Drawables for accelerated visibility queries. Needs to be created to the Scene (root node.)
  507. - Camera: describes a viewpoint for rendering, including projection parameters (FOV, near/far distance, perspective/orthographic)
  508. - Drawable: Base class for anything visible.
  509. - StaticModel: non-skinned geometry. Can LOD transition according to distance.
  510. - StaticModelGroup: renders several object instances while culling and receiving light as one unit.
  511. - Skybox: a subclass of StaticModel that appears to always stay in place.
  512. - AnimatedModel: skinned geometry that can do skeletal and vertex morph animation.
  513. - AnimationController: drives animations forward automatically and controls animation fade-in/out.
  514. - BillboardSet: a group of camera-facing billboards, which can have varying sizes, rotations and texture coordinates.
  515. - ParticleEmitter: a subclass of BillboardSet that emits particle billboards.
  516. - Light: illuminates the scene. Can optionally cast shadows.
  517. - Terrain: renders heightmap terrain.
  518. - CustomGeometry: renders runtime-defined unindexed geometry. The geometry data is not serialized or replicated over the network.
  519. - DecalSet: renders decal geometry on top of objects.
  520. - Zone: defines ambient light and fog settings for objects inside the zone volume.
  521. - Text3D: text that is rendered into the 3D view.
  522. Additionally there are 2D drawable components defined by the \ref Urho2D "Urho2D" sublibrary.
  523. \section Rendering_Optimizations Optimizations
  524. The following techniques will be used to reduce the amount of CPU and GPU work when rendering. By default they are all on:
  525. - Software rasterized occlusion: after the octree has been queried for visible objects, the objects that are marked as occluders are rendered on the CPU to a small hierarchical-depth buffer, and it will be used to test the non-occluders for visibility. Use \ref Renderer::SetMaxOccluderTriangles "SetMaxOccluderTriangles()" and \ref Renderer::SetOccluderSizeThreshold "SetOccluderSizeThreshold()" to configure the occlusion rendering.
  526. - Hardware instancing: rendering operations with the same geometry, material and light will be grouped together and performed as one draw call. Objects with a large amount of triangles will not be rendered as instanced, as that could actually be detrimental to performance. Use \ref Renderer::SetMaxInstanceTriangles "SetMaxInstanceTriangles()" to set the threshold. Note that even when instancing is not available, or the triangle count of objects is too large, they still benefit from the grouping, as render state only needs to be set once before rendering each group, reducing the CPU cost.
  527. - %Light stencil masking: in forward rendering, before objects lit by a spot or point light are re-rendered additively, the light's bounding shape is rendered to the stencil buffer to ensure pixels outside the light range are not processed.
  528. Note that many more optimization opportunities are possible at the content level, for example using geometry & material LOD, grouping many static objects into one object for less draw calls, minimizing the amount of subgeometries (submeshes) per object for less draw calls, using texture atlases to avoid render state changes, using compressed (and smaller) textures, and setting maximum draw distances for objects, lights and shadows.
  529. \section Rendering_GPUResourceLoss Handling GPU resource loss
  530. On Direct3D9 and Android OpenGL ES 2.0 it is possible to lose the rendering context (and therefore GPU resources) due to the application window being minimized to the background. Also, to work around possible GPU driver bugs the desktop OpenGL context will be voluntarily destroyed and recreated when changing screen mode or toggling between fullscreen and windowed. Therefore, on all graphics APIs one must be prepared for losing GPU resources.
  531. Textures that have been loaded from a file, as well as vertex & index buffers that have shadowing enabled will restore their contents automatically, the rest have to be restored manually. On Direct3D9 non-dynamic (managed) textures and buffers will never be lost, as the runtime automatically backs them up to system memory.
  532. See \ref GPUObject::IsDataLost "IsDataLost()" function in VertexBuffer, IndexBuffer, Texture2D, TextureCube and Texture3D classes for detecting data loss. Inbuilt classes such as Model, BillboardSet and Font already handle data loss for their internal GPU resources, so checking for it is only necessary for custom buffers and textures. Watch out especially for trying to render with an index buffer that has uninitialized data after a loss, as this can cause a crash inside the GPU driver due to referencing non-existent (garbage) vertices.
  533. \section Rendering_Further Further details
  534. See also \ref Materials "Materials", \ref Shaders "Shaders", \ref Lights "Lights and shadows", \ref RenderPaths "Render path", \ref SkeletalAnimation "Skeletal animation", \ref Particles "Particle systems", \ref Zones "Zones", and \ref AuxiliaryViews "Auxiliary views".
  535. See \ref RenderingModes "Rendering modes" for detailed discussion on the forward, light pre-pass and deferred rendering modes.
  536. See \ref APIDifferences "Differences between Direct3D9 and OpenGL" for what to watch out for when using the low-level rendering functionality directly.
  537. \page RenderingModes Rendering modes
  538. The default render paths supplied with Urho3D implement forward, light pre-pass and deferred rendering modes. Where they differ is how per-pixel lighting is calculated for opaque objects; transparent objects always use forward rendering. Note that on OpenGL ES 2.0 only forward rendering is available.
  539. \section RenderingModes_Forward Forward rendering
  540. Forward rendering begins with an ambient light pass for the objects; this also adds any per-vertex lights. Then, the objects are re-rendered for each per-pixel light affecting them (basic multipass rendering), up to the maximum per-pixel light count which is by default unlimited, but can be reduced with \ref Drawable::SetMaxLights "SetMaxLights()". The render operations are sorted by light, ie. render the effect of the first light on all affected objects first, then the second etc. If shadow maps are re-used (default on), a shadow casting light's shadow map will be updated immediately before rendering the lit objects. When shadow maps are not re-used, all shadow maps are updated first even before drawing the ambient pass.
  541. Materials can also define an optimization pass, called "litbase", for forward rendering where the ambient light and the first per-pixel light are combined. This pass can not be used, however, if there are per-vertex lights affecting the object, or if the ambient light has a per-vertex gradient.
  542. \section RenderingModes_Prepass Light pre-pass rendering
  543. %Light pre-pass requires a minimum of two passes per object. First the normal, specular power, depth and lightmask (8 low bits only) of opaque objects are rendered to the following G-buffer:
  544. - RT0: World-space normal and specular power (D3DFMT_A8R8G8B8)
  545. - RT1: Linear depth (D3DFMT_R32F)
  546. - DS: Hardware depth and lightmask (D3DFMT_D24S8)
  547. After the G-buffer is complete, light volumes (spot and point lights) or fullscreen quads (directional lights) will be rendered to a light accumulation buffer to calculate the diffuse and specular light at each opaque pixel. Specular light is stored as intensity only. Stencil compare (AND operation) with the 8 low bits of the light's lightmask will be used for light culling. Similarly to forward rendering, shadow maps will be updated before each light as necessary.
  548. Finally the opaque objects are re-rendered during the material pass, which combines ambient and vertex lighting with per-pixel lighting from the light accumulation buffer. After this rendering proceeds to the post-opaque and refract passes, transparent object rendering pass, and the post-alpha pass, just like forward rendering.
  549. \section RenderingModes_Deferred Deferred rendering
  550. Deferred rendering needs to render each opaque object only once to the G-buffer, but this rendering pass is much heavier than in light pre-pass rendering, as also ambient, emissive and diffuse albedo information is output at the same time. The G-buffer is the following:
  551. - RT0: Final rendertarget with ambient, per-vertex and emissive color (D3DFMT_X8R8G8B8)
  552. - RT1: Diffuse albedo and specular intensity (D3DFMT_A8R8G8B8)
  553. - RT2: World-space normal and specular power (D3DFMT_A8R8G8B8)
  554. - RT3: Linear depth (D3DFMT_R32F)
  555. - DS: Hardware depth and lightmask (D3DFMT_D24S8)
  556. After the G-buffer has been rendered, light volumes will be rendered into the final rendertarget to accumulate per-pixel lighting. As the material albedo is available, all lighting calculations are final and output both the diffuse and specular color at the same time. After light accumulation rendering proceeds to post-opaque, refract, transparent, and post-alpha passes, as in other rendering modes.
  557. \section RenderingModes_Comparison Advantages and disadvantages
  558. Whether using forward or deferred rendering modes is more advantageous depends on the scene and lighting complexity.
  559. If the scene contains a large number of complex objects lit by multiple lights, forward rendering quickly increases the total draw call and vertex count due to re-rendering the objects for each light. However, light pre-pass and deferred rendering have a higher fixed cost due to the generation of the G-buffer. Also, in forward per-pixel lighting more calculations (such as light direction and shadow map coordinates) can be done at the vertex shader level, while in deferred all calculations need to happen per-pixel. This means that for a low light count, for example 1-2 per object, forward rendering will run faster based on the more efficient lighting calculations alone.
  560. Forward rendering makes it possible to use hardware multisampling and different shading models in different materials if needed, while neither is possible in the deferred modes. Also, only forward rendering allows to calculate the material's diffuse and specular light response with the most accuracy. %Light pre-pass rendering needs to reconstruct light specular color from the accumulated diffuse light color, which is inaccurate in case of overlapping lights. Deferred rendering on the other hand can not use the material's full specular color, it only stores a monochromatic intensity based on the green component into the G-buffer.
  561. %Light pre-pass rendering has a much more lightweight G-buffer pass, but it must render all opaque geometry twice. %Light accumulation in pre-pass mode is slightly faster than in deferred. Despite this, unless there is significant overdraw, in vertex-heavy scenes deferred rendering will likely be faster than light pre-pass.
  562. Finally note that due to OpenGL framebuffer object limitations an extra framebuffer blit has to happen at the end in both light pre-pass and deferred rendering, which costs some performance. Also, because multiple rendertargets on OpenGL must have the same format, an R32F texture can not be used for linear depth, but instead 24-bit depth is manually encoded and decoded into RGB channels.
  563. \page APIDifferences Differences between Direct3D9 and OpenGL
  564. These differences need to be observed when using the low-level rendering functionality directly. The high-level rendering architecture, including the Renderer and UI subsystems and the Drawable subclasses already handle most of them transparently to the user.
  565. - The post-projection depth range is (0,1) for Direct3D9 and (-1,1) for OpenGL. The Camera can be queried either for an API-specific or API-independent (Direct3D9 convention) projection matrix.
  566. - To render with 1:1 texel-to-pixel mapping, on Direct3D9 UV coordinates have to be shifted a half-pixel to the right and down, or alternatively vertex positions can be shifted a half-pixel left and up.
  567. - On Direct3D9 the depth-stencil surface can be equal or larger in size than the color rendertarget. On OpenGL the sizes must always match. Furthermore, OpenGL can not use the backbuffer depth-stencil surface when rendering to a texture. To overcome these limitations, Graphics will create correctly sized depth-stencil surfaces on demand whenever a texture is set as a color rendertarget, and a null depth-stencil is specified.
  568. - On Direct3D9 the viewport will be reset to full size when the first color rendertarget is changed. On OpenGL this does not happen. To ensure correct operation on both APIs, always use this sequence: first set the rendertargets, then the depth-stencil surface and finally the viewport.
  569. - On OpenGL modifying a texture will cause it to be momentarily set on the first texture unit. If another texture was set there, the assignment will be lost. Graphics performs a check to not assign textures redundantly, so it is safe and recommended to always set all needed textures before rendering.
  570. - Modifying an index buffer on OpenGL will similarly cause the existing index buffer assignment to be lost. Therefore, always set the vertex and index buffers before rendering.
  571. - %Shader resources are stored in different locations depending on the API: Bin/CoreData/Shaders/HLSL for Direct3D9, and Bin/CoreData/Shaders/GLSL for OpenGL.
  572. - To ensure similar UV addressing for render-to-texture viewports on both APIs, on OpenGL texture viewports will be rendered upside down.
  573. OpenGL ES 2.0 has further limitations:
  574. - Of the DXT formats, only DXT1 compressed textures will be uploaded as compressed, and only if the EXT_texture_compression_dxt1 extension is present. Other DXT formats will be uploaded as uncompressed RGBA. ETC1 (Android) and PVRTC (iOS) compressed textures are supported through the .ktx and .pvr file formats.
  575. - %Texture formats such as 16-bit and 32-bit floating point are not available. Corresponding integer 8-bit formats will be returned instead.
  576. - %Light pre-pass and deferred rendering are not supported due to missing multiple rendertarget support, and limited rendertarget formats.
  577. - Wireframe and point fill modes are not supported.
  578. - Due to texture unit limit (usually 8), point light shadow maps are not supported.
  579. - To reduce fillrate, the stencil buffer is not reserved and the stencil test is not available. As a consequence, the light stencil masking optimization is not used.
  580. - For improved performance, shadow mapping quality is reduced: there is no smooth PCF filtering and directional lights do not support shadow cascades. Consider also using the low shadow quality (1 sample) to avoid dependent texture reads in the pixel shader, which have an especially high performance cost on iOS hardware.
  581. - Custom clip planes are not currently supported.
  582. - 3D textures are not currently supported.
  583. \page Materials Materials
  584. Material and Technique resources define how to render 3D scene geometry. On the disk, they are XML data. Default and example materials exist in the Bin/CoreData/Materials & Bin/Data/Materials subdirectories, and techniques exist in the Bin/CoreData/Techniques subdirectory.
  585. A material defines the textures, shader parameters and culling mode to use, and refers to one or several techniques. A technique defines the actual rendering passes, the shaders to use in each, and all other rendering states such as depth test, depth write, and blending.
  586. A material definition looks like this:
  587. \code
  588. <material>
  589. <technique name="TechniqueName" quality="q" loddistance="d" />
  590. <texture unit="diffuse|normal|specular|emissive|environment" name="TextureName" />
  591. <texture ... />
  592. <parameter name="name" value="x y z w" />
  593. <parameter ... />
  594. <cull value="cw|ccw|none" />
  595. <shadowcull value="cw|ccw|none" />
  596. <depthbias constant="x" slopescaled="y" />
  597. </material>
  598. \endcode
  599. Several techniques can be defined for different quality levels and LOD distances. %Technique quality levels are specified from 0 (low) to 2 (high). When rendering, the highest available technique that does not exceed the Renderer's material quality setting will be chosen, see \ref Renderer::SetMaterialQuality "SetMaterialQuality()". It is also possible for a technique to require %Shader %Model 3, in this case it will be skipped on SM2 hardware.
  600. The techniques for different LOD levels and quality settings must appear in a specific order:
  601. - Most distant & highest quality
  602. - ...
  603. - Most distant & lowest quality
  604. - Second most distant & highest quality
  605. - ...
  606. %Material shader parameters can be floats or vectors up to 4 components, or matrices.
  607. Default culling mode is counterclockwise. The shadowcull element specifies the culling mode to use in the shadow pass. Note that material's depth bias settings do not apply in the shadow pass; during shadow rendering the light's depth bias is used instead.
  608. \section Materials_Textures Material textures
  609. Diffuse maps specify the surface color in the RGB channels. Optionally they can use the alpha channel for blending and alpha testing. They should preferably be compressed to DXT1 (no alpha or 1-bit alpha) or DXT5 (smooth alpha) format.
  610. Normal maps encode the tangent-space surface normal for normal mapping. There are two options for storing normals, which require choosing the correct material technique, as the pixel shader is different in each case:
  611. - Store as RGB. In this case use the DiffNormal techniques. This is the default used by AssetImporter, to ensure no conversion of normal textures needs to happen.
  612. - Store as xGxR, ie. Y-component in the green channel, and X-component in the alpha. In this case use the DiffNormalPacked techniques: Z will be reconstructed in the pixel shader. This encoding lends itself well to DXT5 compression. To convert normal maps to this format, you can use AMD's The Compressonator utility, see http://developer.amd.com/Resources/archive/ArchivedTools/gpu/compressonator/Pages/default.aspx
  613. Make sure the normal map is oriented correctly: an even surface should have the color value R 0.5 G 0.5 B 1.0.
  614. Models using a normal-mapped material need to have tangent vectors in their vertex data; the easiest way to ensure this is to use the switch -t (generate tangents) when using either AssetImporter or OgreImporter to import models to Urho3D format. If there are no tangents, the light attenuation on the normal-mapped material will behave in a completely erratic fashion.
  615. Specular maps encode the specular surface color as RGB. Note that deferred rendering is only able to use monochromatic specular intensity from the G channel, while forward and light pre-pass rendering use fully colored specular. DXT1 format should suit these textures well.
  616. Textures can have an accompanying XML file which specifies load-time parameters, such as addressing, mipmapping, and number of mip levels to skip on each quality level:
  617. \code
  618. <texture>
  619. <address coord="u|v|w" mode="wrap|mirror|clamp|border" />
  620. <border color="r g b a" />
  621. <filter mode="nearest|bilinear|trilinear|anisotropic|default" />
  622. <mipmap enable="false|true" />
  623. <quality low="x" medium="y" high="z" />
  624. <srgb enable="false|true" />
  625. </texture>
  626. \endcode
  627. The sRGB flag controls both whether the texture should be sampled with sRGB to linear conversion, and if used as a rendertarget, pixels should be converted back to sRGB when writing to it. To control whether the backbuffer should use sRGB conversion on write, call \ref Graphics::SetSRGB "SetSRGB()" on the Graphics subsystem.
  628. \section Materials_CubeMapTextures Cube map textures
  629. Using cube map textures requires an XML file to define the cube map face textures or layout. In this case the XML file *is* the texture resource name in material scripts or in LoadResource() calls.
  630. Individual face textures are defined in the XML like this: (see Bin/Data/Textures/Skybox.xml for an example)
  631. \code
  632. <cubemap>
  633. <face name="PositiveX_TextureName" />
  634. <face name="NegativeX_TextureName" />
  635. <face name="PositiveY_TextureName" />
  636. <face name="NegativeY_TextureName" />
  637. <face name="PositiveZ_TextureName" />
  638. <face name="NegativeZ_TextureName" />
  639. </cubemap>
  640. \endcode
  641. Using a single image texture and a layout is used like this:
  642. \code
  643. <cubemap>
  644. <image name="TextureName" layout="horizontal|horizontalnvidia|horizontalcross|verticalcross|blender" />
  645. </cubemap>
  646. \endcode
  647. For the layout definitions, see http://www.cgtextures.com/content.php?action=tutorial&name=cubemaps and http://en.wikibooks.org/wiki/Blender_3D:_Noob_to_Pro/Build_a_skybox
  648. \section Materials_Techniques Techniques and passes
  649. A technique definition looks like this:
  650. \code
  651. <technique vs="VertexShaderName" ps="PixelShaderName" vsdefines="DEFINE1 DEFINE2" psdefines="DEFINE3 DEFINE4" sm3="false|true" desktop="false|true" >
  652. <pass name="base|litbase|light|alpha|litalpha|postopaque|refract|postalpha|prepass|material|deferred|depth|shadow" sm3="false|true" desktop="false|true" >
  653. vs="VertexShaderName" ps="PixelShaderName" vsdefines="DEFINE1 DEFINE2" psdefines="DEFINE3 DEFINE4"
  654. lighting="unlit|pervertex|perpixel"
  655. blend="replace|add|multiply|alpha|addalpha|premulalpha|invdestalpha|subtract|subtractalpha"
  656. depthtest="always|equal|less|lessequal|greater|greaterequal"
  657. depthwrite="true|false"
  658. alphamask="true|false" />
  659. <pass ... />
  660. <pass ... />
  661. </technique>
  662. \endcode
  663. The "sm3" attribute in the technique root element allows the technique to specify it requires %Shader %Model 3 hardware. Omitting it is same as specifying false (works on both SM2 & 3.) The sm3 attribute can also be specified per pass, to disable for example a too complex lit base optimization pass on SM2.
  664. The "desktop" attribute in either technique or pass works similarly to allow requiring desktop hardware and excluding mobile devices.
  665. Shaders are referred to by giving the name of a shader without path and file extension. For example "Basic" or "LitSolid". The engine will add the correct path and file extension (Shaders/HLSL/LitSolid.hlsl for Direct3D9, and Shaders/GLSL/LitSolid.glsl for OpenGL) automatically. The same shader source file contains both the vertex and pixel shader. In addition, compilation defines can be specified, which are passed to the shader compiler. For example the define "DIFFMAP" typically enables diffuse mapping in the pixel shader.
  666. Shaders and their compilation defines can be specified on both the technique and pass level. If a pass does not override the default shaders specified on the technique level, it still can specify additional compilation defines to be used. However, if a pass overrides the shaders, then the technique-level defines are not used.
  667. The technique definition does not need to enumerate shaders used for different geometry types (non-skinned, skinned, instanced, billboard) and different per-vertex and per-pixel light combinations. Instead the engine will add certain hardcoded compilation defines for these. See \ref Shaders "Shaders" for details.
  668. The purposes of the different passes are:
  669. - base: Renders ambient light, per-vertex lights and fog for an opaque object.
  670. - litbase: Renders the first per-pixel light, ambient light and fog for an opaque object. This is an optional pass for optimization.
  671. - light: Renders one per-pixel light's contribution additively for an opaque object.
  672. - alpha: Renders ambient light, per-vertex lights and fog for a transparent object.
  673. - litalpha: Renders one per-pixel light's contribution additively for a transparent object
  674. - postopaque: Custom rendering pass after opaque geometry. Can be used to render the skybox.
  675. - refract: Custom rendering pass after postopaque pass. Can sample the viewport texture from the environment texture unit to render refractive objects.
  676. - postalpha: Custom rendering pass after transparent geometry.
  677. - prepass: %Light pre-pass only - renders normals, specular power and depth to the G-buffer.
  678. - material: %Light pre-pass only - renders opaque geometry final color by combining ambient light, per-vertex lights and per-pixel light accumulation.
  679. - deferred: Deferred rendering only - renders ambient light and per-vertex lights to the output rendertarget, and diffuse albedo, normals, specular intensity + power and depth to the G-buffer.
  680. - depth: Renders linear depth to a rendertarget for post-processing effects.
  681. - shadow: Renders to a hardware shadow map (depth only) for shadow map generation.
  682. More custom passes can be defined and referred to in the \ref RenderPaths "render path definition". For the built-in passes listed above, the lighting shader permutations to load (unlit, per-vertex or per-pixel) are recognized automatically, but for custom passes they need to be explicitly specified. The default is unlit.
  683. The optional "litbase" pass reduces draw call count by combining ambient lighting with the first per-pixel light affecting an object. However, it has intentional limitations to not require too many shader permutations: there must be no vertex lights affecting the object, and the ambient lighting can not have a gradient. In case of excessive overdraw, it is possibly better not to define it, but instead allow the base pass (which is computationally very lightweight) to run first, initializing the Z buffer for later passes.
  684. "Alphamask" is not an actual rendering state, but a hint which tells that the pixel shader will use discard based on alpha. Because this may interfere with the early-Z culling, materials without the alpha masking hint will be drawn first.
  685. The refract pass requires pingponging the scene rendertarget to a texture, but this will not be performed if there is no refractive geometry to render, so there is no unnecessary cost to it.
  686. \page Shaders Shaders
  687. Urho3D uses an ubershader-like approach: permutations of each shader will be built with different compilation defines, to produce eg. static or skinned, deferred or forward or shadowed/unshadowed rendering.
  688. The building of these permutations happens on demand: technique and renderpath definition files both refer to shaders and the compilation defines to use with them. In addition the engine will add inbuilt defines related to geometry type and lighting. It is not generally possible to enumerate beforehand all the possible permutations that can be built out of a single shader.
  689. On Direct3D9 compiled shader bytecode is saved to disk in a "Cache" subdirectory next to the shader source code, so that the possibly time-consuming compile can be skipped on the next time the shader permutation is needed. On OpenGL such mechanism is not available.
  690. \section Shaders_InbuiltDefines Inbuilt compilation defines
  691. When rendering scene objects, the engine expects certain shader permutations to exist for different geometry types and lighting conditions. These correspond to the following compilation defines:
  692. Vertex shader:
  693. - NUMVERTEXLIGHTS=1,2,3 or 4: number of vertex lights influencing the object
  694. - DIRLIGHT, SPOTLIGHT, POINTLIGHT: a per-pixel forward light is being used. Accompanied by the define PERPIXEL
  695. - SHADOW: the per-pixel forward light has shadowing
  696. - SKINNED, INSTANCED, BILLBOARD: choosing the geometry type
  697. Pixel shader:
  698. - DIRLIGHT, SPOTLIGHT, POINTLIGHT: a per-pixel forward light is being used. Accompanied by the define PERPIXEL
  699. - CUBEMASK: the point light has a cube map mask
  700. - SPEC: the per-pixel forward light has specular calculations
  701. - SHADOW: the per-pixel forward light has shadowing
  702. - LQSHADOW: use low-quality shadowing (1 hardware PCF sample instead of 4)
  703. - SHADOWCMP: use manual shadow depth compare, Direct3D9 only for DF16 & DF24 shadow map formats
  704. - HEIGHTFOG: object's zone has height fog mode
  705. \section Shaders_InbuiltUniforms Inbuilt shader uniforms
  706. When objects or quad passes are being rendered, various engine inbuilt uniforms are set to assist with the rendering. Below is a partial list of the uniforms listed as HLSL data types. Look at the file Uniforms.glsl for the corresponding GLSL uniforms.
  707. Vertex shader uniforms:
  708. - float3 cAmbientStartColor: the start color value for a zone's ambient gradient
  709. - float3 cAmbientEndColor: the end color value for a zone's ambient gradient
  710. - float3 cCameraPos: camera's world position
  711. - float3x3 cCameraRot: camera's world rotation matrix
  712. - float cNearClip: camera's near clip distance
  713. - float cFarClip: camera's far clip distance
  714. - float cDeltaTime: the timestep of the current frame
  715. - float cElapsedTime: scene's elapsed time value. Can be used to implement animating materials
  716. - float4x3 cModel: the world transform matrix of the object being rendered
  717. - float4x4 cViewProj: the camera's concatenated view and projection matrices
  718. - float4x3 cZone: zone's transform matrix; used for ambient gradient calculations
  719. Pixel shader uniforms:
  720. - float3 cAmbientColor: ambient color for a zone with no ambient gradient
  721. - float3 cCameraPosPS: camera's world position
  722. - float cDeltaTimePS: the timestep of the current frame
  723. - float cElapsedTimePS: scene's elapsed time value
  724. - float3 cFogColor: the zone's fog color
  725. - float4 cFogParams: fog calculation parameters (see Batch.cpp and Fog.hlsl for the exact meaning)
  726. - float cNearClipPS: camera's near clip distance
  727. - float cFarClipPS: camera's far clip distance
  728. \section Shaders_Writing Writing shaders
  729. Shaders must be written separately for HLSL (Direct3D9) and GLSL (OpenGL). The built-in shaders try to implement the same functionality on both shader languages as closely as possible.
  730. To get started with writing your own shaders, start with studying the most basic examples possible: the Basic, Shadow & Unlit shaders. Note the shader include files which bring common functionality, for example Uniforms.hlsl, Samplers.hlsl & Transform.hlsl for HLSL shaders.
  731. Transforming the vertex (which hides the actual skinning, instancing or billboarding process) is a slight hack which uses a combination of macros and functions: it is safest to copy the following piece of code verbatim:
  732. For HLSL:
  733. \code
  734. float4x3 modelMatrix = iModelMatrix;
  735. float3 worldPos = GetWorldPos(modelMatrix);
  736. oPos = GetClipPos(worldPos);
  737. \endcode
  738. For GLSL:
  739. \code
  740. mat4 modelMatrix = iModelMatrix;
  741. vec3 worldPos = GetWorldPos(modelMatrix);
  742. gl_Position = GetClipPos(worldPos);
  743. \endcode
  744. On both Direct3D9 and OpenGL the vertex and pixel shaders are written into the same file, and the entrypoint functions must be called VS() and PS(). In OpenGL mode one of these is transformed to the main() function required by GLSL behind the scenes. When compiling a vertex shader, the compilation define "COMPILEVS" is always present, and likewise "COMPILEPS" when compiling a pixel shader. These are heavily used in the shader include files to prevent constructs that are illegal for the "wrong" type of shader, and to reduce compilation time. When compiling for %Shader %Model 3 on Direct3D9, the compilation define "SM3" is present: this can be used to separate code which would not compile on SM2.
  745. The uniforms must be prefixed in a certain way so that the engine understands them:
  746. - c for uniform constants, for example cMatDiffColor. The c is stripped when referred to inside the engine, so it would be called "MatDiffColor" in eg. \ref Material::SetShaderParameter "SetShaderParameter()"
  747. - s for texture samplers, for example sDiffMap.
  748. In GLSL shaders it is important that the samplers are assigned to the correct texture units. If you are using sampler names that are not predefined in the engine like sDiffMap, just make sure there is a number somewhere in the sampler's name and it will be interpreted as the texture unit. For example the terrain shader uses texture units 0-3 in the following way:
  749. \code
  750. uniform sampler2D sWeightMap0;
  751. uniform sampler2D sDetailMap1;
  752. uniform sampler2D sDetailMap2;
  753. uniform sampler2D sDetailMap3;
  754. \endcode
  755. \section Shaders_Migration Migration of old shaders
  756. In Urho3D V1.3 and before an XML description file was used for shaders, which would enumerate the compilation defines used by shaders into named "options" or "variations".
  757. The shader would then be referred to with these option names, for example a pixel shader LitSolid_Diff would use the LitSolid source code and the define DIFFMAP. To convert to the
  758. current system, look up the defines from the description files and add them directly to the technique or renderpath XML descriptions ("vsdefines" or "psdefines" attributes). Also make sure the shader references ("vs" and "ps" attributes) are just the bare shader names with no underscore or option names attached. Finally, delete the shader XML description files.
  759. GLSL shaders in V1.3 and before used separate .vert and .frag files for the vertex and pixel shader source code. Now these are combined into .glsl files that include both shaders. Include files are likewise merged into .glsl files instead of separate vertex and pixel shader includes. To merge your shader code, append the pixel shader source into the vertex shader source file without the varyings definition (which should already be in the vertex shader code). Merge and fix include statements: change the file extension to .glsl. Note that some include files depend on each other so it is safest to always include Uniforms.glsl and Samplers.glsl first. Finally change the file extension of the vertex shader source file from .vert to .glsl and delete the .frag file. If you have pieces of pixel shader code (for example additional functions or variables) that produce errors when included in the vertex shader compile, wrap these with #ifdef COMPILEPS, and vice versa for vertex shader code.
  760. \section Shaders_Precaching Shader precaching
  761. The shader variations that are potentially used by a material technique in different lighting conditions and rendering passes are enumerated at material load time, but because of their large amount, they are not actually compiled or loaded from bytecode before being used in rendering. Especially on OpenGL the compiling of shaders just before rendering can cause hitches in the framerate. To avoid this, used shader combinations can be dumped out to an XML file, then preloaded. See \ref Graphics::BeginDumpShaders "BeginDumpShaders()", \ref Graphics::EndDumpShaders "EndDumpShaders()" and \ref Graphics::PrecacheShaders "PrecacheShaders()" in the Graphics subsystem. The command line parameters -ds <file> can be used to instruct the Engine to begin dumping shaders automatically on startup.
  762. Note that the used shader variations will vary with graphics settings, for example shadow quality high/low or instancing on/off.
  763. \page RenderPaths Render path
  764. %Scene rendering and any post-processing on a Viewport is defined by its RenderPath object, which can either be read from an XML file or be created programmatically.
  765. The render path consists of rendertarget definitions and commands. The commands are executed in order to yield the rendering result. Each command outputs either to the destination rendertarget & viewport (default if output definition is omitted), or one of the named rendertargets. MRT output is also possible.
  766. A rendertarget's size can be either absolute or multiply or divide the destination viewport size. The multiplier or divisor does not need to be an integer number. Furthermore, a rendertarget can be declared "persistent" so that it will not be mixed with other rendertargets of the same size and format, and its contents can be assumed to be available also on subsequent frames. For examples of rendertarget definitions, see the postprocess renderpath definitions in the Bin/Data/PostProcess directory.
  767. The available commands are:
  768. - clear: Clear any of color, depth and stencil. Color clear can optionally use the fog color from the Zone visible at the far clip distance.
  769. - scenepass: Render scene objects whose \ref Materials "material technique" contains the specified pass. Will either be front-to-back ordered with state sorting, or back-to-front ordered with no state sorting. For deferred rendering, object lightmasks can be optionally marked to the stencil buffer. Vertex lights can optionally be handled during a pass, if it has the necessary shader combinations. Textures global to the pass can be bound to free texture units; these can either be the viewport, a named rendertarget, or a 2D texture resource identified with its pathname.
  770. - quad: Render a viewport-sized quad using the specified shaders and compilation defines. Textures can be bound and additionally shader parameters can be specified.
  771. - forwardlights: Render per-pixel forward lighting for opaque objects with the specified pass name. Shadow maps are also rendered as necessary.
  772. - lightvolumes: Render deferred light volumes using the specified shaders. G-buffer textures can be bound as necessary.
  773. A render path can be loaded from a main XML file by calling \ref RenderPath::Load "Load()", after which other XML files (for example one for each post-processing effect) can be appended to it by calling \ref RenderPath::Append "Append()". Rendertargets and commands can be enabled or disabled by calling \ref RenderPath::SetEnabled "SetEnabled()" to switch eg. a post-processing effect on or off. To aid in this, both can be identified by tag names, for example the bloom effect uses the tag "Bloom" for all of its rendertargets and commands.
  774. It is legal to both write to the destination viewport and sample from it during the same command: pingpong copies of its contents will be made automatically. If the viewport has hardware multisampling on, the multisampled backbuffer will be resolved to a texture before sampling it.
  775. The render path XML definition looks like this:
  776. \code
  777. <renderpath>
  778. <rendertarget name="RTName" tag="TagName" enabled="true|false" size="x y"|sizedivisor="x y"|sizemultiplier="x y"
  779. format="rgb|rgba|r32f|rgba16|rgba16f|rgba32f|rg16|rg16f|rg32f|lineardepth" filter="true|false" srgb="true|false" persistent="true|false" />
  780. <command type="clear" tag="TagName" enabled="true|false" clearcolor="r g b a|fog" cleardepth="x" clearstencil="y" output="viewport|RTName" />
  781. <command type="scenepass" pass="PassName" sort="fronttoback|backtofront" marktostencil="true|false" vertexlights="true|false" metadata="base|alpha|gbuffer" >
  782. <output index="0" name="RTName1" />
  783. <output index="1" name="RTName2" />
  784. <output index="2" name="RTName3" />
  785. <texture unit="unit" name="viewport|RTName|TextureName" />
  786. </command>
  787. <command type="quad" vs="VertexShaderName" ps="PixelShaderName" vsdefines="DEFINE1 DEFINE2" psdefines="DEFINE3 DEFINE4" output="viewport|RTName" />
  788. <texture unit="unit" name="viewport|RTName|TextureName" />
  789. <parameter name="ParameterName" value="x y z w" />
  790. </command>
  791. <command type="forwardlights" pass="PassName" uselitbase="true|false" output="viewport|RTName" />
  792. <command type="lightvolumes" vs="VertexShaderName" ps="PixelShaderName" output="viewport|RTName" />
  793. <texture unit="unit" name="viewport|RTName|TextureName" />
  794. </command>
  795. </renderpath>
  796. \endcode
  797. Note the special "lineardepth" format available for rendertargets. This is intended for storing scene depth in deferred rendering. It will be D3DFMT_R32F on Direct3D9, but RGBA on OpenGL, due to the limitation of all color buffers having to be the same format. The shader include file Samplers.glsl in Bin/CoreData/Shaders/GLSL provides functions to encode and decode linear depth to RGB.
  798. \section RenderPaths_ForwardLighting Forward lighting special considerations
  799. Otherwise fully customized scene render passes can be specified, but there are a few things to remember related to forward lighting:
  800. - The opaque base pass must be tagged with metadata "base". When forward lighting logic does the lit base pass optimization, it will search for a pass with the word "lit" prepended, ie. if your custom opaque base pass is
  801. called "custombase", the corresponding lit base pass would be "litcustombase".
  802. - The transparent base pass must be tagged with metadata "alpha". For lit transparent objects, the forward lighting logic will look for a pass with the word "lit" prepended, ie. if the custom alpha base pass is called "customalpha", the corresponding lit pass is "litcustomalpha". The lit drawcalls will be interleaved with the transparent base pass, and the scenepass command should have back-to-front sorting enabled.
  803. - If forward and deferred lighting are mixed, the G-buffer writing pass must be tagged with metadata "gbuffer" to prevent geometry being double-lit also with forward lights.
  804. - Remember to mark the lighting mode (per-vertex / per-pixel) into the techniques which define custom passes, as the lighting mode can be guessed automatically only for the known default passes.
  805. - The forwardlights command can optionally disable the lit base pass optimization without having to touch the material techniques, if a separate opaque ambient-only base pass is needed. By default the optimization is enabled.
  806. \section RenderPaths_PostProcess Post-processing effects special considerations
  807. Post-processing effects are usually implemented by using the quad command. When using intermediate rendertargets that are of different size than the viewport rendertarget, it is necessary in shaders to reference their (inverse) size and the half-pixel offset for Direct3D9. These shader uniforms are automatically generated for named rendertargets. For an example look at the bloom postprocess shaders: the rendertarget called HBlur will define the shader uniforms cHBlurInvSize and cHBlurOffsets (both Vector2.)
  808. In OpenGL post-processing shaders it is important to distinguish between sampling a rendertarget texture and a regular texture resource, because intermediate rendertargets (such as the G-buffer) may be vertically inverted. Use the GetScreenPos() or GetQuadTexCoord() functions to get rendertarget UV coordinates from the clip coordinates; this takes flipping into account automatically. For sampling a regular texture, use GetQuadTexCoordNoFlip() function, which requires world coordinates instead of clip coordinates.
  809. \page Lights Lights and shadows
  810. Lights in Urho3D can be directional, point, or spot lights, either per-pixel or per-vertex. Shadow mapping is supported for all per-pixel lights.
  811. A directional light's position has no effect, as it's assumed to be infinitely far away, only its rotation matters. It casts orthographically projected shadows. For increasing the shadow quality, cascaded shadow mapping (splitting the view into several shadow maps along the Z-axis) can be used.
  812. Point lights are spherical in shape. When a point light casts shadows, it will be internally split into 6 spot lights with a 90 degree FOV each. This is very expensive rendering-wise, so shadow casting point lights should be used sparingly.
  813. Spot lights have FOV & aspect ratio values like cameras to define the shape of the light cone.
  814. Both point and spot lights in per-pixel mode use an attenuation ramp texture to determine how the intensity varies with distance. In addition they have a shape texture, 2D for spot lights, and an optional cube texture for point lights. It is important that the spot light's shape texture has black at the borders, and has mipmapping disabled, otherwise there will be "bleeding" artifacts at the edges of the light cone.
  815. Per-vertex mode is enabled on a light by calling \ref Light::SetPerVertex "SetPerVertex()". Per-vertex lights are evaluated during each object's ambient light and fog calculations and can be substantially faster than per-pixel lights. There is currently a maximum of 4 per-vertex lights for each object; if this number is exceeded, only the brightest per-vertex lights affecting the object will be rendered.
  816. \section Lights_LightColor Light color
  817. A light's color and strength are controlled by three values: \ref Light::SetColor "color", \ref Light::SetSpecularIntensity "specular intensity", and \ref Light::SetBrightness "brightness multiplier".
  818. The brightness multiplier is applied to both the color and specular intensity to yield final values used in rendering. This can be used to implement fades or flickering without affecting the original color.
  819. A specular intensity of 0 disables specular calculations from a per-pixel light, resulting in faster GPU calculations. Per-vertex lights never use specular calculations.
  820. Negative (subtractive) lights can be achieved by setting either the color components or the brightness multiplier to a negative value. These can be used to locally reduce the ambient light level, for example to create a dark cave. Negative per-pixel lights will not work in light pre-pass rendering mode, as it uses a light accumulation buffer with a black initial value, so there is nothing to subtract from.
  821. \section Lights_LightCulling Light culling
  822. When occlusion is used, a light will automatically be culled if its bounding box is fully behind an occluder. However, directional lights have an infinite bounding box, and can not be culled this way.
  823. It is possible to limit which objects are affected by each light, by calling \ref Drawable::SetLightMask "SetLightMask()" on both the light and the objects. The lightmasks of the light and objects are ANDed to check whether the light should have effect: the light will only illuminate an object if the result is nonzero. By default objects and lights have all bits set in their lightmask, thus passing this test always.
  824. \ref Zone "Zones" can also be used for light culling. When an object is inside a zone, its lightmask will be ANDed with the zone's lightmask before testing it against the lights' lightmasks. Using this mechanism, objects can change their accepted light set dynamically as they move through the scene.
  825. Care must be utilized when doing light culling with lightmasks, because they easily create situations where a light's influence is cut off unnaturally. However, they can be helpful in preventing light spill into undesired areas, for example lights inside one room bleeding into another, without having to resort into shadow-casting lights.
  826. In light pre-pass and deferred rendering, light culling happens by writing the objects' lightmasks to the stencil buffer during G-buffer rendering, and comparing the stencil buffer to the light's light mask when rendering light volumes. In this case lightmasks are limited to the low 8 bits only.
  827. \section Lights_ShadowedLights Shadowed lights
  828. Shadow rendering is easily the most complex aspect of using lights, and therefore a wide range of per-light parameters exists for controlling the shadows:
  829. - BiasParameters: define constant and slope-scaled depth bias values for preventing self-shadowing artifacts. In practice, need to be determined experimentally. Orthographic (directional) and projective (point and spot) shadows may require rather different bias values. Another way of fighting self-shadowing issues is to render shadowcaster backfaces, see \ref Rendering_Materials "Materials".
  830. - CascadeParameters: these have effect only for directional lights. They specify the far clip distance of each of the cascaded shadow map splits (maximum 4), and the fade start point relative to the maximum shadow range. Unused splits can be set to far clip 0.
  831. - FocusParameters: these have effect for directional and spot lights, and control techniques to increase shadow map resolution. They consist of focus enable flag (allows focusing the shadow camera on the visible shadow casters & receivers), nonuniform scale enable flag (allows better resolution), automatic size reduction flag (reduces shadow map resolution when the light is far away), and quantization & minimum size parameters for the shadow camera view.
  832. Additionally there are shadow fade distance, shadow intensity, shadow resolution and shadow near/far ratio parameters:
  833. - If both shadow distance and shadow fade distance are greater than zero, shadows start to fade at the shadow fade distance, and vanish completely at the shadow distance.
  834. - Shadow intensity defines how dark the shadows are, between 0.0 (maximum darkness, the default) and 1.0 (fully lit.)
  835. - The shadow resolution parameter scales the global shadow map size set in Renderer to determine the actual shadow map size. Maximum is 1.0 (full size) and minimum is 0.125 (one eighth size.) Choose according to the size and importance of the light; smaller shadow maps will be less performance hungry.
  836. - The shadow near/far ratio controls shadow camera near clip distance for point & spot lights. The default ratio is 0.002, which means a light with range 100 would have its shadow camera near plane set at the distance of 0.2. Set this as high as you can for better shadow depth resolution, but note that the bias parameters will likely have to be adjusted as well.
  837. Finally, there are global settings for the shadow map base resolution and shadow map depth (16 or 24 bit) & filtering quality (1 or 4 samples) in Renderer.
  838. \section Lights_ShadowCulling Shadow culling
  839. Similarly to light culling with lightmasks, shadowmasks can be used to select which objects should cast shadows with respect to each light. See \ref Drawable::SetShadowMask "SetShadowMask()". A potential shadow caster's shadow mask will be ANDed with the light's lightmask to see if it should be rendered to the light's shadow map. Also, when an object is inside a zone, its shadowmask will be ANDed with the zone's shadowmask as well. By default all bits are set in the shadowmask.
  840. For an example of shadow culling, imagine a house (which itself is a shadow caster) containing several objects inside, and a shadowed directional light shining in from the windows. In that case shadow map rendering can be avoided for objects already in shadow by clearing the respective bit from their shadowmasks.
  841. \section Lights_ShadowMapReuse Shadow map reuse
  842. The Renderer can be configured to either reuse shadow maps, or not. To reuse is the default, use \ref Renderer::SetReuseShadowMaps "SetReuseShadowMaps()" to change.
  843. When reuse is enabled, only one shadow texture of each shadow map size needs to be reserved, and shadow maps are rendered "on the fly" before rendering a single shadowed light's contribution onto opaque geometry. This has the downside that shadow maps are no longer available during transparent geometry rendering, so transparent objects will not receive shadows.
  844. When reuse is disabled, all shadow maps are rendered before the actual scene rendering. Now multiple shadow textures need to be reserved based on the number of simultaneous shadow casting lights. See the function \ref Renderer::SetNumShadowMaps "SetNumShadowMaps()". If there are not enough shadow textures, they will be assigned to the closest/brightest lights, and the rest will be rendered unshadowed. Now more texture memory is needed, but the advantage is that also transparent objects can receive shadows.
  845. \page SkeletalAnimation Skeletal animation
  846. The AnimatedModel component renders GPU-skinned geometry and is capable of skeletal animation. When a model is assigned to it using \ref AnimatedModel::SetModel "SetModel()", it creates a bone node hierarchy under its scene node, and these bone nodes can be moved and rotated to animate.
  847. There are two ways to play skeletal animations:
  848. - Manually, by adding or removing animation states to the AnimatedModel, and advancing their time positions & weights, see \ref AnimatedModel::AddAnimationState "AddAnimationState()", \ref AnimatedModel::RemoveAnimationState "RemoveAnimationState()", \ref AnimationState::AddTime "AddTime()" and \ref AnimationState::SetWeight "SetWeight()".
  849. - Using the AnimationController helper component: create it into the same scene node as the AnimatedModel, and use its functions, such as \ref AnimationController::Play "Play()" and \ref AnimationController::Stop "Stop()". AnimationController will advance the animations automatically during scene update. It also enables automatic network synchronization of animations, which the AnimatedModel does not do on its own.
  850. Note that AnimationController does not by default stop non-looping animations automatically once they reach the end, so their final pose will stay in effect. Rather they must either be stopped manually, or the \ref AnimationController::SetAutoFade "SetAutoFade()" function can be used to make them automatically fade out once reaching the end.
  851. \section SkeletalAnimation_Blending Animation blending
  852. %Animation blending uses the concept of numbered layers. Layer numbers are unsigned 8-bit integers, and the active \ref AnimationState "AnimationStates" on each layer are processed in order from the lowest layer to the highest. As animations are applied by lerp-blending between absolute bone transforms, the effect is that the higher layer numbers have higher priority, as they will remain in effect last.
  853. By default an Animation is played back by using all the available bone tracks. However an animation can be only partially applied by setting a start bone, see \ref AnimationState::SetStartBone "SetStartBone()". Once set, the bone tracks will be applied hierarchically starting from the start bone. For example, to apply an animation only to a bipedal character's upper body, which is typically parented to the spine bone, one could set the spine as the start bone.
  854. \section SkeletalAnimation_Triggers Animation triggers
  855. Animations can be accompanied with trigger data that contains timestamped Variant data to be interpreted by the application. This trigger data is in XML format next to the animation file itself. When an animation contains triggers, the AnimatedModel's scene node sends the E_ANIMATIONTRIGGER event each time a trigger point is crossed. The event data contains the timestamp, the animation name, and the variant data. Triggers will fire when the animation is advanced using \ref AnimationState::AddTime "AddTime()", but not when setting the absolute animation time position.
  856. The trigger data definition is below. Either normalized (0 = animation start, 1 = animation end) or non-normalized (time in seconds) timestamps can be used. See Bin/Data/Models/Ninja_Walk.xml and Bin/Data/Models/Ninja_Stealth.xml for examples; NinjaSnowWar implements footstep particle effects using animation triggers.
  857. \code
  858. <animation>
  859. <trigger time="t" normalizedtime="t" type="Int|Bool|Float|String..." value="x" />
  860. <trigger ... />
  861. </animation>
  862. \endcode
  863. \section SkeletalAnimation_ManualControl Manual bone control
  864. By default an AnimatedModel's bone nodes are reset on each frame, after which all active animation states are applied to the bones. This mechanism can be turned off per-bone basis to allow manual bone control. To do this, query a bone from the AnimatedModel's skeleton and set its \ref Bone::animated_ "animated_" member variable to false. For example:
  865. \code
  866. Bone* headBone = model->GetSkeleton().GetBone("Bip01_Head");
  867. if (headBone)
  868. headBone->animated_ = false;
  869. \endcode
  870. \section SkeletalAnimation_CombinedModels Combined skinned models
  871. To create a combined skinned model from many parts (for example body + clothes), several AnimatedModel components can be created to the same scene node. These will then share the same bone nodes. The component that was first created will be the "master" model which drives the animations; the rest of the models will just skin themselves using the same bones. For this to work, all parts must have been authored from a compatible skeleton, with the same bone names. The master model should have all the bones required by the combined whole (for example a full biped), while the other models may omit unnecessary bones. Note that if the parts contain compatible vertex morphs (matching names), the vertex morph weights will also be controlled by the master model and copied to the rest.
  872. \section SkeletalAnimation_NodeAnimation Node animations
  873. Animations can also be applied outside of an AnimatedModel's bone hierarchy, to control the transforms of named nodes in the scene. The AssetImporter utility will automatically save node animations in both model or scene modes to the output file directory.
  874. Like with skeletal animations, there are two ways to play back node animations:
  875. - Instantiate an AnimationState yourself, using the constructor which takes a root scene node (animated nodes are searched for as children of this node) and an animation pointer. You need to manually advance its time position, and then call \ref AnimationState::Apply "Apply()" to apply to the scene nodes.
  876. - Create an AnimationController component to the root scene node of the animation. This node should not contain an AnimatedModel component. Use the AnimationController to play back the animation just like you would play back a skeletal animation.
  877. %Node animations do not support blending, as there is no initial pose to blend from. Instead they are always played back with full weight. Note that the scene node names in the animation and in the scene must match exactly, otherwise the animation will not play.
  878. \page Particles %Particle systems
  879. The ParticleEmitter class derives from BillboardSet to implement a particle system that updates automatically.
  880. The parameters of the particle system are stored in a ParticleEffect resource class, which uses XML format. Call \ref ParticleEmitter::SetEffect "SetEffect()" to assign the effect resource to the emitter. Most of the parameters can take either a single value, or minimum and maximum values to allow for random variation. See below for all supported parameters:
  881. \code
  882. <particleemitter>
  883. <material name="MaterialName" />
  884. <updateinvisible enable="true|false" />
  885. <relative enable="true|false" />
  886. <scaled enable="true|false" />
  887. <sorted enable="true|false" />
  888. <emittertype value="sphere|box" />
  889. <emittersize value="x y z" />
  890. <emitterradius value="x" />
  891. <direction min="x1 y1 z1" max="x2 y2 z2" />
  892. <constantforce value="x y z" />
  893. <dampingforce value="x" />
  894. <activetime value="t" />
  895. <inactivetime value="t" />
  896. <interval min="t1" max="t2" />
  897. <emissionrate min="t1" max="t2" />
  898. <particlesize min="x1 y1" max="x2 y2" />
  899. <timetolive min="t1" max="t2" />
  900. <velocity min="x1" max="x2" />
  901. <rotation min="x1" max="x2" />
  902. <rotationspeed min="x1" max="x2" />
  903. <sizedelta add="x" mul="y" />
  904. <color value="r g b a" />
  905. <colorfade color="r g b a" time="t" />
  906. <texanim uv="u1 v1 u2 v2" time="t" />
  907. </particleemitter>
  908. \endcode
  909. Notes:
  910. - Zero active or inactive time period means infinite.
  911. - Interval is the reciprocal of emission rate. Either can be used to define the rate at which new particles are emitted.
  912. - Instead of defining a single color element, several colorfade elements can be defined in time order to describe how the particles change color over time.
  913. - Use several texanim elements to define a texture animation for the particles.
  914. \page Zones Zones
  915. A Zone controls ambient lighting and fogging. Each geometry object determines the zone it is inside (by testing against the zone's oriented bounding box) and uses that zone's ambient light color, fog color and fog start/end distance for rendering. For the case of multiple overlapping zones, zones also have an integer priority value, and objects will choose the highest priority zone they touch.
  916. The viewport will be initially cleared to the fog color of the zone found at the camera's far clip distance. If no zone is found either for the far clip or an object, a default zone with black ambient and fog color will be used.
  917. Zones have three special flags: height fog mode, override mode and ambient gradient.
  918. - When height fog mode is enabled, objects inside the zone receive height fog in addition of distance fog. The fog's \ref Zone::SetFogHeight "height level" is specified relative to the zone's world position. The width of the fog band on the Y-axis is specified by the \ref Zone::SetFogHeightScale "fog height scale" parameter.
  919. - If the camera is inside a zone with override mode enabled, all rendered objects will use that zone's ambient and fog settings, instead of the zone they belong to. This can be used for example to implement an underwater effect.
  920. - When ambient gradient mode is enabled, the zone's own ambient color value is not used, but instead it will look for two highest-priority neighbor zones that touch it at the minimum and maximum Z face of its oriented bounding box: any objects inside will then get a per-vertex ambient color fade between the neighbor zones' ambient colors. To ensure objects use the gradient zone when inside it, the gradient zone should have higher priority than the neighbor zones. The gradient is always oriented along the gradient zone's local Z axis.
  921. Like lights, zones also define a lightmask and a shadowmask (with all bits set by default.) An object's final lightmask for light culling is determined by ANDing the object lightmask and the zone lightmask. The final shadowmask is also calculated in the same way.
  922. Finally, zones can optionally define a texture, see \ref Zone::SetZoneTexture "SetZoneTexture()". This should be either a cube or 3D texture that will be bound to the zone texture unit (TU_ZONE) when rendering objects within the zone. This could be used to achieve for example precomputed environment reflections, ambient lighting or ambient occlusion in custom shaders; the default shaders do not use this texture. Due to texture unit limitations it is not available on OpenGL ES 2.0.
  923. \page AuxiliaryViews Auxiliary views
  924. Auxiliary views are viewports assigned to a RenderSurface by calling its \ref RenderSurface::SetViewport "SetViewport()" function. By default these will be rendered on each frame that the texture containing the surface is visible, and can be typically used to implement for example camera displays or reflections. The texture in question must have been created in rendertarget mode, see Texture's \ref Texture2D::SetSize "SetSize()" function.
  925. The viewport is not assigned directly to the texture because of cube map support: a renderable cube map has 6 render surfaces, and done this way, a different camera could be assigned to each.
  926. A "backup texture" can be assigned to the rendertarget texture: because it is illegal to sample a texture that is also being simultaneously rendered to (in cases where the texture becomes "recursively" visible in the auxiliary view), the backup texture can be used to specify which texture should be used in place instead.
  927. Rendering detailed auxiliary views can easily have a large performance impact. Some things you can do for optimization with the auxiliary view camera:
  928. - Set the far clip distance as small as possible.
  929. - Use viewmasks on the camera and the scene objects to only render some of the objects in the auxiliary view.
  930. - Use the camera's \ref Camera::SetViewOverrideFlags "SetViewOverrideFlags()" function to disable shadows, to disable occlusion, or force the lowest material quality.
  931. The surface can also be configured to always update its viewports, or to only update when manually requested. See \ref RenderSurface::SetUpdateMode "SetUpdateMode()". For example an editor widget showing a rendered texture might use either of those modes. Call \ref RenderSurface::QueueUpdate "QueueUpdate()" to request a manual update of the surface on the current frame.
  932. \page Input %Input
  933. The Input subsystem provides keyboard, mouse, joystick and touch input both via a polled interface and events. This subsystem is also used for querying whether the application window has input focus or is minimized.
  934. The subsystem is always instantiated, even in headless mode, but is active only once the application window has been created. Once active, the subsystem takes over the operating system mouse cursor. It will be hidden by default, so the UI should be used to render a software cursor if necessary. For editor-like applications the operating system cursor can be made visible by calling \ref Input::SetMouseVisible "SetMouseVisible()".
  935. The input events include:
  936. - E_MOUSEBUTTONUP: a mouse button was released.
  937. - E_MOUSEBUTTONDOWN: a mouse button was pressed.
  938. - E_MOUSEMOVE: the mouse moved.
  939. - E_MOUSEWHEEL: the mouse wheel moved.
  940. - E_KEYUP: a key was released.
  941. - E_KEYDOWN: a key was pressed.
  942. - E_TEXTINPUT: a string of translated text input in UTF8 format. May contain a single character or several.
  943. - E_JOYSTICKCONNECTED: a joystick was plugged in.
  944. - E_JOYSTICKDISCONNECTED: a joystick was disconnected.
  945. - E_JOYSTICKBUTTONDOWN: a joystick button was pressed.
  946. - E_JOYSTICKBUTTONUP: a joystick button was released.
  947. - E_JOYSTICKAXISMOVE: a joystick axis was moved.
  948. - E_JOYSTICKHATMOVE: a joystick POV hat was moved.
  949. - E_TOUCHBEGIN: a finger touched the screen.
  950. - E_TOUCHEND: a finger was lifted from the screen.
  951. - E_TOUCHMOVE: a finger moved on the screen.
  952. - E_GESTURERECORDED : recording a touch gesture is complete.
  953. - E_GESTUREINPUT : a touch gesture was recognized.
  954. - E_MULTIGESTURE : a multi-finger pinch/rotation touch gesture is underway.
  955. - E_DROPFILE : a file was drag-dropped on the application window.
  956. - E_INPUTFOCUS : application input focus or window minimization state changed.
  957. - E_MOUSEVISIBLECHANGED : the visibility of the operating system mouse cursor was changed.
  958. - E_EXITREQUESTED : application exit was requested (eg. with the window close button.)
  959. \section InputKeyboard Keyboard and mouse input
  960. Key events include both the symbolic keycode ("Key") that depends on the keyboard layout, the layout- and operating system-independent SDL scancode ("Scancode"), and the true operating system-specific raw keycode ("Raw").
  961. The input polling API differentiates between the initiation of a key/mouse button press, and holding the key or button down. \ref Input::GetKeyPress "GetKeyPress()" and \ref Input::GetMouseButtonPress "GetMouseButtonPress()" return true only for one frame (the initiation) while \ref Input::GetKeyDown "GetKeyDown()" and \ref Input::GetMouseButtonDown "GetMouseButtonDown()" return true as long as the key or button is held down. To check whether keys are down or pressed by scancode, use \ref Input::GetScancodeDown "GetScancodeDown()" and \ref Input::GetScancodePress "GetScancodePress()". Functions also exist for converting keycodes to scancodes or vice versa, or getting key names. See for example \ref Input::GetKeyName "GetKeyName()" and \ref Input::GetKeyFromScancode "GetKeyFromScancode()".
  962. Mouse motion since the last frame can be accessed with \ref Input::GetMouseMove() "GetMouseMove()". The cursor position within the window can be queried with \ref Input::GetMousePosition "GetMousePosition()".
  963. In AngelScript, the polling API is accessed via properties: input.keyDown[], input.keyPress[], input.scancodeDown[], input.scancodePress[], input.mouseButtonDown[], input.mouseButtonPress[], input.mouseMove, input.mousePosition.
  964. \section InputMouseModes Mouse modes
  965. The operating system mouse cursor can be used in three modes which can be switched with \ref Input::SetMouseMode() "SetMouseMode()".
  966. - MM_ABSOLUTE is the default behaviour, allowing the toggling of operating system cursor visibility and allowing the cursor to escape the window when visible.
  967. When the operating system cursor is invisible in absolute mouse mode, the mouse is confined to the window.
  968. If the operating system and %UI cursors are both invisible, interaction with the \ref UI "user interface" will be limited (eg: drag move / drag end events will not trigger).
  969. SetMouseMode(MM_ABSOLUTE) will call SetMouseGrabbed(false).
  970. - MM_RELATIVE sets the operating system cursor to invisible and confines the cursor to the window.
  971. The operating system cursor cannot be set to be visible in this mode via SetMouseVisible(), however changes are tracked and will be restored when another mouse mode is set.
  972. When the virtual cursor is also invisible, %UI interaction will still function as normal (eg: drag events will trigger).
  973. SetMouseMode(MM_RELATIVE) will call SetMouseGrabbed(true).
  974. - MM_WRAP grabs the mouse from the operating system and confines the operating system cursor to the window, wrapping the cursor when it is near the edges.
  975. SetMouseMode(MM_WRAP) will call SetMouseGrabbed(true).
  976. \section InputJoystick Joystick input
  977. Plugged in joysticks will begin sending input events automatically. Each joystick will be assigned a joystick ID which will be used in subsequent joystick events, as well as for retrieving the \ref JoystickState "joystick state". Use \ref Input::GetJoystick "GetJoystick()" to retrieve the joystick state by ID. In case you do not have the ID, you can also use \ref Input::GetJoystickByIndex() "GetJoystickByIndex()" which uses a zero-based index; see \ref Input::GetNumJoysticks "GetNumJoysticks()" for the number of currently connected joysticks. The ID, as well as the joystick name, can be looked up from the joystick state.
  978. If the joystick model is recognized by SDL as a game controller the buttons and axes mappings utilize known constants such as CONTROLLER_BUTTON_A or CONTROLLER_AXIS_LEFTX without having to guess them. Use \ref JoystickState::IsController "IsController()" to distinguish between a game controller and an unrecognized joystick.
  979. On platforms that support the accelerometer, it will appear as a "virtual" joystick.
  980. \section InputTouch Touch input
  981. On platforms where touch input is available, touch begin/end/move events will be sent, as well as multi-gesture events with pinch/rotation delta values when more than one finger is pressed down. The current finger touches can also be accessed via a polling API: \ref Input::GetNumTouches "GetNumTouches()" and \ref Input::GetTouch "GetTouch()".
  982. Touch gestures can be recorded using SDL's inbuilt $1 gesture recognition system. Use \ref Input::RecordGesture "RecordGesture()" to start recording. The following finger movements will be recorded until the finger is lifted, at which point the recording ends and the E_GESTURERECORDED event is sent with the hash ID of the new gesture. The current in-memory gesture(s) can be saved or loaded as binary data using the \ref Input::SaveGestures "SaveGestures()", \ref Input::SaveGesture "SaveGesture()", \ref Input::LoadGestures "LoadGestures()" functions.
  983. Whenever a recognized gesture is entered by the user, the E_GESTUREINPUT event will be sent. In addition to the ID of the best matched gesture, it contains the center position and an error metric (lower = better) to help filter out false gestures.
  984. Note that all recorded (whether saved or not) and loaded gestures are held in-memory. Two additional functions are available to clear them: \ref Input::RemoveGesture "RemoveGesture()" to selectively clear a gesture by its ID and \ref Input::RemoveAllGestures "RemoveAllGestures()" to clear them all.
  985. Touch input can also emulate a virtual joystick by displaying on-screen buttons. See the function \ref Input::AddScreenJoystick "AddScreenJoystick()".
  986. Touch emulation can be used to test mobile applications on a desktop machine without a touch screen. See \ref Input::SetTouchEmulation "SetTouchEmulation()". When touch emulation is enabled, actual mouse events are no longer sent and the operating system mouse cursor is forced visible. The left mouse button acts as a moving finger, while the rest of the mouse buttons act as stationary fingers for multi-finger gestures. For example pressing down both left and right mouse buttons, then dragging the mouse with the buttons still pressed would emulate a two-finger pinch zoom-in gesture.
  987. \section InputPlatformSpecific Platform-specific details
  988. On platforms that support it (such as Android) an on-screen virtual keyboard can be shown or hidden. When shown, keypresses from the virtual keyboard will be sent as text input events just as if typed from an actual keyboard. Show or hide it by calling \ref Input::SetScreenKeyboardVisible "SetScreenKeyboardVisible()". The UI subsystem can also automatically show the virtual keyboard when a LineEdit element is focused, and hide it when defocused. This behavior can be controlled by calling \ref UI::SetUseScreenKeyboard "SetUseScreenKeyboard()".
  989. On Windows the user must first touch the screen once before touch input is activated. Trying to record or load touch gestures will fail before that.
  990. \page Audio %Audio
  991. The Audio subsystem implements an audio output stream. Once it has been initialized, the following operations are supported:
  992. - Playing raw audio, Ogg Vorbis or WAV Sound resources using the SoundSource component. This allows manual stereo panning of mono sounds; stereo sounds will be output with their original stereo mix.
  993. - Playing the above sound formats in pseudo-3D using the SoundSource3D component. It has stereo positioning and distance attenuation, but does not (at least yet) filter the sound depending on the direction.
  994. To hear pseudo-3D positional sounds, a SoundListener component must exist in a scene node and be assigned to the audio subsystem by calling \ref Audio::SetListener "SetListener()". If the sound listener's scene node exists within a specific scene, it will only hear sounds from that scene, but if it has been created into a "sceneless" node it will hear sounds from all scenes.
  995. The output is software mixed for an unlimited amount of simultaneous sounds. Ogg Vorbis sounds are decoded on the fly, and decoding them can be memory- and CPU-intensive, so WAV files are recommended when a large number of short sound effects need to be played.
  996. For purposes of volume control, each SoundSource is classified into one of four categories:
  997. - %Sound effects
  998. - Ambient
  999. - Music
  1000. - Voice
  1001. A master gain category also exists that affects the final output level. To control the category volumes, use \ref Audio::SetMasterGain "SetMasterGain()".
  1002. The SoundSource components support automatic removal from the node they belong to, once playback is finished. To use, call \ref SoundSource::SetAutoRemove "SetAutoRemove()" on them. This may be useful when a game object plays several "fire and forget" sound effects.
  1003. \section Audio_Parameters Sound parameters
  1004. A standard WAV file can not tell whether it should loop, and raw audio does not contain any header information. Parameters for the Sound resource can optionally be specified through an XML file that has the same name as the sound, but .xml extension. Possible elements and attributes are described below:
  1005. \code
  1006. <sound>
  1007. <format frequency="x" sixteenbit="true|false" stereo="true|false" />
  1008. <loop enable="true|false" start="x" end="x" />
  1009. </sound>
  1010. \endcode
  1011. The frequency is in Hz, and loop start and end are bytes from the start of audio data. If a loop is enabled without specifying the start and end, it is assumed to be the whole sound. Ogg Vorbis compressed sounds do not support specifying the loop range, only whether whole sound looping is enabled or disabled.
  1012. The Audio subsystem is always instantiated, but in headless mode it is not active. In headless mode the playback of sounds is simulated, taking the sound length and frequency into account. This allows basing logic on whether a specific sound is still playing or not, even in server code.
  1013. \section Audio_Stream Sound streaming
  1014. In addition to playing existing sound resources, sound can be generated during runtime using the SoundStream class and its subclasses. To start playback of a stream on a SoundSource, call \ref SoundSource::Play(SoundStream* stream) "Play(SoundStream* stream)".
  1015. %Sound streaming is used internally to implement on-the-fly Ogg Vorbis decoding. It is only available in C++ code and not scripting due to its low-level nature. See the SoundSynthesis C++ sample for an example of using the BufferedSoundStream subclass, which allows the sound data to be queued for playback from the main thread.
  1016. \page Physics Physics
  1017. Urho3D implements rigid body physics simulation using the Bullet library.
  1018. To use, a PhysicsWorld component must first be created to the Scene.
  1019. The physics simulation has its own fixed update rate, which by default is 60Hz. When the rendering framerate is higher than the physics update rate, physics motion is interpolated so that it always appears smooth. The update rate can be changed with \ref PhysicsWorld::SetFps "SetFps()" function. The physics update rate also determines the frequency of fixed timestep scene logic updates. Hard limit for physics steps per frame or adaptive timestep can be configured with \ref PhysicsWorld::SetMaxSubSteps "SetMaxSubSteps()" function. These can help to prevent a "spiral of death" due to the CPU being unable to handle the physics load. However, note that using either can lead to time slowing down (when steps are limited) or inconsistent physics behavior (when using adaptive step.)
  1020. The other physics components are:
  1021. - RigidBody: a physics object instance. Its parameters include mass, linear/angular velocities, friction and restitution.
  1022. - CollisionShape: defines physics collision geometry. The supported shapes are box, sphere, cylinder, capsule, cone, triangle mesh, convex hull and heightfield terrain (requires the Terrain component in the same node.)
  1023. - Constraint: connects two RigidBodies together, or one RigidBody to a static point in the world. Point, hinge, slider and cone twist constraints are supported.
  1024. \section Physics_Movement Movement and collision
  1025. Both a RigidBody and at least one CollisionShape component must exist in a scene node for it to behave physically (a collision shape by itself does nothing.) Several collision shapes may exist in the same node to create compound shapes. An offset position and rotation relative to the node's transform can be specified for each. Triangle mesh and convex hull geometries require specifying a Model resource and the LOD level to use.
  1026. CollisionShape provides two APIs for defining the collision geometry. Either setting individual properties such as the \ref CollisionShape::SetShapeType "shape type" or \ref CollisionShape::SetSize "size", or specifying both the shape type and all its properties at once: see for example \ref CollisionShape::SetBox "SetBox()", \ref CollisionShape::SetCapsule "SetCapsule()" or \ref CollisionShape::SetTriangleMesh "SetTriangleMesh()".
  1027. RigidBodies can be either static or moving. A body is static if its mass is 0, and moving if the mass is greater than 0. Note that the triangle mesh collision shape is not supported for moving objects; it will not collide properly due to limitations in the Bullet library. In this case the convex hull shape can be used instead.
  1028. The collision behaviour of a rigid body is controlled by several variables. First, the collision layer and mask define which other objects to collide with: see \ref RigidBody::SetCollisionLayer "SetCollisionLayer()" and \ref RigidBody::SetCollisionMask "SetCollisionMask()". By default a rigid body is on layer 1; the layer will be ANDed with the other body's collision mask to see if the collision should be reported. A rigid body can also be set to \ref RigidBody::SetTrigger "trigger mode" to only report collisions without actually applying collision forces. This can be used to implement trigger areas. Finally, the \ref RigidBody::SetFriction "friction", \ref RigidBody::SetRollingFriction "rolling friction" and \ref RigidBody::SetRestitution "restitution" coefficients (between 0 - 1) control how kinetic energy is transferred in the collisions. Note that rolling friction is by default zero, and if you want for example a sphere rolling on the floor to eventually stop, you need to set a non-zero rolling friction on both the sphere and floor rigid bodies.
  1029. By default rigid bodies can move and rotate about all 3 coordinate axes when forces are applied. To limit the movement, use \ref RigidBody::SetLinearFactor "SetLinearFactor()" and \ref RigidBody::SetAngularFactor "SetAngularFactor()" and set the axes you wish to use to 1 and those you do not wish to use to 0. For example moving humanoid characters are often represented by a capsule shape: to ensure they stay upright and only rotate when you explicitly set the rotation in code, set the angular factor to 0, 0, 0.
  1030. To prevent tunneling of a fast moving rigid body through obstacles, continuous collision detection can be used. It approximates the object as a swept sphere, but has a performance cost, so it should be used only when necessary. Call \ref RigidBody::SetCcdRadius "SetCcdRadius()" and \ref RigidBody::SetCcdMotionThreshold "SetCcdMotionThreshold()" with non-zero values to enable. To prevent false collisions, the body's actual collision shape should completely contain the radius. The motion threshold is the required motion per simulation step for CCD to kick in: for example a box with size 1 should have motion threshold 1 as well.
  1031. All physics calculations are performed in world space. Nodes containing a RigidBody component should preferably be parented to the Scene (root node) to ensure independent motion. For ragdolls this is not absolute, as retaining proper bone hierarchy is more important, but be aware that the ragdoll bones may drift far from the animated model's root scene node.
  1032. When several collision shapes are present in the same node, edits to them can cause redundant mass/inertia update computation in the RigidBody. To optimize performance in these cases, the edits can be enclosed between calls to \ref RigidBody::DisableMassUpdate "DisableMassUpdate()" and \ref RigidBody::EnableMassUpdate "EnableMassUpdate()".
  1033. \section Physics_ConstraintParameters Constraint parameters
  1034. %Constraint position (and rotation if relevant) need to be defined in relation to both connected bodies, see \ref Constraint::SetPosition "SetPosition()" and \ref Constraint::SetOtherPosition "SetOtherPosition()". If the constraint connects a body to the static world, then the "other body position" and "other body rotation" mean the static end's transform in world space. There is also a helper function \ref Constraint::SetWorldPosition "SetWorldPosition()" to assign the constraint to a world-space position; this sets both relative positions.
  1035. Specifying the constraint's motion axis instead of rotation is provided as an alternative as it can be more intuitive, see \ref Constraint::SetAxis "SetAxis()". However, by explicitly specifying a rotation you can be sure the constraint is oriented precisely as you want.
  1036. Hinge, slider and cone twist constraints support defining limits for the motion. To be generic, these are encoded slightly unintuitively into Vector2's. For a hinge constraint, the low and high limit X coordinates define the minimum and maximum angle in degrees. For example -45 to 45. For a slider constraint, the X coordinates define the maximum linear motion in world space units, and the Y coordinates define maximum angular motion in degrees. The cone twist constraint uses only the high limit to define the maximum angles (minimum angle is always -maximum) in the following manner: The X coordinate is the limit of the twist (main) axis, while Y is the limit of the swinging motion about the other axes.
  1037. \section Physics_Events Physics events
  1038. The physics world sends 8 types of events during its update step:
  1039. - E_PHYSICSPRESTEP before the simulation is stepped.
  1040. - E_PHYSICSCOLLISIONSTART for each new collision during the simulation step. The participating scene nodes will also send E_NODECOLLISIONSTART events.
  1041. - E_PHYSICSCOLLISION for each ongoing collision during the simulation step. The participating scene nodes will also send E_NODECOLLISION events.
  1042. - E_PHYSICSCOLLISIONEND for each collision which has ceased. The participating scene nodes will also send E_NODECOLLISIONEND events.
  1043. - E_PHYSICSPOSTSTEP after the simulation has been stepped.
  1044. Note that if the rendering framerate is high, the physics might not be stepped at all on each frame: in that case those events will not be sent.
  1045. \section Physics_Collision Reading collision events
  1046. A new or ongoing physics collision event will report the collided scene nodes and rigid bodies, whether either of the bodies is a trigger, and the list of contact points.
  1047. The contact points are encoded in a byte buffer, which can be read using the VectorBuffer or MemoryBuffer helper class. The following structure repeats for each contact:
  1048. - World-space position (Vector3)
  1049. - Normal vector (Vector3)
  1050. - Distance, negative when interpenetrating (float)
  1051. - Impulse applied in collision (float)
  1052. An example of reading collision event and contact point data in script, from NinjaSnowWar game object collision handling code:
  1053. \code
  1054. void HandleNodeCollision(StringHash eventType, VariantMap& eventData)
  1055. {
  1056. Node@ otherNode = eventData["OtherNode"].GetPtr();
  1057. RigidBody@ otherBody = eventData["OtherBody"].GetPtr();
  1058. VectorBuffer contacts = eventData["Contacts"].GetBuffer();
  1059. while (!contacts.eof)
  1060. {
  1061. Vector3 contactPosition = contacts.ReadVector3();
  1062. Vector3 contactNormal = contacts.ReadVector3();
  1063. float contactDistance = contacts.ReadFloat();
  1064. float contactImpulse = contacts.ReadFloat();
  1065. // Do something with the contact data...
  1066. }
  1067. }
  1068. \endcode
  1069. \section Physics_Queries Physics queries
  1070. The following queries into the physics world are provided:
  1071. - Raycasts, see \ref PhysicsWorld::Raycast "Raycast()" and \ref PhysicsWorld::RaycastSingle "RaycastSingle()".
  1072. - %Sphere cast (raycast with thickness), see \ref PhysicsWorld::SphereCast "SphereCast()".
  1073. - %Sphere and box overlap tests, see \ref PhysicsWorld::GetRigidBodies() "GetRigidBodies()".
  1074. - Which other rigid bodies are colliding with a body, see \ref RigidBody::GetCollidingBodies() "GetCollidingBodies()". In script this maps into the collidingBodies property.
  1075. \page Navigation Navigation
  1076. Urho3D implements navigation mesh generation and pathfinding by using the Recast & Detour libraries.
  1077. The navigation functionality is exposed through the NavigationMesh and Navigable components.
  1078. NavigationMesh collects geometry from its child nodes that have been tagged with the Navigable component. By default the Navigable component behaves recursively: geometry from its child nodes will be collected too, unless the recursion is disabled. If possible, physics CollisionShape geometry is preferred, however only the triangle mesh, convex hull and box shapes are supported. If no suitable physics geometry is found from a node, static drawable geometry is used instead from StaticModel and TerrainPatch components if they exist. The LOD level used is the same as for occlusion and raycasts (see \ref StaticModel::SetOcclusionLodLevel "SetOcclusionLodLevel()".
  1079. The easiest way to make the whole scene participate in navigation mesh generation is to create the %NavigationMesh and %Navigable components to the scene root node.
  1080. The navigation mesh generation must be triggered manually by calling \ref NavigationMesh::Build "Build()". After the initial build, portions of the mesh can also be rebuilt by specifying a world bounding box for the volume to be rebuilt, but this can not expand the total bounding box size. Once the navigation mesh is built, it will be serialized and deserialized with the scene.
  1081. To query for a path between start and end points on the navigation mesh, call \ref NavigationMesh::FindPath "FindPath()".
  1082. For a demonstration of the navigation capabilities, check the related sample application (Bin/Data/Scripts/15_Navigation.as), which features partial navigation mesh rebuilds (objects can be created and deleted) and querying paths.
  1083. \page UI User interface
  1084. Urho3D implements a simple, hierarchical user interface system based on rectangular elements. The elements provided are:
  1085. - BorderImage: a texture image with an optional border
  1086. - Button: a pushbutton
  1087. - CheckBox: a button that can be toggled on/off
  1088. - Cursor: a mouse cursor
  1089. - DropDownList: shows a vertical list of items (optionally scrollable) as a popup
  1090. - LineEdit: a single-line text editor
  1091. - ListView: shows a scrollable vertical list of items
  1092. - Menu: a button which can show a popup element
  1093. - ScrollBar: a slider with back and forward buttons
  1094. - ScrollView: a scrollable view of child elements
  1095. - Slider: a horizontal or vertical slider bar
  1096. - Sprite: a texture image which supports subpixel positioning, scaling and rotating.
  1097. - Text: static text that can be multiline
  1098. - ToolTip: a popup which automatically displays itself when the cursor hovers on its parent element.
  1099. - UIElement: container for other elements, renders nothing by itself
  1100. - View3D: a window that renders a 3D viewport
  1101. - Window: a movable and resizable window
  1102. The root %UI element can be queried from the UI subsystem. It is an empty canvas (UIElement) as large as the application window, into which other elements can be added.
  1103. Elements are added into each other similarly as scene nodes, using the \ref UIElement::AddChild "AddChild()" and \ref UIElement::RemoveChild "RemoveChild()" functions. Each %UI element has also a \ref UIElement::GetVars "user variables" VariantMap for storing custom data.
  1104. To allow the elements react to mouse input, either a mouse cursor element must be defined using \ref UI::SetCursor "SetCursor()" or the operating system mouse cursor must be set visible from the Input subsystem.
  1105. \section UI_Textures UI textures
  1106. The BorderImage and elements deriving from it specify a texture and an absolute pixel rect within it to use for rendering; see \ref BorderImage::SetTexture "SetTexture()" and \ref BorderImage::SetImageRect "SetImageRect()". The texture is modulated with the element's color. To allow for more versatile scaling the element can be divided into 9 sub-quads or patches by specifying the width of each of its borders, see \ref BorderImage::SetBorder "SetBorder()". Setting zero borders (the default) causes the element to be drawn as one quad.
  1107. The absolute pixel rects interact poorly with the Renderer's texture quality setting, which reduces texture sizes by skipping the topmost mipmaps. Generating mipmaps is also often unnecessary for %UI textures, as they are usually displayed with 1:1 ratio on the screen. Therefore it's a good practice to use the following accompanying settings XML file for %UI textures to disable quality reduction and mipmaps:
  1108. \code
  1109. <texture>
  1110. <mipmap enable="false" />
  1111. <quality low="0" />
  1112. </texture>
  1113. \endcode
  1114. \section UI_Defining Defining UI elements in XML
  1115. User interface elements derive from Serializable, so they can be serialized to/from XML using their attributes. There are two distinct use cases for %UI definition files: either defining just the %UI element style and leaving the actual position and dimensions to be filled in later, or fully defining an %UI element layout. The default element style definitions, used for example by the editor and the debug console, are in the file Bin/Data/UI/DefaultStyle.xml.
  1116. The function \ref UI::LoadLayout "LoadLayout()" in UI will take an XML file and instantiate the elements defined in it. To be valid XML, there should be one root-level %UI element. An optional style XML file can be specified; the idea is to first read the element's style from that file, then fill in the rest from the actual layout XML file. This way the layout file can be relatively simple, as the majority of the data is already defined.
  1117. Note that a style can not be easily applied recursively to the loaded elements afterward. Therefore remember to specify the style file already when loading, or alternatively \ref UIElement::SetDefaultStyle "assign a default style file" to the %UI root element, which will then be picked up by all loaded layouts. This works because the %UI subsystem searches the style file by going up the parental chain starting from target parent %UI element. The search stops immediately when a style file is found or when it has reached the root element. Also note that Urho3D does not limit the number of style files being used at the same time in an application. You may have different style file set along the %UI parental hierarchy, if your application needs that.
  1118. See the elements' C++ code for all supported attributes, and look at the editor's user interface layouts in the Bin/Data/UI directory for examples. You can also use the Editor application to create %UI layouts. The serialization format is similar to scene XML serialization, with three important differences:
  1119. 1) The element type to instantiate, and the style to use for it can be set separately. For example the following element definition
  1120. \code
  1121. <element type="Button" style="CloseButton" />
  1122. \endcode
  1123. tells to instantiate a Button element, and that it should use the style "CloseButton" defined in the style XML file.
  1124. 2) Internal child elements, for example the scroll bars of a ScrollView, need to be marked as such to avoid instantiating them as duplicates. This is done by adding the attribute internal="true" to the XML element, and is required in both layout and style XML files. Furthermore, the elements must be listed in the order they have been added as children of the parent element (if in doubt, see the element's C++ constructor code. Omitting elements in the middle is OK.) For example:
  1125. \code
  1126. <element type="ScrollView" />
  1127. <element type="ScrollBar" internal="true" />
  1128. ...customize the horizontal scroll bar attributes here...
  1129. </element>
  1130. <element type="ScrollBar" internal="true" />
  1131. ...customize the vertical scroll bar attributes here...
  1132. </element>
  1133. </element>
  1134. \endcode
  1135. 3) The popup element shown by Menu and DropDownList is not an actual child element. In XML serialization, it is nevertheless stored as a child element, but is marked with the attribute popup="true".
  1136. \section UI_Layouts UI element layout
  1137. By default %UI elements operate in a "free" layout mode, where child elements' positions can be specified relative to any of the parent element corners, but they are not automatically positioned or resized.
  1138. To create automatically adjusting layouts, the layout mode can be switched to either "horizontal" or "vertical". Now the child elements will be positioned left to right or top to bottom, based on the order in which they were added. They will be preferably resized to fit the parent element, taking into account their minimum and maximum sizes, but failing to do that, the parent element will be resized.
  1139. Left, top, right & bottom border widths and spacing between elements can also be specified for the layout. A grid layout is not directly supported, but it can be manually created with a horizontal layout inside a vertical layout, or vice versa.
  1140. \section UI_Fonts Fonts
  1141. Urho3D supports both FreeType (.ttf, .otf) and \ref http://www.angelcode.com/products/bmfont/ "bitmap" fonts.
  1142. For FreeType fonts, it is possible to adjust the positioning of the font glyphs. See \ref Font::SetAbsoluteGlyphOffset "SetAbsoluteGlyphOffset()" to set a fixed pixel offset for all point sizes, or \ref Font::SetScaledGlyphOffset "SetScaledGlyphOffset()" to set a floating point offset that will be multiplied with the point size before applying. The offset information can be also stored in an accompanying XML file next to the font file, which is formatted in the following way: (it is legal to specify either or both of absolute and scaled offsets, and either or both of X & Y coordinates)
  1143. \code
  1144. <font>
  1145. <absoluteoffset x="xInt" y="yInt" />
  1146. <scaledoffset x="xFloat" y="yFloat" />
  1147. </font>
  1148. \endcode
  1149. \section UI_Sprites Sprites
  1150. Sprites are a special kind of %UI element that allow subpixel (float) positioning and scaling, as well as rotation, while the other elements use integer positioning for pixel-perfect display. Sprites can be used to implement rotating HUD elements such as minimaps or speedometer needles.
  1151. Due to the free transformability, sprites can not be reliably queried with \ref UI::GetElementAt "GetElementAt()". Also, only other sprites should be parented to sprites, as the other elements do not support scaling and rotation.
  1152. \page Urho2D Urho2D
  1153. In order to make 2D games in Urho3D, the Urho2D sublibrary is provided. Urho2D includes 2D graphics and 2D physics.
  1154. A typical 2D game setup would consist of the following:
  1155. - Create an orthographic camera
  1156. - Create some sprites
  1157. - Use physics and constraints to interact with the scene
  1158. \section Urho2D_Orthographic Orthographic camera
  1159. In order to use Urho2D we need to set camera to orthographic mode first; it can be done with following code:
  1160. C++:
  1161. \code
  1162. // Create camera node
  1163. Node* cameraNode = scene_->CreateChild("Camera");
  1164. // Create camera
  1165. Camera* camera = cameraNode->CreateComponent<Camera>();
  1166. // Set camera orthographic
  1167. camera->SetOrthographic(true);
  1168. // Set camera ortho size (the value of PIXEL_SIZE is 0.01)
  1169. camera->SetOrthoSize((float)graphics->GetHeight() * PIXEL_SIZE);
  1170. \endcode
  1171. AngelScript:
  1172. \code
  1173. // Create camera node
  1174. Node@ cameraNode = scene_.CreateChild("Camera");
  1175. // Create camera
  1176. Camera@ camera = cameraNode.CreateComponent("Camera");
  1177. // Set camera orthographic
  1178. camera.orthographic = true;
  1179. // Set camera ortho size (the value of PIXEL_SIZE is 0.01)
  1180. camera.orthoSize = graphics.height * PIXEL_SIZE;
  1181. \endcode
  1182. Lua:
  1183. \code
  1184. -- Create camera node
  1185. cameraNode = scene_:CreateChild("Camera")
  1186. -- Create camera
  1187. local camera = cameraNode:CreateComponent("Camera")
  1188. -- Set camera orthographic
  1189. camera.orthographic = true
  1190. -- Set camera ortho size (the value of PIXEL_SIZE is 0.01)
  1191. camera.orthoSize = graphics.height * PIXEL_SIZE
  1192. \endcode
  1193. To zoom in/out, use \ref Camera::SetZoom "SetZoom()".
  1194. \section Urho2D_Sprites Sprites
  1195. Urho2D provides a handful of classes for loading/drawing the kind of sprite required by your game.
  1196. You can chose from animated sprites, 2D particle emitters and static sprites.
  1197. \section Urho2D_Animated Animated sprites
  1198. Workflow for creating animated sprites in Urho2D relies on Spriter (c).
  1199. Spriter is a crossplatform tool for creating 2D animations. It comes both as an almost fully featured free version and a more advanced 'pro' version. Free version is available at http://www.brashmonkey.com/spriter.htm. To get started, scml files from Bin/Data/Urho2D folder can be loaded in Spriter. Note that although currently Spriter doesn't support spritesheets/texture atlases, Urho2D does: you just have to use the same name for your scml file and your spritesheet's xml file (see \ref SpriteSheet2D below for details on how to generate this file). Example 33_Urho2DSpriterAnimation is a good demonstration of this feature (scml file and xml spritesheet are both named 'imp' to instruct Urho2D to use the atlas instead of the individual files). You could remove every image files in the 'imp' folder and just keep 'imp_all.png' to test it out. However, keep your individual image files as they are still required if you want to later edit your scml project in Spriter.
  1200. A *.scml file is loaded using AnimationSet2D class (Resource) and rendered using AnimatedSprite2D class (Drawable component):
  1201. - AnimationSet2D: a Spriter *.scml file including one or more animations.
  1202. Each Spriter animation (Animation2D) contained in an AnimationSet2D can be accessed by its index and by its name (\ref AnimationSet2D::GetAnimation "GetAnimation()").
  1203. - AnimatedSprite2D: used to display a Spriter animation (Animation2D from an AnimationSet2D). Equivalent to a 3D AnimatedModel. Animation2D animations inside the AnimationSet2D are accessed by their name (String) using \ref AnimatedSprite2D::SetAnimation "SetAnimation()". Playback animation speed can be controlled using \ref AnimatedSprite2D::SetSpeed "SetSpeed()". Loop mode can be controlled using \ref AnimatedSprite2D::SetLoopMode "SetLoopMode()" (you can use the default value set in Spriter or make the animation repeat or clamp).
  1204. One interesting feature is the ability to flip/mirror animations on both axes, using \ref AnimatedSprite2D::SetFlip "SetFlip()", \ref AnimatedSprite2D::SetFlipX "SetFlipX()" or \ref AnimatedSprite2D::SetFlipY "SetFlipY()". Once flipped, the animation remains in that state until boolean state is restored to false. It is recommended to build your sprites centered in Spriter if you want to easily flip their animations (otherwise sprite position will seem to diverge).
  1205. - Animation2D (RefCounted): a Spriter animation from an AnimationSet2D.
  1206. For a demonstration, check examples 33_Urho2DSpriterAnimation and 24_Urho2DSprite.
  1207. \section Urho2D_Particle Particle emitters
  1208. A 2D particle emitter is built from a *.pex file (a format used by many 2D engines).
  1209. A *.pex file is loaded using ParticleEffect2D class (Resource) and rendered using AnimatedSprite2D class (Drawable component):
  1210. - ParticleEffect2D: a *.pex file defining the behavior and texture of a 2D particle (ParticleEmitter2D). For an example, see Bin/Data/Urho2D/greenspiral.pex
  1211. - ParticleEmitter2D: used to display a ParticleEffect2D. Equivalent to a 3D ParticleEmitter.
  1212. For a demonstration, check example 25_Urho2DParticle.
  1213. ParticleEditor2D tool (https://github.com/aster2013/ParticleEditor2D) can be used to easily create pex files.
  1214. \section Urho2D_Static_Sprites Static sprites
  1215. Static sprites are built from single image files or from spritesheets/texture atlases.
  1216. Single image files are loaded using Sprite2D class (Resource) and spritesheets/texture atlases are loaded using SpriteSheet2D class (Resource).
  1217. Both are rendered using StaticSprite2D class (Drawable component):
  1218. - StaticSprite2D: used to display a Sprite2D. Equivalent to a 3D StaticModel.
  1219. - Sprite2D: an image defined with texture, texture rectangle and hot spot.
  1220. - SpriteSheet2D: a texture atlas image (that packs multiple Sprite2D images).
  1221. Spritesheets can be created using tools like ShoeBox (http://renderhjs.net/shoebox/), darkFunction Editor (http://darkfunction.com/editor/), SpriteHelper (http://www.gamedevhelper.com/spriteHelper2Info.php), TexturePacker (http://www.codeandweb.com/texturepacker), ...
  1222. These tools will generate an image file and a xml file mapping coordinates and size for each individual image. Note that Urho2D uses same xml file format as Sparrow/Starling engines.
  1223. You can assign a material to an image by creating a xml parameter file named as the image and located in the same folder.
  1224. For example, to make the box sprite (Bin/Data/Urho2D/Box.png) nearest filtered, create a file Box.xml next to it, with the following content:
  1225. \code
  1226. <texture>
  1227. <filter mode="nearest" />
  1228. </texture>
  1229. \endcode
  1230. The full list of texture parameters is documented \ref Materials "here".
  1231. \section Urho2D_Physics Physics
  1232. Physics in Urho2D uses Box2D. You can refer to Box2D manual at http://box2d.org/manual.pdf for full reference (just substitute "joints" for "constraints").
  1233. - PhysicsWorld2D: implements 2D physics simulation. Mandatory for 2D physics components such as RigidBody2D, CollisionShape2D or Constraint2D.
  1234. \section Urho2D_Rigidbodies_Components Rigid bodies components
  1235. - RigidBody2D: a 2D physics object instance.
  1236. Available BodyType2Ds are:
  1237. - BT_STATIC: A static body does not move under simulation and behaves as if it has infinite mass. Internally, Box2D stores zero for the mass and the inverse mass. Static bodies can be moved manually by the user. A static body has zero velocity. Static bodies do not collide with other static or kinematic bodies.
  1238. - BT_DYNAMIC: A dynamic body is fully simulated. It can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass. If you try to set the mass of a dynamic body to zero, it will automatically acquire a mass of one kilogram.
  1239. - BT_KINEMATIC: A kinematic body moves under simulation according to its velocity. Kinematic bodies do not respond to forces. They can be moved manually by the user, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass, however, Box2D stores zero for the mass and the inverse mass. Kinematic bodies do not collide with other static or kinematic bodies.
  1240. You should establish the body type at creation, using \ref RigidBody2D::SetBodyType "SetBodyType()", because changing the body type later is expensive.
  1241. \section Urho2D_Collision_Shapes_Components Collision shapes components
  1242. Use \ref PhysicsWorld2D::DrawDebugGeometry "DrawDebugGeometry()" to display the shapes.
  1243. - CollisionShape2D: base class for 2D physics collision shapes.
  1244. - CollisionBox2D: defines 2D physics collision box.
  1245. - CollisionCircle2D: defines 2D physics collision circle. Circle shapes have a position (\ref CollisionCircle2D::SetCenter "SetCenter()") and radius (\ref CollisionCircle2D::SetRadius "SetRadius()"). Circles are solid, you cannot make a hollow circle using the circle shape.
  1246. - CollisionEdge2D: defines 2D physics collision edge. Edge shapes are line segments defined by 2 vertices (\ref CollisionEdge2D::SetVertex1 "SetVertex1()" and \ref CollisionEdge2D::SetVertex2 "SetVertex2()" or globaly \ref CollisionEdge2D::SetVertices "SetVertices()"). They are provided to assist in making a free-form static environment for your game. A major limitation of edge shapes is that they can collide with circles and polygons but not with themselves. The collision algorithms used by Box2D require that at least one of two colliding shapes have volume. Edge shapes have no volume, so edge-edge collision is not possible.
  1247. - CollisionChain2D: defines 2D physics collision chain. The chain shape provides an efficient way to connect many edges together (\ref CollisionChain2D::SetVertices "SetVertices()") to construct your static game worlds. You can connect chains together using ghost vertices. Self-intersection of chain shapes is not supported.
  1248. - CollisionPolygon2D: defines 2D physics collision polygon. Polygon shapes are solid convex polygons. A polygon is convex when all line segments connecting two points in the interior do not cross any edge of the polygon. A polygon must have 3 or more vertices (\ref CollisionPolygon2D::SetVertices "SetVertices()"). Polygons vertices are stored with a counter clockwise winding.
  1249. Important: collision shapes must match your textures in order to be accurate. You can use tools like Physics Body Editor (https://code.google.com/p/box2d-editor/), RUBE (https://www.iforce2d.net/rube/), LevelHelper (http://www.gamedevhelper.com/levelhelper/), PhysicsEditor (http://www.codeandweb.com/physicseditor), ... to help you.
  1250. Other interesting tool is BisonKick (https://bisonkick.com/app/518195d06927101d38a83b66/).
  1251. \section Urho2D_Constraints_Components Constraints components
  1252. Apply a constraint to a node (called 'ownerBody') and use \ref Constraint::SetOtherBody "SetOtherBody()" to set the other node's body to be constrained to the ownerBody.
  1253. Use \ref Constraint2D::SetCollideConnected "SetCollideConnected()" to switch collision on/off between the bodies.
  1254. Use \ref PhysicsWorld2D::SetDrawJoint "SetDrawJoint()" in combination with \ref PhysicsWorld2D::DrawDebugGeometry "DrawDebugGeometry()" to display the joints.
  1255. See 32_Urho2DConstraints sample for detailed examples and to help selecting the appropriate constraint.
  1256. - Constraint2D: base class for 2D physics constraints.
  1257. - ConstraintDistance2D: defines 2D physics distance constraint. The distance between two anchor points (\ref ConstraintDistance2D::SetOwnerBodyAnchor "SetOwnerBodyAnchor()" and \ref ConstraintDistance2D::SetOtherBodyAnchor "SetOtherBodyAnchor()") on two bodies is kept constant. The constraint can also be made soft, like a spring-damper connection. Softness is achieved by tuning frequency (\ref ConstraintDistance2D::SetFrequencyHz "SetFrequencyHz()" is below half of the timestep) and damping ratio (\ref ConstraintDistance2D::SetDampingRatio "SetDampingRatio()").
  1258. - ConstraintFriction2D: defines 2D physics friction constraint. This constraint is used for top-down friction. It provides 2D translational friction (\ref ConstraintFriction2D::SetMaxForce "SetMaxForce()") and angular friction (\ref ConstraintFriction2D::SetMaxTorque "SetMaxTorque()").
  1259. - ConstraintGear2D: defines 2D physics gear constraint. Used to create sophisticated mechanisms and saves from using compound shapes. This constraint can only connect ConstraintRevolute2Ds and/or ConstraintPrismatic2Ds (\ref ConstraintGear2D::SetOwnerConstraint "SetOwnerConstraint()" and \ref ConstraintGear2D::SetOtherConstraint "SetOtherConstraint()"). Like the pulley ratio, you can specify a gear ratio (\ref ConstraintGear2D::SetRatio "SetRatio()"). However, in this case the gear ratio can be negative.
  1260. - ConstraintMotor2D: defines 2D physics motor constraint. This constraint lets you control the motion of a body by specifying target position (\ref ConstraintMotor2D::SetLinearOffset "SetLinearOffset()") and rotation offsets (\ref ConstraintMotor2D::SetAngularOffset "SetAngularOffset()"). You can set the maximum motor force (\ref ConstraintMotor2D::SetMaxForce "SetMaxForce()") and torque (\ref ConstraintMotor2D::SetMaxTorque "SetMaxTorque()") that will be applied to reach the target position and rotation. If the body is blocked, it will stop and the contact forces will be proportional to the maximum motor force and torque.
  1261. - ConstraintMouse2D: defines 2D physics mouse constraint. Used to manipulate bodies with the mouse, this constraint is almost used in every Box2D tutorial available on the net, to allow interacting with the 2D scene. It attempts to drive a point on a body towards the current position of the cursor. There is no restriction on rotation. This constraint has a target point, maximum force, frequency, and damping ratio. The target point (\ref ConstraintMouse2D::SetTarget "SetTarget()") initially coincides with the body’s anchor point. The maximum force (\ref ConstraintMouse2D::SetMaxForce "SetMaxForce()") is used to prevent violent reactions when multiple dynamic bodies interact. You can make this as large as you like. The frequency (\ref ConstraintMouse2D::SetFrequencyHz "SetFrequencyHz()") and damping ratio (\ref ConstraintMouse2D::SetDampingRatio "SetDampingRatio()") are used to create a spring/damper effect similar to the ConstraintDistance2D. Many users have tried to adapt the ConstraintMouse2D for game play. Users often want to achieve precise positioning and instantaneous response. The ConstraintMouse2D doesn’t work very well in that context. You may wish to consider using kinematic bodies instead.
  1262. - ConstraintPrismatic2D: defines 2D physics prismatic constraint. This constraint allows for relative translation of two bodies along a specified axis (\ref ConstraintPrismatic2D::SetAxis "SetAxis()"). There's no rotation applied. This constraint definition is similar to ConstraintRevolute2D description; just substitute translation for angle and force for torque.
  1263. - ConstraintPulley2D: defines 2D physics pulley constraint. The pulley connects two bodies to ground (\ref ConstraintPulley2D::SetOwnerBodyGroundAnchor "SetOwnerBodyGroundAnchor()" and \ref ConstraintPulley2D::SetOtherBodyGroundAnchor "SetOtherBodyGroundAnchor()") and to each other (\ref ConstraintPulley2D::SetOwnerBodyAnchor "SetOwnerBodyAnchor()" and \ref ConstraintPulley2D::SetOtherBodyAnchor "SetOtherBodyAnchor()"). As one body goes up, the other goes down. You can supply a ratio (\ref ConstraintPulley2D::SetRatio "SetRatio()") that simulates a block and tackle. This causes one side of the pulley to extend faster than the other. At the same time the constraint force is smaller on one side than the other. You can use this to create mechanical leverage.
  1264. - ConstraintRevolute2D: defines 2D physics revolute constraint. This constraint forces two bodies to share a common hinge anchor point (\ref ConstraintRevolute2D::SetAnchor "SetAnchor()"). You can control the relative rotation of the two bodies (the constraint angle) using a limit and/or a motor. A limit (\ref ConstraintRevolute2D::SetEnableLimit "SetEnableLimit()") forces the joint angle to remain between a lower (\ref ConstraintRevolute2D::SetLowerAngle "SetLowerAngle()") and upper (\ref ConstraintRevolute2D::SetUpperAngle "SetUpperAngle()") bound. The limit will apply as much torque as needed to make this happen. The limit range should include zero, otherwise the constraint will lurch when the simulation begins. A motor (\ref ConstraintRevolute2D::SetEnableMotor "SetEnableMotor()") allows you to specify the constraint speed (the time derivative of the angle). The speed (\ref ConstraintRevolute2D::SetMotorSpeed "SetMotorSpeed()") can be negative or positive. When the maximum torque (\ref ConstraintRevolute2D::SetMaxMotorTorque "SetMaxMotorTorque()") is exceeded, the joint will slow down and can even reverse. You can use a motor to simulate friction. Just set the joint speed to zero, and set the maximum torque to some small, but significant value. The motor will try to prevent the constraint from rotating, but will yield to a significant load.
  1265. - ConstraintRope2D: defines 2D physics rope constraint. This constraint restricts the maximum distance (\ref ConstraintRope2D::SetMaxLength "SetMaxLength()") between two points (\ref ConstraintRope2D::SetOwnerBodyAnchor "SetOwnerBodyAnchor()" and \ref ConstraintRope2D::SetOtherBodyAnchor "SetOtherBodyAnchor()"). This can be useful to prevent chains of bodies from stretching, even under high load.
  1266. - ConstraintWeld2D: defines 2D physics weld constraint. This constraint attempts to constrain all relative motion between two bodies.
  1267. - ConstraintWheel2D: defines 2D physics wheel constraint. This constraint restricts a point on bodyB (\ref ConstraintWheel2D::SetAnchor() "SetAnchor()") to a line on bodyA (\ref ConstraintWheel2D::SetAxis "SetAxis()"). It also provides a suspension spring.
  1268. \section Urho2D_Background_and_Layers Background and layers
  1269. To set the background color for the scene, use \ref Renderer::GetDefaultZone "GetDefaultZone()".fogColor
  1270. You can use different layers in order to simulate perspective. In this case you can use \ref Drawable2D::SetLayer "SetLayer()" and \ref Drawable2D::SetOrderInLayer "SetOrderInLayer()" to organise your sprites and arrange thir display order.
  1271. Finally, note that you can easily mix both 2D and 3D resources. 3D assets' position need to be slightly offset on the Z axis (z=1 is enough), Camera's position needs to be slightly offset (on the Z axis) from 3D assets' max girth and a Light is required.
  1272. \section Urho2D_TileMap Tile maps
  1273. Tile maps workflow relies on the tmx file format, which is the native format of Tiled, a free app available at http://www.mapeditor.org/. It is strongly recommended to only use the latest stable release (currently 0.9.1). Do not use daily builds or older revisions, otherwise results may be unpredictable.
  1274. Check example 36_Urho2DTileMap for a basic demonstration.
  1275. You can use tile maps for the design of the whole scene/level, or in adjunction to other 2D resources.
  1276. \subsection Urho2D_LoadingTMX "Loading" a TMX tile map file
  1277. A tmx file is loaded using \ref TmxFile2D "TmxFile2D resource class" and rendered using \ref TileMap2D "TileMap2D component class".
  1278. You just have to create a \ref TileMap2D "TileMap2D" component inside a node and then assign the tmx resource file to it.
  1279. C++:
  1280. \code
  1281. SharedPtr<Node> tileMapNode(scene_->CreateChild("TileMap")); // Create a standard Urho3D node
  1282. tileMapNode->SetPosition(Vector3(0.0f, 0.0f, -1.0f));
  1283. TileMap2D* tileMap = tileMapNode->CreateComponent<TileMap2D>(); // Create the TileMap2D component
  1284. tileMap->SetTmxFile(cache->GetResource<TmxFile2D>("Urho2D/isometric_grass_and_water.tmx")); // Assign tmx resource file to component
  1285. \endcode
  1286. AngelScript:
  1287. \code
  1288. Node@ tileMapNode = scene_.CreateChild("TileMap"); // Create a standard Urho3D node
  1289. tileMapNode.position = Vector3(0.0f, 0.0f, -1.0f);
  1290. TileMap2D@ tileMap = tileMapNode.CreateComponent("TileMap2D"); // Create the TileMap2D component
  1291. tileMap.tmxFile = cache.GetResource("TmxFile2D", "Urho2D/isometric_grass_and_water.tmx"); // Assign the tmx resource file to component
  1292. \endcode
  1293. Lua:
  1294. \code
  1295. local tileMapNode = scene_:CreateChild("TileMap") -- Create a standard Urho3D node
  1296. tileMapNode.position = Vector3(0, 0, -1)
  1297. local tileMap = tileMapNode:CreateComponent("TileMap2D") -- Create the TileMap2D component
  1298. tileMap.tmxFile = cache:GetResource("TmxFile2D", "Urho2D/isometric_grass_and_water.tmx") -- Assign tmx resource file to component
  1299. \endcode
  1300. Note that currently only XML Layer Format is supported (Base64 and CSV are not). In Tiled, go to Maps > Map Properties to set 'Layer Format' to 'XML'.
  1301. \subsection Urho2D_TMX_maps TMX tile maps
  1302. Once a tmx file is loaded in Urho, use \ref TileMap2D::GetInfo "GetInfo()" to access the map properties through \ref TileMapInfo2D class.
  1303. A map is defined by its:
  1304. - orientation: Urho2D supports both orthogonal (flat) and isometric (strict iso 2.5D and staggered iso) tile maps. Orientation can be retrieved with \ref TileMapInfo2D::orientation_ "orientation_" attribute (returns 0 for ortho, 1 for iso and 2 for staggered).
  1305. - width and height expressed as a number of tiles in the map: use \ref TileMapInfo2D::width_ "width_" and \ref TileMapInfo2D::height_ "height_" attributes to access these values
  1306. - width and height expressed in Urho2D space: use \ref TileMapInfo2D::GetMapWidth "GetMapWidth()" and \ref TileMapInfo2D::GetMapHeight "GetMapHeight()" to access these values which are useful to set the camera's position for example
  1307. - tile width and tile height as the size in pixels of the tiles in the map (expressed a percentage): use \ref TileMapInfo2D::tileWidth_ "tileWidth_" and \ref TileMapInfo2D::tileHeight_ "tileHeight_" attributes to access these values
  1308. Two convenient functions are provided to convert Tiled index to/from Urho2D space:
  1309. - \ref TileMapInfo2D::TileIndexToPosition "TileIndexToPosition()" to convert tile index to Urho position
  1310. - \ref TileMapInfo2D::PositionToTileIndex "PositionToTileIndex()" to convert Urho position to tile index (returns false if position is outside of the map)
  1311. \subsection Urho2D_TMX_layers TMX tile map layers
  1312. A tile map is composed of a mix of ordered \ref TileMapLayer2D "layers".
  1313. Accessing layers : from a \ref TileMap2D "TileMap2D component", layers are accessed by their index from bottom to top using \ref TileMap2D::GetLayer "GetLayer()" function. \ref TileMap2D::GetNumLayers "GetNumLayers()" returns the number of layers contained in the tmx file. \ref TileMapLayer2D::GetLayerType "GetLayerType()" returns the type of layer (Tile, Object or Image).
  1314. A layer is characterized by its:
  1315. - name: currently not accessible
  1316. - width and height expressed as a number of tiles: use \ref TileMapLayer2D::GetWidth "GetWidth()" and \ref TileMapLayer2D::GetHeight "GetHeight()" to access these values
  1317. Layer visibility can be toggled using \ref TileMapLayer2D::SetVisible "SetVisible()" (and visibility state can be accessed with \ref TileMapLayer2D::IsVisible "IsVisible()")
  1318. \subsection Urho2D_TMX_Objects TMX tile map objects
  1319. Tiled \ref TileMapObject2D "objects" are wire shapes (Rectangle, Ellipse, Polygon, Polyline) and sprites (Tile) that are freely positionable in the tile map.
  1320. Accessing Tiled objects : from a \ref TileMapLayer2D "TileMapLayer2D layer", objects are accessed by their index using \ref TileMapLayer2D::GetObject "GetObject()". \ref TileMapLayer2D::GetNumObjects "GetNumObjects()" returns the number of objects contained in the object layer (tile and image layers will return 0 as they don't hold objects).
  1321. Use \ref TileMapObject2D::GetObjectType "GetObjectType()" to get the nature (TileMapObjectType2D) of the selected object.
  1322. Objects' properties (Name and Type) can be accessed using respectively \ref TileMapObject2D::GetName "GetName()" and \ref TileMapObject2D::GetType "GetType()". Type can be useful to flag categories of objects in Tiled.
  1323. Except Tile, object layers are not visible. They can be used:
  1324. - to easily design polygon sprites and Box2D shapes using the object's vertices: use \ref TileMapObject2D::GetNumPoints "GetNumPoints()" to get the number of vertices and \ref TileMapObject2D::GetPoint "GetPoint()" to iterate through the vertices
  1325. - as placeholders to easily set the position and size of entities in the world, using \ref TileMapObject2D::GetPosition "GetPosition()" and \ref TileMapObject2D::GetSize "GetSize()"
  1326. - to display Tile objects as sprites
  1327. - to create a background from Tile sprites
  1328. - etc.
  1329. Additionaly \ref Sprite2D "Sprite2D" resource from a Tile object is retrieved using \ref TileMapObject2D::GetTileSprite "GetTileSprite()".
  1330. If need be you can access the grid id (relative to the tilesets used) of a Tile object using \ref TileMapObject2D::GetTileGid "GetTileGid()".
  1331. \page Serialization Serialization
  1332. Classes that derive from Serializable can perform automatic serialization to binary or XML format by defining \ref AttributeInfo "attributes". Attributes are stored to the Context per class. %Scene load/save and network replication are both implemented by having the Node and Component classes derive from Serializable.
  1333. The supported attribute types are all those supported by Variant, excluding pointers. Attributes can either define a direct memory offset into the object, or setter & getter functions. Zero-based enumerations are also supported, so that the enum values can be stored as text into XML files instead of just numbers. For editing, the attributes also have human-readable names.
  1334. To implement side effects to attributes, for example that a Node needs to dirty its world transform whenever the local transform changes, the default attribute access functions in Serializable can be overridden. See \ref Serializable::OnSetAttribute "OnSetAttribute()" and \ref Serializable::OnGetAttribute "OnGetAttribute()".
  1335. Each attribute can have a combination of the following flags:
  1336. - AM_FILE: Is used for file serialization (load/save.)
  1337. - AM_NET: Is used for network replication.
  1338. - AM_LATESTDATA: Frequently changing data for network replication, where only the latest values matter. Used for motion and animation.
  1339. - AM_NOEDIT: Is an internal attribute and is not to be shown for editing.
  1340. - AM_NODEID: Is a node ID and may need rewriting when instantiating scene content.
  1341. - AM_COMPONENTID: Is a component ID and may need rewriting when instantiating scene content.
  1342. The default flags are AM_FILE and AM_NET. Note that it is legal to define neither AM_FILE or AM_NET, meaning the attribute has only run-time significance (perhaps for editing.)
  1343. \page Network Networking
  1344. The Network subsystem provides reliable and unreliable UDP messaging using kNet. A server can be created that listens for incoming connections, and client connections can be made to the server. After connecting, code running on the server can assign the client into a scene to enable scene replication, provided that when connecting, the client specified a blank scene for receiving the updates.
  1345. %Scene replication is one-directional: the server always has authority and sends scene updates to the client at a fixed update rate, by default 30 FPS. The client responds by sending controls updates (buttons, yaw and pitch + possible extra data) also at a fixed rate.
  1346. Bidirectional communication between the server and the client can happen either using raw network messages, which are binary-serialized data, or remote events, which operate like ordinary events, but are processed on the receiving end only. Code on the server can send messages or remote events either to one client, all clients assigned into a particular scene, or to all connected clients. In contrast the client can only send messages or remote events to the server, not directly to other clients.
  1347. Note that if a particular networked application does not need scene replication, network messages and remote events can also be transmitted without assigning the client to a scene. The Chat example does just that: it does not create a scene either on the server or the client.
  1348. \section Network_Connecting Connecting to a server
  1349. Starting the server and connecting to it both happen through the Network subsystem. See \ref Network::StartServer "StartServer()" and \ref Network::Connect "Connect()". A UDP port must be chosen; the examples use the port 1234.
  1350. Note the scene (to be used for replication) and identity VariantMap supplied as parameters when connecting. The identity data can contain for example the user name or credentials, it is completely application-specified. The identity data is sent right after connecting and causes the E_CLIENTIDENTITY event to be sent on the server when received. By subscribing to this event, server code can examine incoming connections and accept or deny them. The default is to accept all connections.
  1351. After connecting successfully, client code can get the Connection object representing the server connection, see \ref Network::GetServerConnection "GetServerConnection()". Likewise, on the server a Connection object will be created for each connected client, and these can be iterated through. This object is used to send network messages or remote events to the remote peer, to assign the client into a scene (on the server only), or to disconnect.
  1352. \section Network_Replication Scene replication
  1353. %Network replication of scene content has been implemented in a straightforward manner, using \ref Serialization "attributes". Nodes and components that have been not been created in local mode - see the CreateMode parameter of \ref Node::CreateChild "CreateChild()" or \ref Node::CreateComponent "CreateComponent()" - will be automatically replicated. Note that a replicated component created into a local node will not be replicated, as the node's locality is checked first.
  1354. The CreateMode translates into two different node and component ID ranges - replicated ID's range from 0x1 to 0xffffff, while local ID's range from 0x1000000 to 0xffffffff. This means there is a maximum of 16777215 replicated nodes or components in a scene.
  1355. If the scene was originally loaded from a file on the server, the client will also load the scene from the same file first. In this case all predefined, static objects such as the world geometry should be defined as local nodes, so that they are not needlessly retransmitted through the network during the initial update, and do not exhaust the more limited replicated ID range.
  1356. The server can be made to transmit needed resource \ref PackageFile "packages" to the client. This requires attaching the package files to the Scene by calling \ref Scene::AddRequiredPackageFile "AddRequiredPackageFile()". On the client, a cache directory for the packages must be chosen before receiving them is possible: see \ref Network::SetPackageCacheDir "SetPackageCacheDir()".
  1357. There are some things to watch out for:
  1358. - When a client is assigned to a scene, the client will first remove all existing replicated scene nodes from the scene, to prepare for receiving objects from the server. This means that for example a client's camera should be created into a local node, otherwise it will be removed when connecting.
  1359. - After connecting to a server, the client should not create, update or remove non-local nodes or components on its own. However, to create client-side special effects and such, the client can freely manipulate local nodes.
  1360. - A node's \ref Node::GetVars "user variables" VariantMap will be automatically replicated on a per-variable basis. This can be useful in transmitting data shared by several components, for example the player's score or health.
  1361. - To implement interpolation, exponential smoothing of the nodes' rendering transforms is enabled on the client. It can be controlled by two properties of the Scene, the smoothing constant and the snap threshold. Snap threshold is the distance between network updates which, if exceeded, causes the node to immediately snap to the end position, instead of moving smoothly. See \ref Scene::SetSmoothingConstant "SetSmoothingConstant()" and \ref Scene::SetSnapThreshold "SetSnapThreshold()".
  1362. - Position and rotation are Node attributes, while linear and angular velocities are RigidBody attributes. To cut down on the needed network bandwidth the physics components can be created as local on the server: in this case the client will not see them at all, and will only interpolate motion based on the node's transform changes. Replicating the actual physics components allows the client to extrapolate using its own physics simulation, and to also perform collision detection, though always non-authoritatively.
  1363. - By default the physics simulation also performs interpolation to enable smooth motion when the rendering framerate is higher than the physics FPS. This should be disabled on the server scene to ensure that the clients do not receive interpolated and therefore possibly non-physical positions and rotations. See \ref PhysicsWorld::SetInterpolation "SetInterpolation()".
  1364. - AnimatedModel does not replicate animation by itself. Rather, AnimationController will replicate its command state (such as "fade this animation in, play that animation at 1.5x speed.") To turn off animation replication, create the AnimationController as local. To ensure that also the first animation update will be received correctly, always create the AnimatedModel component first, then the AnimationController.
  1365. - Networked attributes can either be in delta update or latest data mode. Delta updates are small incremental changes and must be applied in order, which may cause increased latency if there is a stall in network message delivery eg. due to packet loss. High volume data such as position, rotation and velocities are transmitted as latest data, which does not need ordering, instead this mode simply discards any old data received out of order. Note that node and component creation (when initial attributes need to be sent) and removal can also be considered as delta updates and are therefore applied in order.
  1366. - To avoid going through the whole scene when sending network updates, nodes and components explicitly mark themselves for update when necessary. When writing your own replicated C++ components, call \ref Component::MarkNetworkUpdate "MarkNetworkUpdate()" in member functions that modify any networked attribute.
  1367. - The server update logic orders replication messages so that parent nodes are created and updated before their children. Remote events are queued and only sent after the replication update to ensure that if they originate from a newly created node, it will already exist on the receiving end. However, it is also possible to specify unordered transmission for a remote event, in which case that guarantee does not hold.
  1368. - Nodes have the concept of the \ref Node::SetOwner "owner connection" (for example the player that is controlling a specific game object), which can be set in server code. This property is not replicated to the client. Messages or remote events can be used instead to tell the players what object they control.
  1369. - At least for now, there is no built-in client-side prediction.
  1370. \section Network_InterestManagement Interest management
  1371. %Scene replication includes a simple, distance-based interest management mechanism for reducing bandwidth use. To use, create the NetworkPriority component to a Node you wish to apply interest management to. The component can be created as local, as it is not important to the clients.
  1372. This component has three parameters for controlling the update frequency: \ref NetworkPriority::SetBasePriority "base priority", \ref NetworkPriority::SetDistanceFactor "distance factor", and \ref NetworkPriority::SetMinPriority "minimum priority".
  1373. A current priority value is calculated on each server update as "base priority - distance factor * distance." Additionally, it can never go lower than the minimum priority. This value is then added to an update accumulator. Whenever the update accumulator reaches 100.0, the attribute changes to the node and its components are sent, and the accumulator is reset.
  1374. The default values are base priority 100.0, distance factor 0.0, and minimum priority 0.0. This means that by default an update is always sent (which is also the case if the node has no NetworkPriority component.) Additionally, there is a rule that the node's owner connection always receives updates at full frequency. This rule can be controlled by calling \ref NetworkPriority::SetAlwaysUpdateOwner "SetAlwaysUpdateOwner()".
  1375. Calculating the distance requires the client to tell its current observer position (typically, either the camera's or the player character's world position.) This is accomplished by the client code calling \ref Connection::SetPosition "SetPosition()" on the server connection. The client can also tell its current observer rotation by
  1376. calling \ref Connection::SetRotation "SetRotation()" but that will only be useful for custom logic, as it is not used by the NetworkPriority component.
  1377. For now, creation and removal of nodes is always sent immediately, without consulting interest management. This is based on the assumption that nodes' motion updates consume the most bandwidth.
  1378. \section Network_Controls Client controls update
  1379. The Controls structure is used to send controls information from the client to the server, by default also at 30 FPS. This includes held down buttons, which is an application-defined 32-bit bitfield, floating point yaw and pitch, and possible extra data (for example the currently selected weapon) stored within a VariantMap.
  1380. It is up to the client code to ensure they are kept up-to-date, by calling \ref Connection::SetControls "SetControls()" on the server connection. The event E_NETWORKUPDDATE will be sent to remind of the impending update, and the event E_NETWORKUPDATESENT will be sent after the update. The controls can then be inspected on the server side by calling \ref Connection::GetControls "GetControls()".
  1381. The controls update message also includes the client's observer position for interest management.
  1382. \section Network_Messages Raw network messages
  1383. All network messages have an integer ID. The first ID you can use for custom messages is 22 (lower ID's are either reserved for kNet's or the %Network subsystem's internal use.) Messages can be sent either unreliably or reliably, in-order or unordered. The data payload is simply raw binary data that can be crafted by using for example VectorBuffer.
  1384. To send a message to a Connection, use its \ref Connection::SendMessage "SendMessage()" function. On the server, messages can also be broadcast to all client connections by calling the \ref Network::BroadcastMessage "BroadcastMessage()" function.
  1385. When a message is received, and it is not an internal protocol message, it will be forwarded as the E_NETWORKMESSAGE event. See the Chat example for details of sending and receiving.
  1386. For high performance, consider using unordered messages, because for in-order messages there is only a single channel within the connection, and all previous in-order messages must arrive first before a new one can be processed.
  1387. \section Network_RemoteEvents Remote events
  1388. A remote event consists of its event type (name hash), a flag that tells whether it is to be sent in-order or unordered, and the event data VariantMap. It can optionally set to be originate from a specific Node in the receiver's scene ("remote node event.")
  1389. To send a remote event to a Connection, use its \ref Connection::SendRemoteEvent "SendRemoteEvent()" function. To broadcast remote events to several connections at once (server only), use Network's \ref Network::BroadcastRemoteEvent "BroadcastRemoteEvent()" function.
  1390. For safety, allowed remote event types must be registered. See \ref Network::RegisterRemoteEvent "RegisterRemoteEvent()". The registration affects only receiving events; sending whatever event is always allowed. There is a fixed blacklist of event types defined in Source/Engine/Network/Network.cpp that pose a security risk and are never allowed to be registered for reception; for example E_CONSOLECOMMAND.
  1391. Like with ordinary events, in script remote event types are strings instead of name hashes for convenience.
  1392. Remote events will always have the originating connection as a parameter in the event data. Here is how to get it in both C++ and script (in C++, include NetworkEvents.h):
  1393. C++:
  1394. \code
  1395. using namespace RemoteEventData;
  1396. Connection* remoteSender = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
  1397. \endcode
  1398. %Script:
  1399. \code
  1400. Connection@ remoteSender = eventData["Connection"].GetPtr();
  1401. \endcode
  1402. \section Network_HttpRequests HTTP requests
  1403. In addition to UDP messaging, the network subsystem allows to make HTTP requests. Use the \ref Network::MakeHttpRequest "MakeHttpRequest()" function for this. You can specify the URL, the verb to use (default GET if empty), optional headers and optional post data. The HttpRequest object that is returned acts like a Deserializer, and you can read the response data in suitably sized chunks. After the whole response is read, the connection closes. The connection can also be closed early by allowing the request object to expire.
  1404. \page Multithreading Multithreading
  1405. Urho3D uses a task-based multithreading model. The WorkQueue subsystem can be supplied with tasks described by the WorkItem structure, by calling \ref WorkQueue::AddWorkItem "AddWorkItem()". These will be executed in background worker threads. The function \ref WorkQueue::Complete "Complete()" will complete all currently pending tasks, and execute them also in the main thread to make them finish faster.
  1406. On single-core systems no worker threads will be created, and tasks are immediately processed by the main thread instead. In the presence of more cores, a worker thread will be created for each hardware core except one which is reserved for the main thread. Hyperthreaded cores are not included, as creating worker threads also for them leads to unpredictable extra synchronization overhead.
  1407. The work items include a function pointer to call, with the signature
  1408. \verbatim
  1409. void WorkFunction(const WorkItem* item, unsigned threadIndex)
  1410. \endverbatim
  1411. The thread index ranges from 0 to n, where 0 represents the main thread and n is the number of worker threads created. Its function is to aid in splitting work into per-thread data structures that need no locking. The work item also contains three void pointers: start, end and aux, which can be used to describe a range of sub-work items, and an auxiliary data structure, which may for example be the object that originally queued the work.
  1412. Multithreading is so far not exposed to scripts, and is currently used only in a limited manner: to speed up the preparation of rendering views, including lit object and shadow caster queries, occlusion tests and particle system, animation and skinning updates. Raycasts into the Octree are also threaded, but physics raycasts are not. Additionally there are dedicated threads for audio mixing and background loading of resources.
  1413. When making your own work functions or threads, observe that the following things are unsafe and will result in undefined behavior and crashes, if done outside the main thread:
  1414. - Modifying scene or %UI content
  1415. - Modifying GPU resources
  1416. - Executing script functions
  1417. - Pointing SharedPtr's or WeakPtr's to the same RefCounted object from multiple threads simultaneously
  1418. Using the Profiler is treated as a no-op when called from outside the main thread. Trying to send an event or get a resource from the ResourceCache when not in the main thread will cause an error to be logged. %Log messages from other threads are collected and handled in the main thread at the end of the frame.
  1419. \page AttributeAnimation %Attribute animation
  1420. Attribute animation is a new system for Urho3D, With it user can apply animation to object's attribute. All object derived from Animatable can use attribute animation, currently these classes include Node, Component and UIElement.
  1421. These are two way to use use attribute animation. First user can create attribute animation with code, and then apply it to object's attribute. Here is a simple code for light color animation:
  1422. \code
  1423. SharedPtr<ValueAnimation> colorAnimation(new ValueAnimation(context_));
  1424. colorAnimation->SetKeyFrame(0.0f, Color::WHITE);
  1425. colorAnimation->SetKeyFrame(2.0f, Color::YELLOW);
  1426. colorAnimation->SetKeyFrame(4.0f, Color::WHITE);
  1427. light->SetAttributeAnimation("Color", colorAnimation, WM_LOOP);
  1428. \endcode
  1429. On above code, we first create an ValueAnimation object call colorAnimation, and set its key frame value, then apply it to light's color attribute. (Note here: in order to make animation look correct, the last key frame must equal to the first key frame for loop mode).
  1430. Another way is load attribute animation from resource, here is a simple sample:
  1431. \code
  1432. ValueAnimation* colorAnimation = cache->GetResource<ValueAnimation>("Scene/LightColorAnimation.xml");
  1433. light->SetAttributeAnimation("Color", colorAnimation, WM_LOOP);
  1434. \endcode
  1435. These are three kind of wrap mode for attribute animation:
  1436. - WM_LOOP: Loop mode, when the animation arrived to end, it will loop from begin.
  1437. - WM_ONCE: Play once mode, when the animation finished, it will be removed from the object.
  1438. - WM_CLAMP: Clamp mode, then the animation finished, it will keep the last key frame's value.
  1439. These is another argument call speed the animation play speed, the default value is 1.0f, user can change the value to control the animation play speed. User can also change animation’s wrap mode and speed on fly.
  1440. When user want to apply multi-attribute animation to an object, ObjectAnimation is for it. For example when user want to apply position and color animation for light, can use following code:
  1441. \code
  1442. // Create object animation.
  1443. SharedPtr<ObjectAnimation> lightAnimation(new ObjectAnimation(context_));
  1444. // Create position animation
  1445. SharedPtr<ValueAnimation> positionAnimation(new ValueAnimation(context_));
  1446. positionAnimation->SetKeyFrame(0.0f, Vector3::ZERO);
  1447. positionAnimation->SetKeyFrame(1.0f, Vector3(1.0f, 1.0f, 1.0f));
  1448. positionAnimation->SetKeyFrame(4.0f, Vector3::ZERO);
  1449. // Add position animation
  1450. lightAnimation->AddAttributeAnimation("Position", positionAnimation, WM_LOOP);
  1451. // Create color animation
  1452. SharedPtr<ValueAnimation> colorAnimation(new ValueAnimation(context_));
  1453. colorAnimation->SetKeyFrame(0.0f, Color::WHITE);
  1454. colorAnimation->SetKeyFrame(2.0f, Color::YELLOW);
  1455. colorAnimation->SetKeyFrame(4.0f, Color::WHITE);
  1456. // Add color animation
  1457. lightAnimation->AddAttributeAnimation("Color", colorAnimation, WM_LOOP);
  1458. // Apply object animation to light
  1459. light->SetObjectAnimation(lightAnimation);
  1460. \endcode
  1461. Also user can load object animation from file, like:
  1462. \code
  1463. ObjectAnimation * lightAnimation = cache->GetResource<ObjectAnimation>("Scene/LightAnimation.xml");
  1464. light-> SetObjectAnimation (lightAnimation);
  1465. \endcode
  1466. Current attribute animation use linear interpolation for numeric value type (like float, Vector2, Vector3 etc), and these is no interpolation for non-numeric type (like int, bool).
  1467. Attribute animation and object animation can be save to scene file, Someday if our editor support edit animation, we can create animation in editor and save it to scene file.
  1468. \section AttributeAnimation_Classes Classes of attribute animation:
  1469. - Animatable: Base class for animatable object, an animatable object can be set animation on it's attributes, or can be set an object animation to it.
  1470. - ValueAnimation: Animation class, include some key frame in it.
  1471. - ObjectAnimation: Object animation class, an object animation include one or more attribute animations and theirs wrap mode and speed for an Animatable object.
  1472. - ValueAnimationInfo: Animation info, it include attribute animation, wrap mode and animation speed.
  1473. - AttributeAnimationInstance: Attribute animation instance, it is derived from ValueAnimationInfo. and include animation runtime information, when animation playing it will update the object's attribute value automatically.
  1474. \page Tools Tools
  1475. \section Tools_AssetImporter AssetImporter
  1476. Loads various 3D formats supported by Open Asset Import Library (http://assimp.sourceforge.net/) and saves Urho3D model, animation, material and scene files out of them. For the list of supported formats, look at http://assimp.sourceforge.net/main_features_formats.html.
  1477. An alternative export path for Blender is to use the Urho3D add-on (https://github.com/reattiva/Urho3D-Blender).
  1478. Usage:
  1479. \verbatim
  1480. AssetImporter <command> <input file> <output file> [options]
  1481. Commands:
  1482. model Output a model
  1483. scene Output a scene
  1484. node Output a node and its children (prefab)
  1485. dump Dump scene node structure. No output file is generated
  1486. lod Combine several Urho3D models as LOD levels of the output model
  1487. Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>
  1488. Options:
  1489. -b Save scene in binary format, default format is XML
  1490. -h Generate hard instead of smooth normals if input file has no normals
  1491. -i Use local ID's for scene nodes
  1492. -l Output a material list file for models
  1493. -na Do not output animations
  1494. -nm Do not output materials
  1495. -nt Do not output material textures
  1496. -nc Do not use material diffuse color value, instead output white
  1497. -nh Do not save full node hierarchy (scene mode only)\n"
  1498. -ns Do not create subdirectories for resources
  1499. -nz Do not create a zone and a directional light (scene mode only)
  1500. -nf Do not fix infacing normals
  1501. -p <path> Set path for scene resources. Default is output file path
  1502. -r <name> Use the named scene node as root node\n"
  1503. -f <freq> Animation tick frequency to use if unspecified. Default 4800
  1504. -o Optimize redundant submeshes. Loses scene hierarchy and animations
  1505. -s <filter> Include non-skinning bones in the model's skeleton. Can be given a
  1506. case-insensitive semicolon separated filter list. Bone is included
  1507. if its name contains any of the filters. Prefix filter with minus
  1508. sign to use as an exclude. For example -s "Bip01;-Dummy;-Helper"
  1509. -t Generate tangents
  1510. -v Enable verbose Assimp library logging
  1511. -eao Interpret material emissive texture as ambient occlusion
  1512. -cm Check and do not overwrite if material exists
  1513. -ct Check and do not overwrite if texture exists
  1514. -ctn Check and do not overwrite if texture has newer timestamp
  1515. -am Export all meshes even if identical (scene mode only)
  1516. \endverbatim
  1517. The material list is a text file, one material per line, saved alongside the Urho3D model. It is used by the scene editor to automatically apply the imported default materials when setting a new model for a StaticModel, StaticModelGroup, AnimatedModel or Skybox component, and can also be manually invoked by calling \ref StaticModel::ApplyMaterialList "ApplyMaterialList()". The list files can safely be deleted if not needed.
  1518. In model or scene mode, the AssetImporter utility will also automatically save non-skeletal node animations into the output file directory.
  1519. \section Tools_OgreImporter OgreImporter
  1520. Loads OGRE .mesh.xml and .skeleton.xml files and saves them as Urho3D .mdl (model) and .ani (animation) files. For other 3D formats and whole scene importing, see AssetImporter instead. However that tool does not handle the OGRE formats as completely as this.
  1521. Usage:
  1522. \verbatim
  1523. OgreImporter <input file> <output file> [options]
  1524. Options:
  1525. -l Output a material list file
  1526. -na Do not output animations
  1527. -nm Do not output morphs
  1528. -r Output only rotations from animations
  1529. -s Split each submesh into own vertex buffer
  1530. -t Generate tangents
  1531. \endverbatim
  1532. Note: outputting only bone rotations may help when using an animation in a different model, but if bone position changes have been used for effect, the animation may become less lively. Unpredictable mutilations might result from using an animation in a model not originally intended for, as Urho3D does not specifically attempt to retarget animations.
  1533. \section Tools_PackageTool PackageTool
  1534. Examines a directory recursively for files and subdirectories and creates a PackageFile. The package file can be added to the ResourceCache and used as if the files were on a (read-only) filesystem. The file data can optionally be compressed using the LZ4 compression library.
  1535. Usage:
  1536. \verbatim
  1537. PackageTool <directory to process> <package name> [basepath] [options]
  1538. Options:
  1539. -c Enable package file LZ4 compression
  1540. \endverbatim
  1541. When PackageTool runs, it will go inside the source directory, then look for subdirectories and any files. Paths inside the package will by default be relative to the source directory, but if an extra path prefix is desired, it can be specified by the optional basepath argument.
  1542. For example, this would convert all the resource files inside the Urho3D Data directory into a package called Data.pak (execute the command from the Bin directory)
  1543. \verbatim
  1544. PackageTool Data Data.pak
  1545. \endverbatim
  1546. The -c option enables LZ4 compression on the files.
  1547. \section Tools_RampGenerator RampGenerator
  1548. Creates 1D and 2D ramp textures for use in light attenuation and spotlight spot shapes.
  1549. Usage:
  1550. \verbatim
  1551. RampGenerator <output file> <width> <power> [dimensions]
  1552. \endverbatim
  1553. The output is saved in PNG format. The power parameter is fed into the pow() function to determine ramp shape; higher value gives more brightness and more abrupt fade at the edge.
  1554. \section Tools_ScriptCompiler ScriptCompiler
  1555. Compiles AngelScript file(s) to binary bytecode for faster loading. Can also dump the %Script API in Doxygen format.
  1556. Usage:
  1557. \verbatim
  1558. ScriptCompiler <input file> [resource path for includes]
  1559. ScriptCompiler -dumpapi <Doxygen output file> [C header output file]
  1560. \endverbatim
  1561. The output files are saved with the extension .asc (compiled AngelScript.) Binary files are not automatically loaded instead of the text format (.as) script files, instead resource requests and resource references in objects need to point to the compiled files. In a final build of an application it may be convenient to simply replace the text format script files with the compiled scripts.
  1562. The script API dump mode can be used to replace the 'ScriptAPI.dox' file in the 'Docs' directory. If the output file name is not provided then the script API would be dumped to standard output (console) instead.
  1563. \page Unicode Unicode support
  1564. The String class supports UTF-8 encoding. However, by default strings are treated as a sequence of bytes without regard to the encoding. There is a separate
  1565. API for operating on Unicode characters, see for example \ref String::LengthUTF8 "LengthUTF8()", \ref String::AtUTF8 "AtUTF8()" and \ref String::SubstringUTF8 "SubstringUTF8()". Urho3D itself needs to be aware of the Unicode characters only in the \ref UI "user interface", when displaying text and manipulating it through user input.
  1566. On Windows, wide char strings are used in all calls to the operating system, such as accessing the command line, files, and the window title. The WString class is used as a helper for conversion. On Linux & Mac OS X 8-bit strings are used directly and they are assumed to contain UTF-8.
  1567. Note that \ref FileSystem::ScanDir "ScanDir()" function may return filenames in unnormalized Unicode on Mac OS X. Unicode re-normalization is not yet implemented.
  1568. \page FileFormats Custom file formats
  1569. Urho3D tries to use existing file formats whenever possible, and define custom file formats only when absolutely necessary. Currently used custom file formats are:
  1570. \section FileFormats_Model Binary model format (.mdl)
  1571. \verbatim
  1572. Model geometry and vertex morph data
  1573. byte[4] Identifier "UMDL"
  1574. uint Number of vertex buffers
  1575. For each vertex buffer:
  1576. uint Vertex count
  1577. uint Vertex element mask (determines vertex size)
  1578. uint Morphable vertex range start index
  1579. uint Morphable vertex count
  1580. byte[] Vertex data (vertex count * vertex size)
  1581. uint Number of index buffers
  1582. For each index buffer:
  1583. uint Index count
  1584. uint Index size (2 for 16-bit indices, 4 for 32-bit indices)
  1585. byte[] Index data (index count * index size)
  1586. uint Number of geometries
  1587. For each geometry:
  1588. uint Number of bone mapping entries
  1589. uint[] Bone mapping data, Maps geometry bone indices to global bone indices for HW skinning.
  1590. May be empty, in this case identity mapping will be used.
  1591. uint Number of LOD levels
  1592. For each LOD level:
  1593. float LOD distance
  1594. uint Primitive type (0 = triangle list, 1 = line list)
  1595. uint Vertex buffer index, starting from 0
  1596. uint Index buffer index, starting from 0
  1597. uint Draw range: index start
  1598. uint Draw range: index count
  1599. uint Number of vertex morphs (may be 0)
  1600. For each vertex morph:
  1601. cstring Name of morph
  1602. uint Number of affected vertex buffers
  1603. For each affected vertex buffer:
  1604. uint Vertex buffer index, starting from 0
  1605. uint Vertex element mask for morph data. Only positions, normals & tangents are supported.
  1606. uint Vertex count
  1607. For each vertex:
  1608. uint Vertex index
  1609. Vector3 Position (if included in the mask)
  1610. Vector3 Normal (if included in the mask)
  1611. Vector3 Tangent (if included in the mask)
  1612. Skeleton data
  1613. uint Number of bones (may be 0)
  1614. For each bone:
  1615. cstring Bone name
  1616. uint Parent bone index starting from 0. Same as own bone index for the root bone
  1617. Vector3 Initial position
  1618. Quaternion Initial rotation
  1619. Vector3 Initial scale
  1620. float[12] 4x3 offset matrix for skinning
  1621. byte Bone collision info bitmask. 1 = bounding sphere 2 = bounding box
  1622. If bounding sphere data included:
  1623. float Bone radius
  1624. If bounding box data included:
  1625. Vector3 Bone bounding box minimum
  1626. Vector3 Bone bounding box maximum
  1627. Bounding box data
  1628. Vector3 Model bounding box minimum
  1629. Vector3 Model bounding box maximum
  1630. Geometry center data
  1631. For each geometry:
  1632. Vector3 Geometry center
  1633. \endverbatim
  1634. \section FileFormats_Animation Binary animation format (.ani)
  1635. \verbatim
  1636. byte[4] Identifier "UANI"
  1637. cstring Animation name
  1638. float Length in seconds
  1639. uint Number of tracks
  1640. For each track:
  1641. cstring Track name (practically same as the bone name that should be driven)
  1642. byte Mask of included animation data. 1 = bone positions 2 = bone rotations 4 = bone scaling
  1643. uint Number of keyframes
  1644. For each keyframe:
  1645. float Time position in seconds
  1646. Vector3 Position (if included in data)
  1647. Quaternion Rotation (if included in data)
  1648. Vector3 Scale (if included in data)
  1649. \endverbatim
  1650. Note: animations are stored using absolute bone transformations. Therefore only lerp-blending between animations is supported; additive pose modification is not.
  1651. \section FileFormats_Shader Direct3D9 binary shader format (.vs2, .ps2, .vs3, .ps3)
  1652. \verbatim
  1653. byte[4] Identifier "USHD"
  1654. short Shader type (0 = vertex, 1 = pixel)
  1655. short Shader model (2 or 3)
  1656. uint Number of constant parameters
  1657. For each constant parameter:
  1658. cstring Parameter name
  1659. byte Register index
  1660. byte Number of registers
  1661. uint Number of texture units
  1662. For each texture unit:
  1663. cstring Texture unit name
  1664. byte Sampler index
  1665. uint Bytecode size
  1666. byte[] Bytecode
  1667. \endverbatim
  1668. \section FileFormats_Package Package file (.pak)
  1669. \verbatim
  1670. byte[4] Identifier "UPAK" or "ULZ4" if compressed
  1671. uint Number of file entries
  1672. uint Whole package checksum
  1673. For each file entry:
  1674. cstring Name
  1675. uint Start offset
  1676. uint Size
  1677. uint Checksum
  1678. The compressed data for each file is the following, repeated until the file is done:
  1679. ushort Uncompressed length of block
  1680. ushort Compressed length of block
  1681. byte[] Compressed data
  1682. \endverbatim
  1683. \section FileFormats_Script Compiled AngelScript (.asc)
  1684. \verbatim
  1685. byte[4] Identifier "ASBC"
  1686. byte[] Bytecode, produced by AngelScript serializer
  1687. \endverbatim
  1688. \page CodingConventions Coding conventions
  1689. - Indent style is Allman (BSD) -like, ie. brace on the next line from a control statement, indented on the same level. In switch-case statements the cases are on the same indent level as the switch statement.
  1690. - Indents use 4 spaces instead of tabs.
  1691. - Class and struct names are in camelcase beginning with an uppercase letter. They should be nouns. For example DebugRenderer, FreeTypeLibrary, Graphics.
  1692. - Functions are likewise in upper-camelcase. For example CreateComponent, SetLinearRestThreshold.
  1693. - Variables are in lower-camelcase. Member variables have an underscore appended. For example numContacts, randomSeed_.
  1694. - Constants and enumerations are in uppercase. For example Vector3::ZERO or PASS_SHADOW.
  1695. - Pointers and references append the * or & symbol to the type without a space in between. For example Drawable* drawable, Serializer& dest.
  1696. - Class definitions proceed in the following order:
  1697. - public constructors and the destructor
  1698. - public virtual functions
  1699. - public non-virtual member functions
  1700. - public static functions
  1701. - public member variables
  1702. - public static variables
  1703. - repeat all of the above in order for protected definitions, and finally private
  1704. - Header files are commented using one-line comments beginning with /// to mark them for Doxygen.
  1705. - Inline functions are defined inside the class definitions where possible, without using the inline keyword.
  1706. \page ContributionChecklist Contribution checklist
  1707. When contributing code to the Urho3D project, there are a few things to check so that the process goes smoothly.
  1708. First of all, the contribution should be wholly your own, so that you hold the copyright. If you are borrowing anything (for example a specific implementation of a math formula), you must be sure that you're allowed to do so, and give credit appropriately. For example borrowing code that is in the public domain would be OK.
  1709. Second, you need to agree that code is released under the MIT license with the copyright statement "Copyright (c) 2008-2014 the Urho3D project." Note here that "Urho3D project" is not an actual legal entity, but just shorthand to avoid listing all the contributors. You certainly retain your individual copyright. You should copy-paste the license statement from an existing .cpp or .h file to each new file that you contribute, to avoid having to add it later.
  1710. Third, there are requirements for new code that come from Urho3D striving to be a cohesive, easy-to-use package where features like events, serialization and script bindings integrate tightly. Check all that apply:
  1711. - For all code (classes, functions) for which it makes sense, both AngelScript and Lua bindings should exist. Refer to the existing bindings and the scripting documentation for specific conventions, for example the use of properties in AngelScript instead of setters / getters where possible, or Lua bindings providing both functions and properties.
  1712. - %Script bindings do not need to be made for low-level functionality that only makes sense to be called from C++, such as thread handling or byte-level access to GPU resources, or for internal but public functions that are only accessed by subsystems and are not needed when using the classes.
  1713. - Unless impossible due to missing bindings (see above) new examples should be implemented in all of C++, AngelScript and Lua.
  1714. - For new Component or UIElement subclasses, \ref Serialization "attributes" should exist for serialization, network replication and editing. The classes should be possible to create from within the editor; check the component category and supply icons for them as necessary (see the files Bin/Data/Textures/EditorIcons.png and Bin/Data/UI/EditorIcons.xml.)
  1715. - If the classes inherit attribute definitions from other classes, make sure that they are registered in the correct order on engine initialization.
  1716. - \ref Network "Network replication" of a component's attributes must be triggered manually by calling MarkNetworkUpdate() in each setter function that modifies a network-replicated attribute. See the Camera class for a straightforward example.
  1717. - Define \ref Events "events" where you anticipate that an external party may want to hook up to something happening. For example the editor updates its scene hierarchy window by subscribing to the scene change events: child node added/removed, component added/removed.
  1718. - Mark all application-usable classes, structs and functions with the macro URHO3D_API so that they are exported correctly in a shared library build.
  1719. - When you add a new third-party library, insert its license statement to the License.txt in the root directory.
  1720. - Please heed all the \ref CodingConventions "coding conventions" and study existing code where unsure. Ensure that your text editor or IDE is configured to show whitespace, so that you don't accidentally mix spaces and tabs.
  1721. */
  1722. }