3#include "MemoryContext.h"
4#include "ViewContext.h"
8#include "ExtensionRegistry.h"
10#include "EntityStore.h"
14#include "Renderer/CullingManager.h"
15#include "Renderer/RenderResources.h"
16#include "Renderer/RenderTexture.h"
17#include "Renderer/Renderer.h"
19#include "Scene/RayPick.h"
20#include "Scene/GetBounds.h"
22#include "Services/PipelineService.h"
23#include "Services/QualityService.h"
24#include "Services/Services.h"
25#include "Services/DPIService.h"
26#include "Services/Features.h"
27#include "Services/Variables.h"
28#include "Services/TaskManager.h"
29#include "Services/Time.h"
30#include "Services/Random.h"
31#include "Services/DeferredNameResolution.h"
32#include "Services/ResourceUsageLogger.h"
34#include "Scripting/ScriptingManager.h"
36#include "Components/Data/TrajectoryComponent.h"
37#include "Components/Data/DataSetComponent.h"
38#include "Components/Geometry/MarkerPointSetComponent.h"
40#include "Generators/MeshGenerator.h"
41#include "Generators/TextureGenerator.h"
43#include "Input/InputManager.h"
45#include "Systems/Core/DynamicComponentSystem.h"
46#include "Systems/Core/InstancedModelSystem.h"
47#include "Systems/Core/LightSystem.h"
48#include "Systems/Core/ModelSystem.h"
50#include "Systems/Data/TrajectorySystem.h"
52#include "Systems/Geometry/ExtrusionSystem.h"
53#include "Systems/Geometry/ShapeSystem.h"
54#include "Systems/Geometry/VariableExtrusionSystem.h"
55#include "Systems/Geometry/MarkerPointSetSystem.h"
56#include "Systems/Geometry/MeshGeneratorSystem.h"
57#include "Systems/Geometry/AdaptivePlanarGridSystem.h"
59#include "Systems/Appearance/MaterialSystem.h"
60#include "Systems/Appearance/TextureGeneratorSystem.h"
61#include "Systems/Appearance/BasicOceanSystem.h"
62#include "Systems/Appearance/ScreenSizeSystem.h"
64#include "Systems/Layout/TrajectoryLayoutSystem.h"
66#include "Resources/MaterialManager.h"
67#include "Resources/ModelManager.h"
68#include "Resources/ResourceStore.h"
69#include "Resources/Texture.h"
70#include "Resources/TextureManager.h"
72#include "ResourceManifest.h"
74#include "Serialization/AssetReader.h"
76#include "Rendering/Factory.h"
77#include "Rendering/ISwapChain.h"
79#include "Foundation/Logging/Logger.h"
80#include "Foundation/Platform/FileSystemWatcher.h"
81#include "Foundation/Platform/WindowData.h"
96 std::unordered_map<Reflection::TypeId, ComponentSystemBase *> systems;
101Cogs::Core::Context::Context() : Context(nullptr, 0) {
108 variables(
std::make_unique<
Variables>(variableValues, count)),
114 time(
std::make_unique<
Time>(this)),
122 scene(
std::make_unique<
Scene>(this)),
125 LOG_TRACE(logger,
"Created context.");
127 if (
variables->exist(
"filesystemwatcher")) {
128 LOG_INFO(logger,
"Enabling filesystemwatcher for auto-reload");
129 watcher = std::make_unique<FileSystemWatcher>();
135 variables->set(
"renderer.graphicsDevice",
"Null");
138 LOG_INFO(logger,
"renderer.graphicsDevice is already set. Ignoring nowindow.");
148 dynamicComponentSystem = Memory::create<DynamicComponentSystem>(
memory->baseAllocator);
155 textureGenerator->cleanup();
157 if (
auto meshGenerator = services->getService<
MeshGenerator>()) {
158 meshGenerator->cleanup();
165 defaultView =
nullptr;
167 scriptingManager->cleanup();
171 taskManager->waitAll();
188 LOG_DEBUG(logger,
"Destroyed context.");
194 static bool initialized =
false;
197 LOG_WARNING(logger,
"Context already statically initialized.");
202 LOG_INFO(logger,
"COGS_VERSION_STRING %s", COGS_VERSION_STRING);
203 LOG_INFO(logger,
"COGS_GIT_REVISION %s", COGS_XQUOTE(COGS_GIT_REVISION));
213 LOG_DEBUG(logger,
"Initialized types for reflection.");
219 static bool cleaned =
false;
222 LOG_WARNING(logger,
"Context already statically cleaned.");
227 Cogs::Core::cleanupTypes();
228 Cogs::Core::Strings::cleanup();
231bool Cogs::Core::Context::createDevice()
234 auto deviceType = parseEnum<GraphicsDeviceType>(variables->get(
"renderer.graphicsDevice",
"Default"),
GraphicsDeviceType::Default);
239 LOG_WARNING(logger,
"Device could not be created using the given type id: %d",
static_cast<int>(deviceType));
240 LOG_INFO(logger,
"Trying to create default device.");
246 LOG_INFO(logger,
"Successfully created fallback device of type %s", device->getIdentifier().c_str());
250 LOG_INFO(logger,
"Initialized device of type %s", device->getIdentifier().c_str());
254 LOG_ERROR(logger,
"Could not create graphics device. Destroying context.");
258 GraphicsDeviceSettings settings = {};
259 settings.windowData = getDefaultView()->refWindowData();
264 settings.featureLevelMajor = 4;
265 settings.featureLevelMinor = 6;
268 settings.numSamples = variables->get(
"renderer.samples", 2);
270 if (variables->get(
"cache.enableShaderCache",
false)) {
274 if (variables->get(
"effects.dumpShaders",
false)) {
278 if (variables->get(
"renderer.forceSoftwareRendering",
false)) {
282 if (variables->get(
"renderer.sharedSurface",
false)) {
286 if (variables->get(
"renderer.debugDevice",
false)) {
290 if (variables->get(
"renderer.useSwapEffectDiscard",
false)) {
294 if (!variables->get(
"renderer.disableClipControl",
false)) {
298 settings.colorFormat = parseTextureFormat(variables->get(
"renderer.colorFormat",
"R8G8B8A8_UNORM_SRGB"), TextureFormat::R8G8B8A8_UNORM_SRGB);
299 settings.depthFormat = parseTextureFormat(variables->get(
"renderer.depthFormat",
"D32_FLOAT"), TextureFormat::D32_FLOAT);
300 settings.ioHandler = resourceStore->getIOHandler();
301 settings.sharedSurface = &sharedSurface;
303 return device->setSettings(settings);
307 scriptingManager->initialize();
317 LOG_TRACE(logger,
"Initialized static systems.");
338 initializeDynamicComponents();
340 materialManager->initializeDefaultMaterial();
341 materialInstanceManager->initializeDefaultMaterialInstance();
343 LOG_TRACE(logger,
"Initializing extensions...");
347 LOG_TRACE(logger,
"Extensions initialized.");
351 defaultView->initialize(
nullptr);
360 transformSystem->setOrigin({ 0, 0, 0 });
366 registerDynamicComponentType(
"CurvedEarthPositionComponent");
367 registerDynamicComponentType(
"FontSelectorComponent");
368 registerDynamicComponentType(
"TrajectoryAlignedComponent");
369 registerDynamicComponentType(
"ReflectionComponent");
370 registerDynamicComponentType(
"BasicTerrainComponent");
371 registerDynamicComponentType(
"NearLimitComponent");
372 registerDynamicComponentType(
"ExpressionComponent");
373 registerDynamicComponentType(
"FPSNavigationComponent");
374 registerDynamicComponentType(
"TeleportNavigationComponent");
375 registerDynamicComponentType(
"PickingBeamComponent");
376 registerDynamicComponentType(
"MotionComponent");
377 registerDynamicComponentType(
"SwitchComponent");
378 registerDynamicComponentType(
"OrbitingCameraController");
385 if (!type.isValid()) {
386 LOG_ERROR(logger,
"Cannot register %.*s as dynamic component. Did you forget to register the type?", StringViewFormat(typeName));
391 auto base = type.getBase();
392 while (base && base != &Reflection::TypeDatabase::getType<DynamicComponent>()) {
393 base = base->getBase();
397 LOG_ERROR(logger,
"Cannot register %.*s as dynamic component without inheriting from DynamicComponent base class.", StringViewFormat(typeName));
399 assert(
false &&
"Invalid dynamic component base class.");
402 dynamicComponentSystem->registerType(
this, type);
407 extensionSystems->systems[id] = system;
411 if (engine && engine->isReady()) {
418 return extensionSystems->systems[id];
421void Cogs::Core::Context::update() {
424 taskManager->updateState(
this);
427 services->dispatchFrameCallbacks();
434void Cogs::Core::Context::preRender() {
435 for (
auto & c : cameraSystem->pool) {
437 cullingManager->dispatchCulling(&cameraSystem->getData(&c));
440 lightSystem->preRender(
this);
442 if (callbacks.preRenderCallback) {
443 callbacks.preRenderCallback(
this);
445 for (ViewContext* view : views) {
451 ViewContext* viewContext =
new ViewContext(
this, windowData);
453 views.push_back(viewContext);
457void Cogs::Core::Context::deleteView(ViewContext* view) {
458 auto e = views.end();
459 auto i = std::find(views.begin(), e, view);
Utility class for bounds calculation of Scene / Entity.
Base class for component systems.
virtual void initialize(Context *context)
Initialize the system.
Typed component system managing a pool of components with the given ComponentType.
static void cleanupStatic()
Perform static cleanup of the Context.
class ComponentSystemBase * getExtensionSystem(const uint16_t id)
Retrieve the system with the given id.
void initializeDynamicComponents()
Initialize and register dynamic component types.
void initialize()
Initialize all services and component systems.
static void initializeStatic()
Perform static initialization of the Context.
void clear()
Does clearing of context.
void registerDynamicComponentType(const StringView &typeName)
Register a dynamic component type with the given typeName.
class EntityStore * store
Entity store.
std::unique_ptr< struct MemoryContext > memory
Memory and allocation info.
std::unique_ptr< class Variables > variables
Variables service instance.
Context(const char **variables, int count)
Constructs a new context instance, initializing all services, an engine instance, and extension syste...
std::unique_ptr< class ResourceStore > resourceStore
ResourceStore service instance.
void registerExtensionSystem(const uint16_t id, class ComponentSystemBase *system)
Register an extension component system using the given id.
~Context() override
Destructs a context instance.
std::unique_ptr< FileSystemWatcher > watcher
File system watcher.
The engine owns all the systems and resource managers, and is responsible for executing different sta...
Stores top level entities for the engine.
static void initialize(Context *context)
Performs initialization of all extensions registered with add().
static void initializeStatic()
Performs static initialization of all extensions registered with add().
Contains extension systems accessible by key.
Updates material components.
Provides handling of reading and caching of external resources.
Manages Task queuing and execution.
Provides time services for components depending on elapsed or system time for animation or other trac...
Manages runtime variables for the engine.
Log implementation class.
static const Type & getType()
Get the Type of the given template argument.
Provides a weakly referenced view over the contents of a string.
@ EnableRender
Renderable.
@ NoDefault
Don't load the default scene. Highly recommended as not setting this flag cause extra scene parse.
constexpr Log getLogger(const char(&name)[LEN]) noexcept
Contains all Cogs related functionality.
@ Default
Default type of graphics device, same as unknown.
@ OpenGL20
Graphics device using OpenGL, supporting at least OpenGL 2.0.
@ ForceSoftwareRendering
Force software rendering.
@ DumpShaderContents
Dump shader contents for debugging.
@ EnableShaderCache
Enables using a shader cache to avoid recompiling previously seen shaders.
@ UseOpenGLClipControl
For OpenGL / OpenGLES backends.
@ Debug
If available, the device will operate in debug mode, performing additional validation of input data,...
@ UseSwapEffectDiscard
Under DX11 the default swap effect is FLIP_DISCARD, however there are some systems where this does no...
@ UseSharedSurface
Use shared surface for D3D9 interop.
@ PreTransform
Run before transformations are updated.
@ PreRendering
Run before rendering is performed.
@ PostView
Run after view data has been updated. Anything after this is appropriate for geometry depending on e....
@ Geometry
Run at the time geometry data is updated.
@ PreLightView
Run after view, but before the time light views are updated.
@ PostTransform
Run immediately after transformations are updated.
static void releaseDevice(class IGraphicsDevice *device)
Release the given graphics device, freeing all associated resources.
static class IGraphicsDevice * createDevice(RenderingAllocatorInfo *allocatorInfo=nullptr)
Creates a graphics device.
Memory::Allocator * baseAllocator
Base allocator. Used for misc. internal memory allocations.