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/Geometry/InstancedMeshBuilderSystem.h"
66#include "Systems/Layout/TrajectoryLayoutSystem.h"
68#include "Resources/MaterialManager.h"
69#include "Resources/ModelManager.h"
70#include "Resources/ResourceStore.h"
71#include "Resources/Texture.h"
72#include "Resources/TextureManager.h"
74#include "ResourceManifest.h"
76#include "Serialization/AssetReader.h"
78#include "Rendering/Factory.h"
79#include "Rendering/ISwapChain.h"
81#include "Foundation/Logging/Logger.h"
82#include "Foundation/Platform/FileSystemWatcher.h"
83#include "Foundation/Platform/WindowData.h"
95 void onRedrawRequested(
void* userData)
109 std::unordered_map<Reflection::TypeId, ComponentSystemBase *> systems;
114Cogs::Core::Context::Context() : Context(nullptr, 0) {
121 variables(
std::make_unique<
Variables>(variableValues, count)),
127 time(
std::make_unique<
Time>(this)),
135 scene(
std::make_unique<
Scene>(this)),
138 LOG_TRACE(logger,
"Created context.");
140 if (
variables->exist(
"filesystemwatcher")) {
141 LOG_DEBUG(logger,
"Enabling filesystemwatcher for auto-reload");
142 watcher = std::make_unique<FileSystemWatcher>();
148 variables->set(
"renderer.graphicsDevice",
"Null");
151 LOG_DEBUG(logger,
"renderer.graphicsDevice is already set. Ignoring nowindow.");
155#ifndef __EMSCRIPTEN__
161 dynamicComponentSystem = Memory::create<DynamicComponentSystem>(
memory->baseAllocator);
168 textureGenerator->cleanup();
170 if (
auto meshGenerator = services->getService<
MeshGenerator>()) {
171 meshGenerator->cleanup();
178 defaultView =
nullptr;
180 scriptingManager->cleanup();
184 taskManager->waitAll();
190 deviceSettings.redrawRequestCallback =
nullptr;
191 deviceSettings.redrawRequestCallbackUserData =
nullptr;
192 device->setSettings(deviceSettings);
210 LOG_DEBUG(logger,
"Destroyed context.");
216 static bool initialized =
false;
219 LOG_WARNING(logger,
"Context already statically initialized.");
224 LOG_DEBUG(logger,
"COGS_VERSION_STRING %s", COGS_VERSION_STRING);
225 LOG_DEBUG(logger,
"COGS_GIT_REVISION %s", COGS_XQUOTE(COGS_GIT_REVISION));
235 LOG_DEBUG(logger,
"Initialized types for reflection.");
241 static bool cleaned =
false;
244 LOG_WARNING(logger,
"Context already statically cleaned.");
249 Cogs::Core::cleanupTypes();
250 Cogs::Core::Strings::cleanup();
253bool Cogs::Core::Context::createDevice()
256 auto deviceType = parseEnum<GraphicsDeviceType>(variables->get(
"renderer.graphicsDevice",
"Default"),
GraphicsDeviceType::Default);
261 LOG_WARNING(logger,
"Device could not be created using the given type id: %d",
static_cast<int>(deviceType));
262 LOG_DEBUG(logger,
"Trying to create default device.");
268 LOG_DEBUG(logger,
"Successfully created fallback device of type %s", device->getIdentifier().c_str());
272 LOG_DEBUG(logger,
"Initialized device of type %s", device->getIdentifier().c_str());
276 LOG_ERROR(logger,
"Could not create graphics device. Destroying context.");
280 GraphicsDeviceSettings settings = {};
281 settings.windowData = getDefaultView()->refWindowData();
282 settings.redrawRequestCallback = &onRedrawRequested;
283 settings.redrawRequestCallbackUserData =
this;
288 settings.featureLevelMajor = 4;
289 settings.featureLevelMinor = 6;
292 settings.numSamples = variables->get(
"renderer.samples", 2);
294 int fakeAsyncEffectLoadFrames = variables->get(
"renderer.fakeAsyncEffectLoadFrames", 0);
295 if (fakeAsyncEffectLoadFrames > 0) {
296 LOG_DEBUG(logger,
"renderer.fakeAsyncEffectLoadFrames set to %d, effects will simulate async loading.", fakeAsyncEffectLoadFrames);
297 settings.fakeAsyncEffectLoadFrames =
static_cast<uint32_t
>(fakeAsyncEffectLoadFrames);
300 if (variables->get(
"cache.enableShaderCache",
false)) {
304 if (variables->get(
"effects.dumpShaders",
false)) {
308 if (variables->get(
"renderer.forceSoftwareRendering",
false)) {
312 if (variables->get(
"renderer.sharedSurface",
false)) {
316 if (variables->get(
"renderer.debugDevice",
false)) {
320 if (variables->get(
"renderer.useSwapEffectDiscard",
false)) {
324 if (!variables->get(
"renderer.disableClipControl",
false)) {
328 settings.colorFormat = parseTextureFormat(variables->get(
"renderer.colorFormat",
"R8G8B8A8_UNORM_SRGB"), TextureFormat::R8G8B8A8_UNORM_SRGB);
329 settings.depthFormat = parseTextureFormat(variables->get(
"renderer.depthFormat",
"D32_FLOAT"), TextureFormat::D32_FLOAT);
330 settings.ioHandler = resourceStore->getIOHandler();
331 settings.sharedSurface = &sharedSurface;
333 return device->setSettings(settings);
337 scriptingManager->initialize();
347 LOG_TRACE(logger,
"Initialized static systems.");
370 initializeDynamicComponents();
372 materialManager->initializeDefaultMaterial();
373 materialInstanceManager->initializeDefaultMaterialInstance();
375 LOG_TRACE(logger,
"Initializing extensions...");
379 LOG_TRACE(logger,
"Extensions initialized.");
383 defaultView->initialize(
nullptr);
392 transformSystem->setOrigin({ 0, 0, 0 });
398 registerDynamicComponentType(
"CurvedEarthPositionComponent");
399 registerDynamicComponentType(
"FontSelectorComponent");
400 registerDynamicComponentType(
"TrajectoryAlignedComponent");
401 registerDynamicComponentType(
"ReflectionComponent");
402 registerDynamicComponentType(
"BasicTerrainComponent");
403 registerDynamicComponentType(
"NearLimitComponent");
404 registerDynamicComponentType(
"ExpressionComponent");
405 registerDynamicComponentType(
"FPSNavigationComponent");
406 registerDynamicComponentType(
"TeleportNavigationComponent");
407 registerDynamicComponentType(
"PickingBeamComponent");
408 registerDynamicComponentType(
"MotionComponent");
409 registerDynamicComponentType(
"SwitchComponent");
410 registerDynamicComponentType(
"OrbitingCameraController");
417 if (!type.isValid()) {
418 LOG_ERROR(logger,
"Cannot register %.*s as dynamic component. Did you forget to register the type?", StringViewFormat(typeName));
423 auto base = type.getBase();
424 while (base && base != &Reflection::TypeDatabase::getType<DynamicComponent>()) {
425 base = base->getBase();
429 LOG_ERROR(logger,
"Cannot register %.*s as dynamic component without inheriting from DynamicComponent base class.", StringViewFormat(typeName));
431 assert(
false &&
"Invalid dynamic component base class.");
434 dynamicComponentSystem->registerType(
this, type);
439 extensionSystems->systems[id] = system;
443 if (engine && engine->isReady()) {
450 return extensionSystems->systems[id];
453void Cogs::Core::Context::update() {
456 taskManager->updateState(
this);
459 services->dispatchFrameCallbacks();
466void Cogs::Core::Context::preRender() {
467 for (
auto & c : cameraSystem->pool) {
469 cullingManager->dispatchCulling(&cameraSystem->getData(&c));
472 lightSystem->preRender(
this);
474 if (callbacks.preRenderCallback) {
475 callbacks.preRenderCallback(
this);
477 for (ViewContext* view : views) {
483 ViewContext* viewContext =
new ViewContext(
this, windowData);
485 views.push_back(viewContext);
489void Cogs::Core::Context::deleteView(ViewContext* view) {
490 auto e = views.end();
491 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.
A Context instance contains all the services, systems and runtime components needed to use Cogs.
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.
Settings for graphics device initialization.
Memory::Allocator * baseAllocator
Base allocator. Used for misc. internal memory allocations.