/** \page Containers Container types Urho3D implements its own string type and template containers instead of using STL. The rationale for this consists of the following: - Increased performance in some cases, for example when using the PODVector class. - Reduced size of each string or vector instance compared to the MSVC STL implementations. - Reduced compile time. - Straightforward naming and implementation that aids in debugging and profiling. - Convenient member functions can be added, for example String::Split() or Vector::Compact(). - Consistency with the rest of the classes, see \ref CodingConventions "Coding conventions". The classes in question are String, Vector, PODVector, List, Set, Map, 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. 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. 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 Map. \page ObjectTypes %Object types and factories 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. %Object factory registration and object creation through factories are directly accessible only in C++, not in script. 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 16-bit hash of the type name (GetType() or GetTypeStatic()). In addition the OBJECTTYPESTATIC(className) macro must appear in a .cpp file to actually define the type identification data. The reason for this instead of defining the data directly inside the OBJECT macro as function-static data is thread safety: function-static data is initialized on the first use, and if the first call to an object's GetTypeStatic() or GetTypeNameStatic() happened on several threads simultaneously, the results would be undefined. 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: \code context_->RegisterFactory(); \endcode To create an object using a factory, call Context's \ref Context::CreateObject "CreateObject()" function. This takes the 16-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. For example: \code SharedPtr newComponent = context_->CreateObject(type)); \endcode \page Subsystems Subsystems 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. After Engine initialization, the following subsystems will always exist: - Time: manages frame updates, frame number and elapsed time counting, and controls the frequency of the operating system low-resolution timer. - WorkQueue: executes background tasks in worker threads. - FileSystem: provides directory operations. - Log: provides logging services. - ResourceCache: loads resources and keeps them cached for later access. - Network: provides UDP networking and scene replication. - Input: handles keyboard and mouse input. Will be inactive in headless mode. - UI: the graphical user interface. Will be inactive in headless mode. - Audio: provides sound output. Will be inactive if sound disabled. - Engine: creates the other subsystems and controls the main loop iteration and framerate limiting. The following subsystems are optional, so GetSubsystem() may return null if they have not been created: - 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) - Graphics: Manages the application window, the rendering context and resources. Exists if not in headless mode. - Renderer: Renders scenes in 3D and manages rendering quality settings. Exists if not in headless mode. - Script: Provides the AngelScript execution environment. Created by calling \ref Engine::InitializeScripting "InitializeScripting()". - Console: provides an interactive AngelScript console and log display. Created by calling \ref Engine::CreateConsole "CreateConsole()". - DebugHud: displays rendering mode information and statistics and profiling data. Created by calling \ref Engine::CreateDebugHud "CreateDebugHud()". In script, the subsystems are available through the following global properties: 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. \page Events Events The Urho3D event system allows for data transport and function invocation without the sender and receiver having to explicitly know of each other. It supports both broadcast and targeted events. 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. 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 16-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. 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: \code SubscribeToEvent(E_UPDATE, HANDLER(MyClass, MyEventHandler)); \endcode 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: \code SubscribeToEvent("Update", "MyEventHandler"); \endcode 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. To send an event, fill the event parameters (if necessary) and call \ref Object::SendEvent "SendEvent()". For example, this (in C++) is how the Time subsystem sends the Update event. 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: \code using namespace Update; VariantMap eventData; eventData[P_TIMESTEP] = timeStep_; SendEvent(E_UPDATE, eventData); \endcode In script event parameters, like event types, are referred to with strings, so the same code would look like: \code VariantMap eventData; eventData["TimeStep"] = timeStep; SendEvent("Update", eventData); \endcode Events can also be unsubscribed from. See \ref Object::UnsubscribeFromEvent "UnsubscribeFromEvent()" for details. \page MainLoop Main loop and frame update The main loop iteration (also called a frame) is driven by the Engine. In contrast it is the program's (for example Urho3D.exe) responsibility to continuously loop this iteration. The iteration consists of the Engine calling the Time subsystem's \ref Time::BeginFrame "BeginFrame()" and \ref Time::EndFrame "EndFrame()" functions, and in between sending various update events. The event order is: - 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. - E_UPDATE: application-wide logic update event. By default each active Scene reacts to this and triggers the scene update (more on this below.) - E_POSTUPDATE: application-wide logic post-update event. The UI subsystem updates its logic here. - E_RENDERUPDATE: Renderer updates its viewports here to prepare for rendering, and the UI generates render commands necessary to render the user interface. - 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.) - E_ENDFRAME: signals the end of the frame. Before this, rendering the frame and measuring the next frame's timestep will have occurred. The update of each Scene causes further events to be sent: - 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. - 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: - 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. - E_PHYSICSPOSTSTEP: called after the simulation iteration. Happens at the same rate as E_PHYSICSPRESTEP. - E_SCENEPOSTUPDATE: variable timestep scene post-update. ParticleEmitter and AnimationController update themselves as a response to this event. 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 world simulation steps will be performed on each frame to keep up the apparent passage if 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. \page SceneModel %Scene model 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. \section SceneModel_Components Components 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: \code Light* light = lightNode->CreateComponent(); \endcode In script, strings are used to identify component types instead, so the same code would look like: \code Light@ light = lightNode.CreateComponent("Light"); \endcode Because components are created using \ref ObjectTypes "object factories", a factory must be registered for each component type. 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: - Octree: implements spatial partitioning and accelerated visibility queries. Without this 3D objects can not be rendered. - PhysicsWorld: implements physics simulation. Physics components such as RigidBody or CollisionShape can not function properly without this. - DebugRenderer: implements debug geometry rendering. "Ordinary" components like Light, Camera or StaticModel should not be created directly into the Scene, but rather into child nodes. \section SceneModel_Identification Identification and scene hierarchy 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. 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. 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. 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. %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. It is also legal to create a Node that does not belong to a scene. This is particularly useful with cameras, because then the camera will not be serialized along with the actual scene, which is perhaps not always wanted. \section SceneModel_Update Scene updates and serialization A Scene can be either active or inactive (paused.) Active scenes will be automatically updated on each main loop iteration. Scenes can be loaded and saved in either binary or XML format; see \ref Serialization "Serialization" for details. \section SceneModel_FurtherInformation Further information For more information on the component-based scene model, see for example http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/. \page Resources Resources Resources include most things in Urho3D that are loaded from mass storage during initialization or runtime: - Animation - Image - Model - Material - ScriptFile - Shader - Sound - Technique - Texture2D - TextureCube - XMLFile They are managed and loaded by the ResourceCache subsystem. Like with all other \ref ObjectTypes "typed objects", resource types are identified by 16-bit type name hashes (C++) or type names (script). An object factory must be registered for each resource type. The resources themselves are identified by their file paths, relative to the registered resource directories or \ref PackageFile "package files". By default, Urho3D.exe registers the resource directories Data and CoreData, or the packages Data.pak and CoreData.pak if they exist. If loading a resource fails, an error will be logged and a null pointer is returned. 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. \code healthBar->SetTexture(GetSubsystem()->GetResource("Textures/HealthBarBorder.png")); \endcode The same in script would look like this (note the use of a property instead of a setter function): \code healthBar.texture = cache.GetResource("Texture2D", "Textures/HealthBarBorder.png"); \endcode Resources can also be created manually and stored to the resource cache as if they had been loaded from disk. 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. \page Scripting Scripting There are three ways the AngelScript language can be interacted with in Urho3D: \section Scripting_Immediate Immediate execution 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: \code GetSubsystem